V8 API Reference, 7.2.502.16 (for Deno 0.2.4)
api.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/api.h"
6 
7 #include <string.h> // For memcpy, strlen.
8 #include <cmath> // For isnan.
9 #include <limits>
10 #include <vector>
11 
12 #include "src/api-inl.h"
13 
14 #include "include/v8-profiler.h"
15 #include "include/v8-testing.h"
16 #include "include/v8-util.h"
17 #include "src/accessors.h"
18 #include "src/api-natives.h"
19 #include "src/assert-scope.h"
20 #include "src/base/functional.h"
21 #include "src/base/logging.h"
22 #include "src/base/platform/platform.h"
23 #include "src/base/platform/time.h"
24 #include "src/base/safe_conversions.h"
25 #include "src/base/utils/random-number-generator.h"
26 #include "src/bootstrapper.h"
27 #include "src/builtins/builtins-utils.h"
28 #include "src/char-predicates-inl.h"
29 #include "src/code-stubs.h"
30 #include "src/compiler-dispatcher/compiler-dispatcher.h"
31 #include "src/compiler.h"
32 #include "src/contexts.h"
33 #include "src/conversions-inl.h"
34 #include "src/counters.h"
35 #include "src/date.h"
36 #include "src/debug/debug-coverage.h"
37 #include "src/debug/debug-evaluate.h"
38 #include "src/debug/debug-type-profile.h"
39 #include "src/debug/debug.h"
40 #include "src/debug/liveedit.h"
41 #include "src/deoptimizer.h"
42 #include "src/detachable-vector.h"
43 #include "src/execution.h"
44 #include "src/frames-inl.h"
45 #include "src/gdb-jit.h"
46 #include "src/global-handles.h"
47 #include "src/globals.h"
48 #include "src/icu_util.h"
49 #include "src/isolate-inl.h"
50 #include "src/json-parser.h"
51 #include "src/json-stringifier.h"
52 #include "src/messages.h"
53 #include "src/objects-inl.h"
54 #include "src/objects/api-callbacks.h"
55 #include "src/objects/embedder-data-array-inl.h"
56 #include "src/objects/embedder-data-slot-inl.h"
57 #include "src/objects/hash-table-inl.h"
58 #include "src/objects/heap-object.h"
59 #include "src/objects/js-array-inl.h"
60 #include "src/objects/js-collection-inl.h"
61 #include "src/objects/js-generator-inl.h"
62 #include "src/objects/js-promise-inl.h"
63 #include "src/objects/js-regexp-inl.h"
64 #include "src/objects/module-inl.h"
65 #include "src/objects/ordered-hash-table-inl.h"
66 #include "src/objects/slots.h"
67 #include "src/objects/smi.h"
68 #include "src/objects/stack-frame-info-inl.h"
69 #include "src/objects/templates.h"
70 #include "src/parsing/parse-info.h"
71 #include "src/parsing/parser.h"
72 #include "src/parsing/scanner-character-streams.h"
73 #include "src/pending-compilation-error-handler.h"
74 #include "src/profiler/cpu-profiler.h"
75 #include "src/profiler/heap-profiler.h"
76 #include "src/profiler/heap-snapshot-generator-inl.h"
77 #include "src/profiler/profile-generator-inl.h"
78 #include "src/profiler/tick-sample.h"
79 #include "src/property-descriptor.h"
80 #include "src/property-details.h"
81 #include "src/property.h"
82 #include "src/prototype.h"
83 #include "src/runtime-profiler.h"
84 #include "src/runtime/runtime.h"
85 #include "src/simulator.h"
86 #include "src/snapshot/code-serializer.h"
87 #include "src/snapshot/natives.h"
88 #include "src/snapshot/partial-serializer.h"
89 #include "src/snapshot/read-only-serializer.h"
90 #include "src/snapshot/snapshot.h"
91 #include "src/snapshot/startup-serializer.h"
92 #include "src/startup-data-util.h"
93 #include "src/string-hasher.h"
94 #include "src/tracing/trace-event.h"
95 #include "src/trap-handler/trap-handler.h"
96 #include "src/unicode-inl.h"
97 #include "src/v8.h"
98 #include "src/v8threads.h"
99 #include "src/value-serializer.h"
100 #include "src/version.h"
101 #include "src/vm-state-inl.h"
102 #include "src/wasm/streaming-decoder.h"
103 #include "src/wasm/wasm-engine.h"
104 #include "src/wasm/wasm-objects-inl.h"
105 #include "src/wasm/wasm-result.h"
106 #include "src/wasm/wasm-serialization.h"
107 
108 #if V8_OS_LINUX || V8_OS_MACOSX
109 #include <signal.h>
110 #include "src/trap-handler/handler-inside-posix.h"
111 #endif
112 
113 #if V8_OS_WIN
114 #include <windows.h>
115 #include "src/trap-handler/handler-inside-win.h"
116 #endif
117 
118 namespace v8 {
119 
120 /*
121  * Most API methods should use one of the three macros:
122  *
123  * ENTER_V8, ENTER_V8_NO_SCRIPT, ENTER_V8_NO_SCRIPT_NO_EXCEPTION.
124  *
125  * The latter two assume that no script is executed, and no exceptions are
126  * scheduled in addition (respectively). Creating a pending exception and
127  * removing it before returning is ok.
128  *
129  * Exceptions should be handled either by invoking one of the
130  * RETURN_ON_FAILED_EXECUTION* macros.
131  *
132  * Don't use macros with DO_NOT_USE in their name.
133  *
134  * TODO(jochen): Document debugger specific macros.
135  * TODO(jochen): Document LOG_API and other RuntimeCallStats macros.
136  * TODO(jochen): All API methods should invoke one of the ENTER_V8* macros.
137  * TODO(jochen): Remove calls form API methods to DO_NOT_USE macros.
138  */
139 
140 #define LOG_API(isolate, class_name, function_name) \
141  i::RuntimeCallTimerScope _runtime_timer( \
142  isolate, i::RuntimeCallCounterId::kAPI_##class_name##_##function_name); \
143  LOG(isolate, ApiEntryCall("v8::" #class_name "::" #function_name))
144 
145 #define ENTER_V8_DO_NOT_USE(isolate) i::VMState<v8::OTHER> __state__((isolate))
146 
147 #define ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, \
148  function_name, bailout_value, \
149  HandleScopeClass, do_callback) \
150  if (IsExecutionTerminatingCheck(isolate)) { \
151  return bailout_value; \
152  } \
153  HandleScopeClass handle_scope(isolate); \
154  CallDepthScope<do_callback> call_depth_scope(isolate, context); \
155  LOG_API(isolate, class_name, function_name); \
156  i::VMState<v8::OTHER> __state__((isolate)); \
157  bool has_pending_exception = false
158 
159 #define PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, T) \
160  if (IsExecutionTerminatingCheck(isolate)) { \
161  return MaybeLocal<T>(); \
162  } \
163  InternalEscapableScope handle_scope(isolate); \
164  CallDepthScope<false> call_depth_scope(isolate, v8::Local<v8::Context>()); \
165  i::VMState<v8::OTHER> __state__((isolate)); \
166  bool has_pending_exception = false
167 
168 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \
169  bailout_value, HandleScopeClass, \
170  do_callback) \
171  auto isolate = context.IsEmpty() \
172  ? i::Isolate::Current() \
173  : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \
174  ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
175  bailout_value, HandleScopeClass, do_callback);
176 
177 #define PREPARE_FOR_EXECUTION(context, class_name, function_name, T) \
178  PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \
179  MaybeLocal<T>(), InternalEscapableScope, \
180  false)
181 
182 #define ENTER_V8(isolate, context, class_name, function_name, bailout_value, \
183  HandleScopeClass) \
184  ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
185  bailout_value, HandleScopeClass, true)
186 
187 #ifdef DEBUG
188 #define ENTER_V8_NO_SCRIPT(isolate, context, class_name, function_name, \
189  bailout_value, HandleScopeClass) \
190  ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
191  bailout_value, HandleScopeClass, false); \
192  i::DisallowJavascriptExecutionDebugOnly __no_script__((isolate))
193 
194 #define ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate) \
195  i::VMState<v8::OTHER> __state__((isolate)); \
196  i::DisallowJavascriptExecutionDebugOnly __no_script__((isolate)); \
197  i::DisallowExceptions __no_exceptions__((isolate))
198 
199 #define ENTER_V8_FOR_NEW_CONTEXT(isolate) \
200  i::VMState<v8::OTHER> __state__((isolate)); \
201  i::DisallowExceptions __no_exceptions__((isolate))
202 #else
203 #define ENTER_V8_NO_SCRIPT(isolate, context, class_name, function_name, \
204  bailout_value, HandleScopeClass) \
205  ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
206  bailout_value, HandleScopeClass, false)
207 
208 #define ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate) \
209  i::VMState<v8::OTHER> __state__((isolate));
210 
211 #define ENTER_V8_FOR_NEW_CONTEXT(isolate) \
212  i::VMState<v8::OTHER> __state__((isolate));
213 #endif // DEBUG
214 
215 #define EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, value) \
216  do { \
217  if (has_pending_exception) { \
218  call_depth_scope.Escape(); \
219  return value; \
220  } \
221  } while (false)
222 
223 #define RETURN_ON_FAILED_EXECUTION(T) \
224  EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, MaybeLocal<T>())
225 
226 #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \
227  EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, Nothing<T>())
228 
229 #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \
230  return maybe_local.FromMaybe(Local<T>());
231 
232 
233 #define RETURN_ESCAPED(value) return handle_scope.Escape(value);
234 
235 namespace {
236 
237 Local<Context> ContextFromNeverReadOnlySpaceObject(
239  return reinterpret_cast<v8::Isolate*>(obj->GetIsolate())->GetCurrentContext();
240 }
241 
242 class InternalEscapableScope : public v8::EscapableHandleScope {
243  public:
244  explicit inline InternalEscapableScope(i::Isolate* isolate)
245  : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {}
246 };
247 
248 // TODO(jochen): This should be #ifdef DEBUG
249 #ifdef V8_CHECK_MICROTASKS_SCOPES_CONSISTENCY
250 void CheckMicrotasksScopesConsistency(i::Isolate* isolate) {
251  auto handle_scope_implementer = isolate->handle_scope_implementer();
252  if (handle_scope_implementer->microtasks_policy() ==
253  v8::MicrotasksPolicy::kScoped) {
254  DCHECK(handle_scope_implementer->GetMicrotasksScopeDepth() ||
255  !handle_scope_implementer->DebugMicrotasksScopeDepthIsZero());
256  }
257 }
258 #endif
259 
260 template <bool do_callback>
261 class CallDepthScope {
262  public:
263  explicit CallDepthScope(i::Isolate* isolate, Local<Context> context)
264  : isolate_(isolate),
265  context_(context),
266  escaped_(false),
267  safe_for_termination_(isolate->next_v8_call_is_safe_for_termination()),
268  interrupts_scope_(isolate_, i::StackGuard::TERMINATE_EXECUTION,
269  isolate_->only_terminate_in_safe_scope()
270  ? (safe_for_termination_
271  ? i::InterruptsScope::kRunInterrupts
272  : i::InterruptsScope::kPostponeInterrupts)
273  : i::InterruptsScope::kNoop) {
274  // TODO(dcarney): remove this when blink stops crashing.
275  DCHECK(!isolate_->external_caught_exception());
276  isolate_->handle_scope_implementer()->IncrementCallDepth();
277  isolate_->set_next_v8_call_is_safe_for_termination(false);
278  if (!context.IsEmpty()) {
279  i::Handle<i::Context> env = Utils::OpenHandle(*context);
280  i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
281  if (!isolate->context().is_null() &&
282  isolate->context()->native_context() == env->native_context()) {
283  context_ = Local<Context>();
284  } else {
285  impl->SaveContext(isolate->context());
286  isolate->set_context(*env);
287  }
288  }
289  if (do_callback) isolate_->FireBeforeCallEnteredCallback();
290  }
291  ~CallDepthScope() {
292  if (!context_.IsEmpty()) {
293  i::HandleScopeImplementer* impl = isolate_->handle_scope_implementer();
294  isolate_->set_context(impl->RestoreContext());
295  }
296  if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth();
297  if (do_callback) isolate_->FireCallCompletedCallback();
298 // TODO(jochen): This should be #ifdef DEBUG
299 #ifdef V8_CHECK_MICROTASKS_SCOPES_CONSISTENCY
300  if (do_callback) CheckMicrotasksScopesConsistency(isolate_);
301 #endif
302  isolate_->set_next_v8_call_is_safe_for_termination(safe_for_termination_);
303  }
304 
305  void Escape() {
306  DCHECK(!escaped_);
307  escaped_ = true;
308  auto handle_scope_implementer = isolate_->handle_scope_implementer();
309  handle_scope_implementer->DecrementCallDepth();
310  bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero();
311  isolate_->OptionalRescheduleException(call_depth_is_zero);
312  }
313 
314  private:
315  i::Isolate* const isolate_;
316  Local<Context> context_;
317  bool escaped_;
318  bool do_callback_;
319  bool safe_for_termination_;
320  i::InterruptsScope interrupts_scope_;
321 };
322 
323 } // namespace
324 
325 
326 static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate,
327  i::Handle<i::Script> script) {
328  i::Handle<i::Object> scriptName(script->GetNameOrSourceURL(), isolate);
329  i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate);
330  i::Handle<i::FixedArray> host_defined_options(script->host_defined_options(),
331  isolate);
332  v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
333  ScriptOriginOptions options(script->origin_options());
334  v8::ScriptOrigin origin(
335  Utils::ToLocal(scriptName),
336  v8::Integer::New(v8_isolate, script->line_offset()),
337  v8::Integer::New(v8_isolate, script->column_offset()),
338  v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()),
339  v8::Integer::New(v8_isolate, script->id()),
340  Utils::ToLocal(source_map_url),
341  v8::Boolean::New(v8_isolate, options.IsOpaque()),
342  v8::Boolean::New(v8_isolate, script->type() == i::Script::TYPE_WASM),
343  v8::Boolean::New(v8_isolate, options.IsModule()),
344  Utils::ToLocal(host_defined_options));
345  return origin;
346 }
347 
348 
349 // --- E x c e p t i o n B e h a v i o r ---
350 
351 void i::FatalProcessOutOfMemory(i::Isolate* isolate, const char* location) {
352  i::V8::FatalProcessOutOfMemory(isolate, location, false);
353 }
354 
355 // When V8 cannot allocate memory FatalProcessOutOfMemory is called. The default
356 // OOM error handler is called and execution is stopped.
357 void i::V8::FatalProcessOutOfMemory(i::Isolate* isolate, const char* location,
358  bool is_heap_oom) {
359  char last_few_messages[Heap::kTraceRingBufferSize + 1];
360  char js_stacktrace[Heap::kStacktraceBufferSize + 1];
361  i::HeapStats heap_stats;
362 
363  if (isolate == nullptr) {
364  isolate = Isolate::TryGetCurrent();
365  }
366 
367  if (isolate == nullptr) {
368  // If the Isolate is not available for the current thread we cannot retrieve
369  // memory information from the Isolate. Write easy-to-recognize values on
370  // the stack.
371  memset(last_few_messages, 0x0BADC0DE, Heap::kTraceRingBufferSize + 1);
372  memset(js_stacktrace, 0x0BADC0DE, Heap::kStacktraceBufferSize + 1);
373  memset(&heap_stats, 0xBADC0DE, sizeof(heap_stats));
374  // Note that the embedder's oom handler is also not available and therefore
375  // won't be called in this case. We just crash.
376  FATAL("Fatal process out of memory: %s", location);
377  UNREACHABLE();
378  }
379 
380  memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
381  memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1);
382 
383  intptr_t start_marker;
384  heap_stats.start_marker = &start_marker;
385  size_t ro_space_size;
386  heap_stats.ro_space_size = &ro_space_size;
387  size_t ro_space_capacity;
388  heap_stats.ro_space_capacity = &ro_space_capacity;
389  size_t new_space_size;
390  heap_stats.new_space_size = &new_space_size;
391  size_t new_space_capacity;
392  heap_stats.new_space_capacity = &new_space_capacity;
393  size_t old_space_size;
394  heap_stats.old_space_size = &old_space_size;
395  size_t old_space_capacity;
396  heap_stats.old_space_capacity = &old_space_capacity;
397  size_t code_space_size;
398  heap_stats.code_space_size = &code_space_size;
399  size_t code_space_capacity;
400  heap_stats.code_space_capacity = &code_space_capacity;
401  size_t map_space_size;
402  heap_stats.map_space_size = &map_space_size;
403  size_t map_space_capacity;
404  heap_stats.map_space_capacity = &map_space_capacity;
405  size_t lo_space_size;
406  heap_stats.lo_space_size = &lo_space_size;
407  size_t code_lo_space_size;
408  heap_stats.code_lo_space_size = &code_lo_space_size;
409  size_t global_handle_count;
410  heap_stats.global_handle_count = &global_handle_count;
411  size_t weak_global_handle_count;
412  heap_stats.weak_global_handle_count = &weak_global_handle_count;
413  size_t pending_global_handle_count;
414  heap_stats.pending_global_handle_count = &pending_global_handle_count;
415  size_t near_death_global_handle_count;
416  heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
417  size_t free_global_handle_count;
418  heap_stats.free_global_handle_count = &free_global_handle_count;
419  size_t memory_allocator_size;
420  heap_stats.memory_allocator_size = &memory_allocator_size;
421  size_t memory_allocator_capacity;
422  heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
423  size_t malloced_memory;
424  heap_stats.malloced_memory = &malloced_memory;
425  size_t malloced_peak_memory;
426  heap_stats.malloced_peak_memory = &malloced_peak_memory;
427  size_t objects_per_type[LAST_TYPE + 1] = {0};
428  heap_stats.objects_per_type = objects_per_type;
429  size_t size_per_type[LAST_TYPE + 1] = {0};
430  heap_stats.size_per_type = size_per_type;
431  int os_error;
432  heap_stats.os_error = &os_error;
433  heap_stats.last_few_messages = last_few_messages;
434  heap_stats.js_stacktrace = js_stacktrace;
435  intptr_t end_marker;
436  heap_stats.end_marker = &end_marker;
437  if (isolate->heap()->HasBeenSetUp()) {
438  // BUG(1718): Don't use the take_snapshot since we don't support
439  // HeapIterator here without doing a special GC.
440  isolate->heap()->RecordStats(&heap_stats, false);
441  char* first_newline = strchr(last_few_messages, '\n');
442  if (first_newline == nullptr || first_newline[1] == '\0')
443  first_newline = last_few_messages;
444  PrintF("\n<--- Last few GCs --->\n%s\n", first_newline);
445  PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace);
446  }
447  Utils::ReportOOMFailure(isolate, location, is_heap_oom);
448  // If the fatal error handler returns, we stop execution.
449  FATAL("API fatal error handler returned after process out of memory");
450 }
451 
452 
453 void Utils::ReportApiFailure(const char* location, const char* message) {
454  i::Isolate* isolate = i::Isolate::Current();
455  FatalErrorCallback callback = nullptr;
456  if (isolate != nullptr) {
457  callback = isolate->exception_behavior();
458  }
459  if (callback == nullptr) {
460  base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
461  message);
462  base::OS::Abort();
463  } else {
464  callback(location, message);
465  }
466  isolate->SignalFatalError();
467 }
468 
469 void Utils::ReportOOMFailure(i::Isolate* isolate, const char* location,
470  bool is_heap_oom) {
471  OOMErrorCallback oom_callback = isolate->oom_behavior();
472  if (oom_callback == nullptr) {
473  // TODO(wfh): Remove this fallback once Blink is setting OOM handler. See
474  // crbug.com/614440.
475  FatalErrorCallback fatal_callback = isolate->exception_behavior();
476  if (fatal_callback == nullptr) {
477  base::OS::PrintError("\n#\n# Fatal %s OOM in %s\n#\n\n",
478  is_heap_oom ? "javascript" : "process", location);
479  base::OS::Abort();
480  } else {
481  fatal_callback(location,
482  is_heap_oom
483  ? "Allocation failed - JavaScript heap out of memory"
484  : "Allocation failed - process out of memory");
485  }
486  } else {
487  oom_callback(location, is_heap_oom);
488  }
489  isolate->SignalFatalError();
490 }
491 
492 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
493  if (isolate->has_scheduled_exception()) {
494  return isolate->scheduled_exception() ==
495  i::ReadOnlyRoots(isolate).termination_exception();
496  }
497  return false;
498 }
499 
500 
501 void V8::SetNativesDataBlob(StartupData* natives_blob) {
502  i::V8::SetNativesBlob(natives_blob);
503 }
504 
505 
506 void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
507  i::V8::SetSnapshotBlob(snapshot_blob);
508 }
509 
510 namespace {
511 
512 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
513  public:
514  void* Allocate(size_t length) override {
515 #if V8_OS_AIX && _LINUX_SOURCE_COMPAT
516  // Work around for GCC bug on AIX
517  // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79839
518  void* data = __linux_calloc(length, 1);
519 #else
520  void* data = calloc(length, 1);
521 #endif
522  return data;
523  }
524 
525  void* AllocateUninitialized(size_t length) override {
526 #if V8_OS_AIX && _LINUX_SOURCE_COMPAT
527  // Work around for GCC bug on AIX
528  // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79839
529  void* data = __linux_malloc(length);
530 #else
531  void* data = malloc(length);
532 #endif
533  return data;
534  }
535 
536  void Free(void* data, size_t) override { free(data); }
537 };
538 
539 struct SnapshotCreatorData {
540  explicit SnapshotCreatorData(Isolate* isolate)
541  : isolate_(isolate),
542  default_context_(),
543  contexts_(isolate),
544  created_(false) {}
545 
546  static SnapshotCreatorData* cast(void* data) {
547  return reinterpret_cast<SnapshotCreatorData*>(data);
548  }
549 
550  ArrayBufferAllocator allocator_;
551  Isolate* isolate_;
552  Persistent<Context> default_context_;
553  SerializeInternalFieldsCallback default_embedder_fields_serializer_;
554  PersistentValueVector<Context> contexts_;
555  std::vector<SerializeInternalFieldsCallback> embedder_fields_serializers_;
556  bool created_;
557 };
558 
559 } // namespace
560 
561 SnapshotCreator::SnapshotCreator(Isolate* isolate,
562  const intptr_t* external_references,
563  StartupData* existing_snapshot) {
564  SnapshotCreatorData* data = new SnapshotCreatorData(isolate);
565  data->isolate_ = isolate;
566  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
567  internal_isolate->set_array_buffer_allocator(&data->allocator_);
568  internal_isolate->set_api_external_references(external_references);
569  internal_isolate->enable_serializer();
570  isolate->Enter();
571  const StartupData* blob = existing_snapshot
572  ? existing_snapshot
573  : i::Snapshot::DefaultSnapshotBlob();
574  if (blob && blob->raw_size > 0) {
575  internal_isolate->set_snapshot_blob(blob);
576  i::Snapshot::Initialize(internal_isolate);
577  } else {
578  internal_isolate->Init(nullptr);
579  }
580  data_ = data;
581 }
582 
583 SnapshotCreator::SnapshotCreator(const intptr_t* external_references,
584  StartupData* existing_snapshot)
585  : SnapshotCreator(Isolate::Allocate(), external_references,
586  existing_snapshot) {}
587 
588 SnapshotCreator::~SnapshotCreator() {
589  SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
590  DCHECK(data->created_);
591  Isolate* isolate = data->isolate_;
592  isolate->Exit();
593  isolate->Dispose();
594  delete data;
595 }
596 
597 Isolate* SnapshotCreator::GetIsolate() {
598  return SnapshotCreatorData::cast(data_)->isolate_;
599 }
600 
601 void SnapshotCreator::SetDefaultContext(
602  Local<Context> context, SerializeInternalFieldsCallback callback) {
603  DCHECK(!context.IsEmpty());
604  SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
605  DCHECK(!data->created_);
606  DCHECK(data->default_context_.IsEmpty());
607  Isolate* isolate = data->isolate_;
608  CHECK_EQ(isolate, context->GetIsolate());
609  data->default_context_.Reset(isolate, context);
610  data->default_embedder_fields_serializer_ = callback;
611 }
612 
613 size_t SnapshotCreator::AddContext(Local<Context> context,
614  SerializeInternalFieldsCallback callback) {
615  DCHECK(!context.IsEmpty());
616  SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
617  DCHECK(!data->created_);
618  Isolate* isolate = data->isolate_;
619  CHECK_EQ(isolate, context->GetIsolate());
620  size_t index = data->contexts_.Size();
621  data->contexts_.Append(context);
622  data->embedder_fields_serializers_.push_back(callback);
623  return index;
624 }
625 
626 size_t SnapshotCreator::AddTemplate(Local<Template> template_obj) {
627  return AddData(template_obj);
628 }
629 
630 size_t SnapshotCreator::AddData(i::Address object) {
631  DCHECK_NE(object, i::kNullAddress);
632  SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
633  DCHECK(!data->created_);
634  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_);
635  i::HandleScope scope(isolate);
636  i::Handle<i::Object> obj(reinterpret_cast<i::Object*>(object), isolate);
638  if (!isolate->heap()->serialized_objects()->IsArrayList()) {
639  list = i::ArrayList::New(isolate, 1);
640  } else {
642  i::ArrayList::cast(isolate->heap()->serialized_objects()), isolate);
643  }
644  size_t index = static_cast<size_t>(list->Length());
645  list = i::ArrayList::Add(isolate, list, obj);
646  isolate->heap()->SetSerializedObjects(*list);
647  return index;
648 }
649 
650 size_t SnapshotCreator::AddData(Local<Context> context, i::Address object) {
651  DCHECK_NE(object, i::kNullAddress);
652  DCHECK(!SnapshotCreatorData::cast(data_)->created_);
653  i::Handle<i::Context> ctx = Utils::OpenHandle(*context);
654  i::Isolate* isolate = ctx->GetIsolate();
655  i::HandleScope scope(isolate);
656  i::Handle<i::Object> obj(reinterpret_cast<i::Object*>(object), isolate);
658  if (!ctx->serialized_objects()->IsArrayList()) {
659  list = i::ArrayList::New(isolate, 1);
660  } else {
662  i::ArrayList::cast(ctx->serialized_objects()), isolate);
663  }
664  size_t index = static_cast<size_t>(list->Length());
665  list = i::ArrayList::Add(isolate, list, obj);
666  ctx->set_serialized_objects(*list);
667  return index;
668 }
669 
670 namespace {
671 void ConvertSerializedObjectsToFixedArray(Local<Context> context) {
672  i::Handle<i::Context> ctx = Utils::OpenHandle(*context);
673  i::Isolate* isolate = ctx->GetIsolate();
674  if (!ctx->serialized_objects()->IsArrayList()) {
675  ctx->set_serialized_objects(i::ReadOnlyRoots(isolate).empty_fixed_array());
676  } else {
677  i::Handle<i::ArrayList> list(i::ArrayList::cast(ctx->serialized_objects()),
678  isolate);
679  i::Handle<i::FixedArray> elements = i::ArrayList::Elements(isolate, list);
680  ctx->set_serialized_objects(*elements);
681  }
682 }
683 
684 void ConvertSerializedObjectsToFixedArray(i::Isolate* isolate) {
685  if (!isolate->heap()->serialized_objects()->IsArrayList()) {
686  isolate->heap()->SetSerializedObjects(
687  i::ReadOnlyRoots(isolate).empty_fixed_array());
688  } else {
690  i::ArrayList::cast(isolate->heap()->serialized_objects()), isolate);
691  i::Handle<i::FixedArray> elements = i::ArrayList::Elements(isolate, list);
692  isolate->heap()->SetSerializedObjects(*elements);
693  }
694 }
695 } // anonymous namespace
696 
697 StartupData SnapshotCreator::CreateBlob(
698  SnapshotCreator::FunctionCodeHandling function_code_handling) {
699  SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
700  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_);
701  DCHECK(!data->created_);
702  DCHECK(!data->default_context_.IsEmpty());
703 
704  int num_additional_contexts = static_cast<int>(data->contexts_.Size());
705 
706  {
707  i::HandleScope scope(isolate);
708  // Convert list of context-independent data to FixedArray.
709  ConvertSerializedObjectsToFixedArray(isolate);
710 
711  // Convert lists of context-dependent data to FixedArray.
712  ConvertSerializedObjectsToFixedArray(
713  data->default_context_.Get(data->isolate_));
714  for (int i = 0; i < num_additional_contexts; i++) {
715  ConvertSerializedObjectsToFixedArray(data->contexts_.Get(i));
716  }
717 
718  // We need to store the global proxy size upfront in case we need the
719  // bootstrapper to create a global proxy before we deserialize the context.
720  i::Handle<i::FixedArray> global_proxy_sizes =
721  isolate->factory()->NewFixedArray(num_additional_contexts, i::TENURED);
722  for (int i = 0; i < num_additional_contexts; i++) {
723  i::Handle<i::Context> context =
724  v8::Utils::OpenHandle(*data->contexts_.Get(i));
725  global_proxy_sizes->set(i,
726  i::Smi::FromInt(context->global_proxy()->Size()));
727  }
728  isolate->heap()->SetSerializedGlobalProxySizes(*global_proxy_sizes);
729  }
730 
731  // We might rehash strings and re-sort descriptors. Clear the lookup cache.
732  isolate->descriptor_lookup_cache()->Clear();
733 
734  // If we don't do this then we end up with a stray root pointing at the
735  // context even after we have disposed of the context.
736  isolate->heap()->CollectAllAvailableGarbage(
737  i::GarbageCollectionReason::kSnapshotCreator);
738  {
739  i::HandleScope scope(isolate);
740  isolate->heap()->CompactWeakArrayLists(internal::TENURED);
741  }
742 
743  isolate->heap()->read_only_space()->ClearStringPaddingIfNeeded();
744 
745  if (function_code_handling == FunctionCodeHandling::kClear) {
746  // Clear out re-compilable data from all shared function infos. Any
747  // JSFunctions using these SFIs will have their code pointers reset by the
748  // partial serializer.
749  //
750  // We have to iterate the heap and collect handles to each clearable SFI,
751  // before we disable allocation, since we have to allocate UncompiledDatas
752  // to be able to recompile them.
753  i::HandleScope scope(isolate);
754  std::vector<i::Handle<i::SharedFunctionInfo>> sfis_to_clear;
755 
756  i::HeapIterator heap_iterator(isolate->heap());
757  while (i::HeapObject* current_obj = heap_iterator.next()) {
758  if (current_obj->IsSharedFunctionInfo()) {
759  i::SharedFunctionInfo* shared =
760  i::SharedFunctionInfo::cast(current_obj);
761  if (shared->CanDiscardCompiled()) {
762  sfis_to_clear.emplace_back(shared, isolate);
763  }
764  }
765  }
766  i::AllowHeapAllocation allocate_for_discard;
767  for (i::Handle<i::SharedFunctionInfo> shared : sfis_to_clear) {
768  i::SharedFunctionInfo::DiscardCompiled(isolate, shared);
769  }
770  }
771 
772  i::DisallowHeapAllocation no_gc_from_here_on;
773 
774  int num_contexts = num_additional_contexts + 1;
775  std::vector<i::Context> contexts;
776  contexts.reserve(num_contexts);
777  {
778  i::HandleScope scope(isolate);
779  contexts.push_back(
780  *v8::Utils::OpenHandle(*data->default_context_.Get(data->isolate_)));
781  data->default_context_.Reset();
782  for (int i = 0; i < num_additional_contexts; i++) {
783  i::Handle<i::Context> context =
784  v8::Utils::OpenHandle(*data->contexts_.Get(i));
785  contexts.push_back(*context);
786  }
787  data->contexts_.Clear();
788  }
789 
790  // Check that values referenced by global/eternal handles are accounted for.
791  i::SerializedHandleChecker handle_checker(isolate, &contexts);
792  CHECK(handle_checker.CheckGlobalAndEternalHandles());
793 
794  i::HeapIterator heap_iterator(isolate->heap());
795  while (i::HeapObject* current_obj = heap_iterator.next()) {
796  if (current_obj->IsJSFunction()) {
797  i::JSFunction* fun = i::JSFunction::cast(current_obj);
798 
799  // Complete in-object slack tracking for all functions.
800  fun->CompleteInobjectSlackTrackingIfActive();
801 
802  // Also, clear out feedback vectors, or any optimized code.
803  if (fun->has_feedback_vector()) {
804  fun->feedback_cell()->set_value(
805  i::ReadOnlyRoots(isolate).undefined_value());
806  fun->set_code(isolate->builtins()->builtin(i::Builtins::kCompileLazy));
807  }
808  if (function_code_handling == FunctionCodeHandling::kClear) {
809  DCHECK(fun->shared()->HasWasmExportedFunctionData() ||
810  fun->shared()->HasBuiltinId() ||
811  fun->shared()->IsApiFunction() ||
812  fun->shared()->HasUncompiledDataWithoutPreParsedScope());
813  }
814  }
815  }
816 
817  i::ReadOnlySerializer read_only_serializer(isolate);
818  read_only_serializer.SerializeReadOnlyRoots();
819 
820  i::StartupSerializer startup_serializer(isolate, &read_only_serializer);
821  startup_serializer.SerializeStrongReferences();
822 
823  // Serialize each context with a new partial serializer.
824  std::vector<i::SnapshotData*> context_snapshots;
825  context_snapshots.reserve(num_contexts);
826 
827  // TODO(6593): generalize rehashing, and remove this flag.
828  bool can_be_rehashed = true;
829 
830  for (int i = 0; i < num_contexts; i++) {
831  bool is_default_context = i == 0;
832  i::PartialSerializer partial_serializer(
833  isolate, &startup_serializer,
834  is_default_context ? data->default_embedder_fields_serializer_
835  : data->embedder_fields_serializers_[i - 1]);
836  partial_serializer.Serialize(&contexts[i], !is_default_context);
837  can_be_rehashed = can_be_rehashed && partial_serializer.can_be_rehashed();
838  context_snapshots.push_back(new i::SnapshotData(&partial_serializer));
839  }
840 
841  startup_serializer.SerializeWeakReferencesAndDeferred();
842  can_be_rehashed = can_be_rehashed && startup_serializer.can_be_rehashed();
843 
844  read_only_serializer.FinalizeSerialization();
845  can_be_rehashed = can_be_rehashed && read_only_serializer.can_be_rehashed();
846 
847  i::SnapshotData read_only_snapshot(&read_only_serializer);
848  i::SnapshotData startup_snapshot(&startup_serializer);
849  StartupData result =
850  i::Snapshot::CreateSnapshotBlob(&startup_snapshot, &read_only_snapshot,
851  context_snapshots, can_be_rehashed);
852 
853  // Delete heap-allocated context snapshot instances.
854  for (const auto context_snapshot : context_snapshots) {
855  delete context_snapshot;
856  }
857  data->created_ = true;
858 
859  DCHECK(i::Snapshot::VerifyChecksum(&result));
860  return result;
861 }
862 
863 void V8::SetDcheckErrorHandler(DcheckErrorCallback that) {
864  v8::base::SetDcheckFunction(that);
865 }
866 
867 void V8::SetFlagsFromString(const char* str, int length) {
868  i::FlagList::SetFlagsFromString(str, length);
869  i::FlagList::EnforceFlagImplications();
870 }
871 
872 
873 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
874  i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
875 }
876 
877 RegisteredExtension* RegisteredExtension::first_extension_ = nullptr;
878 
879 RegisteredExtension::RegisteredExtension(Extension* extension)
880  : extension_(extension) { }
881 
882 
883 void RegisteredExtension::Register(RegisteredExtension* that) {
884  that->next_ = first_extension_;
885  first_extension_ = that;
886 }
887 
888 
889 void RegisteredExtension::UnregisterAll() {
890  RegisteredExtension* re = first_extension_;
891  while (re != nullptr) {
892  RegisteredExtension* next = re->next();
893  delete re;
894  re = next;
895  }
896  first_extension_ = nullptr;
897 }
898 
899 namespace {
900 class ExtensionResource : public String::ExternalOneByteStringResource {
901  public:
902  ExtensionResource() : data_(nullptr), length_(0) {}
903  ExtensionResource(const char* data, size_t length)
904  : data_(data), length_(length) {}
905  const char* data() const override { return data_; }
906  size_t length() const override { return length_; }
907  void Dispose() override {}
908 
909  private:
910  const char* data_;
911  size_t length_;
912 };
913 } // anonymous namespace
914 
915 void RegisterExtension(Extension* that) {
916  RegisteredExtension* extension = new RegisteredExtension(that);
917  RegisteredExtension::Register(extension);
918 }
919 
920 
921 Extension::Extension(const char* name,
922  const char* source,
923  int dep_count,
924  const char** deps,
925  int source_length)
926  : name_(name),
927  source_length_(source_length >= 0 ?
928  source_length :
929  (source ? static_cast<int>(strlen(source)) : 0)),
930  dep_count_(dep_count),
931  deps_(deps),
932  auto_enable_(false) {
933  source_ = new ExtensionResource(source, source_length_);
934  CHECK(source != nullptr || source_length_ == 0);
935 }
936 
937 ResourceConstraints::ResourceConstraints()
938  : max_semi_space_size_in_kb_(0),
939  max_old_space_size_(0),
940  stack_limit_(nullptr),
941  code_range_size_(0),
942  max_zone_pool_size_(0) {}
943 
944 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
945  uint64_t virtual_memory_limit) {
946  set_max_semi_space_size_in_kb(
947  i::Heap::ComputeMaxSemiSpaceSize(physical_memory));
948  set_max_old_space_size(i::Heap::ComputeMaxOldGenerationSize(physical_memory));
949  set_max_zone_pool_size(i::AccountingAllocator::kMaxPoolSize);
950 
951  if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
952  // Reserve no more than 1/8 of the memory for the code range, but at most
953  // kMaximalCodeRangeSize.
954  set_code_range_size(
955  i::Min(i::kMaximalCodeRangeSize / i::MB,
956  static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
957  }
958 }
959 
960 void SetResourceConstraints(i::Isolate* isolate,
961  const ResourceConstraints& constraints) {
962  size_t semi_space_size = constraints.max_semi_space_size_in_kb();
963  size_t old_space_size = constraints.max_old_space_size();
964  size_t code_range_size = constraints.code_range_size();
965  size_t max_pool_size = constraints.max_zone_pool_size();
966  if (semi_space_size != 0 || old_space_size != 0 || code_range_size != 0) {
967  isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
968  code_range_size);
969  }
970  isolate->allocator()->ConfigureSegmentPool(max_pool_size);
971 
972  if (constraints.stack_limit() != nullptr) {
973  uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
974  isolate->stack_guard()->SetStackLimit(limit);
975  }
976 }
977 
978 i::Address* V8::GlobalizeReference(i::Isolate* isolate, i::Address* obj) {
979  LOG_API(isolate, Persistent, New);
980  i::Handle<i::Object> result = isolate->global_handles()->Create(*obj);
981 #ifdef VERIFY_HEAP
982  if (i::FLAG_verify_heap) {
983  i::ObjectPtr(*obj)->ObjectVerify(isolate);
984  }
985 #endif // VERIFY_HEAP
986  return result.location();
987 }
988 
989 i::Address* V8::CopyPersistent(i::Address* obj) {
990  i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj);
991  return result.location();
992 }
993 
994 void V8::RegisterExternallyReferencedObject(i::Address* location,
995  i::Isolate* isolate) {
996  isolate->heap()->RegisterExternallyReferencedObject(location);
997 }
998 
999 void V8::MakeWeak(i::Address* location, void* parameter,
1000  WeakCallbackInfo<void>::Callback weak_callback,
1001  WeakCallbackType type) {
1002  i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type);
1003 }
1004 
1005 void V8::MakeWeak(i::Address** location_addr) {
1006  i::GlobalHandles::MakeWeak(location_addr);
1007 }
1008 
1009 void* V8::ClearWeak(i::Address* location) {
1010  return i::GlobalHandles::ClearWeakness(location);
1011 }
1012 
1013 void V8::AnnotateStrongRetainer(i::Address* location, const char* label) {
1014  i::GlobalHandles::AnnotateStrongRetainer(location, label);
1015 }
1016 
1017 void V8::DisposeGlobal(i::Address* location) {
1018  i::GlobalHandles::Destroy(location);
1019 }
1020 
1021 Value* V8::Eternalize(Isolate* v8_isolate, Value* value) {
1022  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1023  i::Object* object = *Utils::OpenHandle(value);
1024  int index = -1;
1025  isolate->eternal_handles()->Create(isolate, object, &index);
1026  return reinterpret_cast<Value*>(
1027  isolate->eternal_handles()->Get(index).location());
1028 }
1029 
1030 
1031 void V8::FromJustIsNothing() {
1032  Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing.");
1033 }
1034 
1035 
1036 void V8::ToLocalEmpty() {
1037  Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal.");
1038 }
1039 
1040 void V8::InternalFieldOutOfBounds(int index) {
1041  Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback,
1042  "WeakCallbackInfo::GetInternalField",
1043  "Internal field out of bounds.");
1044 }
1045 
1046 
1047 // --- H a n d l e s ---
1048 
1049 
1050 HandleScope::HandleScope(Isolate* isolate) {
1051  Initialize(isolate);
1052 }
1053 
1054 
1055 void HandleScope::Initialize(Isolate* isolate) {
1056  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
1057  // We do not want to check the correct usage of the Locker class all over the
1058  // place, so we do it only here: Without a HandleScope, an embedder can do
1059  // almost nothing, so it is enough to check in this central place.
1060  // We make an exception if the serializer is enabled, which means that the
1061  // Isolate is exclusively used to create a snapshot.
1062  Utils::ApiCheck(
1063  !v8::Locker::IsActive() ||
1064  internal_isolate->thread_manager()->IsLockedByCurrentThread() ||
1065  internal_isolate->serializer_enabled(),
1066  "HandleScope::HandleScope",
1067  "Entering the V8 API without proper locking in place");
1068  i::HandleScopeData* current = internal_isolate->handle_scope_data();
1069  isolate_ = internal_isolate;
1070  prev_next_ = current->next;
1071  prev_limit_ = current->limit;
1072  current->level++;
1073 }
1074 
1075 
1076 HandleScope::~HandleScope() {
1077  i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
1078 }
1079 
1080 void* HandleScope::operator new(size_t) { base::OS::Abort(); }
1081 void* HandleScope::operator new[](size_t) { base::OS::Abort(); }
1082 void HandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
1083 void HandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }
1084 
1085 int HandleScope::NumberOfHandles(Isolate* isolate) {
1086  return i::HandleScope::NumberOfHandles(
1087  reinterpret_cast<i::Isolate*>(isolate));
1088 }
1089 
1090 i::Address* HandleScope::CreateHandle(i::Isolate* isolate, i::Address value) {
1091  return i::HandleScope::CreateHandle(isolate, value);
1092 }
1093 
1094 i::Address* HandleScope::CreateHandle(
1095  i::NeverReadOnlySpaceObject* writable_object, i::Address value) {
1096  DCHECK(reinterpret_cast<i::HeapObject*>(writable_object)->IsHeapObject());
1097  return i::HandleScope::CreateHandle(writable_object->GetIsolate(), value);
1098 }
1099 
1100 
1101 EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
1102  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1103  escape_slot_ = CreateHandle(
1104  isolate,
1105  reinterpret_cast<i::Address>(i::ReadOnlyRoots(isolate).the_hole_value()));
1106  Initialize(v8_isolate);
1107 }
1108 
1110  i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
1111  Utils::ApiCheck(
1112  reinterpret_cast<i::Object*>(*escape_slot_)->IsTheHole(heap->isolate()),
1113  "EscapableHandleScope::Escape", "Escape value set twice");
1114  if (escape_value == nullptr) {
1115  *escape_slot_ =
1116  reinterpret_cast<i::Address>(i::ReadOnlyRoots(heap).undefined_value());
1117  return nullptr;
1118  }
1119  *escape_slot_ = *escape_value;
1120  return escape_slot_;
1121 }
1122 
1123 void* EscapableHandleScope::operator new(size_t) { base::OS::Abort(); }
1124 void* EscapableHandleScope::operator new[](size_t) { base::OS::Abort(); }
1125 void EscapableHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
1126 void EscapableHandleScope::operator delete[](void*, size_t) {
1127  base::OS::Abort();
1128 }
1129 
1130 SealHandleScope::SealHandleScope(Isolate* isolate)
1131  : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
1132  i::HandleScopeData* current = isolate_->handle_scope_data();
1133  prev_limit_ = current->limit;
1134  current->limit = current->next;
1135  prev_sealed_level_ = current->sealed_level;
1136  current->sealed_level = current->level;
1137 }
1138 
1139 
1140 SealHandleScope::~SealHandleScope() {
1141  i::HandleScopeData* current = isolate_->handle_scope_data();
1142  DCHECK_EQ(current->next, current->limit);
1143  current->limit = prev_limit_;
1144  DCHECK_EQ(current->level, current->sealed_level);
1145  current->sealed_level = prev_sealed_level_;
1146 }
1147 
1148 void* SealHandleScope::operator new(size_t) { base::OS::Abort(); }
1149 void* SealHandleScope::operator new[](size_t) { base::OS::Abort(); }
1150 void SealHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
1151 void SealHandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }
1152 
1153 void Context::Enter() {
1154  i::Handle<i::Context> env = Utils::OpenHandle(this);
1155  i::Isolate* isolate = env->GetIsolate();
1156  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1157  i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
1158  impl->EnterContext(env);
1159  impl->SaveContext(isolate->context());
1160  isolate->set_context(*env);
1161 }
1162 
1163 void Context::Exit() {
1164  i::Handle<i::Context> env = Utils::OpenHandle(this);
1165  i::Isolate* isolate = env->GetIsolate();
1166  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1167  i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
1168  if (!Utils::ApiCheck(impl->LastEnteredContextWas(env),
1169  "v8::Context::Exit()",
1170  "Cannot exit non-entered context")) {
1171  return;
1172  }
1173  impl->LeaveContext();
1174  isolate->set_context(impl->RestoreContext());
1175 }
1176 
1178  Local<Context> backup_incumbent_context)
1179  : backup_incumbent_context_(backup_incumbent_context) {
1180  DCHECK(!backup_incumbent_context_.IsEmpty());
1181 
1182  i::Handle<i::Context> env = Utils::OpenHandle(*backup_incumbent_context_);
1183  i::Isolate* isolate = env->GetIsolate();
1184  prev_ = isolate->top_backup_incumbent_scope();
1185  isolate->set_top_backup_incumbent_scope(this);
1186 }
1187 
1188 Context::BackupIncumbentScope::~BackupIncumbentScope() {
1189  i::Handle<i::Context> env = Utils::OpenHandle(*backup_incumbent_context_);
1190  i::Isolate* isolate = env->GetIsolate();
1191  isolate->set_top_backup_incumbent_scope(prev_);
1192 }
1193 
1194 STATIC_ASSERT(i::Internals::kEmbedderDataSlotSize == i::kEmbedderDataSlotSize);
1195 
1196 static i::Handle<i::EmbedderDataArray> EmbedderDataFor(Context* context,
1197  int index, bool can_grow,
1198  const char* location) {
1199  i::Handle<i::Context> env = Utils::OpenHandle(context);
1200  i::Isolate* isolate = env->GetIsolate();
1201  bool ok =
1202  Utils::ApiCheck(env->IsNativeContext(),
1203  location,
1204  "Not a native context") &&
1205  Utils::ApiCheck(index >= 0, location, "Negative index");
1206  if (!ok) return i::Handle<i::EmbedderDataArray>();
1207  // TODO(ishell): remove cast once embedder_data slot has a proper type.
1209  i::EmbedderDataArray::cast(env->embedder_data()), isolate);
1210  if (index < data->length()) return data;
1211  if (!Utils::ApiCheck(can_grow && index < i::EmbedderDataArray::kMaxLength,
1212  location, "Index too large")) {
1214  }
1215  data = i::EmbedderDataArray::EnsureCapacity(isolate, data, index);
1216  env->set_embedder_data(*data);
1217  return data;
1218 }
1219 
1220 uint32_t Context::GetNumberOfEmbedderDataFields() {
1221  i::Handle<i::Context> context = Utils::OpenHandle(this);
1222  CHECK(context->IsNativeContext());
1223  // TODO(ishell): remove cast once embedder_data slot has a proper type.
1224  return static_cast<uint32_t>(
1225  i::EmbedderDataArray::cast(context->embedder_data())->length());
1226 }
1227 
1228 v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
1229  const char* location = "v8::Context::GetEmbedderData()";
1231  EmbedderDataFor(this, index, false, location);
1232  if (data.is_null()) return Local<Value>();
1233  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1234  i::Handle<i::Object> result(i::EmbedderDataSlot(*data, index).load_tagged(),
1235  isolate);
1236  return Utils::ToLocal(result);
1237 }
1238 
1239 
1240 void Context::SetEmbedderData(int index, v8::Local<Value> value) {
1241  const char* location = "v8::Context::SetEmbedderData()";
1243  EmbedderDataFor(this, index, true, location);
1244  if (data.is_null()) return;
1245  i::Handle<i::Object> val = Utils::OpenHandle(*value);
1246  i::EmbedderDataSlot::store_tagged(*data, index, *val);
1247  DCHECK_EQ(*Utils::OpenHandle(*value),
1248  *Utils::OpenHandle(*GetEmbedderData(index)));
1249 }
1250 
1251 
1252 void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
1253  const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
1255  EmbedderDataFor(this, index, false, location);
1256  if (data.is_null()) return nullptr;
1257  void* result;
1258  Utils::ApiCheck(i::EmbedderDataSlot(*data, index).ToAlignedPointer(&result),
1259  location, "Pointer is not aligned");
1260  return result;
1261 }
1262 
1263 
1264 void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
1265  const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
1267  EmbedderDataFor(this, index, true, location);
1268  bool ok = i::EmbedderDataSlot(*data, index).store_aligned_pointer(value);
1269  Utils::ApiCheck(ok, location, "Pointer is not aligned");
1270  DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
1271 }
1272 
1273 
1274 // --- T e m p l a t e ---
1275 
1276 
1277 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
1278  that->set_number_of_properties(0);
1279  that->set_tag(i::Smi::FromInt(type));
1280 }
1281 
1282 
1284  v8::PropertyAttribute attribute) {
1285  auto templ = Utils::OpenHandle(this);
1286  i::Isolate* isolate = templ->GetIsolate();
1287  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1288  i::HandleScope scope(isolate);
1289  auto value_obj = Utils::OpenHandle(*value);
1290  CHECK(!value_obj->IsJSReceiver() || value_obj->IsTemplateInfo());
1291  if (value_obj->IsObjectTemplateInfo()) {
1292  templ->set_serial_number(i::Smi::kZero);
1293  if (templ->IsFunctionTemplateInfo()) {
1294  i::Handle<i::FunctionTemplateInfo>::cast(templ)->set_do_not_cache(true);
1295  }
1296  }
1297  i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
1298  value_obj,
1299  static_cast<i::PropertyAttributes>(attribute));
1300 }
1301 
1302 void Template::SetPrivate(v8::Local<Private> name, v8::Local<Data> value,
1303  v8::PropertyAttribute attribute) {
1304  Set(Utils::ToLocal(Utils::OpenHandle(reinterpret_cast<Name*>(*name))), value,
1305  attribute);
1306 }
1307 
1308 void Template::SetAccessorProperty(
1309  v8::Local<v8::Name> name,
1312  v8::PropertyAttribute attribute,
1313  v8::AccessControl access_control) {
1314  // TODO(verwaest): Remove |access_control|.
1315  DCHECK_EQ(v8::DEFAULT, access_control);
1316  auto templ = Utils::OpenHandle(this);
1317  auto isolate = templ->GetIsolate();
1318  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1319  DCHECK(!name.IsEmpty());
1320  DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
1321  i::HandleScope scope(isolate);
1322  i::ApiNatives::AddAccessorProperty(
1323  isolate, templ, Utils::OpenHandle(*name),
1324  Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true),
1325  static_cast<i::PropertyAttributes>(attribute));
1326 }
1327 
1328 
1329 // --- F u n c t i o n T e m p l a t e ---
1330 static void InitializeFunctionTemplate(
1332  InitializeTemplate(info, Consts::FUNCTION_TEMPLATE);
1333  info->set_flag(0);
1334 }
1335 
1336 static Local<ObjectTemplate> ObjectTemplateNew(
1337  i::Isolate* isolate, v8::Local<FunctionTemplate> constructor,
1338  bool do_not_cache);
1339 
1341  i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
1342  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
1343  i::Handle<i::Object> result(Utils::OpenHandle(this)->GetPrototypeTemplate(),
1344  i_isolate);
1345  if (result->IsUndefined(i_isolate)) {
1346  // Do not cache prototype objects.
1347  result = Utils::OpenHandle(
1348  *ObjectTemplateNew(i_isolate, Local<FunctionTemplate>(), true));
1349  i::FunctionTemplateInfo::SetPrototypeTemplate(
1350  i_isolate, Utils::OpenHandle(this), result);
1351  }
1352  return ToApiHandle<ObjectTemplate>(result);
1353 }
1354 
1356  Local<FunctionTemplate> prototype_provider) {
1357  i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
1358  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
1359  i::Handle<i::Object> result = Utils::OpenHandle(*prototype_provider);
1360  auto info = Utils::OpenHandle(this);
1361  CHECK(info->GetPrototypeTemplate()->IsUndefined(i_isolate));
1362  CHECK(info->GetParentTemplate()->IsUndefined(i_isolate));
1363  i::FunctionTemplateInfo::SetPrototypeProviderTemplate(i_isolate, info,
1364  result);
1365 }
1366 
1367 static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info,
1368  const char* func) {
1369  Utils::ApiCheck(!info->instantiated(), func,
1370  "FunctionTemplate already instantiated");
1371 }
1372 
1373 
1375  auto info = Utils::OpenHandle(this);
1376  EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit");
1377  i::Isolate* i_isolate = info->GetIsolate();
1378  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
1379  CHECK(info->GetPrototypeProviderTemplate()->IsUndefined(i_isolate));
1380  i::FunctionTemplateInfo::SetParentTemplate(i_isolate, info,
1381  Utils::OpenHandle(*value));
1382 }
1383 
1384 static Local<FunctionTemplate> FunctionTemplateNew(
1385  i::Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
1386  v8::Local<Signature> signature, int length, bool do_not_cache,
1387  v8::Local<Private> cached_property_name = v8::Local<Private>(),
1388  SideEffectType side_effect_type = SideEffectType::kHasSideEffect) {
1389  i::Handle<i::Struct> struct_obj =
1390  isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE, i::TENURED);
1393  InitializeFunctionTemplate(obj);
1394  obj->set_do_not_cache(do_not_cache);
1395  int next_serial_number = i::FunctionTemplateInfo::kInvalidSerialNumber;
1396  if (!do_not_cache) {
1397  next_serial_number = isolate->heap()->GetNextTemplateSerialNumber();
1398  }
1399  obj->set_serial_number(i::Smi::FromInt(next_serial_number));
1400  if (callback != nullptr) {
1401  Utils::ToLocal(obj)->SetCallHandler(callback, data, side_effect_type);
1402  }
1403  obj->set_length(length);
1404  obj->set_undetectable(false);
1405  obj->set_needs_access_check(false);
1406  obj->set_accept_any_receiver(true);
1407  if (!signature.IsEmpty()) {
1408  obj->set_signature(*Utils::OpenHandle(*signature));
1409  }
1410  obj->set_cached_property_name(
1411  cached_property_name.IsEmpty()
1412  ? i::ReadOnlyRoots(isolate).the_hole_value()
1413  : *Utils::OpenHandle(*cached_property_name));
1414  return Utils::ToLocal(obj);
1415 }
1416 
1418  Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
1419  v8::Local<Signature> signature, int length, ConstructorBehavior behavior,
1420  SideEffectType side_effect_type) {
1421  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1422  // Changes to the environment cannot be captured in the snapshot. Expect no
1423  // function templates when the isolate is created for serialization.
1424  LOG_API(i_isolate, FunctionTemplate, New);
1425  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
1426  auto templ = FunctionTemplateNew(i_isolate, callback, data, signature, length,
1427  false, Local<Private>(), side_effect_type);
1428  if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype();
1429  return templ;
1430 }
1431 
1433  size_t index) {
1434  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1435  i::FixedArray serialized_objects = i_isolate->heap()->serialized_objects();
1436  int int_index = static_cast<int>(index);
1437  if (int_index < serialized_objects->length()) {
1438  i::Object* info = serialized_objects->get(int_index);
1439  if (info->IsFunctionTemplateInfo()) {
1440  return Utils::ToLocal(i::Handle<i::FunctionTemplateInfo>(
1441  i::FunctionTemplateInfo::cast(info), i_isolate));
1442  }
1443  }
1444  return Local<FunctionTemplate>();
1445 }
1446 
1448  Isolate* isolate, FunctionCallback callback, Local<Private> cache_property,
1449  Local<Value> data, Local<Signature> signature, int length,
1450  SideEffectType side_effect_type) {
1451  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1452  LOG_API(i_isolate, FunctionTemplate, NewWithCache);
1453  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
1454  return FunctionTemplateNew(i_isolate, callback, data, signature, length,
1455  false, cache_property, side_effect_type);
1456 }
1457 
1458 Local<Signature> Signature::New(Isolate* isolate,
1459  Local<FunctionTemplate> receiver) {
1460  return Utils::SignatureToLocal(Utils::OpenHandle(*receiver));
1461 }
1462 
1463 
1464 Local<AccessorSignature> AccessorSignature::New(
1465  Isolate* isolate, Local<FunctionTemplate> receiver) {
1466  return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
1467 }
1468 
1469 #define SET_FIELD_WRAPPED(isolate, obj, setter, cdata) \
1470  do { \
1471  i::Handle<i::Object> foreign = FromCData(isolate, cdata); \
1472  (obj)->setter(*foreign); \
1473  } while (false)
1474 
1475 void FunctionTemplate::SetCallHandler(FunctionCallback callback,
1476  v8::Local<Value> data,
1477  SideEffectType side_effect_type) {
1478  auto info = Utils::OpenHandle(this);
1479  EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler");
1480  i::Isolate* isolate = info->GetIsolate();
1481  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1482  i::HandleScope scope(isolate);
1483  i::Handle<i::CallHandlerInfo> obj = isolate->factory()->NewCallHandlerInfo(
1484  side_effect_type == SideEffectType::kHasNoSideEffect);
1485  SET_FIELD_WRAPPED(isolate, obj, set_callback, callback);
1486  SET_FIELD_WRAPPED(isolate, obj, set_js_callback, obj->redirected_callback());
1487  if (data.IsEmpty()) {
1488  data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1489  }
1490  obj->set_data(*Utils::OpenHandle(*data));
1491  info->set_call_code(*obj);
1492 }
1493 
1494 
1495 namespace {
1496 
1497 template <typename Getter, typename Setter>
1498 i::Handle<i::AccessorInfo> MakeAccessorInfo(
1499  i::Isolate* isolate, v8::Local<Name> name, Getter getter, Setter setter,
1500  v8::Local<Value> data, v8::AccessControl settings,
1501  v8::Local<AccessorSignature> signature, bool is_special_data_property,
1502  bool replace_on_access) {
1503  i::Handle<i::AccessorInfo> obj = isolate->factory()->NewAccessorInfo();
1504  SET_FIELD_WRAPPED(isolate, obj, set_getter, getter);
1505  DCHECK_IMPLIES(replace_on_access,
1506  is_special_data_property && setter == nullptr);
1507  if (is_special_data_property && setter == nullptr) {
1508  setter = reinterpret_cast<Setter>(&i::Accessors::ReconfigureToDataProperty);
1509  }
1510  SET_FIELD_WRAPPED(isolate, obj, set_setter, setter);
1511  i::Address redirected = obj->redirected_getter();
1512  if (redirected != i::kNullAddress) {
1513  SET_FIELD_WRAPPED(isolate, obj, set_js_getter, redirected);
1514  }
1515  if (data.IsEmpty()) {
1516  data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1517  }
1518  obj->set_data(*Utils::OpenHandle(*data));
1519  obj->set_is_special_data_property(is_special_data_property);
1520  obj->set_replace_on_access(replace_on_access);
1521  i::Handle<i::Name> accessor_name = Utils::OpenHandle(*name);
1522  if (!accessor_name->IsUniqueName()) {
1523  accessor_name = isolate->factory()->InternalizeString(
1524  i::Handle<i::String>::cast(accessor_name));
1525  }
1526  obj->set_name(*accessor_name);
1527  if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
1528  if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
1529  obj->set_initial_property_attributes(i::NONE);
1530  if (!signature.IsEmpty()) {
1531  obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
1532  }
1533  return obj;
1534 }
1535 
1536 } // namespace
1537 
1539  i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
1540  if (!Utils::ApiCheck(!handle.is_null(),
1541  "v8::FunctionTemplate::InstanceTemplate()",
1542  "Reading from empty handle")) {
1543  return Local<ObjectTemplate>();
1544  }
1545  i::Isolate* isolate = handle->GetIsolate();
1546  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1547  if (handle->GetInstanceTemplate()->IsUndefined(isolate)) {
1548  Local<ObjectTemplate> templ =
1549  ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
1550  i::FunctionTemplateInfo::SetInstanceTemplate(isolate, handle,
1551  Utils::OpenHandle(*templ));
1552  }
1554  i::ObjectTemplateInfo::cast(handle->GetInstanceTemplate()), isolate);
1555  return Utils::ToLocal(result);
1556 }
1557 
1558 
1560  auto info = Utils::OpenHandle(this);
1561  EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength");
1562  auto isolate = info->GetIsolate();
1563  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1564  info->set_length(length);
1565 }
1566 
1567 
1569  auto info = Utils::OpenHandle(this);
1570  EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName");
1571  auto isolate = info->GetIsolate();
1572  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1573  info->set_class_name(*Utils::OpenHandle(*name));
1574 }
1575 
1576 
1578  auto info = Utils::OpenHandle(this);
1579  EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
1580  auto isolate = info->GetIsolate();
1581  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1582  info->set_accept_any_receiver(value);
1583 }
1584 
1585 
1587  auto info = Utils::OpenHandle(this);
1588  EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype");
1589  auto isolate = info->GetIsolate();
1590  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1591  info->set_hidden_prototype(value);
1592 }
1593 
1594 
1596  auto info = Utils::OpenHandle(this);
1597  EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype");
1598  auto isolate = info->GetIsolate();
1599  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1600  info->set_read_only_prototype(true);
1601 }
1602 
1603 
1605  auto info = Utils::OpenHandle(this);
1606  EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype");
1607  auto isolate = info->GetIsolate();
1608  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1609  info->set_remove_prototype(true);
1610 }
1611 
1612 
1613 // --- O b j e c t T e m p l a t e ---
1614 
1615 
1617  Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1618  return New(reinterpret_cast<i::Isolate*>(isolate), constructor);
1619 }
1620 
1621 
1622 static Local<ObjectTemplate> ObjectTemplateNew(
1623  i::Isolate* isolate, v8::Local<FunctionTemplate> constructor,
1624  bool do_not_cache) {
1625  LOG_API(isolate, ObjectTemplate, New);
1626  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1627  i::Handle<i::Struct> struct_obj =
1628  isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE, i::TENURED);
1631  InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
1632  int next_serial_number = 0;
1633  if (!do_not_cache) {
1634  next_serial_number = isolate->heap()->GetNextTemplateSerialNumber();
1635  }
1636  obj->set_serial_number(i::Smi::FromInt(next_serial_number));
1637  if (!constructor.IsEmpty())
1638  obj->set_constructor(*Utils::OpenHandle(*constructor));
1639  obj->set_data(i::Smi::kZero);
1640  return Utils::ToLocal(obj);
1641 }
1642 
1643 Local<ObjectTemplate> ObjectTemplate::New(
1644  i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1645  return ObjectTemplateNew(isolate, constructor, false);
1646 }
1647 
1649  size_t index) {
1650  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1651  i::FixedArray serialized_objects = i_isolate->heap()->serialized_objects();
1652  int int_index = static_cast<int>(index);
1653  if (int_index < serialized_objects->length()) {
1654  i::Object* info = serialized_objects->get(int_index);
1655  if (info->IsObjectTemplateInfo()) {
1656  return Utils::ToLocal(i::Handle<i::ObjectTemplateInfo>(
1657  i::ObjectTemplateInfo::cast(info), i_isolate));
1658  }
1659  }
1660  return Local<ObjectTemplate>();
1661 }
1662 
1663 // Ensure that the object template has a constructor. If no
1664 // constructor is available we create one.
1665 static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
1666  i::Isolate* isolate,
1667  ObjectTemplate* object_template) {
1668  i::Object* obj = Utils::OpenHandle(object_template)->constructor();
1669  if (!obj->IsUndefined(isolate)) {
1670  i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj);
1671  return i::Handle<i::FunctionTemplateInfo>(info, isolate);
1672  }
1673  Local<FunctionTemplate> templ =
1674  FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
1675  i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
1676  i::FunctionTemplateInfo::SetInstanceTemplate(
1677  isolate, constructor, Utils::OpenHandle(object_template));
1678  Utils::OpenHandle(object_template)->set_constructor(*constructor);
1679  return constructor;
1680 }
1681 
1682 template <typename Getter, typename Setter, typename Data, typename Template>
1683 static void TemplateSetAccessor(
1684  Template* template_obj, v8::Local<Name> name, Getter getter, Setter setter,
1685  Data data, AccessControl settings, PropertyAttribute attribute,
1686  v8::Local<AccessorSignature> signature, bool is_special_data_property,
1687  bool replace_on_access, SideEffectType getter_side_effect_type,
1688  SideEffectType setter_side_effect_type) {
1689  auto info = Utils::OpenHandle(template_obj);
1690  auto isolate = info->GetIsolate();
1691  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1692  i::HandleScope scope(isolate);
1693  i::Handle<i::AccessorInfo> accessor_info =
1694  MakeAccessorInfo(isolate, name, getter, setter, data, settings, signature,
1695  is_special_data_property, replace_on_access);
1696  accessor_info->set_initial_property_attributes(
1697  static_cast<i::PropertyAttributes>(attribute));
1698  accessor_info->set_getter_side_effect_type(getter_side_effect_type);
1699  accessor_info->set_setter_side_effect_type(setter_side_effect_type);
1700  i::ApiNatives::AddNativeDataProperty(isolate, info, accessor_info);
1701 }
1702 
1705  AccessorSetterCallback setter, v8::Local<Value> data,
1706  PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
1707  AccessControl settings, SideEffectType getter_side_effect_type,
1708  SideEffectType setter_side_effect_type) {
1709  TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
1710  signature, true, false, getter_side_effect_type,
1711  setter_side_effect_type);
1712 }
1713 
1715  v8::Local<Name> name, AccessorNameGetterCallback getter,
1716  AccessorNameSetterCallback setter, v8::Local<Value> data,
1717  PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
1718  AccessControl settings, SideEffectType getter_side_effect_type,
1719  SideEffectType setter_side_effect_type) {
1720  TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
1721  signature, true, false, getter_side_effect_type,
1722  setter_side_effect_type);
1723 }
1724 
1726  AccessorNameGetterCallback getter,
1727  v8::Local<Value> data,
1728  PropertyAttribute attribute,
1729  SideEffectType getter_side_effect_type,
1730  SideEffectType setter_side_effect_type) {
1731  TemplateSetAccessor(this, name, getter,
1732  static_cast<AccessorNameSetterCallback>(nullptr), data,
1733  DEFAULT, attribute, Local<AccessorSignature>(), true,
1734  true, getter_side_effect_type, setter_side_effect_type);
1735 }
1736 
1737 void Template::SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
1738  PropertyAttribute attribute) {
1739  auto templ = Utils::OpenHandle(this);
1740  i::Isolate* isolate = templ->GetIsolate();
1741  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1742  i::HandleScope scope(isolate);
1743  i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
1744  intrinsic,
1745  static_cast<i::PropertyAttributes>(attribute));
1746 }
1747 
1749  AccessorGetterCallback getter,
1750  AccessorSetterCallback setter,
1751  v8::Local<Value> data, AccessControl settings,
1752  PropertyAttribute attribute,
1753  v8::Local<AccessorSignature> signature,
1754  SideEffectType getter_side_effect_type,
1755  SideEffectType setter_side_effect_type) {
1756  TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
1757  signature, i::FLAG_disable_old_api_accessors, false,
1758  getter_side_effect_type, setter_side_effect_type);
1759 }
1760 
1762  AccessorNameGetterCallback getter,
1763  AccessorNameSetterCallback setter,
1764  v8::Local<Value> data, AccessControl settings,
1765  PropertyAttribute attribute,
1766  v8::Local<AccessorSignature> signature,
1767  SideEffectType getter_side_effect_type,
1768  SideEffectType setter_side_effect_type) {
1769  TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
1770  signature, i::FLAG_disable_old_api_accessors, false,
1771  getter_side_effect_type, setter_side_effect_type);
1772 }
1773 
1774 template <typename Getter, typename Setter, typename Query, typename Descriptor,
1775  typename Deleter, typename Enumerator, typename Definer>
1776 static i::Handle<i::InterceptorInfo> CreateInterceptorInfo(
1777  i::Isolate* isolate, Getter getter, Setter setter, Query query,
1778  Descriptor descriptor, Deleter remover, Enumerator enumerator,
1779  Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
1781  isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE, i::TENURED));
1782  obj->set_flags(0);
1783 
1784  if (getter != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_getter, getter);
1785  if (setter != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_setter, setter);
1786  if (query != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_query, query);
1787  if (descriptor != nullptr)
1788  SET_FIELD_WRAPPED(isolate, obj, set_descriptor, descriptor);
1789  if (remover != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_deleter, remover);
1790  if (enumerator != nullptr)
1791  SET_FIELD_WRAPPED(isolate, obj, set_enumerator, enumerator);
1792  if (definer != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_definer, definer);
1793  obj->set_can_intercept_symbols(
1794  !(static_cast<int>(flags) &
1795  static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings)));
1796  obj->set_all_can_read(static_cast<int>(flags) &
1797  static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1798  obj->set_non_masking(static_cast<int>(flags) &
1799  static_cast<int>(PropertyHandlerFlags::kNonMasking));
1800  obj->set_has_no_side_effect(
1801  static_cast<int>(flags) &
1802  static_cast<int>(PropertyHandlerFlags::kHasNoSideEffect));
1803 
1804  if (data.IsEmpty()) {
1805  data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1806  }
1807  obj->set_data(*Utils::OpenHandle(*data));
1808  return obj;
1809 }
1810 
1811 template <typename Getter, typename Setter, typename Query, typename Descriptor,
1812  typename Deleter, typename Enumerator, typename Definer>
1813 static i::Handle<i::InterceptorInfo> CreateNamedInterceptorInfo(
1814  i::Isolate* isolate, Getter getter, Setter setter, Query query,
1815  Descriptor descriptor, Deleter remover, Enumerator enumerator,
1816  Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
1817  auto interceptor =
1818  CreateInterceptorInfo(isolate, getter, setter, query, descriptor, remover,
1819  enumerator, definer, data, flags);
1820  interceptor->set_is_named(true);
1821  return interceptor;
1822 }
1823 
1824 template <typename Getter, typename Setter, typename Query, typename Descriptor,
1825  typename Deleter, typename Enumerator, typename Definer>
1826 static i::Handle<i::InterceptorInfo> CreateIndexedInterceptorInfo(
1827  i::Isolate* isolate, Getter getter, Setter setter, Query query,
1828  Descriptor descriptor, Deleter remover, Enumerator enumerator,
1829  Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
1830  auto interceptor =
1831  CreateInterceptorInfo(isolate, getter, setter, query, descriptor, remover,
1832  enumerator, definer, data, flags);
1833  interceptor->set_is_named(false);
1834  return interceptor;
1835 }
1836 
1837 template <typename Getter, typename Setter, typename Query, typename Descriptor,
1838  typename Deleter, typename Enumerator, typename Definer>
1839 static void ObjectTemplateSetNamedPropertyHandler(
1840  ObjectTemplate* templ, Getter getter, Setter setter, Query query,
1841  Descriptor descriptor, Deleter remover, Enumerator enumerator,
1842  Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
1843  i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate();
1844  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1845  i::HandleScope scope(isolate);
1846  auto cons = EnsureConstructor(isolate, templ);
1847  EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler");
1848  auto obj =
1849  CreateNamedInterceptorInfo(isolate, getter, setter, query, descriptor,
1850  remover, enumerator, definer, data, flags);
1851  i::FunctionTemplateInfo::SetNamedPropertyHandler(isolate, cons, obj);
1852 }
1853 
1855  const NamedPropertyHandlerConfiguration& config) {
1856  ObjectTemplateSetNamedPropertyHandler(
1857  this, config.getter, config.setter, config.query, config.descriptor,
1858  config.deleter, config.enumerator, config.definer, config.data,
1859  config.flags);
1860 }
1861 
1862 
1864  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1865  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1866  i::HandleScope scope(isolate);
1867  auto cons = EnsureConstructor(isolate, this);
1868  EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable");
1869  cons->set_undetectable(true);
1870 }
1871 
1872 
1874  Local<Value> data) {
1875  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1876  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1877  i::HandleScope scope(isolate);
1878  auto cons = EnsureConstructor(isolate, this);
1879  EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallback");
1880 
1881  i::Handle<i::Struct> struct_info =
1882  isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE, i::TENURED);
1885 
1886  SET_FIELD_WRAPPED(isolate, info, set_callback, callback);
1887  info->set_named_interceptor(nullptr);
1888  info->set_indexed_interceptor(nullptr);
1889 
1890  if (data.IsEmpty()) {
1891  data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1892  }
1893  info->set_data(*Utils::OpenHandle(*data));
1894 
1895  i::FunctionTemplateInfo::SetAccessCheckInfo(isolate, cons, info);
1896  cons->set_needs_access_check(true);
1897 }
1898 
1900  AccessCheckCallback callback,
1901  const NamedPropertyHandlerConfiguration& named_handler,
1902  const IndexedPropertyHandlerConfiguration& indexed_handler,
1903  Local<Value> data) {
1904  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1905  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1906  i::HandleScope scope(isolate);
1907  auto cons = EnsureConstructor(isolate, this);
1908  EnsureNotInstantiated(
1909  cons, "v8::ObjectTemplate::SetAccessCheckCallbackWithHandler");
1910 
1911  i::Handle<i::Struct> struct_info =
1912  isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE, i::TENURED);
1915 
1916  SET_FIELD_WRAPPED(isolate, info, set_callback, callback);
1917  auto named_interceptor = CreateNamedInterceptorInfo(
1918  isolate, named_handler.getter, named_handler.setter, named_handler.query,
1919  named_handler.descriptor, named_handler.deleter, named_handler.enumerator,
1920  named_handler.definer, named_handler.data, named_handler.flags);
1921  info->set_named_interceptor(*named_interceptor);
1922  auto indexed_interceptor = CreateIndexedInterceptorInfo(
1923  isolate, indexed_handler.getter, indexed_handler.setter,
1924  indexed_handler.query, indexed_handler.descriptor,
1925  indexed_handler.deleter, indexed_handler.enumerator,
1926  indexed_handler.definer, indexed_handler.data, indexed_handler.flags);
1927  info->set_indexed_interceptor(*indexed_interceptor);
1928 
1929  if (data.IsEmpty()) {
1930  data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1931  }
1932  info->set_data(*Utils::OpenHandle(*data));
1933 
1934  i::FunctionTemplateInfo::SetAccessCheckInfo(isolate, cons, info);
1935  cons->set_needs_access_check(true);
1936 }
1937 
1939  const IndexedPropertyHandlerConfiguration& config) {
1940  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1941  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1942  i::HandleScope scope(isolate);
1943  auto cons = EnsureConstructor(isolate, this);
1944  EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler");
1945  auto obj = CreateIndexedInterceptorInfo(
1946  isolate, config.getter, config.setter, config.query, config.descriptor,
1947  config.deleter, config.enumerator, config.definer, config.data,
1948  config.flags);
1949  i::FunctionTemplateInfo::SetIndexedPropertyHandler(isolate, cons, obj);
1950 }
1951 
1952 void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
1953  Local<Value> data) {
1954  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1955  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1956  i::HandleScope scope(isolate);
1957  auto cons = EnsureConstructor(isolate, this);
1958  EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
1959  i::Handle<i::CallHandlerInfo> obj = isolate->factory()->NewCallHandlerInfo();
1960  SET_FIELD_WRAPPED(isolate, obj, set_callback, callback);
1961  SET_FIELD_WRAPPED(isolate, obj, set_js_callback, obj->redirected_callback());
1962  if (data.IsEmpty()) {
1963  data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1964  }
1965  obj->set_data(*Utils::OpenHandle(*data));
1966  i::FunctionTemplateInfo::SetInstanceCallHandler(isolate, cons, obj);
1967 }
1968 
1970  return Utils::OpenHandle(this)->embedder_field_count();
1971 }
1972 
1974  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1975  if (!Utils::ApiCheck(i::Smi::IsValid(value),
1976  "v8::ObjectTemplate::SetInternalFieldCount()",
1977  "Invalid embedder field count")) {
1978  return;
1979  }
1980  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1981  if (value > 0) {
1982  // The embedder field count is set by the constructor function's
1983  // construct code, so we ensure that there is a constructor
1984  // function to do the setting.
1985  EnsureConstructor(isolate, this);
1986  }
1987  Utils::OpenHandle(this)->set_embedder_field_count(value);
1988 }
1989 
1991  return Utils::OpenHandle(this)->immutable_proto();
1992 }
1993 
1995  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1996  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
1997  Utils::OpenHandle(this)->set_immutable_proto(true);
1998 }
1999 
2000 // --- S c r i p t s ---
2001 
2002 
2003 // Internally, UnboundScript is a SharedFunctionInfo, and Script is a
2004 // JSFunction.
2005 
2006 ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
2007  BufferPolicy buffer_policy_)
2008  : data(data_),
2009  length(length_),
2010  rejected(false),
2011  buffer_policy(buffer_policy_) {}
2012 
2013 
2014 ScriptCompiler::CachedData::~CachedData() {
2015  if (buffer_policy == BufferOwned) {
2016  delete[] data;
2017  }
2018 }
2019 
2021 
2023 
2024 ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
2025  Encoding encoding)
2026  : impl_(new i::ScriptStreamingData(stream, encoding)) {}
2027 
2028 ScriptCompiler::StreamedSource::~StreamedSource() = default;
2029 
2031  auto function_info =
2032  i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
2033  i::Isolate* isolate = function_info->GetIsolate();
2034  i::Handle<i::JSFunction> function =
2035  isolate->factory()->NewFunctionFromSharedFunctionInfo(
2036  function_info, isolate->native_context());
2037  return ToApiHandle<Script>(function);
2038 }
2039 
2040 int UnboundScript::GetId() {
2041  auto function_info =
2042  i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
2043  i::Isolate* isolate = function_info->GetIsolate();
2044  LOG_API(isolate, UnboundScript, GetId);
2045  i::HandleScope scope(isolate);
2046  i::Handle<i::Script> script(i::Script::cast(function_info->script()),
2047  isolate);
2048  return script->id();
2049 }
2050 
2051 
2052 int UnboundScript::GetLineNumber(int code_pos) {
2054  i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
2055  i::Isolate* isolate = obj->GetIsolate();
2056  LOG_API(isolate, UnboundScript, GetLineNumber);
2057  if (obj->script()->IsScript()) {
2058  i::Handle<i::Script> script(i::Script::cast(obj->script()), isolate);
2059  return i::Script::GetLineNumber(script, code_pos);
2060  } else {
2061  return -1;
2062  }
2063 }
2064 
2065 
2066 Local<Value> UnboundScript::GetScriptName() {
2068  i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
2069  i::Isolate* isolate = obj->GetIsolate();
2070  LOG_API(isolate, UnboundScript, GetName);
2071  if (obj->script()->IsScript()) {
2072  i::Object* name = i::Script::cast(obj->script())->name();
2073  return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
2074  } else {
2075  return Local<String>();
2076  }
2077 }
2078 
2079 
2082  i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
2083  i::Isolate* isolate = obj->GetIsolate();
2084  LOG_API(isolate, UnboundScript, GetSourceURL);
2085  if (obj->script()->IsScript()) {
2086  i::Object* url = i::Script::cast(obj->script())->source_url();
2087  return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
2088  } else {
2089  return Local<String>();
2090  }
2091 }
2092 
2093 
2096  i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
2097  i::Isolate* isolate = obj->GetIsolate();
2098  LOG_API(isolate, UnboundScript, GetSourceMappingURL);
2099  if (obj->script()->IsScript()) {
2100  i::Object* url = i::Script::cast(obj->script())->source_mapping_url();
2101  return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
2102  } else {
2103  return Local<String>();
2104  }
2105 }
2106 
2107 
2109  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2110  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
2111  ENTER_V8(isolate, context, Script, Run, MaybeLocal<Value>(),
2112  InternalEscapableScope);
2113  i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true);
2114  i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
2115  i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
2116  auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this));
2117 
2118  i::Handle<i::Object> receiver = isolate->global_proxy();
2119  Local<Value> result;
2120  has_pending_exception = !ToLocal<Value>(
2121  i::Execution::Call(isolate, fun, receiver, 0, nullptr), &result);
2122 
2123  RETURN_ON_FAILED_EXECUTION(Value);
2124  RETURN_ESCAPED(result);
2125 }
2126 
2127 
2129  i::Handle<i::Script> obj = Utils::OpenHandle(this);
2130  i::Isolate* isolate = obj->GetIsolate();
2131  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2132  i::Handle<i::Object> val(obj->name(), isolate);
2133  return ToApiHandle<Value>(val);
2134 }
2135 
2137  i::Handle<i::Script> obj = Utils::OpenHandle(this);
2138  i::Isolate* isolate = obj->GetIsolate();
2139  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2140  i::Handle<i::FixedArray> val(obj->host_defined_options(), isolate);
2141  return ToApiHandle<PrimitiveArray>(val);
2142 }
2143 
2145  i::Handle<i::Object> obj = Utils::OpenHandle(this);
2146  i::SharedFunctionInfo* sfi = i::JSFunction::cast(*obj)->shared();
2147  i::Isolate* isolate = sfi->GetIsolate();
2148  return ToApiHandle<UnboundScript>(i::handle(sfi, isolate));
2149 }
2150 
2151 // static
2152 Local<PrimitiveArray> PrimitiveArray::New(Isolate* v8_isolate, int length) {
2153  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2154  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2155  Utils::ApiCheck(length >= 0, "v8::PrimitiveArray::New",
2156  "length must be equal or greater than zero");
2157  i::Handle<i::FixedArray> array = isolate->factory()->NewFixedArray(length);
2158  return ToApiHandle<PrimitiveArray>(array);
2159 }
2160 
2161 int PrimitiveArray::Length() const {
2162  i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
2163  return array->length();
2164 }
2165 
2166 void PrimitiveArray::Set(Isolate* v8_isolate, int index,
2167  Local<Primitive> item) {
2168  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2169  i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
2170  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2171  Utils::ApiCheck(index >= 0 && index < array->length(),
2172  "v8::PrimitiveArray::Set",
2173  "index must be greater than or equal to 0 and less than the "
2174  "array length");
2175  i::Handle<i::Object> i_item = Utils::OpenHandle(*item);
2176  array->set(index, *i_item);
2177 }
2178 
2179 Local<Primitive> PrimitiveArray::Get(Isolate* v8_isolate, int index) {
2180  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2181  i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
2182  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2183  Utils::ApiCheck(index >= 0 && index < array->length(),
2184  "v8::PrimitiveArray::Get",
2185  "index must be greater than or equal to 0 and less than the "
2186  "array length");
2187  i::Handle<i::Object> i_item(array->get(index), isolate);
2188  return ToApiHandle<Primitive>(i_item);
2189 }
2190 
2192  i::Handle<i::Module> self = Utils::OpenHandle(this);
2193  switch (self->status()) {
2194  case i::Module::kUninstantiated:
2195  case i::Module::kPreInstantiating:
2196  return kUninstantiated;
2197  case i::Module::kInstantiating:
2198  return kInstantiating;
2199  case i::Module::kInstantiated:
2200  return kInstantiated;
2201  case i::Module::kEvaluating:
2202  return kEvaluating;
2203  case i::Module::kEvaluated:
2204  return kEvaluated;
2205  case i::Module::kErrored:
2206  return kErrored;
2207  }
2208  UNREACHABLE();
2209 }
2210 
2212  Utils::ApiCheck(GetStatus() == kErrored, "v8::Module::GetException",
2213  "Module status must be kErrored");
2214  i::Handle<i::Module> self = Utils::OpenHandle(this);
2215  i::Isolate* isolate = self->GetIsolate();
2216  return ToApiHandle<Value>(i::handle(self->GetException(), isolate));
2217 }
2218 
2220  i::Handle<i::Module> self = Utils::OpenHandle(this);
2221  return self->info()->module_requests()->length();
2222 }
2223 
2225  CHECK_GE(i, 0);
2226  i::Handle<i::Module> self = Utils::OpenHandle(this);
2227  i::Isolate* isolate = self->GetIsolate();
2228  i::Handle<i::FixedArray> module_requests(self->info()->module_requests(),
2229  isolate);
2230  CHECK_LT(i, module_requests->length());
2231  return ToApiHandle<String>(i::handle(module_requests->get(i), isolate));
2232 }
2233 
2235  CHECK_GE(i, 0);
2236  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2237  i::HandleScope scope(isolate);
2238  i::Handle<i::Module> self = Utils::OpenHandle(this);
2239  i::Handle<i::FixedArray> module_request_positions(
2240  self->info()->module_request_positions(), isolate);
2241  CHECK_LT(i, module_request_positions->length());
2242  int position = i::Smi::ToInt(module_request_positions->get(i));
2243  i::Handle<i::Script> script(self->script(), isolate);
2244  i::Script::PositionInfo info;
2245  i::Script::GetPositionInfo(script, position, &info, i::Script::WITH_OFFSET);
2246  return v8::Location(info.line, info.column);
2247 }
2248 
2250  Utils::ApiCheck(
2251  GetStatus() >= kInstantiated, "v8::Module::GetModuleNamespace",
2252  "v8::Module::GetModuleNamespace must be used on an instantiated module");
2253  i::Handle<i::Module> self = Utils::OpenHandle(this);
2254  i::Handle<i::JSModuleNamespace> module_namespace =
2255  i::Module::GetModuleNamespace(self->GetIsolate(), self);
2256  return ToApiHandle<Value>(module_namespace);
2257 }
2258 
2260  Utils::ApiCheck(
2261  GetStatus() < kEvaluating, "v8::Module::GetUnboundScript",
2262  "v8::Module::GetUnboundScript must be used on an unevaluated module");
2263  i::Handle<i::Module> self = Utils::OpenHandle(this);
2264  return ToApiHandle<UnboundModuleScript>(i::Handle<i::SharedFunctionInfo>(
2265  self->GetSharedFunctionInfo(), self->GetIsolate()));
2266 }
2267 
2268 int Module::GetIdentityHash() const { return Utils::OpenHandle(this)->hash(); }
2269 
2271  Module::ResolveCallback callback) {
2272  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2273  ENTER_V8(isolate, context, Module, InstantiateModule, Nothing<bool>(),
2274  i::HandleScope);
2275  has_pending_exception = !i::Module::Instantiate(
2276  isolate, Utils::OpenHandle(this), context, callback);
2277  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
2278  return Just(true);
2279 }
2280 
2282  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2283  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
2284  ENTER_V8(isolate, context, Module, Evaluate, MaybeLocal<Value>(),
2285  InternalEscapableScope);
2286  i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true);
2287  i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
2288  i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
2289 
2290  i::Handle<i::Module> self = Utils::OpenHandle(this);
2291  // It's an API error to call Evaluate before Instantiate.
2292  CHECK_GE(self->status(), i::Module::kInstantiated);
2293 
2294  Local<Value> result;
2295  has_pending_exception = !ToLocal(i::Module::Evaluate(isolate, self), &result);
2296  RETURN_ON_FAILED_EXECUTION(Value);
2297  RETURN_ESCAPED(result);
2298 }
2299 
2300 namespace {
2301 
2302 i::Compiler::ScriptDetails GetScriptDetails(
2303  i::Isolate* isolate, Local<Value> resource_name,
2304  Local<Integer> resource_line_offset, Local<Integer> resource_column_offset,
2305  Local<Value> source_map_url, Local<PrimitiveArray> host_defined_options) {
2306  i::Compiler::ScriptDetails script_details;
2307  if (!resource_name.IsEmpty()) {
2308  script_details.name_obj = Utils::OpenHandle(*(resource_name));
2309  }
2310  if (!resource_line_offset.IsEmpty()) {
2311  script_details.line_offset =
2312  static_cast<int>(resource_line_offset->Value());
2313  }
2314  if (!resource_column_offset.IsEmpty()) {
2315  script_details.column_offset =
2316  static_cast<int>(resource_column_offset->Value());
2317  }
2318  script_details.host_defined_options = isolate->factory()->empty_fixed_array();
2319  if (!host_defined_options.IsEmpty()) {
2320  script_details.host_defined_options =
2321  Utils::OpenHandle(*(host_defined_options));
2322  }
2323  if (!source_map_url.IsEmpty()) {
2324  script_details.source_map_url = Utils::OpenHandle(*(source_map_url));
2325  }
2326  return script_details;
2327 }
2328 
2329 } // namespace
2330 
2331 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal(
2332  Isolate* v8_isolate, Source* source, CompileOptions options,
2333  NoCacheReason no_cache_reason) {
2334  auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2335  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
2336  ENTER_V8_NO_SCRIPT(isolate, v8_isolate->GetCurrentContext(), ScriptCompiler,
2337  CompileUnbound, MaybeLocal<UnboundScript>(),
2338  InternalEscapableScope);
2339 
2340  i::ScriptData* script_data = nullptr;
2341  if (options == kConsumeCodeCache) {
2342  DCHECK(source->cached_data);
2343  // ScriptData takes care of pointer-aligning the data.
2344  script_data = new i::ScriptData(source->cached_data->data,
2345  source->cached_data->length);
2346  }
2347 
2348  i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
2350  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileScript");
2351  i::Compiler::ScriptDetails script_details = GetScriptDetails(
2352  isolate, source->resource_name, source->resource_line_offset,
2353  source->resource_column_offset, source->source_map_url,
2354  source->host_defined_options);
2355  i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
2356  i::Compiler::GetSharedFunctionInfoForScript(
2357  isolate, str, script_details, source->resource_options, nullptr,
2358  script_data, options, no_cache_reason, i::NOT_NATIVES_CODE);
2359  if (options == kConsumeCodeCache) {
2360  source->cached_data->rejected = script_data->rejected();
2361  }
2362  delete script_data;
2363  has_pending_exception = !maybe_function_info.ToHandle(&result);
2364  RETURN_ON_FAILED_EXECUTION(UnboundScript);
2365  RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
2366 }
2367 
2369  Isolate* v8_isolate, Source* source, CompileOptions options,
2370  NoCacheReason no_cache_reason) {
2371  Utils::ApiCheck(
2372  !source->GetResourceOptions().IsModule(),
2373  "v8::ScriptCompiler::CompileUnboundScript",
2374  "v8::ScriptCompiler::CompileModule must be used to compile modules");
2375  return CompileUnboundInternal(v8_isolate, source, options, no_cache_reason);
2376 }
2377 
2379  Source* source,
2380  CompileOptions options,
2381  NoCacheReason no_cache_reason) {
2382  Utils::ApiCheck(
2383  !source->GetResourceOptions().IsModule(), "v8::ScriptCompiler::Compile",
2384  "v8::ScriptCompiler::CompileModule must be used to compile modules");
2385  auto isolate = context->GetIsolate();
2386  auto maybe =
2387  CompileUnboundInternal(isolate, source, options, no_cache_reason);
2388  Local<UnboundScript> result;
2389  if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
2390  v8::Context::Scope scope(context);
2391  return result->BindToCurrentContext();
2392 }
2393 
2395  Isolate* isolate, Source* source, CompileOptions options,
2396  NoCacheReason no_cache_reason) {
2397  CHECK(options == kNoCompileOptions || options == kConsumeCodeCache);
2398 
2399  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2400 
2401  Utils::ApiCheck(source->GetResourceOptions().IsModule(),
2402  "v8::ScriptCompiler::CompileModule",
2403  "Invalid ScriptOrigin: is_module must be true");
2404  auto maybe =
2405  CompileUnboundInternal(isolate, source, options, no_cache_reason);
2406  Local<UnboundScript> unbound;
2407  if (!maybe.ToLocal(&unbound)) return MaybeLocal<Module>();
2408 
2409  i::Handle<i::SharedFunctionInfo> shared = Utils::OpenHandle(*unbound);
2410  return ToApiHandle<Module>(i_isolate->factory()->NewModule(shared));
2411 }
2412 
2413 
2415  public:
2416  IsIdentifierHelper() : is_identifier_(false), first_char_(true) {}
2417 
2418  bool Check(i::String string) {
2419  i::ConsString cons_string = i::String::VisitFlat(this, string, 0);
2420  if (cons_string.is_null()) return is_identifier_;
2421  // We don't support cons strings here.
2422  return false;
2423  }
2424  void VisitOneByteString(const uint8_t* chars, int length) {
2425  for (int i = 0; i < length; ++i) {
2426  if (first_char_) {
2427  first_char_ = false;
2428  is_identifier_ = i::IsIdentifierStart(chars[0]);
2429  } else {
2430  is_identifier_ &= i::IsIdentifierPart(chars[i]);
2431  }
2432  }
2433  }
2434  void VisitTwoByteString(const uint16_t* chars, int length) {
2435  for (int i = 0; i < length; ++i) {
2436  if (first_char_) {
2437  first_char_ = false;
2438  is_identifier_ = i::IsIdentifierStart(chars[0]);
2439  } else {
2440  is_identifier_ &= i::IsIdentifierPart(chars[i]);
2441  }
2442  }
2443  }
2444 
2445  private:
2446  bool is_identifier_;
2447  bool first_char_;
2448  DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper);
2449 };
2450 
2452  Local<Context> v8_context, Source* source, size_t arguments_count,
2453  Local<String> arguments[], size_t context_extension_count,
2454  Local<Object> context_extensions[], CompileOptions options,
2455  NoCacheReason no_cache_reason) {
2456  PREPARE_FOR_EXECUTION(v8_context, ScriptCompiler, CompileFunctionInContext,
2457  Function);
2458  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
2459 
2460  DCHECK(options == CompileOptions::kConsumeCodeCache ||
2461  options == CompileOptions::kEagerCompile ||
2462  options == CompileOptions::kNoCompileOptions);
2463 
2464  i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
2465 
2466  DCHECK(context->IsNativeContext());
2468  context->empty_function()->shared(), isolate);
2469 
2471  i::Handle<i::FixedArray> arguments_list =
2472  isolate->factory()->NewFixedArray(static_cast<int>(arguments_count));
2473  for (int i = 0; i < static_cast<int>(arguments_count); i++) {
2474  IsIdentifierHelper helper;
2475  i::Handle<i::String> argument = Utils::OpenHandle(*arguments[i]);
2476  if (!helper.Check(*argument)) return Local<Function>();
2477  arguments_list->set(i, *argument);
2478  }
2479 
2480  for (size_t i = 0; i < context_extension_count; ++i) {
2481  i::Handle<i::JSReceiver> extension =
2482  Utils::OpenHandle(*context_extensions[i]);
2483  if (!extension->IsJSObject()) return Local<Function>();
2484  context = isolate->factory()->NewWithContext(
2485  context,
2486  i::ScopeInfo::CreateForWithScope(
2487  isolate,
2488  context->IsNativeContext()
2490  : i::Handle<i::ScopeInfo>(context->scope_info(), isolate)),
2491  extension);
2492  }
2493 
2494  i::Compiler::ScriptDetails script_details = GetScriptDetails(
2495  isolate, source->resource_name, source->resource_line_offset,
2496  source->resource_column_offset, source->source_map_url,
2497  source->host_defined_options);
2498 
2499  i::ScriptData* script_data = nullptr;
2500  if (options == kConsumeCodeCache) {
2501  DCHECK(source->cached_data);
2502  // ScriptData takes care of pointer-aligning the data.
2503  script_data = new i::ScriptData(source->cached_data->data,
2504  source->cached_data->length);
2505  }
2506 
2507  i::Handle<i::JSFunction> result;
2508  has_pending_exception =
2509  !i::Compiler::GetWrappedFunction(
2510  Utils::OpenHandle(*source->source_string), arguments_list, context,
2511  script_details, source->resource_options, script_data, options,
2512  no_cache_reason)
2513  .ToHandle(&result);
2514  if (options == kConsumeCodeCache) {
2515  source->cached_data->rejected = script_data->rejected();
2516  }
2517  delete script_data;
2518  RETURN_ON_FAILED_EXECUTION(Function);
2519  RETURN_ESCAPED(Utils::CallableToLocal(result));
2520 }
2521 
2522 void ScriptCompiler::ScriptStreamingTask::Run() { data_->task->Run(); }
2523 
2525  Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
2526  if (!i::FLAG_script_streaming) {
2527  return nullptr;
2528  }
2529  // We don't support other compile options on streaming background compiles.
2530  // TODO(rmcilroy): remove CompileOptions from the API.
2531  CHECK(options == ScriptCompiler::kNoCompileOptions);
2532  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2533  i::ScriptStreamingData* data = source->impl();
2534  std::unique_ptr<i::BackgroundCompileTask> task =
2535  base::make_unique<i::BackgroundCompileTask>(data, isolate);
2536  data->task = std::move(task);
2537  return new ScriptCompiler::ScriptStreamingTask(data);
2538 }
2539 
2541  StreamedSource* v8_source,
2542  Local<String> full_source_string,
2543  const ScriptOrigin& origin) {
2544  PREPARE_FOR_EXECUTION(context, ScriptCompiler, Compile, Script);
2545  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
2546  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"),
2547  "V8.CompileStreamedScript");
2548 
2549  i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
2550  i::Compiler::ScriptDetails script_details = GetScriptDetails(
2551  isolate, origin.ResourceName(), origin.ResourceLineOffset(),
2552  origin.ResourceColumnOffset(), origin.SourceMapUrl(),
2553  origin.HostDefinedOptions());
2554  i::ScriptStreamingData* data = v8_source->impl();
2555 
2556  i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
2557  i::Compiler::GetSharedFunctionInfoForStreamedScript(
2558  isolate, str, script_details, origin.Options(), data);
2559 
2561  has_pending_exception = !maybe_function_info.ToHandle(&result);
2562  if (has_pending_exception) isolate->ReportPendingMessages();
2563 
2564  RETURN_ON_FAILED_EXECUTION(Script);
2565 
2566  Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
2567  if (generic.IsEmpty()) return Local<Script>();
2568  Local<Script> bound = generic->BindToCurrentContext();
2569  if (bound.IsEmpty()) return Local<Script>();
2570  RETURN_ESCAPED(bound);
2571 }
2572 
2574  return static_cast<uint32_t>(base::hash_combine(
2575  internal::Version::Hash(), internal::FlagList::Hash(),
2576  static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures())));
2577 }
2578 
2580  Local<UnboundScript> unbound_script) {
2583  Utils::OpenHandle(*unbound_script));
2584  DCHECK(shared->is_toplevel());
2585  return i::CodeSerializer::Serialize(shared);
2586 }
2587 
2588 // static
2590  Local<UnboundModuleScript> unbound_module_script) {
2593  Utils::OpenHandle(*unbound_module_script));
2594  DCHECK(shared->is_toplevel());
2595  return i::CodeSerializer::Serialize(shared);
2596 }
2597 
2599  Local<Function> function) {
2600  auto js_function =
2601  i::Handle<i::JSFunction>::cast(Utils::OpenHandle(*function));
2602  i::Handle<i::SharedFunctionInfo> shared(js_function->shared(),
2603  js_function->GetIsolate());
2604  CHECK(shared->is_wrapped());
2605  return i::CodeSerializer::Serialize(shared);
2606 }
2607 
2609  ScriptOrigin* origin) {
2610  if (origin) {
2611  ScriptCompiler::Source script_source(source, *origin);
2612  return ScriptCompiler::Compile(context, &script_source);
2613  }
2614  ScriptCompiler::Source script_source(source);
2615  return ScriptCompiler::Compile(context, &script_source);
2616 }
2617 
2618 
2619 // --- E x c e p t i o n s ---
2620 
2621 v8::TryCatch::TryCatch(v8::Isolate* isolate)
2622  : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
2623  next_(isolate_->try_catch_handler()),
2624  is_verbose_(false),
2625  can_continue_(true),
2626  capture_message_(true),
2627  rethrow_(false),
2628  has_terminated_(false) {
2629  ResetInternal();
2630  // Special handling for simulators which have a separate JS stack.
2631  js_stack_comparable_address_ =
2632  reinterpret_cast<void*>(i::SimulatorStack::RegisterCTryCatch(
2633  isolate_, i::GetCurrentStackPosition()));
2634  isolate_->RegisterTryCatchHandler(this);
2635 }
2636 
2637 
2638 v8::TryCatch::~TryCatch() {
2639  if (rethrow_) {
2640  v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
2641  v8::HandleScope scope(isolate);
2642  v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
2643  if (HasCaught() && capture_message_) {
2644  // If an exception was caught and rethrow_ is indicated, the saved
2645  // message, script, and location need to be restored to Isolate TLS
2646  // for reuse. capture_message_ needs to be disabled so that Throw()
2647  // does not create a new message.
2648  isolate_->thread_local_top()->rethrowing_message_ = true;
2649  isolate_->RestorePendingMessageFromTryCatch(this);
2650  }
2651  isolate_->UnregisterTryCatchHandler(this);
2652  i::SimulatorStack::UnregisterCTryCatch(isolate_);
2653  reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
2654  DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
2655  } else {
2656  if (HasCaught() && isolate_->has_scheduled_exception()) {
2657  // If an exception was caught but is still scheduled because no API call
2658  // promoted it, then it is canceled to prevent it from being propagated.
2659  // Note that this will not cancel termination exceptions.
2660  isolate_->CancelScheduledExceptionFromTryCatch(this);
2661  }
2662  isolate_->UnregisterTryCatchHandler(this);
2663  i::SimulatorStack::UnregisterCTryCatch(isolate_);
2664  }
2665 }
2666 
2667 void* v8::TryCatch::operator new(size_t) { base::OS::Abort(); }
2668 void* v8::TryCatch::operator new[](size_t) { base::OS::Abort(); }
2669 void v8::TryCatch::operator delete(void*, size_t) { base::OS::Abort(); }
2670 void v8::TryCatch::operator delete[](void*, size_t) { base::OS::Abort(); }
2671 
2672 bool v8::TryCatch::HasCaught() const {
2673  return !reinterpret_cast<i::Object*>(exception_)->IsTheHole(isolate_);
2674 }
2675 
2676 
2677 bool v8::TryCatch::CanContinue() const {
2678  return can_continue_;
2679 }
2680 
2681 
2682 bool v8::TryCatch::HasTerminated() const {
2683  return has_terminated_;
2684 }
2685 
2686 
2687 v8::Local<v8::Value> v8::TryCatch::ReThrow() {
2688  if (!HasCaught()) return v8::Local<v8::Value>();
2689  rethrow_ = true;
2690  return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
2691 }
2692 
2693 
2694 v8::Local<Value> v8::TryCatch::Exception() const {
2695  if (HasCaught()) {
2696  // Check for out of memory exception.
2697  i::Object* exception = reinterpret_cast<i::Object*>(exception_);
2698  return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
2699  } else {
2700  return v8::Local<Value>();
2701  }
2702 }
2703 
2704 
2705 MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const {
2706  if (!HasCaught()) return v8::Local<Value>();
2707  i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
2708  if (!raw_obj->IsJSObject()) return v8::Local<Value>();
2709  PREPARE_FOR_EXECUTION(context, TryCatch, StackTrace, Value);
2710  i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
2711  i::Handle<i::String> name = isolate->factory()->stack_string();
2712  Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
2713  has_pending_exception = maybe.IsNothing();
2714  RETURN_ON_FAILED_EXECUTION(Value);
2715  if (!maybe.FromJust()) return v8::Local<Value>();
2716  Local<Value> result;
2717  has_pending_exception =
2718  !ToLocal<Value>(i::JSReceiver::GetProperty(isolate, obj, name), &result);
2719  RETURN_ON_FAILED_EXECUTION(Value);
2720  RETURN_ESCAPED(result);
2721 }
2722 
2723 
2724 v8::Local<v8::Message> v8::TryCatch::Message() const {
2725  i::Object* message = reinterpret_cast<i::Object*>(message_obj_);
2726  DCHECK(message->IsJSMessageObject() || message->IsTheHole(isolate_));
2727  if (HasCaught() && !message->IsTheHole(isolate_)) {
2728  return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
2729  } else {
2730  return v8::Local<v8::Message>();
2731  }
2732 }
2733 
2734 
2735 void v8::TryCatch::Reset() {
2736  if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
2737  // If an exception was caught but is still scheduled because no API call
2738  // promoted it, then it is canceled to prevent it from being propagated.
2739  // Note that this will not cancel termination exceptions.
2740  isolate_->CancelScheduledExceptionFromTryCatch(this);
2741  }
2742  ResetInternal();
2743 }
2744 
2745 
2746 void v8::TryCatch::ResetInternal() {
2747  i::Object* the_hole = i::ReadOnlyRoots(isolate_).the_hole_value();
2748  exception_ = the_hole;
2749  message_obj_ = the_hole;
2750 }
2751 
2752 
2753 void v8::TryCatch::SetVerbose(bool value) {
2754  is_verbose_ = value;
2755 }
2756 
2757 bool v8::TryCatch::IsVerbose() const { return is_verbose_; }
2758 
2759 void v8::TryCatch::SetCaptureMessage(bool value) {
2760  capture_message_ = value;
2761 }
2762 
2763 
2764 // --- M e s s a g e ---
2765 
2766 
2767 Local<String> Message::Get() const {
2768  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2769  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2770  EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2771  i::Handle<i::Object> obj = Utils::OpenHandle(this);
2772  i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
2773  Local<String> result = Utils::ToLocal(raw_result);
2774  return scope.Escape(result);
2775 }
2776 
2777 v8::Isolate* Message::GetIsolate() const {
2778  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2779  return reinterpret_cast<Isolate*>(isolate);
2780 }
2781 
2783  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2784  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2785  auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2786  i::Handle<i::Script> script(message->script(), isolate);
2787  return GetScriptOriginForScript(isolate, script);
2788 }
2789 
2790 
2792  return GetScriptOrigin().ResourceName();
2793 }
2794 
2795 
2797  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2798  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2799  EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2800  auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2801  i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
2802  if (!stackFramesObj->IsFixedArray()) return v8::Local<v8::StackTrace>();
2803  auto stackTrace = i::Handle<i::FixedArray>::cast(stackFramesObj);
2804  return scope.Escape(Utils::StackTraceToLocal(stackTrace));
2805 }
2806 
2807 
2809  auto self = Utils::OpenHandle(this);
2810  i::Isolate* isolate = self->GetIsolate();
2811  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2812  EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
2813  auto msg = i::Handle<i::JSMessageObject>::cast(self);
2814  return Just(msg->GetLineNumber());
2815 }
2816 
2817 
2819  auto self = Utils::OpenHandle(this);
2820  return self->start_position();
2821 }
2822 
2823 
2825  auto self = Utils::OpenHandle(this);
2826  return self->end_position();
2827 }
2828 
2829 int Message::ErrorLevel() const {
2830  auto self = Utils::OpenHandle(this);
2831  return self->error_level();
2832 }
2833 
2835  auto self = Utils::OpenHandle(this);
2836  i::Isolate* isolate = self->GetIsolate();
2837  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2838  EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
2839  auto msg = i::Handle<i::JSMessageObject>::cast(self);
2840  return msg->GetColumnNumber();
2841 }
2842 
2844  return Just(GetStartColumn());
2845 }
2846 
2848  auto self = Utils::OpenHandle(this);
2849  i::Isolate* isolate = self->GetIsolate();
2850  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2851  EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
2852  auto msg = i::Handle<i::JSMessageObject>::cast(self);
2853  const int column_number = msg->GetColumnNumber();
2854  if (column_number == -1) return -1;
2855  const int start = self->start_position();
2856  const int end = self->end_position();
2857  return column_number + (end - start);
2858 }
2859 
2861  return Just(GetEndColumn());
2862 }
2863 
2864 
2866  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2867  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2868  return Utils::OpenHandle(this)
2869  ->script()
2870  ->origin_options()
2871  .IsSharedCrossOrigin();
2872 }
2873 
2874 bool Message::IsOpaque() const {
2875  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2876  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2877  return Utils::OpenHandle(this)->script()->origin_options().IsOpaque();
2878 }
2879 
2880 
2881 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
2882  auto self = Utils::OpenHandle(this);
2883  i::Isolate* isolate = self->GetIsolate();
2884  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2885  EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
2886  auto msg = i::Handle<i::JSMessageObject>::cast(self);
2887  RETURN_ESCAPED(Utils::ToLocal(msg->GetSourceLine()));
2888 }
2889 
2890 
2891 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
2892  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2893  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
2894  i_isolate->PrintCurrentStackTrace(out);
2895 }
2896 
2897 
2898 // --- S t a c k T r a c e ---
2899 
2901  uint32_t index) const {
2902  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2903  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
2904  EscapableHandleScope scope(v8_isolate);
2905  auto obj = handle(Utils::OpenHandle(this)->get(index), isolate);
2906  auto info = i::Handle<i::StackFrameInfo>::cast(obj);
2907  return scope.Escape(Utils::StackFrameToLocal(info));
2908 }
2909 
2911  return Utils::OpenHandle(this)->length();
2912 }
2913 
2914 
2916  Isolate* isolate,
2917  int frame_limit,
2918  StackTraceOptions options) {
2919  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2920  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
2921  i::Handle<i::FixedArray> stackTrace =
2922  i_isolate->CaptureCurrentStackTrace(frame_limit, options);
2923  return Utils::StackTraceToLocal(stackTrace);
2924 }
2925 
2926 
2927 // --- S t a c k F r a m e ---
2928 
2930  int v = Utils::OpenHandle(this)->line_number();
2931  return v ? v : Message::kNoLineNumberInfo;
2932 }
2933 
2934 
2936  int v = Utils::OpenHandle(this)->column_number();
2937  return v ? v : Message::kNoLineNumberInfo;
2938 }
2939 
2940 
2942  int v = Utils::OpenHandle(this)->script_id();
2943  return v ? v : Message::kNoScriptIdInfo;
2944 }
2945 
2947  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2948  EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2949  i::Handle<i::StackFrameInfo> self = Utils::OpenHandle(this);
2950  i::Handle<i::Object> obj(self->script_name(), isolate);
2951  return obj->IsString()
2952  ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2953  : Local<String>();
2954 }
2955 
2956 
2958  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2959  EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2960  i::Handle<i::StackFrameInfo> self = Utils::OpenHandle(this);
2961  i::Handle<i::Object> obj(self->script_name_or_source_url(), isolate);
2962  return obj->IsString()
2963  ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2964  : Local<String>();
2965 }
2966 
2967 
2969  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2970  EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2971  i::Handle<i::StackFrameInfo> self = Utils::OpenHandle(this);
2972  i::Handle<i::Object> obj(self->function_name(), isolate);
2973  return obj->IsString()
2974  ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2975  : Local<String>();
2976 }
2977 
2978 bool StackFrame::IsEval() const { return Utils::OpenHandle(this)->is_eval(); }
2979 
2981  return Utils::OpenHandle(this)->is_constructor();
2982 }
2983 
2984 bool StackFrame::IsWasm() const { return Utils::OpenHandle(this)->is_wasm(); }
2985 
2986 
2987 // --- J S O N ---
2988 
2989 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) {
2990  PREPARE_FOR_EXECUTION(v8_isolate->GetCurrentContext(), JSON, Parse, Value);
2991  i::Handle<i::String> string = Utils::OpenHandle(*json_string);
2992  i::Handle<i::String> source = i::String::Flatten(isolate, string);
2993  i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2994  auto maybe = source->IsSeqOneByteString()
2995  ? i::JsonParser<true>::Parse(isolate, source, undefined)
2996  : i::JsonParser<false>::Parse(isolate, source, undefined);
2997  Local<Value> result;
2998  has_pending_exception = !ToLocal<Value>(maybe, &result);
2999  RETURN_ON_FAILED_EXECUTION(Value);
3000  RETURN_ESCAPED(result);
3001 }
3002 
3003 MaybeLocal<Value> JSON::Parse(Local<Context> context,
3004  Local<String> json_string) {
3005  PREPARE_FOR_EXECUTION(context, JSON, Parse, Value);
3006  i::Handle<i::String> string = Utils::OpenHandle(*json_string);
3007  i::Handle<i::String> source = i::String::Flatten(isolate, string);
3008  i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
3009  auto maybe = source->IsSeqOneByteString()
3010  ? i::JsonParser<true>::Parse(isolate, source, undefined)
3011  : i::JsonParser<false>::Parse(isolate, source, undefined);
3012  Local<Value> result;
3013  has_pending_exception = !ToLocal<Value>(maybe, &result);
3014  RETURN_ON_FAILED_EXECUTION(Value);
3015  RETURN_ESCAPED(result);
3016 }
3017 
3019  Local<Value> json_object,
3020  Local<String> gap) {
3021  PREPARE_FOR_EXECUTION(context, JSON, Stringify, String);
3022  i::Handle<i::Object> object = Utils::OpenHandle(*json_object);
3023  i::Handle<i::Object> replacer = isolate->factory()->undefined_value();
3024  i::Handle<i::String> gap_string = gap.IsEmpty()
3025  ? isolate->factory()->empty_string()
3026  : Utils::OpenHandle(*gap);
3027  i::Handle<i::Object> maybe;
3028  has_pending_exception =
3029  !i::JsonStringify(isolate, object, replacer, gap_string).ToHandle(&maybe);
3030  RETURN_ON_FAILED_EXECUTION(String);
3031  Local<String> result;
3032  has_pending_exception =
3033  !ToLocal<String>(i::Object::ToString(isolate, maybe), &result);
3034  RETURN_ON_FAILED_EXECUTION(String);
3035  RETURN_ESCAPED(result);
3036 }
3037 
3038 // --- V a l u e S e r i a l i z a t i o n ---
3039 
3041  Local<Object> object) {
3042  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3043  isolate->ScheduleThrow(*isolate->factory()->NewError(
3044  isolate->error_function(), i::MessageTemplate::kDataCloneError,
3045  Utils::OpenHandle(*object)));
3046  return Nothing<bool>();
3047 }
3048 
3050  Isolate* v8_isolate, Local<SharedArrayBuffer> shared_array_buffer) {
3051  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3052  isolate->ScheduleThrow(*isolate->factory()->NewError(
3053  isolate->error_function(), i::MessageTemplate::kDataCloneError,
3054  Utils::OpenHandle(*shared_array_buffer)));
3055  return Nothing<uint32_t>();
3056 }
3057 
3058 Maybe<uint32_t> ValueSerializer::Delegate::GetWasmModuleTransferId(
3059  Isolate* v8_isolate, Local<WasmCompiledModule> module) {
3060  return Nothing<uint32_t>();
3061 }
3062 
3064  size_t size,
3065  size_t* actual_size) {
3066  *actual_size = size;
3067  return realloc(old_buffer, size);
3068 }
3069 
3071  return free(buffer);
3072 }
3073 
3075  explicit PrivateData(i::Isolate* i, ValueSerializer::Delegate* delegate)
3076  : isolate(i), serializer(i, delegate) {}
3077  i::Isolate* isolate;
3078  i::ValueSerializer serializer;
3079 };
3080 
3081 ValueSerializer::ValueSerializer(Isolate* isolate)
3082  : ValueSerializer(isolate, nullptr) {}
3083 
3084 ValueSerializer::ValueSerializer(Isolate* isolate, Delegate* delegate)
3085  : private_(
3086  new PrivateData(reinterpret_cast<i::Isolate*>(isolate), delegate)) {}
3087 
3088 ValueSerializer::~ValueSerializer() { delete private_; }
3089 
3090 void ValueSerializer::WriteHeader() { private_->serializer.WriteHeader(); }
3091 
3093  private_->serializer.SetTreatArrayBufferViewsAsHostObjects(mode);
3094 }
3095 
3097  Local<Value> value) {
3098  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3099  ENTER_V8(isolate, context, ValueSerializer, WriteValue, Nothing<bool>(),
3100  i::HandleScope);
3101  i::Handle<i::Object> object = Utils::OpenHandle(*value);
3102  Maybe<bool> result = private_->serializer.WriteObject(object);
3103  has_pending_exception = result.IsNothing();
3104  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3105  return result;
3106 }
3107 
3108 std::vector<uint8_t> ValueSerializer::ReleaseBuffer() {
3109  return private_->serializer.ReleaseBuffer();
3110 }
3111 
3112 std::pair<uint8_t*, size_t> ValueSerializer::Release() {
3113  return private_->serializer.Release();
3114 }
3115 
3117  Local<ArrayBuffer> array_buffer) {
3118  private_->serializer.TransferArrayBuffer(transfer_id,
3119  Utils::OpenHandle(*array_buffer));
3120 }
3121 
3122 void ValueSerializer::TransferSharedArrayBuffer(
3123  uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) {
3124  private_->serializer.TransferArrayBuffer(
3125  transfer_id, Utils::OpenHandle(*shared_array_buffer));
3126 }
3127 
3129  private_->serializer.WriteUint32(value);
3130 }
3131 
3132 void ValueSerializer::WriteUint64(uint64_t value) {
3133  private_->serializer.WriteUint64(value);
3134 }
3135 
3136 void ValueSerializer::WriteDouble(double value) {
3137  private_->serializer.WriteDouble(value);
3138 }
3139 
3140 void ValueSerializer::WriteRawBytes(const void* source, size_t length) {
3141  private_->serializer.WriteRawBytes(source, length);
3142 }
3143 
3145  Isolate* v8_isolate) {
3146  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3147  isolate->ScheduleThrow(*isolate->factory()->NewError(
3148  isolate->error_function(),
3149  i::MessageTemplate::kDataCloneDeserializationError));
3150  return MaybeLocal<Object>();
3151 }
3152 
3154  Isolate* v8_isolate, uint32_t id) {
3155  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3156  isolate->ScheduleThrow(*isolate->factory()->NewError(
3157  isolate->error_function(),
3158  i::MessageTemplate::kDataCloneDeserializationError));
3160 }
3161 
3164  uint32_t id) {
3165  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3166  isolate->ScheduleThrow(*isolate->factory()->NewError(
3167  isolate->error_function(),
3168  i::MessageTemplate::kDataCloneDeserializationError));
3170 }
3171 
3174  : isolate(i), deserializer(i, data, delegate) {}
3175  i::Isolate* isolate;
3176  i::ValueDeserializer deserializer;
3177  bool has_aborted = false;
3178  bool supports_legacy_wire_format = false;
3179 };
3180 
3181 ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data,
3182  size_t size)
3183  : ValueDeserializer(isolate, data, size, nullptr) {}
3184 
3185 ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data,
3186  size_t size, Delegate* delegate) {
3187  if (base::IsValueInRangeForNumericType<int>(size)) {
3188  private_ = new PrivateData(
3189  reinterpret_cast<i::Isolate*>(isolate),
3190  i::Vector<const uint8_t>(data, static_cast<int>(size)), delegate);
3191  } else {
3192  private_ = new PrivateData(reinterpret_cast<i::Isolate*>(isolate),
3193  i::Vector<const uint8_t>(nullptr, 0), nullptr);
3194  private_->has_aborted = true;
3195  }
3196 }
3197 
3198 ValueDeserializer::~ValueDeserializer() { delete private_; }
3199 
3201  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3202  ENTER_V8_NO_SCRIPT(isolate, context, ValueDeserializer, ReadHeader,
3203  Nothing<bool>(), i::HandleScope);
3204 
3205  // We could have aborted during the constructor.
3206  // If so, ReadHeader is where we report it.
3207  if (private_->has_aborted) {
3208  isolate->Throw(*isolate->factory()->NewError(
3209  i::MessageTemplate::kDataCloneDeserializationError));
3210  has_pending_exception = true;
3211  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3212  }
3213 
3214  bool read_header = false;
3215  has_pending_exception = !private_->deserializer.ReadHeader().To(&read_header);
3216  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3217  DCHECK(read_header);
3218 
3219  static const uint32_t kMinimumNonLegacyVersion = 13;
3220  if (GetWireFormatVersion() < kMinimumNonLegacyVersion &&
3221  !private_->supports_legacy_wire_format) {
3222  isolate->Throw(*isolate->factory()->NewError(
3223  i::MessageTemplate::kDataCloneDeserializationVersionError));
3224  has_pending_exception = true;
3225  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3226  }
3227 
3228  return Just(true);
3229 }
3230 
3232  bool supports_legacy_wire_format) {
3233  private_->supports_legacy_wire_format = supports_legacy_wire_format;
3234 }
3235 
3236 void ValueDeserializer::SetExpectInlineWasm(bool expect_inline_wasm) {
3237  private_->deserializer.set_expect_inline_wasm(expect_inline_wasm);
3238 }
3239 
3241  CHECK(!private_->has_aborted);
3242  return private_->deserializer.GetWireFormatVersion();
3243 }
3244 
3246  CHECK(!private_->has_aborted);
3247  PREPARE_FOR_EXECUTION(context, ValueDeserializer, ReadValue, Value);
3249  if (GetWireFormatVersion() > 0) {
3250  result = private_->deserializer.ReadObject();
3251  } else {
3252  result =
3253  private_->deserializer.ReadObjectUsingEntireBufferForLegacyFormat();
3254  }
3255  Local<Value> value;
3256  has_pending_exception = !ToLocal(result, &value);
3257  RETURN_ON_FAILED_EXECUTION(Value);
3258  RETURN_ESCAPED(value);
3259 }
3260 
3262  Local<ArrayBuffer> array_buffer) {
3263  CHECK(!private_->has_aborted);
3264  private_->deserializer.TransferArrayBuffer(transfer_id,
3265  Utils::OpenHandle(*array_buffer));
3266 }
3267 
3269  uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) {
3270  CHECK(!private_->has_aborted);
3271  private_->deserializer.TransferArrayBuffer(
3272  transfer_id, Utils::OpenHandle(*shared_array_buffer));
3273 }
3274 
3276  return private_->deserializer.ReadUint32(value);
3277 }
3278 
3279 bool ValueDeserializer::ReadUint64(uint64_t* value) {
3280  return private_->deserializer.ReadUint64(value);
3281 }
3282 
3283 bool ValueDeserializer::ReadDouble(double* value) {
3284  return private_->deserializer.ReadDouble(value);
3285 }
3286 
3287 bool ValueDeserializer::ReadRawBytes(size_t length, const void** data) {
3288  return private_->deserializer.ReadRawBytes(length, data);
3289 }
3290 
3291 // --- D a t a ---
3292 
3293 bool Value::FullIsUndefined() const {
3294  i::Handle<i::Object> object = Utils::OpenHandle(this);
3295  bool result = object->IsUndefined();
3296  DCHECK_EQ(result, QuickIsUndefined());
3297  return result;
3298 }
3299 
3300 
3301 bool Value::FullIsNull() const {
3302  i::Handle<i::Object> object = Utils::OpenHandle(this);
3303  bool result = object->IsNull();
3304  DCHECK_EQ(result, QuickIsNull());
3305  return result;
3306 }
3307 
3308 
3309 bool Value::IsTrue() const {
3310  i::Handle<i::Object> object = Utils::OpenHandle(this);
3311  if (object->IsSmi()) return false;
3312  return object->IsTrue();
3313 }
3314 
3315 
3316 bool Value::IsFalse() const {
3317  i::Handle<i::Object> object = Utils::OpenHandle(this);
3318  if (object->IsSmi()) return false;
3319  return object->IsFalse();
3320 }
3321 
3322 
3323 bool Value::IsFunction() const { return Utils::OpenHandle(this)->IsCallable(); }
3324 
3325 
3326 bool Value::IsName() const {
3327  return Utils::OpenHandle(this)->IsName();
3328 }
3329 
3330 
3331 bool Value::FullIsString() const {
3332  bool result = Utils::OpenHandle(this)->IsString();
3333  DCHECK_EQ(result, QuickIsString());
3334  return result;
3335 }
3336 
3337 
3338 bool Value::IsSymbol() const {
3339  return Utils::OpenHandle(this)->IsSymbol();
3340 }
3341 
3342 
3343 bool Value::IsArray() const {
3344  return Utils::OpenHandle(this)->IsJSArray();
3345 }
3346 
3347 
3348 bool Value::IsArrayBuffer() const {
3349  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3350  return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
3351 }
3352 
3353 
3355  return Utils::OpenHandle(this)->IsJSArrayBufferView();
3356 }
3357 
3358 
3359 bool Value::IsTypedArray() const {
3360  return Utils::OpenHandle(this)->IsJSTypedArray();
3361 }
3362 
3363 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype) \
3364  bool Value::Is##Type##Array() const { \
3365  i::Handle<i::Object> obj = Utils::OpenHandle(this); \
3366  return obj->IsJSTypedArray() && \
3367  i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
3368  }
3369 
3370 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
3371 
3372 #undef VALUE_IS_TYPED_ARRAY
3373 
3374 
3375 bool Value::IsDataView() const {
3376  return Utils::OpenHandle(this)->IsJSDataView();
3377 }
3378 
3379 
3381  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3382  return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
3383 }
3384 
3385 
3386 bool Value::IsObject() const { return Utils::OpenHandle(this)->IsJSReceiver(); }
3387 
3388 
3389 bool Value::IsNumber() const {
3390  return Utils::OpenHandle(this)->IsNumber();
3391 }
3392 
3393 bool Value::IsBigInt() const { return Utils::OpenHandle(this)->IsBigInt(); }
3394 
3395 bool Value::IsProxy() const { return Utils::OpenHandle(this)->IsJSProxy(); }
3396 
3397 #define VALUE_IS_SPECIFIC_TYPE(Type, Check) \
3398  bool Value::Is##Type() const { \
3399  i::Handle<i::Object> obj = Utils::OpenHandle(this); \
3400  return obj->Is##Check(); \
3401  }
3402 
3403 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, JSArgumentsObject)
3404 VALUE_IS_SPECIFIC_TYPE(BigIntObject, BigIntWrapper)
3405 VALUE_IS_SPECIFIC_TYPE(BooleanObject, BooleanWrapper)
3406 VALUE_IS_SPECIFIC_TYPE(NumberObject, NumberWrapper)
3407 VALUE_IS_SPECIFIC_TYPE(StringObject, StringWrapper)
3408 VALUE_IS_SPECIFIC_TYPE(SymbolObject, SymbolWrapper)
3409 VALUE_IS_SPECIFIC_TYPE(Date, JSDate)
3410 VALUE_IS_SPECIFIC_TYPE(Map, JSMap)
3411 VALUE_IS_SPECIFIC_TYPE(Set, JSSet)
3412 VALUE_IS_SPECIFIC_TYPE(WeakMap, JSWeakMap)
3413 VALUE_IS_SPECIFIC_TYPE(WeakSet, JSWeakSet)
3414 VALUE_IS_SPECIFIC_TYPE(WebAssemblyCompiledModule, WasmModuleObject)
3415 
3416 #undef VALUE_IS_SPECIFIC_TYPE
3417 
3418 
3419 bool Value::IsBoolean() const {
3420  return Utils::OpenHandle(this)->IsBoolean();
3421 }
3422 
3423 bool Value::IsExternal() const {
3424  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3425  if (!obj->IsHeapObject()) return false;
3427  // Check the instance type is JS_OBJECT (instance type of Externals) before
3428  // attempting to get the Isolate since that guarantees the object is writable
3429  // and GetIsolate will work.
3430  if (heap_obj->map()->instance_type() != i::JS_OBJECT_TYPE) return false;
3431  i::Isolate* isolate = i::JSObject::cast(*heap_obj)->GetIsolate();
3432  return heap_obj->IsExternal(isolate);
3433 }
3434 
3435 
3436 bool Value::IsInt32() const {
3437  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3438  if (obj->IsSmi()) return true;
3439  if (obj->IsNumber()) {
3440  return i::IsInt32Double(obj->Number());
3441  }
3442  return false;
3443 }
3444 
3445 
3446 bool Value::IsUint32() const {
3447  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3448  if (obj->IsSmi()) return i::Smi::ToInt(*obj) >= 0;
3449  if (obj->IsNumber()) {
3450  double value = obj->Number();
3451  return !i::IsMinusZero(value) &&
3452  value >= 0 &&
3453  value <= i::kMaxUInt32 &&
3454  value == i::FastUI2D(i::FastD2UI(value));
3455  }
3456  return false;
3457 }
3458 
3459 
3460 bool Value::IsNativeError() const {
3461  return Utils::OpenHandle(this)->IsJSError();
3462 }
3463 
3464 
3465 bool Value::IsRegExp() const {
3466  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3467  return obj->IsJSRegExp();
3468 }
3469 
3471  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3472  if (!obj->IsJSFunction()) return false;
3474  return i::IsAsyncFunction(func->shared()->kind());
3475 }
3476 
3478  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3479  if (!obj->IsJSFunction()) return false;
3481  return i::IsGeneratorFunction(func->shared()->kind());
3482 }
3483 
3484 
3486  return Utils::OpenHandle(this)->IsJSGeneratorObject();
3487 }
3488 
3489 
3490 bool Value::IsMapIterator() const {
3491  return Utils::OpenHandle(this)->IsJSMapIterator();
3492 }
3493 
3494 
3495 bool Value::IsSetIterator() const {
3496  return Utils::OpenHandle(this)->IsJSSetIterator();
3497 }
3498 
3499 bool Value::IsPromise() const { return Utils::OpenHandle(this)->IsJSPromise(); }
3500 
3502  return Utils::OpenHandle(this)->IsJSModuleNamespace();
3503 }
3504 
3505 MaybeLocal<String> Value::ToString(Local<Context> context) const {
3506  auto obj = Utils::OpenHandle(this);
3507  if (obj->IsString()) return ToApiHandle<String>(obj);
3508  PREPARE_FOR_EXECUTION(context, Object, ToString, String);
3509  Local<String> result;
3510  has_pending_exception =
3511  !ToLocal<String>(i::Object::ToString(isolate, obj), &result);
3512  RETURN_ON_FAILED_EXECUTION(String);
3513  RETURN_ESCAPED(result);
3514 }
3515 
3516 
3517 Local<String> Value::ToString(Isolate* isolate) const {
3518  RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
3519 }
3520 
3521 
3522 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
3523  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3524  if (obj->IsString()) return ToApiHandle<String>(obj);
3525  PREPARE_FOR_EXECUTION(context, Object, ToDetailString, String);
3526  Local<String> result =
3527  Utils::ToLocal(i::Object::NoSideEffectsToString(isolate, obj));
3528  RETURN_ON_FAILED_EXECUTION(String);
3529  RETURN_ESCAPED(result);
3530 }
3531 
3532 
3533 MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
3534  auto obj = Utils::OpenHandle(this);
3535  if (obj->IsJSReceiver()) return ToApiHandle<Object>(obj);
3536  PREPARE_FOR_EXECUTION(context, Object, ToObject, Object);
3537  Local<Object> result;
3538  has_pending_exception =
3539  !ToLocal<Object>(i::Object::ToObject(isolate, obj), &result);
3540  RETURN_ON_FAILED_EXECUTION(Object);
3541  RETURN_ESCAPED(result);
3542 }
3543 
3544 
3545 Local<v8::Object> Value::ToObject(Isolate* isolate) const {
3546  RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
3547 }
3548 
3549 MaybeLocal<BigInt> Value::ToBigInt(Local<Context> context) const {
3550  i::Handle<i::Object> obj = Utils::OpenHandle(this);
3551  if (obj->IsBigInt()) return ToApiHandle<BigInt>(obj);
3552  PREPARE_FOR_EXECUTION(context, Object, ToBigInt, BigInt);
3553  Local<BigInt> result;
3554  has_pending_exception =
3555  !ToLocal<BigInt>(i::BigInt::FromObject(isolate, obj), &result);
3556  RETURN_ON_FAILED_EXECUTION(BigInt);
3557  RETURN_ESCAPED(result);
3558 }
3559 
3560 bool Value::BooleanValue(Isolate* v8_isolate) const {
3561  return Utils::OpenHandle(this)->BooleanValue(
3562  reinterpret_cast<i::Isolate*>(v8_isolate));
3563 }
3564 
3565 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
3566  return ToBoolean(context->GetIsolate());
3567 }
3568 
3569 
3570 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
3571  auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3572  return ToApiHandle<Boolean>(
3573  isolate->factory()->ToBoolean(BooleanValue(v8_isolate)));
3574 }
3575 
3576 
3577 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
3578  auto obj = Utils::OpenHandle(this);
3579  if (obj->IsNumber()) return ToApiHandle<Number>(obj);
3580  PREPARE_FOR_EXECUTION(context, Object, ToNumber, Number);
3581  Local<Number> result;
3582  has_pending_exception =
3583  !ToLocal<Number>(i::Object::ToNumber(isolate, obj), &result);
3584  RETURN_ON_FAILED_EXECUTION(Number);
3585  RETURN_ESCAPED(result);
3586 }
3587 
3588 
3589 Local<Number> Value::ToNumber(Isolate* isolate) const {
3590  RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
3591 }
3592 
3593 
3594 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
3595  auto obj = Utils::OpenHandle(this);
3596  if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
3597  PREPARE_FOR_EXECUTION(context, Object, ToInteger, Integer);
3598  Local<Integer> result;
3599  has_pending_exception =
3600  !ToLocal<Integer>(i::Object::ToInteger(isolate, obj), &result);
3601  RETURN_ON_FAILED_EXECUTION(Integer);
3602  RETURN_ESCAPED(result);
3603 }
3604 
3605 
3606 Local<Integer> Value::ToInteger(Isolate* isolate) const {
3607  RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
3608 }
3609 
3610 
3611 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
3612  auto obj = Utils::OpenHandle(this);
3613  if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
3614  Local<Int32> result;
3615  PREPARE_FOR_EXECUTION(context, Object, ToInt32, Int32);
3616  has_pending_exception =
3617  !ToLocal<Int32>(i::Object::ToInt32(isolate, obj), &result);
3618  RETURN_ON_FAILED_EXECUTION(Int32);
3619  RETURN_ESCAPED(result);
3620 }
3621 
3622 
3623 Local<Int32> Value::ToInt32(Isolate* isolate) const {
3624  RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
3625 }
3626 
3627 
3628 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
3629  auto obj = Utils::OpenHandle(this);
3630  if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
3631  Local<Uint32> result;
3632  PREPARE_FOR_EXECUTION(context, Object, ToUint32, Uint32);
3633  has_pending_exception =
3634  !ToLocal<Uint32>(i::Object::ToUint32(isolate, obj), &result);
3635  RETURN_ON_FAILED_EXECUTION(Uint32);
3636  RETURN_ESCAPED(result);
3637 }
3638 
3639 
3640 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
3641  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
3642  Utils::ApiCheck(isolate != nullptr && !isolate->IsDead(),
3643  "v8::internal::Internals::CheckInitialized",
3644  "Isolate is not initialized or V8 has died");
3645 }
3646 
3647 
3648 void External::CheckCast(v8::Value* that) {
3649  Utils::ApiCheck(that->IsExternal(), "v8::External::Cast",
3650  "Could not convert to external");
3651 }
3652 
3653 
3654 void v8::Object::CheckCast(Value* that) {
3655  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3656  Utils::ApiCheck(obj->IsJSReceiver(), "v8::Object::Cast",
3657  "Could not convert to object");
3658 }
3659 
3660 
3661 void v8::Function::CheckCast(Value* that) {
3662  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3663  Utils::ApiCheck(obj->IsCallable(), "v8::Function::Cast",
3664  "Could not convert to function");
3665 }
3666 
3667 
3668 void v8::Boolean::CheckCast(v8::Value* that) {
3669  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3670  Utils::ApiCheck(obj->IsBoolean(), "v8::Boolean::Cast",
3671  "Could not convert to boolean");
3672 }
3673 
3674 
3675 void v8::Name::CheckCast(v8::Value* that) {
3676  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3677  Utils::ApiCheck(obj->IsName(), "v8::Name::Cast", "Could not convert to name");
3678 }
3679 
3680 
3681 void v8::String::CheckCast(v8::Value* that) {
3682  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3683  Utils::ApiCheck(obj->IsString(), "v8::String::Cast",
3684  "Could not convert to string");
3685 }
3686 
3687 
3688 void v8::Symbol::CheckCast(v8::Value* that) {
3689  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3690  Utils::ApiCheck(obj->IsSymbol(), "v8::Symbol::Cast",
3691  "Could not convert to symbol");
3692 }
3693 
3694 
3695 void v8::Private::CheckCast(v8::Data* that) {
3696  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3697  Utils::ApiCheck(obj->IsSymbol() &&
3698  i::Handle<i::Symbol>::cast(obj)->is_private(),
3699  "v8::Private::Cast",
3700  "Could not convert to private");
3701 }
3702 
3703 
3704 void v8::Number::CheckCast(v8::Value* that) {
3705  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3706  Utils::ApiCheck(obj->IsNumber(),
3707  "v8::Number::Cast()",
3708  "Could not convert to number");
3709 }
3710 
3711 
3712 void v8::Integer::CheckCast(v8::Value* that) {
3713  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3714  Utils::ApiCheck(obj->IsNumber(), "v8::Integer::Cast",
3715  "Could not convert to number");
3716 }
3717 
3718 
3719 void v8::Int32::CheckCast(v8::Value* that) {
3720  Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast",
3721  "Could not convert to 32-bit signed integer");
3722 }
3723 
3724 
3725 void v8::Uint32::CheckCast(v8::Value* that) {
3726  Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast",
3727  "Could not convert to 32-bit unsigned integer");
3728 }
3729 
3730 void v8::BigInt::CheckCast(v8::Value* that) {
3731  Utils::ApiCheck(that->IsBigInt(), "v8::BigInt::Cast",
3732  "Could not convert to BigInt");
3733 }
3734 
3735 void v8::Array::CheckCast(Value* that) {
3736  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3737  Utils::ApiCheck(obj->IsJSArray(), "v8::Array::Cast",
3738  "Could not convert to array");
3739 }
3740 
3741 
3742 void v8::Map::CheckCast(Value* that) {
3743  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3744  Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast", "Could not convert to Map");
3745 }
3746 
3747 
3748 void v8::Set::CheckCast(Value* that) {
3749  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3750  Utils::ApiCheck(obj->IsJSSet(), "v8_Set_Cast", "Could not convert to Set");
3751 }
3752 
3753 
3754 void v8::Promise::CheckCast(Value* that) {
3755  Utils::ApiCheck(that->IsPromise(), "v8::Promise::Cast",
3756  "Could not convert to promise");
3757 }
3758 
3759 
3760 void v8::Promise::Resolver::CheckCast(Value* that) {
3761  Utils::ApiCheck(that->IsPromise(), "v8::Promise::Resolver::Cast",
3762  "Could not convert to promise resolver");
3763 }
3764 
3765 
3766 void v8::Proxy::CheckCast(Value* that) {
3767  Utils::ApiCheck(that->IsProxy(), "v8::Proxy::Cast",
3768  "Could not convert to proxy");
3769 }
3770 
3771 void v8::WasmCompiledModule::CheckCast(Value* that) {
3772  Utils::ApiCheck(that->IsWebAssemblyCompiledModule(),
3773  "v8::WasmCompiledModule::Cast",
3774  "Could not convert to wasm compiled module");
3775 }
3776 
3777 void v8::ArrayBuffer::CheckCast(Value* that) {
3778  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3779  Utils::ApiCheck(
3780  obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
3781  "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
3782 }
3783 
3784 
3785 void v8::ArrayBufferView::CheckCast(Value* that) {
3786  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3787  Utils::ApiCheck(obj->IsJSArrayBufferView(),
3788  "v8::ArrayBufferView::Cast()",
3789  "Could not convert to ArrayBufferView");
3790 }
3791 
3792 
3793 void v8::TypedArray::CheckCast(Value* that) {
3794  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3795  Utils::ApiCheck(obj->IsJSTypedArray(),
3796  "v8::TypedArray::Cast()",
3797  "Could not convert to TypedArray");
3798 }
3799 
3800 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype) \
3801  void v8::Type##Array::CheckCast(Value* that) { \
3802  i::Handle<i::Object> obj = Utils::OpenHandle(that); \
3803  Utils::ApiCheck( \
3804  obj->IsJSTypedArray() && \
3805  i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
3806  "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
3807  }
3808 
3809 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
3810 
3811 #undef CHECK_TYPED_ARRAY_CAST
3812 
3813 
3814 void v8::DataView::CheckCast(Value* that) {
3815  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3816  Utils::ApiCheck(obj->IsJSDataView(),
3817  "v8::DataView::Cast()",
3818  "Could not convert to DataView");
3819 }
3820 
3821 
3822 void v8::SharedArrayBuffer::CheckCast(Value* that) {
3823  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3824  Utils::ApiCheck(
3825  obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
3826  "v8::SharedArrayBuffer::Cast()",
3827  "Could not convert to SharedArrayBuffer");
3828 }
3829 
3830 
3831 void v8::Date::CheckCast(v8::Value* that) {
3832  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3833  Utils::ApiCheck(obj->IsJSDate(), "v8::Date::Cast()",
3834  "Could not convert to date");
3835 }
3836 
3837 
3838 void v8::StringObject::CheckCast(v8::Value* that) {
3839  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3840  Utils::ApiCheck(obj->IsStringWrapper(), "v8::StringObject::Cast()",
3841  "Could not convert to StringObject");
3842 }
3843 
3844 
3845 void v8::SymbolObject::CheckCast(v8::Value* that) {
3846  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3847  Utils::ApiCheck(obj->IsSymbolWrapper(), "v8::SymbolObject::Cast()",
3848  "Could not convert to SymbolObject");
3849 }
3850 
3851 
3852 void v8::NumberObject::CheckCast(v8::Value* that) {
3853  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3854  Utils::ApiCheck(obj->IsNumberWrapper(), "v8::NumberObject::Cast()",
3855  "Could not convert to NumberObject");
3856 }
3857 
3858 void v8::BigIntObject::CheckCast(v8::Value* that) {
3859  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3860  Utils::ApiCheck(obj->IsBigIntWrapper(), "v8::BigIntObject::Cast()",
3861  "Could not convert to BigIntObject");
3862 }
3863 
3864 void v8::BooleanObject::CheckCast(v8::Value* that) {
3865  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3866  Utils::ApiCheck(obj->IsBooleanWrapper(), "v8::BooleanObject::Cast()",
3867  "Could not convert to BooleanObject");
3868 }
3869 
3870 
3871 void v8::RegExp::CheckCast(v8::Value* that) {
3872  i::Handle<i::Object> obj = Utils::OpenHandle(that);
3873  Utils::ApiCheck(obj->IsJSRegExp(),
3874  "v8::RegExp::Cast()",
3875  "Could not convert to regular expression");
3876 }
3877 
3878 
3879 Maybe<bool> Value::BooleanValue(Local<Context> context) const {
3880  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3881  return Just(Utils::OpenHandle(this)->BooleanValue(isolate));
3882 }
3883 
3884 
3885 Maybe<double> Value::NumberValue(Local<Context> context) const {
3886  auto obj = Utils::OpenHandle(this);
3887  if (obj->IsNumber()) return Just(obj->Number());
3888  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3889  ENTER_V8(isolate, context, Value, NumberValue, Nothing<double>(),
3890  i::HandleScope);
3892  has_pending_exception = !i::Object::ToNumber(isolate, obj).ToHandle(&num);
3893  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
3894  return Just(num->Number());
3895 }
3896 
3897 
3898 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
3899  auto obj = Utils::OpenHandle(this);
3900  if (obj->IsNumber()) {
3901  return Just(NumberToInt64(*obj));
3902  }
3903  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3904  ENTER_V8(isolate, context, Value, IntegerValue, Nothing<int64_t>(),
3905  i::HandleScope);
3907  has_pending_exception = !i::Object::ToInteger(isolate, obj).ToHandle(&num);
3908  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
3909  return Just(NumberToInt64(*num));
3910 }
3911 
3912 
3913 Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
3914  auto obj = Utils::OpenHandle(this);
3915  if (obj->IsNumber()) return Just(NumberToInt32(*obj));
3916  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3917  ENTER_V8(isolate, context, Value, Int32Value, Nothing<int32_t>(),
3918  i::HandleScope);
3920  has_pending_exception = !i::Object::ToInt32(isolate, obj).ToHandle(&num);
3921  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
3922  return Just(num->IsSmi() ? i::Smi::ToInt(*num)
3923  : static_cast<int32_t>(num->Number()));
3924 }
3925 
3926 
3927 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
3928  auto obj = Utils::OpenHandle(this);
3929  if (obj->IsNumber()) return Just(NumberToUint32(*obj));
3930  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3931  ENTER_V8(isolate, context, Value, Uint32Value, Nothing<uint32_t>(),
3932  i::HandleScope);
3934  has_pending_exception = !i::Object::ToUint32(isolate, obj).ToHandle(&num);
3935  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
3936  return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::ToInt(*num))
3937  : static_cast<uint32_t>(num->Number()));
3938 }
3939 
3940 
3942  auto self = Utils::OpenHandle(this);
3943  if (self->IsSmi()) {
3944  if (i::Smi::ToInt(*self) >= 0) return Utils::Uint32ToLocal(self);
3945  return Local<Uint32>();
3946  }
3947  PREPARE_FOR_EXECUTION(context, Object, ToArrayIndex, Uint32);
3948  i::Handle<i::Object> string_obj;
3949  has_pending_exception =
3950  !i::Object::ToString(isolate, self).ToHandle(&string_obj);
3951  RETURN_ON_FAILED_EXECUTION(Uint32);
3953  uint32_t index;
3954  if (str->AsArrayIndex(&index)) {
3955  i::Handle<i::Object> value;
3956  if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
3957  value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
3958  } else {
3959  value = isolate->factory()->NewNumber(index);
3960  }
3961  RETURN_ESCAPED(Utils::Uint32ToLocal(value));
3962  }
3963  return Local<Uint32>();
3964 }
3965 
3966 
3968  i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
3969  auto self = Utils::OpenHandle(this);
3970  auto other = Utils::OpenHandle(*that);
3971  return i::Object::Equals(isolate, self, other);
3972 }
3973 
3974 
3975 bool Value::StrictEquals(Local<Value> that) const {
3976  auto self = Utils::OpenHandle(this);
3977  auto other = Utils::OpenHandle(*that);
3978  return self->StrictEquals(*other);
3979 }
3980 
3981 
3982 bool Value::SameValue(Local<Value> that) const {
3983  auto self = Utils::OpenHandle(this);
3984  auto other = Utils::OpenHandle(*that);
3985  return self->SameValue(*other);
3986 }
3987 
3988 Local<String> Value::TypeOf(v8::Isolate* external_isolate) {
3989  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
3990  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
3991  LOG_API(isolate, Value, TypeOf);
3992  return Utils::ToLocal(i::Object::TypeOf(isolate, Utils::OpenHandle(this)));
3993 }
3994 
3995 Maybe<bool> Value::InstanceOf(v8::Local<v8::Context> context,
3996  v8::Local<v8::Object> object) {
3997  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3998  ENTER_V8(isolate, context, Value, InstanceOf, Nothing<bool>(),
3999  i::HandleScope);
4000  auto left = Utils::OpenHandle(this);
4001  auto right = Utils::OpenHandle(*object);
4002  i::Handle<i::Object> result;
4003  has_pending_exception =
4004  !i::Object::InstanceOf(isolate, left, right).ToHandle(&result);
4005  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4006  return Just(result->IsTrue(isolate));
4007 }
4008 
4009 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
4010  v8::Local<Value> key, v8::Local<Value> value) {
4011  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4012  ENTER_V8(isolate, context, Object, Set, Nothing<bool>(), i::HandleScope);
4013  auto self = Utils::OpenHandle(this);
4014  auto key_obj = Utils::OpenHandle(*key);
4015  auto value_obj = Utils::OpenHandle(*value);
4016  has_pending_exception =
4017  i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
4018  i::LanguageMode::kSloppy,
4019  i::StoreOrigin::kMaybeKeyed)
4020  .is_null();
4021  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4022  return Just(true);
4023 }
4024 
4025 
4026 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
4027  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4028  return Set(context, key, value).FromMaybe(false);
4029 }
4030 
4031 
4032 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
4033  v8::Local<Value> value) {
4034  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4035  ENTER_V8(isolate, context, Object, Set, Nothing<bool>(), i::HandleScope);
4036  auto self = Utils::OpenHandle(this);
4037  auto value_obj = Utils::OpenHandle(*value);
4038  has_pending_exception = i::Object::SetElement(isolate, self, index, value_obj,
4039  i::LanguageMode::kSloppy)
4040  .is_null();
4041  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4042  return Just(true);
4043 }
4044 
4045 
4046 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
4047  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4048  return Set(context, index, value).FromMaybe(false);
4049 }
4050 
4051 
4052 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
4053  v8::Local<Name> key,
4054  v8::Local<Value> value) {
4055  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4056  ENTER_V8(isolate, context, Object, CreateDataProperty, Nothing<bool>(),
4057  i::HandleScope);
4058  i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
4059  i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
4060  i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4061 
4062  Maybe<bool> result = i::JSReceiver::CreateDataProperty(
4063  isolate, self, key_obj, value_obj, i::kDontThrow);
4064  has_pending_exception = result.IsNothing();
4065  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4066  return result;
4067 }
4068 
4069 
4070 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
4071  uint32_t index,
4072  v8::Local<Value> value) {
4073  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4074  ENTER_V8(isolate, context, Object, CreateDataProperty, Nothing<bool>(),
4075  i::HandleScope);
4076  i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
4077  i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4078 
4079  i::LookupIterator it(isolate, self, index, self, i::LookupIterator::OWN);
4080  Maybe<bool> result =
4081  i::JSReceiver::CreateDataProperty(&it, value_obj, i::kDontThrow);
4082  has_pending_exception = result.IsNothing();
4083  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4084  return result;
4085 }
4086 
4088  PrivateData() : desc() {}
4089  i::PropertyDescriptor desc;
4090 };
4091 
4092 v8::PropertyDescriptor::PropertyDescriptor() : private_(new PrivateData()) {}
4093 
4094 // DataDescriptor
4095 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value)
4096  : private_(new PrivateData()) {
4097  private_->desc.set_value(Utils::OpenHandle(*value, true));
4098 }
4099 
4100 // DataDescriptor with writable field
4101 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value,
4102  bool writable)
4103  : private_(new PrivateData()) {
4104  private_->desc.set_value(Utils::OpenHandle(*value, true));
4105  private_->desc.set_writable(writable);
4106 }
4107 
4108 // AccessorDescriptor
4109 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> get,
4111  : private_(new PrivateData()) {
4112  DCHECK(get.IsEmpty() || get->IsUndefined() || get->IsFunction());
4113  DCHECK(set.IsEmpty() || set->IsUndefined() || set->IsFunction());
4114  private_->desc.set_get(Utils::OpenHandle(*get, true));
4115  private_->desc.set_set(Utils::OpenHandle(*set, true));
4116 }
4117 
4118 v8::PropertyDescriptor::~PropertyDescriptor() { delete private_; }
4119 
4120 v8::Local<Value> v8::PropertyDescriptor::value() const {
4121  DCHECK(private_->desc.has_value());
4122  return Utils::ToLocal(private_->desc.value());
4123 }
4124 
4125 v8::Local<Value> v8::PropertyDescriptor::get() const {
4126  DCHECK(private_->desc.has_get());
4127  return Utils::ToLocal(private_->desc.get());
4128 }
4129 
4130 v8::Local<Value> v8::PropertyDescriptor::set() const {
4131  DCHECK(private_->desc.has_set());
4132  return Utils::ToLocal(private_->desc.set());
4133 }
4134 
4135 bool v8::PropertyDescriptor::has_value() const {
4136  return private_->desc.has_value();
4137 }
4138 bool v8::PropertyDescriptor::has_get() const {
4139  return private_->desc.has_get();
4140 }
4141 bool v8::PropertyDescriptor::has_set() const {
4142  return private_->desc.has_set();
4143 }
4144 
4145 bool v8::PropertyDescriptor::writable() const {
4146  DCHECK(private_->desc.has_writable());
4147  return private_->desc.writable();
4148 }
4149 
4150 bool v8::PropertyDescriptor::has_writable() const {
4151  return private_->desc.has_writable();
4152 }
4153 
4154 void v8::PropertyDescriptor::set_enumerable(bool enumerable) {
4155  private_->desc.set_enumerable(enumerable);
4156 }
4157 
4158 bool v8::PropertyDescriptor::enumerable() const {
4159  DCHECK(private_->desc.has_enumerable());
4160  return private_->desc.enumerable();
4161 }
4162 
4163 bool v8::PropertyDescriptor::has_enumerable() const {
4164  return private_->desc.has_enumerable();
4165 }
4166 
4167 void v8::PropertyDescriptor::set_configurable(bool configurable) {
4168  private_->desc.set_configurable(configurable);
4169 }
4170 
4171 bool v8::PropertyDescriptor::configurable() const {
4172  DCHECK(private_->desc.has_configurable());
4173  return private_->desc.configurable();
4174 }
4175 
4176 bool v8::PropertyDescriptor::has_configurable() const {
4177  return private_->desc.has_configurable();
4178 }
4179 
4180 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
4181  v8::Local<Name> key,
4182  v8::Local<Value> value,
4183  v8::PropertyAttribute attributes) {
4184  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4185  i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
4186  i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
4187  i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4188 
4189  i::PropertyDescriptor desc;
4190  desc.set_writable(!(attributes & v8::ReadOnly));
4191  desc.set_enumerable(!(attributes & v8::DontEnum));
4192  desc.set_configurable(!(attributes & v8::DontDelete));
4193  desc.set_value(value_obj);
4194 
4195  if (self->IsJSProxy()) {
4196  ENTER_V8(isolate, context, Object, DefineOwnProperty, Nothing<bool>(),
4197  i::HandleScope);
4198  Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
4199  isolate, self, key_obj, &desc, i::kDontThrow);
4200  // Even though we said kDontThrow, there might be accessors that do throw.
4201  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4202  return success;
4203  } else {
4204  // If it's not a JSProxy, i::JSReceiver::DefineOwnProperty should never run
4205  // a script.
4206  ENTER_V8_NO_SCRIPT(isolate, context, Object, DefineOwnProperty,
4207  Nothing<bool>(), i::HandleScope);
4208  Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
4209  isolate, self, key_obj, &desc, i::kDontThrow);
4210  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4211  return success;
4212  }
4213 }
4214 
4215 Maybe<bool> v8::Object::DefineProperty(v8::Local<v8::Context> context,
4216  v8::Local<Name> key,
4217  PropertyDescriptor& descriptor) {
4218  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4219  ENTER_V8(isolate, context, Object, DefineOwnProperty, Nothing<bool>(),
4220  i::HandleScope);
4221  i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
4222  i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
4223 
4224  Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
4225  isolate, self, key_obj, &descriptor.get_private()->desc, i::kDontThrow);
4226  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4227  return success;
4228 }
4229 
4230 Maybe<bool> v8::Object::SetPrivate(Local<Context> context, Local<Private> key,
4231  Local<Value> value) {
4232  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4233  ENTER_V8_NO_SCRIPT(isolate, context, Object, SetPrivate, Nothing<bool>(),
4234  i::HandleScope);
4235  auto self = Utils::OpenHandle(this);
4236  auto key_obj = Utils::OpenHandle(reinterpret_cast<Name*>(*key));
4237  auto value_obj = Utils::OpenHandle(*value);
4238  if (self->IsJSProxy()) {
4239  i::PropertyDescriptor desc;
4240  desc.set_writable(true);
4241  desc.set_enumerable(false);
4242  desc.set_configurable(true);
4243  desc.set_value(value_obj);
4244  return i::JSProxy::SetPrivateSymbol(
4245  isolate, i::Handle<i::JSProxy>::cast(self),
4246  i::Handle<i::Symbol>::cast(key_obj), &desc, i::kDontThrow);
4247  }
4248  auto js_object = i::Handle<i::JSObject>::cast(self);
4249  i::LookupIterator it(js_object, key_obj, js_object);
4250  has_pending_exception = i::JSObject::DefineOwnPropertyIgnoreAttributes(
4251  &it, value_obj, i::DONT_ENUM)
4252  .is_null();
4253  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4254  return Just(true);
4255 }
4256 
4257 
4258 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
4259  Local<Value> key) {
4260  PREPARE_FOR_EXECUTION(context, Object, Get, Value);
4261  auto self = Utils::OpenHandle(this);
4262  auto key_obj = Utils::OpenHandle(*key);
4263  i::Handle<i::Object> result;
4264  has_pending_exception =
4265  !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
4266  RETURN_ON_FAILED_EXECUTION(Value);
4267  RETURN_ESCAPED(Utils::ToLocal(result));
4268 }
4269 
4270 
4271 Local<Value> v8::Object::Get(v8::Local<Value> key) {
4272  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4273  RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
4274 }
4275 
4276 
4277 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
4278  PREPARE_FOR_EXECUTION(context, Object, Get, Value);
4279  auto self = Utils::OpenHandle(this);
4280  i::Handle<i::Object> result;
4281  has_pending_exception =
4282  !i::JSReceiver::GetElement(isolate, self, index).ToHandle(&result);
4283  RETURN_ON_FAILED_EXECUTION(Value);
4284  RETURN_ESCAPED(Utils::ToLocal(result));
4285 }
4286 
4287 
4288 Local<Value> v8::Object::Get(uint32_t index) {
4289  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4290  RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
4291 }
4292 
4293 
4294 MaybeLocal<Value> v8::Object::GetPrivate(Local<Context> context,
4295  Local<Private> key) {
4296  return Get(context, Local<Value>(reinterpret_cast<Value*>(*key)));
4297 }
4298 
4299 
4301  Local<Context> context, Local<Value> key) {
4302  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4303  ENTER_V8(isolate, context, Object, GetPropertyAttributes,
4304  Nothing<PropertyAttribute>(), i::HandleScope);
4305  auto self = Utils::OpenHandle(this);
4306  auto key_obj = Utils::OpenHandle(*key);
4307  if (!key_obj->IsName()) {
4308  has_pending_exception =
4309  !i::Object::ToString(isolate, key_obj).ToHandle(&key_obj);
4310  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4311  }
4312  auto key_name = i::Handle<i::Name>::cast(key_obj);
4313  auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
4314  has_pending_exception = result.IsNothing();
4315  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4316  if (result.FromJust() == i::ABSENT) {
4317  return Just(static_cast<PropertyAttribute>(i::NONE));
4318  }
4319  return Just(static_cast<PropertyAttribute>(result.FromJust()));
4320 }
4321 
4322 
4324  Local<Name> key) {
4325  PREPARE_FOR_EXECUTION(context, Object, GetOwnPropertyDescriptor, Value);
4326  i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
4327  i::Handle<i::Name> key_name = Utils::OpenHandle(*key);
4328 
4329  i::PropertyDescriptor desc;
4330  Maybe<bool> found =
4331  i::JSReceiver::GetOwnPropertyDescriptor(isolate, obj, key_name, &desc);
4332  has_pending_exception = found.IsNothing();
4333  RETURN_ON_FAILED_EXECUTION(Value);
4334  if (!found.FromJust()) {
4335  return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
4336  }
4337  RETURN_ESCAPED(Utils::ToLocal(desc.ToObject(isolate)));
4338 }
4339 
4340 
4342  auto isolate = Utils::OpenHandle(this)->GetIsolate();
4343  auto self = Utils::OpenHandle(this);
4344  i::PrototypeIterator iter(isolate, self);
4345  return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
4346 }
4347 
4348 
4350  Local<Value> value) {
4351  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4352  ENTER_V8(isolate, context, Object, SetPrototype, Nothing<bool>(),
4353  i::HandleScope);
4354  auto self = Utils::OpenHandle(this);
4355  auto value_obj = Utils::OpenHandle(*value);
4356  // We do not allow exceptions thrown while setting the prototype
4357  // to propagate outside.
4358  TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
4359  auto result =
4360  i::JSReceiver::SetPrototype(self, value_obj, false, i::kThrowOnError);
4361  has_pending_exception = result.IsNothing();
4362  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4363  return Just(true);
4364 }
4365 
4366 
4369  auto self = Utils::OpenHandle(this);
4370  auto isolate = self->GetIsolate();
4371  i::PrototypeIterator iter(isolate, *self, i::kStartAtReceiver);
4372  auto tmpl_info = *Utils::OpenHandle(*tmpl);
4373  while (!tmpl_info->IsTemplateFor(iter.GetCurrent<i::JSObject>())) {
4374  iter.Advance();
4375  if (iter.IsAtEnd()) return Local<Object>();
4376  if (!iter.GetCurrent()->IsJSObject()) return Local<Object>();
4377  }
4378  // IsTemplateFor() ensures that iter.GetCurrent() can't be a Proxy here.
4379  return Utils::ToLocal(i::handle(iter.GetCurrent<i::JSObject>(), isolate));
4380 }
4381 
4382 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
4383  return GetPropertyNames(
4384  context, v8::KeyCollectionMode::kIncludePrototypes,
4385  static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS),
4386  v8::IndexFilter::kIncludeIndices);
4387 }
4388 
4389 MaybeLocal<Array> v8::Object::GetPropertyNames(
4390  Local<Context> context, KeyCollectionMode mode,
4391  PropertyFilter property_filter, IndexFilter index_filter,
4392  KeyConversionMode key_conversion) {
4393  PREPARE_FOR_EXECUTION(context, Object, GetPropertyNames, Array);
4394  auto self = Utils::OpenHandle(this);
4396  i::KeyAccumulator accumulator(
4397  isolate, static_cast<i::KeyCollectionMode>(mode),
4398  static_cast<i::PropertyFilter>(property_filter));
4399  accumulator.set_skip_indices(index_filter == IndexFilter::kSkipIndices);
4400  has_pending_exception = accumulator.CollectKeys(self, self).IsNothing();
4401  RETURN_ON_FAILED_EXECUTION(Array);
4402  value =
4403  accumulator.GetKeys(static_cast<i::GetKeysConversion>(key_conversion));
4404  DCHECK(self->map()->EnumLength() == i::kInvalidEnumCacheSentinel ||
4405  self->map()->EnumLength() == 0 ||
4406  self->map()->instance_descriptors()->enum_cache()->keys() != *value);
4407  auto result = isolate->factory()->NewJSArrayWithElements(value);
4408  RETURN_ESCAPED(Utils::ToLocal(result));
4409 }
4410 
4411 
4412 Local<Array> v8::Object::GetPropertyNames() {
4413  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4414  RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array);
4415 }
4416 
4417 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
4418  return GetOwnPropertyNames(
4419  context, static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS));
4420 }
4421 
4422 Local<Array> v8::Object::GetOwnPropertyNames() {
4423  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4424  RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array);
4425 }
4426 
4427 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(
4428  Local<Context> context, PropertyFilter filter,
4429  KeyConversionMode key_conversion) {
4430  return GetPropertyNames(context, KeyCollectionMode::kOwnOnly, filter,
4431  v8::IndexFilter::kIncludeIndices, key_conversion);
4432 }
4433 
4435  PREPARE_FOR_EXECUTION(context, Object, ObjectProtoToString, String);
4436  auto self = Utils::OpenHandle(this);
4437  Local<Value> result;
4438  has_pending_exception =
4439  !ToLocal<Value>(i::Execution::Call(isolate, isolate->object_to_string(),
4440  self, 0, nullptr),
4441  &result);
4442  RETURN_ON_FAILED_EXECUTION(String);
4443  RETURN_ESCAPED(Local<String>::Cast(result));
4444 }
4445 
4446 
4448  auto self = Utils::OpenHandle(this);
4449  i::Handle<i::String> name = i::JSReceiver::GetConstructorName(self);
4450  return Utils::ToLocal(name);
4451 }
4452 
4454  IntegrityLevel level) {
4455  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4456  ENTER_V8(isolate, context, Object, SetIntegrityLevel, Nothing<bool>(),
4457  i::HandleScope);
4458  auto self = Utils::OpenHandle(this);
4459  i::JSReceiver::IntegrityLevel i_level =
4460  level == IntegrityLevel::kFrozen ? i::FROZEN : i::SEALED;
4461  Maybe<bool> result =
4462  i::JSReceiver::SetIntegrityLevel(self, i_level, i::kThrowOnError);
4463  has_pending_exception = result.IsNothing();
4464  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4465  return result;
4466 }
4467 
4468 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
4469  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4470  auto self = Utils::OpenHandle(this);
4471  auto key_obj = Utils::OpenHandle(*key);
4472  if (self->IsJSProxy()) {
4473  ENTER_V8(isolate, context, Object, Delete, Nothing<bool>(), i::HandleScope);
4474  Maybe<bool> result = i::Runtime::DeleteObjectProperty(
4475  isolate, self, key_obj, i::LanguageMode::kSloppy);
4476  has_pending_exception = result.IsNothing();
4477  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4478  return result;
4479  } else {
4480  // If it's not a JSProxy, i::Runtime::DeleteObjectProperty should never run
4481  // a script.
4482  ENTER_V8_NO_SCRIPT(isolate, context, Object, Delete, Nothing<bool>(),
4483  i::HandleScope);
4484  Maybe<bool> result = i::Runtime::DeleteObjectProperty(
4485  isolate, self, key_obj, i::LanguageMode::kSloppy);
4486  has_pending_exception = result.IsNothing();
4487  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4488  return result;
4489  }
4490 }
4491 
4492 bool v8::Object::Delete(v8::Local<Value> key) {
4493  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4494  return Delete(context, key).FromMaybe(false);
4495 }
4496 
4497 Maybe<bool> v8::Object::DeletePrivate(Local<Context> context,
4498  Local<Private> key) {
4499  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4500  // In case of private symbols, i::Runtime::DeleteObjectProperty does not run
4501  // any author script.
4502  ENTER_V8_NO_SCRIPT(isolate, context, Object, Delete, Nothing<bool>(),
4503  i::HandleScope);
4504  auto self = Utils::OpenHandle(this);
4505  auto key_obj = Utils::OpenHandle(*key);
4506  Maybe<bool> result = i::Runtime::DeleteObjectProperty(
4507  isolate, self, key_obj, i::LanguageMode::kSloppy);
4508  has_pending_exception = result.IsNothing();
4509  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4510  return result;
4511 }
4512 
4514  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4515  ENTER_V8(isolate, context, Object, Has, Nothing<bool>(), i::HandleScope);
4516  auto self = Utils::OpenHandle(this);
4517  auto key_obj = Utils::OpenHandle(*key);
4518  Maybe<bool> maybe = Nothing<bool>();
4519  // Check if the given key is an array index.
4520  uint32_t index = 0;
4521  if (key_obj->ToArrayIndex(&index)) {
4522  maybe = i::JSReceiver::HasElement(self, index);
4523  } else {
4524  // Convert the key to a name - possibly by calling back into JavaScript.
4525  i::Handle<i::Name> name;
4526  if (i::Object::ToName(isolate, key_obj).ToHandle(&name)) {
4527  maybe = i::JSReceiver::HasProperty(self, name);
4528  }
4529  }
4530  has_pending_exception = maybe.IsNothing();
4531  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4532  return maybe;
4533 }
4534 
4535 
4537  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4538  return Has(context, key).FromMaybe(false);
4539 }
4540 
4541 
4543  return HasOwnProperty(context, Local<Name>(reinterpret_cast<Name*>(*key)));
4544 }
4545 
4546 
4547 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
4548  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4549  ENTER_V8(isolate, context, Object, Delete, Nothing<bool>(), i::HandleScope);
4550  auto self = Utils::OpenHandle(this);
4551  Maybe<bool> result = i::JSReceiver::DeleteElement(self, index);
4552  has_pending_exception = result.IsNothing();
4553  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4554  return result;
4555 }
4556 
4557 
4558 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
4559  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4560  ENTER_V8(isolate, context, Object, Has, Nothing<bool>(), i::HandleScope);
4561  auto self = Utils::OpenHandle(this);
4562  auto maybe = i::JSReceiver::HasElement(self, index);
4563  has_pending_exception = maybe.IsNothing();
4564  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4565  return maybe;
4566 }
4567 
4568 template <typename Getter, typename Setter, typename Data>
4569 static Maybe<bool> ObjectSetAccessor(
4570  Local<Context> context, Object* self, Local<Name> name, Getter getter,
4571  Setter setter, Data data, AccessControl settings,
4572  PropertyAttribute attributes, bool is_special_data_property,
4573  bool replace_on_access, SideEffectType getter_side_effect_type,
4574  SideEffectType setter_side_effect_type) {
4575  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4576  ENTER_V8_NO_SCRIPT(isolate, context, Object, SetAccessor, Nothing<bool>(),
4577  i::HandleScope);
4578  if (!Utils::OpenHandle(self)->IsJSObject()) return Just(false);
4580  i::Handle<i::JSObject>::cast(Utils::OpenHandle(self));
4581  v8::Local<AccessorSignature> signature;
4583  MakeAccessorInfo(isolate, name, getter, setter, data, settings, signature,
4584  is_special_data_property, replace_on_access);
4585  info->set_getter_side_effect_type(getter_side_effect_type);
4586  info->set_setter_side_effect_type(setter_side_effect_type);
4587  if (info.is_null()) return Nothing<bool>();
4588  bool fast = obj->HasFastProperties();
4589  i::Handle<i::Object> result;
4590 
4591  i::Handle<i::Name> accessor_name(info->name(), isolate);
4592  i::PropertyAttributes attrs = static_cast<i::PropertyAttributes>(attributes);
4593  has_pending_exception =
4594  !i::JSObject::SetAccessor(obj, accessor_name, info, attrs)
4595  .ToHandle(&result);
4596  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4597  if (result->IsUndefined(isolate)) return Just(false);
4598  if (fast) {
4599  i::JSObject::MigrateSlowToFast(obj, 0, "APISetAccessor");
4600  }
4601  return Just(true);
4602 }
4603 
4605  AccessorNameGetterCallback getter,
4606  AccessorNameSetterCallback setter,
4607  MaybeLocal<Value> data, AccessControl settings,
4608  PropertyAttribute attribute,
4609  SideEffectType getter_side_effect_type,
4610  SideEffectType setter_side_effect_type) {
4611  return ObjectSetAccessor(context, this, name, getter, setter,
4612  data.FromMaybe(Local<Value>()), settings, attribute,
4613  i::FLAG_disable_old_api_accessors, false,
4614  getter_side_effect_type, setter_side_effect_type);
4615 }
4616 
4617 
4618 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
4619  Local<Function> setter,
4620  PropertyAttribute attribute,
4621  AccessControl settings) {
4622  // TODO(verwaest): Remove |settings|.
4623  DCHECK_EQ(v8::DEFAULT, settings);
4624  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4625  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
4626  i::HandleScope scope(isolate);
4627  auto self = Utils::OpenHandle(this);
4628  if (!self->IsJSObject()) return;
4629  i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
4630  i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
4631  if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
4632  i::JSObject::DefineAccessor(i::Handle<i::JSObject>::cast(self),
4633  v8::Utils::OpenHandle(*name), getter_i, setter_i,
4634  static_cast<i::PropertyAttributes>(attribute));
4635 }
4636 
4639  AccessorNameGetterCallback getter, AccessorNameSetterCallback setter,
4640  v8::Local<Value> data, PropertyAttribute attributes,
4641  SideEffectType getter_side_effect_type,
4642  SideEffectType setter_side_effect_type) {
4643  return ObjectSetAccessor(context, this, name, getter, setter, data, DEFAULT,
4644  attributes, true, false, getter_side_effect_type,
4645  setter_side_effect_type);
4646 }
4647 
4650  AccessorNameGetterCallback getter, v8::Local<Value> data,
4651  PropertyAttribute attributes, SideEffectType getter_side_effect_type,
4652  SideEffectType setter_side_effect_type) {
4653  return ObjectSetAccessor(context, this, name, getter,
4654  static_cast<AccessorNameSetterCallback>(nullptr),
4655  data, DEFAULT, attributes, true, true,
4656  getter_side_effect_type, setter_side_effect_type);
4657 }
4658 
4660  Local<Name> key) {
4661  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4662  ENTER_V8(isolate, context, Object, HasOwnProperty, Nothing<bool>(),
4663  i::HandleScope);
4664  auto self = Utils::OpenHandle(this);
4665  auto key_val = Utils::OpenHandle(*key);
4666  auto result = i::JSReceiver::HasOwnProperty(self, key_val);
4667  has_pending_exception = result.IsNothing();
4668  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4669  return result;
4670 }
4671 
4673  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4674  ENTER_V8(isolate, context, Object, HasOwnProperty, Nothing<bool>(),
4675  i::HandleScope);
4676  auto self = Utils::OpenHandle(this);
4677  auto result = i::JSReceiver::HasOwnProperty(self, index);
4678  has_pending_exception = result.IsNothing();
4679  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4680  return result;
4681 }
4682 
4684  Local<Name> key) {
4685  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4686  ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealNamedProperty,
4687  Nothing<bool>(), i::HandleScope);
4688  auto self = Utils::OpenHandle(this);
4689  if (!self->IsJSObject()) return Just(false);
4690  auto key_val = Utils::OpenHandle(*key);
4691  auto result = i::JSObject::HasRealNamedProperty(
4692  i::Handle<i::JSObject>::cast(self), key_val);
4693  has_pending_exception = result.IsNothing();
4694  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4695  return result;
4696 }
4697 
4698 
4700  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4701  return HasRealNamedProperty(context, key).FromMaybe(false);
4702 }
4703 
4704 
4705 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
4706  uint32_t index) {
4707  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4708  ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealIndexedProperty,
4709  Nothing<bool>(), i::HandleScope);
4710  auto self = Utils::OpenHandle(this);
4711  if (!self->IsJSObject()) return Just(false);
4712  auto result = i::JSObject::HasRealElementProperty(
4713  i::Handle<i::JSObject>::cast(self), index);
4714  has_pending_exception = result.IsNothing();
4715  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4716  return result;
4717 }
4718 
4719 
4720 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
4721  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4722  return HasRealIndexedProperty(context, index).FromMaybe(false);
4723 }
4724 
4725 
4726 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
4727  Local<Name> key) {
4728  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4729  ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealNamedCallbackProperty,
4730  Nothing<bool>(), i::HandleScope);
4731  auto self = Utils::OpenHandle(this);
4732  if (!self->IsJSObject()) return Just(false);
4733  auto key_val = Utils::OpenHandle(*key);
4734  auto result = i::JSObject::HasRealNamedCallbackProperty(
4735  i::Handle<i::JSObject>::cast(self), key_val);
4736  has_pending_exception = result.IsNothing();
4737  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4738  return result;
4739 }
4740 
4741 
4742 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) {
4743  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
4744  return HasRealNamedCallbackProperty(context, key).FromMaybe(false);
4745 }
4746 
4747 
4749  auto self = Utils::OpenHandle(this);
4750  return self->IsJSObject() &&
4751  i::Handle<i::JSObject>::cast(self)->HasNamedInterceptor();
4752 }
4753 
4754 
4756  auto self = Utils::OpenHandle(this);
4757  return self->IsJSObject() &&
4758  i::Handle<i::JSObject>::cast(self)->HasIndexedInterceptor();
4759 }
4760 
4761 
4763  Local<Context> context, Local<Name> key) {
4764  PREPARE_FOR_EXECUTION(context, Object, GetRealNamedPropertyInPrototypeChain,
4765  Value);
4766  i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
4767  if (!self->IsJSObject()) return MaybeLocal<Value>();
4768  i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
4769  i::PrototypeIterator iter(isolate, self);
4770  if (iter.IsAtEnd()) return MaybeLocal<Value>();
4771  i::Handle<i::JSReceiver> proto =
4772  i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
4773  i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4774  isolate, self, key_obj, proto,
4775  i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4776  Local<Value> result;
4777  has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4778  RETURN_ON_FAILED_EXECUTION(Value);
4779  if (!it.IsFound()) return MaybeLocal<Value>();
4780  RETURN_ESCAPED(result);
4781 }
4782 
4783 
4786  Local<Context> context, Local<Name> key) {
4787  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4788  ENTER_V8_NO_SCRIPT(isolate, context, Object,
4789  GetRealNamedPropertyAttributesInPrototypeChain,
4790  Nothing<PropertyAttribute>(), i::HandleScope);
4791  i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
4792  if (!self->IsJSObject()) return Nothing<PropertyAttribute>();
4793  i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
4794  i::PrototypeIterator iter(isolate, self);
4795  if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
4796  i::Handle<i::JSReceiver> proto =
4797  i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
4798  i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4799  isolate, self, key_obj, proto,
4800  i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4802  i::JSReceiver::GetPropertyAttributes(&it);
4803  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4804  if (!it.IsFound()) return Nothing<PropertyAttribute>();
4805  if (result.FromJust() == i::ABSENT) return Just(None);
4806  return Just(static_cast<PropertyAttribute>(result.FromJust()));
4807 }
4808 
4809 
4811  Local<Name> key) {
4812  PREPARE_FOR_EXECUTION(context, Object, GetRealNamedProperty, Value);
4813  auto self = Utils::OpenHandle(this);
4814  auto key_obj = Utils::OpenHandle(*key);
4815  i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4816  isolate, self, key_obj, self,
4817  i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4818  Local<Value> result;
4819  has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4820  RETURN_ON_FAILED_EXECUTION(Value);
4821  if (!it.IsFound()) return MaybeLocal<Value>();
4822  RETURN_ESCAPED(result);
4823 }
4824 
4825 
4827  Local<Context> context, Local<Name> key) {
4828  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4829  ENTER_V8_NO_SCRIPT(isolate, context, Object, GetRealNamedPropertyAttributes,
4830  Nothing<PropertyAttribute>(), i::HandleScope);
4831  auto self = Utils::OpenHandle(this);
4832  auto key_obj = Utils::OpenHandle(*key);
4833  i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4834  isolate, self, key_obj, self,
4835  i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4836  auto result = i::JSReceiver::GetPropertyAttributes(&it);
4837  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4838  if (!it.IsFound()) return Nothing<PropertyAttribute>();
4839  if (result.FromJust() == i::ABSENT) {
4840  return Just(static_cast<PropertyAttribute>(i::NONE));
4841  }
4842  return Just<PropertyAttribute>(
4843  static_cast<PropertyAttribute>(result.FromJust()));
4844 }
4845 
4846 
4848  auto self = i::Handle<i::JSObject>::cast(Utils::OpenHandle(this));
4849  auto isolate = self->GetIsolate();
4850  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
4851  auto result = isolate->factory()->CopyJSObject(self);
4852  CHECK(!result.is_null());
4853  return Utils::ToLocal(result);
4854 }
4855 
4856 
4858  auto self = Utils::OpenHandle(this);
4859  return Utils::ToLocal(self->GetCreationContext());
4860 }
4861 
4862 
4865  auto isolate = Utils::OpenHandle(this)->GetIsolate();
4866  i::HandleScope scope(isolate);
4867  auto self = Utils::OpenHandle(this);
4868  return self->GetOrCreateIdentityHash(isolate)->value();
4869 }
4870 
4871 
4873  auto self = Utils::OpenHandle(this);
4874  return self->IsCallable();
4875 }
4876 
4878  auto self = Utils::OpenHandle(this);
4879  return self->IsConstructor();
4880 }
4881 
4883  Local<Value> recv, int argc,
4884  Local<Value> argv[]) {
4885  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4886  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
4887  ENTER_V8(isolate, context, Object, CallAsFunction, MaybeLocal<Value>(),
4888  InternalEscapableScope);
4889  i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4890  auto self = Utils::OpenHandle(this);
4891  auto recv_obj = Utils::OpenHandle(*recv);
4892  STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
4893  i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4894  Local<Value> result;
4895  has_pending_exception = !ToLocal<Value>(
4896  i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
4897  RETURN_ON_FAILED_EXECUTION(Value);
4898  RETURN_ESCAPED(result);
4899 }
4900 
4901 
4903  Local<Value> argv[]) {
4904  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4905  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
4906  ENTER_V8(isolate, context, Object, CallAsConstructor, MaybeLocal<Value>(),
4907  InternalEscapableScope);
4908  i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4909  auto self = Utils::OpenHandle(this);
4910  STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
4911  i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4912  Local<Value> result;
4913  has_pending_exception = !ToLocal<Value>(
4914  i::Execution::New(isolate, self, self, argc, args), &result);
4915  RETURN_ON_FAILED_EXECUTION(Value);
4916  RETURN_ESCAPED(result);
4917 }
4918 
4920  FunctionCallback callback, Local<Value> data,
4921  int length, ConstructorBehavior behavior,
4922  SideEffectType side_effect_type) {
4923  i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
4924  LOG_API(isolate, Function, New);
4925  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
4926  auto templ =
4927  FunctionTemplateNew(isolate, callback, data, Local<Signature>(), length,
4928  true, Local<Private>(), side_effect_type);
4929  if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype();
4930  return templ->GetFunction(context);
4931 }
4932 
4933 
4934 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback,
4935  Local<Value> data, int length) {
4936  return Function::New(v8_isolate->GetCurrentContext(), callback, data, length,
4937  ConstructorBehavior::kAllow)
4938  .FromMaybe(Local<Function>());
4939 }
4940 
4941 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
4942  v8::Local<v8::Value> argv[]) const {
4943  return NewInstanceWithSideEffectType(context, argc, argv,
4944  SideEffectType::kHasSideEffect);
4945 }
4946 
4948  Local<Context> context, int argc, v8::Local<v8::Value> argv[],
4949  SideEffectType side_effect_type) const {
4950  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4951  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
4952  ENTER_V8(isolate, context, Function, NewInstance, MaybeLocal<Object>(),
4953  InternalEscapableScope);
4954  i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4955  auto self = Utils::OpenHandle(this);
4956  STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
4957  bool should_set_has_no_side_effect =
4958  side_effect_type == SideEffectType::kHasNoSideEffect &&
4959  isolate->debug_execution_mode() == i::DebugInfo::kSideEffects;
4960  if (should_set_has_no_side_effect) {
4961  CHECK(self->IsJSFunction() &&
4962  i::JSFunction::cast(*self)->shared()->IsApiFunction());
4963  i::Object* obj =
4964  i::JSFunction::cast(*self)->shared()->get_api_func_data()->call_code();
4965  if (obj->IsCallHandlerInfo()) {
4966  i::CallHandlerInfo* handler_info = i::CallHandlerInfo::cast(obj);
4967  if (!handler_info->IsSideEffectFreeCallHandlerInfo()) {
4968  handler_info->SetNextCallHasNoSideEffect();
4969  }
4970  }
4971  }
4972  i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4973  Local<Object> result;
4974  has_pending_exception = !ToLocal<Object>(
4975  i::Execution::New(isolate, self, self, argc, args), &result);
4976  if (should_set_has_no_side_effect) {
4977  i::Object* obj =
4978  i::JSFunction::cast(*self)->shared()->get_api_func_data()->call_code();
4979  if (obj->IsCallHandlerInfo()) {
4980  i::CallHandlerInfo* handler_info = i::CallHandlerInfo::cast(obj);
4981  if (has_pending_exception) {
4982  // Restore the map if an exception prevented restoration.
4983  handler_info->NextCallHasNoSideEffect();
4984  } else {
4985  DCHECK(handler_info->IsSideEffectCallHandlerInfo() ||
4986  handler_info->IsSideEffectFreeCallHandlerInfo());
4987  }
4988  }
4989  }
4990  RETURN_ON_FAILED_EXECUTION(Object);
4991  RETURN_ESCAPED(result);
4992 }
4993 
4994 
4995 MaybeLocal<v8::Value> Function::Call(Local<Context> context,
4996  v8::Local<v8::Value> recv, int argc,
4997  v8::Local<v8::Value> argv[]) {
4998  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4999  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
5000  ENTER_V8(isolate, context, Function, Call, MaybeLocal<Value>(),
5001  InternalEscapableScope);
5002  i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
5003  auto self = Utils::OpenHandle(this);
5004  Utils::ApiCheck(!self.is_null(), "v8::Function::Call",
5005  "Function to be called is a null pointer");
5006  i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
5007  STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
5008  i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
5009  Local<Value> result;
5010  has_pending_exception = !ToLocal<Value>(
5011  i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
5012  RETURN_ON_FAILED_EXECUTION(Value);
5013  RETURN_ESCAPED(result);
5014 }
5015 
5016 
5017 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc,
5018  v8::Local<v8::Value> argv[]) {
5019  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
5020  RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value);
5021 }
5022 
5023 
5024 void Function::SetName(v8::Local<v8::String> name) {
5025  auto self = Utils::OpenHandle(this);
5026  if (!self->IsJSFunction()) return;
5027  auto func = i::Handle<i::JSFunction>::cast(self);
5028  func->shared()->SetName(*Utils::OpenHandle(*name));
5029 }
5030 
5031 
5032 Local<Value> Function::GetName() const {
5033  auto self = Utils::OpenHandle(this);
5034  i::Isolate* isolate = self->GetIsolate();
5035  if (self->IsJSBoundFunction()) {
5036  auto func = i::Handle<i::JSBoundFunction>::cast(self);
5037  i::Handle<i::Object> name;
5038  ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
5039  i::JSBoundFunction::GetName(isolate, func),
5040  Local<Value>());
5041  return Utils::ToLocal(name);
5042  }
5043  if (self->IsJSFunction()) {
5044  auto func = i::Handle<i::JSFunction>::cast(self);
5045  return Utils::ToLocal(handle(func->shared()->Name(), isolate));
5046  }
5047  return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
5048 }
5049 
5050 
5052  auto self = Utils::OpenHandle(this);
5053  if (!self->IsJSFunction()) {
5054  return ToApiHandle<Primitive>(
5055  self->GetIsolate()->factory()->undefined_value());
5056  }
5057  auto func = i::Handle<i::JSFunction>::cast(self);
5058  return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
5059  func->GetIsolate()));
5060 }
5061 
5062 
5064  auto self = Utils::OpenHandle(this);
5065  if (!self->IsJSFunction()) {
5066  return ToApiHandle<Primitive>(
5067  self->GetIsolate()->factory()->undefined_value());
5068  }
5069  auto func = i::Handle<i::JSFunction>::cast(self);
5070  i::Handle<i::String> name = i::JSFunction::GetDebugName(func);
5071  return Utils::ToLocal(i::Handle<i::Object>(*name, self->GetIsolate()));
5072 }
5073 
5074 
5076  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
5077  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
5078  auto self = Utils::OpenHandle(this);
5079  if (!self->IsJSFunction()) {
5080  return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
5081  }
5082  auto func = i::Handle<i::JSFunction>::cast(self);
5083  i::Handle<i::String> property_name =
5084  isolate->factory()->NewStringFromStaticChars("displayName");
5085  i::Handle<i::Object> value =
5086  i::JSReceiver::GetDataProperty(func, property_name);
5087  if (value->IsString()) {
5089  if (name->length() > 0) return Utils::ToLocal(name);
5090  }
5091  return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
5092 }
5093 
5094 
5095 ScriptOrigin Function::GetScriptOrigin() const {
5096  auto self = Utils::OpenHandle(this);
5097  if (!self->IsJSFunction()) {
5098  return v8::ScriptOrigin(Local<Value>());
5099  }
5100  auto func = i::Handle<i::JSFunction>::cast(self);
5101  if (func->shared()->script()->IsScript()) {
5102  i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
5103  func->GetIsolate());
5104  return GetScriptOriginForScript(func->GetIsolate(), script);
5105  }
5106  return v8::ScriptOrigin(Local<Value>());
5107 }
5108 
5109 
5110 const int Function::kLineOffsetNotFound = -1;
5111 
5112 
5114  auto self = Utils::OpenHandle(this);
5115  if (!self->IsJSFunction()) {
5116  return kLineOffsetNotFound;
5117  }
5118  auto func = i::Handle<i::JSFunction>::cast(self);
5119  if (func->shared()->script()->IsScript()) {
5120  i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
5121  func->GetIsolate());
5122  return i::Script::GetLineNumber(script, func->shared()->StartPosition());
5123  }
5124  return kLineOffsetNotFound;
5125 }
5126 
5127 
5129  auto self = Utils::OpenHandle(this);
5130  if (!self->IsJSFunction()) {
5131  return kLineOffsetNotFound;
5132  }
5133  auto func = i::Handle<i::JSFunction>::cast(self);
5134  if (func->shared()->script()->IsScript()) {
5135  i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
5136  func->GetIsolate());
5137  return i::Script::GetColumnNumber(script, func->shared()->StartPosition());
5138  }
5139  return kLineOffsetNotFound;
5140 }
5141 
5142 
5143 int Function::ScriptId() const {
5144  auto self = Utils::OpenHandle(this);
5145  if (!self->IsJSFunction()) {
5146  return v8::UnboundScript::kNoScriptId;
5147  }
5148  auto func = i::Handle<i::JSFunction>::cast(self);
5149  if (!func->shared()->script()->IsScript()) {
5150  return v8::UnboundScript::kNoScriptId;
5151  }
5152  i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
5153  func->GetIsolate());
5154  return script->id();
5155 }
5156 
5157 
5159  auto self = Utils::OpenHandle(this);
5160  if (self->IsJSBoundFunction()) {
5161  auto bound_function = i::Handle<i::JSBoundFunction>::cast(self);
5162  auto bound_target_function = i::handle(
5163  bound_function->bound_target_function(), bound_function->GetIsolate());
5164  return Utils::CallableToLocal(bound_target_function);
5165  }
5166  return v8::Undefined(reinterpret_cast<v8::Isolate*>(self->GetIsolate()));
5167 }
5168 
5170  auto self = Utils::OpenHandle(this);
5171  return static_cast<int>(self->Hash());
5172 }
5173 
5174 
5175 int String::Length() const {
5176  i::Handle<i::String> str = Utils::OpenHandle(this);
5177  return str->length();
5178 }
5179 
5180 
5181 bool String::IsOneByte() const {
5182  i::Handle<i::String> str = Utils::OpenHandle(this);
5183  return str->HasOnlyOneByteChars();
5184 }
5185 
5186 
5187 // Helpers for ContainsOnlyOneByteHelper
5188 template<size_t size> struct OneByteMask;
5189 template<> struct OneByteMask<4> {
5190  static const uint32_t value = 0xFF00FF00;
5191 };
5192 template<> struct OneByteMask<8> {
5193  static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
5194 };
5195 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
5196 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
5197 static inline bool Unaligned(const uint16_t* chars) {
5198  return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
5199 }
5200 
5201 
5202 static inline const uint16_t* Align(const uint16_t* chars) {
5203  return reinterpret_cast<uint16_t*>(
5204  reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
5205 }
5206 
5208  public:
5209  ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
5210  bool Check(i::String string) {
5211  i::ConsString cons_string = i::String::VisitFlat(this, string, 0);
5212  if (cons_string.is_null()) return is_one_byte_;
5213  return CheckCons(cons_string);
5214  }
5215  void VisitOneByteString(const uint8_t* chars, int length) {
5216  // Nothing to do.
5217  }
5218  void VisitTwoByteString(const uint16_t* chars, int length) {
5219  // Accumulated bits.
5220  uintptr_t acc = 0;
5221  // Align to uintptr_t.
5222  const uint16_t* end = chars + length;
5223  while (Unaligned(chars) && chars != end) {
5224  acc |= *chars++;
5225  }
5226  // Read word aligned in blocks,
5227  // checking the return value at the end of each block.
5228  const uint16_t* aligned_end = Align(end);
5229  const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
5230  const int inner_loops = 16;
5231  while (chars + inner_loops*increment < aligned_end) {
5232  for (int i = 0; i < inner_loops; i++) {
5233  acc |= *reinterpret_cast<const uintptr_t*>(chars);
5234  chars += increment;
5235  }
5236  // Check for early return.
5237  if ((acc & kOneByteMask) != 0) {
5238  is_one_byte_ = false;
5239  return;
5240  }
5241  }
5242  // Read the rest.
5243  while (chars != end) {
5244  acc |= *chars++;
5245  }
5246  // Check result.
5247  if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
5248  }
5249 
5250  private:
5251  bool CheckCons(i::ConsString cons_string) {
5252  while (true) {
5253  // Check left side if flat.
5254  i::String left = cons_string->first();
5255  i::ConsString left_as_cons = i::String::VisitFlat(this, left, 0);
5256  if (!is_one_byte_) return false;
5257  // Check right side if flat.
5258  i::String right = cons_string->second();
5259  i::ConsString right_as_cons = i::String::VisitFlat(this, right, 0);
5260  if (!is_one_byte_) return false;
5261  // Standard recurse/iterate trick.
5262  if (!left_as_cons.is_null() && !right_as_cons.is_null()) {
5263  if (left->length() < right->length()) {
5264  CheckCons(left_as_cons);
5265  cons_string = right_as_cons;
5266  } else {
5267  CheckCons(right_as_cons);
5268  cons_string = left_as_cons;
5269  }
5270  // Check fast return.
5271  if (!is_one_byte_) return false;
5272  continue;
5273  }
5274  // Descend left in place.
5275  if (!left_as_cons.is_null()) {
5276  cons_string = left_as_cons;
5277  continue;
5278  }
5279  // Descend right in place.
5280  if (!right_as_cons.is_null()) {
5281  cons_string = right_as_cons;
5282  continue;
5283  }
5284  // Terminate.
5285  break;
5286  }
5287  return is_one_byte_;
5288  }
5289  bool is_one_byte_;
5290  DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
5291 };
5292 
5293 
5295  i::Handle<i::String> str = Utils::OpenHandle(this);
5296  if (str->HasOnlyOneByteChars()) return true;
5298  return helper.Check(*str);
5299 }
5300 
5301 int String::Utf8Length(Isolate* isolate) const {
5302  i::Handle<i::String> str = Utils::OpenHandle(this);
5303  str = i::String::Flatten(reinterpret_cast<i::Isolate*>(isolate), str);
5304  int length = str->length();
5305  if (length == 0) return 0;
5307  i::String::FlatContent flat = str->GetFlatContent();
5308  DCHECK(flat.IsFlat());
5309  int utf8_length = 0;
5310  if (flat.IsOneByte()) {
5311  for (uint8_t c : flat.ToOneByteVector()) {
5312  utf8_length += c >> 7;
5313  }
5314  utf8_length += length;
5315  } else {
5316  int last_character = unibrow::Utf16::kNoPreviousCharacter;
5317  for (uint16_t c : flat.ToUC16Vector()) {
5318  utf8_length += unibrow::Utf8::Length(c, last_character);
5319  last_character = c;
5320  }
5321  }
5322  return utf8_length;
5323 }
5324 
5326  public:
5328  char* buffer,
5329  int capacity,
5330  bool skip_capacity_check,
5331  bool replace_invalid_utf8)
5332  : early_termination_(false),
5333  last_character_(unibrow::Utf16::kNoPreviousCharacter),
5334  buffer_(buffer),
5335  start_(buffer),
5336  capacity_(capacity),
5337  skip_capacity_check_(capacity == -1 || skip_capacity_check),
5338  replace_invalid_utf8_(replace_invalid_utf8),
5339  utf16_chars_read_(0) {
5340  }
5341 
5342  static int WriteEndCharacter(uint16_t character,
5343  int last_character,
5344  int remaining,
5345  char* const buffer,
5346  bool replace_invalid_utf8) {
5347  DCHECK_GT(remaining, 0);
5348  // We can't use a local buffer here because Encode needs to modify
5349  // previous characters in the stream. We know, however, that
5350  // exactly one character will be advanced.
5351  if (unibrow::Utf16::IsSurrogatePair(last_character, character)) {
5352  int written = unibrow::Utf8::Encode(buffer, character, last_character,
5353  replace_invalid_utf8);
5354  DCHECK_EQ(written, 1);
5355  return written;
5356  }
5357  // Use a scratch buffer to check the required characters.
5358  char temp_buffer[unibrow::Utf8::kMaxEncodedSize];
5359  // Can't encode using last_character as gcc has array bounds issues.
5360  int written = unibrow::Utf8::Encode(temp_buffer, character,
5361  unibrow::Utf16::kNoPreviousCharacter,
5362  replace_invalid_utf8);
5363  // Won't fit.
5364  if (written > remaining) return 0;
5365  // Copy over the character from temp_buffer.
5366  for (int j = 0; j < written; j++) {
5367  buffer[j] = temp_buffer[j];
5368  }
5369  return written;
5370  }
5371 
5372  // Visit writes out a group of code units (chars) of a v8::String to the
5373  // internal buffer_. This is done in two phases. The first phase calculates a
5374  // pesimistic estimate (writable_length) on how many code units can be safely
5375  // written without exceeding the buffer capacity and without writing the last
5376  // code unit (it could be a lead surrogate). The estimated number of code
5377  // units is then written out in one go, and the reported byte usage is used
5378  // to correct the estimate. This is repeated until the estimate becomes <= 0
5379  // or all code units have been written out. The second phase writes out code
5380  // units until the buffer capacity is reached, would be exceeded by the next
5381  // unit, or all units have been written out.
5382  template<typename Char>
5383  void Visit(const Char* chars, const int length) {
5384  DCHECK(!early_termination_);
5385  if (length == 0) return;
5386  // Copy state to stack.
5387  char* buffer = buffer_;
5388  int last_character = sizeof(Char) == 1
5389  ? unibrow::Utf16::kNoPreviousCharacter
5390  : last_character_;
5391  int i = 0;
5392  // Do a fast loop where there is no exit capacity check.
5393  while (true) {
5394  int fast_length;
5395  if (skip_capacity_check_) {
5396  fast_length = length;
5397  } else {
5398  int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
5399  // Need enough space to write everything but one character.
5400  STATIC_ASSERT(unibrow::Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit ==
5401  3);
5402  int max_size_per_char = sizeof(Char) == 1 ? 2 : 3;
5403  int writable_length =
5404  (remaining_capacity - max_size_per_char)/max_size_per_char;
5405  // Need to drop into slow loop.
5406  if (writable_length <= 0) break;
5407  fast_length = i + writable_length;
5408  if (fast_length > length) fast_length = length;
5409  }
5410  // Write the characters to the stream.
5411  if (sizeof(Char) == 1) {
5412  for (; i < fast_length; i++) {
5413  buffer += unibrow::Utf8::EncodeOneByte(
5414  buffer, static_cast<uint8_t>(*chars++));
5415  DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
5416  }
5417  } else {
5418  for (; i < fast_length; i++) {
5419  uint16_t character = *chars++;
5420  buffer += unibrow::Utf8::Encode(buffer, character, last_character,
5421  replace_invalid_utf8_);
5422  last_character = character;
5423  DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
5424  }
5425  }
5426  // Array is fully written. Exit.
5427  if (fast_length == length) {
5428  // Write state back out to object.
5429  last_character_ = last_character;
5430  buffer_ = buffer;
5431  utf16_chars_read_ += length;
5432  return;
5433  }
5434  }
5435  DCHECK(!skip_capacity_check_);
5436  // Slow loop. Must check capacity on each iteration.
5437  int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
5438  DCHECK_GE(remaining_capacity, 0);
5439  for (; i < length && remaining_capacity > 0; i++) {
5440  uint16_t character = *chars++;
5441  // remaining_capacity is <= 3 bytes at this point, so we do not write out
5442  // an umatched lead surrogate.
5443  if (replace_invalid_utf8_ && unibrow::Utf16::IsLeadSurrogate(character)) {
5444  early_termination_ = true;
5445  break;
5446  }
5447  int written = WriteEndCharacter(character,
5448  last_character,
5449  remaining_capacity,
5450  buffer,
5451  replace_invalid_utf8_);
5452  if (written == 0) {
5453  early_termination_ = true;
5454  break;
5455  }
5456  buffer += written;
5457  remaining_capacity -= written;
5458  last_character = character;
5459  }
5460  // Write state back out to object.
5461  last_character_ = last_character;
5462  buffer_ = buffer;
5463  utf16_chars_read_ += i;
5464  }
5465 
5466  inline bool IsDone() {
5467  return early_termination_;
5468  }
5469 
5470  inline void VisitOneByteString(const uint8_t* chars, int length) {
5471  Visit(chars, length);
5472  }
5473 
5474  inline void VisitTwoByteString(const uint16_t* chars, int length) {
5475  Visit(chars, length);
5476  }
5477 
5478  int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
5479  // Write out number of utf16 characters written to the stream.
5480  if (utf16_chars_read_out != nullptr) {
5481  *utf16_chars_read_out = utf16_chars_read_;
5482  }
5483  // Only null terminate if all of the string was written and there's space.
5484  if (write_null &&
5485  !early_termination_ &&
5486  (capacity_ == -1 || (buffer_ - start_) < capacity_)) {
5487  *buffer_++ = '\0';
5488  }
5489  return static_cast<int>(buffer_ - start_);
5490  }
5491 
5492  private:
5493  bool early_termination_;
5494  int last_character_;
5495  char* buffer_;
5496  char* const start_;
5497  int capacity_;
5498  bool const skip_capacity_check_;
5499  bool const replace_invalid_utf8_;
5500  int utf16_chars_read_;
5501  DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
5502 };
5503 
5504 // TODO(yangguo): Simplify this. We can now expect the string to be flat.
5505 static bool RecursivelySerializeToUtf8(i::String current,
5506  Utf8WriterVisitor* writer,
5507  int recursion_budget) {
5508  while (!writer->IsDone()) {
5509  i::ConsString cons_string = i::String::VisitFlat(writer, current);
5510  if (cons_string.is_null()) return true; // Leaf node.
5511  if (recursion_budget <= 0) return false;
5512  // Must write the left branch first.
5513  i::String first = cons_string->first();
5514  bool success = RecursivelySerializeToUtf8(first,
5515  writer,
5516  recursion_budget - 1);
5517  if (!success) return false;
5518  // Inline tail recurse for right branch.
5519  current = cons_string->second();
5520  }
5521  return true;
5522 }
5523 
5524 int String::WriteUtf8(Isolate* v8_isolate, char* buffer, int capacity,
5525  int* nchars_ref, int options) const {
5526  i::Handle<i::String> str = Utils::OpenHandle(this);
5527  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
5528  LOG_API(isolate, String, WriteUtf8);
5529  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
5530  str = i::String::Flatten(isolate, str); // Flatten the string for efficiency.
5531  const int string_length = str->length();
5532  bool write_null = !(options & NO_NULL_TERMINATION);
5533  bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
5534  int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
5535  // First check if we can just write the string without checking capacity.
5536  if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
5537  Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
5538  const int kMaxRecursion = 100;
5539  bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
5540  if (success) return writer.CompleteWrite(write_null, nchars_ref);
5541  } else if (capacity >= string_length) {
5542  // First check that the buffer is large enough.
5543  int utf8_bytes = Utf8Length(v8_isolate);
5544  if (utf8_bytes <= capacity) {
5545  // one-byte fast path.
5546  if (utf8_bytes == string_length) {
5547  WriteOneByte(v8_isolate, reinterpret_cast<uint8_t*>(buffer), 0,
5548  capacity, options);
5549  if (nchars_ref != nullptr) *nchars_ref = string_length;
5550  if (write_null && (utf8_bytes+1 <= capacity)) {
5551  return string_length + 1;
5552  }
5553  return string_length;
5554  }
5555  if (write_null && (utf8_bytes+1 > capacity)) {
5556  options |= NO_NULL_TERMINATION;
5557  }
5558  // Recurse once without a capacity limit.
5559  // This will get into the first branch above.
5560  // TODO(dcarney) Check max left rec. in Utf8Length and fall through.
5561  return WriteUtf8(v8_isolate, buffer, -1, nchars_ref, options);
5562  }
5563  }
5564  Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
5565  i::String::VisitFlat(&writer, *str);
5566  return writer.CompleteWrite(write_null, nchars_ref);
5567 }
5568 
5569 template <typename CharType>
5570 static inline int WriteHelper(i::Isolate* isolate, const String* string,
5571  CharType* buffer, int start, int length,
5572  int options) {
5573  LOG_API(isolate, String, Write);
5574  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
5575  DCHECK(start >= 0 && length >= -1);
5576  i::Handle<i::String> str = Utils::OpenHandle(string);
5577  str = i::String::Flatten(isolate, str);
5578  int end = start + length;
5579  if ((length == -1) || (length > str->length() - start) )
5580  end = str->length();
5581  if (end < 0) return 0;
5582  i::String::WriteToFlat(*str, buffer, start, end);
5583  if (!(options & String::NO_NULL_TERMINATION) &&
5584  (length == -1 || end - start < length)) {
5585  buffer[end - start] = '\0';
5586  }
5587  return end - start;
5588 }
5589 
5590 
5591 int String::WriteOneByte(Isolate* isolate, uint8_t* buffer, int start,
5592  int length, int options) const {
5593  return WriteHelper(reinterpret_cast<i::Isolate*>(isolate), this, buffer,
5594  start, length, options);
5595 }
5596 
5597 
5598 int String::Write(Isolate* isolate, uint16_t* buffer, int start, int length,
5599  int options) const {
5600  return WriteHelper(reinterpret_cast<i::Isolate*>(isolate), this, buffer,
5601  start, length, options);
5602 }
5603 
5604 
5606  i::Handle<i::String> str = Utils::OpenHandle(this);
5607  return i::StringShape(*str).IsExternalTwoByte();
5608 }
5609 
5610 
5612  i::Handle<i::String> str = Utils::OpenHandle(this);
5613  return i::StringShape(*str).IsExternalOneByte();
5614 }
5615 
5616 
5617 void v8::String::VerifyExternalStringResource(
5618  v8::String::ExternalStringResource* value) const {
5619  i::DisallowHeapAllocation no_allocation;
5620  i::String str = *Utils::OpenHandle(this);
5621  const v8::String::ExternalStringResource* expected;
5622 
5623  if (str->IsThinString()) {
5624  str = i::ThinString::cast(str)->actual();
5625  }
5626 
5627  if (i::StringShape(str).IsExternalTwoByte()) {
5628  const void* resource = i::ExternalTwoByteString::cast(str)->resource();
5629  expected = reinterpret_cast<const ExternalStringResource*>(resource);
5630  } else {
5631  expected = nullptr;
5632  }
5633  CHECK_EQ(expected, value);
5634 }
5635 
5636 void v8::String::VerifyExternalStringResourceBase(
5637  v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
5638  i::DisallowHeapAllocation no_allocation;
5639  i::String str = *Utils::OpenHandle(this);
5641  Encoding expectedEncoding;
5642 
5643  if (str->IsThinString()) {
5644  str = i::ThinString::cast(str)->actual();
5645  }
5646 
5647  if (i::StringShape(str).IsExternalOneByte()) {
5648  const void* resource = i::ExternalOneByteString::cast(str)->resource();
5649  expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5650  expectedEncoding = ONE_BYTE_ENCODING;
5651  } else if (i::StringShape(str).IsExternalTwoByte()) {
5652  const void* resource = i::ExternalTwoByteString::cast(str)->resource();
5653  expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5654  expectedEncoding = TWO_BYTE_ENCODING;
5655  } else {
5656  expected = nullptr;
5657  expectedEncoding =
5658  str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
5659  }
5660  CHECK_EQ(expected, value);
5661  CHECK_EQ(expectedEncoding, encoding);
5662 }
5663 
5664 String::ExternalStringResource* String::GetExternalStringResourceSlow() const {
5665  i::DisallowHeapAllocation no_allocation;
5666  typedef internal::Internals I;
5667  i::String str = *Utils::OpenHandle(this);
5668 
5669  if (str->IsThinString()) {
5670  str = i::ThinString::cast(str)->actual();
5671  }
5672 
5673  if (i::StringShape(str).IsExternalTwoByte()) {
5674  void* value = I::ReadField<void*>(str.ptr(), I::kStringResourceOffset);
5675  return reinterpret_cast<String::ExternalStringResource*>(value);
5676  }
5677  return nullptr;
5678 }
5679 
5680 String::ExternalStringResourceBase* String::GetExternalStringResourceBaseSlow(
5681  String::Encoding* encoding_out) const {
5682  i::DisallowHeapAllocation no_allocation;
5683  typedef internal::Internals I;
5684  ExternalStringResourceBase* resource = nullptr;
5685  i::String str = *Utils::OpenHandle(this);
5686 
5687  if (str->IsThinString()) {
5688  str = i::ThinString::cast(str)->actual();
5689  }
5690 
5691  internal::Address string = str.ptr();
5692  int type = I::GetInstanceType(string) & I::kFullStringRepresentationMask;
5693  *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
5694  if (i::StringShape(str).IsExternalOneByte() ||
5695  i::StringShape(str).IsExternalTwoByte()) {
5696  void* value = I::ReadField<void*>(string, I::kStringResourceOffset);
5697  resource = static_cast<ExternalStringResourceBase*>(value);
5698  }
5699  return resource;
5700 }
5701 
5704  i::DisallowHeapAllocation no_allocation;
5705  i::String str = *Utils::OpenHandle(this);
5706  if (i::StringShape(str).IsExternalOneByte()) {
5707  return i::ExternalOneByteString::cast(str)->resource();
5708  } else if (str->IsThinString()) {
5709  str = i::ThinString::cast(str)->actual();
5710  if (i::StringShape(str).IsExternalOneByte()) {
5711  return i::ExternalOneByteString::cast(str)->resource();
5712  }
5713  }
5714  return nullptr;
5715 }
5716 
5717 
5719  i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
5720 
5721  i::Isolate* isolate;
5722  if (!i::Isolate::FromWritableHeapObject(*sym, &isolate)) {
5723  // If the Symbol is in RO_SPACE, then its name must be too. Since RO_SPACE
5724  // objects are immovable we can use the Handle(Address*) constructor with
5725  // the address of the name field in the Symbol object without needing an
5726  // isolate.
5727  i::Handle<i::HeapObject> ro_name(reinterpret_cast<i::Address*>(
5728  sym->GetFieldAddress(i::Symbol::kNameOffset)));
5729  return Utils::ToLocal(ro_name);
5730  }
5731 
5732  i::Handle<i::Object> name(sym->name(), isolate);
5733 
5734  return Utils::ToLocal(name);
5735 }
5736 
5737 
5739  return reinterpret_cast<const Symbol*>(this)->Name();
5740 }
5741 
5742 
5743 double Number::Value() const {
5744  i::Handle<i::Object> obj = Utils::OpenHandle(this);
5745  return obj->Number();
5746 }
5747 
5748 
5749 bool Boolean::Value() const {
5750  i::Handle<i::Object> obj = Utils::OpenHandle(this);
5751  return obj->IsTrue();
5752 }
5753 
5754 
5755 int64_t Integer::Value() const {
5756  i::Handle<i::Object> obj = Utils::OpenHandle(this);
5757  if (obj->IsSmi()) {
5758  return i::Smi::ToInt(*obj);
5759  } else {
5760  return static_cast<int64_t>(obj->Number());
5761  }
5762 }
5763 
5764 
5765 int32_t Int32::Value() const {
5766  i::Handle<i::Object> obj = Utils::OpenHandle(this);
5767  if (obj->IsSmi()) {
5768  return i::Smi::ToInt(*obj);
5769  } else {
5770  return static_cast<int32_t>(obj->Number());
5771  }
5772 }
5773 
5774 
5775 uint32_t Uint32::Value() const {
5776  i::Handle<i::Object> obj = Utils::OpenHandle(this);
5777  if (obj->IsSmi()) {
5778  return i::Smi::ToInt(*obj);
5779  } else {
5780  return static_cast<uint32_t>(obj->Number());
5781  }
5782 }
5783 
5785  i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
5786  if (!self->IsJSObject()) return 0;
5787  return i::Handle<i::JSObject>::cast(self)->GetEmbedderFieldCount();
5788 }
5789 
5790 static bool InternalFieldOK(i::Handle<i::JSReceiver> obj, int index,
5791  const char* location) {
5792  return Utils::ApiCheck(
5793  obj->IsJSObject() &&
5794  (index < i::Handle<i::JSObject>::cast(obj)->GetEmbedderFieldCount()),
5795  location, "Internal field out of bounds");
5796 }
5797 
5798 Local<Value> v8::Object::SlowGetInternalField(int index) {
5799  i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
5800  const char* location = "v8::Object::GetInternalField()";
5801  if (!InternalFieldOK(obj, index, location)) return Local<Value>();
5802  i::Handle<i::Object> value(i::JSObject::cast(*obj)->GetEmbedderField(index),
5803  obj->GetIsolate());
5804  return Utils::ToLocal(value);
5805 }
5806 
5808  i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
5809  const char* location = "v8::Object::SetInternalField()";
5810  if (!InternalFieldOK(obj, index, location)) return;
5811  i::Handle<i::Object> val = Utils::OpenHandle(*value);
5812  i::Handle<i::JSObject>::cast(obj)->SetEmbedderField(index, *val);
5813 }
5814 
5815 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
5816  i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
5817  const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
5818  if (!InternalFieldOK(obj, index, location)) return nullptr;
5819  void* result;
5820  Utils::ApiCheck(i::EmbedderDataSlot(i::JSObject::cast(*obj), index)
5821  .ToAlignedPointer(&result),
5822  location, "Unaligned pointer");
5823  return result;
5824 }
5825 
5826 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
5827  i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
5828  const char* location = "v8::Object::SetAlignedPointerInInternalField()";
5829  if (!InternalFieldOK(obj, index, location)) return;
5830  Utils::ApiCheck(i::EmbedderDataSlot(i::JSObject::cast(*obj), index)
5831  .store_aligned_pointer(value),
5832  location, "Unaligned pointer");
5833  DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
5834 }
5835 
5836 void v8::Object::SetAlignedPointerInInternalFields(int argc, int indices[],
5837  void* values[]) {
5838  i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
5839  const char* location = "v8::Object::SetAlignedPointerInInternalFields()";
5841  i::JSObject* js_obj = i::JSObject::cast(*obj);
5842  int nof_embedder_fields = js_obj->GetEmbedderFieldCount();
5843  for (int i = 0; i < argc; i++) {
5844  int index = indices[i];
5845  if (!Utils::ApiCheck(index < nof_embedder_fields, location,
5846  "Internal field out of bounds")) {
5847  return;
5848  }
5849  void* value = values[i];
5850  Utils::ApiCheck(
5851  i::EmbedderDataSlot(js_obj, index).store_aligned_pointer(value),
5852  location, "Unaligned pointer");
5853  DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
5854  }
5855 }
5856 
5857 static void* ExternalValue(i::Object* obj) {
5858  // Obscure semantics for undefined, but somehow checked in our unit tests...
5859  if (obj->IsUndefined()) {
5860  return nullptr;
5861  }
5862  i::Object* foreign = i::JSObject::cast(obj)->GetEmbedderField(0);
5863  return reinterpret_cast<void*>(i::Foreign::cast(foreign)->foreign_address());
5864 }
5865 
5866 
5867 // --- E n v i r o n m e n t ---
5868 
5869 
5870 void v8::V8::InitializePlatform(Platform* platform) {
5871  i::V8::InitializePlatform(platform);
5872 }
5873 
5874 
5875 void v8::V8::ShutdownPlatform() {
5876  i::V8::ShutdownPlatform();
5877 }
5878 
5879 
5880 bool v8::V8::Initialize() {
5881  i::V8::Initialize();
5882 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5883  i::ReadNatives();
5884 #endif
5885  return true;
5886 }
5887 
5888 #if V8_OS_LINUX || V8_OS_MACOSX
5889 bool TryHandleWebAssemblyTrapPosix(int sig_code, siginfo_t* info,
5890  void* context) {
5891 #if V8_TARGET_ARCH_X64 && !V8_OS_ANDROID
5892  return i::trap_handler::TryHandleSignal(sig_code, info, context);
5893 #else
5894  return false;
5895 #endif
5896 }
5897 
5898 bool V8::TryHandleSignal(int signum, void* info, void* context) {
5900  signum, reinterpret_cast<siginfo_t*>(info), context);
5901 }
5902 #endif
5903 
5904 #if V8_OS_WIN
5905 bool TryHandleWebAssemblyTrapWindows(EXCEPTION_POINTERS* exception) {
5906 #if V8_TARGET_ARCH_X64
5907  return i::trap_handler::TryHandleWasmTrap(exception);
5908 #endif
5909  return false;
5910 }
5911 #endif
5912 
5913 bool V8::RegisterDefaultSignalHandler() {
5914  return v8::internal::trap_handler::RegisterDefaultTrapHandler();
5915 }
5916 
5917 bool V8::EnableWebAssemblyTrapHandler(bool use_v8_signal_handler) {
5918  return v8::internal::trap_handler::EnableTrapHandler(use_v8_signal_handler);
5919 }
5920 
5921 void v8::V8::SetEntropySource(EntropySource entropy_source) {
5922  base::RandomNumberGenerator::SetEntropySource(entropy_source);
5923 }
5924 
5925 
5926 void v8::V8::SetReturnAddressLocationResolver(
5927  ReturnAddressLocationResolver return_address_resolver) {
5928  i::StackFrame::SetReturnAddressLocationResolver(return_address_resolver);
5929 }
5930 
5931 
5932 bool v8::V8::Dispose() {
5933  i::V8::TearDown();
5934 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5935  i::DisposeNatives();
5936 #endif
5937  return true;
5938 }
5939 
5940 HeapStatistics::HeapStatistics()
5941  : total_heap_size_(0),
5942  total_heap_size_executable_(0),
5943  total_physical_size_(0),
5944  total_available_size_(0),
5945  used_heap_size_(0),
5946  heap_size_limit_(0),
5947  malloced_memory_(0),
5948  external_memory_(0),
5949  peak_malloced_memory_(0),
5950  does_zap_garbage_(false),
5951  number_of_native_contexts_(0),
5952  number_of_detached_contexts_(0) {}
5953 
5954 HeapSpaceStatistics::HeapSpaceStatistics()
5955  : space_name_(nullptr),
5956  space_size_(0),
5957  space_used_size_(0),
5958  space_available_size_(0),
5959  physical_space_size_(0) {}
5960 
5961 HeapObjectStatistics::HeapObjectStatistics()
5962  : object_type_(nullptr),
5963  object_sub_type_(nullptr),
5964  object_count_(0),
5965  object_size_(0) {}
5966 
5967 HeapCodeStatistics::HeapCodeStatistics()
5968  : code_and_metadata_size_(0),
5969  bytecode_and_metadata_size_(0),
5970  external_script_source_size_(0) {}
5971 
5972 bool v8::V8::InitializeICU(const char* icu_data_file) {
5973  return i::InitializeICU(icu_data_file);
5974 }
5975 
5976 bool v8::V8::InitializeICUDefaultLocation(const char* exec_path,
5977  const char* icu_data_file) {
5978  return i::InitializeICUDefaultLocation(exec_path, icu_data_file);
5979 }
5980 
5981 void v8::V8::InitializeExternalStartupData(const char* directory_path) {
5982  i::InitializeExternalStartupData(directory_path);
5983 }
5984 
5985 
5986 void v8::V8::InitializeExternalStartupData(const char* natives_blob,
5987  const char* snapshot_blob) {
5988  i::InitializeExternalStartupData(natives_blob, snapshot_blob);
5989 }
5990 
5991 
5992 const char* v8::V8::GetVersion() {
5993  return i::Version::GetVersion();
5994 }
5995 
5996 template <typename ObjectType>
5998 
5999 template <>
6000 struct InvokeBootstrapper<i::Context> {
6001  i::Handle<i::Context> Invoke(
6002  i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy,
6003  v8::Local<v8::ObjectTemplate> global_proxy_template,
6004  v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
6005  v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
6006  return isolate->bootstrapper()->CreateEnvironment(
6007  maybe_global_proxy, global_proxy_template, extensions,
6008  context_snapshot_index, embedder_fields_deserializer);
6009  }
6010 };
6011 
6012 template <>
6013 struct InvokeBootstrapper<i::JSGlobalProxy> {
6015  i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy,
6016  v8::Local<v8::ObjectTemplate> global_proxy_template,
6017  v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
6018  v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
6019  USE(extensions);
6020  USE(context_snapshot_index);
6021  return isolate->bootstrapper()->NewRemoteContext(maybe_global_proxy,
6022  global_proxy_template);
6023  }
6024 };
6025 
6026 template <typename ObjectType>
6027 static i::Handle<ObjectType> CreateEnvironment(
6028  i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
6029  v8::MaybeLocal<ObjectTemplate> maybe_global_template,
6030  v8::MaybeLocal<Value> maybe_global_proxy, size_t context_snapshot_index,
6031  v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
6032  i::Handle<ObjectType> result;
6033 
6034  {
6035  ENTER_V8_FOR_NEW_CONTEXT(isolate);
6036  v8::Local<ObjectTemplate> proxy_template;
6037  i::Handle<i::FunctionTemplateInfo> proxy_constructor;
6038  i::Handle<i::FunctionTemplateInfo> global_constructor;
6039  i::Handle<i::Object> named_interceptor(
6040  isolate->factory()->undefined_value());
6041  i::Handle<i::Object> indexed_interceptor(
6042  isolate->factory()->undefined_value());
6043 
6044  if (!maybe_global_template.IsEmpty()) {
6045  v8::Local<v8::ObjectTemplate> global_template =
6046  maybe_global_template.ToLocalChecked();
6047  // Make sure that the global_template has a constructor.
6048  global_constructor = EnsureConstructor(isolate, *global_template);
6049 
6050  // Create a fresh template for the global proxy object.
6051  proxy_template = ObjectTemplate::New(
6052  reinterpret_cast<v8::Isolate*>(isolate));
6053  proxy_constructor = EnsureConstructor(isolate, *proxy_template);
6054 
6055  // Set the global template to be the prototype template of
6056  // global proxy template.
6057  i::FunctionTemplateInfo::SetPrototypeTemplate(
6058  isolate, proxy_constructor, Utils::OpenHandle(*global_template));
6059 
6060  proxy_template->SetInternalFieldCount(
6061  global_template->InternalFieldCount());
6062 
6063  // Migrate security handlers from global_template to
6064  // proxy_template. Temporarily removing access check
6065  // information from the global template.
6066  if (!global_constructor->GetAccessCheckInfo()->IsUndefined(isolate)) {
6067  i::FunctionTemplateInfo::SetAccessCheckInfo(
6068  isolate, proxy_constructor,
6069  i::handle(global_constructor->GetAccessCheckInfo(), isolate));
6070  proxy_constructor->set_needs_access_check(
6071  global_constructor->needs_access_check());
6072  global_constructor->set_needs_access_check(false);
6073  i::FunctionTemplateInfo::SetAccessCheckInfo(
6074  isolate, global_constructor,
6075  i::ReadOnlyRoots(isolate).undefined_value_handle());
6076  }
6077 
6078  // Same for other interceptors. If the global constructor has
6079  // interceptors, we need to replace them temporarily with noop
6080  // interceptors, so the map is correctly marked as having interceptors,
6081  // but we don't invoke any.
6082  if (!global_constructor->GetNamedPropertyHandler()->IsUndefined(
6083  isolate)) {
6084  named_interceptor =
6085  handle(global_constructor->GetNamedPropertyHandler(), isolate);
6086  i::FunctionTemplateInfo::SetNamedPropertyHandler(
6087  isolate, global_constructor,
6088  i::ReadOnlyRoots(isolate).noop_interceptor_info_handle());
6089  }
6090  if (!global_constructor->GetIndexedPropertyHandler()->IsUndefined(
6091  isolate)) {
6092  indexed_interceptor =
6093  handle(global_constructor->GetIndexedPropertyHandler(), isolate);
6094  i::FunctionTemplateInfo::SetIndexedPropertyHandler(
6095  isolate, global_constructor,
6096  i::ReadOnlyRoots(isolate).noop_interceptor_info_handle());
6097  }
6098  }
6099 
6101  if (!maybe_global_proxy.IsEmpty()) {
6102  maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(
6103  Utils::OpenHandle(*maybe_global_proxy.ToLocalChecked()));
6104  }
6105  // Create the environment.
6106  InvokeBootstrapper<ObjectType> invoke;
6107  result =
6108  invoke.Invoke(isolate, maybe_proxy, proxy_template, extensions,
6109  context_snapshot_index, embedder_fields_deserializer);
6110 
6111  // Restore the access check info and interceptors on the global template.
6112  if (!maybe_global_template.IsEmpty()) {
6113  DCHECK(!global_constructor.is_null());
6114  DCHECK(!proxy_constructor.is_null());
6115  i::FunctionTemplateInfo::SetAccessCheckInfo(
6116  isolate, global_constructor,
6117  i::handle(proxy_constructor->GetAccessCheckInfo(), isolate));
6118  global_constructor->set_needs_access_check(
6119  proxy_constructor->needs_access_check());
6120  i::FunctionTemplateInfo::SetNamedPropertyHandler(
6121  isolate, global_constructor, named_interceptor);
6122  i::FunctionTemplateInfo::SetIndexedPropertyHandler(
6123  isolate, global_constructor, indexed_interceptor);
6124  }
6125  }
6126  // Leave V8.
6127 
6128  return result;
6129 }
6130 
6131 Local<Context> NewContext(
6132  v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
6133  v8::MaybeLocal<ObjectTemplate> global_template,
6134  v8::MaybeLocal<Value> global_object, size_t context_snapshot_index,
6135  v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
6136  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
6137  // TODO(jkummerow): This is for crbug.com/713699. Remove it if it doesn't
6138  // fail.
6139  // Sanity-check that the isolate is initialized and usable.
6140  CHECK(isolate->builtins()->builtin(i::Builtins::kIllegal)->IsCode());
6141 
6142  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.NewContext");
6143  LOG_API(isolate, Context, New);
6144  i::HandleScope scope(isolate);
6145  ExtensionConfiguration no_extensions;
6146  if (extensions == nullptr) extensions = &no_extensions;
6147  i::Handle<i::Context> env = CreateEnvironment<i::Context>(
6148  isolate, extensions, global_template, global_object,
6149  context_snapshot_index, embedder_fields_deserializer);
6150  if (env.is_null()) {
6151  if (isolate->has_pending_exception()) isolate->clear_pending_exception();
6152  return Local<Context>();
6153  }
6154  return Utils::ToLocal(scope.CloseAndEscape(env));
6155 }
6156 
6157 Local<Context> v8::Context::New(
6158  v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
6159  v8::MaybeLocal<ObjectTemplate> global_template,
6160  v8::MaybeLocal<Value> global_object,
6161  DeserializeInternalFieldsCallback internal_fields_deserializer) {
6162  return NewContext(external_isolate, extensions, global_template,
6163  global_object, 0, internal_fields_deserializer);
6164 }
6165 
6166 MaybeLocal<Context> v8::Context::FromSnapshot(
6167  v8::Isolate* external_isolate, size_t context_snapshot_index,
6168  v8::DeserializeInternalFieldsCallback embedder_fields_deserializer,
6169  v8::ExtensionConfiguration* extensions, MaybeLocal<Value> global_object) {
6170  size_t index_including_default_context = context_snapshot_index + 1;
6171  if (!i::Snapshot::HasContextSnapshot(
6172  reinterpret_cast<i::Isolate*>(external_isolate),
6173  index_including_default_context)) {
6174  return MaybeLocal<Context>();
6175  }
6176  return NewContext(external_isolate, extensions, MaybeLocal<ObjectTemplate>(),
6177  global_object, index_including_default_context,
6178  embedder_fields_deserializer);
6179 }
6180 
6181 MaybeLocal<Object> v8::Context::NewRemoteContext(
6182  v8::Isolate* external_isolate, v8::Local<ObjectTemplate> global_template,
6183  v8::MaybeLocal<v8::Value> global_object) {
6184  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
6185  LOG_API(isolate, Context, NewRemoteContext);
6186  i::HandleScope scope(isolate);
6187  i::Handle<i::FunctionTemplateInfo> global_constructor =
6188  EnsureConstructor(isolate, *global_template);
6189  Utils::ApiCheck(global_constructor->needs_access_check(),
6190  "v8::Context::NewRemoteContext",
6191  "Global template needs to have access checks enabled.");
6192  i::Handle<i::AccessCheckInfo> access_check_info = i::handle(
6193  i::AccessCheckInfo::cast(global_constructor->GetAccessCheckInfo()),
6194  isolate);
6195  Utils::ApiCheck(access_check_info->named_interceptor() != nullptr,
6196  "v8::Context::NewRemoteContext",
6197  "Global template needs to have access check handlers.");
6198  i::Handle<i::JSGlobalProxy> global_proxy =
6199  CreateEnvironment<i::JSGlobalProxy>(isolate, nullptr, global_template,
6200  global_object, 0,
6201  DeserializeInternalFieldsCallback());
6202  if (global_proxy.is_null()) {
6203  if (isolate->has_pending_exception()) isolate->clear_pending_exception();
6204  return MaybeLocal<Object>();
6205  }
6206  return Utils::ToLocal(
6207  scope.CloseAndEscape(i::Handle<i::JSObject>::cast(global_proxy)));
6208 }
6209 
6210 void v8::Context::SetSecurityToken(Local<Value> token) {
6211  i::Handle<i::Context> env = Utils::OpenHandle(this);
6212  i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
6213  env->set_security_token(*token_handle);
6214 }
6215 
6216 
6217 void v8::Context::UseDefaultSecurityToken() {
6218  i::Handle<i::Context> env = Utils::OpenHandle(this);
6219  env->set_security_token(env->global_object());
6220 }
6221 
6222 
6223 Local<Value> v8::Context::GetSecurityToken() {
6224  i::Handle<i::Context> env = Utils::OpenHandle(this);
6225  i::Isolate* isolate = env->GetIsolate();
6226  i::Object* security_token = env->security_token();
6227  i::Handle<i::Object> token_handle(security_token, isolate);
6228  return Utils::ToLocal(token_handle);
6229 }
6230 
6231 
6232 v8::Isolate* Context::GetIsolate() {
6233  i::Handle<i::Context> env = Utils::OpenHandle(this);
6234  return reinterpret_cast<Isolate*>(env->GetIsolate());
6235 }
6236 
6237 v8::Local<v8::Object> Context::Global() {
6238  i::Handle<i::Context> context = Utils::OpenHandle(this);
6239  i::Isolate* isolate = context->GetIsolate();
6240  i::Handle<i::Object> global(context->global_proxy(), isolate);
6241  // TODO(dcarney): This should always return the global proxy
6242  // but can't presently as calls to GetProtoype will return the wrong result.
6244  global)->IsDetachedFrom(context->global_object())) {
6245  global = i::Handle<i::Object>(context->global_object(), isolate);
6246  }
6247  return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
6248 }
6249 
6250 
6251 void Context::DetachGlobal() {
6252  i::Handle<i::Context> context = Utils::OpenHandle(this);
6253  i::Isolate* isolate = context->GetIsolate();
6254  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
6255  isolate->bootstrapper()->DetachGlobal(context);
6256 }
6257 
6258 
6259 Local<v8::Object> Context::GetExtrasBindingObject() {
6260  i::Handle<i::Context> context = Utils::OpenHandle(this);
6261  i::Isolate* isolate = context->GetIsolate();
6262  i::Handle<i::JSObject> binding(context->extras_binding_object(), isolate);
6263  return Utils::ToLocal(binding);
6264 }
6265 
6266 
6267 void Context::AllowCodeGenerationFromStrings(bool allow) {
6268  i::Handle<i::Context> context = Utils::OpenHandle(this);
6269  i::Isolate* isolate = context->GetIsolate();
6270  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
6271  context->set_allow_code_gen_from_strings(
6272  allow ? i::ReadOnlyRoots(isolate).true_value()
6273  : i::ReadOnlyRoots(isolate).false_value());
6274 }
6275 
6276 
6277 bool Context::IsCodeGenerationFromStringsAllowed() {
6278  i::Handle<i::Context> context = Utils::OpenHandle(this);
6279  return !context->allow_code_gen_from_strings()->IsFalse(
6280  context->GetIsolate());
6281 }
6282 
6283 
6284 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
6285  i::Handle<i::Context> context = Utils::OpenHandle(this);
6286  i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
6287  context->set_error_message_for_code_gen_from_strings(*error_handle);
6288 }
6289 
6290 namespace {
6291 i::Address* GetSerializedDataFromFixedArray(i::Isolate* isolate,
6292  i::FixedArray list, size_t index) {
6293  if (index < static_cast<size_t>(list->length())) {
6294  int int_index = static_cast<int>(index);
6295  i::Object* object = list->get(int_index);
6296  if (!object->IsTheHole(isolate)) {
6297  list->set_the_hole(isolate, int_index);
6298  // Shrink the list so that the last element is not the hole (unless it's
6299  // the first element, because we don't want to end up with a non-canonical
6300  // empty FixedArray).
6301  int last = list->length() - 1;
6302  while (last >= 0 && list->is_the_hole(isolate, last)) last--;
6303  if (last != -1) list->Shrink(isolate, last + 1);
6304  return i::Handle<i::Object>(object, isolate).location();
6305  }
6306  }
6307  return nullptr;
6308 }
6309 } // anonymous namespace
6310 
6311 i::Address* Context::GetDataFromSnapshotOnce(size_t index) {
6312  auto context = Utils::OpenHandle(this);
6313  i::Isolate* i_isolate = context->GetIsolate();
6314  i::FixedArray list = context->serialized_objects();
6315  return GetSerializedDataFromFixedArray(i_isolate, list, index);
6316 }
6317 
6318 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
6319  PREPARE_FOR_EXECUTION(context, ObjectTemplate, NewInstance, Object);
6320  auto self = Utils::OpenHandle(this);
6321  Local<Object> result;
6322  has_pending_exception = !ToLocal<Object>(
6323  i::ApiNatives::InstantiateObject(isolate, self), &result);
6324  RETURN_ON_FAILED_EXECUTION(Object);
6325  RETURN_ESCAPED(result);
6326 }
6327 
6328 
6329 Local<v8::Object> ObjectTemplate::NewInstance() {
6330  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
6331  RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object);
6332 }
6333 
6334 void v8::ObjectTemplate::CheckCast(Data* that) {
6335  i::Handle<i::Object> obj = Utils::OpenHandle(that);
6336  Utils::ApiCheck(obj->IsObjectTemplateInfo(), "v8::ObjectTemplate::Cast",
6337  "Could not convert to object template");
6338 }
6339 
6340 void v8::FunctionTemplate::CheckCast(Data* that) {
6341  i::Handle<i::Object> obj = Utils::OpenHandle(that);
6342  Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::FunctionTemplate::Cast",
6343  "Could not convert to function template");
6344 }
6345 
6346 void v8::Signature::CheckCast(Data* that) {
6347  i::Handle<i::Object> obj = Utils::OpenHandle(that);
6348  Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::Signature::Cast",
6349  "Could not convert to signature");
6350 }
6351 
6352 void v8::AccessorSignature::CheckCast(Data* that) {
6353  i::Handle<i::Object> obj = Utils::OpenHandle(that);
6354  Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::AccessorSignature::Cast",
6355  "Could not convert to accessor signature");
6356 }
6357 
6358 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
6359  PREPARE_FOR_EXECUTION(context, FunctionTemplate, GetFunction, Function);
6360  auto self = Utils::OpenHandle(this);
6361  Local<Function> result;
6362  has_pending_exception =
6363  !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
6364  RETURN_ON_FAILED_EXECUTION(Function);
6365  RETURN_ESCAPED(result);
6366 }
6367 
6368 
6369 Local<v8::Function> FunctionTemplate::GetFunction() {
6370  auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
6371  RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function);
6372 }
6373 
6375  auto self = Utils::OpenHandle(this);
6376  i::Isolate* isolate = self->GetIsolate();
6377  LOG_API(isolate, FunctionTemplate, NewRemoteInstance);
6378  i::HandleScope scope(isolate);
6380  EnsureConstructor(isolate, *InstanceTemplate());
6381  Utils::ApiCheck(constructor->needs_access_check(),
6382  "v8::FunctionTemplate::NewRemoteInstance",
6383  "InstanceTemplate needs to have access checks enabled.");
6384  i::Handle<i::AccessCheckInfo> access_check_info = i::handle(
6385  i::AccessCheckInfo::cast(constructor->GetAccessCheckInfo()), isolate);
6386  Utils::ApiCheck(access_check_info->named_interceptor() != nullptr,
6387  "v8::FunctionTemplate::NewRemoteInstance",
6388  "InstanceTemplate needs to have access check handlers.");
6389  i::Handle<i::JSObject> object;
6390  if (!i::ApiNatives::InstantiateRemoteObject(
6391  Utils::OpenHandle(*InstanceTemplate()))
6392  .ToHandle(&object)) {
6393  if (isolate->has_pending_exception()) {
6394  isolate->OptionalRescheduleException(true);
6395  }
6396  return MaybeLocal<Object>();
6397  }
6398  return Utils::ToLocal(scope.CloseAndEscape(object));
6399 }
6400 
6402  auto self = Utils::OpenHandle(this);
6403  auto obj = Utils::OpenHandle(*value);
6404  if (obj->IsJSObject() && self->IsTemplateFor(i::JSObject::cast(*obj))) {
6405  return true;
6406  }
6407  if (obj->IsJSGlobalProxy()) {
6408  // If it's a global proxy, then test with the global object. Note that the
6409  // inner global object may not necessarily be a JSGlobalObject.
6410  i::PrototypeIterator iter(self->GetIsolate(),
6411  i::JSObject::cast(*obj)->map());
6412  // The global proxy should always have a prototype, as it is a bug to call
6413  // this on a detached JSGlobalProxy.
6414  DCHECK(!iter.IsAtEnd());
6415  return self->IsTemplateFor(iter.GetCurrent<i::JSObject>());
6416  }
6417  return false;
6418 }
6419 
6420 
6421 Local<External> v8::External::New(Isolate* isolate, void* value) {
6422  STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
6423  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6424  LOG_API(i_isolate, External, New);
6425  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6426  i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
6427  return Utils::ExternalToLocal(external);
6428 }
6429 
6430 
6431 void* External::Value() const {
6432  return ExternalValue(*Utils::OpenHandle(this));
6433 }
6434 
6435 
6436 // anonymous namespace for string creation helper functions
6437 namespace {
6438 
6439 inline int StringLength(const char* string) {
6440  return i::StrLength(string);
6441 }
6442 
6443 
6444 inline int StringLength(const uint8_t* string) {
6445  return i::StrLength(reinterpret_cast<const char*>(string));
6446 }
6447 
6448 
6449 inline int StringLength(const uint16_t* string) {
6450  int length = 0;
6451  while (string[length] != '\0')
6452  length++;
6453  return length;
6454 }
6455 
6456 V8_WARN_UNUSED_RESULT
6457 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
6458  v8::NewStringType type,
6459  i::Vector<const char> string) {
6460  if (type == v8::NewStringType::kInternalized) {
6461  return factory->InternalizeUtf8String(string);
6462  }
6463  return factory->NewStringFromUtf8(string);
6464 }
6465 
6466 V8_WARN_UNUSED_RESULT
6467 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
6468  v8::NewStringType type,
6469  i::Vector<const uint8_t> string) {
6470  if (type == v8::NewStringType::kInternalized) {
6471  return factory->InternalizeOneByteString(string);
6472  }
6473  return factory->NewStringFromOneByte(string);
6474 }
6475 
6476 V8_WARN_UNUSED_RESULT
6477 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
6478  v8::NewStringType type,
6479  i::Vector<const uint16_t> string) {
6480  if (type == v8::NewStringType::kInternalized) {
6481  return factory->InternalizeTwoByteString(string);
6482  }
6483  return factory->NewStringFromTwoByte(string);
6484 }
6485 
6486 
6487 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
6488 
6489 } // anonymous namespace
6490 
6491 // TODO(dcarney): throw a context free exception.
6492 #define NEW_STRING(isolate, class_name, function_name, Char, data, type, \
6493  length) \
6494  MaybeLocal<String> result; \
6495  if (length == 0) { \
6496  result = String::Empty(isolate); \
6497  } else if (length > i::String::kMaxLength) { \
6498  result = MaybeLocal<String>(); \
6499  } else { \
6500  i::Isolate* i_isolate = reinterpret_cast<internal::Isolate*>(isolate); \
6501  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate); \
6502  LOG_API(i_isolate, class_name, function_name); \
6503  if (length < 0) length = StringLength(data); \
6504  i::Handle<i::String> handle_result = \
6505  NewString(i_isolate->factory(), type, \
6506  i::Vector<const Char>(data, length)) \
6507  .ToHandleChecked(); \
6508  result = Utils::ToLocal(handle_result); \
6509  }
6510 
6512  const char* data,
6513  NewStringType type,
6514  int length) {
6515  NEW_STRING(isolate, String, NewFromUtf8, char, data,
6516  static_cast<v8::NewStringType>(type), length);
6517  RETURN_TO_LOCAL_UNCHECKED(result, String);
6518 }
6519 
6520 
6521 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
6522  v8::NewStringType type, int length) {
6523  NEW_STRING(isolate, String, NewFromUtf8, char, data, type, length);
6524  return result;
6525 }
6526 
6527 
6528 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
6529  v8::NewStringType type, int length) {
6530  NEW_STRING(isolate, String, NewFromOneByte, uint8_t, data, type, length);
6531  return result;
6532 }
6533 
6534 
6536  const uint16_t* data,
6537  NewStringType type,
6538  int length) {
6539  NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data,
6540  static_cast<v8::NewStringType>(type), length);
6541  RETURN_TO_LOCAL_UNCHECKED(result, String);
6542 }
6543 
6544 
6546  const uint16_t* data,
6547  v8::NewStringType type, int length) {
6548  NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data, type, length);
6549  return result;
6550 }
6551 
6553  Local<String> right) {
6554  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
6555  i::Handle<i::String> left_string = Utils::OpenHandle(*left);
6556  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
6557  LOG_API(isolate, String, Concat);
6558  i::Handle<i::String> right_string = Utils::OpenHandle(*right);
6559  // If we are steering towards a range error, do not wait for the error to be
6560  // thrown, and return the null handle instead.
6561  if (left_string->length() + right_string->length() > i::String::kMaxLength) {
6562  return Local<String>();
6563  }
6564  i::Handle<i::String> result = isolate->factory()->NewConsString(
6565  left_string, right_string).ToHandleChecked();
6566  return Utils::ToLocal(result);
6567 }
6568 
6570  Isolate* isolate, v8::String::ExternalStringResource* resource) {
6571  CHECK(resource && resource->data());
6572  // TODO(dcarney): throw a context free exception.
6573  if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
6574  return MaybeLocal<String>();
6575  }
6576  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6577  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6578  LOG_API(i_isolate, String, NewExternalTwoByte);
6579  if (resource->length() > 0) {
6580  i::Handle<i::String> string = i_isolate->factory()
6581  ->NewExternalStringFromTwoByte(resource)
6582  .ToHandleChecked();
6583  return Utils::ToLocal(string);
6584  } else {
6585  // The resource isn't going to be used, free it immediately.
6586  resource->Dispose();
6587  return Utils::ToLocal(i_isolate->factory()->empty_string());
6588  }
6589 }
6590 
6591 
6592 MaybeLocal<String> v8::String::NewExternalOneByte(
6593  Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
6594  CHECK(resource && resource->data());
6595  // TODO(dcarney): throw a context free exception.
6596  if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
6597  return MaybeLocal<String>();
6598  }
6599  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6600  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6601  LOG_API(i_isolate, String, NewExternalOneByte);
6602  if (resource->length() > 0) {
6603  i::Handle<i::String> string = i_isolate->factory()
6604  ->NewExternalStringFromOneByte(resource)
6605  .ToHandleChecked();
6606  return Utils::ToLocal(string);
6607  } else {
6608  // The resource isn't going to be used, free it immediately.
6609  resource->Dispose();
6610  return Utils::ToLocal(i_isolate->factory()->empty_string());
6611  }
6612 }
6613 
6614 
6615 Local<String> v8::String::NewExternal(
6616  Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
6617  RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
6618 }
6619 
6620 
6622  i::DisallowHeapAllocation no_allocation;
6623 
6624  i::String obj = *Utils::OpenHandle(this);
6625 
6626  if (obj->IsThinString()) {
6627  obj = i::ThinString::cast(obj)->actual();
6628  }
6629 
6630  if (!obj->SupportsExternalization()) {
6631  return false;
6632  }
6633 
6634  // It is safe to call FromWritable because SupportsExternalization already
6635  // checked that the object is writable.
6636  i::Isolate* isolate;
6637  i::Isolate::FromWritableHeapObject(obj, &isolate);
6638  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
6639 
6640  CHECK(resource && resource->data());
6641 
6642  bool result = obj->MakeExternal(resource);
6643  DCHECK(result);
6644  DCHECK(obj->IsExternalString());
6645  return result;
6646 }
6647 
6648 
6651  i::DisallowHeapAllocation no_allocation;
6652 
6653  i::String obj = *Utils::OpenHandle(this);
6654 
6655  if (obj->IsThinString()) {
6656  obj = i::ThinString::cast(obj)->actual();
6657  }
6658 
6659  if (!obj->SupportsExternalization()) {
6660  return false;
6661  }
6662 
6663  // It is safe to call FromWritable because SupportsExternalization already
6664  // checked that the object is writable.
6665  i::Isolate* isolate;
6666  i::Isolate::FromWritableHeapObject(obj, &isolate);
6667  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
6668 
6669  CHECK(resource && resource->data());
6670 
6671  bool result = obj->MakeExternal(resource);
6672  DCHECK(result);
6673  DCHECK(obj->IsExternalString());
6674  return result;
6675 }
6676 
6677 
6679  i::DisallowHeapAllocation no_allocation;
6680  i::String obj = *Utils::OpenHandle(this);
6681 
6682  if (obj->IsThinString()) {
6683  obj = i::ThinString::cast(obj)->actual();
6684  }
6685 
6686  if (!obj->SupportsExternalization()) {
6687  return false;
6688  }
6689 
6690  // Only old space strings should be externalized.
6691  return !i::Heap::InNewSpace(obj);
6692 }
6693 
6695  auto self = Utils::OpenHandle(this);
6696  auto other = Utils::OpenHandle(*that);
6697  return self->Equals(*other);
6698 }
6699 
6701  i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
6702  return reinterpret_cast<Isolate*>(i_isolate);
6703 }
6704 
6705 
6706 Local<v8::Object> v8::Object::New(Isolate* isolate) {
6707  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6708  LOG_API(i_isolate, Object, New);
6709  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6711  i_isolate->factory()->NewJSObject(i_isolate->object_function());
6712  return Utils::ToLocal(obj);
6713 }
6714 
6715 Local<v8::Object> v8::Object::New(Isolate* isolate,
6716  Local<Value> prototype_or_null,
6717  Local<Name>* names, Local<Value>* values,
6718  size_t length) {
6719  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6720  i::Handle<i::Object> proto = Utils::OpenHandle(*prototype_or_null);
6721  if (!Utils::ApiCheck(proto->IsNull() || proto->IsJSReceiver(),
6722  "v8::Object::New", "prototype must be null or object")) {
6723  return Local<v8::Object>();
6724  }
6725  LOG_API(i_isolate, Object, New);
6726  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6727 
6728  // We assume that this API is mostly used to create objects with named
6729  // properties, and so we default to creating a properties backing store
6730  // large enough to hold all of them, while we start with no elements
6731  // (see http://bit.ly/v8-fast-object-create-cpp for the motivation).
6732  i::Handle<i::NameDictionary> properties =
6733  i::NameDictionary::New(i_isolate, static_cast<int>(length));
6734  i::Handle<i::FixedArrayBase> elements =
6735  i_isolate->factory()->empty_fixed_array();
6736  for (size_t i = 0; i < length; ++i) {
6737  i::Handle<i::Name> name = Utils::OpenHandle(*names[i]);
6738  i::Handle<i::Object> value = Utils::OpenHandle(*values[i]);
6739 
6740  // See if the {name} is a valid array index, in which case we need to
6741  // add the {name}/{value} pair to the {elements}, otherwise they end
6742  // up in the {properties} backing store.
6743  uint32_t index;
6744  if (name->AsArrayIndex(&index)) {
6745  // If this is the first element, allocate a proper
6746  // dictionary elements backing store for {elements}.
6747  if (!elements->IsNumberDictionary()) {
6748  // TODO(3770): Drop explicit cast.
6749  elements = i::Handle<i::FixedArrayBase>(
6750  i::NumberDictionary::New(i_isolate, static_cast<int>(length))
6751  .location());
6752  }
6753  // TODO(3770): Drop explicit cast.
6754  elements = i::Handle<i::FixedArrayBase>(
6755  i::NumberDictionary::Set(
6756  i_isolate, i::Handle<i::NumberDictionary>::cast(elements), index,
6757  value)
6758  .location());
6759  } else {
6760  // Internalize the {name} first.
6761  name = i_isolate->factory()->InternalizeName(name);
6762  int const entry = properties->FindEntry(i_isolate, name);
6763  if (entry == i::NameDictionary::kNotFound) {
6764  // Add the {name}/{value} pair as a new entry.
6765  properties = i::NameDictionary::Add(i_isolate, properties, name, value,
6766  i::PropertyDetails::Empty());
6767  } else {
6768  // Overwrite the {entry} with the {value}.
6769  properties->ValueAtPut(entry, *value);
6770  }
6771  }
6772  }
6774  i_isolate->factory()->NewSlowJSObjectWithPropertiesAndElements(
6775  proto, properties, elements);
6776  return Utils::ToLocal(obj);
6777 }
6778 
6779 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
6780  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6781  LOG_API(i_isolate, NumberObject, New);
6782  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6783  i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
6784  i::Handle<i::Object> obj =
6785  i::Object::ToObject(i_isolate, number).ToHandleChecked();
6786  return Utils::ToLocal(obj);
6787 }
6788 
6789 
6790 double v8::NumberObject::ValueOf() const {
6791  i::Handle<i::Object> obj = Utils::OpenHandle(this);
6793  i::Isolate* isolate = jsvalue->GetIsolate();
6794  LOG_API(isolate, NumberObject, NumberValue);
6795  return jsvalue->value()->Number();
6796 }
6797 
6798 Local<v8::Value> v8::BigIntObject::New(Isolate* isolate, int64_t value) {
6799  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6800  LOG_API(i_isolate, BigIntObject, New);
6801  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6802  i::Handle<i::Object> bigint = i::BigInt::FromInt64(i_isolate, value);
6803  i::Handle<i::Object> obj =
6804  i::Object::ToObject(i_isolate, bigint).ToHandleChecked();
6805  return Utils::ToLocal(obj);
6806 }
6807 
6808 Local<v8::BigInt> v8::BigIntObject::ValueOf() const {
6809  i::Handle<i::Object> obj = Utils::OpenHandle(this);
6811  i::Isolate* isolate = jsvalue->GetIsolate();
6812  LOG_API(isolate, BigIntObject, BigIntValue);
6813  return Utils::ToLocal(
6814  i::Handle<i::BigInt>(i::BigInt::cast(jsvalue->value()), isolate));
6815 }
6816 
6817 Local<v8::Value> v8::BooleanObject::New(Isolate* isolate, bool value) {
6818  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6819  LOG_API(i_isolate, BooleanObject, New);
6820  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6821  i::Handle<i::Object> boolean(value
6822  ? i::ReadOnlyRoots(i_isolate).true_value()
6823  : i::ReadOnlyRoots(i_isolate).false_value(),
6824  i_isolate);
6825  i::Handle<i::Object> obj =
6826  i::Object::ToObject(i_isolate, boolean).ToHandleChecked();
6827  return Utils::ToLocal(obj);
6828 }
6829 
6830 
6831 bool v8::BooleanObject::ValueOf() const {
6832  i::Handle<i::Object> obj = Utils::OpenHandle(this);
6834  i::Isolate* isolate = jsvalue->GetIsolate();
6835  LOG_API(isolate, BooleanObject, BooleanValue);
6836  return jsvalue->value()->IsTrue(isolate);
6837 }
6838 
6839 
6840 Local<v8::Value> v8::StringObject::New(Isolate* v8_isolate,
6841  Local<String> value) {
6842  i::Handle<i::String> string = Utils::OpenHandle(*value);
6843  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
6844  LOG_API(isolate, StringObject, New);
6845  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
6846  i::Handle<i::Object> obj =
6847  i::Object::ToObject(isolate, string).ToHandleChecked();
6848  return Utils::ToLocal(obj);
6849 }
6850 
6851 
6852 Local<v8::String> v8::StringObject::ValueOf() const {
6853  i::Handle<i::Object> obj = Utils::OpenHandle(this);
6855  i::Isolate* isolate = jsvalue->GetIsolate();
6856  LOG_API(isolate, StringObject, StringValue);
6857  return Utils::ToLocal(
6858  i::Handle<i::String>(i::String::cast(jsvalue->value()), isolate));
6859 }
6860 
6861 
6862 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
6863  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6864  LOG_API(i_isolate, SymbolObject, New);
6865  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6866  i::Handle<i::Object> obj = i::Object::ToObject(
6867  i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
6868  return Utils::ToLocal(obj);
6869 }
6870 
6871 
6872 Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
6873  i::Handle<i::Object> obj = Utils::OpenHandle(this);
6875  i::Isolate* isolate = jsvalue->GetIsolate();
6876  LOG_API(isolate, SymbolObject, SymbolValue);
6877  return Utils::ToLocal(
6878  i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value()), isolate));
6879 }
6880 
6881 
6882 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
6883  if (std::isnan(time)) {
6884  // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6885  time = std::numeric_limits<double>::quiet_NaN();
6886  }
6887  PREPARE_FOR_EXECUTION(context, Date, New, Value);
6888  Local<Value> result;
6889  has_pending_exception = !ToLocal<Value>(
6890  i::JSDate::New(isolate->date_function(), isolate->date_function(), time),
6891  &result);
6892  RETURN_ON_FAILED_EXECUTION(Value);
6893  RETURN_ESCAPED(result);
6894 }
6895 
6896 
6897 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
6898  auto context = isolate->GetCurrentContext();
6899  RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value);
6900 }
6901 
6902 
6903 double v8::Date::ValueOf() const {
6904  i::Handle<i::Object> obj = Utils::OpenHandle(this);
6906  i::Isolate* isolate = jsdate->GetIsolate();
6907  LOG_API(isolate, Date, NumberValue);
6908  return jsdate->value()->Number();
6909 }
6910 
6911 
6913  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6914  LOG_API(i_isolate, Date, DateTimeConfigurationChangeNotification);
6915  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6916  i_isolate->date_cache()->ResetDateCache();
6917 #ifdef V8_INTL_SUPPORT
6918  i_isolate->clear_cached_icu_object(
6919  i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormat);
6920  i_isolate->clear_cached_icu_object(
6921  i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForTime);
6922  i_isolate->clear_cached_icu_object(
6923  i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForDate);
6924 #endif // V8_INTL_SUPPORT
6925 }
6926 
6927 
6929  Local<String> pattern, Flags flags) {
6930  PREPARE_FOR_EXECUTION(context, RegExp, New, RegExp);
6931  Local<v8::RegExp> result;
6932  has_pending_exception =
6933  !ToLocal<RegExp>(i::JSRegExp::New(isolate, Utils::OpenHandle(*pattern),
6934  static_cast<i::JSRegExp::Flags>(flags)),
6935  &result);
6936  RETURN_ON_FAILED_EXECUTION(RegExp);
6937  RETURN_ESCAPED(result);
6938 }
6939 
6940 
6942  i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6943  return Utils::ToLocal(
6944  i::Handle<i::String>(obj->Pattern(), obj->GetIsolate()));
6945 }
6946 
6947 
6948 // Assert that the static flags cast in GetFlags is valid.
6949 #define REGEXP_FLAG_ASSERT_EQ(flag) \
6950  STATIC_ASSERT(static_cast<int>(v8::RegExp::flag) == \
6951  static_cast<int>(i::JSRegExp::flag))
6952 REGEXP_FLAG_ASSERT_EQ(kNone);
6953 REGEXP_FLAG_ASSERT_EQ(kGlobal);
6954 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase);
6955 REGEXP_FLAG_ASSERT_EQ(kMultiline);
6956 REGEXP_FLAG_ASSERT_EQ(kSticky);
6957 REGEXP_FLAG_ASSERT_EQ(kUnicode);
6958 #undef REGEXP_FLAG_ASSERT_EQ
6959 
6961  i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6962  return RegExp::Flags(static_cast<int>(obj->GetFlags()));
6963 }
6964 
6965 
6966 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
6967  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6968  LOG_API(i_isolate, Array, New);
6969  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6970  int real_length = length > 0 ? length : 0;
6971  i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
6972  i::Handle<i::Object> length_obj =
6973  i_isolate->factory()->NewNumberFromInt(real_length);
6974  obj->set_length(*length_obj);
6975  return Utils::ToLocal(obj);
6976 }
6977 
6978 Local<v8::Array> v8::Array::New(Isolate* isolate, Local<Value>* elements,
6979  size_t length) {
6980  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6981  i::Factory* factory = i_isolate->factory();
6982  LOG_API(i_isolate, Array, New);
6983  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
6984  int len = static_cast<int>(length);
6985 
6986  i::Handle<i::FixedArray> result = factory->NewFixedArray(len);
6987  for (int i = 0; i < len; i++) {
6988  i::Handle<i::Object> element = Utils::OpenHandle(*elements[i]);
6989  result->set(i, *element);
6990  }
6991 
6992  return Utils::ToLocal(
6993  factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS, len));
6994 }
6995 
6996 uint32_t v8::Array::Length() const {
6997  i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
6998  i::Object* length = obj->length();
6999  if (length->IsSmi()) {
7000  return i::Smi::ToInt(length);
7001  } else {
7002  return static_cast<uint32_t>(length->Number());
7003  }
7004 }
7005 
7006 
7007 Local<v8::Map> v8::Map::New(Isolate* isolate) {
7008  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7009  LOG_API(i_isolate, Map, New);
7010  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7011  i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
7012  return Utils::ToLocal(obj);
7013 }
7014 
7015 
7016 size_t v8::Map::Size() const {
7017  i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
7018  return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
7019 }
7020 
7021 
7022 void Map::Clear() {
7023  auto self = Utils::OpenHandle(this);
7024  i::Isolate* isolate = self->GetIsolate();
7025  LOG_API(isolate, Map, Clear);
7026  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7027  i::JSMap::Clear(isolate, self);
7028 }
7029 
7030 
7031 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
7032  PREPARE_FOR_EXECUTION(context, Map, Get, Value);
7033  auto self = Utils::OpenHandle(this);
7034  Local<Value> result;
7035  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
7036  has_pending_exception =
7037  !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
7038  arraysize(argv), argv),
7039  &result);
7040  RETURN_ON_FAILED_EXECUTION(Value);
7041  RETURN_ESCAPED(result);
7042 }
7043 
7044 
7045 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
7046  Local<Value> value) {
7047  PREPARE_FOR_EXECUTION(context, Map, Set, Map);
7048  auto self = Utils::OpenHandle(this);
7049  i::Handle<i::Object> result;
7050  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
7051  Utils::OpenHandle(*value)};
7052  has_pending_exception = !i::Execution::Call(isolate, isolate->map_set(), self,
7053  arraysize(argv), argv)
7054  .ToHandle(&result);
7055  RETURN_ON_FAILED_EXECUTION(Map);
7056  RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
7057 }
7058 
7059 
7060 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
7061  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
7062  ENTER_V8(isolate, context, Map, Has, Nothing<bool>(), i::HandleScope);
7063  auto self = Utils::OpenHandle(this);
7064  i::Handle<i::Object> result;
7065  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
7066  has_pending_exception = !i::Execution::Call(isolate, isolate->map_has(), self,
7067  arraysize(argv), argv)
7068  .ToHandle(&result);
7069  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
7070  return Just(result->IsTrue(isolate));
7071 }
7072 
7073 
7074 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
7075  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
7076  ENTER_V8(isolate, context, Map, Delete, Nothing<bool>(), i::HandleScope);
7077  auto self = Utils::OpenHandle(this);
7078  i::Handle<i::Object> result;
7079  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
7080  has_pending_exception = !i::Execution::Call(isolate, isolate->map_delete(),
7081  self, arraysize(argv), argv)
7082  .ToHandle(&result);
7083  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
7084  return Just(result->IsTrue(isolate));
7085 }
7086 
7087 namespace {
7088 
7089 enum class MapAsArrayKind {
7090  kEntries = i::JS_MAP_KEY_VALUE_ITERATOR_TYPE,
7091  kKeys = i::JS_MAP_KEY_ITERATOR_TYPE,
7092  kValues = i::JS_MAP_VALUE_ITERATOR_TYPE
7093 };
7094 
7095 i::Handle<i::JSArray> MapAsArray(i::Isolate* isolate, i::Object* table_obj,
7096  int offset, MapAsArrayKind kind) {
7097  i::Factory* factory = isolate->factory();
7098  i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(table_obj),
7099  isolate);
7100  const bool collect_keys =
7101  kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kKeys;
7102  const bool collect_values =
7103  kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kValues;
7104  int capacity = table->UsedCapacity();
7105  int max_length =
7106  (capacity - offset) * ((collect_keys && collect_values) ? 2 : 1);
7107  i::Handle<i::FixedArray> result = factory->NewFixedArray(max_length);
7108  int result_index = 0;
7109  {
7111  i::Oddball* the_hole = i::ReadOnlyRoots(isolate).the_hole_value();
7112  for (int i = offset; i < capacity; ++i) {
7113  i::Object* key = table->KeyAt(i);
7114  if (key == the_hole) continue;
7115  if (collect_keys) result->set(result_index++, key);
7116  if (collect_values) result->set(result_index++, table->ValueAt(i));
7117  }
7118  }
7119  DCHECK_GE(max_length, result_index);
7120  if (result_index == 0) return factory->NewJSArray(0);
7121  result->Shrink(isolate, result_index);
7122  return factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS,
7123  result_index);
7124 }
7125 
7126 } // namespace
7127 
7129  i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
7130  i::Isolate* isolate = obj->GetIsolate();
7131  LOG_API(isolate, Map, AsArray);
7132  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7133  return Utils::ToLocal(
7134  MapAsArray(isolate, obj->table(), 0, MapAsArrayKind::kEntries));
7135 }
7136 
7137 
7138 Local<v8::Set> v8::Set::New(Isolate* isolate) {
7139  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7140  LOG_API(i_isolate, Set, New);
7141  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7142  i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
7143  return Utils::ToLocal(obj);
7144 }
7145 
7146 
7147 size_t v8::Set::Size() const {
7148  i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
7149  return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
7150 }
7151 
7152 
7153 void Set::Clear() {
7154  auto self = Utils::OpenHandle(this);
7155  i::Isolate* isolate = self->GetIsolate();
7156  LOG_API(isolate, Set, Clear);
7157  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7158  i::JSSet::Clear(isolate, self);
7159 }
7160 
7161 
7162 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
7163  PREPARE_FOR_EXECUTION(context, Set, Add, Set);
7164  auto self = Utils::OpenHandle(this);
7165  i::Handle<i::Object> result;
7166  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
7167  has_pending_exception = !i::Execution::Call(isolate, isolate->set_add(), self,
7168  arraysize(argv), argv)
7169  .ToHandle(&result);
7170  RETURN_ON_FAILED_EXECUTION(Set);
7171  RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
7172 }
7173 
7174 
7175 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
7176  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
7177  ENTER_V8(isolate, context, Set, Has, Nothing<bool>(), i::HandleScope);
7178  auto self = Utils::OpenHandle(this);
7179  i::Handle<i::Object> result;
7180  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
7181  has_pending_exception = !i::Execution::Call(isolate, isolate->set_has(), self,
7182  arraysize(argv), argv)
7183  .ToHandle(&result);
7184  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
7185  return Just(result->IsTrue(isolate));
7186 }
7187 
7188 
7189 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
7190  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
7191  ENTER_V8(isolate, context, Set, Delete, Nothing<bool>(), i::HandleScope);
7192  auto self = Utils::OpenHandle(this);
7193  i::Handle<i::Object> result;
7194  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
7195  has_pending_exception = !i::Execution::Call(isolate, isolate->set_delete(),
7196  self, arraysize(argv), argv)
7197  .ToHandle(&result);
7198  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
7199  return Just(result->IsTrue(isolate));
7200 }
7201 
7202 namespace {
7203 i::Handle<i::JSArray> SetAsArray(i::Isolate* isolate, i::Object* table_obj,
7204  int offset) {
7205  i::Factory* factory = isolate->factory();
7206  i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(table_obj),
7207  isolate);
7208  // Elements skipped by |offset| may already be deleted.
7209  int capacity = table->UsedCapacity();
7210  int max_length = capacity - offset;
7211  if (max_length == 0) return factory->NewJSArray(0);
7212  i::Handle<i::FixedArray> result = factory->NewFixedArray(max_length);
7213  int result_index = 0;
7214  {
7216  i::Oddball* the_hole = i::ReadOnlyRoots(isolate).the_hole_value();
7217  for (int i = offset; i < capacity; ++i) {
7218  i::Object* key = table->KeyAt(i);
7219  if (key == the_hole) continue;
7220  result->set(result_index++, key);
7221  }
7222  }
7223  DCHECK_GE(max_length, result_index);
7224  if (result_index == 0) return factory->NewJSArray(0);
7225  result->Shrink(isolate, result_index);
7226  return factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS,
7227  result_index);
7228 }
7229 } // namespace
7230 
7232  i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
7233  i::Isolate* isolate = obj->GetIsolate();
7234  LOG_API(isolate, Set, AsArray);
7235  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7236  return Utils::ToLocal(SetAsArray(isolate, obj->table(), 0));
7237 }
7238 
7239 
7241  PREPARE_FOR_EXECUTION(context, Promise_Resolver, New, Resolver);
7242  Local<Promise::Resolver> result;
7243  has_pending_exception =
7244  !ToLocal<Promise::Resolver>(isolate->factory()->NewJSPromise(), &result);
7245  RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
7246  RETURN_ESCAPED(result);
7247 }
7248 
7249 
7251  i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
7252  return Local<Promise>::Cast(Utils::ToLocal(promise));
7253 }
7254 
7255 
7257  Local<Value> value) {
7258  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
7259  ENTER_V8(isolate, context, Promise_Resolver, Resolve, Nothing<bool>(),
7260  i::HandleScope);
7261  auto self = Utils::OpenHandle(this);
7262  auto promise = i::Handle<i::JSPromise>::cast(self);
7263 
7264  if (promise->status() != Promise::kPending) {
7265  return Just(true);
7266  }
7267 
7268  has_pending_exception =
7269  i::JSPromise::Resolve(promise, Utils::OpenHandle(*value)).is_null();
7270  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
7271  return Just(true);
7272 }
7273 
7274 
7275 Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
7276  Local<Value> value) {
7277  auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
7278  ENTER_V8(isolate, context, Promise_Resolver, Reject, Nothing<bool>(),
7279  i::HandleScope);
7280  auto self = Utils::OpenHandle(this);
7281  auto promise = i::Handle<i::JSPromise>::cast(self);
7282 
7283  if (promise->status() != Promise::kPending) {
7284  return Just(true);
7285  }
7286 
7287  has_pending_exception =
7288  i::JSPromise::Reject(promise, Utils::OpenHandle(*value)).is_null();
7289  RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
7290  return Just(true);
7291 }
7292 
7293 
7295  Local<Function> handler) {
7296  PREPARE_FOR_EXECUTION(context, Promise, Catch, Promise);
7297  auto self = Utils::OpenHandle(this);
7298  i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
7299  i::Handle<i::Object> result;
7300  has_pending_exception = !i::Execution::Call(isolate, isolate->promise_catch(),
7301  self, arraysize(argv), argv)
7302  .ToHandle(&result);
7303  RETURN_ON_FAILED_EXECUTION(Promise);
7304  RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
7305 }
7306 
7307 
7308 MaybeLocal<Promise> Promise::Then(Local<Context> context,
7309  Local<Function> handler) {
7310  PREPARE_FOR_EXECUTION(context, Promise, Then, Promise);
7311  auto self = Utils::OpenHandle(this);
7312  i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
7313  i::Handle<i::Object> result;
7314  has_pending_exception = !i::Execution::Call(isolate, isolate->promise_then(),
7315  self, arraysize(argv), argv)
7316  .ToHandle(&result);
7317  RETURN_ON_FAILED_EXECUTION(Promise);
7318  RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
7319 }
7320 
7321 
7323  i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
7324  i::Isolate* isolate = promise->GetIsolate();
7325  LOG_API(isolate, Promise, HasRejectHandler);
7326  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7327  if (promise->IsJSPromise()) {
7329  return js_promise->has_handler();
7330  }
7331  return false;
7332 }
7333 
7335  i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
7336  i::Isolate* isolate = promise->GetIsolate();
7337  LOG_API(isolate, Promise, Result);
7339  Utils::ApiCheck(js_promise->status() != kPending, "v8_Promise_Result",
7340  "Promise is still pending");
7341  i::Handle<i::Object> result(js_promise->result(), isolate);
7342  return Utils::ToLocal(result);
7343 }
7344 
7346  i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
7347  i::Isolate* isolate = promise->GetIsolate();
7348  LOG_API(isolate, Promise, Status);
7350  return static_cast<PromiseState>(js_promise->status());
7351 }
7352 
7354  i::Handle<i::JSPromise> js_promise = Utils::OpenHandle(this);
7355  js_promise->set_has_handler(true);
7356 }
7357 
7358 Local<Value> Proxy::GetTarget() {
7359  i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
7360  i::Handle<i::Object> target(self->target(), self->GetIsolate());
7361  return Utils::ToLocal(target);
7362 }
7363 
7364 
7365 Local<Value> Proxy::GetHandler() {
7366  i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
7367  i::Handle<i::Object> handler(self->handler(), self->GetIsolate());
7368  return Utils::ToLocal(handler);
7369 }
7370 
7371 
7372 bool Proxy::IsRevoked() {
7373  i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
7374  return self->IsRevoked();
7375 }
7376 
7377 
7378 void Proxy::Revoke() {
7379  i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
7380  i::JSProxy::Revoke(self);
7381 }
7382 
7383 
7385  Local<Object> local_handler) {
7386  PREPARE_FOR_EXECUTION(context, Proxy, New, Proxy);
7387  i::Handle<i::JSReceiver> target = Utils::OpenHandle(*local_target);
7388  i::Handle<i::JSReceiver> handler = Utils::OpenHandle(*local_handler);
7389  Local<Proxy> result;
7390  has_pending_exception =
7391  !ToLocal<Proxy>(i::JSProxy::New(isolate, target, handler), &result);
7392  RETURN_ON_FAILED_EXECUTION(Proxy);
7393  RETURN_ESCAPED(result);
7394 }
7395 
7398  i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
7399  i::Vector<const uint8_t> bytes_vec = obj->native_module()->wire_bytes();
7400  return {bytes_vec.start(), bytes_vec.size()};
7401 }
7402 
7405  if (i::FLAG_wasm_shared_code) {
7407  i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
7408  return TransferrableModule(obj->managed_native_module()->get());
7409  } else {
7410  WasmCompiledModule::SerializedModule serialized_module = Serialize();
7411  BufferReference wire_bytes_ref = GetWasmWireBytesRef();
7412  size_t wire_size = wire_bytes_ref.size;
7413  std::unique_ptr<uint8_t[]> wire_bytes_copy(new uint8_t[wire_size]);
7414  memcpy(wire_bytes_copy.get(), wire_bytes_ref.start, wire_size);
7415  return TransferrableModule(std::move(serialized_module),
7416  {std::move(wire_bytes_copy), wire_size});
7417  }
7418 }
7419 
7421  Isolate* isolate,
7422  const WasmCompiledModule::TransferrableModule& transferrable_module) {
7423  if (i::FLAG_wasm_shared_code) {
7424  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7425  i::Handle<i::WasmModuleObject> module_object =
7426  i_isolate->wasm_engine()->ImportNativeModule(
7427  i_isolate, transferrable_module.shared_module_);
7429  Utils::ToLocal(i::Handle<i::JSObject>::cast(module_object)));
7430  } else {
7431  return Deserialize(isolate, AsReference(transferrable_module.serialized_),
7432  AsReference(transferrable_module.wire_bytes_));
7433  }
7434 }
7435 
7436 WasmCompiledModule::SerializedModule WasmCompiledModule::Serialize() {
7438  i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
7439  i::wasm::NativeModule* native_module = obj->native_module();
7440  i::wasm::WasmSerializer wasm_serializer(obj->GetIsolate(), native_module);
7441  size_t buffer_size = wasm_serializer.GetSerializedNativeModuleSize();
7442  std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
7443  if (wasm_serializer.SerializeNativeModule({buffer.get(), buffer_size}))
7444  return {std::move(buffer), buffer_size};
7445  return {};
7446 }
7447 
7448 MaybeLocal<WasmCompiledModule> WasmCompiledModule::Deserialize(
7449  Isolate* isolate, WasmCompiledModule::BufferReference serialized_module,
7451  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7452  i::MaybeHandle<i::WasmModuleObject> maybe_module_object =
7453  i::wasm::DeserializeNativeModule(
7454  i_isolate, {serialized_module.start, serialized_module.size},
7455  {wire_bytes.start, wire_bytes.size});
7456  i::Handle<i::WasmModuleObject> module_object;
7457  if (!maybe_module_object.ToHandle(&module_object)) {
7458  return MaybeLocal<WasmCompiledModule>();
7459  }
7461  Utils::ToLocal(i::Handle<i::JSObject>::cast(module_object)));
7462 }
7463 
7465  Isolate* isolate, WasmCompiledModule::BufferReference serialized_module,
7468  Deserialize(isolate, serialized_module, wire_bytes);
7469  if (!ret.IsEmpty()) {
7470  return ret;
7471  }
7472  return Compile(isolate, wire_bytes.start, wire_bytes.size);
7473 }
7474 
7475 MaybeLocal<WasmCompiledModule> WasmCompiledModule::Compile(Isolate* isolate,
7476  const uint8_t* start,
7477  size_t length) {
7478  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7479  i::wasm::ErrorThrower thrower(i_isolate, "WasmCompiledModule::Compile()");
7480  if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
7482  }
7483  auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
7484  i::MaybeHandle<i::JSObject> maybe_compiled =
7485  i_isolate->wasm_engine()->SyncCompile(
7486  i_isolate, enabled_features, &thrower,
7487  i::wasm::ModuleWireBytes(start, start + length));
7488  if (maybe_compiled.is_null()) return MaybeLocal<WasmCompiledModule>();
7490  Utils::ToLocal(maybe_compiled.ToHandleChecked()));
7491 }
7492 
7493 // Resolves the result of streaming compilation.
7494 // TODO(ahaas): Refactor the streaming compilation API so that this class can
7495 // move to wasm-js.cc.
7496 class AsyncCompilationResolver : public i::wasm::CompilationResultResolver {
7497  public:
7498  AsyncCompilationResolver(Isolate* isolate, Local<Promise> promise)
7499  : promise_(
7500  reinterpret_cast<i::Isolate*>(isolate)->global_handles()->Create(
7501  *Utils::OpenHandle(*promise))) {}
7502 
7503  ~AsyncCompilationResolver() override {
7504  i::GlobalHandles::Destroy(promise_.location());
7505  }
7506 
7507  void OnCompilationSucceeded(i::Handle<i::WasmModuleObject> result) override {
7508  i::MaybeHandle<i::Object> promise_result =
7509  i::JSPromise::Resolve(promise_, result);
7510  CHECK_EQ(promise_result.is_null(),
7511  promise_->GetIsolate()->has_pending_exception());
7512  }
7513 
7514  void OnCompilationFailed(i::Handle<i::Object> error_reason) override {
7515  i::MaybeHandle<i::Object> promise_result =
7516  i::JSPromise::Reject(promise_, error_reason);
7517  CHECK_EQ(promise_result.is_null(),
7518  promise_->GetIsolate()->has_pending_exception());
7519  }
7520 
7521  private:
7522  i::Handle<i::JSPromise> promise_;
7523 };
7524 
7525 WasmModuleObjectBuilderStreaming::WasmModuleObjectBuilderStreaming(
7526  Isolate* isolate) {
7527  USE(isolate_);
7528 }
7529 
7530 Local<Promise> WasmModuleObjectBuilderStreaming::GetPromise() { return {}; }
7531 
7533  size_t size) {
7534 }
7535 
7536 void WasmModuleObjectBuilderStreaming::Finish() {
7537 }
7538 
7540 }
7541 
7542 // static
7544  return new ArrayBufferAllocator();
7545 }
7546 
7548  return Utils::OpenHandle(this)->is_external();
7549 }
7550 
7551 
7553  return Utils::OpenHandle(this)->is_neuterable();
7554 }
7555 
7556 
7558  i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
7559  i::Isolate* isolate = self->GetIsolate();
7560  Utils::ApiCheck(!self->is_external(), "v8_ArrayBuffer_Externalize",
7561  "ArrayBuffer already externalized");
7562  self->set_is_external(true);
7563 
7564  const v8::ArrayBuffer::Contents contents = GetContents();
7565  isolate->heap()->UnregisterArrayBuffer(*self);
7566 
7567  // A regular copy is good enough. No move semantics needed.
7568  return contents;
7569 }
7570 
7571 v8::ArrayBuffer::Contents::Contents(void* data, size_t byte_length,
7572  void* allocation_base,
7573  size_t allocation_length,
7574  Allocator::AllocationMode allocation_mode,
7575  DeleterCallback deleter, void* deleter_data)
7576  : data_(data),
7577  byte_length_(byte_length),
7578  allocation_base_(allocation_base),
7579  allocation_length_(allocation_length),
7580  allocation_mode_(allocation_mode),
7581  deleter_(deleter),
7582  deleter_data_(deleter_data) {
7583  DCHECK_LE(allocation_base_, data_);
7584  DCHECK_LE(byte_length_, allocation_length_);
7585 }
7586 
7587 void WasmMemoryDeleter(void* buffer, size_t lenght, void* info) {
7588  internal::wasm::WasmEngine* engine =
7589  reinterpret_cast<internal::wasm::WasmEngine*>(info);
7590  CHECK(engine->memory_tracker()->FreeMemoryIfIsWasmMemory(nullptr, buffer));
7591 }
7592 
7593 void ArrayBufferDeleter(void* buffer, size_t length, void* info) {
7594  v8::ArrayBuffer::Allocator* allocator =
7595  reinterpret_cast<v8::ArrayBuffer::Allocator*>(info);
7596  allocator->Free(buffer, length);
7597 }
7598 
7600  i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
7601  Contents contents(
7602  self->backing_store(), self->byte_length(), self->allocation_base(),
7603  self->allocation_length(),
7604  self->is_wasm_memory() ? Allocator::AllocationMode::kReservation
7605  : Allocator::AllocationMode::kNormal,
7606  self->is_wasm_memory() ? WasmMemoryDeleter : ArrayBufferDeleter,
7607  self->is_wasm_memory()
7608  ? static_cast<void*>(self->GetIsolate()->wasm_engine())
7609  : static_cast<void*>(self->GetIsolate()->array_buffer_allocator()));
7610  return contents;
7611 }
7612 
7613 
7615  i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
7616  i::Isolate* isolate = obj->GetIsolate();
7617  Utils::ApiCheck(obj->is_external(),
7618  "v8::ArrayBuffer::Neuter",
7619  "Only externalized ArrayBuffers can be neutered");
7620  Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter",
7621  "Only neuterable ArrayBuffers can be neutered");
7622  LOG_API(isolate, ArrayBuffer, Neuter);
7623  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7624  obj->Neuter();
7625 }
7626 
7627 
7629  i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
7630  return obj->byte_length();
7631 }
7632 
7633 
7634 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
7635  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7636  LOG_API(i_isolate, ArrayBuffer, New);
7637  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7639  i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
7640  // TODO(jbroman): It may be useful in the future to provide a MaybeLocal
7641  // version that throws an exception or otherwise does not crash.
7642  if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length)) {
7643  i::FatalProcessOutOfMemory(i_isolate, "v8::ArrayBuffer::New");
7644  }
7645  return Utils::ToLocal(obj);
7646 }
7647 
7648 
7649 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
7650  size_t byte_length,
7651  ArrayBufferCreationMode mode) {
7652  // Embedders must guarantee that the external backing store is valid.
7653  CHECK(byte_length == 0 || data != nullptr);
7654  CHECK_LE(byte_length, i::JSArrayBuffer::kMaxByteLength);
7655  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7656  LOG_API(i_isolate, ArrayBuffer, New);
7657  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7659  i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
7660  i::JSArrayBuffer::Setup(obj, i_isolate,
7661  mode == ArrayBufferCreationMode::kExternalized, data,
7662  byte_length);
7663  return Utils::ToLocal(obj);
7664 }
7665 
7666 
7668  i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
7670  if (obj->IsJSDataView()) {
7671  i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj),
7672  obj->GetIsolate());
7673  DCHECK(data_view->buffer()->IsJSArrayBuffer());
7674  buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()),
7675  data_view->GetIsolate());
7676  } else {
7677  DCHECK(obj->IsJSTypedArray());
7678  buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
7679  }
7680  return Utils::ToLocal(buffer);
7681 }
7682 
7683 
7684 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
7685  i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
7686  size_t byte_offset = self->byte_offset();
7687  size_t bytes_to_copy = i::Min(byte_length, self->byte_length());
7688  if (bytes_to_copy) {
7690  i::Isolate* isolate = self->GetIsolate();
7691  i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()),
7692  isolate);
7693  const char* source = reinterpret_cast<char*>(buffer->backing_store());
7694  if (source == nullptr) {
7695  DCHECK(self->IsJSTypedArray());
7696  i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self),
7697  isolate);
7699  i::FixedTypedArrayBase::cast(typed_array->elements()), isolate);
7700  source = reinterpret_cast<char*>(fixed_array->DataPtr());
7701  }
7702  memcpy(dest, source + byte_offset, bytes_to_copy);
7703  }
7704  return bytes_to_copy;
7705 }
7706 
7707 
7709  i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
7710  i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()),
7711  self->GetIsolate());
7712  return buffer->backing_store() != nullptr;
7713 }
7714 
7715 
7717  i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
7718  return obj->WasNeutered() ? 0 : obj->byte_offset();
7719 }
7720 
7721 
7723  i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
7724  return obj->WasNeutered() ? 0 : obj->byte_length();
7725 }
7726 
7727 
7729  i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
7730  return obj->WasNeutered() ? 0 : obj->length_value();
7731 }
7732 
7733 static_assert(v8::TypedArray::kMaxLength == i::Smi::kMaxValue,
7734  "v8::TypedArray::kMaxLength must match i::Smi::kMaxValue");
7735 
7736 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype) \
7737  Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer, \
7738  size_t byte_offset, size_t length) { \
7739  i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate(); \
7740  LOG_API(isolate, Type##Array, New); \
7741  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate); \
7742  if (!Utils::ApiCheck(length <= kMaxLength, \
7743  "v8::" #Type \
7744  "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
7745  "length exceeds max allowed value")) { \
7746  return Local<Type##Array>(); \
7747  } \
7748  i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \
7749  i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
7750  i::kExternal##Type##Array, buffer, byte_offset, length); \
7751  return Utils::ToLocal##Type##Array(obj); \
7752  } \
7753  Local<Type##Array> Type##Array::New( \
7754  Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, \
7755  size_t length) { \
7756  CHECK(i::FLAG_harmony_sharedarraybuffer); \
7757  i::Isolate* isolate = \
7758  Utils::OpenHandle(*shared_array_buffer)->GetIsolate(); \
7759  LOG_API(isolate, Type##Array, New); \
7760  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate); \
7761  if (!Utils::ApiCheck( \
7762  length <= kMaxLength, \
7763  "v8::" #Type \
7764  "Array::New(Local<SharedArrayBuffer>, size_t, size_t)", \
7765  "length exceeds max allowed value")) { \
7766  return Local<Type##Array>(); \
7767  } \
7768  i::Handle<i::JSArrayBuffer> buffer = \
7769  Utils::OpenHandle(*shared_array_buffer); \
7770  i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
7771  i::kExternal##Type##Array, buffer, byte_offset, length); \
7772  return Utils::ToLocal##Type##Array(obj); \
7773  }
7774 
7775 TYPED_ARRAYS(TYPED_ARRAY_NEW)
7776 #undef TYPED_ARRAY_NEW
7777 
7778 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
7779  size_t byte_offset, size_t byte_length) {
7780  i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
7781  i::Isolate* isolate = buffer->GetIsolate();
7782  LOG_API(isolate, DataView, New);
7783  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7785  isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
7786  return Utils::ToLocal(obj);
7787 }
7788 
7789 
7790 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
7791  size_t byte_offset, size_t byte_length) {
7792  CHECK(i::FLAG_harmony_sharedarraybuffer);
7793  i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
7794  i::Isolate* isolate = buffer->GetIsolate();
7795  LOG_API(isolate, DataView, New);
7796  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
7798  isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
7799  return Utils::ToLocal(obj);
7800 }
7801 
7802 
7804  return Utils::OpenHandle(this)->is_external();
7805 }
7806 
7808  i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
7809  i::Isolate* isolate = self->GetIsolate();
7810  Utils::ApiCheck(!self->is_external(), "v8_SharedArrayBuffer_Externalize",
7811  "SharedArrayBuffer already externalized");
7812  self->set_is_external(true);
7813 
7814  const v8::SharedArrayBuffer::Contents contents = GetContents();
7815  isolate->heap()->UnregisterArrayBuffer(*self);
7816 
7817  // A regular copy is good enough. No move semantics needed.
7818  return contents;
7819 }
7820 
7821 v8::SharedArrayBuffer::Contents::Contents(
7822  void* data, size_t byte_length, void* allocation_base,
7823  size_t allocation_length, Allocator::AllocationMode allocation_mode,
7824  DeleterCallback deleter, void* deleter_data)
7825  : data_(data),
7826  byte_length_(byte_length),
7827  allocation_base_(allocation_base),
7828  allocation_length_(allocation_length),
7829  allocation_mode_(allocation_mode),
7830  deleter_(deleter),
7831  deleter_data_(deleter_data) {
7832  DCHECK_LE(allocation_base_, data_);
7833  DCHECK_LE(byte_length_, allocation_length_);
7834 }
7835 
7837  i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
7838  Contents contents(
7839  self->backing_store(), self->byte_length(), self->allocation_base(),
7840  self->allocation_length(),
7841  self->is_wasm_memory()
7842  ? ArrayBuffer::Allocator::AllocationMode::kReservation
7843  : ArrayBuffer::Allocator::AllocationMode::kNormal,
7844  self->is_wasm_memory()
7845  ? reinterpret_cast<Contents::DeleterCallback>(WasmMemoryDeleter)
7846  : reinterpret_cast<Contents::DeleterCallback>(ArrayBufferDeleter),
7847  self->is_wasm_memory()
7848  ? static_cast<void*>(self->GetIsolate()->wasm_engine())
7849  : static_cast<void*>(self->GetIsolate()->array_buffer_allocator()));
7850  return contents;
7851 }
7852 
7854  i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
7855  return obj->byte_length();
7856 }
7857 
7859  size_t byte_length) {
7860  CHECK(i::FLAG_harmony_sharedarraybuffer);
7861  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7862  LOG_API(i_isolate, SharedArrayBuffer, New);
7863  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7865  i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
7866  // TODO(jbroman): It may be useful in the future to provide a MaybeLocal
7867  // version that throws an exception or otherwise does not crash.
7868  if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length, true,
7869  i::SharedFlag::kShared)) {
7870  i::FatalProcessOutOfMemory(i_isolate, "v8::SharedArrayBuffer::New");
7871  }
7872  return Utils::ToLocalShared(obj);
7873 }
7874 
7875 
7877  Isolate* isolate, void* data, size_t byte_length,
7878  ArrayBufferCreationMode mode) {
7879  CHECK(i::FLAG_harmony_sharedarraybuffer);
7880  // Embedders must guarantee that the external backing store is valid.
7881  CHECK(byte_length == 0 || data != nullptr);
7882  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7883  LOG_API(i_isolate, SharedArrayBuffer, New);
7884  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7886  i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
7887  bool is_wasm_memory =
7888  i_isolate->wasm_engine()->memory_tracker()->IsWasmMemory(data);
7889  i::JSArrayBuffer::Setup(obj, i_isolate,
7890  mode == ArrayBufferCreationMode::kExternalized, data,
7891  byte_length, i::SharedFlag::kShared, is_wasm_memory);
7892  return Utils::ToLocalShared(obj);
7893 }
7894 
7895 
7897  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7898  LOG_API(i_isolate, Symbol, New);
7899  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7900  i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
7901  if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
7902  return Utils::ToLocal(result);
7903 }
7904 
7905 
7907  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7908  i::Handle<i::String> i_name = Utils::OpenHandle(*name);
7909  return Utils::ToLocal(
7910  i_isolate->SymbolFor(i::RootIndex::kPublicSymbolTable, i_name, false));
7911 }
7912 
7913 
7915  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7916  i::Handle<i::String> i_name = Utils::OpenHandle(*name);
7917  return Utils::ToLocal(
7918  i_isolate->SymbolFor(i::RootIndex::kApiSymbolTable, i_name, false));
7919 }
7920 
7921 #define WELL_KNOWN_SYMBOLS(V) \
7922  V(AsyncIterator, async_iterator) \
7923  V(HasInstance, has_instance) \
7924  V(IsConcatSpreadable, is_concat_spreadable) \
7925  V(Iterator, iterator) \
7926  V(Match, match) \
7927  V(Replace, replace) \
7928  V(Search, search) \
7929  V(Split, split) \
7930  V(ToPrimitive, to_primitive) \
7931  V(ToStringTag, to_string_tag) \
7932  V(Unscopables, unscopables)
7933 
7934 #define SYMBOL_GETTER(Name, name) \
7935  Local<Symbol> v8::Symbol::Get##Name(Isolate* isolate) { \
7936  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); \
7937  return Utils::ToLocal(i_isolate->factory()->name##_symbol()); \
7938  }
7939 
7940 WELL_KNOWN_SYMBOLS(SYMBOL_GETTER)
7941 
7942 #undef SYMBOL_GETTER
7943 #undef WELL_KNOWN_SYMBOLS
7944 
7946  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7947  LOG_API(i_isolate, Private, New);
7948  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
7949  i::Handle<i::Symbol> symbol = i_isolate->factory()->NewPrivateSymbol();
7950  if (!name.IsEmpty()) symbol->set_name(*Utils::OpenHandle(*name));
7951  Local<Symbol> result = Utils::ToLocal(symbol);
7952  return v8::Local<Private>(reinterpret_cast<Private*>(*result));
7953 }
7954 
7955 
7957  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7958  i::Handle<i::String> i_name = Utils::OpenHandle(*name);
7959  Local<Symbol> result = Utils::ToLocal(
7960  i_isolate->SymbolFor(i::RootIndex::kApiPrivateSymbolTable, i_name, true));
7961  return v8::Local<Private>(reinterpret_cast<Private*>(*result));
7962 }
7963 
7964 
7965 Local<Number> v8::Number::New(Isolate* isolate, double value) {
7966  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7967  if (std::isnan(value)) {
7968  // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
7969  value = std::numeric_limits<double>::quiet_NaN();
7970  }
7971  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
7972  i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
7973  return Utils::NumberToLocal(result);
7974 }
7975 
7976 
7977 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
7978  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7979  if (i::Smi::IsValid(value)) {
7980  return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
7981  internal_isolate));
7982  }
7983  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
7984  i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
7985  return Utils::IntegerToLocal(result);
7986 }
7987 
7988 
7989 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
7990  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7991  bool fits_into_int32_t = (value & (1 << 31)) == 0;
7992  if (fits_into_int32_t) {
7993  return Integer::New(isolate, static_cast<int32_t>(value));
7994  }
7995  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
7996  i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
7997  return Utils::IntegerToLocal(result);
7998 }
7999 
8000 Local<BigInt> v8::BigInt::New(Isolate* isolate, int64_t value) {
8001  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
8002  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
8003  i::Handle<i::BigInt> result = i::BigInt::FromInt64(internal_isolate, value);
8004  return Utils::ToLocal(result);
8005 }
8006 
8007 Local<BigInt> v8::BigInt::NewFromUnsigned(Isolate* isolate, uint64_t value) {
8008  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
8009  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
8010  i::Handle<i::BigInt> result = i::BigInt::FromUint64(internal_isolate, value);
8011  return Utils::ToLocal(result);
8012 }
8013 
8015  int sign_bit, int word_count,
8016  const uint64_t* words) {
8017  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
8018  ENTER_V8_NO_SCRIPT(isolate, context, BigInt, NewFromWords,
8019  MaybeLocal<BigInt>(), InternalEscapableScope);
8020  i::MaybeHandle<i::BigInt> result =
8021  i::BigInt::FromWords64(isolate, sign_bit, word_count, words);
8022  has_pending_exception = result.is_null();
8023  RETURN_ON_FAILED_EXECUTION(BigInt);
8024  RETURN_ESCAPED(Utils::ToLocal(result.ToHandleChecked()));
8025 }
8026 
8027 uint64_t v8::BigInt::Uint64Value(bool* lossless) const {
8028  i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
8029  return handle->AsUint64(lossless);
8030 }
8031 
8032 int64_t v8::BigInt::Int64Value(bool* lossless) const {
8033  i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
8034  return handle->AsInt64(lossless);
8035 }
8036 
8037 int BigInt::WordCount() const {
8038  i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
8039  return handle->Words64Count();
8040 }
8041 
8042 void BigInt::ToWordsArray(int* sign_bit, int* word_count,
8043  uint64_t* words) const {
8044  i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
8045  return handle->ToWordsArray64(sign_bit, word_count, words);
8046 }
8047 
8048 void Isolate::ReportExternalAllocationLimitReached() {
8049  i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
8050  if (heap->gc_state() != i::Heap::NOT_IN_GC) return;
8051  heap->ReportExternalMemoryPressure();
8052 }
8053 
8054 void Isolate::CheckMemoryPressure() {
8055  i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
8056  if (heap->gc_state() != i::Heap::NOT_IN_GC) return;
8057  heap->CheckMemoryPressure();
8058 }
8059 
8060 HeapProfiler* Isolate::GetHeapProfiler() {
8061  i::HeapProfiler* heap_profiler =
8062  reinterpret_cast<i::Isolate*>(this)->heap_profiler();
8063  return reinterpret_cast<HeapProfiler*>(heap_profiler);
8064 }
8065 
8066 void Isolate::SetIdle(bool is_idle) {
8067  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8068  isolate->SetIdle(is_idle);
8069 }
8070 
8071 bool Isolate::InContext() {
8072  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8073  return !isolate->context().is_null();
8074 }
8075 
8076 
8077 v8::Local<v8::Context> Isolate::GetCurrentContext() {
8078  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8079  i::Context context = isolate->context();
8080  if (context.is_null()) return Local<Context>();
8081  i::Context native_context = context->native_context();
8082  if (native_context.is_null()) return Local<Context>();
8083  return Utils::ToLocal(i::Handle<i::Context>(native_context, isolate));
8084 }
8085 
8086 
8087 v8::Local<v8::Context> Isolate::GetEnteredContext() {
8088  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8089  i::Handle<i::Object> last =
8090  isolate->handle_scope_implementer()->LastEnteredContext();
8091  if (last.is_null()) return Local<Context>();
8092  return Utils::ToLocal(i::Handle<i::Context>::cast(last));
8093 }
8094 
8095 v8::Local<v8::Context> Isolate::GetEnteredOrMicrotaskContext() {
8096  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8097  i::Handle<i::Object> last =
8098  isolate->handle_scope_implementer()->LastEnteredOrMicrotaskContext();
8099  if (last.is_null()) return Local<Context>();
8100  DCHECK(last->IsNativeContext());
8101  return Utils::ToLocal(i::Handle<i::Context>::cast(last));
8102 }
8103 
8104 v8::Local<v8::Context> Isolate::GetIncumbentContext() {
8105  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8106  i::Handle<i::Context> context = isolate->GetIncumbentContext();
8107  return Utils::ToLocal(context);
8108 }
8109 
8110 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
8111  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8112  ENTER_V8_DO_NOT_USE(isolate);
8113  // If we're passed an empty handle, we throw an undefined exception
8114  // to deal more gracefully with out of memory situations.
8115  if (value.IsEmpty()) {
8116  isolate->ScheduleThrow(i::ReadOnlyRoots(isolate).undefined_value());
8117  } else {
8118  isolate->ScheduleThrow(*Utils::OpenHandle(*value));
8119  }
8120  return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
8121 }
8122 
8123 void Isolate::AddGCPrologueCallback(GCCallbackWithData callback, void* data,
8124  GCType gc_type) {
8125  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8126  isolate->heap()->AddGCPrologueCallback(callback, gc_type, data);
8127 }
8128 
8129 void Isolate::RemoveGCPrologueCallback(GCCallbackWithData callback,
8130  void* data) {
8131  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8132  isolate->heap()->RemoveGCPrologueCallback(callback, data);
8133 }
8134 
8135 void Isolate::AddGCEpilogueCallback(GCCallbackWithData callback, void* data,
8136  GCType gc_type) {
8137  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8138  isolate->heap()->AddGCEpilogueCallback(callback, gc_type, data);
8139 }
8140 
8141 void Isolate::RemoveGCEpilogueCallback(GCCallbackWithData callback,
8142  void* data) {
8143  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8144  isolate->heap()->RemoveGCEpilogueCallback(callback, data);
8145 }
8146 
8147 static void CallGCCallbackWithoutData(Isolate* isolate, GCType type,
8148  GCCallbackFlags flags, void* data) {
8149  reinterpret_cast<Isolate::GCCallback>(data)(isolate, type, flags);
8150 }
8151 
8152 void Isolate::AddGCPrologueCallback(GCCallback callback, GCType gc_type) {
8153  void* data = reinterpret_cast<void*>(callback);
8154  AddGCPrologueCallback(CallGCCallbackWithoutData, data, gc_type);
8155 }
8156 
8157 void Isolate::RemoveGCPrologueCallback(GCCallback callback) {
8158  void* data = reinterpret_cast<void*>(callback);
8159  RemoveGCPrologueCallback(CallGCCallbackWithoutData, data);
8160 }
8161 
8162 void Isolate::AddGCEpilogueCallback(GCCallback callback, GCType gc_type) {
8163  void* data = reinterpret_cast<void*>(callback);
8164  AddGCEpilogueCallback(CallGCCallbackWithoutData, data, gc_type);
8165 }
8166 
8167 void Isolate::RemoveGCEpilogueCallback(GCCallback callback) {
8168  void* data = reinterpret_cast<void*>(callback);
8169  RemoveGCEpilogueCallback(CallGCCallbackWithoutData, data);
8170 }
8171 
8172 void Isolate::SetEmbedderHeapTracer(EmbedderHeapTracer* tracer) {
8173  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8174  isolate->heap()->SetEmbedderHeapTracer(tracer);
8175 }
8176 
8177 EmbedderHeapTracer* Isolate::GetEmbedderHeapTracer() {
8178  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8179  return isolate->heap()->GetEmbedderHeapTracer();
8180 }
8181 
8182 void Isolate::SetGetExternallyAllocatedMemoryInBytesCallback(
8183  GetExternallyAllocatedMemoryInBytesCallback callback) {
8184  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8185  isolate->heap()->SetGetExternallyAllocatedMemoryInBytesCallback(callback);
8186 }
8187 
8188 void Isolate::TerminateExecution() {
8189  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8190  isolate->stack_guard()->RequestTerminateExecution();
8191 }
8192 
8193 
8194 bool Isolate::IsExecutionTerminating() {
8195  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8196  return IsExecutionTerminatingCheck(isolate);
8197 }
8198 
8199 
8200 void Isolate::CancelTerminateExecution() {
8201  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8202  isolate->stack_guard()->ClearTerminateExecution();
8203  isolate->CancelTerminateExecution();
8204 }
8205 
8206 
8207 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
8208  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8209  isolate->RequestInterrupt(callback, data);
8210 }
8211 
8212 
8213 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
8214  CHECK(i::FLAG_expose_gc);
8215  if (type == kMinorGarbageCollection) {
8216  reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
8217  i::NEW_SPACE, i::GarbageCollectionReason::kTesting,
8218  kGCCallbackFlagForced);
8219  } else {
8220  DCHECK_EQ(kFullGarbageCollection, type);
8221  reinterpret_cast<i::Isolate*>(this)->heap()->PreciseCollectAllGarbage(
8222  i::Heap::kNoGCFlags, i::GarbageCollectionReason::kTesting,
8223  kGCCallbackFlagForced);
8224  }
8225 }
8226 
8227 
8228 Isolate* Isolate::GetCurrent() {
8229  i::Isolate* isolate = i::Isolate::Current();
8230  return reinterpret_cast<Isolate*>(isolate);
8231 }
8232 
8233 // static
8234 Isolate* Isolate::Allocate() {
8235  return reinterpret_cast<Isolate*>(i::Isolate::New());
8236 }
8237 
8238 // static
8239 // This is separate so that tests can provide a different |isolate|.
8240 void Isolate::Initialize(Isolate* isolate,
8241  const v8::Isolate::CreateParams& params) {
8242  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
8243  CHECK_NOT_NULL(params.array_buffer_allocator);
8244  i_isolate->set_array_buffer_allocator(params.array_buffer_allocator);
8245  if (params.snapshot_blob != nullptr) {
8246  i_isolate->set_snapshot_blob(params.snapshot_blob);
8247  } else {
8248  i_isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
8249  }
8250  auto code_event_handler = params.code_event_handler;
8251 #ifdef ENABLE_GDB_JIT_INTERFACE
8252  if (code_event_handler == nullptr && i::FLAG_gdbjit) {
8253  code_event_handler = i::GDBJITInterface::EventHandler;
8254  }
8255 #endif // ENABLE_GDB_JIT_INTERFACE
8256  if (code_event_handler) {
8257  i_isolate->InitializeLoggingAndCounters();
8258  i_isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
8259  code_event_handler);
8260  }
8261  if (params.counter_lookup_callback) {
8262  isolate->SetCounterFunction(params.counter_lookup_callback);
8263  }
8264 
8265  if (params.create_histogram_callback) {
8266  isolate->SetCreateHistogramFunction(params.create_histogram_callback);
8267  }
8268 
8269  if (params.add_histogram_sample_callback) {
8270  isolate->SetAddHistogramSampleFunction(
8271  params.add_histogram_sample_callback);
8272  }
8273 
8274  i_isolate->set_api_external_references(params.external_references);
8275  i_isolate->set_allow_atomics_wait(params.allow_atomics_wait);
8276 
8277  SetResourceConstraints(i_isolate, params.constraints);
8278  // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
8279  Isolate::Scope isolate_scope(isolate);
8280  if (!i::Snapshot::Initialize(i_isolate)) {
8281  // If snapshot data was provided and we failed to deserialize it must
8282  // have been corrupted.
8283  if (i_isolate->snapshot_blob() != nullptr) {
8284  FATAL(
8285  "Failed to deserialize the V8 snapshot blob. This can mean that the "
8286  "snapshot blob file is corrupted or missing.");
8287  }
8288  base::ElapsedTimer timer;
8289  if (i::FLAG_profile_deserialization) timer.Start();
8290  i_isolate->Init(nullptr);
8291  if (i::FLAG_profile_deserialization) {
8292  double ms = timer.Elapsed().InMillisecondsF();
8293  i::PrintF("[Initializing isolate from scratch took %0.3f ms]\n", ms);
8294  }
8295  }
8296  i_isolate->set_only_terminate_in_safe_scope(
8298 }
8299 
8300 Isolate* Isolate::New(const Isolate::CreateParams& params) {
8301  Isolate* isolate = Allocate();
8302  Initialize(isolate, params);
8303  return isolate;
8304 }
8305 
8306 void Isolate::Dispose() {
8307  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8308  if (!Utils::ApiCheck(!isolate->IsInUse(),
8309  "v8::Isolate::Dispose()",
8310  "Disposing the isolate that is entered by a thread.")) {
8311  return;
8312  }
8313  i::Isolate::Delete(isolate);
8314 }
8315 
8316 void Isolate::DumpAndResetStats() {
8317  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8318  isolate->DumpAndResetStats();
8319 }
8320 
8321 void Isolate::DiscardThreadSpecificMetadata() {
8322  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8323  isolate->DiscardPerThreadDataForThisThread();
8324 }
8325 
8326 
8327 void Isolate::Enter() {
8328  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8329  isolate->Enter();
8330 }
8331 
8332 
8333 void Isolate::Exit() {
8334  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8335  isolate->Exit();
8336 }
8337 
8338 
8339 void Isolate::SetAbortOnUncaughtExceptionCallback(
8340  AbortOnUncaughtExceptionCallback callback) {
8341  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8342  isolate->SetAbortOnUncaughtExceptionCallback(callback);
8343 }
8344 
8345 void Isolate::SetHostImportModuleDynamicallyCallback(
8346  HostImportModuleDynamicallyCallback callback) {
8347  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8348  isolate->SetHostImportModuleDynamicallyCallback(callback);
8349 }
8350 
8351 void Isolate::SetHostInitializeImportMetaObjectCallback(
8352  HostInitializeImportMetaObjectCallback callback) {
8353  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8354  isolate->SetHostInitializeImportMetaObjectCallback(callback);
8355 }
8356 
8357 void Isolate::SetPrepareStackTraceCallback(PrepareStackTraceCallback callback) {
8358  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8359  isolate->SetPrepareStackTraceCallback(callback);
8360 }
8361 
8362 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
8363  Isolate* isolate,
8364  Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
8365  : on_failure_(on_failure) {
8366  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
8367  switch (on_failure_) {
8368  case CRASH_ON_FAILURE:
8369  internal_ = reinterpret_cast<void*>(
8370  new i::DisallowJavascriptExecution(i_isolate));
8371  break;
8372  case THROW_ON_FAILURE:
8373  DCHECK_EQ(THROW_ON_FAILURE, on_failure);
8374  internal_ =
8375  reinterpret_cast<void*>(new i::ThrowOnJavascriptExecution(i_isolate));
8376  break;
8377  case DUMP_ON_FAILURE:
8378  internal_ =
8379  reinterpret_cast<void*>(new i::DumpOnJavascriptExecution(i_isolate));
8380  break;
8381  default:
8382  UNREACHABLE();
8383  break;
8384  }
8385 }
8386 
8387 
8388 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
8389  switch (on_failure_) {
8390  case CRASH_ON_FAILURE:
8391  delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
8392  break;
8393  case THROW_ON_FAILURE:
8394  delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
8395  break;
8396  case DUMP_ON_FAILURE:
8397  delete reinterpret_cast<i::DumpOnJavascriptExecution*>(internal_);
8398  break;
8399  default:
8400  UNREACHABLE();
8401  break;
8402  }
8403 }
8404 
8405 
8406 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
8407  Isolate* isolate) {
8408  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
8409  internal_assert_ = reinterpret_cast<void*>(
8410  new i::AllowJavascriptExecution(i_isolate));
8411  internal_throws_ = reinterpret_cast<void*>(
8412  new i::NoThrowOnJavascriptExecution(i_isolate));
8413  internal_dump_ =
8414  reinterpret_cast<void*>(new i::NoDumpOnJavascriptExecution(i_isolate));
8415 }
8416 
8417 
8418 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
8419  delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
8420  delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
8421  delete reinterpret_cast<i::NoDumpOnJavascriptExecution*>(internal_dump_);
8422 }
8423 
8424 
8425 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
8426  Isolate* isolate)
8427  : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
8428  isolate_->handle_scope_implementer()->IncrementCallDepth();
8429  isolate_->handle_scope_implementer()->IncrementMicrotasksSuppressions();
8430 }
8431 
8432 
8433 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
8434  isolate_->handle_scope_implementer()->DecrementMicrotasksSuppressions();
8435  isolate_->handle_scope_implementer()->DecrementCallDepth();
8436 }
8437 
8438 Isolate::SafeForTerminationScope::SafeForTerminationScope(v8::Isolate* isolate)
8439  : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
8440  prev_value_(isolate_->next_v8_call_is_safe_for_termination()) {
8441  isolate_->set_next_v8_call_is_safe_for_termination(true);
8442 }
8443 
8444 Isolate::SafeForTerminationScope::~SafeForTerminationScope() {
8445  isolate_->set_next_v8_call_is_safe_for_termination(prev_value_);
8446 }
8447 
8448 i::Address* Isolate::GetDataFromSnapshotOnce(size_t index) {
8449  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
8450  i::FixedArray list = i_isolate->heap()->serialized_objects();
8451  return GetSerializedDataFromFixedArray(i_isolate, list, index);
8452 }
8453 
8454 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
8455  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8456  i::Heap* heap = isolate->heap();
8457  heap_statistics->total_heap_size_ = heap->CommittedMemory();
8458  heap_statistics->total_heap_size_executable_ =
8459  heap->CommittedMemoryExecutable();
8460  heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
8461  heap_statistics->total_available_size_ = heap->Available();
8462  heap_statistics->used_heap_size_ = heap->SizeOfObjects();
8463  heap_statistics->heap_size_limit_ = heap->MaxReserved();
8464  // TODO(7424): There is no public API for the {WasmEngine} yet. Once such an
8465  // API becomes available we should report the malloced memory separately. For
8466  // now we just add the values, thereby over-approximating the peak slightly.
8467  heap_statistics->malloced_memory_ =
8468  isolate->allocator()->GetCurrentMemoryUsage() +
8469  isolate->wasm_engine()->allocator()->GetCurrentMemoryUsage();
8470  heap_statistics->external_memory_ = isolate->heap()->external_memory();
8471  heap_statistics->peak_malloced_memory_ =
8472  isolate->allocator()->GetMaxMemoryUsage() +
8473  isolate->wasm_engine()->allocator()->GetMaxMemoryUsage();
8474  heap_statistics->number_of_native_contexts_ = heap->NumberOfNativeContexts();
8475  heap_statistics->number_of_detached_contexts_ =
8476  heap->NumberOfDetachedContexts();
8477  heap_statistics->does_zap_garbage_ = heap->ShouldZapGarbage();
8478 }
8479 
8480 
8481 size_t Isolate::NumberOfHeapSpaces() {
8482  return i::LAST_SPACE - i::FIRST_SPACE + 1;
8483 }
8484 
8485 
8486 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
8487  size_t index) {
8488  if (!space_statistics) return false;
8489  if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
8490  return false;
8491 
8492  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8493  i::Heap* heap = isolate->heap();
8494  i::Space* space = heap->space(static_cast<int>(index));
8495 
8496  space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
8497  space_statistics->space_size_ = space->CommittedMemory();
8498  space_statistics->space_used_size_ = space->SizeOfObjects();
8499  space_statistics->space_available_size_ = space->Available();
8500  space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
8501  return true;
8502 }
8503 
8504 
8505 size_t Isolate::NumberOfTrackedHeapObjectTypes() {
8506  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8507  i::Heap* heap = isolate->heap();
8508  return heap->NumberOfTrackedHeapObjectTypes();
8509 }
8510 
8511 
8512 bool Isolate::GetHeapObjectStatisticsAtLastGC(
8513  HeapObjectStatistics* object_statistics, size_t type_index) {
8514  if (!object_statistics) return false;
8515  if (V8_LIKELY(!i::FLAG_gc_stats)) return false;
8516 
8517  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8518  i::Heap* heap = isolate->heap();
8519  if (type_index >= heap->NumberOfTrackedHeapObjectTypes()) return false;
8520 
8521  const char* object_type;
8522  const char* object_sub_type;
8523  size_t object_count = heap->ObjectCountAtLastGC(type_index);
8524  size_t object_size = heap->ObjectSizeAtLastGC(type_index);
8525  if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
8526  // There should be no objects counted when the type is unknown.
8527  DCHECK_EQ(object_count, 0U);
8528  DCHECK_EQ(object_size, 0U);
8529  return false;
8530  }
8531 
8532  object_statistics->object_type_ = object_type;
8533  object_statistics->object_sub_type_ = object_sub_type;
8534  object_statistics->object_count_ = object_count;
8535  object_statistics->object_size_ = object_size;
8536  return true;
8537 }
8538 
8539 bool Isolate::GetHeapCodeAndMetadataStatistics(
8540  HeapCodeStatistics* code_statistics) {
8541  if (!code_statistics) return false;
8542 
8543  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8544  isolate->heap()->CollectCodeStatistics();
8545 
8546  code_statistics->code_and_metadata_size_ = isolate->code_and_metadata_size();
8547  code_statistics->bytecode_and_metadata_size_ =
8548  isolate->bytecode_and_metadata_size();
8549  code_statistics->external_script_source_size_ =
8550  isolate->external_script_source_size();
8551  return true;
8552 }
8553 
8554 void Isolate::GetStackSample(const RegisterState& state, void** frames,
8555  size_t frames_limit, SampleInfo* sample_info) {
8556  RegisterState regs = state;
8557  if (TickSample::GetStackSample(this, &regs, TickSample::kSkipCEntryFrame,
8558  frames, frames_limit, sample_info)) {
8559  return;
8560  }
8561  sample_info->frames_count = 0;
8562  sample_info->vm_state = OTHER;
8563  sample_info->external_callback_entry = nullptr;
8564 }
8565 
8566 size_t Isolate::NumberOfPhantomHandleResetsSinceLastCall() {
8567  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8568  size_t result = isolate->global_handles()->NumberOfPhantomHandleResets();
8569  isolate->global_handles()->ResetNumberOfPhantomHandleResets();
8570  return result;
8571 }
8572 
8573 void Isolate::SetEventLogger(LogEventCallback that) {
8574  // Do not overwrite the event logger if we want to log explicitly.
8575  if (i::FLAG_log_internal_timer_events) return;
8576  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8577  isolate->set_event_logger(that);
8578 }
8579 
8580 
8581 void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) {
8582  if (callback == nullptr) return;
8583  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8584  isolate->AddBeforeCallEnteredCallback(callback);
8585 }
8586 
8587 
8588 void Isolate::RemoveBeforeCallEnteredCallback(
8589  BeforeCallEnteredCallback callback) {
8590  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8591  isolate->RemoveBeforeCallEnteredCallback(callback);
8592 }
8593 
8594 
8595 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
8596  if (callback == nullptr) return;
8597  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8598  isolate->AddCallCompletedCallback(callback);
8599 }
8600 
8601 
8602 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
8603  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8604  isolate->RemoveCallCompletedCallback(callback);
8605 }
8606 
8608  reinterpret_cast<i::AtomicsWaitWakeHandle*>(this)->Wake();
8609 }
8610 
8611 void Isolate::SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data) {
8612  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8613  isolate->SetAtomicsWaitCallback(callback, data);
8614 }
8615 
8616 void Isolate::SetPromiseHook(PromiseHook hook) {
8617  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8618  isolate->SetPromiseHook(hook);
8619 }
8620 
8621 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
8622  if (callback == nullptr) return;
8623  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8624  isolate->SetPromiseRejectCallback(callback);
8625 }
8626 
8627 
8628 void Isolate::RunMicrotasks() {
8629  DCHECK_NE(MicrotasksPolicy::kScoped, GetMicrotasksPolicy());
8630  reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
8631 }
8632 
8633 void Isolate::EnqueueMicrotask(Local<Function> function) {
8634  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8635  i::Handle<i::CallableTask> microtask = isolate->factory()->NewCallableTask(
8636  Utils::OpenHandle(*function), isolate->native_context());
8637  isolate->EnqueueMicrotask(microtask);
8638 }
8639 
8640 void Isolate::EnqueueMicrotask(MicrotaskCallback callback, void* data) {
8641  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8642  i::HandleScope scope(isolate);
8643  i::Handle<i::CallbackTask> microtask = isolate->factory()->NewCallbackTask(
8644  isolate->factory()->NewForeign(reinterpret_cast<i::Address>(callback)),
8645  isolate->factory()->NewForeign(reinterpret_cast<i::Address>(data)));
8646  isolate->EnqueueMicrotask(microtask);
8647 }
8648 
8649 
8650 void Isolate::SetMicrotasksPolicy(MicrotasksPolicy policy) {
8651  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8652  isolate->handle_scope_implementer()->set_microtasks_policy(policy);
8653 }
8654 
8655 
8656 MicrotasksPolicy Isolate::GetMicrotasksPolicy() const {
8657  i::Isolate* isolate =
8658  reinterpret_cast<i::Isolate*>(const_cast<Isolate*>(this));
8659  return isolate->handle_scope_implementer()->microtasks_policy();
8660 }
8661 
8662 
8663 void Isolate::AddMicrotasksCompletedCallback(
8664  MicrotasksCompletedCallback callback) {
8665  DCHECK(callback);
8666  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8667  isolate->AddMicrotasksCompletedCallback(callback);
8668 }
8669 
8670 
8671 void Isolate::RemoveMicrotasksCompletedCallback(
8672  MicrotasksCompletedCallback callback) {
8673  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8674  isolate->RemoveMicrotasksCompletedCallback(callback);
8675 }
8676 
8677 
8678 void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
8679  reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
8680 }
8681 
8682 
8683 void Isolate::SetCounterFunction(CounterLookupCallback callback) {
8684  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8685  isolate->counters()->ResetCounterFunction(callback);
8686 }
8687 
8688 
8689 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
8690  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8691  isolate->counters()->ResetCreateHistogramFunction(callback);
8692 }
8693 
8694 
8695 void Isolate::SetAddHistogramSampleFunction(
8696  AddHistogramSampleCallback callback) {
8697  reinterpret_cast<i::Isolate*>(this)
8698  ->counters()
8699  ->SetAddHistogramSampleFunction(callback);
8700 }
8701 
8702 
8703 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
8704  // Returning true tells the caller that it need not
8705  // continue to call IdleNotification.
8706  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8707  if (!i::FLAG_use_idle_notification) return true;
8708  return isolate->heap()->IdleNotification(deadline_in_seconds);
8709 }
8710 
8711 void Isolate::LowMemoryNotification() {
8712  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8713  {
8714  i::HistogramTimerScope idle_notification_scope(
8715  isolate->counters()->gc_low_memory_notification());
8716  TRACE_EVENT0("v8", "V8.GCLowMemoryNotification");
8717  isolate->heap()->CollectAllAvailableGarbage(
8718  i::GarbageCollectionReason::kLowMemoryNotification);
8719  }
8720  {
8721  i::HeapIterator iterator(isolate->heap());
8722  i::HeapObject* obj;
8723  while ((obj = iterator.next()) != nullptr) {
8724  if (obj->IsAbstractCode()) {
8725  i::AbstractCode::cast(obj)->DropStackFrameCache();
8726  }
8727  }
8728  }
8729 }
8730 
8731 
8732 int Isolate::ContextDisposedNotification(bool dependant_context) {
8733  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8734  if (!dependant_context) {
8735  // We left the current context, we can abort all WebAssembly compilations on
8736  // that isolate.
8737  isolate->wasm_engine()->DeleteCompileJobsOnIsolate(isolate);
8738  }
8739  // TODO(ahaas): move other non-heap activity out of the heap call.
8740  return isolate->heap()->NotifyContextDisposed(dependant_context);
8741 }
8742 
8743 
8744 void Isolate::IsolateInForegroundNotification() {
8745  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8746  return isolate->IsolateInForegroundNotification();
8747 }
8748 
8749 
8750 void Isolate::IsolateInBackgroundNotification() {
8751  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8752  return isolate->IsolateInBackgroundNotification();
8753 }
8754 
8755 void Isolate::MemoryPressureNotification(MemoryPressureLevel level) {
8756  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8757  bool on_isolate_thread =
8758  v8::Locker::IsActive()
8759  ? isolate->thread_manager()->IsLockedByCurrentThread()
8760  : i::ThreadId::Current().Equals(isolate->thread_id());
8761  isolate->heap()->MemoryPressureNotification(level, on_isolate_thread);
8762  isolate->allocator()->MemoryPressureNotification(level);
8763 }
8764 
8765 void Isolate::EnableMemorySavingsMode() {
8766  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8767  isolate->EnableMemorySavingsMode();
8768 }
8769 
8770 void Isolate::DisableMemorySavingsMode() {
8771  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8772  isolate->DisableMemorySavingsMode();
8773 }
8774 
8775 void Isolate::SetRAILMode(RAILMode rail_mode) {
8776  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8777  return isolate->SetRAILMode(rail_mode);
8778 }
8779 
8780 void Isolate::IncreaseHeapLimitForDebugging() {
8781  // No-op.
8782 }
8783 
8784 void Isolate::RestoreOriginalHeapLimit() {
8785  // No-op.
8786 }
8787 
8788 bool Isolate::IsHeapLimitIncreasedForDebugging() { return false; }
8789 
8790 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
8791  JitCodeEventHandler event_handler) {
8792  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8793  // Ensure that logging is initialized for our isolate.
8794  isolate->InitializeLoggingAndCounters();
8795  isolate->logger()->SetCodeEventHandler(options, event_handler);
8796 }
8797 
8798 
8799 void Isolate::SetStackLimit(uintptr_t stack_limit) {
8800  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8801  CHECK(stack_limit);
8802  isolate->stack_guard()->SetStackLimit(stack_limit);
8803 }
8804 
8805 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
8806  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8807  const base::AddressRegion& code_range =
8808  isolate->heap()->memory_allocator()->code_range();
8809  *start = reinterpret_cast<void*>(code_range.begin());
8810  *length_in_bytes = code_range.size();
8811 }
8812 
8813 UnwindState Isolate::GetUnwindState() {
8814  UnwindState unwind_state;
8815  void* code_range_start;
8816  GetCodeRange(&code_range_start, &unwind_state.code_range.length_in_bytes);
8817  unwind_state.code_range.start = code_range_start;
8818 
8819  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8820  unwind_state.embedded_code_range.start =
8821  reinterpret_cast<const void*>(isolate->embedded_blob());
8822  unwind_state.embedded_code_range.length_in_bytes =
8823  isolate->embedded_blob_size();
8824 
8825  i::Code js_entry = isolate->heap()->js_entry_code();
8826  unwind_state.js_entry_stub.code.start =
8827  reinterpret_cast<const void*>(js_entry->InstructionStart());
8828  unwind_state.js_entry_stub.code.length_in_bytes = js_entry->InstructionSize();
8829 
8830  return unwind_state;
8831 }
8832 
8833 #define CALLBACK_SETTER(ExternalName, Type, InternalName) \
8834  void Isolate::Set##ExternalName(Type callback) { \
8835  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); \
8836  isolate->set_##InternalName(callback); \
8837  }
8838 
8839 CALLBACK_SETTER(FatalErrorHandler, FatalErrorCallback, exception_behavior)
8840 CALLBACK_SETTER(OOMErrorHandler, OOMErrorCallback, oom_behavior)
8841 CALLBACK_SETTER(AllowCodeGenerationFromStringsCallback,
8842  AllowCodeGenerationFromStringsCallback, allow_code_gen_callback)
8843 CALLBACK_SETTER(AllowWasmCodeGenerationCallback,
8844  AllowWasmCodeGenerationCallback, allow_wasm_code_gen_callback)
8845 
8846 CALLBACK_SETTER(WasmModuleCallback, ExtensionCallback, wasm_module_callback)
8847 CALLBACK_SETTER(WasmInstanceCallback, ExtensionCallback, wasm_instance_callback)
8848 
8849 CALLBACK_SETTER(WasmCompileStreamingCallback, ApiImplementationCallback,
8850  wasm_compile_streaming_callback)
8851 
8852 CALLBACK_SETTER(WasmStreamingCallback, WasmStreamingCallback,
8853  wasm_streaming_callback)
8854 
8855 CALLBACK_SETTER(WasmThreadsEnabledCallback, WasmThreadsEnabledCallback,
8856  wasm_threads_enabled_callback)
8857 
8858 void Isolate::AddNearHeapLimitCallback(v8::NearHeapLimitCallback callback,
8859  void* data) {
8860  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8861  isolate->heap()->AddNearHeapLimitCallback(callback, data);
8862 }
8863 
8864 void Isolate::RemoveNearHeapLimitCallback(v8::NearHeapLimitCallback callback,
8865  size_t heap_limit) {
8866  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8867  isolate->heap()->RemoveNearHeapLimitCallback(callback, heap_limit);
8868 }
8869 
8870 bool Isolate::IsDead() {
8871  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8872  return isolate->IsDead();
8873 }
8874 
8875 bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
8876  return AddMessageListenerWithErrorLevel(that, kMessageError, data);
8877 }
8878 
8879 bool Isolate::AddMessageListenerWithErrorLevel(MessageCallback that,
8880  int message_levels,
8881  Local<Value> data) {
8882  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8883  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
8884  i::HandleScope scope(isolate);
8885  i::Handle<i::TemplateList> list = isolate->factory()->message_listeners();
8886  i::Handle<i::FixedArray> listener = isolate->factory()->NewFixedArray(3);
8887  i::Handle<i::Foreign> foreign =
8888  isolate->factory()->NewForeign(FUNCTION_ADDR(that));
8889  listener->set(0, *foreign);
8890  listener->set(1, data.IsEmpty() ? i::ReadOnlyRoots(isolate).undefined_value()
8891  : *Utils::OpenHandle(*data));
8892  listener->set(2, i::Smi::FromInt(message_levels));
8893  list = i::TemplateList::Add(isolate, list, listener);
8894  isolate->heap()->SetMessageListeners(*list);
8895  return true;
8896 }
8897 
8898 
8899 void Isolate::RemoveMessageListeners(MessageCallback that) {
8900  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8901  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
8902  i::HandleScope scope(isolate);
8904  i::TemplateList listeners = isolate->heap()->message_listeners();
8905  for (int i = 0; i < listeners->length(); i++) {
8906  if (listeners->get(i)->IsUndefined(isolate)) continue; // skip deleted ones
8907  i::FixedArray listener = i::FixedArray::cast(listeners->get(i));
8908  i::Foreign* callback_obj = i::Foreign::cast(listener->get(0));
8909  if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
8910  listeners->set(i, i::ReadOnlyRoots(isolate).undefined_value());
8911  }
8912  }
8913 }
8914 
8915 
8916 void Isolate::SetFailedAccessCheckCallbackFunction(
8917  FailedAccessCheckCallback callback) {
8918  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8919  isolate->SetFailedAccessCheckCallback(callback);
8920 }
8921 
8922 
8923 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
8924  bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
8925  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8926  isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
8927  options);
8928 }
8929 
8930 
8931 void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) {
8932  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8933  isolate->heap()->VisitExternalResources(visitor);
8934 }
8935 
8936 
8937 bool Isolate::IsInUse() {
8938  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8939  return isolate->IsInUse();
8940 }
8941 
8942 
8943 void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8944  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8945  i::DisallowHeapAllocation no_allocation;
8946  isolate->global_handles()->IterateAllRootsWithClassIds(visitor);
8947 }
8948 
8949 
8950 void Isolate::VisitHandlesForPartialDependence(
8951  PersistentHandleVisitor* visitor) {
8952  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8953  i::DisallowHeapAllocation no_allocation;
8954  isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds(visitor);
8955 }
8956 
8957 
8958 void Isolate::VisitWeakHandles(PersistentHandleVisitor* visitor) {
8959  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8960  i::DisallowHeapAllocation no_allocation;
8961  isolate->global_handles()->IterateWeakRootsInNewSpaceWithClassIds(visitor);
8962 }
8963 
8964 void Isolate::SetAllowAtomicsWait(bool allow) {
8965  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
8966  isolate->set_allow_atomics_wait(allow);
8967 }
8968 
8969 MicrotasksScope::MicrotasksScope(Isolate* isolate, MicrotasksScope::Type type)
8970  : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
8971  run_(type == MicrotasksScope::kRunMicrotasks) {
8972  auto handle_scope_implementer = isolate_->handle_scope_implementer();
8973  if (run_) handle_scope_implementer->IncrementMicrotasksScopeDepth();
8974 #ifdef DEBUG
8975  if (!run_) handle_scope_implementer->IncrementDebugMicrotasksScopeDepth();
8976 #endif
8977 }
8978 
8979 
8980 MicrotasksScope::~MicrotasksScope() {
8981  auto handle_scope_implementer = isolate_->handle_scope_implementer();
8982  if (run_) {
8983  handle_scope_implementer->DecrementMicrotasksScopeDepth();
8984  if (MicrotasksPolicy::kScoped ==
8985  handle_scope_implementer->microtasks_policy()) {
8986  PerformCheckpoint(reinterpret_cast<Isolate*>(isolate_));
8987  }
8988  }
8989 #ifdef DEBUG
8990  if (!run_) handle_scope_implementer->DecrementDebugMicrotasksScopeDepth();
8991 #endif
8992 }
8993 
8994 
8995 void MicrotasksScope::PerformCheckpoint(Isolate* v8Isolate) {
8996  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8Isolate);
8997  if (IsExecutionTerminatingCheck(isolate)) return;
8998  auto handle_scope_implementer = isolate->handle_scope_implementer();
8999  if (!handle_scope_implementer->GetMicrotasksScopeDepth() &&
9000  !handle_scope_implementer->HasMicrotasksSuppressions()) {
9001  isolate->RunMicrotasks();
9002  }
9003 }
9004 
9005 
9006 int MicrotasksScope::GetCurrentDepth(Isolate* v8Isolate) {
9007  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8Isolate);
9008  return isolate->handle_scope_implementer()->GetMicrotasksScopeDepth();
9009 }
9010 
9011 bool MicrotasksScope::IsRunningMicrotasks(Isolate* v8Isolate) {
9012  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8Isolate);
9013  return isolate->IsRunningMicrotasks();
9014 }
9015 
9016 String::Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> obj)
9017  : str_(nullptr), length_(0) {
9018  if (obj.IsEmpty()) return;
9019  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
9020  ENTER_V8_DO_NOT_USE(i_isolate);
9021  i::HandleScope scope(i_isolate);
9022  Local<Context> context = isolate->GetCurrentContext();
9023  TryCatch try_catch(isolate);
9024  Local<String> str;
9025  if (!obj->ToString(context).ToLocal(&str)) return;
9026  length_ = str->Utf8Length(isolate);
9027  str_ = i::NewArray<char>(length_ + 1);
9028  str->WriteUtf8(isolate, str_);
9029 }
9030 
9031 String::Utf8Value::~Utf8Value() {
9032  i::DeleteArray(str_);
9033 }
9034 
9035 String::Value::Value(v8::Isolate* isolate, v8::Local<v8::Value> obj)
9036  : str_(nullptr), length_(0) {
9037  if (obj.IsEmpty()) return;
9038  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
9039  ENTER_V8_DO_NOT_USE(i_isolate);
9040  i::HandleScope scope(i_isolate);
9041  Local<Context> context = isolate->GetCurrentContext();
9042  TryCatch try_catch(isolate);
9043  Local<String> str;
9044  if (!obj->ToString(context).ToLocal(&str)) return;
9045  length_ = str->Length();
9046  str_ = i::NewArray<uint16_t>(length_ + 1);
9047  str->Write(isolate, str_);
9048 }
9049 
9050 String::Value::~Value() {
9051  i::DeleteArray(str_);
9052 }
9053 
9054 #define DEFINE_ERROR(NAME, name) \
9055  Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) { \
9056  i::Isolate* isolate = i::Isolate::Current(); \
9057  LOG_API(isolate, NAME, New); \
9058  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate); \
9059  i::Object* error; \
9060  { \
9061  i::HandleScope scope(isolate); \
9062  i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \
9063  i::Handle<i::JSFunction> constructor = isolate->name##_function(); \
9064  error = *isolate->factory()->NewError(constructor, message); \
9065  } \
9066  i::Handle<i::Object> result(error, isolate); \
9067  return Utils::ToLocal(result); \
9068  }
9069 
9070 DEFINE_ERROR(RangeError, range_error)
9071 DEFINE_ERROR(ReferenceError, reference_error)
9072 DEFINE_ERROR(SyntaxError, syntax_error)
9073 DEFINE_ERROR(TypeError, type_error)
9074 DEFINE_ERROR(Error, error)
9075 
9076 #undef DEFINE_ERROR
9077 
9078 
9079 Local<Message> Exception::CreateMessage(Isolate* isolate,
9080  Local<Value> exception) {
9081  i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
9082  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
9083  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
9084  i::HandleScope scope(i_isolate);
9085  return Utils::MessageToLocal(
9086  scope.CloseAndEscape(i_isolate->CreateMessage(obj, nullptr)));
9087 }
9088 
9089 
9090 Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) {
9091  i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
9092  if (!obj->IsJSObject()) return Local<StackTrace>();
9094  i::Isolate* isolate = js_obj->GetIsolate();
9095  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9096  return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj));
9097 }
9098 
9099 
9100 // --- D e b u g S u p p o r t ---
9101 
9102 void debug::SetContextId(Local<Context> context, int id) {
9103  Utils::OpenHandle(*context)->set_debug_context_id(i::Smi::FromInt(id));
9104 }
9105 
9106 int debug::GetContextId(Local<Context> context) {
9107  i::Object* value = Utils::OpenHandle(*context)->debug_context_id();
9108  return (value->IsSmi()) ? i::Smi::ToInt(value) : 0;
9109 }
9110 
9111 void debug::SetInspector(Isolate* isolate,
9112  v8_inspector::V8Inspector* inspector) {
9113  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
9114  i_isolate->set_inspector(inspector);
9115 }
9116 
9117 v8_inspector::V8Inspector* debug::GetInspector(Isolate* isolate) {
9118  return reinterpret_cast<i::Isolate*>(isolate)->inspector();
9119 }
9120 
9121 void debug::SetBreakOnNextFunctionCall(Isolate* isolate) {
9122  reinterpret_cast<i::Isolate*>(isolate)->debug()->SetBreakOnNextFunctionCall();
9123 }
9124 
9125 void debug::ClearBreakOnNextFunctionCall(Isolate* isolate) {
9126  reinterpret_cast<i::Isolate*>(isolate)
9127  ->debug()
9128  ->ClearBreakOnNextFunctionCall();
9129 }
9130 
9131 MaybeLocal<Array> debug::GetInternalProperties(Isolate* v8_isolate,
9132  Local<Value> value) {
9133  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9134  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9135  i::Handle<i::Object> val = Utils::OpenHandle(*value);
9136  i::Handle<i::JSArray> result;
9137  if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
9138  return MaybeLocal<Array>();
9139  return Utils::ToLocal(result);
9140 }
9141 
9142 void debug::ChangeBreakOnException(Isolate* isolate, ExceptionBreakState type) {
9143  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
9144  internal_isolate->debug()->ChangeBreakOnException(
9145  i::BreakException, type == BreakOnAnyException);
9146  internal_isolate->debug()->ChangeBreakOnException(i::BreakUncaughtException,
9147  type != NoBreakOnException);
9148 }
9149 
9150 void debug::SetBreakPointsActive(Isolate* v8_isolate, bool is_active) {
9151  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9152  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9153  isolate->debug()->set_break_points_active(is_active);
9154 }
9155 
9156 void debug::PrepareStep(Isolate* v8_isolate, StepAction action) {
9157  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9158  ENTER_V8_DO_NOT_USE(isolate);
9159  CHECK(isolate->debug()->CheckExecutionState());
9160  // Clear all current stepping setup.
9161  isolate->debug()->ClearStepping();
9162  // Prepare step.
9163  isolate->debug()->PrepareStep(static_cast<i::StepAction>(action));
9164 }
9165 
9166 void debug::ClearStepping(Isolate* v8_isolate) {
9167  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9168  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9169  // Clear all current stepping setup.
9170  isolate->debug()->ClearStepping();
9171 }
9172 
9173 void debug::BreakRightNow(Isolate* v8_isolate) {
9174  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9175  ENTER_V8_DO_NOT_USE(isolate);
9176  isolate->debug()->HandleDebugBreak(i::kIgnoreIfAllFramesBlackboxed);
9177 }
9178 
9179 bool debug::AllFramesOnStackAreBlackboxed(Isolate* v8_isolate) {
9180  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9181  ENTER_V8_DO_NOT_USE(isolate);
9182  return isolate->debug()->AllFramesOnStackAreBlackboxed();
9183 }
9184 
9185 v8::Isolate* debug::Script::GetIsolate() const {
9186  return reinterpret_cast<v8::Isolate*>(Utils::OpenHandle(this)->GetIsolate());
9187 }
9188 
9189 ScriptOriginOptions debug::Script::OriginOptions() const {
9190  return Utils::OpenHandle(this)->origin_options();
9191 }
9192 
9193 bool debug::Script::WasCompiled() const {
9194  return Utils::OpenHandle(this)->compilation_state() ==
9195  i::Script::COMPILATION_STATE_COMPILED;
9196 }
9197 
9198 bool debug::Script::IsEmbedded() const {
9199  i::Handle<i::Script> script = Utils::OpenHandle(this);
9200  return script->context_data() ==
9201  script->GetReadOnlyRoots().uninitialized_symbol();
9202 }
9203 
9204 int debug::Script::Id() const { return Utils::OpenHandle(this)->id(); }
9205 
9206 int debug::Script::LineOffset() const {
9207  return Utils::OpenHandle(this)->line_offset();
9208 }
9209 
9210 int debug::Script::ColumnOffset() const {
9211  return Utils::OpenHandle(this)->column_offset();
9212 }
9213 
9214 std::vector<int> debug::Script::LineEnds() const {
9215  i::Handle<i::Script> script = Utils::OpenHandle(this);
9216  if (script->type() == i::Script::TYPE_WASM &&
9217  this->SourceMappingURL().IsEmpty()) {
9218  return std::vector<int>();
9219  }
9220  i::Isolate* isolate = script->GetIsolate();
9221  i::HandleScope scope(isolate);
9222  i::Script::InitLineEnds(script);
9223  CHECK(script->line_ends()->IsFixedArray());
9224  i::Handle<i::FixedArray> line_ends(i::FixedArray::cast(script->line_ends()),
9225  isolate);
9226  std::vector<int> result(line_ends->length());
9227  for (int i = 0; i < line_ends->length(); ++i) {
9228  i::Smi line_end = i::Smi::cast(line_ends->get(i));
9229  result[i] = line_end->value();
9230  }
9231  return result;
9232 }
9233 
9234 MaybeLocal<String> debug::Script::Name() const {
9235  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
9236  i::HandleScope handle_scope(isolate);
9237  i::Handle<i::Script> script = Utils::OpenHandle(this);
9238  i::Handle<i::Object> value(script->name(), isolate);
9239  if (!value->IsString()) return MaybeLocal<String>();
9240  return Utils::ToLocal(
9241  handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
9242 }
9243 
9244 MaybeLocal<String> debug::Script::SourceURL() const {
9245  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
9246  i::HandleScope handle_scope(isolate);
9247  i::Handle<i::Script> script = Utils::OpenHandle(this);
9248  i::Handle<i::Object> value(script->source_url(), isolate);
9249  if (!value->IsString()) return MaybeLocal<String>();
9250  return Utils::ToLocal(
9251  handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
9252 }
9253 
9254 MaybeLocal<String> debug::Script::SourceMappingURL() const {
9255  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
9256  i::HandleScope handle_scope(isolate);
9257  i::Handle<i::Script> script = Utils::OpenHandle(this);
9258  i::Handle<i::Object> value(script->source_mapping_url(), isolate);
9259  if (!value->IsString()) return MaybeLocal<String>();
9260  return Utils::ToLocal(
9261  handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
9262 }
9263 
9264 Maybe<int> debug::Script::ContextId() const {
9265  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
9266  i::HandleScope handle_scope(isolate);
9267  i::Handle<i::Script> script = Utils::OpenHandle(this);
9268  i::Object* value = script->context_data();
9269  if (value->IsSmi()) return Just(i::Smi::ToInt(value));
9270  return Nothing<int>();
9271 }
9272 
9273 MaybeLocal<String> debug::Script::Source() const {
9274  i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
9275  i::HandleScope handle_scope(isolate);
9276  i::Handle<i::Script> script = Utils::OpenHandle(this);
9277  i::Handle<i::Object> value(script->source(), isolate);
9278  if (!value->IsString()) return MaybeLocal<String>();
9279  return Utils::ToLocal(
9280  handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
9281 }
9282 
9283 bool debug::Script::IsWasm() const {
9284  return Utils::OpenHandle(this)->type() == i::Script::TYPE_WASM;
9285 }
9286 
9287 bool debug::Script::IsModule() const {
9288  return Utils::OpenHandle(this)->origin_options().IsModule();
9289 }
9290 
9291 namespace {
9292 int GetSmiValue(i::Handle<i::FixedArray> array, int index) {
9293  return i::Smi::ToInt(array->get(index));
9294 }
9295 
9296 bool CompareBreakLocation(const i::BreakLocation& loc1,
9297  const i::BreakLocation& loc2) {
9298  return loc1.position() < loc2.position();
9299 }
9300 } // namespace
9301 
9302 bool debug::Script::GetPossibleBreakpoints(
9303  const debug::Location& start, const debug::Location& end,
9304  bool restrict_to_function,
9305  std::vector<debug::BreakLocation>* locations) const {
9306  CHECK(!start.IsEmpty());
9307  i::Handle<i::Script> script = Utils::OpenHandle(this);
9308  if (script->type() == i::Script::TYPE_WASM &&
9309  this->SourceMappingURL().IsEmpty()) {
9310  i::WasmModuleObject* module_object =
9311  i::WasmModuleObject::cast(script->wasm_module_object());
9312  return module_object->GetPossibleBreakpoints(start, end, locations);
9313  }
9314 
9315  i::Script::InitLineEnds(script);
9316  CHECK(script->line_ends()->IsFixedArray());
9317  i::Isolate* isolate = script->GetIsolate();
9318  i::Handle<i::FixedArray> line_ends =
9319  i::Handle<i::FixedArray>::cast(i::handle(script->line_ends(), isolate));
9320  CHECK(line_ends->length());
9321 
9322  int start_offset = GetSourceOffset(start);
9323  int end_offset = end.IsEmpty()
9324  ? GetSmiValue(line_ends, line_ends->length() - 1) + 1
9325  : GetSourceOffset(end);
9326  if (start_offset >= end_offset) return true;
9327 
9328  std::vector<i::BreakLocation> v8_locations;
9329  if (!isolate->debug()->GetPossibleBreakpoints(
9330  script, start_offset, end_offset, restrict_to_function,
9331  &v8_locations)) {
9332  return false;
9333  }
9334 
9335  std::sort(v8_locations.begin(), v8_locations.end(), CompareBreakLocation);
9336  int current_line_end_index = 0;
9337  for (const auto& v8_location : v8_locations) {
9338  int offset = v8_location.position();
9339  while (offset > GetSmiValue(line_ends, current_line_end_index)) {
9340  ++current_line_end_index;
9341  CHECK(current_line_end_index < line_ends->length());
9342  }
9343  int line_offset = 0;
9344 
9345  if (current_line_end_index > 0) {
9346  line_offset = GetSmiValue(line_ends, current_line_end_index - 1) + 1;
9347  }
9348  locations->emplace_back(
9349  current_line_end_index + script->line_offset(),
9350  offset - line_offset +
9351  (current_line_end_index == 0 ? script->column_offset() : 0),
9352  v8_location.type());
9353  }
9354  return true;
9355 }
9356 
9357 int debug::Script::GetSourceOffset(const debug::Location& location) const {
9358  i::Handle<i::Script> script = Utils::OpenHandle(this);
9359  if (script->type() == i::Script::TYPE_WASM) {
9360  if (this->SourceMappingURL().IsEmpty()) {
9361  return i::WasmModuleObject::cast(script->wasm_module_object())
9362  ->GetFunctionOffset(location.GetLineNumber()) +
9363  location.GetColumnNumber();
9364  }
9365  DCHECK_EQ(0, location.GetLineNumber());
9366  return location.GetColumnNumber();
9367  }
9368 
9369  int line = std::max(location.GetLineNumber() - script->line_offset(), 0);
9370  int column = location.GetColumnNumber();
9371  if (line == 0) {
9372  column = std::max(0, column - script->column_offset());
9373  }
9374 
9375  i::Script::InitLineEnds(script);
9376  CHECK(script->line_ends()->IsFixedArray());
9378  i::handle(script->line_ends(), script->GetIsolate()));
9379  CHECK(line_ends->length());
9380  if (line >= line_ends->length())
9381  return GetSmiValue(line_ends, line_ends->length() - 1);
9382  int line_offset = GetSmiValue(line_ends, line);
9383  if (line == 0) return std::min(column, line_offset);
9384  int prev_line_offset = GetSmiValue(line_ends, line - 1);
9385  return std::min(prev_line_offset + column + 1, line_offset);
9386 }
9387 
9388 v8::debug::Location debug::Script::GetSourceLocation(int offset) const {
9389  i::Handle<i::Script> script = Utils::OpenHandle(this);
9390  i::Script::PositionInfo info;
9391  i::Script::GetPositionInfo(script, offset, &info, i::Script::WITH_OFFSET);
9392  return debug::Location(info.line, info.column);
9393 }
9394 
9395 bool debug::Script::SetScriptSource(v8::Local<v8::String> newSource,
9396  bool preview,
9397  debug::LiveEditResult* result) const {
9398  i::Handle<i::Script> script = Utils::OpenHandle(this);
9399  i::Isolate* isolate = script->GetIsolate();
9400  return isolate->debug()->SetScriptSource(
9401  script, Utils::OpenHandle(*newSource), preview, result);
9402 }
9403 
9404 bool debug::Script::SetBreakpoint(v8::Local<v8::String> condition,
9405  debug::Location* location,
9406  debug::BreakpointId* id) const {
9407  i::Handle<i::Script> script = Utils::OpenHandle(this);
9408  i::Isolate* isolate = script->GetIsolate();
9409  int offset = GetSourceOffset(*location);
9410  if (!isolate->debug()->SetBreakPointForScript(
9411  script, Utils::OpenHandle(*condition), &offset, id)) {
9412  return false;
9413  }
9414  *location = GetSourceLocation(offset);
9415  return true;
9416 }
9417 
9418 void debug::RemoveBreakpoint(Isolate* v8_isolate, BreakpointId id) {
9419  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9420  i::HandleScope handle_scope(isolate);
9421  isolate->debug()->RemoveBreakpoint(id);
9422 }
9423 
9424 v8::Platform* debug::GetCurrentPlatform() {
9425  return i::V8::GetCurrentPlatform();
9426 }
9427 
9428 debug::WasmScript* debug::WasmScript::Cast(debug::Script* script) {
9429  CHECK(script->IsWasm());
9430  return static_cast<WasmScript*>(script);
9431 }
9432 
9433 int debug::WasmScript::NumFunctions() const {
9435  i::Handle<i::Script> script = Utils::OpenHandle(this);
9436  DCHECK_EQ(i::Script::TYPE_WASM, script->type());
9437  i::WasmModuleObject* module_object =
9438  i::WasmModuleObject::cast(script->wasm_module_object());
9439  const i::wasm::WasmModule* module = module_object->module();
9440  DCHECK_GE(i::kMaxInt, module->functions.size());
9441  return static_cast<int>(module->functions.size());
9442 }
9443 
9444 int debug::WasmScript::NumImportedFunctions() const {
9446  i::Handle<i::Script> script = Utils::OpenHandle(this);
9447  DCHECK_EQ(i::Script::TYPE_WASM, script->type());
9448  i::WasmModuleObject* module_object =
9449  i::WasmModuleObject::cast(script->wasm_module_object());
9450  const i::wasm::WasmModule* module = module_object->module();
9451  DCHECK_GE(i::kMaxInt, module->num_imported_functions);
9452  return static_cast<int>(module->num_imported_functions);
9453 }
9454 
9455 std::pair<int, int> debug::WasmScript::GetFunctionRange(
9456  int function_index) const {
9458  i::Handle<i::Script> script = Utils::OpenHandle(this);
9459  DCHECK_EQ(i::Script::TYPE_WASM, script->type());
9460  i::WasmModuleObject* module_object =
9461  i::WasmModuleObject::cast(script->wasm_module_object());
9462  const i::wasm::WasmModule* module = module_object->module();
9463  DCHECK_LE(0, function_index);
9464  DCHECK_GT(module->functions.size(), function_index);
9465  const i::wasm::WasmFunction& func = module->functions[function_index];
9466  DCHECK_GE(i::kMaxInt, func.code.offset());
9467  DCHECK_GE(i::kMaxInt, func.code.end_offset());
9468  return std::make_pair(static_cast<int>(func.code.offset()),
9469  static_cast<int>(func.code.end_offset()));
9470 }
9471 
9472 uint32_t debug::WasmScript::GetFunctionHash(int function_index) {
9474  i::Handle<i::Script> script = Utils::OpenHandle(this);
9475  DCHECK_EQ(i::Script::TYPE_WASM, script->type());
9476  i::WasmModuleObject* module_object =
9477  i::WasmModuleObject::cast(script->wasm_module_object());
9478  const i::wasm::WasmModule* module = module_object->module();
9479  DCHECK_LE(0, function_index);
9480  DCHECK_GT(module->functions.size(), function_index);
9481  const i::wasm::WasmFunction& func = module->functions[function_index];
9482  i::wasm::ModuleWireBytes wire_bytes(
9483  module_object->native_module()->wire_bytes());
9484  i::Vector<const i::byte> function_bytes = wire_bytes.GetFunctionBytes(&func);
9485  // TODO(herhut): Maybe also take module, name and signature into account.
9486  return i::StringHasher::HashSequentialString(function_bytes.start(),
9487  function_bytes.length(), 0);
9488 }
9489 
9490 debug::WasmDisassembly debug::WasmScript::DisassembleFunction(
9491  int function_index) const {
9493  i::Handle<i::Script> script = Utils::OpenHandle(this);
9494  DCHECK_EQ(i::Script::TYPE_WASM, script->type());
9495  i::WasmModuleObject* module_object =
9496  i::WasmModuleObject::cast(script->wasm_module_object());
9497  return module_object->DisassembleFunction(function_index);
9498 }
9499 
9500 debug::Location::Location(int line_number, int column_number)
9501  : line_number_(line_number),
9502  column_number_(column_number),
9503  is_empty_(false) {}
9504 
9506  : line_number_(v8::Function::kLineOffsetNotFound),
9507  column_number_(v8::Function::kLineOffsetNotFound),
9508  is_empty_(true) {}
9509 
9510 int debug::Location::GetLineNumber() const {
9511  DCHECK(!IsEmpty());
9512  return line_number_;
9513 }
9514 
9515 int debug::Location::GetColumnNumber() const {
9516  DCHECK(!IsEmpty());
9517  return column_number_;
9518 }
9519 
9520 bool debug::Location::IsEmpty() const { return is_empty_; }
9521 
9522 void debug::GetLoadedScripts(v8::Isolate* v8_isolate,
9523  PersistentValueVector<debug::Script>& scripts) {
9524  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9525  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9526  {
9528  i::Script::Iterator iterator(isolate);
9529  i::Script* script;
9530  while ((script = iterator.Next()) != nullptr) {
9531  if (!script->IsUserJavaScript()) continue;
9532  if (script->HasValidSource()) {
9533  i::HandleScope handle_scope(isolate);
9534  i::Handle<i::Script> script_handle(script, isolate);
9535  scripts.Append(ToApiHandle<Script>(script_handle));
9536  }
9537  }
9538  }
9539 }
9540 
9541 MaybeLocal<UnboundScript> debug::CompileInspectorScript(Isolate* v8_isolate,
9542  Local<String> source) {
9543  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9544  PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, UnboundScript);
9545  i::Handle<i::String> str = Utils::OpenHandle(*source);
9547  {
9548  ScriptOriginOptions origin_options;
9549  i::ScriptData* script_data = nullptr;
9550  i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
9551  i::Compiler::GetSharedFunctionInfoForScript(
9552  isolate, str, i::Compiler::ScriptDetails(), origin_options, nullptr,
9553  script_data, ScriptCompiler::kNoCompileOptions,
9554  ScriptCompiler::kNoCacheBecauseInspector,
9555  i::FLAG_expose_inspector_scripts ? i::NOT_NATIVES_CODE
9556  : i::INSPECTOR_CODE);
9557  has_pending_exception = !maybe_function_info.ToHandle(&result);
9558  RETURN_ON_FAILED_EXECUTION(UnboundScript);
9559  }
9560  RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
9561 }
9562 
9563 void debug::SetDebugDelegate(Isolate* v8_isolate,
9564  debug::DebugDelegate* delegate) {
9565  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9566  isolate->debug()->SetDebugDelegate(delegate);
9567 }
9568 
9569 void debug::SetAsyncEventDelegate(Isolate* v8_isolate,
9570  debug::AsyncEventDelegate* delegate) {
9571  reinterpret_cast<i::Isolate*>(v8_isolate)->set_async_event_delegate(delegate);
9572 }
9573 
9574 void debug::ResetBlackboxedStateCache(Isolate* v8_isolate,
9575  v8::Local<debug::Script> script) {
9576  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9577  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9579  i::SharedFunctionInfo::ScriptIterator iter(isolate,
9580  *Utils::OpenHandle(*script));
9581  while (i::SharedFunctionInfo* info = iter.Next()) {
9582  if (info->HasDebugInfo()) {
9583  info->GetDebugInfo()->set_computed_debug_is_blackboxed(false);
9584  }
9585  }
9586 }
9587 
9588 int debug::EstimatedValueSize(Isolate* v8_isolate, v8::Local<v8::Value> value) {
9589  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9590  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9591  i::Handle<i::Object> object = Utils::OpenHandle(*value);
9592  if (object->IsSmi()) return i::kPointerSize;
9593  CHECK(object->IsHeapObject());
9594  return i::Handle<i::HeapObject>::cast(object)->Size();
9595 }
9596 
9598  if (IsMap()) {
9599  *is_key_value = true;
9600  return Map::Cast(this)->AsArray();
9601  }
9602  if (IsSet()) {
9603  *is_key_value = false;
9604  return Set::Cast(this)->AsArray();
9605  }
9606 
9607  i::Handle<i::JSReceiver> object = Utils::OpenHandle(this);
9608  i::Isolate* isolate = object->GetIsolate();
9609  Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
9610  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9611  if (object->IsJSWeakCollection()) {
9612  *is_key_value = object->IsJSWeakMap();
9613  return Utils::ToLocal(i::JSWeakCollection::GetEntries(
9615  }
9616  if (object->IsJSMapIterator()) {
9617  i::Handle<i::JSMapIterator> iterator =
9619  MapAsArrayKind const kind =
9620  static_cast<MapAsArrayKind>(iterator->map()->instance_type());
9621  *is_key_value = kind == MapAsArrayKind::kEntries;
9622  if (!iterator->HasMore()) return v8::Array::New(v8_isolate);
9623  return Utils::ToLocal(MapAsArray(isolate, iterator->table(),
9624  i::Smi::ToInt(iterator->index()), kind));
9625  }
9626  if (object->IsJSSetIterator()) {
9628  *is_key_value = false;
9629  if (!it->HasMore()) return v8::Array::New(v8_isolate);
9630  return Utils::ToLocal(
9631  SetAsArray(isolate, it->table(), i::Smi::ToInt(it->index())));
9632  }
9633  return v8::MaybeLocal<v8::Array>();
9634 }
9635 
9636 Local<Function> debug::GetBuiltin(Isolate* v8_isolate, Builtin builtin) {
9637  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9638  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9639  i::HandleScope handle_scope(isolate);
9640  i::Builtins::Name builtin_id;
9641  switch (builtin) {
9642  case kStringToLowerCase:
9643  builtin_id = i::Builtins::kStringPrototypeToLocaleLowerCase;
9644  break;
9645  default:
9646  UNREACHABLE();
9647  }
9648 
9649  i::Handle<i::String> name = isolate->factory()->empty_string();
9650  i::NewFunctionArgs args = i::NewFunctionArgs::ForBuiltinWithoutPrototype(
9651  name, builtin_id, i::LanguageMode::kStrict);
9652  i::Handle<i::JSFunction> fun = isolate->factory()->NewFunction(args);
9653 
9654  fun->shared()->set_internal_formal_parameter_count(0);
9655  fun->shared()->set_length(0);
9656  return Utils::ToLocal(handle_scope.CloseAndEscape(fun));
9657 }
9658 
9659 void debug::SetConsoleDelegate(Isolate* v8_isolate, ConsoleDelegate* delegate) {
9660  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9661  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9662  isolate->set_console_delegate(delegate);
9663 }
9664 
9665 debug::ConsoleCallArguments::ConsoleCallArguments(
9667  : v8::FunctionCallbackInfo<v8::Value>(nullptr, info.values_, info.length_) {
9668 }
9669 
9670 debug::ConsoleCallArguments::ConsoleCallArguments(
9671  internal::BuiltinArguments& args)
9672  : v8::FunctionCallbackInfo<v8::Value>(
9673  nullptr,
9674  // Drop the first argument (receiver, i.e. the "console" object).
9675  args.address_of_arg_at(args.length() > 1 ? 1 : 0),
9676  args.length() - 1) {}
9677 
9678 int debug::GetStackFrameId(v8::Local<v8::StackFrame> frame) {
9679  return Utils::OpenHandle(*frame)->id();
9680 }
9681 
9682 v8::Local<v8::StackTrace> debug::GetDetailedStackTrace(
9683  Isolate* v8_isolate, v8::Local<v8::Object> v8_error) {
9684  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9685  i::Handle<i::JSReceiver> error = Utils::OpenHandle(*v8_error);
9686  if (!error->IsJSObject()) {
9687  return v8::Local<v8::StackTrace>();
9688  }
9689  i::Handle<i::FixedArray> stack_trace =
9690  isolate->GetDetailedStackTrace(i::Handle<i::JSObject>::cast(error));
9691  return Utils::StackTraceToLocal(stack_trace);
9692 }
9693 
9694 MaybeLocal<debug::Script> debug::GeneratorObject::Script() {
9695  i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
9696  i::Object* maybe_script = obj->function()->shared()->script();
9697  if (!maybe_script->IsScript()) return MaybeLocal<debug::Script>();
9698  i::Handle<i::Script> script(i::Script::cast(maybe_script), obj->GetIsolate());
9699  return ToApiHandle<debug::Script>(script);
9700 }
9701 
9702 Local<Function> debug::GeneratorObject::Function() {
9703  i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
9704  return Utils::ToLocal(handle(obj->function(), obj->GetIsolate()));
9705 }
9706 
9707 debug::Location debug::GeneratorObject::SuspendedLocation() {
9708  i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
9709  CHECK(obj->is_suspended());
9710  i::Object* maybe_script = obj->function()->shared()->script();
9711  if (!maybe_script->IsScript()) return debug::Location();
9712  i::Handle<i::Script> script(i::Script::cast(maybe_script), obj->GetIsolate());
9713  i::Script::PositionInfo info;
9714  i::Script::GetPositionInfo(script, obj->source_position(), &info,
9715  i::Script::WITH_OFFSET);
9716  return debug::Location(info.line, info.column);
9717 }
9718 
9719 bool debug::GeneratorObject::IsSuspended() {
9720  return Utils::OpenHandle(this)->is_suspended();
9721 }
9722 
9723 v8::Local<debug::GeneratorObject> debug::GeneratorObject::Cast(
9724  v8::Local<v8::Value> value) {
9725  CHECK(value->IsGeneratorObject());
9726  return ToApiHandle<debug::GeneratorObject>(Utils::OpenHandle(*value));
9727 }
9728 
9729 MaybeLocal<v8::Value> debug::EvaluateGlobal(v8::Isolate* isolate,
9730  v8::Local<v8::String> source,
9731  bool throw_on_side_effect) {
9732  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
9733  PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(internal_isolate, Value);
9734  Local<Value> result;
9735  has_pending_exception = !ToLocal<Value>(
9736  i::DebugEvaluate::Global(internal_isolate, Utils::OpenHandle(*source),
9737  throw_on_side_effect),
9738  &result);
9739  RETURN_ON_FAILED_EXECUTION(Value);
9740  RETURN_ESCAPED(result);
9741 }
9742 
9743 void debug::QueryObjects(v8::Local<v8::Context> v8_context,
9744  QueryObjectPredicate* predicate,
9745  PersistentValueVector<v8::Object>* objects) {
9746  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_context->GetIsolate());
9747  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
9748  isolate->heap_profiler()->QueryObjects(Utils::OpenHandle(*v8_context),
9749  predicate, objects);
9750 }
9751 
9752 void debug::GlobalLexicalScopeNames(
9753  v8::Local<v8::Context> v8_context,
9755  i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
9756  i::Isolate* isolate = context->GetIsolate();
9758  context->global_object()->native_context()->script_context_table(),
9759  isolate);
9760  for (int i = 0; i < table->used(); i++) {
9761  i::Handle<i::Context> context =
9762  i::ScriptContextTable::GetContext(isolate, table, i);
9763  DCHECK(context->IsScriptContext());
9764  i::Handle<i::ScopeInfo> scope_info(context->scope_info(), isolate);
9765  int local_count = scope_info->ContextLocalCount();
9766  for (int j = 0; j < local_count; ++j) {
9767  i::String name = scope_info->ContextLocalName(j);
9768  if (i::ScopeInfo::VariableIsSynthetic(name)) continue;
9769  names->Append(Utils::ToLocal(handle(name, isolate)));
9770  }
9771  }
9772 }
9773 
9774 void debug::SetReturnValue(v8::Isolate* v8_isolate,
9775  v8::Local<v8::Value> value) {
9776  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9777  isolate->debug()->set_return_value(*Utils::OpenHandle(*value));
9778 }
9779 
9780 int64_t debug::GetNextRandomInt64(v8::Isolate* v8_isolate) {
9781  return reinterpret_cast<i::Isolate*>(v8_isolate)
9782  ->random_number_generator()
9783  ->NextInt64();
9784 }
9785 
9786 int debug::GetDebuggingId(v8::Local<v8::Function> function) {
9787  i::Handle<i::JSReceiver> callable = v8::Utils::OpenHandle(*function);
9788  if (!callable->IsJSFunction()) return i::DebugInfo::kNoDebuggingId;
9790  int id = func->GetIsolate()->debug()->GetFunctionDebuggingId(func);
9791  DCHECK_NE(i::DebugInfo::kNoDebuggingId, id);
9792  return id;
9793 }
9794 
9795 bool debug::SetFunctionBreakpoint(v8::Local<v8::Function> function,
9796  v8::Local<v8::String> condition,
9797  BreakpointId* id) {
9798  i::Handle<i::JSReceiver> callable = Utils::OpenHandle(*function);
9799  if (!callable->IsJSFunction()) return false;
9800  i::Handle<i::JSFunction> jsfunction =
9802  i::Isolate* isolate = jsfunction->GetIsolate();
9803  i::Handle<i::String> condition_string =
9804  condition.IsEmpty() ? isolate->factory()->empty_string()
9805  : Utils::OpenHandle(*condition);
9806  return isolate->debug()->SetBreakpointForFunction(jsfunction,
9807  condition_string, id);
9808 }
9809 
9810 debug::PostponeInterruptsScope::PostponeInterruptsScope(v8::Isolate* isolate)
9811  : scope_(
9812  new i::PostponeInterruptsScope(reinterpret_cast<i::Isolate*>(isolate),
9813  i::StackGuard::API_INTERRUPT)) {}
9814 
9815 debug::PostponeInterruptsScope::~PostponeInterruptsScope() = default;
9816 
9818  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
9819  i::Isolate* isolate = node->isolate();
9820  const i::CodeEntry* entry = node->entry();
9821  i::Handle<i::String> name =
9822  isolate->factory()->InternalizeUtf8String(entry->name());
9823  return ToApiHandle<String>(name);
9824 }
9825 
9826 int debug::Coverage::BlockData::StartOffset() const { return block_->start; }
9827 int debug::Coverage::BlockData::EndOffset() const { return block_->end; }
9828 uint32_t debug::Coverage::BlockData::Count() const { return block_->count; }
9829 
9830 int debug::Coverage::FunctionData::StartOffset() const {
9831  return function_->start;
9832 }
9833 int debug::Coverage::FunctionData::EndOffset() const { return function_->end; }
9834 uint32_t debug::Coverage::FunctionData::Count() const {
9835  return function_->count;
9836 }
9837 
9838 MaybeLocal<String> debug::Coverage::FunctionData::Name() const {
9839  return ToApiHandle<String>(function_->name);
9840 }
9841 
9842 size_t debug::Coverage::FunctionData::BlockCount() const {
9843  return function_->blocks.size();
9844 }
9845 
9846 bool debug::Coverage::FunctionData::HasBlockCoverage() const {
9847  return function_->has_block_coverage;
9848 }
9849 
9850 debug::Coverage::BlockData debug::Coverage::FunctionData::GetBlockData(
9851  size_t i) const {
9852  return BlockData(&function_->blocks.at(i), coverage_);
9853 }
9854 
9855 Local<debug::Script> debug::Coverage::ScriptData::GetScript() const {
9856  return ToApiHandle<debug::Script>(script_->script);
9857 }
9858 
9859 size_t debug::Coverage::ScriptData::FunctionCount() const {
9860  return script_->functions.size();
9861 }
9862 
9863 debug::Coverage::FunctionData debug::Coverage::ScriptData::GetFunctionData(
9864  size_t i) const {
9865  return FunctionData(&script_->functions.at(i), coverage_);
9866 }
9867 
9868 debug::Coverage::ScriptData::ScriptData(size_t index,
9869  std::shared_ptr<i::Coverage> coverage)
9870  : script_(&coverage->at(index)), coverage_(std::move(coverage)) {}
9871 
9872 size_t debug::Coverage::ScriptCount() const { return coverage_->size(); }
9873 
9874 debug::Coverage::ScriptData debug::Coverage::GetScriptData(size_t i) const {
9875  return ScriptData(i, coverage_);
9876 }
9877 
9878 debug::Coverage debug::Coverage::CollectPrecise(Isolate* isolate) {
9879  return Coverage(
9880  i::Coverage::CollectPrecise(reinterpret_cast<i::Isolate*>(isolate)));
9881 }
9882 
9883 debug::Coverage debug::Coverage::CollectBestEffort(Isolate* isolate) {
9884  return Coverage(
9885  i::Coverage::CollectBestEffort(reinterpret_cast<i::Isolate*>(isolate)));
9886 }
9887 
9888 void debug::Coverage::SelectMode(Isolate* isolate, debug::Coverage::Mode mode) {
9889  i::Coverage::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
9890 }
9891 
9892 int debug::TypeProfile::Entry::SourcePosition() const {
9893  return entry_->position;
9894 }
9895 
9896 std::vector<MaybeLocal<String>> debug::TypeProfile::Entry::Types() const {
9897  std::vector<MaybeLocal<String>> result;
9898  for (const internal::Handle<internal::String>& type : entry_->types) {
9899  result.emplace_back(ToApiHandle<String>(type));
9900  }
9901  return result;
9902 }
9903 
9904 debug::TypeProfile::ScriptData::ScriptData(
9905  size_t index, std::shared_ptr<i::TypeProfile> type_profile)
9906  : script_(&type_profile->at(index)),
9907  type_profile_(std::move(type_profile)) {}
9908 
9909 Local<debug::Script> debug::TypeProfile::ScriptData::GetScript() const {
9910  return ToApiHandle<debug::Script>(script_->script);
9911 }
9912 
9913 std::vector<debug::TypeProfile::Entry> debug::TypeProfile::ScriptData::Entries()
9914  const {
9915  std::vector<debug::TypeProfile::Entry> result;
9916  for (const internal::TypeProfileEntry& entry : script_->entries) {
9917  result.push_back(debug::TypeProfile::Entry(&entry, type_profile_));
9918  }
9919  return result;
9920 }
9921 
9922 debug::TypeProfile debug::TypeProfile::Collect(Isolate* isolate) {
9923  return TypeProfile(
9924  i::TypeProfile::Collect(reinterpret_cast<i::Isolate*>(isolate)));
9925 }
9926 
9927 void debug::TypeProfile::SelectMode(Isolate* isolate,
9928  debug::TypeProfile::Mode mode) {
9929  i::TypeProfile::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
9930 }
9931 
9932 size_t debug::TypeProfile::ScriptCount() const { return type_profile_->size(); }
9933 
9934 debug::TypeProfile::ScriptData debug::TypeProfile::GetScriptData(
9935  size_t i) const {
9936  return ScriptData(i, type_profile_);
9937 }
9938 
9939 v8::MaybeLocal<v8::Value> debug::WeakMap::Get(v8::Local<v8::Context> context,
9940  v8::Local<v8::Value> key) {
9941  PREPARE_FOR_EXECUTION(context, WeakMap, Get, Value);
9942  auto self = Utils::OpenHandle(this);
9943  Local<Value> result;
9944  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
9945  has_pending_exception =
9946  !ToLocal<Value>(i::Execution::Call(isolate, isolate->weakmap_get(), self,
9947  arraysize(argv), argv),
9948  &result);
9949  RETURN_ON_FAILED_EXECUTION(Value);
9950  RETURN_ESCAPED(result);
9951 }
9952 
9953 v8::MaybeLocal<debug::WeakMap> debug::WeakMap::Set(
9955  v8::Local<v8::Value> value) {
9956  PREPARE_FOR_EXECUTION(context, WeakMap, Set, WeakMap);
9957  auto self = Utils::OpenHandle(this);
9958  i::Handle<i::Object> result;
9959  i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
9960  Utils::OpenHandle(*value)};
9961  has_pending_exception = !i::Execution::Call(isolate, isolate->weakmap_set(),
9962  self, arraysize(argv), argv)
9963  .ToHandle(&result);
9964  RETURN_ON_FAILED_EXECUTION(WeakMap);
9965  RETURN_ESCAPED(Local<WeakMap>::Cast(Utils::ToLocal(result)));
9966 }
9967 
9968 Local<debug::WeakMap> debug::WeakMap::New(v8::Isolate* isolate) {
9969  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
9970  LOG_API(i_isolate, WeakMap, New);
9971  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
9972  i::Handle<i::JSWeakMap> obj = i_isolate->factory()->NewJSWeakMap();
9973  return ToApiHandle<debug::WeakMap>(obj);
9974 }
9975 
9976 debug::WeakMap* debug::WeakMap::Cast(v8::Value* value) {
9977  return static_cast<debug::WeakMap*>(value);
9978 }
9979 
9981  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
9982  return node->entry()->name();
9983 }
9984 
9986  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
9987  const i::CodeEntry* entry = node->entry();
9988  return entry->script_id();
9989 }
9990 
9992  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
9993  i::Isolate* isolate = node->isolate();
9994  return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
9995  node->entry()->resource_name()));
9996 }
9997 
9999  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
10000  return node->entry()->resource_name();
10001 }
10002 
10004  return reinterpret_cast<const i::ProfileNode*>(this)->line_number();
10005 }
10006 
10007 
10009  return reinterpret_cast<const i::ProfileNode*>(this)->
10010  entry()->column_number();
10011 }
10012 
10013 
10014 unsigned int CpuProfileNode::GetHitLineCount() const {
10015  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
10016  return node->GetHitLineCount();
10017 }
10018 
10019 
10021  unsigned int length) const {
10022  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
10023  return node->GetLineTicks(entries, length);
10024 }
10025 
10026 
10028  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
10029  return node->entry()->bailout_reason();
10030 }
10031 
10032 
10034  return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
10035 }
10036 
10037 
10038 unsigned CpuProfileNode::GetCallUid() const {
10039  return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
10040 }
10041 
10042 
10043 unsigned CpuProfileNode::GetNodeId() const {
10044  return reinterpret_cast<const i::ProfileNode*>(this)->id();
10045 }
10046 
10047 
10049  return static_cast<int>(
10050  reinterpret_cast<const i::ProfileNode*>(this)->children()->size());
10051 }
10052 
10053 
10054 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
10055  const i::ProfileNode* child =
10056  reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
10057  return reinterpret_cast<const CpuProfileNode*>(child);
10058 }
10059 
10060 
10061 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
10062  const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
10063  return node->deopt_infos();
10064 }
10065 
10066 
10068  i::CpuProfile* profile = reinterpret_cast<i::CpuProfile*>(this);
10069  i::CpuProfiler* profiler = profile->cpu_profiler();
10070  DCHECK_NOT_NULL(profiler);
10071  profiler->DeleteProfile(profile);
10072 }
10073 
10074 
10076  const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
10077  i::Isolate* isolate = profile->top_down()->isolate();
10078  return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
10079  profile->title()));
10080 }
10081 
10082 
10084  const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
10085  return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
10086 }
10087 
10088 
10089 const CpuProfileNode* CpuProfile::GetSample(int index) const {
10090  const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
10091  return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
10092 }
10093 
10094 
10096  const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
10097  return (profile->sample_timestamp(index) - base::TimeTicks())
10098  .InMicroseconds();
10099 }
10100 
10101 
10103  const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
10104  return (profile->start_time() - base::TimeTicks()).InMicroseconds();
10105 }
10106 
10107 
10109  const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
10110  return (profile->end_time() - base::TimeTicks()).InMicroseconds();
10111 }
10112 
10113 
10115  return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
10116 }
10117 
10118 CpuProfiler* CpuProfiler::New(Isolate* isolate) {
10119  return reinterpret_cast<CpuProfiler*>(
10120  new i::CpuProfiler(reinterpret_cast<i::Isolate*>(isolate)));
10121 }
10122 
10123 void CpuProfiler::Dispose() { delete reinterpret_cast<i::CpuProfiler*>(this); }
10124 
10125 // static
10126 void CpuProfiler::CollectSample(Isolate* isolate) {
10127  i::CpuProfiler::CollectSample(reinterpret_cast<i::Isolate*>(isolate));
10128 }
10129 
10131  DCHECK_GE(us, 0);
10132  return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
10133  base::TimeDelta::FromMicroseconds(us));
10134 }
10135 
10137  reinterpret_cast<i::CpuProfiler*>(this)->CollectSample();
10138 }
10139 
10140 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
10141  reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
10142  *Utils::OpenHandle(*title), record_samples, kLeafNodeLineNumbers);
10143 }
10144 
10145 void CpuProfiler::StartProfiling(Local<String> title, CpuProfilingMode mode,
10146  bool record_samples) {
10147  reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
10148  *Utils::OpenHandle(*title), record_samples, mode);
10149 }
10150 
10152  return reinterpret_cast<CpuProfile*>(
10153  reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
10154  *Utils::OpenHandle(*title)));
10155 }
10156 
10157 
10158 void CpuProfiler::SetIdle(bool is_idle) {
10159  i::CpuProfiler* profiler = reinterpret_cast<i::CpuProfiler*>(this);
10160  i::Isolate* isolate = profiler->isolate();
10161  isolate->SetIdle(is_idle);
10162 }
10163 
10165  reinterpret_cast<i::Isolate*>(isolate)
10166  ->set_detailed_source_positions_for_profiling(true);
10167 }
10168 
10169 uintptr_t CodeEvent::GetCodeStartAddress() {
10170  return reinterpret_cast<i::CodeEvent*>(this)->code_start_address;
10171 }
10172 
10173 size_t CodeEvent::GetCodeSize() {
10174  return reinterpret_cast<i::CodeEvent*>(this)->code_size;
10175 }
10176 
10177 Local<String> CodeEvent::GetFunctionName() {
10178  return ToApiHandle<String>(
10179  reinterpret_cast<i::CodeEvent*>(this)->function_name);
10180 }
10181 
10182 Local<String> CodeEvent::GetScriptName() {
10183  return ToApiHandle<String>(
10184  reinterpret_cast<i::CodeEvent*>(this)->script_name);
10185 }
10186 
10187 int CodeEvent::GetScriptLine() {
10188  return reinterpret_cast<i::CodeEvent*>(this)->script_line;
10189 }
10190 
10191 int CodeEvent::GetScriptColumn() {
10192  return reinterpret_cast<i::CodeEvent*>(this)->script_column;
10193 }
10194 
10196  return reinterpret_cast<i::CodeEvent*>(this)->code_type;
10197 }
10198 
10199 const char* CodeEvent::GetComment() {
10200  return reinterpret_cast<i::CodeEvent*>(this)->comment;
10201 }
10202 
10203 const char* CodeEvent::GetCodeEventTypeName(CodeEventType code_event_type) {
10204  switch (code_event_type) {
10205  case kUnknownType:
10206  return "Unknown";
10207 #define V(Name) \
10208  case k##Name##Type: \
10209  return #Name;
10210  CODE_EVENTS_LIST(V)
10211 #undef V
10212  }
10213  // The execution should never pass here
10214  UNREACHABLE();
10215  // NOTE(mmarchini): Workaround to fix a compiler failure on GCC 4.9
10216  return "Unknown";
10217 }
10218 
10219 CodeEventHandler::CodeEventHandler(Isolate* isolate) {
10220  internal_listener_ =
10221  new i::ExternalCodeEventListener(reinterpret_cast<i::Isolate*>(isolate));
10222 }
10223 
10224 CodeEventHandler::~CodeEventHandler() {
10225  delete reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_);
10226 }
10227 
10228 void CodeEventHandler::Enable() {
10229  reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_)
10230  ->StartListening(this);
10231 }
10232 
10233 void CodeEventHandler::Disable() {
10234  reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_)
10235  ->StopListening();
10236 }
10237 
10238 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
10239  return const_cast<i::HeapGraphEdge*>(
10240  reinterpret_cast<const i::HeapGraphEdge*>(edge));
10241 }
10242 
10243 
10244 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
10245  return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
10246 }
10247 
10248 
10250  i::HeapGraphEdge* edge = ToInternal(this);
10251  i::Isolate* isolate = edge->isolate();
10252  switch (edge->type()) {
10253  case i::HeapGraphEdge::kContextVariable:
10254  case i::HeapGraphEdge::kInternal:
10255  case i::HeapGraphEdge::kProperty:
10256  case i::HeapGraphEdge::kShortcut:
10257  case i::HeapGraphEdge::kWeak:
10258  return ToApiHandle<String>(
10259  isolate->factory()->InternalizeUtf8String(edge->name()));
10260  case i::HeapGraphEdge::kElement:
10261  case i::HeapGraphEdge::kHidden:
10262  return ToApiHandle<Number>(
10263  isolate->factory()->NewNumberFromInt(edge->index()));
10264  default: UNREACHABLE();
10265  }
10266  return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
10267 }
10268 
10269 
10271  const i::HeapEntry* from = ToInternal(this)->from();
10272  return reinterpret_cast<const HeapGraphNode*>(from);
10273 }
10274 
10275 
10277  const i::HeapEntry* to = ToInternal(this)->to();
10278  return reinterpret_cast<const HeapGraphNode*>(to);
10279 }
10280 
10281 
10282 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
10283  return const_cast<i::HeapEntry*>(
10284  reinterpret_cast<const i::HeapEntry*>(entry));
10285 }
10286 
10287 
10288 HeapGraphNode::Type HeapGraphNode::GetType() const {
10289  return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
10290 }
10291 
10292 
10294  i::Isolate* isolate = ToInternal(this)->isolate();
10295  return ToApiHandle<String>(
10296  isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
10297 }
10298 
10299 
10301  return ToInternal(this)->id();
10302 }
10303 
10304 
10306  return ToInternal(this)->self_size();
10307 }
10308 
10309 
10311  return ToInternal(this)->children_count();
10312 }
10313 
10314 
10315 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
10316  return reinterpret_cast<const HeapGraphEdge*>(ToInternal(this)->child(index));
10317 }
10318 
10319 
10320 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
10321  return const_cast<i::HeapSnapshot*>(
10322  reinterpret_cast<const i::HeapSnapshot*>(snapshot));
10323 }
10324 
10325 
10327  i::Isolate* isolate = ToInternal(this)->profiler()->isolate();
10328  if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
10329  ToInternal(this)->Delete();
10330  } else {
10331  // If this is the last snapshot, clean up all accessory data as well.
10332  isolate->heap_profiler()->DeleteAllSnapshots();
10333  }
10334 }
10335 
10336 
10338  return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
10339 }
10340 
10341 
10343  return reinterpret_cast<const HeapGraphNode*>(
10344  ToInternal(this)->GetEntryById(id));
10345 }
10346 
10347 
10349  return static_cast<int>(ToInternal(this)->entries().size());
10350 }
10351 
10352 
10353 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
10354  return reinterpret_cast<const HeapGraphNode*>(
10355  &ToInternal(this)->entries().at(index));
10356 }
10357 
10358 
10360  return ToInternal(this)->max_snapshot_js_object_id();
10361 }
10362 
10363 
10365  HeapSnapshot::SerializationFormat format) const {
10366  Utils::ApiCheck(format == kJSON,
10367  "v8::HeapSnapshot::Serialize",
10368  "Unknown serialization format");
10369  Utils::ApiCheck(stream->GetChunkSize() > 0,
10370  "v8::HeapSnapshot::Serialize",
10371  "Invalid stream chunk size");
10372  i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
10373  serializer.Serialize(stream);
10374 }
10375 
10376 
10377 // static
10378 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
10380 
10381 
10383  return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
10384 }
10385 
10386 
10388  return reinterpret_cast<const HeapSnapshot*>(
10389  reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
10390 }
10391 
10392 
10394  i::Handle<i::Object> obj = Utils::OpenHandle(*value);
10395  return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
10396 }
10397 
10398 
10400  i::Handle<i::Object> obj =
10401  reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
10402  if (obj.is_null()) return Local<Value>();
10403  return Utils::ToLocal(obj);
10404 }
10405 
10406 
10408  reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
10409 }
10410 
10411 
10413  ActivityControl* control, ObjectNameResolver* resolver) {
10414  return reinterpret_cast<const HeapSnapshot*>(
10415  reinterpret_cast<i::HeapProfiler*>(this)
10416  ->TakeSnapshot(control, resolver));
10417 }
10418 
10419 
10420 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
10421  reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
10422  track_allocations);
10423 }
10424 
10425 
10427  reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
10428 }
10429 
10430 
10432  int64_t* timestamp_us) {
10433  i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
10434  return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
10435 }
10436 
10437 bool HeapProfiler::StartSamplingHeapProfiler(uint64_t sample_interval,
10438  int stack_depth,
10439  SamplingFlags flags) {
10440  return reinterpret_cast<i::HeapProfiler*>(this)->StartSamplingHeapProfiler(
10441  sample_interval, stack_depth, flags);
10442 }
10443 
10444 
10446  reinterpret_cast<i::HeapProfiler*>(this)->StopSamplingHeapProfiler();
10447 }
10448 
10449 
10451  return reinterpret_cast<i::HeapProfiler*>(this)->GetAllocationProfile();
10452 }
10453 
10455  reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
10456 }
10457 
10458 
10459 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
10460  WrapperInfoCallback callback) {
10461  reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
10462  callback);
10463 }
10464 
10465 void HeapProfiler::SetGetRetainerInfosCallback(
10466  GetRetainerInfosCallback callback) {
10467  reinterpret_cast<i::HeapProfiler*>(this)->SetGetRetainerInfosCallback(
10468  callback);
10469 }
10470 
10471 void HeapProfiler::SetBuildEmbedderGraphCallback(
10472  LegacyBuildEmbedderGraphCallback callback) {
10473  reinterpret_cast<i::HeapProfiler*>(this)->AddBuildEmbedderGraphCallback(
10474  [](v8::Isolate* isolate, v8::EmbedderGraph* graph, void* data) {
10475  reinterpret_cast<LegacyBuildEmbedderGraphCallback>(data)(isolate,
10476  graph);
10477  },
10478  reinterpret_cast<void*>(callback));
10479 }
10480 
10481 void HeapProfiler::AddBuildEmbedderGraphCallback(
10482  BuildEmbedderGraphCallback callback, void* data) {
10483  reinterpret_cast<i::HeapProfiler*>(this)->AddBuildEmbedderGraphCallback(
10484  callback, data);
10485 }
10486 
10487 void HeapProfiler::RemoveBuildEmbedderGraphCallback(
10488  BuildEmbedderGraphCallback callback, void* data) {
10489  reinterpret_cast<i::HeapProfiler*>(this)->RemoveBuildEmbedderGraphCallback(
10490  callback, data);
10491 }
10492 
10493 v8::Testing::StressType internal::Testing::stress_type_ =
10494  v8::Testing::kStressTypeOpt;
10495 
10496 
10497 void Testing::SetStressRunType(Testing::StressType type) {
10498  internal::Testing::set_stress_type(type);
10499 }
10500 
10501 
10503  if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
10504 #ifdef DEBUG
10505  // In debug mode the code runs much slower so stressing will only make two
10506  // runs.
10507  return 2;
10508 #else
10509  return 5;
10510 #endif
10511 }
10512 
10513 
10514 static void SetFlagsFromString(const char* flags) {
10515  V8::SetFlagsFromString(flags, i::StrLength(flags));
10516 }
10517 
10518 
10520  static const char* kLazyOptimizations =
10521  "--prepare-always-opt "
10522  "--max-inlined-bytecode-size=999999 "
10523  "--max-inlined-bytecode-size-cumulative=999999 "
10524  "--noalways-opt";
10525  static const char* kForcedOptimizations = "--always-opt";
10526 
10527  // If deoptimization stressed turn on frequent deoptimization. If no value
10528  // is spefified through --deopt-every-n-times use a default default value.
10529  static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
10530  if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
10531  internal::FLAG_deopt_every_n_times == 0) {
10532  SetFlagsFromString(kDeoptEvery13Times);
10533  }
10534 
10535 #ifdef DEBUG
10536  // As stressing in debug mode only make two runs skip the deopt stressing
10537  // here.
10538  if (run == GetStressRuns() - 1) {
10539  SetFlagsFromString(kForcedOptimizations);
10540  } else {
10541  SetFlagsFromString(kLazyOptimizations);
10542  }
10543 #else
10544  if (run == GetStressRuns() - 1) {
10545  SetFlagsFromString(kForcedOptimizations);
10546  } else if (run != GetStressRuns() - 2) {
10547  SetFlagsFromString(kLazyOptimizations);
10548  }
10549 #endif
10550 }
10551 
10552 
10553 void Testing::DeoptimizeAll(Isolate* isolate) {
10554  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
10555  i::HandleScope scope(i_isolate);
10556  i::Deoptimizer::DeoptimizeAll(i_isolate);
10557 }
10558 
10559 void EmbedderHeapTracer::FinalizeTracing() {
10560  if (isolate_) {
10561  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(isolate_);
10562  if (isolate->heap()->incremental_marking()->IsMarking()) {
10563  isolate->heap()->FinalizeIncrementalMarkingAtomically(
10564  i::GarbageCollectionReason::kExternalFinalize);
10565  }
10566  }
10567 }
10568 
10569 void EmbedderHeapTracer::GarbageCollectionForTesting(
10570  EmbedderStackState stack_state) {
10571  CHECK(isolate_);
10572  CHECK(i::FLAG_expose_gc);
10573  i::Heap* const heap = reinterpret_cast<i::Isolate*>(isolate_)->heap();
10574  heap->SetEmbedderStackStateForNextFinalizaton(stack_state);
10575  heap->PreciseCollectAllGarbage(i::Heap::kNoGCFlags,
10576  i::GarbageCollectionReason::kTesting,
10577  kGCCallbackFlagForced);
10578 }
10579 
10580 namespace internal {
10581 
10582 void HandleScopeImplementer::FreeThreadResources() {
10583  Free();
10584 }
10585 
10586 
10587 char* HandleScopeImplementer::ArchiveThread(char* storage) {
10588  HandleScopeData* current = isolate_->handle_scope_data();
10589  handle_scope_data_ = *current;
10590  MemCopy(storage, this, sizeof(*this));
10591 
10592  ResetAfterArchive();
10593  current->Initialize();
10594 
10595  return storage + ArchiveSpacePerThread();
10596 }
10597 
10598 
10599 int HandleScopeImplementer::ArchiveSpacePerThread() {
10600  return sizeof(HandleScopeImplementer);
10601 }
10602 
10603 
10604 char* HandleScopeImplementer::RestoreThread(char* storage) {
10605  MemCopy(this, storage, sizeof(*this));
10606  *isolate_->handle_scope_data() = handle_scope_data_;
10607  return storage + ArchiveSpacePerThread();
10608 }
10609 
10610 void HandleScopeImplementer::IterateThis(RootVisitor* v) {
10611 #ifdef DEBUG
10612  bool found_block_before_deferred = false;
10613 #endif
10614  // Iterate over all handles in the blocks except for the last.
10615  for (int i = static_cast<int>(blocks()->size()) - 2; i >= 0; --i) {
10616  Address* block = blocks()->at(i);
10617  // Cast possibly-unrelated pointers to plain Address before comparing them
10618  // to avoid undefined behavior.
10619  if (last_handle_before_deferred_block_ != nullptr &&
10620  (reinterpret_cast<Address>(last_handle_before_deferred_block_) <=
10621  reinterpret_cast<Address>(&block[kHandleBlockSize])) &&
10622  (reinterpret_cast<Address>(last_handle_before_deferred_block_) >=
10623  reinterpret_cast<Address>(block))) {
10624  v->VisitRootPointers(Root::kHandleScope, nullptr, ObjectSlot(block),
10625  ObjectSlot(last_handle_before_deferred_block_));
10626  DCHECK(!found_block_before_deferred);
10627 #ifdef DEBUG
10628  found_block_before_deferred = true;
10629 #endif
10630  } else {
10631  v->VisitRootPointers(Root::kHandleScope, nullptr, ObjectSlot(block),
10632  ObjectSlot(&block[kHandleBlockSize]));
10633  }
10634  }
10635 
10636  DCHECK(last_handle_before_deferred_block_ == nullptr ||
10637  found_block_before_deferred);
10638 
10639  // Iterate over live handles in the last block (if any).
10640  if (!blocks()->empty()) {
10641  v->VisitRootPointers(Root::kHandleScope, nullptr,
10642  ObjectSlot(blocks()->back()),
10643  ObjectSlot(handle_scope_data_.next));
10644  }
10645 
10646  DetachableVector<Context>* context_lists[2] = {&saved_contexts_,
10647  &entered_contexts_};
10648  for (unsigned i = 0; i < arraysize(context_lists); i++) {
10649  context_lists[i]->shrink_to_fit();
10650  if (context_lists[i]->empty()) continue;
10651  ObjectSlot start(&context_lists[i]->front());
10652  v->VisitRootPointers(Root::kHandleScope, nullptr, start,
10653  start + static_cast<int>(context_lists[i]->size()));
10654  }
10655  if (!microtask_context_.is_null()) {
10656  v->VisitRootPointer(Root::kHandleScope, nullptr,
10657  ObjectSlot(&microtask_context_));
10658  }
10659 }
10660 
10661 void HandleScopeImplementer::Iterate(RootVisitor* v) {
10662  HandleScopeData* current = isolate_->handle_scope_data();
10663  handle_scope_data_ = *current;
10664  IterateThis(v);
10665 }
10666 
10667 char* HandleScopeImplementer::Iterate(RootVisitor* v, char* storage) {
10668  HandleScopeImplementer* scope_implementer =
10669  reinterpret_cast<HandleScopeImplementer*>(storage);
10670  scope_implementer->IterateThis(v);
10671  return storage + ArchiveSpacePerThread();
10672 }
10673 
10674 DeferredHandles* HandleScopeImplementer::Detach(Address* prev_limit) {
10675  DeferredHandles* deferred =
10676  new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
10677 
10678  while (!blocks_.empty()) {
10679  Address* block_start = blocks_.back();
10680  Address* block_limit = &block_start[kHandleBlockSize];
10681  // We should not need to check for SealHandleScope here. Assert this.
10682  DCHECK(prev_limit == block_limit ||
10683  !(block_start <= prev_limit && prev_limit <= block_limit));
10684  if (prev_limit == block_limit) break;
10685  deferred->blocks_.push_back(blocks_.back());
10686  blocks_.pop_back();
10687  }
10688 
10689  // deferred->blocks_ now contains the blocks installed on the
10690  // HandleScope stack since BeginDeferredScope was called, but in
10691  // reverse order.
10692 
10693  DCHECK(prev_limit == nullptr || !blocks_.empty());
10694 
10695  DCHECK(!blocks_.empty() && prev_limit != nullptr);
10696  DCHECK_NOT_NULL(last_handle_before_deferred_block_);
10697  last_handle_before_deferred_block_ = nullptr;
10698  return deferred;
10699 }
10700 
10701 
10702 void HandleScopeImplementer::BeginDeferredScope() {
10703  DCHECK_NULL(last_handle_before_deferred_block_);
10704  last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
10705 }
10706 
10707 
10708 DeferredHandles::~DeferredHandles() {
10709  isolate_->UnlinkDeferredHandles(this);
10710 
10711  for (size_t i = 0; i < blocks_.size(); i++) {
10712 #ifdef ENABLE_HANDLE_ZAPPING
10713  HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
10714 #endif
10715  isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
10716  }
10717 }
10718 
10719 void DeferredHandles::Iterate(RootVisitor* v) {
10720  DCHECK(!blocks_.empty());
10721 
10722  // Comparing pointers that do not point into the same array is undefined
10723  // behavior, which means if we didn't cast everything to plain Address
10724  // before comparing, the compiler would be allowed to assume that all
10725  // comparisons evaluate to true and drop the entire check.
10726  DCHECK((reinterpret_cast<Address>(first_block_limit_) >=
10727  reinterpret_cast<Address>(blocks_.front())) &&
10728  (reinterpret_cast<Address>(first_block_limit_) <=
10729  reinterpret_cast<Address>(&(blocks_.front())[kHandleBlockSize])));
10730 
10731  v->VisitRootPointers(Root::kHandleScope, nullptr, ObjectSlot(blocks_.front()),
10732  ObjectSlot(first_block_limit_));
10733 
10734  for (size_t i = 1; i < blocks_.size(); i++) {
10735  v->VisitRootPointers(Root::kHandleScope, nullptr, ObjectSlot(blocks_[i]),
10736  ObjectSlot(&blocks_[i][kHandleBlockSize]));
10737  }
10738 }
10739 
10740 
10741 void InvokeAccessorGetterCallback(
10742  v8::Local<v8::Name> property,
10744  v8::AccessorNameGetterCallback getter) {
10745  // Leaving JavaScript.
10746  Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
10747  RuntimeCallTimerScope timer(isolate,
10748  RuntimeCallCounterId::kAccessorGetterCallback);
10749  Address getter_address = reinterpret_cast<Address>(getter);
10750  VMState<EXTERNAL> state(isolate);
10751  ExternalCallbackScope call_scope(isolate, getter_address);
10752  getter(property, info);
10753 }
10754 
10755 
10756 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
10757  v8::FunctionCallback callback) {
10758  Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
10759  RuntimeCallTimerScope timer(isolate,
10760  RuntimeCallCounterId::kInvokeFunctionCallback);
10761  Address callback_address = reinterpret_cast<Address>(callback);
10762  VMState<EXTERNAL> state(isolate);
10763  ExternalCallbackScope call_scope(isolate, callback_address);
10764  callback(info);
10765 }
10766 
10767 // Undefine macros for jumbo build.
10768 #undef LOG_API
10769 #undef ENTER_V8_DO_NOT_USE
10770 #undef ENTER_V8_HELPER_DO_NOT_USE
10771 #undef PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE
10772 #undef PREPARE_FOR_EXECUTION_WITH_CONTEXT
10773 #undef PREPARE_FOR_EXECUTION
10774 #undef ENTER_V8
10775 #undef ENTER_V8_NO_SCRIPT
10776 #undef ENTER_V8_NO_SCRIPT_NO_EXCEPTION
10777 #undef ENTER_V8_FOR_NEW_CONTEXT
10778 #undef EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE
10779 #undef RETURN_ON_FAILED_EXECUTION
10780 #undef RETURN_ON_FAILED_EXECUTION_PRIMITIVE
10781 #undef RETURN_TO_LOCAL_UNCHECKED
10782 #undef RETURN_ESCAPED
10783 #undef SET_FIELD_WRAPPED
10784 #undef NEW_STRING
10785 #undef CALLBACK_SETTER
10786 
10787 } // namespace internal
10788 } // namespace v8
void TransferSharedArrayBuffer(uint32_t id, Local< SharedArrayBuffer > shared_array_buffer)
Definition: api.cc:3268
const HeapGraphNode * GetNodeById(SnapshotObjectId id) const
Definition: api.cc:10342
int GetSamplesCount() const
Definition: api.cc:10114
bool IsSetIterator() const
Definition: api.cc:3495
int Length() const
Definition: api.cc:5175
V8_WARN_UNUSED_RESULT Maybe< bool > HasOwnProperty(Local< Context > context, Local< Name > key)
Definition: api.cc:4659
static V8_WARN_UNUSED_RESULT MaybeLocal< Module > CompileModule(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition: api.cc:2394
bool IsExternal() const
Definition: api.cc:5605
size_t Length()
Definition: api.cc:7728
static V8_WARN_UNUSED_RESULT MaybeLocal< Resolver > New(Local< Context > context)
Definition: api.cc:7240
int64_t GetStartTime() const
Definition: api.cc:10102
static CachedData * CreateCodeCache(Local< UnboundScript > unbound_script)
Definition: api.cc:2579
bool StringEquals(Local< String > str)
Definition: api.cc:6694
IntegrityLevel
Definition: v8.h:3234
V8_WARN_UNUSED_RESULT Maybe< bool > Resolve(Local< Context > context, Local< Value > value)
Definition: api.cc:7256
const HeapSnapshot * TakeHeapSnapshot(ActivityControl *control=nullptr, ObjectNameResolver *global_object_name_resolver=nullptr)
Definition: api.cc:10412
static V8_WARN_UNUSED_RESULT MaybeLocal< String > Stringify(Local< Context > context, Local< Value > json_object, Local< String > gap=Local< String >())
Definition: api.cc:3018
static Local< Set > New(Isolate *isolate)
Definition: api.cc:7138
V8_WARN_UNUSED_RESULT MaybeLocal< Value > CallAsFunction(Local< Context > context, Local< Value > recv, int argc, Local< Value > argv[])
Definition: api.cc:4882
void SetTreatArrayBufferViewsAsHostObjects(bool mode)
Definition: api.cc:3092
KeyConversionMode
Definition: v8.h:3229
static MaybeLocal< FunctionTemplate > FromSnapshot(Isolate *isolate, size_t index)
Definition: api.cc:1432
static Local< Symbol > New(Isolate *isolate, Local< String > name=Local< String >())
Definition: api.cc:7896
Contents Externalize()
Definition: api.cc:7807
Local< Value > GetSourceURL()
Definition: api.cc:2080
bool IsOneByte() const
Definition: api.cc:5181
bool IsMapIterator() const
Definition: api.cc:3490
void SetAlignedPointerInInternalField(int index, void *value)
Definition: api.cc:5826
int GetScriptId() const
Definition: api.cc:9985
bool only_terminate_in_safe_scope
Definition: v8.h:7201
const ExternalOneByteStringResource * GetExternalOneByteStringResource() const
Definition: api.cc:5703
Contents Externalize()
Definition: api.cc:7557
bool IsNativeError() const
Definition: api.cc:3460
virtual Maybe< uint32_t > GetSharedArrayBufferId(Isolate *isolate, Local< SharedArrayBuffer > shared_array_buffer)
Definition: api.cc:3049
int64_t GetEndTime() const
Definition: api.cc:10108
V8_WARN_UNUSED_RESULT Maybe< int > GetLineNumber(Local< Context > context) const
Definition: api.cc:2808
Local< String > GetScriptResourceName() const
Definition: api.cc:9991
Local< Value > GetPrototype()
Definition: api.cc:4341
virtual const uint16_t * data() const =0
PromiseState State()
Definition: api.cc:7345
NewStringType
Definition: v8.h:2520
int GetIdentityHash()
Definition: api.cc:4863
int ErrorLevel() const
Definition: api.cc:2829
Local< String > GetFunctionName() const
Definition: api.cc:2968
Local< String > GetName() const
Definition: api.cc:10293
Local< ArrayBuffer > Buffer()
Definition: api.cc:7667
void SetLazyDataProperty(Local< Name > name, AccessorNameGetterCallback getter, Local< Value > data=Local< Value >(), PropertyAttribute attribute=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:1725
void SetInternalField(int index, Local< Value > value)
Definition: api.cc:5807
Local< Value > GetSourceMappingURL()
Definition: api.cc:2094
SnapshotObjectId GetId() const
Definition: api.cc:10300
int GetModuleRequestsLength() const
Definition: api.cc:2219
Local< Value > FindObjectById(SnapshotObjectId id)
Definition: api.cc:10399
int GetEndColumn() const
Definition: api.cc:2847
int InternalFieldCount()
Definition: api.cc:5784
bool IsProxy() const
Definition: api.cc:3395
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromOneByte(Isolate *isolate, const uint8_t *data, v8::NewStringType type, int length=-1)
Definition: api.cc:6528
Isolate * GetIsolate()
Definition: api.cc:6700
static Local< Symbol > ForApi(Isolate *isolate, Local< String > name)
Definition: api.cc:7914
static Local< FunctionTemplate > NewWithCache(Isolate *isolate, FunctionCallback callback, Local< Private > cache_property, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:1447
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstanceWithSideEffectType(Local< Context > context, int argc, Local< Value > argv[], SideEffectType side_effect_type=SideEffectType::kHasSideEffect) const
Definition: api.cc:4947
int GetScriptLineNumber() const
Definition: api.cc:5113
unsigned GetNodeId() const
Definition: api.cc:10043
int WordCount() const
Definition: api.cc:8037
V8_INLINE Local< T > Escape(Local< T > value)
Definition: v8.h:904
Type GetType() const
Definition: api.cc:10244
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition: api.cc:2378
const CpuProfileNode * GetSample(int index) const
Definition: api.cc:10089
IndexFilter
Definition: v8.h:3223
PropertyAttribute
Definition: v8.h:3132
bool IsGeneratorFunction() const
Definition: api.cc:3477
BufferReference GetWasmWireBytesRef()
Definition: api.cc:7396
bool IsSharedCrossOrigin() const
Definition: api.cc:2865
const std::vector< CpuProfileDeoptInfo > & GetDeoptInfos() const
Definition: api.cc:10061
virtual MaybeLocal< SharedArrayBuffer > GetSharedArrayBufferFromId(Isolate *isolate, uint32_t clone_id)
Definition: api.cc:3163
static V8_INLINE Local< T > Cast(Local< S > that)
Definition: v8.h:251
KeyCollectionMode
Definition: v8.h:3217
static int GetStressRuns()
Definition: api.cc:10502
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Run(Local< Context > context)
Definition: api.cc:2108
Local< String > GetScriptName() const
Definition: api.cc:2946
const HeapGraphNode * GetRoot() const
Definition: api.cc:10337
Local< StackTrace > GetStackTrace() const
Definition: api.cc:2796
SerializedModule Serialize()
Definition: api.cc:7436
void SetPrototypeProviderTemplate(Local< FunctionTemplate > prototype_provider)
Definition: api.cc:1355
static Local< SharedArrayBuffer > New(Isolate *isolate, size_t byte_length)
Definition: api.cc:7858
void SetSamplingInterval(int us)
Definition: api.cc:10130
void Inherit(Local< FunctionTemplate > parent)
Definition: api.cc:1374
Local< Array > AsArray() const
Definition: api.cc:7231
CodeEventType GetCodeType()
Definition: api.cc:10195
virtual void Free(void *data, size_t length)=0
uint64_t Uint64Value(bool *lossless=nullptr) const
Definition: api.cc:8027
Local< Value > Result()
Definition: api.cc:7334
Local< Script > BindToCurrentContext()
Definition: api.cc:2030
void Delete()
Definition: api.cc:10326
V8_WARN_UNUSED_RESULT MaybeLocal< Promise > Catch(Local< Context > context, Local< Function > handler)
Definition: api.cc:7294
Local< Value > GetName() const
Definition: api.cc:10249
STL namespace.
void SetHiddenPrototype(bool value)
Definition: api.cc:1586
Definition: v8.h:56
Local< StackFrame > GetFrame(Isolate *isolate, uint32_t index) const
Definition: api.cc:2900
const HeapGraphNode * GetFromNode() const
Definition: api.cc:10270
Maybe< bool > SetIntegrityLevel(Local< Context > context, IntegrityLevel level)
Definition: api.cc:4453
static CachedData * CreateCodeCacheForFunction(Local< Function > function)
Definition: api.cc:2598
bool IsArray() const
Definition: api.cc:3343
void(* AccessorGetterCallback)(Local< String > property, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:3148
Definition: v8.h:2497
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewExternalTwoByte(Isolate *isolate, ExternalStringResource *resource)
Definition: api.cc:6569
virtual void * ReallocateBufferMemory(void *old_buffer, size_t size, size_t *actual_size)
Definition: api.cc:3063
void SetClassName(Local< String > name)
Definition: api.cc:1568
V8_INLINE bool IsEmpty() const
Definition: v8.h:195
Local< Context > CreationContext()
Definition: api.cc:4857
int GetChildrenCount() const
Definition: api.cc:10048
Definition: v8.h:2119
size_t ByteLength() const
Definition: api.cc:7628
bool IsModuleNamespaceObject() const
Definition: api.cc:3501
MaybeLocal< Array > PreviewEntries(bool *is_key_value)
Definition: api.cc:9597
bool IsWasm() const
Definition: api.cc:2984
V8_WARN_UNUSED_RESULT Maybe< bool > SetAccessor(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, MaybeLocal< Value > data=MaybeLocal< Value >(), AccessControl settings=DEFAULT, PropertyAttribute attribute=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:4604
static Local< Array > New(Isolate *isolate, int length=0)
Definition: api.cc:6966
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Evaluate(Local< Context > context)
Definition: api.cc:2281
bool IsRegExp() const
Definition: api.cc:3465
void SetAccessCheckCallbackAndHandler(AccessCheckCallback callback, const NamedPropertyHandlerConfiguration &named_handler, const IndexedPropertyHandlerConfiguration &indexed_handler, Local< Value > data=Local< Value >())
Definition: api.cc:1899
void SetInternalFieldCount(int value)
Definition: api.cc:1973
void ReadOnlyPrototype()
Definition: api.cc:1595
V8_WARN_UNUSED_RESULT Maybe< bool > HasRealNamedProperty(Local< Context > context, Local< Name > key)
Definition: api.cc:4683
Local< String > GetTitle() const
Definition: api.cc:10075
V8_WARN_UNUSED_RESULT Maybe< bool > InstantiateModule(Local< Context > context, ResolveCallback callback)
Definition: api.cc:2270
Local< PrimitiveArray > GetHostDefinedOptions()
Definition: api.cc:2136
void SetCallHandler(FunctionCallback callback, Local< Value > data=Local< Value >(), SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:1475
Local< String > GetModuleRequest(int i) const
Definition: api.cc:2224
void StartTrackingHeapObjects(bool track_allocations=false)
Definition: api.cc:10420
static MaybeLocal< WasmCompiledModule > DeserializeOrCompile(Isolate *isolate, BufferReference serialized_module, BufferReference wire_bytes)
Definition: api.cc:7464
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:10366
static MaybeLocal< Function > New(Local< Context > context, FunctionCallback callback, Local< Value > data=Local< Value >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:4919
CpuProfile * StopProfiling(Local< String > title)
Definition: api.cc:10151
int GetSnapshotCount()
Definition: api.cc:10382
void StopTrackingHeapObjects()
Definition: api.cc:10426
V8_INLINE T FromJust() const
Definition: v8.h:8683
PropertyHandlerFlags
Definition: v8.h:5851
void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format)
Definition: api.cc:3231
Local< String > GetSource() const
Definition: api.cc:6941
void RemovePrototype()
Definition: api.cc:1604
const char * GetScriptResourceNameStr() const
Definition: api.cc:9998
Local< Value > GetDebugName() const
Definition: api.cc:5063
Local< ObjectTemplate > InstanceTemplate()
Definition: api.cc:1538
void SetExpectInlineWasm(bool allow_inline_wasm)
Definition: api.cc:3236
Isolate * GetIsolate() const
Definition: api.cc:2777
Local< Value > GetResourceName()
Definition: api.cc:2128
size_t ByteLength() const
Definition: api.cc:7853
V8_WARN_UNUSED_RESULT MaybeLocal< Uint32 > ToArrayIndex(Local< Context > context) const
Definition: api.cc:3941
bool(* AccessCheckCallback)(Local< Context > accessing_context, Local< Object > accessed_object, Local< Value > data)
Definition: v8.h:5614
virtual int GetChunkSize()
Definition: v8-profiler.h:458
CreateHistogramCallback create_histogram_callback
Definition: v8.h:7175
static void DateTimeConfigurationChangeNotification(Isolate *isolate)
Definition: api.cc:6912
int GetFrameCount() const
Definition: api.cc:2910
static CpuProfiler * New(Isolate *isolate)
Definition: api.cc:10118
int GetLineNumber(int code_pos)
Definition: api.cc:2052
Definition: v8.h:3678
virtual const char * data() const =0
int GetStartColumn() const
Definition: api.cc:2834
void TransferArrayBuffer(uint32_t transfer_id, Local< ArrayBuffer > array_buffer)
Definition: api.cc:3261
bool HasIndexedLookupInterceptor()
Definition: api.cc:4755
bool IsFunction() const
Definition: api.cc:3323
StartupData * snapshot_blob
Definition: v8.h:7160
bool IsObject() const
Definition: api.cc:3386
V8_WARN_UNUSED_RESULT Maybe< bool > SetPrototype(Local< Context > context, Local< Value > prototype)
Definition: api.cc:4349
virtual void FreeBufferMemory(void *buffer)
Definition: api.cc:3070
bool IsNumber() const
Definition: api.cc:3389
bool IsSymbol() const
Definition: api.cc:3338
Definition: libplatform.h:13
size_t ByteOffset()
Definition: api.cc:7716
void SetAccessor(Local< String > name, AccessorGetterCallback getter, AccessorSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), AccessControl settings=DEFAULT, PropertyAttribute attribute=None, Local< AccessorSignature > signature=Local< AccessorSignature >(), SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:1748
static MaybeLocal< ObjectTemplate > FromSnapshot(Isolate *isolate, size_t index)
Definition: api.cc:1648
V8_WARN_UNUSED_RESULT MaybeLocal< Value > CallAsConstructor(Local< Context > context, int argc, Local< Value > argv[])
Definition: api.cc:4902
bool IsDataView() const
Definition: api.cc:3375
Location GetModuleRequestLocation(int i) const
Definition: api.cc:2234
void SetHandler(const NamedPropertyHandlerConfiguration &configuration)
Definition: api.cc:1854
void StartProfiling(Local< String > title, CpuProfilingMode mode, bool record_samples=false)
Definition: api.cc:10145
int InternalFieldCount()
Definition: api.cc:1969
V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t *value)
Definition: api.cc:3275
bool IsAsyncFunction() const
Definition: api.cc:3470
virtual MaybeLocal< Object > ReadHostObject(Isolate *isolate)
Definition: api.cc:3144
bool IsExternalOneByte() const
Definition: api.cc:5611
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Local< String > source, ScriptOrigin *origin=nullptr)
Definition: api.cc:2608
void SetLength(int length)
Definition: api.cc:1559
Type GetType() const
Definition: api.cc:10288
static uint32_t CachedDataVersionTag()
Definition: api.cc:2573
SnapshotObjectId GetObjectId(Local< Value > value)
Definition: api.cc:10393
CounterLookupCallback counter_lookup_callback
Definition: v8.h:7167
const HeapGraphNode * GetToNode() const
Definition: api.cc:10276
Local< Value > Name() const
Definition: api.cc:5738
bool MakeExternal(ExternalStringResource *resource)
Definition: api.cc:6621
void SetAcceptAnyReceiver(bool value)
Definition: api.cc:1577
static Local< ObjectTemplate > New(Isolate *isolate, Local< FunctionTemplate > constructor=Local< FunctionTemplate >())
Definition: api.cc:1616
int GetIdentityHash() const
Definition: api.cc:2268
V8_WARN_UNUSED_RESULT MaybeLocal< String > ObjectProtoToString(Local< Context > context)
Definition: api.cc:4434
static void CollectSample(Isolate *isolate)
Definition: api.cc:10126
uint32_t GetWireFormatVersion() const
Definition: api.cc:3240
int GetLineNumber() const
Definition: api.cc:10003
static Local< ArrayBuffer > New(Isolate *isolate, size_t byte_length)
Definition: api.cc:7634
unsigned GetHitCount() const
Definition: api.cc:10033
V8_INLINE Local< T > ToLocalChecked()
Definition: v8.h:9402
int GetIdentityHash()
Definition: api.cc:5169
V8_WARN_UNUSED_RESULT Maybe< bool > ReadHeader(Local< Context > context)
Definition: api.cc:3200
const CpuProfileNode * GetTopDownRoot() const
Definition: api.cc:10083
virtual MaybeLocal< WasmCompiledModule > GetWasmModuleFromId(Isolate *isolate, uint32_t transfer_id)
Definition: api.cc:3153
const HeapGraphNode * GetNode(int index) const
Definition: api.cc:10353
Flags GetFlags() const
Definition: api.cc:6960
Local< Array > AsArray() const
Definition: api.cc:7128
Local< Value > GetInferredName() const
Definition: api.cc:5051
static Local< Private > ForApi(Isolate *isolate, Local< String > name)
Definition: api.cc:7956
Local< UnboundModuleScript > GetUnboundModuleScript()
Definition: api.cc:2259
static Local< StackTrace > CurrentStackTrace(Isolate *isolate, int frame_limit, StackTraceOptions options=kDetailed)
Definition: api.cc:2915
bool IsPromise() const
Definition: api.cc:3499
int GetScriptColumnNumber() const
Definition: api.cc:5128
bool IsImmutableProto()
Definition: api.cc:1990
void MarkAsHandled()
Definition: api.cc:7353
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewRemoteInstance()
Definition: api.cc:6374
static Local< Symbol > For(Isolate *isolate, Local< String > name)
Definition: api.cc:7906
Definition: v8.h:3134
Local< Value > GetBoundFunction() const
Definition: api.cc:5158
void SetNativeDataProperty(Local< String > name, AccessorGetterCallback getter, AccessorSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), PropertyAttribute attribute=None, Local< AccessorSignature > signature=Local< AccessorSignature >(), AccessControl settings=DEFAULT, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:1703
void WriteHeader()
Definition: api.cc:3090
Definition: v8.h:3740
Local< String > GetScriptNameOrSourceURL() const
Definition: api.cc:2957
bool IsExternal() const
Definition: api.cc:3423
bool IsBigInt() const
Definition: api.cc:3393
static V8_WARN_UNUSED_RESULT MaybeLocal< RegExp > New(Local< Context > context, Local< String > pattern, Flags flags)
Definition: api.cc:6928
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetPropertyAttributes(Local< Context > context, Local< Value > key)
Definition: api.cc:4300
Local< Value > GetModuleNamespace()
Definition: api.cc:2249
Contents GetContents()
Definition: api.cc:7836
bool TryHandleWebAssemblyTrapWindows(EXCEPTION_POINTERS *exception)
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetRealNamedPropertyInPrototypeChain(Local< Context > context, Local< Name > key)
Definition: api.cc:4762
bool IsNeuterable() const
Definition: api.cc:7552
void MarkAsUndetectable()
Definition: api.cc:1863
AllocationProfile * GetAllocationProfile()
Definition: api.cc:10450
Definition: v8.h:4256
void ClearObjectIds()
Definition: api.cc:10407
static Local< Private > New(Isolate *isolate, Local< String > name=Local< String >())
Definition: api.cc:7945
int GetLineNumber() const
Definition: api.cc:2929
static MaybeLocal< BigInt > NewFromWords(Local< Context > context, int sign_bit, int word_count, const uint64_t *words)
Definition: api.cc:8014
const intptr_t * external_references
Definition: v8.h:7190
void Dispose()
Definition: api.cc:10123
V8_WARN_UNUSED_RESULT Maybe< bool > WriteValue(Local< Context > context, Local< Value > value)
Definition: api.cc:3096
int64_t GetSampleTimestamp(int index) const
Definition: api.cc:10095
const char * GetFunctionNameStr() const
Definition: api.cc:9980
V8_WARN_UNUSED_RESULT MaybeLocal< Value > ReadValue(Local< Context > context)
Definition: api.cc:3245
void Set(Local< Name > name, Local< Data > value, PropertyAttribute attributes=None)
Definition: api.cc:1283
int GetNodesCount() const
Definition: api.cc:10348
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromTwoByte(Isolate *isolate, const uint16_t *data, v8::NewStringType type, int length=-1)
Definition: api.cc:6535
int GetChildrenCount() const
Definition: api.cc:10310
bool HasNamedLookupInterceptor()
Definition: api.cc:4748
SnapshotObjectId GetMaxSnapshotJSObjectId() const
Definition: api.cc:10359
void Abort(MaybeLocal< Value > exception)
Definition: api.cc:7539
bool IsExternal() const
Definition: api.cc:7547
static V8_WARN_UNUSED_RESULT MaybeLocal< UnboundScript > CompileUnboundScript(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition: api.cc:2368
void SetAccessCheckCallback(AccessCheckCallback callback, Local< Value > data=Local< Value >())
Definition: api.cc:1873
Maybe< bool > HasPrivate(Local< Context > context, Local< Private > key)
Definition: api.cc:4542
Status GetStatus() const
Definition: api.cc:2191
SideEffectType
Definition: v8.h:3204
bool IsFalse() const
Definition: api.cc:3316
static V8_INLINE Local< T > New(Isolate *isolate, Local< T > that)
Definition: v8.h:9365
static void UseDetailedSourcePositionsForProfiling(Isolate *isolate)
Definition: api.cc:10164
Local< Object > FindInstanceInPrototypeChain(Local< FunctionTemplate > tmpl)
Definition: api.cc:4367
Local< Promise > GetPromise()
Definition: api.cc:7250
void SetImmutableProto()
Definition: api.cc:1994
Local< Value > GetException() const
Definition: api.cc:2211
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetOwnPropertyDescriptor(Local< Context > context, Local< Name > key)
Definition: api.cc:4323
CodeEventType
Definition: v8-profiler.h:1064
bool IsBoolean() const
Definition: api.cc:3419
size_t ByteLength()
Definition: api.cc:7722
double ValueOf() const
Definition: api.cc:6903
static MaybeLocal< Proxy > New(Local< Context > context, Local< Object > local_target, Local< Object > local_handler)
Definition: api.cc:7384
StackTraceOptions
Definition: v8.h:1691
JitCodeEventHandler code_event_handler
Definition: v8.h:7150
const HeapSnapshot * GetHeapSnapshot(int index)
Definition: api.cc:10387
int64_t Int64Value(bool *lossless=nullptr) const
Definition: api.cc:8032
Definition: v8.h:5090
int GetColumn() const
Definition: api.cc:2935
const char * GetBailoutReason() const
Definition: api.cc:10027
static void SetStressRunType(StressType type)
Definition: api.cc:10497
void DeleteAllHeapSnapshots()
Definition: api.cc:10454
bool HasHandler()
Definition: api.cc:7322
bool CanMakeExternal()
Definition: api.cc:6678
bool IsSharedArrayBuffer() const
Definition: api.cc:3380
const CpuProfileNode * GetChild(int index) const
Definition: api.cc:10054
static MaybeLocal< WasmCompiledModule > FromTransferrableModule(Isolate *isolate, const TransferrableModule &)
Definition: api.cc:7420
void Append(Local< V > value)
Definition: v8-util.h:578
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromUtf8(Isolate *isolate, const char *data, v8::NewStringType type, int length=-1)
Definition: api.cc:6511
Local< Value > GetDisplayName() const
Definition: api.cc:5075
void Serialize(OutputStream *stream, SerializationFormat format=kJSON) const
Definition: api.cc:10364
size_t GetShallowSize() const
Definition: api.cc:10305
void Delete()
Definition: api.cc:10067
ArrayBuffer::Allocator * array_buffer_allocator
Definition: v8.h:7182
Local< UnboundScript > GetUnboundScript()
Definition: api.cc:2144
int GetColumnNumber() const
Definition: api.cc:10008
static Local< FunctionTemplate > New(Isolate *isolate, FunctionCallback callback=nullptr, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:1417
V8_WARN_UNUSED_RESULT Maybe< bool > Equals(Local< Context > context, Local< Value > that) const
Definition: api.cc:3967
Local< String > GetFunctionName() const
Definition: api.cc:9817
int GetStartPosition() const
Definition: api.cc:2818
bool IsArrayBufferView() const
Definition: api.cc:3354
int Utf8Length(Isolate *isolate) const
Definition: api.cc:5301
BackupIncumbentScope(Local< Context > backup_incumbent_context)
Definition: api.cc:1177
ScriptOrigin GetScriptOrigin() const
Definition: api.cc:2782
bool IsTrue() const
Definition: api.cc:3309
bool IsInt32() const
Definition: api.cc:3436
bool IsConstructor()
Definition: api.cc:4877
void StopSamplingHeapProfiler()
Definition: api.cc:10445
bool HasInstance(Local< Value > object)
Definition: api.cc:6401
bool GetLineTicks(LineTick *entries, unsigned int length) const
Definition: api.cc:10020
Definition: v8.h:1842
Local< String > GetConstructorName()
Definition: api.cc:4447
void Neuter()
Definition: api.cc:7614
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetRealNamedPropertyAttributes(Local< Context > context, Local< Name > key)
Definition: api.cc:4826
bool StartSamplingHeapProfiler(uint64_t sample_interval=512 *1024, int stack_depth=16, SamplingFlags flags=kSamplingNoFlags)
Definition: api.cc:10437
Local< Value > Name() const
Definition: api.cc:5718
Local< Object > Clone()
Definition: api.cc:4847
bool HasBuffer() const
Definition: api.cc:7708
static Local< Map > New(Isolate *isolate)
Definition: api.cc:7007
TransferrableModule GetTransferrableModule()
Definition: api.cc:7404
const HeapGraphEdge * GetChild(int index) const
Definition: api.cc:10315
V8_WARN_UNUSED_RESULT std::pair< uint8_t *, size_t > Release()
Definition: api.cc:3112
void SetIntrinsicDataProperty(Local< Name > name, Intrinsic intrinsic, PropertyAttribute attribute=None)
Definition: api.cc:1737
Definition: v8.h:963
static bool GetStackSample(Isolate *isolate, v8::RegisterState *state, RecordCEntryFrame record_c_entry_frame, void **frames, size_t frames_limit, v8::SampleInfo *sample_info, bool use_simulator_reg_state=true)
Definition: tick-sample.cc:183
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, Local< Value > key)
Definition: api.cc:4513
void WriteUint32(uint32_t value)
Definition: api.cc:3128
bool IsCallable()
Definition: api.cc:4872
virtual Maybe< bool > WriteHostObject(Isolate *isolate, Local< Object > object)
Definition: api.cc:3040
unsigned int GetHitLineCount() const
Definition: api.cc:10014
bool IsArrayBuffer() const
Definition: api.cc:3348
static Allocator * NewDefaultAllocator()
Definition: api.cc:7543
Status
Definition: v8.h:1140
Local< ObjectTemplate > PrototypeTemplate()
Definition: api.cc:1340
bool IsTypedArray() const
Definition: api.cc:3359
PromiseState
Definition: v8.h:4104
Local< Value > GetScriptResourceName() const
Definition: api.cc:2791
void ToWordsArray(int *sign_bit, int *word_count, uint64_t *words) const
Definition: api.cc:8042
void SetCallAsFunctionHandler(FunctionCallback callback, Local< Value > data=Local< Value >())
Definition: api.cc:1952
size_t CopyContents(void *dest, size_t byte_length)
Definition: api.cc:7684
int GetScriptId() const
Definition: api.cc:2941
bool TryHandleWebAssemblyTrapPosix(int sig_code, siginfo_t *info, void *context)
bool ContainsOnlyOneByte() const
Definition: api.cc:5294
AccessControl
Definition: v8.h:3175
void OnBytesReceived(const uint8_t *, size_t size)
Definition: api.cc:7532
bool IsExternal() const
Definition: api.cc:7803
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetRealNamedPropertyAttributesInPrototypeChain(Local< Context > context, Local< Name > key)
Definition: api.cc:4785
static const SnapshotObjectId kUnknownObjectId
Definition: v8-profiler.h:820
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:9733
PropertyFilter
Definition: v8.h:3185
static V8_WARN_UNUSED_RESULT MaybeLocal< Function > CompileFunctionInContext(Local< Context > context, Source *source, size_t arguments_count, Local< String > arguments[], size_t context_extension_count, Local< Object > context_extensions[], CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition: api.cc:2451
ResourceConstraints constraints
Definition: v8.h:7155
bool IsConstructor() const
Definition: api.cc:2980
V8_WARN_UNUSED_RESULT Maybe< bool > SetLazyDataProperty(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, Local< Value > data=Local< Value >(), PropertyAttribute attributes=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:4648
static Local< String > Concat(Isolate *isolate, Local< String > left, Local< String > right)
Definition: api.cc:6552
Definition: v8.h:3704
int GetEndPosition() const
Definition: api.cc:2824
bool IsUint32() const
Definition: api.cc:3446
static void DeoptimizeAll(Isolate *isolate)
Definition: api.cc:10553
V8_WARN_UNUSED_RESULT Maybe< bool > SetNativeDataProperty(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), PropertyAttribute attributes=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition: api.cc:4637
static void PrepareStressRun(int run)
Definition: api.cc:10519
int ScriptId() const
Definition: api.cc:5143
virtual size_t length() const =0
bool IsName() const
Definition: api.cc:3326
bool IsGeneratorObject() const
Definition: api.cc:3485
static ScriptStreamingTask * StartStreamingScript(Isolate *isolate, StreamedSource *source, CompileOptions options=kNoCompileOptions)
Definition: api.cc:2524
Contents GetContents()
Definition: api.cc:7599
SnapshotObjectId GetHeapStats(OutputStream *stream, int64_t *timestamp_us=nullptr)
Definition: api.cc:10431
void TransferArrayBuffer(uint32_t transfer_id, Local< ArrayBuffer > array_buffer)
Definition: api.cc:3116
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetRealNamedProperty(Local< Context > context, Local< Name > key)
Definition: api.cc:4810
bool IsEval() const
Definition: api.cc:2978