Home | History | Annotate | Download | only in src
      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/debug/debug-coverage.h"
     36 #include "src/debug/debug-evaluate.h"
     37 #include "src/debug/debug-type-profile.h"
     38 #include "src/debug/debug.h"
     39 #include "src/debug/liveedit.h"
     40 #include "src/deoptimizer.h"
     41 #include "src/detachable-vector.h"
     42 #include "src/execution.h"
     43 #include "src/frames-inl.h"
     44 #include "src/gdb-jit.h"
     45 #include "src/global-handles.h"
     46 #include "src/globals.h"
     47 #include "src/icu_util.h"
     48 #include "src/isolate-inl.h"
     49 #include "src/json-parser.h"
     50 #include "src/json-stringifier.h"
     51 #include "src/messages.h"
     52 #include "src/objects-inl.h"
     53 #include "src/objects/api-callbacks.h"
     54 #include "src/objects/js-array-inl.h"
     55 #include "src/objects/js-collection-inl.h"
     56 #include "src/objects/js-generator-inl.h"
     57 #include "src/objects/js-promise-inl.h"
     58 #include "src/objects/js-regexp-inl.h"
     59 #include "src/objects/module-inl.h"
     60 #include "src/objects/ordered-hash-table-inl.h"
     61 #include "src/objects/templates.h"
     62 #include "src/parsing/parser.h"
     63 #include "src/parsing/scanner-character-streams.h"
     64 #include "src/pending-compilation-error-handler.h"
     65 #include "src/profiler/cpu-profiler.h"
     66 #include "src/profiler/heap-profiler.h"
     67 #include "src/profiler/heap-snapshot-generator-inl.h"
     68 #include "src/profiler/profile-generator-inl.h"
     69 #include "src/profiler/tick-sample.h"
     70 #include "src/property-descriptor.h"
     71 #include "src/property-details.h"
     72 #include "src/property.h"
     73 #include "src/prototype.h"
     74 #include "src/runtime-profiler.h"
     75 #include "src/runtime/runtime.h"
     76 #include "src/simulator.h"
     77 #include "src/snapshot/builtin-serializer.h"
     78 #include "src/snapshot/code-serializer.h"
     79 #include "src/snapshot/natives.h"
     80 #include "src/snapshot/snapshot.h"
     81 #include "src/startup-data-util.h"
     82 #include "src/string-hasher.h"
     83 #include "src/tracing/trace-event.h"
     84 #include "src/trap-handler/trap-handler.h"
     85 #include "src/unicode-cache-inl.h"
     86 #include "src/unicode-inl.h"
     87 #include "src/v8.h"
     88 #include "src/v8threads.h"
     89 #include "src/value-serializer.h"
     90 #include "src/version.h"
     91 #include "src/vm-state-inl.h"
     92 #include "src/wasm/streaming-decoder.h"
     93 #include "src/wasm/wasm-engine.h"
     94 #include "src/wasm/wasm-objects-inl.h"
     95 #include "src/wasm/wasm-result.h"
     96 #include "src/wasm/wasm-serialization.h"
     97 
     98 namespace v8 {
     99 
    100 /*
    101  * Most API methods should use one of the three macros:
    102  *
    103  * ENTER_V8, ENTER_V8_NO_SCRIPT, ENTER_V8_NO_SCRIPT_NO_EXCEPTION.
    104  *
    105  * The latter two assume that no script is executed, and no exceptions are
    106  * scheduled in addition (respectively). Creating a pending exception and
    107  * removing it before returning is ok.
    108  *
    109  * Exceptions should be handled either by invoking one of the
    110  * RETURN_ON_FAILED_EXECUTION* macros.
    111  *
    112  * Don't use macros with DO_NOT_USE in their name.
    113  *
    114  * TODO(jochen): Document debugger specific macros.
    115  * TODO(jochen): Document LOG_API and other RuntimeCallStats macros.
    116  * TODO(jochen): All API methods should invoke one of the ENTER_V8* macros.
    117  * TODO(jochen): Remove calls form API methods to DO_NOT_USE macros.
    118  */
    119 
    120 #define LOG_API(isolate, class_name, function_name)                           \
    121   i::RuntimeCallTimerScope _runtime_timer(                                    \
    122       isolate, i::RuntimeCallCounterId::kAPI_##class_name##_##function_name); \
    123   LOG(isolate, ApiEntryCall("v8::" #class_name "::" #function_name))
    124 
    125 #define ENTER_V8_DO_NOT_USE(isolate) i::VMState<v8::OTHER> __state__((isolate))
    126 
    127 #define ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name,  \
    128                                    function_name, bailout_value,  \
    129                                    HandleScopeClass, do_callback) \
    130   if (IsExecutionTerminatingCheck(isolate)) {                     \
    131     return bailout_value;                                         \
    132   }                                                               \
    133   HandleScopeClass handle_scope(isolate);                         \
    134   CallDepthScope<do_callback> call_depth_scope(isolate, context); \
    135   LOG_API(isolate, class_name, function_name);                    \
    136   i::VMState<v8::OTHER> __state__((isolate));                     \
    137   bool has_pending_exception = false
    138 
    139 #define PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, T)       \
    140   if (IsExecutionTerminatingCheck(isolate)) {                                \
    141     return MaybeLocal<T>();                                                  \
    142   }                                                                          \
    143   InternalEscapableScope handle_scope(isolate);                              \
    144   CallDepthScope<false> call_depth_scope(isolate, v8::Local<v8::Context>()); \
    145   i::VMState<v8::OTHER> __state__((isolate));                                \
    146   bool has_pending_exception = false
    147 
    148 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \
    149                                            bailout_value, HandleScopeClass,    \
    150                                            do_callback)                        \
    151   auto isolate = context.IsEmpty()                                             \
    152                      ? i::Isolate::Current()                                   \
    153                      : reinterpret_cast<i::Isolate*>(context->GetIsolate());   \
    154   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name,      \
    155                              bailout_value, HandleScopeClass, do_callback);
    156 
    157 #define PREPARE_FOR_EXECUTION(context, class_name, function_name, T)          \
    158   PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name,      \
    159                                      MaybeLocal<T>(), InternalEscapableScope, \
    160                                      false)
    161 
    162 #define ENTER_V8(isolate, context, class_name, function_name, bailout_value, \
    163                  HandleScopeClass)                                           \
    164   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name,    \
    165                              bailout_value, HandleScopeClass, true)
    166 
    167 #ifdef DEBUG
    168 #define ENTER_V8_NO_SCRIPT(isolate, context, class_name, function_name,   \
    169                            bailout_value, HandleScopeClass)               \
    170   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
    171                              bailout_value, HandleScopeClass, false);     \
    172   i::DisallowJavascriptExecutionDebugOnly __no_script__((isolate))
    173 
    174 #define ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate)                    \
    175   i::VMState<v8::OTHER> __state__((isolate));                       \
    176   i::DisallowJavascriptExecutionDebugOnly __no_script__((isolate)); \
    177   i::DisallowExceptions __no_exceptions__((isolate))
    178 
    179 #define ENTER_V8_FOR_NEW_CONTEXT(isolate)     \
    180   i::VMState<v8::OTHER> __state__((isolate)); \
    181   i::DisallowExceptions __no_exceptions__((isolate))
    182 #else
    183 #define ENTER_V8_NO_SCRIPT(isolate, context, class_name, function_name,   \
    184                            bailout_value, HandleScopeClass)               \
    185   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
    186                              bailout_value, HandleScopeClass, false)
    187 
    188 #define ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate) \
    189   i::VMState<v8::OTHER> __state__((isolate));
    190 
    191 #define ENTER_V8_FOR_NEW_CONTEXT(isolate) \
    192   i::VMState<v8::OTHER> __state__((isolate));
    193 #endif  // DEBUG
    194 
    195 #define EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, value) \
    196   do {                                                            \
    197     if (has_pending_exception) {                                  \
    198       call_depth_scope.Escape();                                  \
    199       return value;                                               \
    200     }                                                             \
    201   } while (false)
    202 
    203 #define RETURN_ON_FAILED_EXECUTION(T) \
    204   EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, MaybeLocal<T>())
    205 
    206 #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \
    207   EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, Nothing<T>())
    208 
    209 #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \
    210   return maybe_local.FromMaybe(Local<T>());
    211 
    212 
    213 #define RETURN_ESCAPED(value) return handle_scope.Escape(value);
    214 
    215 namespace {
    216 
    217 Local<Context> ContextFromNeverReadOnlySpaceObject(
    218     i::Handle<i::NeverReadOnlySpaceObject> obj) {
    219   return reinterpret_cast<v8::Isolate*>(obj->GetIsolate())->GetCurrentContext();
    220 }
    221 
    222 // TODO(delphick): Remove this completely when the deprecated functions that use
    223 // it are removed.
    224 // DO NOT USE THIS IN NEW CODE!
    225 i::Isolate* UnsafeIsolateFromHeapObject(i::Handle<i::HeapObject> obj) {
    226   // Use MemoryChunk directly instead of Isolate::FromWritableHeapObject to
    227   // temporarily allow isolate access from read-only space objects.
    228   i::MemoryChunk* chunk = i::MemoryChunk::FromHeapObject(*obj);
    229   return chunk->heap()->isolate();
    230 }
    231 
    232 // TODO(delphick): Remove this completely when the deprecated functions that use
    233 // it are removed.
    234 // DO NOT USE THIS IN NEW CODE!
    235 Local<Context> UnsafeContextFromHeapObject(i::Handle<i::Object> obj) {
    236   // Use MemoryChunk directly instead of Isolate::FromWritableHeapObject to
    237   // temporarily allow isolate access from read-only space objects.
    238   i::MemoryChunk* chunk =
    239       i::MemoryChunk::FromHeapObject(i::HeapObject::cast(*obj));
    240   return reinterpret_cast<Isolate*>(chunk->heap()->isolate())
    241       ->GetCurrentContext();
    242 }
    243 
    244 class InternalEscapableScope : public v8::EscapableHandleScope {
    245  public:
    246   explicit inline InternalEscapableScope(i::Isolate* isolate)
    247       : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {}
    248 };
    249 
    250 // TODO(jochen): This should be #ifdef DEBUG
    251 #ifdef V8_CHECK_MICROTASKS_SCOPES_CONSISTENCY
    252 void CheckMicrotasksScopesConsistency(i::Isolate* isolate) {
    253   auto handle_scope_implementer = isolate->handle_scope_implementer();
    254   if (handle_scope_implementer->microtasks_policy() ==
    255       v8::MicrotasksPolicy::kScoped) {
    256     DCHECK(handle_scope_implementer->GetMicrotasksScopeDepth() ||
    257            !handle_scope_implementer->DebugMicrotasksScopeDepthIsZero());
    258   }
    259 }
    260 #endif
    261 
    262 template <bool do_callback>
    263 class CallDepthScope {
    264  public:
    265   explicit CallDepthScope(i::Isolate* isolate, Local<Context> context)
    266       : isolate_(isolate),
    267         context_(context),
    268         escaped_(false),
    269         safe_for_termination_(isolate->next_v8_call_is_safe_for_termination()),
    270         interrupts_scope_(isolate_, i::StackGuard::TERMINATE_EXECUTION,
    271                           isolate_->only_terminate_in_safe_scope()
    272                               ? (safe_for_termination_
    273                                      ? i::InterruptsScope::kRunInterrupts
    274                                      : i::InterruptsScope::kPostponeInterrupts)
    275                               : i::InterruptsScope::kNoop) {
    276     // TODO(dcarney): remove this when blink stops crashing.
    277     DCHECK(!isolate_->external_caught_exception());
    278     isolate_->handle_scope_implementer()->IncrementCallDepth();
    279     isolate_->set_next_v8_call_is_safe_for_termination(false);
    280     if (!context.IsEmpty()) {
    281       i::Handle<i::Context> env = Utils::OpenHandle(*context);
    282       i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
    283       if (isolate->context() != nullptr &&
    284           isolate->context()->native_context() == env->native_context()) {
    285         context_ = Local<Context>();
    286       } else {
    287         impl->SaveContext(isolate->context());
    288         isolate->set_context(*env);
    289       }
    290     }
    291     if (do_callback) isolate_->FireBeforeCallEnteredCallback();
    292   }
    293   ~CallDepthScope() {
    294     if (!context_.IsEmpty()) {
    295       i::HandleScopeImplementer* impl = isolate_->handle_scope_implementer();
    296       isolate_->set_context(impl->RestoreContext());
    297     }
    298     if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth();
    299     if (do_callback) isolate_->FireCallCompletedCallback();
    300 // TODO(jochen): This should be #ifdef DEBUG
    301 #ifdef V8_CHECK_MICROTASKS_SCOPES_CONSISTENCY
    302     if (do_callback) CheckMicrotasksScopesConsistency(isolate_);
    303 #endif
    304     isolate_->set_next_v8_call_is_safe_for_termination(safe_for_termination_);
    305   }
    306 
    307   void Escape() {
    308     DCHECK(!escaped_);
    309     escaped_ = true;
    310     auto handle_scope_implementer = isolate_->handle_scope_implementer();
    311     handle_scope_implementer->DecrementCallDepth();
    312     bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero();
    313     isolate_->OptionalRescheduleException(call_depth_is_zero);
    314   }
    315 
    316  private:
    317   i::Isolate* const isolate_;
    318   Local<Context> context_;
    319   bool escaped_;
    320   bool do_callback_;
    321   bool safe_for_termination_;
    322   i::InterruptsScope interrupts_scope_;
    323 };
    324 
    325 }  // namespace
    326 
    327 
    328 static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate,
    329                                              i::Handle<i::Script> script) {
    330   i::Handle<i::Object> scriptName(script->GetNameOrSourceURL(), isolate);
    331   i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate);
    332   i::Handle<i::FixedArray> host_defined_options(script->host_defined_options(),
    333                                                 isolate);
    334   v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
    335   ScriptOriginOptions options(script->origin_options());
    336   v8::ScriptOrigin origin(
    337       Utils::ToLocal(scriptName),
    338       v8::Integer::New(v8_isolate, script->line_offset()),
    339       v8::Integer::New(v8_isolate, script->column_offset()),
    340       v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()),
    341       v8::Integer::New(v8_isolate, script->id()),
    342       Utils::ToLocal(source_map_url),
    343       v8::Boolean::New(v8_isolate, options.IsOpaque()),
    344       v8::Boolean::New(v8_isolate, script->type() == i::Script::TYPE_WASM),
    345       v8::Boolean::New(v8_isolate, options.IsModule()),
    346       Utils::ToLocal(host_defined_options));
    347   return origin;
    348 }
    349 
    350 
    351 // --- E x c e p t i o n   B e h a v i o r ---
    352 
    353 void i::FatalProcessOutOfMemory(i::Isolate* isolate, const char* location) {
    354   i::V8::FatalProcessOutOfMemory(isolate, location, false);
    355 }
    356 
    357 // When V8 cannot allocate memory FatalProcessOutOfMemory is called. The default
    358 // OOM error handler is called and execution is stopped.
    359 void i::V8::FatalProcessOutOfMemory(i::Isolate* isolate, const char* location,
    360                                     bool is_heap_oom) {
    361   char last_few_messages[Heap::kTraceRingBufferSize + 1];
    362   char js_stacktrace[Heap::kStacktraceBufferSize + 1];
    363   i::HeapStats heap_stats;
    364 
    365   if (isolate == nullptr) {
    366     isolate = Isolate::Current();
    367   }
    368 
    369   if (isolate == nullptr) {
    370     // On a background thread -> we cannot retrieve memory information from the
    371     // Isolate. Write easy-to-recognize values on the stack.
    372     memset(last_few_messages, 0x0BADC0DE, Heap::kTraceRingBufferSize + 1);
    373     memset(js_stacktrace, 0x0BADC0DE, Heap::kStacktraceBufferSize + 1);
    374     memset(&heap_stats, 0xBADC0DE, sizeof(heap_stats));
    375     // Note that the embedder's oom handler won't be called in this case. We
    376     // just crash.
    377     FATAL(
    378         "API fatal error handler returned after process out of memory on the "
    379         "background thread");
    380     UNREACHABLE();
    381   }
    382 
    383   memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
    384   memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1);
    385 
    386   intptr_t start_marker;
    387   heap_stats.start_marker = &start_marker;
    388   size_t ro_space_size;
    389   heap_stats.ro_space_size = &ro_space_size;
    390   size_t ro_space_capacity;
    391   heap_stats.ro_space_capacity = &ro_space_capacity;
    392   size_t new_space_size;
    393   heap_stats.new_space_size = &new_space_size;
    394   size_t new_space_capacity;
    395   heap_stats.new_space_capacity = &new_space_capacity;
    396   size_t old_space_size;
    397   heap_stats.old_space_size = &old_space_size;
    398   size_t old_space_capacity;
    399   heap_stats.old_space_capacity = &old_space_capacity;
    400   size_t code_space_size;
    401   heap_stats.code_space_size = &code_space_size;
    402   size_t code_space_capacity;
    403   heap_stats.code_space_capacity = &code_space_capacity;
    404   size_t map_space_size;
    405   heap_stats.map_space_size = &map_space_size;
    406   size_t map_space_capacity;
    407   heap_stats.map_space_capacity = &map_space_capacity;
    408   size_t lo_space_size;
    409   heap_stats.lo_space_size = &lo_space_size;
    410   size_t global_handle_count;
    411   heap_stats.global_handle_count = &global_handle_count;
    412   size_t weak_global_handle_count;
    413   heap_stats.weak_global_handle_count = &weak_global_handle_count;
    414   size_t pending_global_handle_count;
    415   heap_stats.pending_global_handle_count = &pending_global_handle_count;
    416   size_t near_death_global_handle_count;
    417   heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
    418   size_t free_global_handle_count;
    419   heap_stats.free_global_handle_count = &free_global_handle_count;
    420   size_t memory_allocator_size;
    421   heap_stats.memory_allocator_size = &memory_allocator_size;
    422   size_t memory_allocator_capacity;
    423   heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
    424   size_t malloced_memory;
    425   heap_stats.malloced_memory = &malloced_memory;
    426   size_t malloced_peak_memory;
    427   heap_stats.malloced_peak_memory = &malloced_peak_memory;
    428   size_t objects_per_type[LAST_TYPE + 1] = {0};
    429   heap_stats.objects_per_type = objects_per_type;
    430   size_t size_per_type[LAST_TYPE + 1] = {0};
    431   heap_stats.size_per_type = size_per_type;
    432   int os_error;
    433   heap_stats.os_error = &os_error;
    434   heap_stats.last_few_messages = last_few_messages;
    435   heap_stats.js_stacktrace = js_stacktrace;
    436   intptr_t end_marker;
    437   heap_stats.end_marker = &end_marker;
    438   if (isolate->heap()->HasBeenSetUp()) {
    439     // BUG(1718): Don't use the take_snapshot since we don't support
    440     // HeapIterator here without doing a special GC.
    441     isolate->heap()->RecordStats(&heap_stats, false);
    442     char* first_newline = strchr(last_few_messages, '\n');
    443     if (first_newline == nullptr || first_newline[1] == '\0')
    444       first_newline = last_few_messages;
    445     PrintF("\n<--- Last few GCs --->\n%s\n", first_newline);
    446     PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace);
    447   }
    448   Utils::ReportOOMFailure(isolate, location, is_heap_oom);
    449   // If the fatal error handler returns, we stop execution.
    450   FATAL("API fatal error handler returned after process out of memory");
    451 }
    452 
    453 
    454 void Utils::ReportApiFailure(const char* location, const char* message) {
    455   i::Isolate* isolate = i::Isolate::Current();
    456   FatalErrorCallback callback = nullptr;
    457   if (isolate != nullptr) {
    458     callback = isolate->exception_behavior();
    459   }
    460   if (callback == nullptr) {
    461     base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
    462                          message);
    463     base::OS::Abort();
    464   } else {
    465     callback(location, message);
    466   }
    467   isolate->SignalFatalError();
    468 }
    469 
    470 void Utils::ReportOOMFailure(i::Isolate* isolate, const char* location,
    471                              bool is_heap_oom) {
    472   OOMErrorCallback oom_callback = isolate->oom_behavior();
    473   if (oom_callback == nullptr) {
    474     // TODO(wfh): Remove this fallback once Blink is setting OOM handler. See
    475     // crbug.com/614440.
    476     FatalErrorCallback fatal_callback = isolate->exception_behavior();
    477     if (fatal_callback == nullptr) {
    478       base::OS::PrintError("\n#\n# Fatal %s OOM in %s\n#\n\n",
    479                            is_heap_oom ? "javascript" : "process", location);
    480       base::OS::Abort();
    481     } else {
    482       fatal_callback(location,
    483                      is_heap_oom
    484                          ? "Allocation failed - JavaScript heap out of memory"
    485                          : "Allocation failed - process out of memory");
    486     }
    487   } else {
    488     oom_callback(location, is_heap_oom);
    489   }
    490   isolate->SignalFatalError();
    491 }
    492 
    493 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
    494   if (isolate->has_scheduled_exception()) {
    495     return isolate->scheduled_exception() ==
    496            i::ReadOnlyRoots(isolate).termination_exception();
    497   }
    498   return false;
    499 }
    500 
    501 
    502 void V8::SetNativesDataBlob(StartupData* natives_blob) {
    503   i::V8::SetNativesBlob(natives_blob);
    504 }
    505 
    506 
    507 void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
    508   i::V8::SetSnapshotBlob(snapshot_blob);
    509 }
    510 
    511 namespace {
    512 
    513 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
    514  public:
    515   void* Allocate(size_t length) override {
    516 #if V8_OS_AIX && _LINUX_SOURCE_COMPAT
    517     // Work around for GCC bug on AIX
    518     // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79839
    519     void* data = __linux_calloc(length, 1);
    520 #else
    521     void* data = calloc(length, 1);
    522 #endif
    523     return data;
    524   }
    525 
    526   void* AllocateUninitialized(size_t length) override {
    527 #if V8_OS_AIX && _LINUX_SOURCE_COMPAT
    528     // Work around for GCC bug on AIX
    529     // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79839
    530     void* data = __linux_malloc(length);
    531 #else
    532     void* data = malloc(length);
    533 #endif
    534     return data;
    535   }
    536 
    537   void Free(void* data, size_t) override { free(data); }
    538 };
    539 
    540 struct SnapshotCreatorData {
    541   explicit SnapshotCreatorData(Isolate* isolate)
    542       : isolate_(isolate),
    543         default_context_(),
    544         contexts_(isolate),
    545         created_(false) {}
    546 
    547   static SnapshotCreatorData* cast(void* data) {
    548     return reinterpret_cast<SnapshotCreatorData*>(data);
    549   }
    550 
    551   ArrayBufferAllocator allocator_;
    552   Isolate* isolate_;
    553   Persistent<Context> default_context_;
    554   SerializeInternalFieldsCallback default_embedder_fields_serializer_;
    555   PersistentValueVector<Context> contexts_;
    556   std::vector<SerializeInternalFieldsCallback> embedder_fields_serializers_;
    557   bool created_;
    558 };
    559 
    560 }  // namespace
    561 
    562 SnapshotCreator::SnapshotCreator(Isolate* isolate,
    563                                  const intptr_t* external_references,
    564                                  StartupData* existing_snapshot) {
    565   SnapshotCreatorData* data = new SnapshotCreatorData(isolate);
    566   data->isolate_ = isolate;
    567   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    568   internal_isolate->set_array_buffer_allocator(&data->allocator_);
    569   internal_isolate->set_api_external_references(external_references);
    570   internal_isolate->enable_serializer();
    571   isolate->Enter();
    572   const StartupData* blob = existing_snapshot
    573                                 ? existing_snapshot
    574                                 : i::Snapshot::DefaultSnapshotBlob();
    575   if (blob && blob->raw_size > 0) {
    576     internal_isolate->set_snapshot_blob(blob);
    577     i::Snapshot::Initialize(internal_isolate);
    578   } else {
    579     internal_isolate->Init(nullptr);
    580   }
    581   data_ = data;
    582 }
    583 
    584 SnapshotCreator::SnapshotCreator(const intptr_t* external_references,
    585                                  StartupData* existing_snapshot)
    586     : SnapshotCreator(reinterpret_cast<Isolate*>(new i::Isolate()),
    587                       external_references, existing_snapshot) {}
    588 
    589 SnapshotCreator::~SnapshotCreator() {
    590   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
    591   DCHECK(data->created_);
    592   Isolate* isolate = data->isolate_;
    593   isolate->Exit();
    594   isolate->Dispose();
    595   delete data;
    596 }
    597 
    598 Isolate* SnapshotCreator::GetIsolate() {
    599   return SnapshotCreatorData::cast(data_)->isolate_;
    600 }
    601 
    602 void SnapshotCreator::SetDefaultContext(
    603     Local<Context> context, SerializeInternalFieldsCallback callback) {
    604   DCHECK(!context.IsEmpty());
    605   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
    606   DCHECK(!data->created_);
    607   DCHECK(data->default_context_.IsEmpty());
    608   Isolate* isolate = data->isolate_;
    609   CHECK_EQ(isolate, context->GetIsolate());
    610   data->default_context_.Reset(isolate, context);
    611   data->default_embedder_fields_serializer_ = callback;
    612 }
    613 
    614 size_t SnapshotCreator::AddContext(Local<Context> context,
    615                                    SerializeInternalFieldsCallback callback) {
    616   DCHECK(!context.IsEmpty());
    617   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
    618   DCHECK(!data->created_);
    619   Isolate* isolate = data->isolate_;
    620   CHECK_EQ(isolate, context->GetIsolate());
    621   size_t index = data->contexts_.Size();
    622   data->contexts_.Append(context);
    623   data->embedder_fields_serializers_.push_back(callback);
    624   return index;
    625 }
    626 
    627 size_t SnapshotCreator::AddTemplate(Local<Template> template_obj) {
    628   return AddData(template_obj);
    629 }
    630 
    631 size_t SnapshotCreator::AddData(i::Object* object) {
    632   DCHECK_NOT_NULL(object);
    633   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
    634   DCHECK(!data->created_);
    635   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_);
    636   i::HandleScope scope(isolate);
    637   i::Handle<i::Object> obj(object, isolate);
    638   i::Handle<i::ArrayList> list;
    639   if (!isolate->heap()->serialized_objects()->IsArrayList()) {
    640     list = i::ArrayList::New(isolate, 1);
    641   } else {
    642     list = i::Handle<i::ArrayList>(
    643         i::ArrayList::cast(isolate->heap()->serialized_objects()), isolate);
    644   }
    645   size_t index = static_cast<size_t>(list->Length());
    646   list = i::ArrayList::Add(isolate, list, obj);
    647   isolate->heap()->SetSerializedObjects(*list);
    648   return index;
    649 }
    650 
    651 size_t SnapshotCreator::AddData(Local<Context> context, i::Object* object) {
    652   DCHECK_NOT_NULL(object);
    653   DCHECK(!SnapshotCreatorData::cast(data_)->created_);
    654   i::Handle<i::Context> ctx = Utils::OpenHandle(*context);
    655   i::Isolate* isolate = ctx->GetIsolate();
    656   i::HandleScope scope(isolate);
    657   i::Handle<i::Object> obj(object, isolate);
    658   i::Handle<i::ArrayList> list;
    659   if (!ctx->serialized_objects()->IsArrayList()) {
    660     list = i::ArrayList::New(isolate, 1);
    661   } else {
    662     list = i::Handle<i::ArrayList>(
    663         i::ArrayList::cast(ctx->serialized_objects()), isolate);
    664   }
    665   size_t index = static_cast<size_t>(list->Length());
    666   list = i::ArrayList::Add(isolate, list, obj);
    667   ctx->set_serialized_objects(*list);
    668   return index;
    669 }
    670 
    671 namespace {
    672 void ConvertSerializedObjectsToFixedArray(Local<Context> context) {
    673   i::Handle<i::Context> ctx = Utils::OpenHandle(*context);
    674   i::Isolate* isolate = ctx->GetIsolate();
    675   if (!ctx->serialized_objects()->IsArrayList()) {
    676     ctx->set_serialized_objects(i::ReadOnlyRoots(isolate).empty_fixed_array());
    677   } else {
    678     i::Handle<i::ArrayList> list(i::ArrayList::cast(ctx->serialized_objects()),
    679                                  isolate);
    680     i::Handle<i::FixedArray> elements = i::ArrayList::Elements(isolate, list);
    681     ctx->set_serialized_objects(*elements);
    682   }
    683 }
    684 
    685 void ConvertSerializedObjectsToFixedArray(i::Isolate* isolate) {
    686   if (!isolate->heap()->serialized_objects()->IsArrayList()) {
    687     isolate->heap()->SetSerializedObjects(
    688         i::ReadOnlyRoots(isolate).empty_fixed_array());
    689   } else {
    690     i::Handle<i::ArrayList> list(
    691         i::ArrayList::cast(isolate->heap()->serialized_objects()), isolate);
    692     i::Handle<i::FixedArray> elements = i::ArrayList::Elements(isolate, list);
    693     isolate->heap()->SetSerializedObjects(*elements);
    694   }
    695 }
    696 }  // anonymous namespace
    697 
    698 StartupData SnapshotCreator::CreateBlob(
    699     SnapshotCreator::FunctionCodeHandling function_code_handling) {
    700   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
    701   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_);
    702   DCHECK(!data->created_);
    703   DCHECK(!data->default_context_.IsEmpty());
    704 
    705   int num_additional_contexts = static_cast<int>(data->contexts_.Size());
    706 
    707   {
    708     i::HandleScope scope(isolate);
    709     // Convert list of context-independent data to FixedArray.
    710     ConvertSerializedObjectsToFixedArray(isolate);
    711 
    712     // Convert lists of context-dependent data to FixedArray.
    713     ConvertSerializedObjectsToFixedArray(
    714         data->default_context_.Get(data->isolate_));
    715     for (int i = 0; i < num_additional_contexts; i++) {
    716       ConvertSerializedObjectsToFixedArray(data->contexts_.Get(i));
    717     }
    718 
    719     // We need to store the global proxy size upfront in case we need the
    720     // bootstrapper to create a global proxy before we deserialize the context.
    721     i::Handle<i::FixedArray> global_proxy_sizes =
    722         isolate->factory()->NewFixedArray(num_additional_contexts, i::TENURED);
    723     for (int i = 0; i < num_additional_contexts; i++) {
    724       i::Handle<i::Context> context =
    725           v8::Utils::OpenHandle(*data->contexts_.Get(i));
    726       global_proxy_sizes->set(i,
    727                               i::Smi::FromInt(context->global_proxy()->Size()));
    728     }
    729     isolate->heap()->SetSerializedGlobalProxySizes(*global_proxy_sizes);
    730   }
    731 
    732   // We might rehash strings and re-sort descriptors. Clear the lookup cache.
    733   isolate->descriptor_lookup_cache()->Clear();
    734 
    735   // If we don't do this then we end up with a stray root pointing at the
    736   // context even after we have disposed of the context.
    737   isolate->heap()->CollectAllAvailableGarbage(
    738       i::GarbageCollectionReason::kSnapshotCreator);
    739   {
    740     i::HandleScope scope(isolate);
    741     isolate->heap()->CompactWeakArrayLists(internal::TENURED);
    742   }
    743 
    744   isolate->heap()->read_only_space()->ClearStringPaddingIfNeeded();
    745 
    746   if (function_code_handling == FunctionCodeHandling::kClear) {
    747     // Clear out re-compilable data from all shared function infos. Any
    748     // JSFunctions using these SFIs will have their code pointers reset by the
    749     // partial serializer.
    750     //
    751     // We have to iterate the heap and collect handles to each clearable SFI,
    752     // before we disable allocation, since we have to allocate UncompiledDatas
    753     // to be able to recompile them.
    754     i::HandleScope scope(isolate);
    755     std::vector<i::Handle<i::SharedFunctionInfo>> sfis_to_clear;
    756 
    757     i::HeapIterator heap_iterator(isolate->heap());
    758     while (i::HeapObject* current_obj = heap_iterator.next()) {
    759       if (current_obj->IsSharedFunctionInfo()) {
    760         i::SharedFunctionInfo* shared =
    761             i::SharedFunctionInfo::cast(current_obj);
    762         if (shared->CanDiscardCompiled()) {
    763           sfis_to_clear.emplace_back(shared, isolate);
    764         }
    765       }
    766     }
    767     i::AllowHeapAllocation allocate_for_discard;
    768     for (i::Handle<i::SharedFunctionInfo> shared : sfis_to_clear) {
    769       i::SharedFunctionInfo::DiscardCompiled(isolate, shared);
    770     }
    771   }
    772 
    773   i::DisallowHeapAllocation no_gc_from_here_on;
    774 
    775   int num_contexts = num_additional_contexts + 1;
    776   std::vector<i::Context*> contexts;
    777   contexts.reserve(num_contexts);
    778   {
    779     i::HandleScope scope(isolate);
    780     contexts.push_back(
    781         *v8::Utils::OpenHandle(*data->default_context_.Get(data->isolate_)));
    782     data->default_context_.Reset();
    783     for (int i = 0; i < num_additional_contexts; i++) {
    784       i::Handle<i::Context> context =
    785           v8::Utils::OpenHandle(*data->contexts_.Get(i));
    786       contexts.push_back(*context);
    787     }
    788     data->contexts_.Clear();
    789   }
    790 
    791   // Check that values referenced by global/eternal handles are accounted for.
    792   i::SerializedHandleChecker handle_checker(isolate, &contexts);
    793   CHECK(handle_checker.CheckGlobalAndEternalHandles());
    794 
    795   i::HeapIterator heap_iterator(isolate->heap());
    796   while (i::HeapObject* current_obj = heap_iterator.next()) {
    797     if (current_obj->IsJSFunction()) {
    798       i::JSFunction* fun = i::JSFunction::cast(current_obj);
    799 
    800       // Complete in-object slack tracking for all functions.
    801       fun->CompleteInobjectSlackTrackingIfActive();
    802 
    803       // Also, clear out feedback vectors, or any optimized code.
    804       if (fun->has_feedback_vector()) {
    805         fun->feedback_cell()->set_value(
    806             i::ReadOnlyRoots(isolate).undefined_value());
    807         fun->set_code(isolate->builtins()->builtin(i::Builtins::kCompileLazy));
    808       }
    809       if (function_code_handling == FunctionCodeHandling::kClear) {
    810         DCHECK(fun->shared()->HasWasmExportedFunctionData() ||
    811                fun->shared()->HasBuiltinId() ||
    812                fun->shared()->IsApiFunction() ||
    813                fun->shared()->HasUncompiledDataWithoutPreParsedScope());
    814       }
    815     }
    816   }
    817 
    818   i::StartupSerializer startup_serializer(isolate);
    819   startup_serializer.SerializeStrongReferences();
    820 
    821   // Serialize each context with a new partial serializer.
    822   std::vector<i::SnapshotData*> context_snapshots;
    823   context_snapshots.reserve(num_contexts);
    824 
    825   // TODO(6593): generalize rehashing, and remove this flag.
    826   bool can_be_rehashed = true;
    827 
    828   for (int i = 0; i < num_contexts; i++) {
    829     bool is_default_context = i == 0;
    830     i::PartialSerializer partial_serializer(
    831         isolate, &startup_serializer,
    832         is_default_context ? data->default_embedder_fields_serializer_
    833                            : data->embedder_fields_serializers_[i - 1]);
    834     partial_serializer.Serialize(&contexts[i], !is_default_context);
    835     can_be_rehashed = can_be_rehashed && partial_serializer.can_be_rehashed();
    836     context_snapshots.push_back(new i::SnapshotData(&partial_serializer));
    837   }
    838 
    839   // Builtin serialization places additional objects into the partial snapshot
    840   // cache and thus needs to happen before SerializeWeakReferencesAndDeferred
    841   // is called below.
    842   i::BuiltinSerializer builtin_serializer(isolate, &startup_serializer);
    843   builtin_serializer.SerializeBuiltinsAndHandlers();
    844 
    845   startup_serializer.SerializeWeakReferencesAndDeferred();
    846   can_be_rehashed = can_be_rehashed && startup_serializer.can_be_rehashed();
    847 
    848   i::SnapshotData startup_snapshot(&startup_serializer);
    849   i::BuiltinSnapshotData builtin_snapshot(&builtin_serializer);
    850   StartupData result = i::Snapshot::CreateSnapshotBlob(
    851       &startup_snapshot, &builtin_snapshot, 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   return result;
    860 }
    861 
    862 void V8::SetDcheckErrorHandler(DcheckErrorCallback that) {
    863   v8::base::SetDcheckFunction(that);
    864 }
    865 
    866 void V8::SetFlagsFromString(const char* str, int length) {
    867   i::FlagList::SetFlagsFromString(str, length);
    868   i::FlagList::EnforceFlagImplications();
    869 }
    870 
    871 
    872 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
    873   i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
    874 }
    875 
    876 RegisteredExtension* RegisteredExtension::first_extension_ = nullptr;
    877 
    878 RegisteredExtension::RegisteredExtension(Extension* extension)
    879     : extension_(extension) { }
    880 
    881 
    882 void RegisteredExtension::Register(RegisteredExtension* that) {
    883   that->next_ = first_extension_;
    884   first_extension_ = that;
    885 }
    886 
    887 
    888 void RegisteredExtension::UnregisterAll() {
    889   RegisteredExtension* re = first_extension_;
    890   while (re != nullptr) {
    891     RegisteredExtension* next = re->next();
    892     delete re;
    893     re = next;
    894   }
    895   first_extension_ = nullptr;
    896 }
    897 
    898 namespace {
    899 class ExtensionResource : public String::ExternalOneByteStringResource {
    900  public:
    901   ExtensionResource() : data_(0), length_(0) {}
    902   ExtensionResource(const char* data, size_t length)
    903       : data_(data), length_(length) {}
    904   const char* data() const { return data_; }
    905   size_t length() const { return length_; }
    906   virtual void Dispose() {}
    907 
    908  private:
    909   const char* data_;
    910   size_t length_;
    911 };
    912 }  // anonymous namespace
    913 
    914 void RegisterExtension(Extension* that) {
    915   RegisteredExtension* extension = new RegisteredExtension(that);
    916   RegisteredExtension::Register(extension);
    917 }
    918 
    919 
    920 Extension::Extension(const char* name,
    921                      const char* source,
    922                      int dep_count,
    923                      const char** deps,
    924                      int source_length)
    925     : name_(name),
    926       source_length_(source_length >= 0 ?
    927                      source_length :
    928                      (source ? static_cast<int>(strlen(source)) : 0)),
    929       dep_count_(dep_count),
    930       deps_(deps),
    931       auto_enable_(false) {
    932   source_ = new ExtensionResource(source, source_length_);
    933   CHECK(source != nullptr || source_length_ == 0);
    934 }
    935 
    936 ResourceConstraints::ResourceConstraints()
    937     : max_semi_space_size_in_kb_(0),
    938       max_old_space_size_(0),
    939       stack_limit_(nullptr),
    940       code_range_size_(0),
    941       max_zone_pool_size_(0) {}
    942 
    943 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
    944                                             uint64_t virtual_memory_limit) {
    945   set_max_semi_space_size_in_kb(
    946       i::Heap::ComputeMaxSemiSpaceSize(physical_memory));
    947   set_max_old_space_size(i::Heap::ComputeMaxOldGenerationSize(physical_memory));
    948   set_max_zone_pool_size(i::AccountingAllocator::kMaxPoolSize);
    949 
    950   if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
    951     // Reserve no more than 1/8 of the memory for the code range, but at most
    952     // kMaximalCodeRangeSize.
    953     set_code_range_size(
    954         i::Min(i::kMaximalCodeRangeSize / i::MB,
    955                static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
    956   }
    957 }
    958 
    959 void SetResourceConstraints(i::Isolate* isolate,
    960                             const ResourceConstraints& constraints) {
    961   size_t semi_space_size = constraints.max_semi_space_size_in_kb();
    962   size_t old_space_size = constraints.max_old_space_size();
    963   size_t code_range_size = constraints.code_range_size();
    964   size_t max_pool_size = constraints.max_zone_pool_size();
    965   if (semi_space_size != 0 || old_space_size != 0 || code_range_size != 0) {
    966     isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
    967                                    code_range_size);
    968   }
    969   isolate->allocator()->ConfigureSegmentPool(max_pool_size);
    970 
    971   if (constraints.stack_limit() != nullptr) {
    972     uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
    973     isolate->stack_guard()->SetStackLimit(limit);
    974   }
    975 }
    976 
    977 
    978 i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** 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     (*obj)->ObjectVerify(isolate);
    984   }
    985 #endif  // VERIFY_HEAP
    986   return result.location();
    987 }
    988 
    989 
    990 i::Object** V8::CopyPersistent(i::Object** obj) {
    991   i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj);
    992   return result.location();
    993 }
    994 
    995 void V8::RegisterExternallyReferencedObject(i::Object** object,
    996                                             i::Isolate* isolate) {
    997   isolate->heap()->RegisterExternallyReferencedObject(object);
    998 }
    999 
   1000 void V8::MakeWeak(i::Object** location, void* parameter,
   1001                   int embedder_field_index1, int embedder_field_index2,
   1002                   WeakCallbackInfo<void>::Callback weak_callback) {
   1003   WeakCallbackType type = WeakCallbackType::kParameter;
   1004   if (embedder_field_index1 == 0) {
   1005     if (embedder_field_index2 == 1) {
   1006       type = WeakCallbackType::kInternalFields;
   1007     } else {
   1008       DCHECK_EQ(embedder_field_index2, -1);
   1009       type = WeakCallbackType::kInternalFields;
   1010     }
   1011   } else {
   1012     DCHECK_EQ(embedder_field_index1, -1);
   1013     DCHECK_EQ(embedder_field_index2, -1);
   1014   }
   1015   i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type);
   1016 }
   1017 
   1018 void V8::MakeWeak(i::Object** location, void* parameter,
   1019                   WeakCallbackInfo<void>::Callback weak_callback,
   1020                   WeakCallbackType type) {
   1021   i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type);
   1022 }
   1023 
   1024 void V8::MakeWeak(i::Object*** location_addr) {
   1025   i::GlobalHandles::MakeWeak(location_addr);
   1026 }
   1027 
   1028 void* V8::ClearWeak(i::Object** location) {
   1029   return i::GlobalHandles::ClearWeakness(location);
   1030 }
   1031 
   1032 void V8::AnnotateStrongRetainer(i::Object** location, const char* label) {
   1033   i::GlobalHandles::AnnotateStrongRetainer(location, label);
   1034 }
   1035 
   1036 void V8::DisposeGlobal(i::Object** location) {
   1037   i::GlobalHandles::Destroy(location);
   1038 }
   1039 
   1040 Value* V8::Eternalize(Isolate* v8_isolate, Value* value) {
   1041   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   1042   i::Object* object = *Utils::OpenHandle(value);
   1043   int index = -1;
   1044   isolate->eternal_handles()->Create(isolate, object, &index);
   1045   return reinterpret_cast<Value*>(
   1046       isolate->eternal_handles()->Get(index).location());
   1047 }
   1048 
   1049 
   1050 void V8::FromJustIsNothing() {
   1051   Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing.");
   1052 }
   1053 
   1054 
   1055 void V8::ToLocalEmpty() {
   1056   Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal.");
   1057 }
   1058 
   1059 void V8::InternalFieldOutOfBounds(int index) {
   1060   Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback,
   1061                   "WeakCallbackInfo::GetInternalField",
   1062                   "Internal field out of bounds.");
   1063 }
   1064 
   1065 
   1066 // --- H a n d l e s ---
   1067 
   1068 
   1069 HandleScope::HandleScope(Isolate* isolate) {
   1070   Initialize(isolate);
   1071 }
   1072 
   1073 
   1074 void HandleScope::Initialize(Isolate* isolate) {
   1075   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
   1076   // We do not want to check the correct usage of the Locker class all over the
   1077   // place, so we do it only here: Without a HandleScope, an embedder can do
   1078   // almost nothing, so it is enough to check in this central place.
   1079   // We make an exception if the serializer is enabled, which means that the
   1080   // Isolate is exclusively used to create a snapshot.
   1081   Utils::ApiCheck(
   1082       !v8::Locker::IsActive() ||
   1083           internal_isolate->thread_manager()->IsLockedByCurrentThread() ||
   1084           internal_isolate->serializer_enabled(),
   1085       "HandleScope::HandleScope",
   1086       "Entering the V8 API without proper locking in place");
   1087   i::HandleScopeData* current = internal_isolate->handle_scope_data();
   1088   isolate_ = internal_isolate;
   1089   prev_next_ = current->next;
   1090   prev_limit_ = current->limit;
   1091   current->level++;
   1092 }
   1093 
   1094 
   1095 HandleScope::~HandleScope() {
   1096   i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
   1097 }
   1098 
   1099 void* HandleScope::operator new(size_t) { base::OS::Abort(); }
   1100 void* HandleScope::operator new[](size_t) { base::OS::Abort(); }
   1101 void HandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
   1102 void HandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }
   1103 
   1104 int HandleScope::NumberOfHandles(Isolate* isolate) {
   1105   return i::HandleScope::NumberOfHandles(
   1106       reinterpret_cast<i::Isolate*>(isolate));
   1107 }
   1108 
   1109 
   1110 i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) {
   1111   return i::HandleScope::CreateHandle(isolate, value);
   1112 }
   1113 
   1114 i::Object** HandleScope::CreateHandle(
   1115     i::NeverReadOnlySpaceObject* writable_object, i::Object* value) {
   1116   DCHECK(reinterpret_cast<i::HeapObject*>(writable_object)->IsHeapObject());
   1117   return i::HandleScope::CreateHandle(writable_object->GetIsolate(), value);
   1118 }
   1119 
   1120 
   1121 EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
   1122   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   1123   escape_slot_ =
   1124       CreateHandle(isolate, i::ReadOnlyRoots(isolate).the_hole_value());
   1125   Initialize(v8_isolate);
   1126 }
   1127 
   1128 
   1129 i::Object** EscapableHandleScope::Escape(i::Object** escape_value) {
   1130   i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
   1131   Utils::ApiCheck((*escape_slot_)->IsTheHole(heap->isolate()),
   1132                   "EscapableHandleScope::Escape", "Escape value set twice");
   1133   if (escape_value == nullptr) {
   1134     *escape_slot_ = i::ReadOnlyRoots(heap).undefined_value();
   1135     return nullptr;
   1136   }
   1137   *escape_slot_ = *escape_value;
   1138   return escape_slot_;
   1139 }
   1140 
   1141 void* EscapableHandleScope::operator new(size_t) { base::OS::Abort(); }
   1142 void* EscapableHandleScope::operator new[](size_t) { base::OS::Abort(); }
   1143 void EscapableHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
   1144 void EscapableHandleScope::operator delete[](void*, size_t) {
   1145   base::OS::Abort();
   1146 }
   1147 
   1148 SealHandleScope::SealHandleScope(Isolate* isolate)
   1149     : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
   1150   i::HandleScopeData* current = isolate_->handle_scope_data();
   1151   prev_limit_ = current->limit;
   1152   current->limit = current->next;
   1153   prev_sealed_level_ = current->sealed_level;
   1154   current->sealed_level = current->level;
   1155 }
   1156 
   1157 
   1158 SealHandleScope::~SealHandleScope() {
   1159   i::HandleScopeData* current = isolate_->handle_scope_data();
   1160   DCHECK_EQ(current->next, current->limit);
   1161   current->limit = prev_limit_;
   1162   DCHECK_EQ(current->level, current->sealed_level);
   1163   current->sealed_level = prev_sealed_level_;
   1164 }
   1165 
   1166 void* SealHandleScope::operator new(size_t) { base::OS::Abort(); }
   1167 void* SealHandleScope::operator new[](size_t) { base::OS::Abort(); }
   1168 void SealHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
   1169 void SealHandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }
   1170 
   1171 void Context::Enter() {
   1172   i::Handle<i::Context> env = Utils::OpenHandle(this);
   1173   i::Isolate* isolate = env->GetIsolate();
   1174   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1175   i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
   1176   impl->EnterContext(env);
   1177   impl->SaveContext(isolate->context());
   1178   isolate->set_context(*env);
   1179 }
   1180 
   1181 void Context::Exit() {
   1182   i::Handle<i::Context> env = Utils::OpenHandle(this);
   1183   i::Isolate* isolate = env->GetIsolate();
   1184   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1185   i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
   1186   if (!Utils::ApiCheck(impl->LastEnteredContextWas(env),
   1187                        "v8::Context::Exit()",
   1188                        "Cannot exit non-entered context")) {
   1189     return;
   1190   }
   1191   impl->LeaveContext();
   1192   isolate->set_context(impl->RestoreContext());
   1193 }
   1194 
   1195 Context::BackupIncumbentScope::BackupIncumbentScope(
   1196     Local<Context> backup_incumbent_context)
   1197     : backup_incumbent_context_(backup_incumbent_context) {
   1198   DCHECK(!backup_incumbent_context_.IsEmpty());
   1199 
   1200   i::Handle<i::Context> env = Utils::OpenHandle(*backup_incumbent_context_);
   1201   i::Isolate* isolate = env->GetIsolate();
   1202   prev_ = isolate->top_backup_incumbent_scope();
   1203   isolate->set_top_backup_incumbent_scope(this);
   1204 }
   1205 
   1206 Context::BackupIncumbentScope::~BackupIncumbentScope() {
   1207   i::Handle<i::Context> env = Utils::OpenHandle(*backup_incumbent_context_);
   1208   i::Isolate* isolate = env->GetIsolate();
   1209   isolate->set_top_backup_incumbent_scope(prev_);
   1210 }
   1211 
   1212 static void* DecodeSmiToAligned(i::Object* value, const char* location) {
   1213   Utils::ApiCheck(value->IsSmi(), location, "Not a Smi");
   1214   return reinterpret_cast<void*>(value);
   1215 }
   1216 
   1217 
   1218 static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) {
   1219   i::Smi* smi = reinterpret_cast<i::Smi*>(value);
   1220   Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned");
   1221   return smi;
   1222 }
   1223 
   1224 
   1225 static i::Handle<i::FixedArray> EmbedderDataFor(Context* context,
   1226                                                 int index,
   1227                                                 bool can_grow,
   1228                                                 const char* location) {
   1229   i::Handle<i::Context> env = Utils::OpenHandle(context);
   1230   i::Isolate* isolate = env->GetIsolate();
   1231   bool ok =
   1232       Utils::ApiCheck(env->IsNativeContext(),
   1233                       location,
   1234                       "Not a native context") &&
   1235       Utils::ApiCheck(index >= 0, location, "Negative index");
   1236   if (!ok) return i::Handle<i::FixedArray>();
   1237   i::Handle<i::FixedArray> data(env->embedder_data(), isolate);
   1238   if (index < data->length()) return data;
   1239   if (!Utils::ApiCheck(can_grow, location, "Index too large")) {
   1240     return i::Handle<i::FixedArray>();
   1241   }
   1242   int new_size = index + 1;
   1243   int grow_by = new_size - data->length();
   1244   data = isolate->factory()->CopyFixedArrayAndGrow(data, grow_by);
   1245   env->set_embedder_data(*data);
   1246   return data;
   1247 }
   1248 
   1249 uint32_t Context::GetNumberOfEmbedderDataFields() {
   1250   i::Handle<i::Context> context = Utils::OpenHandle(this);
   1251   CHECK(context->IsNativeContext());
   1252   return static_cast<uint32_t>(context->embedder_data()->length());
   1253 }
   1254 
   1255 v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
   1256   const char* location = "v8::Context::GetEmbedderData()";
   1257   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
   1258   if (data.is_null()) return Local<Value>();
   1259   i::Handle<i::Object> result(
   1260       data->get(index),
   1261       reinterpret_cast<i::Isolate*>(Utils::OpenHandle(this)->GetIsolate()));
   1262   return Utils::ToLocal(result);
   1263 }
   1264 
   1265 
   1266 void Context::SetEmbedderData(int index, v8::Local<Value> value) {
   1267   const char* location = "v8::Context::SetEmbedderData()";
   1268   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
   1269   if (data.is_null()) return;
   1270   i::Handle<i::Object> val = Utils::OpenHandle(*value);
   1271   data->set(index, *val);
   1272   DCHECK_EQ(*Utils::OpenHandle(*value),
   1273             *Utils::OpenHandle(*GetEmbedderData(index)));
   1274 }
   1275 
   1276 
   1277 void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
   1278   const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
   1279   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
   1280   if (data.is_null()) return nullptr;
   1281   return DecodeSmiToAligned(data->get(index), location);
   1282 }
   1283 
   1284 
   1285 void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
   1286   const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
   1287   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
   1288   data->set(index, EncodeAlignedAsSmi(value, location));
   1289   DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
   1290 }
   1291 
   1292 
   1293 // --- T e m p l a t e ---
   1294 
   1295 
   1296 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
   1297   that->set_number_of_properties(0);
   1298   that->set_tag(i::Smi::FromInt(type));
   1299 }
   1300 
   1301 
   1302 void Template::Set(v8::Local<Name> name, v8::Local<Data> value,
   1303                    v8::PropertyAttribute attribute) {
   1304   auto templ = Utils::OpenHandle(this);
   1305   i::Isolate* isolate = templ->GetIsolate();
   1306   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1307   i::HandleScope scope(isolate);
   1308   auto value_obj = Utils::OpenHandle(*value);
   1309   CHECK(!value_obj->IsJSReceiver() || value_obj->IsTemplateInfo());
   1310   if (value_obj->IsObjectTemplateInfo()) {
   1311     templ->set_serial_number(i::Smi::kZero);
   1312     if (templ->IsFunctionTemplateInfo()) {
   1313       i::Handle<i::FunctionTemplateInfo>::cast(templ)->set_do_not_cache(true);
   1314     }
   1315   }
   1316   i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
   1317                                  value_obj,
   1318                                  static_cast<i::PropertyAttributes>(attribute));
   1319 }
   1320 
   1321 void Template::SetPrivate(v8::Local<Private> name, v8::Local<Data> value,
   1322                           v8::PropertyAttribute attribute) {
   1323   Set(Utils::ToLocal(Utils::OpenHandle(reinterpret_cast<Name*>(*name))), value,
   1324       attribute);
   1325 }
   1326 
   1327 void Template::SetAccessorProperty(
   1328     v8::Local<v8::Name> name,
   1329     v8::Local<FunctionTemplate> getter,
   1330     v8::Local<FunctionTemplate> setter,
   1331     v8::PropertyAttribute attribute,
   1332     v8::AccessControl access_control) {
   1333   // TODO(verwaest): Remove |access_control|.
   1334   DCHECK_EQ(v8::DEFAULT, access_control);
   1335   auto templ = Utils::OpenHandle(this);
   1336   auto isolate = templ->GetIsolate();
   1337   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1338   DCHECK(!name.IsEmpty());
   1339   DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
   1340   i::HandleScope scope(isolate);
   1341   i::ApiNatives::AddAccessorProperty(
   1342       isolate, templ, Utils::OpenHandle(*name),
   1343       Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true),
   1344       static_cast<i::PropertyAttributes>(attribute));
   1345 }
   1346 
   1347 
   1348 // --- F u n c t i o n   T e m p l a t e ---
   1349 static void InitializeFunctionTemplate(
   1350     i::Handle<i::FunctionTemplateInfo> info) {
   1351   InitializeTemplate(info, Consts::FUNCTION_TEMPLATE);
   1352   info->set_flag(0);
   1353 }
   1354 
   1355 static Local<ObjectTemplate> ObjectTemplateNew(
   1356     i::Isolate* isolate, v8::Local<FunctionTemplate> constructor,
   1357     bool do_not_cache);
   1358 
   1359 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
   1360   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
   1361   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   1362   i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(),
   1363                               i_isolate);
   1364   if (result->IsUndefined(i_isolate)) {
   1365     // Do not cache prototype objects.
   1366     result = Utils::OpenHandle(
   1367         *ObjectTemplateNew(i_isolate, Local<FunctionTemplate>(), true));
   1368     Utils::OpenHandle(this)->set_prototype_template(*result);
   1369   }
   1370   return ToApiHandle<ObjectTemplate>(result);
   1371 }
   1372 
   1373 void FunctionTemplate::SetPrototypeProviderTemplate(
   1374     Local<FunctionTemplate> prototype_provider) {
   1375   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
   1376   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   1377   i::Handle<i::Object> result = Utils::OpenHandle(*prototype_provider);
   1378   auto info = Utils::OpenHandle(this);
   1379   CHECK(info->prototype_template()->IsUndefined(i_isolate));
   1380   CHECK(info->parent_template()->IsUndefined(i_isolate));
   1381   info->set_prototype_provider_template(*result);
   1382 }
   1383 
   1384 static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info,
   1385                                   const char* func) {
   1386   Utils::ApiCheck(!info->instantiated(), func,
   1387                   "FunctionTemplate already instantiated");
   1388 }
   1389 
   1390 
   1391 void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) {
   1392   auto info = Utils::OpenHandle(this);
   1393   EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit");
   1394   i::Isolate* i_isolate = info->GetIsolate();
   1395   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   1396   CHECK(info->prototype_provider_template()->IsUndefined(i_isolate));
   1397   info->set_parent_template(*Utils::OpenHandle(*value));
   1398 }
   1399 
   1400 static Local<FunctionTemplate> FunctionTemplateNew(
   1401     i::Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
   1402     v8::Local<Signature> signature, int length, bool do_not_cache,
   1403     v8::Local<Private> cached_property_name = v8::Local<Private>(),
   1404     SideEffectType side_effect_type = SideEffectType::kHasSideEffect) {
   1405   i::Handle<i::Struct> struct_obj =
   1406       isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE, i::TENURED);
   1407   i::Handle<i::FunctionTemplateInfo> obj =
   1408       i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
   1409   InitializeFunctionTemplate(obj);
   1410   obj->set_do_not_cache(do_not_cache);
   1411   int next_serial_number = i::FunctionTemplateInfo::kInvalidSerialNumber;
   1412   if (!do_not_cache) {
   1413     next_serial_number = isolate->heap()->GetNextTemplateSerialNumber();
   1414   }
   1415   obj->set_serial_number(i::Smi::FromInt(next_serial_number));
   1416   if (callback != 0) {
   1417     Utils::ToLocal(obj)->SetCallHandler(callback, data, side_effect_type);
   1418   }
   1419   obj->set_length(length);
   1420   obj->set_undetectable(false);
   1421   obj->set_needs_access_check(false);
   1422   obj->set_accept_any_receiver(true);
   1423   if (!signature.IsEmpty()) {
   1424     obj->set_signature(*Utils::OpenHandle(*signature));
   1425   }
   1426   obj->set_cached_property_name(
   1427       cached_property_name.IsEmpty()
   1428           ? i::ReadOnlyRoots(isolate).the_hole_value()
   1429           : *Utils::OpenHandle(*cached_property_name));
   1430   return Utils::ToLocal(obj);
   1431 }
   1432 
   1433 Local<FunctionTemplate> FunctionTemplate::New(
   1434     Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
   1435     v8::Local<Signature> signature, int length, ConstructorBehavior behavior,
   1436     SideEffectType side_effect_type) {
   1437   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   1438   // Changes to the environment cannot be captured in the snapshot. Expect no
   1439   // function templates when the isolate is created for serialization.
   1440   LOG_API(i_isolate, FunctionTemplate, New);
   1441   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   1442   auto templ = FunctionTemplateNew(i_isolate, callback, data, signature, length,
   1443                                    false, Local<Private>(), side_effect_type);
   1444   if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype();
   1445   return templ;
   1446 }
   1447 
   1448 MaybeLocal<FunctionTemplate> FunctionTemplate::FromSnapshot(Isolate* isolate,
   1449                                                             size_t index) {
   1450   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   1451   i::FixedArray* serialized_objects = i_isolate->heap()->serialized_objects();
   1452   int int_index = static_cast<int>(index);
   1453   if (int_index < serialized_objects->length()) {
   1454     i::Object* info = serialized_objects->get(int_index);
   1455     if (info->IsFunctionTemplateInfo()) {
   1456       return Utils::ToLocal(i::Handle<i::FunctionTemplateInfo>(
   1457           i::FunctionTemplateInfo::cast(info), i_isolate));
   1458     }
   1459   }
   1460   return Local<FunctionTemplate>();
   1461 }
   1462 
   1463 Local<FunctionTemplate> FunctionTemplate::NewWithCache(
   1464     Isolate* isolate, FunctionCallback callback, Local<Private> cache_property,
   1465     Local<Value> data, Local<Signature> signature, int length,
   1466     SideEffectType side_effect_type) {
   1467   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   1468   LOG_API(i_isolate, FunctionTemplate, NewWithCache);
   1469   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   1470   return FunctionTemplateNew(i_isolate, callback, data, signature, length,
   1471                              false, cache_property, side_effect_type);
   1472 }
   1473 
   1474 Local<Signature> Signature::New(Isolate* isolate,
   1475                                 Local<FunctionTemplate> receiver) {
   1476   return Utils::SignatureToLocal(Utils::OpenHandle(*receiver));
   1477 }
   1478 
   1479 
   1480 Local<AccessorSignature> AccessorSignature::New(
   1481     Isolate* isolate, Local<FunctionTemplate> receiver) {
   1482   return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
   1483 }
   1484 
   1485 #define SET_FIELD_WRAPPED(isolate, obj, setter, cdata)        \
   1486   do {                                                        \
   1487     i::Handle<i::Object> foreign = FromCData(isolate, cdata); \
   1488     (obj)->setter(*foreign);                                  \
   1489   } while (false)
   1490 
   1491 void FunctionTemplate::SetCallHandler(FunctionCallback callback,
   1492                                       v8::Local<Value> data,
   1493                                       SideEffectType side_effect_type) {
   1494   auto info = Utils::OpenHandle(this);
   1495   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler");
   1496   i::Isolate* isolate = info->GetIsolate();
   1497   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1498   i::HandleScope scope(isolate);
   1499   i::Handle<i::CallHandlerInfo> obj = isolate->factory()->NewCallHandlerInfo(
   1500       side_effect_type == SideEffectType::kHasNoSideEffect);
   1501   SET_FIELD_WRAPPED(isolate, obj, set_callback, callback);
   1502   SET_FIELD_WRAPPED(isolate, obj, set_js_callback, obj->redirected_callback());
   1503   if (data.IsEmpty()) {
   1504     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   1505   }
   1506   obj->set_data(*Utils::OpenHandle(*data));
   1507   info->set_call_code(*obj);
   1508 }
   1509 
   1510 
   1511 namespace {
   1512 
   1513 template <typename Getter, typename Setter>
   1514 i::Handle<i::AccessorInfo> MakeAccessorInfo(
   1515     i::Isolate* isolate, v8::Local<Name> name, Getter getter, Setter setter,
   1516     v8::Local<Value> data, v8::AccessControl settings,
   1517     v8::Local<AccessorSignature> signature, bool is_special_data_property,
   1518     bool replace_on_access) {
   1519   i::Handle<i::AccessorInfo> obj = isolate->factory()->NewAccessorInfo();
   1520   SET_FIELD_WRAPPED(isolate, obj, set_getter, getter);
   1521   DCHECK_IMPLIES(replace_on_access,
   1522                  is_special_data_property && setter == nullptr);
   1523   if (is_special_data_property && setter == nullptr) {
   1524     setter = reinterpret_cast<Setter>(&i::Accessors::ReconfigureToDataProperty);
   1525   }
   1526   SET_FIELD_WRAPPED(isolate, obj, set_setter, setter);
   1527   i::Address redirected = obj->redirected_getter();
   1528   if (redirected != i::kNullAddress) {
   1529     SET_FIELD_WRAPPED(isolate, obj, set_js_getter, redirected);
   1530   }
   1531   if (data.IsEmpty()) {
   1532     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   1533   }
   1534   obj->set_data(*Utils::OpenHandle(*data));
   1535   obj->set_is_special_data_property(is_special_data_property);
   1536   obj->set_replace_on_access(replace_on_access);
   1537   i::Handle<i::Name> accessor_name = Utils::OpenHandle(*name);
   1538   if (!accessor_name->IsUniqueName()) {
   1539     accessor_name = isolate->factory()->InternalizeString(
   1540         i::Handle<i::String>::cast(accessor_name));
   1541   }
   1542   obj->set_name(*accessor_name);
   1543   if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
   1544   if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
   1545   obj->set_initial_property_attributes(i::NONE);
   1546   if (!signature.IsEmpty()) {
   1547     obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
   1548   }
   1549   return obj;
   1550 }
   1551 
   1552 }  // namespace
   1553 
   1554 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
   1555   i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
   1556   if (!Utils::ApiCheck(!handle.is_null(),
   1557                        "v8::FunctionTemplate::InstanceTemplate()",
   1558                        "Reading from empty handle")) {
   1559     return Local<ObjectTemplate>();
   1560   }
   1561   i::Isolate* isolate = handle->GetIsolate();
   1562   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1563   if (handle->instance_template()->IsUndefined(isolate)) {
   1564     Local<ObjectTemplate> templ =
   1565         ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
   1566     handle->set_instance_template(*Utils::OpenHandle(*templ));
   1567   }
   1568   i::Handle<i::ObjectTemplateInfo> result(
   1569       i::ObjectTemplateInfo::cast(handle->instance_template()), isolate);
   1570   return Utils::ToLocal(result);
   1571 }
   1572 
   1573 
   1574 void FunctionTemplate::SetLength(int length) {
   1575   auto info = Utils::OpenHandle(this);
   1576   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength");
   1577   auto isolate = info->GetIsolate();
   1578   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1579   info->set_length(length);
   1580 }
   1581 
   1582 
   1583 void FunctionTemplate::SetClassName(Local<String> name) {
   1584   auto info = Utils::OpenHandle(this);
   1585   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName");
   1586   auto isolate = info->GetIsolate();
   1587   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1588   info->set_class_name(*Utils::OpenHandle(*name));
   1589 }
   1590 
   1591 
   1592 void FunctionTemplate::SetAcceptAnyReceiver(bool value) {
   1593   auto info = Utils::OpenHandle(this);
   1594   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
   1595   auto isolate = info->GetIsolate();
   1596   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1597   info->set_accept_any_receiver(value);
   1598 }
   1599 
   1600 
   1601 void FunctionTemplate::SetHiddenPrototype(bool value) {
   1602   auto info = Utils::OpenHandle(this);
   1603   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype");
   1604   auto isolate = info->GetIsolate();
   1605   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1606   info->set_hidden_prototype(value);
   1607 }
   1608 
   1609 
   1610 void FunctionTemplate::ReadOnlyPrototype() {
   1611   auto info = Utils::OpenHandle(this);
   1612   EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype");
   1613   auto isolate = info->GetIsolate();
   1614   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1615   info->set_read_only_prototype(true);
   1616 }
   1617 
   1618 
   1619 void FunctionTemplate::RemovePrototype() {
   1620   auto info = Utils::OpenHandle(this);
   1621   EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype");
   1622   auto isolate = info->GetIsolate();
   1623   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1624   info->set_remove_prototype(true);
   1625 }
   1626 
   1627 
   1628 // --- O b j e c t T e m p l a t e ---
   1629 
   1630 
   1631 Local<ObjectTemplate> ObjectTemplate::New(
   1632     Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
   1633   return New(reinterpret_cast<i::Isolate*>(isolate), constructor);
   1634 }
   1635 
   1636 
   1637 static Local<ObjectTemplate> ObjectTemplateNew(
   1638     i::Isolate* isolate, v8::Local<FunctionTemplate> constructor,
   1639     bool do_not_cache) {
   1640   LOG_API(isolate, ObjectTemplate, New);
   1641   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1642   i::Handle<i::Struct> struct_obj =
   1643       isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE, i::TENURED);
   1644   i::Handle<i::ObjectTemplateInfo> obj =
   1645       i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
   1646   InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
   1647   int next_serial_number = 0;
   1648   if (!do_not_cache) {
   1649     next_serial_number = isolate->heap()->GetNextTemplateSerialNumber();
   1650   }
   1651   obj->set_serial_number(i::Smi::FromInt(next_serial_number));
   1652   if (!constructor.IsEmpty())
   1653     obj->set_constructor(*Utils::OpenHandle(*constructor));
   1654   obj->set_data(i::Smi::kZero);
   1655   return Utils::ToLocal(obj);
   1656 }
   1657 
   1658 Local<ObjectTemplate> ObjectTemplate::New(
   1659     i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
   1660   return ObjectTemplateNew(isolate, constructor, false);
   1661 }
   1662 
   1663 MaybeLocal<ObjectTemplate> ObjectTemplate::FromSnapshot(Isolate* isolate,
   1664                                                         size_t index) {
   1665   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   1666   i::FixedArray* serialized_objects = i_isolate->heap()->serialized_objects();
   1667   int int_index = static_cast<int>(index);
   1668   if (int_index < serialized_objects->length()) {
   1669     i::Object* info = serialized_objects->get(int_index);
   1670     if (info->IsObjectTemplateInfo()) {
   1671       return Utils::ToLocal(i::Handle<i::ObjectTemplateInfo>(
   1672           i::ObjectTemplateInfo::cast(info), i_isolate));
   1673     }
   1674   }
   1675   return Local<ObjectTemplate>();
   1676 }
   1677 
   1678 // Ensure that the object template has a constructor.  If no
   1679 // constructor is available we create one.
   1680 static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
   1681     i::Isolate* isolate,
   1682     ObjectTemplate* object_template) {
   1683   i::Object* obj = Utils::OpenHandle(object_template)->constructor();
   1684   if (!obj->IsUndefined(isolate)) {
   1685     i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj);
   1686     return i::Handle<i::FunctionTemplateInfo>(info, isolate);
   1687   }
   1688   Local<FunctionTemplate> templ =
   1689       FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
   1690   i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
   1691   constructor->set_instance_template(*Utils::OpenHandle(object_template));
   1692   Utils::OpenHandle(object_template)->set_constructor(*constructor);
   1693   return constructor;
   1694 }
   1695 
   1696 template <typename Getter, typename Setter, typename Data, typename Template>
   1697 static void TemplateSetAccessor(
   1698     Template* template_obj, v8::Local<Name> name, Getter getter, Setter setter,
   1699     Data data, AccessControl settings, PropertyAttribute attribute,
   1700     v8::Local<AccessorSignature> signature, bool is_special_data_property,
   1701     bool replace_on_access, SideEffectType getter_side_effect_type) {
   1702   auto info = Utils::OpenHandle(template_obj);
   1703   auto isolate = info->GetIsolate();
   1704   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1705   i::HandleScope scope(isolate);
   1706   i::Handle<i::AccessorInfo> accessor_info =
   1707       MakeAccessorInfo(isolate, name, getter, setter, data, settings, signature,
   1708                        is_special_data_property, replace_on_access);
   1709   accessor_info->set_initial_property_attributes(
   1710       static_cast<i::PropertyAttributes>(attribute));
   1711   accessor_info->set_has_no_side_effect(getter_side_effect_type ==
   1712                                         SideEffectType::kHasNoSideEffect);
   1713   i::ApiNatives::AddNativeDataProperty(isolate, info, accessor_info);
   1714 }
   1715 
   1716 void Template::SetNativeDataProperty(
   1717     v8::Local<String> name, AccessorGetterCallback getter,
   1718     AccessorSetterCallback setter, v8::Local<Value> data,
   1719     PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
   1720     AccessControl settings, SideEffectType getter_side_effect_type) {
   1721   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
   1722                       signature, true, false, getter_side_effect_type);
   1723 }
   1724 
   1725 void Template::SetNativeDataProperty(
   1726     v8::Local<Name> name, AccessorNameGetterCallback getter,
   1727     AccessorNameSetterCallback setter, v8::Local<Value> data,
   1728     PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
   1729     AccessControl settings, SideEffectType getter_side_effect_type) {
   1730   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
   1731                       signature, true, false, getter_side_effect_type);
   1732 }
   1733 
   1734 void Template::SetLazyDataProperty(v8::Local<Name> name,
   1735                                    AccessorNameGetterCallback getter,
   1736                                    v8::Local<Value> data,
   1737                                    PropertyAttribute attribute,
   1738                                    SideEffectType getter_side_effect_type) {
   1739   TemplateSetAccessor(this, name, getter,
   1740                       static_cast<AccessorNameSetterCallback>(nullptr), data,
   1741                       DEFAULT, attribute, Local<AccessorSignature>(), true,
   1742                       true, getter_side_effect_type);
   1743 }
   1744 
   1745 void Template::SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
   1746                                         PropertyAttribute attribute) {
   1747   auto templ = Utils::OpenHandle(this);
   1748   i::Isolate* isolate = templ->GetIsolate();
   1749   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1750   i::HandleScope scope(isolate);
   1751   i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
   1752                                  intrinsic,
   1753                                  static_cast<i::PropertyAttributes>(attribute));
   1754 }
   1755 
   1756 void ObjectTemplate::SetAccessor(v8::Local<String> name,
   1757                                  AccessorGetterCallback getter,
   1758                                  AccessorSetterCallback setter,
   1759                                  v8::Local<Value> data, AccessControl settings,
   1760                                  PropertyAttribute attribute,
   1761                                  v8::Local<AccessorSignature> signature,
   1762                                  SideEffectType getter_side_effect_type) {
   1763   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
   1764                       signature, i::FLAG_disable_old_api_accessors, false,
   1765                       getter_side_effect_type);
   1766 }
   1767 
   1768 void ObjectTemplate::SetAccessor(v8::Local<Name> name,
   1769                                  AccessorNameGetterCallback getter,
   1770                                  AccessorNameSetterCallback setter,
   1771                                  v8::Local<Value> data, AccessControl settings,
   1772                                  PropertyAttribute attribute,
   1773                                  v8::Local<AccessorSignature> signature,
   1774                                  SideEffectType getter_side_effect_type) {
   1775   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
   1776                       signature, i::FLAG_disable_old_api_accessors, false,
   1777                       getter_side_effect_type);
   1778 }
   1779 
   1780 template <typename Getter, typename Setter, typename Query, typename Descriptor,
   1781           typename Deleter, typename Enumerator, typename Definer>
   1782 static i::Handle<i::InterceptorInfo> CreateInterceptorInfo(
   1783     i::Isolate* isolate, Getter getter, Setter setter, Query query,
   1784     Descriptor descriptor, Deleter remover, Enumerator enumerator,
   1785     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
   1786   auto obj = i::Handle<i::InterceptorInfo>::cast(
   1787       isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE, i::TENURED));
   1788   obj->set_flags(0);
   1789 
   1790   if (getter != 0) SET_FIELD_WRAPPED(isolate, obj, set_getter, getter);
   1791   if (setter != 0) SET_FIELD_WRAPPED(isolate, obj, set_setter, setter);
   1792   if (query != 0) SET_FIELD_WRAPPED(isolate, obj, set_query, query);
   1793   if (descriptor != 0)
   1794     SET_FIELD_WRAPPED(isolate, obj, set_descriptor, descriptor);
   1795   if (remover != 0) SET_FIELD_WRAPPED(isolate, obj, set_deleter, remover);
   1796   if (enumerator != 0)
   1797     SET_FIELD_WRAPPED(isolate, obj, set_enumerator, enumerator);
   1798   if (definer != 0) SET_FIELD_WRAPPED(isolate, obj, set_definer, definer);
   1799   obj->set_can_intercept_symbols(
   1800       !(static_cast<int>(flags) &
   1801         static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings)));
   1802   obj->set_all_can_read(static_cast<int>(flags) &
   1803                         static_cast<int>(PropertyHandlerFlags::kAllCanRead));
   1804   obj->set_non_masking(static_cast<int>(flags) &
   1805                        static_cast<int>(PropertyHandlerFlags::kNonMasking));
   1806   obj->set_has_no_side_effect(
   1807       static_cast<int>(flags) &
   1808       static_cast<int>(PropertyHandlerFlags::kHasNoSideEffect));
   1809 
   1810   if (data.IsEmpty()) {
   1811     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   1812   }
   1813   obj->set_data(*Utils::OpenHandle(*data));
   1814   return obj;
   1815 }
   1816 
   1817 template <typename Getter, typename Setter, typename Query, typename Descriptor,
   1818           typename Deleter, typename Enumerator, typename Definer>
   1819 static i::Handle<i::InterceptorInfo> CreateNamedInterceptorInfo(
   1820     i::Isolate* isolate, Getter getter, Setter setter, Query query,
   1821     Descriptor descriptor, Deleter remover, Enumerator enumerator,
   1822     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
   1823   auto interceptor =
   1824       CreateInterceptorInfo(isolate, getter, setter, query, descriptor, remover,
   1825                             enumerator, definer, data, flags);
   1826   interceptor->set_is_named(true);
   1827   return interceptor;
   1828 }
   1829 
   1830 template <typename Getter, typename Setter, typename Query, typename Descriptor,
   1831           typename Deleter, typename Enumerator, typename Definer>
   1832 static i::Handle<i::InterceptorInfo> CreateIndexedInterceptorInfo(
   1833     i::Isolate* isolate, Getter getter, Setter setter, Query query,
   1834     Descriptor descriptor, Deleter remover, Enumerator enumerator,
   1835     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
   1836   auto interceptor =
   1837       CreateInterceptorInfo(isolate, getter, setter, query, descriptor, remover,
   1838                             enumerator, definer, data, flags);
   1839   interceptor->set_is_named(false);
   1840   return interceptor;
   1841 }
   1842 
   1843 template <typename Getter, typename Setter, typename Query, typename Descriptor,
   1844           typename Deleter, typename Enumerator, typename Definer>
   1845 static void ObjectTemplateSetNamedPropertyHandler(
   1846     ObjectTemplate* templ, Getter getter, Setter setter, Query query,
   1847     Descriptor descriptor, Deleter remover, Enumerator enumerator,
   1848     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
   1849   i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate();
   1850   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1851   i::HandleScope scope(isolate);
   1852   auto cons = EnsureConstructor(isolate, templ);
   1853   EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler");
   1854   auto obj =
   1855       CreateNamedInterceptorInfo(isolate, getter, setter, query, descriptor,
   1856                                  remover, enumerator, definer, data, flags);
   1857   cons->set_named_property_handler(*obj);
   1858 }
   1859 
   1860 void ObjectTemplate::SetHandler(
   1861     const NamedPropertyHandlerConfiguration& config) {
   1862   ObjectTemplateSetNamedPropertyHandler(
   1863       this, config.getter, config.setter, config.query, config.descriptor,
   1864       config.deleter, config.enumerator, config.definer, config.data,
   1865       config.flags);
   1866 }
   1867 
   1868 
   1869 void ObjectTemplate::MarkAsUndetectable() {
   1870   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   1871   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1872   i::HandleScope scope(isolate);
   1873   auto cons = EnsureConstructor(isolate, this);
   1874   EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable");
   1875   cons->set_undetectable(true);
   1876 }
   1877 
   1878 
   1879 void ObjectTemplate::SetAccessCheckCallback(AccessCheckCallback callback,
   1880                                             Local<Value> data) {
   1881   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   1882   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1883   i::HandleScope scope(isolate);
   1884   auto cons = EnsureConstructor(isolate, this);
   1885   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallback");
   1886 
   1887   i::Handle<i::Struct> struct_info =
   1888       isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE, i::TENURED);
   1889   i::Handle<i::AccessCheckInfo> info =
   1890       i::Handle<i::AccessCheckInfo>::cast(struct_info);
   1891 
   1892   SET_FIELD_WRAPPED(isolate, info, set_callback, callback);
   1893   info->set_named_interceptor(nullptr);
   1894   info->set_indexed_interceptor(nullptr);
   1895 
   1896   if (data.IsEmpty()) {
   1897     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   1898   }
   1899   info->set_data(*Utils::OpenHandle(*data));
   1900 
   1901   cons->set_access_check_info(*info);
   1902   cons->set_needs_access_check(true);
   1903 }
   1904 
   1905 void ObjectTemplate::SetAccessCheckCallbackAndHandler(
   1906     AccessCheckCallback callback,
   1907     const NamedPropertyHandlerConfiguration& named_handler,
   1908     const IndexedPropertyHandlerConfiguration& indexed_handler,
   1909     Local<Value> data) {
   1910   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   1911   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1912   i::HandleScope scope(isolate);
   1913   auto cons = EnsureConstructor(isolate, this);
   1914   EnsureNotInstantiated(
   1915       cons, "v8::ObjectTemplate::SetAccessCheckCallbackWithHandler");
   1916 
   1917   i::Handle<i::Struct> struct_info =
   1918       isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE, i::TENURED);
   1919   i::Handle<i::AccessCheckInfo> info =
   1920       i::Handle<i::AccessCheckInfo>::cast(struct_info);
   1921 
   1922   SET_FIELD_WRAPPED(isolate, info, set_callback, callback);
   1923   auto named_interceptor = CreateNamedInterceptorInfo(
   1924       isolate, named_handler.getter, named_handler.setter, named_handler.query,
   1925       named_handler.descriptor, named_handler.deleter, named_handler.enumerator,
   1926       named_handler.definer, named_handler.data, named_handler.flags);
   1927   info->set_named_interceptor(*named_interceptor);
   1928   auto indexed_interceptor = CreateIndexedInterceptorInfo(
   1929       isolate, indexed_handler.getter, indexed_handler.setter,
   1930       indexed_handler.query, indexed_handler.descriptor,
   1931       indexed_handler.deleter, indexed_handler.enumerator,
   1932       indexed_handler.definer, indexed_handler.data, indexed_handler.flags);
   1933   info->set_indexed_interceptor(*indexed_interceptor);
   1934 
   1935   if (data.IsEmpty()) {
   1936     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   1937   }
   1938   info->set_data(*Utils::OpenHandle(*data));
   1939 
   1940   cons->set_access_check_info(*info);
   1941   cons->set_needs_access_check(true);
   1942 }
   1943 
   1944 void ObjectTemplate::SetHandler(
   1945     const IndexedPropertyHandlerConfiguration& config) {
   1946   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   1947   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1948   i::HandleScope scope(isolate);
   1949   auto cons = EnsureConstructor(isolate, this);
   1950   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler");
   1951   auto obj = CreateIndexedInterceptorInfo(
   1952       isolate, config.getter, config.setter, config.query, config.descriptor,
   1953       config.deleter, config.enumerator, config.definer, config.data,
   1954       config.flags);
   1955   cons->set_indexed_property_handler(*obj);
   1956 }
   1957 
   1958 void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
   1959                                               Local<Value> data) {
   1960   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   1961   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1962   i::HandleScope scope(isolate);
   1963   auto cons = EnsureConstructor(isolate, this);
   1964   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
   1965   i::Handle<i::CallHandlerInfo> obj = isolate->factory()->NewCallHandlerInfo();
   1966   SET_FIELD_WRAPPED(isolate, obj, set_callback, callback);
   1967   SET_FIELD_WRAPPED(isolate, obj, set_js_callback, obj->redirected_callback());
   1968   if (data.IsEmpty()) {
   1969     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   1970   }
   1971   obj->set_data(*Utils::OpenHandle(*data));
   1972   cons->set_instance_call_handler(*obj);
   1973 }
   1974 
   1975 int ObjectTemplate::InternalFieldCount() {
   1976   return Utils::OpenHandle(this)->embedder_field_count();
   1977 }
   1978 
   1979 void ObjectTemplate::SetInternalFieldCount(int value) {
   1980   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   1981   if (!Utils::ApiCheck(i::Smi::IsValid(value),
   1982                        "v8::ObjectTemplate::SetInternalFieldCount()",
   1983                        "Invalid embedder field count")) {
   1984     return;
   1985   }
   1986   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   1987   if (value > 0) {
   1988     // The embedder field count is set by the constructor function's
   1989     // construct code, so we ensure that there is a constructor
   1990     // function to do the setting.
   1991     EnsureConstructor(isolate, this);
   1992   }
   1993   Utils::OpenHandle(this)->set_embedder_field_count(value);
   1994 }
   1995 
   1996 bool ObjectTemplate::IsImmutableProto() {
   1997   return Utils::OpenHandle(this)->immutable_proto();
   1998 }
   1999 
   2000 void ObjectTemplate::SetImmutableProto() {
   2001   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2002   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2003   Utils::OpenHandle(this)->set_immutable_proto(true);
   2004 }
   2005 
   2006 // --- S c r i p t s ---
   2007 
   2008 
   2009 // Internally, UnboundScript is a SharedFunctionInfo, and Script is a
   2010 // JSFunction.
   2011 
   2012 ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
   2013                                        BufferPolicy buffer_policy_)
   2014     : data(data_),
   2015       length(length_),
   2016       rejected(false),
   2017       buffer_policy(buffer_policy_) {}
   2018 
   2019 
   2020 ScriptCompiler::CachedData::~CachedData() {
   2021   if (buffer_policy == BufferOwned) {
   2022     delete[] data;
   2023   }
   2024 }
   2025 
   2026 
   2027 bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; }
   2028 
   2029 
   2030 void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); }
   2031 
   2032 ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
   2033                                                Encoding encoding)
   2034     : impl_(new i::ScriptStreamingData(stream, encoding)) {}
   2035 
   2036 ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; }
   2037 
   2038 
   2039 const ScriptCompiler::CachedData*
   2040 ScriptCompiler::StreamedSource::GetCachedData() const {
   2041   return impl_->cached_data.get();
   2042 }
   2043 
   2044 
   2045 Local<Script> UnboundScript::BindToCurrentContext() {
   2046   auto function_info =
   2047       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
   2048   i::Isolate* isolate = function_info->GetIsolate();
   2049   i::Handle<i::JSFunction> function =
   2050       isolate->factory()->NewFunctionFromSharedFunctionInfo(
   2051           function_info, isolate->native_context());
   2052   return ToApiHandle<Script>(function);
   2053 }
   2054 
   2055 
   2056 int UnboundScript::GetId() {
   2057   auto function_info =
   2058       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
   2059   i::Isolate* isolate = function_info->GetIsolate();
   2060   LOG_API(isolate, UnboundScript, GetId);
   2061   i::HandleScope scope(isolate);
   2062   i::Handle<i::Script> script(i::Script::cast(function_info->script()),
   2063                               isolate);
   2064   return script->id();
   2065 }
   2066 
   2067 
   2068 int UnboundScript::GetLineNumber(int code_pos) {
   2069   i::Handle<i::SharedFunctionInfo> obj =
   2070       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
   2071   i::Isolate* isolate = obj->GetIsolate();
   2072   LOG_API(isolate, UnboundScript, GetLineNumber);
   2073   if (obj->script()->IsScript()) {
   2074     i::Handle<i::Script> script(i::Script::cast(obj->script()), isolate);
   2075     return i::Script::GetLineNumber(script, code_pos);
   2076   } else {
   2077     return -1;
   2078   }
   2079 }
   2080 
   2081 
   2082 Local<Value> UnboundScript::GetScriptName() {
   2083   i::Handle<i::SharedFunctionInfo> obj =
   2084       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
   2085   i::Isolate* isolate = obj->GetIsolate();
   2086   LOG_API(isolate, UnboundScript, GetName);
   2087   if (obj->script()->IsScript()) {
   2088     i::Object* name = i::Script::cast(obj->script())->name();
   2089     return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
   2090   } else {
   2091     return Local<String>();
   2092   }
   2093 }
   2094 
   2095 
   2096 Local<Value> UnboundScript::GetSourceURL() {
   2097   i::Handle<i::SharedFunctionInfo> obj =
   2098       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
   2099   i::Isolate* isolate = obj->GetIsolate();
   2100   LOG_API(isolate, UnboundScript, GetSourceURL);
   2101   if (obj->script()->IsScript()) {
   2102     i::Object* url = i::Script::cast(obj->script())->source_url();
   2103     return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
   2104   } else {
   2105     return Local<String>();
   2106   }
   2107 }
   2108 
   2109 
   2110 Local<Value> UnboundScript::GetSourceMappingURL() {
   2111   i::Handle<i::SharedFunctionInfo> obj =
   2112       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
   2113   i::Isolate* isolate = obj->GetIsolate();
   2114   LOG_API(isolate, UnboundScript, GetSourceMappingURL);
   2115   if (obj->script()->IsScript()) {
   2116     i::Object* url = i::Script::cast(obj->script())->source_mapping_url();
   2117     return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
   2118   } else {
   2119     return Local<String>();
   2120   }
   2121 }
   2122 
   2123 
   2124 MaybeLocal<Value> Script::Run(Local<Context> context) {
   2125   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   2126   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
   2127   ENTER_V8(isolate, context, Script, Run, MaybeLocal<Value>(),
   2128            InternalEscapableScope);
   2129   i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true);
   2130   i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
   2131   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
   2132   auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this));
   2133 
   2134   i::Handle<i::Object> receiver = isolate->global_proxy();
   2135   Local<Value> result;
   2136   has_pending_exception = !ToLocal<Value>(
   2137       i::Execution::Call(isolate, fun, receiver, 0, nullptr), &result);
   2138 
   2139   RETURN_ON_FAILED_EXECUTION(Value);
   2140   RETURN_ESCAPED(result);
   2141 }
   2142 
   2143 
   2144 Local<Value> ScriptOrModule::GetResourceName() {
   2145   i::Handle<i::Script> obj = Utils::OpenHandle(this);
   2146   i::Isolate* isolate = obj->GetIsolate();
   2147   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2148   i::Handle<i::Object> val(obj->name(), isolate);
   2149   return ToApiHandle<Value>(val);
   2150 }
   2151 
   2152 Local<PrimitiveArray> ScriptOrModule::GetHostDefinedOptions() {
   2153   i::Handle<i::Script> obj = Utils::OpenHandle(this);
   2154   i::Isolate* isolate = obj->GetIsolate();
   2155   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2156   i::Handle<i::FixedArray> val(obj->host_defined_options(), isolate);
   2157   return ToApiHandle<PrimitiveArray>(val);
   2158 }
   2159 
   2160 Local<UnboundScript> Script::GetUnboundScript() {
   2161   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   2162   i::SharedFunctionInfo* sfi = i::JSFunction::cast(*obj)->shared();
   2163   i::Isolate* isolate = sfi->GetIsolate();
   2164   return ToApiHandle<UnboundScript>(i::handle(sfi, isolate));
   2165 }
   2166 
   2167 // static
   2168 Local<PrimitiveArray> PrimitiveArray::New(Isolate* v8_isolate, int length) {
   2169   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   2170   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2171   Utils::ApiCheck(length >= 0, "v8::PrimitiveArray::New",
   2172                   "length must be equal or greater than zero");
   2173   i::Handle<i::FixedArray> array = isolate->factory()->NewFixedArray(length);
   2174   return ToApiHandle<PrimitiveArray>(array);
   2175 }
   2176 
   2177 int PrimitiveArray::Length() const {
   2178   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
   2179   return array->length();
   2180 }
   2181 
   2182 void PrimitiveArray::Set(Isolate* v8_isolate, int index,
   2183                          Local<Primitive> item) {
   2184   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   2185   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
   2186   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2187   Utils::ApiCheck(index >= 0 && index < array->length(),
   2188                   "v8::PrimitiveArray::Set",
   2189                   "index must be greater than or equal to 0 and less than the "
   2190                   "array length");
   2191   i::Handle<i::Object> i_item = Utils::OpenHandle(*item);
   2192   array->set(index, *i_item);
   2193 }
   2194 
   2195 void PrimitiveArray::Set(int index, Local<Primitive> item) {
   2196   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
   2197   i::Isolate* isolate = UnsafeIsolateFromHeapObject(array);
   2198   Set(reinterpret_cast<Isolate*>(isolate), index, item);
   2199 }
   2200 
   2201 Local<Primitive> PrimitiveArray::Get(Isolate* v8_isolate, int index) {
   2202   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   2203   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
   2204   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2205   Utils::ApiCheck(index >= 0 && index < array->length(),
   2206                   "v8::PrimitiveArray::Get",
   2207                   "index must be greater than or equal to 0 and less than the "
   2208                   "array length");
   2209   i::Handle<i::Object> i_item(array->get(index), isolate);
   2210   return ToApiHandle<Primitive>(i_item);
   2211 }
   2212 
   2213 Local<Primitive> PrimitiveArray::Get(int index) {
   2214   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
   2215   i::Isolate* isolate = UnsafeIsolateFromHeapObject(array);
   2216   return Get(reinterpret_cast<Isolate*>(isolate), index);
   2217 }
   2218 
   2219 Module::Status Module::GetStatus() const {
   2220   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2221   switch (self->status()) {
   2222     case i::Module::kUninstantiated:
   2223     case i::Module::kPreInstantiating:
   2224       return kUninstantiated;
   2225     case i::Module::kInstantiating:
   2226       return kInstantiating;
   2227     case i::Module::kInstantiated:
   2228       return kInstantiated;
   2229     case i::Module::kEvaluating:
   2230       return kEvaluating;
   2231     case i::Module::kEvaluated:
   2232       return kEvaluated;
   2233     case i::Module::kErrored:
   2234       return kErrored;
   2235   }
   2236   UNREACHABLE();
   2237 }
   2238 
   2239 Local<Value> Module::GetException() const {
   2240   Utils::ApiCheck(GetStatus() == kErrored, "v8::Module::GetException",
   2241                   "Module status must be kErrored");
   2242   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2243   i::Isolate* isolate = self->GetIsolate();
   2244   return ToApiHandle<Value>(i::handle(self->GetException(), isolate));
   2245 }
   2246 
   2247 int Module::GetModuleRequestsLength() const {
   2248   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2249   return self->info()->module_requests()->length();
   2250 }
   2251 
   2252 Local<String> Module::GetModuleRequest(int i) const {
   2253   CHECK_GE(i, 0);
   2254   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2255   i::Isolate* isolate = self->GetIsolate();
   2256   i::Handle<i::FixedArray> module_requests(self->info()->module_requests(),
   2257                                            isolate);
   2258   CHECK_LT(i, module_requests->length());
   2259   return ToApiHandle<String>(i::handle(module_requests->get(i), isolate));
   2260 }
   2261 
   2262 Location Module::GetModuleRequestLocation(int i) const {
   2263   CHECK_GE(i, 0);
   2264   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2265   i::HandleScope scope(isolate);
   2266   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2267   i::Handle<i::FixedArray> module_request_positions(
   2268       self->info()->module_request_positions(), isolate);
   2269   CHECK_LT(i, module_request_positions->length());
   2270   int position = i::Smi::ToInt(module_request_positions->get(i));
   2271   i::Handle<i::Script> script(self->script(), isolate);
   2272   i::Script::PositionInfo info;
   2273   i::Script::GetPositionInfo(script, position, &info, i::Script::WITH_OFFSET);
   2274   return v8::Location(info.line, info.column);
   2275 }
   2276 
   2277 Local<Value> Module::GetModuleNamespace() {
   2278   Utils::ApiCheck(
   2279       GetStatus() >= kInstantiated, "v8::Module::GetModuleNamespace",
   2280       "v8::Module::GetModuleNamespace must be used on an instantiated module");
   2281   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2282   i::Handle<i::JSModuleNamespace> module_namespace =
   2283       i::Module::GetModuleNamespace(self->GetIsolate(), self);
   2284   return ToApiHandle<Value>(module_namespace);
   2285 }
   2286 
   2287 Local<UnboundModuleScript> Module::GetUnboundModuleScript() {
   2288   Utils::ApiCheck(
   2289       GetStatus() < kEvaluating, "v8::Module::GetUnboundScript",
   2290       "v8::Module::GetUnboundScript must be used on an unevaluated module");
   2291   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2292   return ToApiHandle<UnboundModuleScript>(i::Handle<i::SharedFunctionInfo>(
   2293       self->GetSharedFunctionInfo(), self->GetIsolate()));
   2294 }
   2295 
   2296 int Module::GetIdentityHash() const { return Utils::OpenHandle(this)->hash(); }
   2297 
   2298 Maybe<bool> Module::InstantiateModule(Local<Context> context,
   2299                                       Module::ResolveCallback callback) {
   2300   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   2301   ENTER_V8(isolate, context, Module, InstantiateModule, Nothing<bool>(),
   2302            i::HandleScope);
   2303   has_pending_exception = !i::Module::Instantiate(
   2304       isolate, Utils::OpenHandle(this), context, callback);
   2305   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   2306   return Just(true);
   2307 }
   2308 
   2309 MaybeLocal<Value> Module::Evaluate(Local<Context> context) {
   2310   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   2311   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
   2312   ENTER_V8(isolate, context, Module, Evaluate, MaybeLocal<Value>(),
   2313            InternalEscapableScope);
   2314   i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true);
   2315   i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
   2316   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
   2317 
   2318   i::Handle<i::Module> self = Utils::OpenHandle(this);
   2319   // It's an API error to call Evaluate before Instantiate.
   2320   CHECK_GE(self->status(), i::Module::kInstantiated);
   2321 
   2322   Local<Value> result;
   2323   has_pending_exception = !ToLocal(i::Module::Evaluate(isolate, self), &result);
   2324   RETURN_ON_FAILED_EXECUTION(Value);
   2325   RETURN_ESCAPED(result);
   2326 }
   2327 
   2328 namespace {
   2329 
   2330 i::Compiler::ScriptDetails GetScriptDetails(
   2331     i::Isolate* isolate, Local<Value> resource_name,
   2332     Local<Integer> resource_line_offset, Local<Integer> resource_column_offset,
   2333     Local<Value> source_map_url, Local<PrimitiveArray> host_defined_options) {
   2334   i::Compiler::ScriptDetails script_details;
   2335   if (!resource_name.IsEmpty()) {
   2336     script_details.name_obj = Utils::OpenHandle(*(resource_name));
   2337   }
   2338   if (!resource_line_offset.IsEmpty()) {
   2339     script_details.line_offset =
   2340         static_cast<int>(resource_line_offset->Value());
   2341   }
   2342   if (!resource_column_offset.IsEmpty()) {
   2343     script_details.column_offset =
   2344         static_cast<int>(resource_column_offset->Value());
   2345   }
   2346   script_details.host_defined_options = isolate->factory()->empty_fixed_array();
   2347   if (!host_defined_options.IsEmpty()) {
   2348     script_details.host_defined_options =
   2349         Utils::OpenHandle(*(host_defined_options));
   2350   }
   2351   if (!source_map_url.IsEmpty()) {
   2352     script_details.source_map_url = Utils::OpenHandle(*(source_map_url));
   2353   }
   2354   return script_details;
   2355 }
   2356 
   2357 }  // namespace
   2358 
   2359 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal(
   2360     Isolate* v8_isolate, Source* source, CompileOptions options,
   2361     NoCacheReason no_cache_reason) {
   2362   auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   2363   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
   2364   ENTER_V8_NO_SCRIPT(isolate, v8_isolate->GetCurrentContext(), ScriptCompiler,
   2365                      CompileUnbound, MaybeLocal<UnboundScript>(),
   2366                      InternalEscapableScope);
   2367   // ProduceParserCache, ProduceCodeCache, ProduceFullCodeCache and
   2368   // ConsumeParserCache are not supported. They are present only for
   2369   // backward compatability. All these options behave as kNoCompileOptions.
   2370   if (options == kConsumeParserCache) {
   2371     // We do not support parser caches anymore. Just set cached_data to
   2372     // rejected to signal an error.
   2373     options = kNoCompileOptions;
   2374     source->cached_data->rejected = true;
   2375   } else if (options == kProduceParserCache || options == kProduceCodeCache ||
   2376              options == kProduceFullCodeCache) {
   2377     options = kNoCompileOptions;
   2378   }
   2379 
   2380   i::ScriptData* script_data = nullptr;
   2381   if (options == kConsumeCodeCache) {
   2382     DCHECK(source->cached_data);
   2383     // ScriptData takes care of pointer-aligning the data.
   2384     script_data = new i::ScriptData(source->cached_data->data,
   2385                                     source->cached_data->length);
   2386   }
   2387 
   2388   i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
   2389   i::Handle<i::SharedFunctionInfo> result;
   2390   TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileScript");
   2391   i::Compiler::ScriptDetails script_details = GetScriptDetails(
   2392       isolate, source->resource_name, source->resource_line_offset,
   2393       source->resource_column_offset, source->source_map_url,
   2394       source->host_defined_options);
   2395   i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
   2396       i::Compiler::GetSharedFunctionInfoForScript(
   2397           isolate, str, script_details, source->resource_options, nullptr,
   2398           script_data, options, no_cache_reason, i::NOT_NATIVES_CODE);
   2399   if (options == kConsumeCodeCache) {
   2400     source->cached_data->rejected = script_data->rejected();
   2401   }
   2402   delete script_data;
   2403   has_pending_exception = !maybe_function_info.ToHandle(&result);
   2404   RETURN_ON_FAILED_EXECUTION(UnboundScript);
   2405   RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
   2406 }
   2407 
   2408 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript(
   2409     Isolate* v8_isolate, Source* source, CompileOptions options,
   2410     NoCacheReason no_cache_reason) {
   2411   Utils::ApiCheck(
   2412       !source->GetResourceOptions().IsModule(),
   2413       "v8::ScriptCompiler::CompileUnboundScript",
   2414       "v8::ScriptCompiler::CompileModule must be used to compile modules");
   2415   return CompileUnboundInternal(v8_isolate, source, options, no_cache_reason);
   2416 }
   2417 
   2418 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
   2419                                            Source* source,
   2420                                            CompileOptions options,
   2421                                            NoCacheReason no_cache_reason) {
   2422   Utils::ApiCheck(
   2423       !source->GetResourceOptions().IsModule(), "v8::ScriptCompiler::Compile",
   2424       "v8::ScriptCompiler::CompileModule must be used to compile modules");
   2425   auto isolate = context->GetIsolate();
   2426   auto maybe =
   2427       CompileUnboundInternal(isolate, source, options, no_cache_reason);
   2428   Local<UnboundScript> result;
   2429   if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
   2430   v8::Context::Scope scope(context);
   2431   return result->BindToCurrentContext();
   2432 }
   2433 
   2434 MaybeLocal<Module> ScriptCompiler::CompileModule(
   2435     Isolate* isolate, Source* source, CompileOptions options,
   2436     NoCacheReason no_cache_reason) {
   2437   CHECK(options == kNoCompileOptions || options == kConsumeCodeCache);
   2438 
   2439   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   2440 
   2441   Utils::ApiCheck(source->GetResourceOptions().IsModule(),
   2442                   "v8::ScriptCompiler::CompileModule",
   2443                   "Invalid ScriptOrigin: is_module must be true");
   2444   auto maybe =
   2445       CompileUnboundInternal(isolate, source, options, no_cache_reason);
   2446   Local<UnboundScript> unbound;
   2447   if (!maybe.ToLocal(&unbound)) return MaybeLocal<Module>();
   2448 
   2449   i::Handle<i::SharedFunctionInfo> shared = Utils::OpenHandle(*unbound);
   2450   return ToApiHandle<Module>(i_isolate->factory()->NewModule(shared));
   2451 }
   2452 
   2453 
   2454 class IsIdentifierHelper {
   2455  public:
   2456   IsIdentifierHelper() : is_identifier_(false), first_char_(true) {}
   2457 
   2458   bool Check(i::String* string) {
   2459     i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
   2460     if (cons_string == nullptr) return is_identifier_;
   2461     // We don't support cons strings here.
   2462     return false;
   2463   }
   2464   void VisitOneByteString(const uint8_t* chars, int length) {
   2465     for (int i = 0; i < length; ++i) {
   2466       if (first_char_) {
   2467         first_char_ = false;
   2468         is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
   2469       } else {
   2470         is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
   2471       }
   2472     }
   2473   }
   2474   void VisitTwoByteString(const uint16_t* chars, int length) {
   2475     for (int i = 0; i < length; ++i) {
   2476       if (first_char_) {
   2477         first_char_ = false;
   2478         is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
   2479       } else {
   2480         is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
   2481       }
   2482     }
   2483   }
   2484 
   2485  private:
   2486   bool is_identifier_;
   2487   bool first_char_;
   2488   i::UnicodeCache unicode_cache_;
   2489   DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper);
   2490 };
   2491 
   2492 MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext(
   2493     Local<Context> v8_context, Source* source, size_t arguments_count,
   2494     Local<String> arguments[], size_t context_extension_count,
   2495     Local<Object> context_extensions[], CompileOptions options,
   2496     NoCacheReason no_cache_reason) {
   2497   PREPARE_FOR_EXECUTION(v8_context, ScriptCompiler, CompileFunctionInContext,
   2498                         Function);
   2499   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
   2500 
   2501   DCHECK(options == CompileOptions::kConsumeCodeCache ||
   2502          options == CompileOptions::kEagerCompile ||
   2503          options == CompileOptions::kNoCompileOptions);
   2504 
   2505   i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
   2506 
   2507   DCHECK(context->IsNativeContext());
   2508   i::Handle<i::SharedFunctionInfo> outer_info(
   2509       context->empty_function()->shared(), isolate);
   2510 
   2511   i::Handle<i::JSFunction> fun;
   2512   i::Handle<i::FixedArray> arguments_list =
   2513       isolate->factory()->NewFixedArray(static_cast<int>(arguments_count));
   2514   for (int i = 0; i < static_cast<int>(arguments_count); i++) {
   2515     IsIdentifierHelper helper;
   2516     i::Handle<i::String> argument = Utils::OpenHandle(*arguments[i]);
   2517     if (!helper.Check(*argument)) return Local<Function>();
   2518     arguments_list->set(i, *argument);
   2519   }
   2520 
   2521   for (size_t i = 0; i < context_extension_count; ++i) {
   2522     i::Handle<i::JSReceiver> extension =
   2523         Utils::OpenHandle(*context_extensions[i]);
   2524     if (!extension->IsJSObject()) return Local<Function>();
   2525     context = isolate->factory()->NewWithContext(
   2526         context,
   2527         i::ScopeInfo::CreateForWithScope(
   2528             isolate,
   2529             context->IsNativeContext()
   2530                 ? i::Handle<i::ScopeInfo>::null()
   2531                 : i::Handle<i::ScopeInfo>(context->scope_info(), isolate)),
   2532         extension);
   2533   }
   2534 
   2535   i::Compiler::ScriptDetails script_details = GetScriptDetails(
   2536       isolate, source->resource_name, source->resource_line_offset,
   2537       source->resource_column_offset, source->source_map_url,
   2538       source->host_defined_options);
   2539 
   2540   i::ScriptData* script_data = nullptr;
   2541   if (options == kConsumeCodeCache) {
   2542     DCHECK(source->cached_data);
   2543     // ScriptData takes care of pointer-aligning the data.
   2544     script_data = new i::ScriptData(source->cached_data->data,
   2545                                     source->cached_data->length);
   2546   }
   2547 
   2548   i::Handle<i::JSFunction> result;
   2549   has_pending_exception =
   2550       !i::Compiler::GetWrappedFunction(
   2551            Utils::OpenHandle(*source->source_string), arguments_list, context,
   2552            script_details, source->resource_options, script_data, options,
   2553            no_cache_reason)
   2554            .ToHandle(&result);
   2555   if (options == kConsumeCodeCache) {
   2556     source->cached_data->rejected = script_data->rejected();
   2557   }
   2558   delete script_data;
   2559   RETURN_ON_FAILED_EXECUTION(Function);
   2560   RETURN_ESCAPED(Utils::CallableToLocal(result));
   2561 }
   2562 
   2563 
   2564 ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript(
   2565     Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
   2566   if (!i::FLAG_script_streaming) {
   2567     return nullptr;
   2568   }
   2569   // We don't support other compile options on streaming background compiles.
   2570   // TODO(rmcilroy): remove CompileOptions from the API.
   2571   CHECK(options == ScriptCompiler::kNoCompileOptions);
   2572   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   2573   return i::Compiler::NewBackgroundCompileTask(source->impl(), isolate);
   2574 }
   2575 
   2576 
   2577 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
   2578                                            StreamedSource* v8_source,
   2579                                            Local<String> full_source_string,
   2580                                            const ScriptOrigin& origin) {
   2581   PREPARE_FOR_EXECUTION(context, ScriptCompiler, Compile, Script);
   2582   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
   2583   TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"),
   2584                "V8.CompileStreamedScript");
   2585 
   2586   i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
   2587   i::Compiler::ScriptDetails script_details = GetScriptDetails(
   2588       isolate, origin.ResourceName(), origin.ResourceLineOffset(),
   2589       origin.ResourceColumnOffset(), origin.SourceMapUrl(),
   2590       origin.HostDefinedOptions());
   2591   i::ScriptStreamingData* streaming_data = v8_source->impl();
   2592 
   2593   i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
   2594       i::Compiler::GetSharedFunctionInfoForStreamedScript(
   2595           isolate, str, script_details, origin.Options(), streaming_data);
   2596 
   2597   i::Handle<i::SharedFunctionInfo> result;
   2598   has_pending_exception = !maybe_function_info.ToHandle(&result);
   2599   if (has_pending_exception) isolate->ReportPendingMessages();
   2600 
   2601   RETURN_ON_FAILED_EXECUTION(Script);
   2602 
   2603   Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
   2604   if (generic.IsEmpty()) return Local<Script>();
   2605   Local<Script> bound = generic->BindToCurrentContext();
   2606   if (bound.IsEmpty()) return Local<Script>();
   2607   RETURN_ESCAPED(bound);
   2608 }
   2609 
   2610 uint32_t ScriptCompiler::CachedDataVersionTag() {
   2611   return static_cast<uint32_t>(base::hash_combine(
   2612       internal::Version::Hash(), internal::FlagList::Hash(),
   2613       static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures())));
   2614 }
   2615 
   2616 ScriptCompiler::CachedData* ScriptCompiler::CreateCodeCache(
   2617     Local<UnboundScript> unbound_script) {
   2618   i::Handle<i::SharedFunctionInfo> shared =
   2619       i::Handle<i::SharedFunctionInfo>::cast(
   2620           Utils::OpenHandle(*unbound_script));
   2621   DCHECK(shared->is_toplevel());
   2622   return i::CodeSerializer::Serialize(shared);
   2623 }
   2624 
   2625 // static
   2626 ScriptCompiler::CachedData* ScriptCompiler::CreateCodeCache(
   2627     Local<UnboundModuleScript> unbound_module_script) {
   2628   i::Handle<i::SharedFunctionInfo> shared =
   2629       i::Handle<i::SharedFunctionInfo>::cast(
   2630           Utils::OpenHandle(*unbound_module_script));
   2631   DCHECK(shared->is_toplevel());
   2632   return i::CodeSerializer::Serialize(shared);
   2633 }
   2634 
   2635 ScriptCompiler::CachedData* ScriptCompiler::CreateCodeCacheForFunction(
   2636     Local<Function> function) {
   2637   auto js_function =
   2638       i::Handle<i::JSFunction>::cast(Utils::OpenHandle(*function));
   2639   i::Handle<i::SharedFunctionInfo> shared(js_function->shared(),
   2640                                           js_function->GetIsolate());
   2641   CHECK(shared->is_wrapped());
   2642   return i::CodeSerializer::Serialize(shared);
   2643 }
   2644 
   2645 MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source,
   2646                                    ScriptOrigin* origin) {
   2647   if (origin) {
   2648     ScriptCompiler::Source script_source(source, *origin);
   2649     return ScriptCompiler::Compile(context, &script_source);
   2650   }
   2651   ScriptCompiler::Source script_source(source);
   2652   return ScriptCompiler::Compile(context, &script_source);
   2653 }
   2654 
   2655 
   2656 // --- E x c e p t i o n s ---
   2657 
   2658 v8::TryCatch::TryCatch(v8::Isolate* isolate)
   2659     : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
   2660       next_(isolate_->try_catch_handler()),
   2661       is_verbose_(false),
   2662       can_continue_(true),
   2663       capture_message_(true),
   2664       rethrow_(false),
   2665       has_terminated_(false) {
   2666   ResetInternal();
   2667   // Special handling for simulators which have a separate JS stack.
   2668   js_stack_comparable_address_ =
   2669       reinterpret_cast<void*>(i::SimulatorStack::RegisterCTryCatch(
   2670           isolate_, i::GetCurrentStackPosition()));
   2671   isolate_->RegisterTryCatchHandler(this);
   2672 }
   2673 
   2674 
   2675 v8::TryCatch::~TryCatch() {
   2676   if (rethrow_) {
   2677     v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
   2678     v8::HandleScope scope(isolate);
   2679     v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
   2680     if (HasCaught() && capture_message_) {
   2681       // If an exception was caught and rethrow_ is indicated, the saved
   2682       // message, script, and location need to be restored to Isolate TLS
   2683       // for reuse.  capture_message_ needs to be disabled so that Throw()
   2684       // does not create a new message.
   2685       isolate_->thread_local_top()->rethrowing_message_ = true;
   2686       isolate_->RestorePendingMessageFromTryCatch(this);
   2687     }
   2688     isolate_->UnregisterTryCatchHandler(this);
   2689     i::SimulatorStack::UnregisterCTryCatch(isolate_);
   2690     reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
   2691     DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
   2692   } else {
   2693     if (HasCaught() && isolate_->has_scheduled_exception()) {
   2694       // If an exception was caught but is still scheduled because no API call
   2695       // promoted it, then it is canceled to prevent it from being propagated.
   2696       // Note that this will not cancel termination exceptions.
   2697       isolate_->CancelScheduledExceptionFromTryCatch(this);
   2698     }
   2699     isolate_->UnregisterTryCatchHandler(this);
   2700     i::SimulatorStack::UnregisterCTryCatch(isolate_);
   2701   }
   2702 }
   2703 
   2704 void* v8::TryCatch::operator new(size_t) { base::OS::Abort(); }
   2705 void* v8::TryCatch::operator new[](size_t) { base::OS::Abort(); }
   2706 void v8::TryCatch::operator delete(void*, size_t) { base::OS::Abort(); }
   2707 void v8::TryCatch::operator delete[](void*, size_t) { base::OS::Abort(); }
   2708 
   2709 bool v8::TryCatch::HasCaught() const {
   2710   return !reinterpret_cast<i::Object*>(exception_)->IsTheHole(isolate_);
   2711 }
   2712 
   2713 
   2714 bool v8::TryCatch::CanContinue() const {
   2715   return can_continue_;
   2716 }
   2717 
   2718 
   2719 bool v8::TryCatch::HasTerminated() const {
   2720   return has_terminated_;
   2721 }
   2722 
   2723 
   2724 v8::Local<v8::Value> v8::TryCatch::ReThrow() {
   2725   if (!HasCaught()) return v8::Local<v8::Value>();
   2726   rethrow_ = true;
   2727   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
   2728 }
   2729 
   2730 
   2731 v8::Local<Value> v8::TryCatch::Exception() const {
   2732   if (HasCaught()) {
   2733     // Check for out of memory exception.
   2734     i::Object* exception = reinterpret_cast<i::Object*>(exception_);
   2735     return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
   2736   } else {
   2737     return v8::Local<Value>();
   2738   }
   2739 }
   2740 
   2741 
   2742 MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const {
   2743   if (!HasCaught()) return v8::Local<Value>();
   2744   i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
   2745   if (!raw_obj->IsJSObject()) return v8::Local<Value>();
   2746   PREPARE_FOR_EXECUTION(context, TryCatch, StackTrace, Value);
   2747   i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
   2748   i::Handle<i::String> name = isolate->factory()->stack_string();
   2749   Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
   2750   has_pending_exception = maybe.IsNothing();
   2751   RETURN_ON_FAILED_EXECUTION(Value);
   2752   if (!maybe.FromJust()) return v8::Local<Value>();
   2753   Local<Value> result;
   2754   has_pending_exception =
   2755       !ToLocal<Value>(i::JSReceiver::GetProperty(isolate, obj, name), &result);
   2756   RETURN_ON_FAILED_EXECUTION(Value);
   2757   RETURN_ESCAPED(result);
   2758 }
   2759 
   2760 
   2761 v8::Local<v8::Message> v8::TryCatch::Message() const {
   2762   i::Object* message = reinterpret_cast<i::Object*>(message_obj_);
   2763   DCHECK(message->IsJSMessageObject() || message->IsTheHole(isolate_));
   2764   if (HasCaught() && !message->IsTheHole(isolate_)) {
   2765     return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
   2766   } else {
   2767     return v8::Local<v8::Message>();
   2768   }
   2769 }
   2770 
   2771 
   2772 void v8::TryCatch::Reset() {
   2773   if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
   2774     // If an exception was caught but is still scheduled because no API call
   2775     // promoted it, then it is canceled to prevent it from being propagated.
   2776     // Note that this will not cancel termination exceptions.
   2777     isolate_->CancelScheduledExceptionFromTryCatch(this);
   2778   }
   2779   ResetInternal();
   2780 }
   2781 
   2782 
   2783 void v8::TryCatch::ResetInternal() {
   2784   i::Object* the_hole = i::ReadOnlyRoots(isolate_).the_hole_value();
   2785   exception_ = the_hole;
   2786   message_obj_ = the_hole;
   2787 }
   2788 
   2789 
   2790 void v8::TryCatch::SetVerbose(bool value) {
   2791   is_verbose_ = value;
   2792 }
   2793 
   2794 bool v8::TryCatch::IsVerbose() const { return is_verbose_; }
   2795 
   2796 void v8::TryCatch::SetCaptureMessage(bool value) {
   2797   capture_message_ = value;
   2798 }
   2799 
   2800 
   2801 // --- M e s s a g e ---
   2802 
   2803 
   2804 Local<String> Message::Get() const {
   2805   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2806   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2807   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
   2808   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   2809   i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
   2810   Local<String> result = Utils::ToLocal(raw_result);
   2811   return scope.Escape(result);
   2812 }
   2813 
   2814 v8::Isolate* Message::GetIsolate() const {
   2815   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2816   return reinterpret_cast<Isolate*>(isolate);
   2817 }
   2818 
   2819 ScriptOrigin Message::GetScriptOrigin() const {
   2820   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2821   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2822   auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
   2823   i::Handle<i::Script> script(message->script(), isolate);
   2824   return GetScriptOriginForScript(isolate, script);
   2825 }
   2826 
   2827 
   2828 v8::Local<Value> Message::GetScriptResourceName() const {
   2829   return GetScriptOrigin().ResourceName();
   2830 }
   2831 
   2832 
   2833 v8::Local<v8::StackTrace> Message::GetStackTrace() const {
   2834   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2835   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2836   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
   2837   auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
   2838   i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
   2839   if (!stackFramesObj->IsFixedArray()) return v8::Local<v8::StackTrace>();
   2840   auto stackTrace = i::Handle<i::FixedArray>::cast(stackFramesObj);
   2841   return scope.Escape(Utils::StackTraceToLocal(stackTrace));
   2842 }
   2843 
   2844 
   2845 Maybe<int> Message::GetLineNumber(Local<Context> context) const {
   2846   auto self = Utils::OpenHandle(this);
   2847   i::Isolate* isolate = self->GetIsolate();
   2848   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2849   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
   2850   auto msg = i::Handle<i::JSMessageObject>::cast(self);
   2851   return Just(msg->GetLineNumber());
   2852 }
   2853 
   2854 
   2855 int Message::GetStartPosition() const {
   2856   auto self = Utils::OpenHandle(this);
   2857   return self->start_position();
   2858 }
   2859 
   2860 
   2861 int Message::GetEndPosition() const {
   2862   auto self = Utils::OpenHandle(this);
   2863   return self->end_position();
   2864 }
   2865 
   2866 int Message::ErrorLevel() const {
   2867   auto self = Utils::OpenHandle(this);
   2868   return self->error_level();
   2869 }
   2870 
   2871 int Message::GetStartColumn() const {
   2872   auto self = Utils::OpenHandle(this);
   2873   i::Isolate* isolate = self->GetIsolate();
   2874   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2875   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
   2876   auto msg = i::Handle<i::JSMessageObject>::cast(self);
   2877   return msg->GetColumnNumber();
   2878 }
   2879 
   2880 Maybe<int> Message::GetStartColumn(Local<Context> context) const {
   2881   return Just(GetStartColumn());
   2882 }
   2883 
   2884 int Message::GetEndColumn() const {
   2885   auto self = Utils::OpenHandle(this);
   2886   i::Isolate* isolate = self->GetIsolate();
   2887   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2888   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
   2889   auto msg = i::Handle<i::JSMessageObject>::cast(self);
   2890   const int column_number = msg->GetColumnNumber();
   2891   if (column_number == -1) return -1;
   2892   const int start = self->start_position();
   2893   const int end = self->end_position();
   2894   return column_number + (end - start);
   2895 }
   2896 
   2897 Maybe<int> Message::GetEndColumn(Local<Context> context) const {
   2898   return Just(GetEndColumn());
   2899 }
   2900 
   2901 
   2902 bool Message::IsSharedCrossOrigin() const {
   2903   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2904   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2905   return Utils::OpenHandle(this)
   2906       ->script()
   2907       ->origin_options()
   2908       .IsSharedCrossOrigin();
   2909 }
   2910 
   2911 bool Message::IsOpaque() const {
   2912   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2913   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2914   return Utils::OpenHandle(this)->script()->origin_options().IsOpaque();
   2915 }
   2916 
   2917 
   2918 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
   2919   auto self = Utils::OpenHandle(this);
   2920   i::Isolate* isolate = self->GetIsolate();
   2921   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2922   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
   2923   auto msg = i::Handle<i::JSMessageObject>::cast(self);
   2924   RETURN_ESCAPED(Utils::ToLocal(msg->GetSourceLine()));
   2925 }
   2926 
   2927 
   2928 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
   2929   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   2930   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   2931   i_isolate->PrintCurrentStackTrace(out);
   2932 }
   2933 
   2934 
   2935 // --- S t a c k T r a c e ---
   2936 
   2937 Local<StackFrame> StackTrace::GetFrame(Isolate* v8_isolate,
   2938                                        uint32_t index) const {
   2939   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   2940   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   2941   EscapableHandleScope scope(v8_isolate);
   2942   auto obj = handle(Utils::OpenHandle(this)->get(index), isolate);
   2943   auto info = i::Handle<i::StackFrameInfo>::cast(obj);
   2944   return scope.Escape(Utils::StackFrameToLocal(info));
   2945 }
   2946 
   2947 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
   2948   i::Isolate* isolate = UnsafeIsolateFromHeapObject(Utils::OpenHandle(this));
   2949   return GetFrame(reinterpret_cast<Isolate*>(isolate), index);
   2950 }
   2951 
   2952 int StackTrace::GetFrameCount() const {
   2953   return Utils::OpenHandle(this)->length();
   2954 }
   2955 
   2956 
   2957 Local<StackTrace> StackTrace::CurrentStackTrace(
   2958     Isolate* isolate,
   2959     int frame_limit,
   2960     StackTraceOptions options) {
   2961   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   2962   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   2963   i::Handle<i::FixedArray> stackTrace =
   2964       i_isolate->CaptureCurrentStackTrace(frame_limit, options);
   2965   return Utils::StackTraceToLocal(stackTrace);
   2966 }
   2967 
   2968 
   2969 // --- S t a c k F r a m e ---
   2970 
   2971 int StackFrame::GetLineNumber() const {
   2972   int v = Utils::OpenHandle(this)->line_number();
   2973   return v ? v : Message::kNoLineNumberInfo;
   2974 }
   2975 
   2976 
   2977 int StackFrame::GetColumn() const {
   2978   int v = Utils::OpenHandle(this)->column_number();
   2979   return v ? v : Message::kNoLineNumberInfo;
   2980 }
   2981 
   2982 
   2983 int StackFrame::GetScriptId() const {
   2984   int v = Utils::OpenHandle(this)->script_id();
   2985   return v ? v : Message::kNoScriptIdInfo;
   2986 }
   2987 
   2988 Local<String> StackFrame::GetScriptName() const {
   2989   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   2990   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
   2991   i::Handle<i::StackFrameInfo> self = Utils::OpenHandle(this);
   2992   i::Handle<i::Object> obj(self->script_name(), isolate);
   2993   return obj->IsString()
   2994              ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
   2995              : Local<String>();
   2996 }
   2997 
   2998 
   2999 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
   3000   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   3001   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
   3002   i::Handle<i::StackFrameInfo> self = Utils::OpenHandle(this);
   3003   i::Handle<i::Object> obj(self->script_name_or_source_url(), isolate);
   3004   return obj->IsString()
   3005              ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
   3006              : Local<String>();
   3007 }
   3008 
   3009 
   3010 Local<String> StackFrame::GetFunctionName() const {
   3011   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   3012   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
   3013   i::Handle<i::StackFrameInfo> self = Utils::OpenHandle(this);
   3014   i::Handle<i::Object> obj(self->function_name(), isolate);
   3015   return obj->IsString()
   3016              ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
   3017              : Local<String>();
   3018 }
   3019 
   3020 bool StackFrame::IsEval() const { return Utils::OpenHandle(this)->is_eval(); }
   3021 
   3022 bool StackFrame::IsConstructor() const {
   3023   return Utils::OpenHandle(this)->is_constructor();
   3024 }
   3025 
   3026 bool StackFrame::IsWasm() const { return Utils::OpenHandle(this)->is_wasm(); }
   3027 
   3028 
   3029 // --- J S O N ---
   3030 
   3031 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) {
   3032   PREPARE_FOR_EXECUTION(v8_isolate->GetCurrentContext(), JSON, Parse, Value);
   3033   i::Handle<i::String> string = Utils::OpenHandle(*json_string);
   3034   i::Handle<i::String> source = i::String::Flatten(isolate, string);
   3035   i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
   3036   auto maybe = source->IsSeqOneByteString()
   3037                    ? i::JsonParser<true>::Parse(isolate, source, undefined)
   3038                    : i::JsonParser<false>::Parse(isolate, source, undefined);
   3039   Local<Value> result;
   3040   has_pending_exception = !ToLocal<Value>(maybe, &result);
   3041   RETURN_ON_FAILED_EXECUTION(Value);
   3042   RETURN_ESCAPED(result);
   3043 }
   3044 
   3045 MaybeLocal<Value> JSON::Parse(Local<Context> context,
   3046                               Local<String> json_string) {
   3047   PREPARE_FOR_EXECUTION(context, JSON, Parse, Value);
   3048   i::Handle<i::String> string = Utils::OpenHandle(*json_string);
   3049   i::Handle<i::String> source = i::String::Flatten(isolate, string);
   3050   i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
   3051   auto maybe = source->IsSeqOneByteString()
   3052                    ? i::JsonParser<true>::Parse(isolate, source, undefined)
   3053                    : i::JsonParser<false>::Parse(isolate, source, undefined);
   3054   Local<Value> result;
   3055   has_pending_exception = !ToLocal<Value>(maybe, &result);
   3056   RETURN_ON_FAILED_EXECUTION(Value);
   3057   RETURN_ESCAPED(result);
   3058 }
   3059 
   3060 MaybeLocal<String> JSON::Stringify(Local<Context> context,
   3061                                    Local<Value> json_object,
   3062                                    Local<String> gap) {
   3063   PREPARE_FOR_EXECUTION(context, JSON, Stringify, String);
   3064   i::Handle<i::Object> object = Utils::OpenHandle(*json_object);
   3065   i::Handle<i::Object> replacer = isolate->factory()->undefined_value();
   3066   i::Handle<i::String> gap_string = gap.IsEmpty()
   3067                                         ? isolate->factory()->empty_string()
   3068                                         : Utils::OpenHandle(*gap);
   3069   i::Handle<i::Object> maybe;
   3070   has_pending_exception =
   3071       !i::JsonStringify(isolate, object, replacer, gap_string).ToHandle(&maybe);
   3072   RETURN_ON_FAILED_EXECUTION(String);
   3073   Local<String> result;
   3074   has_pending_exception =
   3075       !ToLocal<String>(i::Object::ToString(isolate, maybe), &result);
   3076   RETURN_ON_FAILED_EXECUTION(String);
   3077   RETURN_ESCAPED(result);
   3078 }
   3079 
   3080 // --- V a l u e   S e r i a l i z a t i o n ---
   3081 
   3082 Maybe<bool> ValueSerializer::Delegate::WriteHostObject(Isolate* v8_isolate,
   3083                                                        Local<Object> object) {
   3084   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   3085   isolate->ScheduleThrow(*isolate->factory()->NewError(
   3086       isolate->error_function(), i::MessageTemplate::kDataCloneError,
   3087       Utils::OpenHandle(*object)));
   3088   return Nothing<bool>();
   3089 }
   3090 
   3091 Maybe<uint32_t> ValueSerializer::Delegate::GetSharedArrayBufferId(
   3092     Isolate* v8_isolate, Local<SharedArrayBuffer> shared_array_buffer) {
   3093   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   3094   isolate->ScheduleThrow(*isolate->factory()->NewError(
   3095       isolate->error_function(), i::MessageTemplate::kDataCloneError,
   3096       Utils::OpenHandle(*shared_array_buffer)));
   3097   return Nothing<uint32_t>();
   3098 }
   3099 
   3100 Maybe<uint32_t> ValueSerializer::Delegate::GetWasmModuleTransferId(
   3101     Isolate* v8_isolate, Local<WasmCompiledModule> module) {
   3102   return Nothing<uint32_t>();
   3103 }
   3104 
   3105 void* ValueSerializer::Delegate::ReallocateBufferMemory(void* old_buffer,
   3106                                                         size_t size,
   3107                                                         size_t* actual_size) {
   3108   *actual_size = size;
   3109   return realloc(old_buffer, size);
   3110 }
   3111 
   3112 void ValueSerializer::Delegate::FreeBufferMemory(void* buffer) {
   3113   return free(buffer);
   3114 }
   3115 
   3116 struct ValueSerializer::PrivateData {
   3117   explicit PrivateData(i::Isolate* i, ValueSerializer::Delegate* delegate)
   3118       : isolate(i), serializer(i, delegate) {}
   3119   i::Isolate* isolate;
   3120   i::ValueSerializer serializer;
   3121 };
   3122 
   3123 ValueSerializer::ValueSerializer(Isolate* isolate)
   3124     : ValueSerializer(isolate, nullptr) {}
   3125 
   3126 ValueSerializer::ValueSerializer(Isolate* isolate, Delegate* delegate)
   3127     : private_(
   3128           new PrivateData(reinterpret_cast<i::Isolate*>(isolate), delegate)) {}
   3129 
   3130 ValueSerializer::~ValueSerializer() { delete private_; }
   3131 
   3132 void ValueSerializer::WriteHeader() { private_->serializer.WriteHeader(); }
   3133 
   3134 void ValueSerializer::SetTreatArrayBufferViewsAsHostObjects(bool mode) {
   3135   private_->serializer.SetTreatArrayBufferViewsAsHostObjects(mode);
   3136 }
   3137 
   3138 Maybe<bool> ValueSerializer::WriteValue(Local<Context> context,
   3139                                         Local<Value> value) {
   3140   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   3141   ENTER_V8(isolate, context, ValueSerializer, WriteValue, Nothing<bool>(),
   3142            i::HandleScope);
   3143   i::Handle<i::Object> object = Utils::OpenHandle(*value);
   3144   Maybe<bool> result = private_->serializer.WriteObject(object);
   3145   has_pending_exception = result.IsNothing();
   3146   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   3147   return result;
   3148 }
   3149 
   3150 std::vector<uint8_t> ValueSerializer::ReleaseBuffer() {
   3151   return private_->serializer.ReleaseBuffer();
   3152 }
   3153 
   3154 std::pair<uint8_t*, size_t> ValueSerializer::Release() {
   3155   return private_->serializer.Release();
   3156 }
   3157 
   3158 void ValueSerializer::TransferArrayBuffer(uint32_t transfer_id,
   3159                                           Local<ArrayBuffer> array_buffer) {
   3160   private_->serializer.TransferArrayBuffer(transfer_id,
   3161                                            Utils::OpenHandle(*array_buffer));
   3162 }
   3163 
   3164 void ValueSerializer::TransferSharedArrayBuffer(
   3165     uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) {
   3166   private_->serializer.TransferArrayBuffer(
   3167       transfer_id, Utils::OpenHandle(*shared_array_buffer));
   3168 }
   3169 
   3170 void ValueSerializer::WriteUint32(uint32_t value) {
   3171   private_->serializer.WriteUint32(value);
   3172 }
   3173 
   3174 void ValueSerializer::WriteUint64(uint64_t value) {
   3175   private_->serializer.WriteUint64(value);
   3176 }
   3177 
   3178 void ValueSerializer::WriteDouble(double value) {
   3179   private_->serializer.WriteDouble(value);
   3180 }
   3181 
   3182 void ValueSerializer::WriteRawBytes(const void* source, size_t length) {
   3183   private_->serializer.WriteRawBytes(source, length);
   3184 }
   3185 
   3186 MaybeLocal<Object> ValueDeserializer::Delegate::ReadHostObject(
   3187     Isolate* v8_isolate) {
   3188   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   3189   isolate->ScheduleThrow(*isolate->factory()->NewError(
   3190       isolate->error_function(),
   3191       i::MessageTemplate::kDataCloneDeserializationError));
   3192   return MaybeLocal<Object>();
   3193 }
   3194 
   3195 MaybeLocal<WasmCompiledModule> ValueDeserializer::Delegate::GetWasmModuleFromId(
   3196     Isolate* v8_isolate, uint32_t id) {
   3197   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   3198   isolate->ScheduleThrow(*isolate->factory()->NewError(
   3199       isolate->error_function(),
   3200       i::MessageTemplate::kDataCloneDeserializationError));
   3201   return MaybeLocal<WasmCompiledModule>();
   3202 }
   3203 
   3204 MaybeLocal<SharedArrayBuffer>
   3205 ValueDeserializer::Delegate::GetSharedArrayBufferFromId(Isolate* v8_isolate,
   3206                                                         uint32_t id) {
   3207   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   3208   isolate->ScheduleThrow(*isolate->factory()->NewError(
   3209       isolate->error_function(),
   3210       i::MessageTemplate::kDataCloneDeserializationError));
   3211   return MaybeLocal<SharedArrayBuffer>();
   3212 }
   3213 
   3214 struct ValueDeserializer::PrivateData {
   3215   PrivateData(i::Isolate* i, i::Vector<const uint8_t> data, Delegate* delegate)
   3216       : isolate(i), deserializer(i, data, delegate) {}
   3217   i::Isolate* isolate;
   3218   i::ValueDeserializer deserializer;
   3219   bool has_aborted = false;
   3220   bool supports_legacy_wire_format = false;
   3221 };
   3222 
   3223 ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data,
   3224                                      size_t size)
   3225     : ValueDeserializer(isolate, data, size, nullptr) {}
   3226 
   3227 ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data,
   3228                                      size_t size, Delegate* delegate) {
   3229   if (base::IsValueInRangeForNumericType<int>(size)) {
   3230     private_ = new PrivateData(
   3231         reinterpret_cast<i::Isolate*>(isolate),
   3232         i::Vector<const uint8_t>(data, static_cast<int>(size)), delegate);
   3233   } else {
   3234     private_ = new PrivateData(reinterpret_cast<i::Isolate*>(isolate),
   3235                                i::Vector<const uint8_t>(nullptr, 0), nullptr);
   3236     private_->has_aborted = true;
   3237   }
   3238 }
   3239 
   3240 ValueDeserializer::~ValueDeserializer() { delete private_; }
   3241 
   3242 Maybe<bool> ValueDeserializer::ReadHeader(Local<Context> context) {
   3243   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   3244   ENTER_V8_NO_SCRIPT(isolate, context, ValueDeserializer, ReadHeader,
   3245                      Nothing<bool>(), i::HandleScope);
   3246 
   3247   // We could have aborted during the constructor.
   3248   // If so, ReadHeader is where we report it.
   3249   if (private_->has_aborted) {
   3250     isolate->Throw(*isolate->factory()->NewError(
   3251         i::MessageTemplate::kDataCloneDeserializationError));
   3252     has_pending_exception = true;
   3253     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   3254   }
   3255 
   3256   bool read_header = false;
   3257   has_pending_exception = !private_->deserializer.ReadHeader().To(&read_header);
   3258   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   3259   DCHECK(read_header);
   3260 
   3261   static const uint32_t kMinimumNonLegacyVersion = 13;
   3262   if (GetWireFormatVersion() < kMinimumNonLegacyVersion &&
   3263       !private_->supports_legacy_wire_format) {
   3264     isolate->Throw(*isolate->factory()->NewError(
   3265         i::MessageTemplate::kDataCloneDeserializationVersionError));
   3266     has_pending_exception = true;
   3267     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   3268   }
   3269 
   3270   return Just(true);
   3271 }
   3272 
   3273 void ValueDeserializer::SetSupportsLegacyWireFormat(
   3274     bool supports_legacy_wire_format) {
   3275   private_->supports_legacy_wire_format = supports_legacy_wire_format;
   3276 }
   3277 
   3278 void ValueDeserializer::SetExpectInlineWasm(bool expect_inline_wasm) {
   3279   private_->deserializer.set_expect_inline_wasm(expect_inline_wasm);
   3280 }
   3281 
   3282 uint32_t ValueDeserializer::GetWireFormatVersion() const {
   3283   CHECK(!private_->has_aborted);
   3284   return private_->deserializer.GetWireFormatVersion();
   3285 }
   3286 
   3287 MaybeLocal<Value> ValueDeserializer::ReadValue(Local<Context> context) {
   3288   CHECK(!private_->has_aborted);
   3289   PREPARE_FOR_EXECUTION(context, ValueDeserializer, ReadValue, Value);
   3290   i::MaybeHandle<i::Object> result;
   3291   if (GetWireFormatVersion() > 0) {
   3292     result = private_->deserializer.ReadObject();
   3293   } else {
   3294     result =
   3295         private_->deserializer.ReadObjectUsingEntireBufferForLegacyFormat();
   3296   }
   3297   Local<Value> value;
   3298   has_pending_exception = !ToLocal(result, &value);
   3299   RETURN_ON_FAILED_EXECUTION(Value);
   3300   RETURN_ESCAPED(value);
   3301 }
   3302 
   3303 void ValueDeserializer::TransferArrayBuffer(uint32_t transfer_id,
   3304                                             Local<ArrayBuffer> array_buffer) {
   3305   CHECK(!private_->has_aborted);
   3306   private_->deserializer.TransferArrayBuffer(transfer_id,
   3307                                              Utils::OpenHandle(*array_buffer));
   3308 }
   3309 
   3310 void ValueDeserializer::TransferSharedArrayBuffer(
   3311     uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) {
   3312   CHECK(!private_->has_aborted);
   3313   private_->deserializer.TransferArrayBuffer(
   3314       transfer_id, Utils::OpenHandle(*shared_array_buffer));
   3315 }
   3316 
   3317 bool ValueDeserializer::ReadUint32(uint32_t* value) {
   3318   return private_->deserializer.ReadUint32(value);
   3319 }
   3320 
   3321 bool ValueDeserializer::ReadUint64(uint64_t* value) {
   3322   return private_->deserializer.ReadUint64(value);
   3323 }
   3324 
   3325 bool ValueDeserializer::ReadDouble(double* value) {
   3326   return private_->deserializer.ReadDouble(value);
   3327 }
   3328 
   3329 bool ValueDeserializer::ReadRawBytes(size_t length, const void** data) {
   3330   return private_->deserializer.ReadRawBytes(length, data);
   3331 }
   3332 
   3333 // --- D a t a ---
   3334 
   3335 bool Value::FullIsUndefined() const {
   3336   i::Handle<i::Object> object = Utils::OpenHandle(this);
   3337   bool result = object->IsUndefined();
   3338   DCHECK_EQ(result, QuickIsUndefined());
   3339   return result;
   3340 }
   3341 
   3342 
   3343 bool Value::FullIsNull() const {
   3344   i::Handle<i::Object> object = Utils::OpenHandle(this);
   3345   bool result = object->IsNull();
   3346   DCHECK_EQ(result, QuickIsNull());
   3347   return result;
   3348 }
   3349 
   3350 
   3351 bool Value::IsTrue() const {
   3352   i::Handle<i::Object> object = Utils::OpenHandle(this);
   3353   if (object->IsSmi()) return false;
   3354   return object->IsTrue();
   3355 }
   3356 
   3357 
   3358 bool Value::IsFalse() const {
   3359   i::Handle<i::Object> object = Utils::OpenHandle(this);
   3360   if (object->IsSmi()) return false;
   3361   return object->IsFalse();
   3362 }
   3363 
   3364 
   3365 bool Value::IsFunction() const { return Utils::OpenHandle(this)->IsCallable(); }
   3366 
   3367 
   3368 bool Value::IsName() const {
   3369   return Utils::OpenHandle(this)->IsName();
   3370 }
   3371 
   3372 
   3373 bool Value::FullIsString() const {
   3374   bool result = Utils::OpenHandle(this)->IsString();
   3375   DCHECK_EQ(result, QuickIsString());
   3376   return result;
   3377 }
   3378 
   3379 
   3380 bool Value::IsSymbol() const {
   3381   return Utils::OpenHandle(this)->IsSymbol();
   3382 }
   3383 
   3384 
   3385 bool Value::IsArray() const {
   3386   return Utils::OpenHandle(this)->IsJSArray();
   3387 }
   3388 
   3389 
   3390 bool Value::IsArrayBuffer() const {
   3391   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3392   return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
   3393 }
   3394 
   3395 
   3396 bool Value::IsArrayBufferView() const {
   3397   return Utils::OpenHandle(this)->IsJSArrayBufferView();
   3398 }
   3399 
   3400 
   3401 bool Value::IsTypedArray() const {
   3402   return Utils::OpenHandle(this)->IsJSTypedArray();
   3403 }
   3404 
   3405 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype)                    \
   3406   bool Value::Is##Type##Array() const {                                      \
   3407     i::Handle<i::Object> obj = Utils::OpenHandle(this);                      \
   3408     return obj->IsJSTypedArray() &&                                          \
   3409            i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
   3410   }
   3411 
   3412 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
   3413 
   3414 #undef VALUE_IS_TYPED_ARRAY
   3415 
   3416 
   3417 bool Value::IsDataView() const {
   3418   return Utils::OpenHandle(this)->IsJSDataView();
   3419 }
   3420 
   3421 
   3422 bool Value::IsSharedArrayBuffer() const {
   3423   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3424   return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
   3425 }
   3426 
   3427 
   3428 bool Value::IsObject() const { return Utils::OpenHandle(this)->IsJSReceiver(); }
   3429 
   3430 
   3431 bool Value::IsNumber() const {
   3432   return Utils::OpenHandle(this)->IsNumber();
   3433 }
   3434 
   3435 bool Value::IsBigInt() const { return Utils::OpenHandle(this)->IsBigInt(); }
   3436 
   3437 bool Value::IsProxy() const { return Utils::OpenHandle(this)->IsJSProxy(); }
   3438 
   3439 #define VALUE_IS_SPECIFIC_TYPE(Type, Check)             \
   3440   bool Value::Is##Type() const {                        \
   3441     i::Handle<i::Object> obj = Utils::OpenHandle(this); \
   3442     return obj->Is##Check();                            \
   3443   }
   3444 
   3445 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, JSArgumentsObject)
   3446 VALUE_IS_SPECIFIC_TYPE(BigIntObject, BigIntWrapper)
   3447 VALUE_IS_SPECIFIC_TYPE(BooleanObject, BooleanWrapper)
   3448 VALUE_IS_SPECIFIC_TYPE(NumberObject, NumberWrapper)
   3449 VALUE_IS_SPECIFIC_TYPE(StringObject, StringWrapper)
   3450 VALUE_IS_SPECIFIC_TYPE(SymbolObject, SymbolWrapper)
   3451 VALUE_IS_SPECIFIC_TYPE(Date, JSDate)
   3452 VALUE_IS_SPECIFIC_TYPE(Map, JSMap)
   3453 VALUE_IS_SPECIFIC_TYPE(Set, JSSet)
   3454 VALUE_IS_SPECIFIC_TYPE(WeakMap, JSWeakMap)
   3455 VALUE_IS_SPECIFIC_TYPE(WeakSet, JSWeakSet)
   3456 VALUE_IS_SPECIFIC_TYPE(WebAssemblyCompiledModule, WasmModuleObject)
   3457 
   3458 #undef VALUE_IS_SPECIFIC_TYPE
   3459 
   3460 
   3461 bool Value::IsBoolean() const {
   3462   return Utils::OpenHandle(this)->IsBoolean();
   3463 }
   3464 
   3465 bool Value::IsExternal() const {
   3466   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3467   if (!obj->IsHeapObject()) return false;
   3468   i::Handle<i::HeapObject> heap_obj = i::Handle<i::HeapObject>::cast(obj);
   3469   // Check the instance type is JS_OBJECT (instance type of Externals) before
   3470   // attempting to get the Isolate since that guarantees the object is writable
   3471   // and GetIsolate will work.
   3472   if (heap_obj->map()->instance_type() != i::JS_OBJECT_TYPE) return false;
   3473   i::Isolate* isolate = i::JSObject::cast(*heap_obj)->GetIsolate();
   3474   return heap_obj->IsExternal(isolate);
   3475 }
   3476 
   3477 
   3478 bool Value::IsInt32() const {
   3479   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3480   if (obj->IsSmi()) return true;
   3481   if (obj->IsNumber()) {
   3482     return i::IsInt32Double(obj->Number());
   3483   }
   3484   return false;
   3485 }
   3486 
   3487 
   3488 bool Value::IsUint32() const {
   3489   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3490   if (obj->IsSmi()) return i::Smi::ToInt(*obj) >= 0;
   3491   if (obj->IsNumber()) {
   3492     double value = obj->Number();
   3493     return !i::IsMinusZero(value) &&
   3494         value >= 0 &&
   3495         value <= i::kMaxUInt32 &&
   3496         value == i::FastUI2D(i::FastD2UI(value));
   3497   }
   3498   return false;
   3499 }
   3500 
   3501 
   3502 bool Value::IsNativeError() const {
   3503   return Utils::OpenHandle(this)->IsJSError();
   3504 }
   3505 
   3506 
   3507 bool Value::IsRegExp() const {
   3508   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3509   return obj->IsJSRegExp();
   3510 }
   3511 
   3512 bool Value::IsAsyncFunction() const {
   3513   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3514   if (!obj->IsJSFunction()) return false;
   3515   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
   3516   return i::IsAsyncFunction(func->shared()->kind());
   3517 }
   3518 
   3519 bool Value::IsGeneratorFunction() const {
   3520   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3521   if (!obj->IsJSFunction()) return false;
   3522   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
   3523   return i::IsGeneratorFunction(func->shared()->kind());
   3524 }
   3525 
   3526 
   3527 bool Value::IsGeneratorObject() const {
   3528   return Utils::OpenHandle(this)->IsJSGeneratorObject();
   3529 }
   3530 
   3531 
   3532 bool Value::IsMapIterator() const {
   3533   return Utils::OpenHandle(this)->IsJSMapIterator();
   3534 }
   3535 
   3536 
   3537 bool Value::IsSetIterator() const {
   3538   return Utils::OpenHandle(this)->IsJSSetIterator();
   3539 }
   3540 
   3541 bool Value::IsPromise() const { return Utils::OpenHandle(this)->IsJSPromise(); }
   3542 
   3543 bool Value::IsModuleNamespaceObject() const {
   3544   return Utils::OpenHandle(this)->IsJSModuleNamespace();
   3545 }
   3546 
   3547 MaybeLocal<String> Value::ToString(Local<Context> context) const {
   3548   auto obj = Utils::OpenHandle(this);
   3549   if (obj->IsString()) return ToApiHandle<String>(obj);
   3550   PREPARE_FOR_EXECUTION(context, Object, ToString, String);
   3551   Local<String> result;
   3552   has_pending_exception =
   3553       !ToLocal<String>(i::Object::ToString(isolate, obj), &result);
   3554   RETURN_ON_FAILED_EXECUTION(String);
   3555   RETURN_ESCAPED(result);
   3556 }
   3557 
   3558 
   3559 Local<String> Value::ToString(Isolate* isolate) const {
   3560   RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
   3561 }
   3562 
   3563 
   3564 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
   3565   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3566   if (obj->IsString()) return ToApiHandle<String>(obj);
   3567   PREPARE_FOR_EXECUTION(context, Object, ToDetailString, String);
   3568   Local<String> result =
   3569       Utils::ToLocal(i::Object::NoSideEffectsToString(isolate, obj));
   3570   RETURN_ON_FAILED_EXECUTION(String);
   3571   RETURN_ESCAPED(result);
   3572 }
   3573 
   3574 
   3575 MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
   3576   auto obj = Utils::OpenHandle(this);
   3577   if (obj->IsJSReceiver()) return ToApiHandle<Object>(obj);
   3578   PREPARE_FOR_EXECUTION(context, Object, ToObject, Object);
   3579   Local<Object> result;
   3580   has_pending_exception =
   3581       !ToLocal<Object>(i::Object::ToObject(isolate, obj), &result);
   3582   RETURN_ON_FAILED_EXECUTION(Object);
   3583   RETURN_ESCAPED(result);
   3584 }
   3585 
   3586 
   3587 Local<v8::Object> Value::ToObject(Isolate* isolate) const {
   3588   RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
   3589 }
   3590 
   3591 MaybeLocal<BigInt> Value::ToBigInt(Local<Context> context) const {
   3592   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   3593   if (obj->IsBigInt()) return ToApiHandle<BigInt>(obj);
   3594   PREPARE_FOR_EXECUTION(context, Object, ToBigInt, BigInt);
   3595   Local<BigInt> result;
   3596   has_pending_exception =
   3597       !ToLocal<BigInt>(i::BigInt::FromObject(isolate, obj), &result);
   3598   RETURN_ON_FAILED_EXECUTION(BigInt);
   3599   RETURN_ESCAPED(result);
   3600 }
   3601 
   3602 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
   3603   auto obj = Utils::OpenHandle(this);
   3604   if (obj->IsBoolean()) return ToApiHandle<Boolean>(obj);
   3605   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   3606   auto val = isolate->factory()->ToBoolean(obj->BooleanValue(isolate));
   3607   return ToApiHandle<Boolean>(val);
   3608 }
   3609 
   3610 
   3611 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
   3612   return ToBoolean(v8_isolate->GetCurrentContext()).ToLocalChecked();
   3613 }
   3614 
   3615 
   3616 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
   3617   auto obj = Utils::OpenHandle(this);
   3618   if (obj->IsNumber()) return ToApiHandle<Number>(obj);
   3619   PREPARE_FOR_EXECUTION(context, Object, ToNumber, Number);
   3620   Local<Number> result;
   3621   has_pending_exception =
   3622       !ToLocal<Number>(i::Object::ToNumber(isolate, obj), &result);
   3623   RETURN_ON_FAILED_EXECUTION(Number);
   3624   RETURN_ESCAPED(result);
   3625 }
   3626 
   3627 
   3628 Local<Number> Value::ToNumber(Isolate* isolate) const {
   3629   RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
   3630 }
   3631 
   3632 
   3633 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
   3634   auto obj = Utils::OpenHandle(this);
   3635   if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
   3636   PREPARE_FOR_EXECUTION(context, Object, ToInteger, Integer);
   3637   Local<Integer> result;
   3638   has_pending_exception =
   3639       !ToLocal<Integer>(i::Object::ToInteger(isolate, obj), &result);
   3640   RETURN_ON_FAILED_EXECUTION(Integer);
   3641   RETURN_ESCAPED(result);
   3642 }
   3643 
   3644 
   3645 Local<Integer> Value::ToInteger(Isolate* isolate) const {
   3646   RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
   3647 }
   3648 
   3649 
   3650 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
   3651   auto obj = Utils::OpenHandle(this);
   3652   if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
   3653   Local<Int32> result;
   3654   PREPARE_FOR_EXECUTION(context, Object, ToInt32, Int32);
   3655   has_pending_exception =
   3656       !ToLocal<Int32>(i::Object::ToInt32(isolate, obj), &result);
   3657   RETURN_ON_FAILED_EXECUTION(Int32);
   3658   RETURN_ESCAPED(result);
   3659 }
   3660 
   3661 
   3662 Local<Int32> Value::ToInt32(Isolate* isolate) const {
   3663   RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
   3664 }
   3665 
   3666 
   3667 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
   3668   auto obj = Utils::OpenHandle(this);
   3669   if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
   3670   Local<Uint32> result;
   3671   PREPARE_FOR_EXECUTION(context, Object, ToUint32, Uint32);
   3672   has_pending_exception =
   3673       !ToLocal<Uint32>(i::Object::ToUint32(isolate, obj), &result);
   3674   RETURN_ON_FAILED_EXECUTION(Uint32);
   3675   RETURN_ESCAPED(result);
   3676 }
   3677 
   3678 
   3679 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
   3680   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
   3681   Utils::ApiCheck(isolate != nullptr && !isolate->IsDead(),
   3682                   "v8::internal::Internals::CheckInitialized",
   3683                   "Isolate is not initialized or V8 has died");
   3684 }
   3685 
   3686 
   3687 void External::CheckCast(v8::Value* that) {
   3688   Utils::ApiCheck(that->IsExternal(), "v8::External::Cast",
   3689                   "Could not convert to external");
   3690 }
   3691 
   3692 
   3693 void v8::Object::CheckCast(Value* that) {
   3694   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3695   Utils::ApiCheck(obj->IsJSReceiver(), "v8::Object::Cast",
   3696                   "Could not convert to object");
   3697 }
   3698 
   3699 
   3700 void v8::Function::CheckCast(Value* that) {
   3701   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3702   Utils::ApiCheck(obj->IsCallable(), "v8::Function::Cast",
   3703                   "Could not convert to function");
   3704 }
   3705 
   3706 
   3707 void v8::Boolean::CheckCast(v8::Value* that) {
   3708   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3709   Utils::ApiCheck(obj->IsBoolean(), "v8::Boolean::Cast",
   3710                   "Could not convert to boolean");
   3711 }
   3712 
   3713 
   3714 void v8::Name::CheckCast(v8::Value* that) {
   3715   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3716   Utils::ApiCheck(obj->IsName(), "v8::Name::Cast", "Could not convert to name");
   3717 }
   3718 
   3719 
   3720 void v8::String::CheckCast(v8::Value* that) {
   3721   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3722   Utils::ApiCheck(obj->IsString(), "v8::String::Cast",
   3723                   "Could not convert to string");
   3724 }
   3725 
   3726 
   3727 void v8::Symbol::CheckCast(v8::Value* that) {
   3728   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3729   Utils::ApiCheck(obj->IsSymbol(), "v8::Symbol::Cast",
   3730                   "Could not convert to symbol");
   3731 }
   3732 
   3733 
   3734 void v8::Private::CheckCast(v8::Data* that) {
   3735   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3736   Utils::ApiCheck(obj->IsSymbol() &&
   3737                   i::Handle<i::Symbol>::cast(obj)->is_private(),
   3738                   "v8::Private::Cast",
   3739                   "Could not convert to private");
   3740 }
   3741 
   3742 
   3743 void v8::Number::CheckCast(v8::Value* that) {
   3744   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3745   Utils::ApiCheck(obj->IsNumber(),
   3746                   "v8::Number::Cast()",
   3747                   "Could not convert to number");
   3748 }
   3749 
   3750 
   3751 void v8::Integer::CheckCast(v8::Value* that) {
   3752   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3753   Utils::ApiCheck(obj->IsNumber(), "v8::Integer::Cast",
   3754                   "Could not convert to number");
   3755 }
   3756 
   3757 
   3758 void v8::Int32::CheckCast(v8::Value* that) {
   3759   Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast",
   3760                   "Could not convert to 32-bit signed integer");
   3761 }
   3762 
   3763 
   3764 void v8::Uint32::CheckCast(v8::Value* that) {
   3765   Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast",
   3766                   "Could not convert to 32-bit unsigned integer");
   3767 }
   3768 
   3769 void v8::BigInt::CheckCast(v8::Value* that) {
   3770   Utils::ApiCheck(that->IsBigInt(), "v8::BigInt::Cast",
   3771                   "Could not convert to BigInt");
   3772 }
   3773 
   3774 void v8::Array::CheckCast(Value* that) {
   3775   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3776   Utils::ApiCheck(obj->IsJSArray(), "v8::Array::Cast",
   3777                   "Could not convert to array");
   3778 }
   3779 
   3780 
   3781 void v8::Map::CheckCast(Value* that) {
   3782   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3783   Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast", "Could not convert to Map");
   3784 }
   3785 
   3786 
   3787 void v8::Set::CheckCast(Value* that) {
   3788   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3789   Utils::ApiCheck(obj->IsJSSet(), "v8_Set_Cast", "Could not convert to Set");
   3790 }
   3791 
   3792 
   3793 void v8::Promise::CheckCast(Value* that) {
   3794   Utils::ApiCheck(that->IsPromise(), "v8::Promise::Cast",
   3795                   "Could not convert to promise");
   3796 }
   3797 
   3798 
   3799 void v8::Promise::Resolver::CheckCast(Value* that) {
   3800   Utils::ApiCheck(that->IsPromise(), "v8::Promise::Resolver::Cast",
   3801                   "Could not convert to promise resolver");
   3802 }
   3803 
   3804 
   3805 void v8::Proxy::CheckCast(Value* that) {
   3806   Utils::ApiCheck(that->IsProxy(), "v8::Proxy::Cast",
   3807                   "Could not convert to proxy");
   3808 }
   3809 
   3810 void v8::WasmCompiledModule::CheckCast(Value* that) {
   3811   Utils::ApiCheck(that->IsWebAssemblyCompiledModule(),
   3812                   "v8::WasmCompiledModule::Cast",
   3813                   "Could not convert to wasm compiled module");
   3814 }
   3815 
   3816 void v8::ArrayBuffer::CheckCast(Value* that) {
   3817   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3818   Utils::ApiCheck(
   3819       obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
   3820       "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
   3821 }
   3822 
   3823 
   3824 void v8::ArrayBufferView::CheckCast(Value* that) {
   3825   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3826   Utils::ApiCheck(obj->IsJSArrayBufferView(),
   3827                   "v8::ArrayBufferView::Cast()",
   3828                   "Could not convert to ArrayBufferView");
   3829 }
   3830 
   3831 
   3832 void v8::TypedArray::CheckCast(Value* that) {
   3833   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3834   Utils::ApiCheck(obj->IsJSTypedArray(),
   3835                   "v8::TypedArray::Cast()",
   3836                   "Could not convert to TypedArray");
   3837 }
   3838 
   3839 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype)                   \
   3840   void v8::Type##Array::CheckCast(Value* that) {                              \
   3841     i::Handle<i::Object> obj = Utils::OpenHandle(that);                       \
   3842     Utils::ApiCheck(                                                          \
   3843         obj->IsJSTypedArray() &&                                              \
   3844             i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
   3845         "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
   3846   }
   3847 
   3848 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
   3849 
   3850 #undef CHECK_TYPED_ARRAY_CAST
   3851 
   3852 
   3853 void v8::DataView::CheckCast(Value* that) {
   3854   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3855   Utils::ApiCheck(obj->IsJSDataView(),
   3856                   "v8::DataView::Cast()",
   3857                   "Could not convert to DataView");
   3858 }
   3859 
   3860 
   3861 void v8::SharedArrayBuffer::CheckCast(Value* that) {
   3862   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3863   Utils::ApiCheck(
   3864       obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
   3865       "v8::SharedArrayBuffer::Cast()",
   3866       "Could not convert to SharedArrayBuffer");
   3867 }
   3868 
   3869 
   3870 void v8::Date::CheckCast(v8::Value* that) {
   3871   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3872   Utils::ApiCheck(obj->IsJSDate(), "v8::Date::Cast()",
   3873                   "Could not convert to date");
   3874 }
   3875 
   3876 
   3877 void v8::StringObject::CheckCast(v8::Value* that) {
   3878   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3879   Utils::ApiCheck(obj->IsStringWrapper(), "v8::StringObject::Cast()",
   3880                   "Could not convert to StringObject");
   3881 }
   3882 
   3883 
   3884 void v8::SymbolObject::CheckCast(v8::Value* that) {
   3885   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3886   Utils::ApiCheck(obj->IsSymbolWrapper(), "v8::SymbolObject::Cast()",
   3887                   "Could not convert to SymbolObject");
   3888 }
   3889 
   3890 
   3891 void v8::NumberObject::CheckCast(v8::Value* that) {
   3892   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3893   Utils::ApiCheck(obj->IsNumberWrapper(), "v8::NumberObject::Cast()",
   3894                   "Could not convert to NumberObject");
   3895 }
   3896 
   3897 void v8::BigIntObject::CheckCast(v8::Value* that) {
   3898   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3899   Utils::ApiCheck(obj->IsBigIntWrapper(), "v8::BigIntObject::Cast()",
   3900                   "Could not convert to BigIntObject");
   3901 }
   3902 
   3903 void v8::BooleanObject::CheckCast(v8::Value* that) {
   3904   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3905   Utils::ApiCheck(obj->IsBooleanWrapper(), "v8::BooleanObject::Cast()",
   3906                   "Could not convert to BooleanObject");
   3907 }
   3908 
   3909 
   3910 void v8::RegExp::CheckCast(v8::Value* that) {
   3911   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   3912   Utils::ApiCheck(obj->IsJSRegExp(),
   3913                   "v8::RegExp::Cast()",
   3914                   "Could not convert to regular expression");
   3915 }
   3916 
   3917 
   3918 Maybe<bool> Value::BooleanValue(Local<Context> context) const {
   3919   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   3920   return Just(Utils::OpenHandle(this)->BooleanValue(isolate));
   3921 }
   3922 
   3923 bool Value::BooleanValue() const {
   3924   auto obj = Utils::OpenHandle(this);
   3925   if (obj->IsSmi()) return *obj != i::Smi::kZero;
   3926   DCHECK(obj->IsHeapObject());
   3927   i::Isolate* isolate =
   3928       UnsafeIsolateFromHeapObject(i::Handle<i::HeapObject>::cast(obj));
   3929   return obj->BooleanValue(isolate);
   3930 }
   3931 
   3932 Maybe<double> Value::NumberValue(Local<Context> context) const {
   3933   auto obj = Utils::OpenHandle(this);
   3934   if (obj->IsNumber()) return Just(obj->Number());
   3935   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   3936   ENTER_V8(isolate, context, Value, NumberValue, Nothing<double>(),
   3937            i::HandleScope);
   3938   i::Handle<i::Object> num;
   3939   has_pending_exception = !i::Object::ToNumber(isolate, obj).ToHandle(&num);
   3940   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
   3941   return Just(num->Number());
   3942 }
   3943 
   3944 double Value::NumberValue() const {
   3945   auto obj = Utils::OpenHandle(this);
   3946   if (obj->IsNumber()) return obj->Number();
   3947   return NumberValue(UnsafeContextFromHeapObject(obj))
   3948       .FromMaybe(std::numeric_limits<double>::quiet_NaN());
   3949 }
   3950 
   3951 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
   3952   auto obj = Utils::OpenHandle(this);
   3953   if (obj->IsNumber()) {
   3954     return Just(NumberToInt64(*obj));
   3955   }
   3956   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   3957   ENTER_V8(isolate, context, Value, IntegerValue, Nothing<int64_t>(),
   3958            i::HandleScope);
   3959   i::Handle<i::Object> num;
   3960   has_pending_exception = !i::Object::ToInteger(isolate, obj).ToHandle(&num);
   3961   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
   3962   return Just(NumberToInt64(*num));
   3963 }
   3964 
   3965 int64_t Value::IntegerValue() const {
   3966   auto obj = Utils::OpenHandle(this);
   3967   if (obj->IsNumber()) {
   3968     if (obj->IsSmi()) {
   3969       return i::Smi::ToInt(*obj);
   3970     } else {
   3971       return static_cast<int64_t>(obj->Number());
   3972     }
   3973   }
   3974   return IntegerValue(UnsafeContextFromHeapObject(obj)).FromMaybe(0);
   3975 }
   3976 
   3977 Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
   3978   auto obj = Utils::OpenHandle(this);
   3979   if (obj->IsNumber()) return Just(NumberToInt32(*obj));
   3980   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   3981   ENTER_V8(isolate, context, Value, Int32Value, Nothing<int32_t>(),
   3982            i::HandleScope);
   3983   i::Handle<i::Object> num;
   3984   has_pending_exception = !i::Object::ToInt32(isolate, obj).ToHandle(&num);
   3985   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
   3986   return Just(num->IsSmi() ? i::Smi::ToInt(*num)
   3987                            : static_cast<int32_t>(num->Number()));
   3988 }
   3989 
   3990 int32_t Value::Int32Value() const {
   3991   auto obj = Utils::OpenHandle(this);
   3992   if (obj->IsNumber()) return NumberToInt32(*obj);
   3993   return Int32Value(UnsafeContextFromHeapObject(obj)).FromMaybe(0);
   3994 }
   3995 
   3996 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
   3997   auto obj = Utils::OpenHandle(this);
   3998   if (obj->IsNumber()) return Just(NumberToUint32(*obj));
   3999   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4000   ENTER_V8(isolate, context, Value, Uint32Value, Nothing<uint32_t>(),
   4001            i::HandleScope);
   4002   i::Handle<i::Object> num;
   4003   has_pending_exception = !i::Object::ToUint32(isolate, obj).ToHandle(&num);
   4004   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
   4005   return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::ToInt(*num))
   4006                            : static_cast<uint32_t>(num->Number()));
   4007 }
   4008 
   4009 uint32_t Value::Uint32Value() const {
   4010   auto obj = Utils::OpenHandle(this);
   4011   if (obj->IsNumber()) return NumberToUint32(*obj);
   4012   return Uint32Value(UnsafeContextFromHeapObject(obj)).FromMaybe(0);
   4013 }
   4014 
   4015 MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const {
   4016   auto self = Utils::OpenHandle(this);
   4017   if (self->IsSmi()) {
   4018     if (i::Smi::ToInt(*self) >= 0) return Utils::Uint32ToLocal(self);
   4019     return Local<Uint32>();
   4020   }
   4021   PREPARE_FOR_EXECUTION(context, Object, ToArrayIndex, Uint32);
   4022   i::Handle<i::Object> string_obj;
   4023   has_pending_exception =
   4024       !i::Object::ToString(isolate, self).ToHandle(&string_obj);
   4025   RETURN_ON_FAILED_EXECUTION(Uint32);
   4026   i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
   4027   uint32_t index;
   4028   if (str->AsArrayIndex(&index)) {
   4029     i::Handle<i::Object> value;
   4030     if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
   4031       value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
   4032     } else {
   4033       value = isolate->factory()->NewNumber(index);
   4034     }
   4035     RETURN_ESCAPED(Utils::Uint32ToLocal(value));
   4036   }
   4037   return Local<Uint32>();
   4038 }
   4039 
   4040 
   4041 Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const {
   4042   i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
   4043   auto self = Utils::OpenHandle(this);
   4044   auto other = Utils::OpenHandle(*that);
   4045   return i::Object::Equals(isolate, self, other);
   4046 }
   4047 
   4048 bool Value::Equals(Local<Value> that) const {
   4049   auto self = Utils::OpenHandle(this);
   4050   auto other = Utils::OpenHandle(*that);
   4051   if (self->IsSmi() && other->IsSmi()) {
   4052     return self->Number() == other->Number();
   4053   }
   4054   if (self->IsJSObject() && other->IsJSObject()) {
   4055     return *self == *other;
   4056   }
   4057   auto heap_object = self->IsSmi() ? other : self;
   4058   auto context = UnsafeContextFromHeapObject(heap_object);
   4059   return Equals(context, that).FromMaybe(false);
   4060 }
   4061 
   4062 bool Value::StrictEquals(Local<Value> that) const {
   4063   auto self = Utils::OpenHandle(this);
   4064   auto other = Utils::OpenHandle(*that);
   4065   return self->StrictEquals(*other);
   4066 }
   4067 
   4068 
   4069 bool Value::SameValue(Local<Value> that) const {
   4070   auto self = Utils::OpenHandle(this);
   4071   auto other = Utils::OpenHandle(*that);
   4072   return self->SameValue(*other);
   4073 }
   4074 
   4075 Local<String> Value::TypeOf(v8::Isolate* external_isolate) {
   4076   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
   4077   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   4078   LOG_API(isolate, Value, TypeOf);
   4079   return Utils::ToLocal(i::Object::TypeOf(isolate, Utils::OpenHandle(this)));
   4080 }
   4081 
   4082 Maybe<bool> Value::InstanceOf(v8::Local<v8::Context> context,
   4083                               v8::Local<v8::Object> object) {
   4084   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4085   ENTER_V8(isolate, context, Value, InstanceOf, Nothing<bool>(),
   4086            i::HandleScope);
   4087   auto left = Utils::OpenHandle(this);
   4088   auto right = Utils::OpenHandle(*object);
   4089   i::Handle<i::Object> result;
   4090   has_pending_exception =
   4091       !i::Object::InstanceOf(isolate, left, right).ToHandle(&result);
   4092   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4093   return Just(result->IsTrue(isolate));
   4094 }
   4095 
   4096 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
   4097                             v8::Local<Value> key, v8::Local<Value> value) {
   4098   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4099   ENTER_V8(isolate, context, Object, Set, Nothing<bool>(), i::HandleScope);
   4100   auto self = Utils::OpenHandle(this);
   4101   auto key_obj = Utils::OpenHandle(*key);
   4102   auto value_obj = Utils::OpenHandle(*value);
   4103   has_pending_exception =
   4104       i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
   4105                                     i::LanguageMode::kSloppy)
   4106           .is_null();
   4107   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4108   return Just(true);
   4109 }
   4110 
   4111 
   4112 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
   4113   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4114   return Set(context, key, value).FromMaybe(false);
   4115 }
   4116 
   4117 
   4118 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
   4119                             v8::Local<Value> value) {
   4120   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4121   ENTER_V8(isolate, context, Object, Set, Nothing<bool>(), i::HandleScope);
   4122   auto self = Utils::OpenHandle(this);
   4123   auto value_obj = Utils::OpenHandle(*value);
   4124   has_pending_exception = i::Object::SetElement(isolate, self, index, value_obj,
   4125                                                 i::LanguageMode::kSloppy)
   4126                               .is_null();
   4127   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4128   return Just(true);
   4129 }
   4130 
   4131 
   4132 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
   4133   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4134   return Set(context, index, value).FromMaybe(false);
   4135 }
   4136 
   4137 
   4138 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
   4139                                            v8::Local<Name> key,
   4140                                            v8::Local<Value> value) {
   4141   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4142   ENTER_V8(isolate, context, Object, CreateDataProperty, Nothing<bool>(),
   4143            i::HandleScope);
   4144   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
   4145   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
   4146   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
   4147 
   4148   Maybe<bool> result = i::JSReceiver::CreateDataProperty(
   4149       isolate, self, key_obj, value_obj, i::kDontThrow);
   4150   has_pending_exception = result.IsNothing();
   4151   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4152   return result;
   4153 }
   4154 
   4155 
   4156 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
   4157                                            uint32_t index,
   4158                                            v8::Local<Value> value) {
   4159   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4160   ENTER_V8(isolate, context, Object, CreateDataProperty, Nothing<bool>(),
   4161            i::HandleScope);
   4162   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
   4163   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
   4164 
   4165   i::LookupIterator it(isolate, self, index, self, i::LookupIterator::OWN);
   4166   Maybe<bool> result =
   4167       i::JSReceiver::CreateDataProperty(&it, value_obj, i::kDontThrow);
   4168   has_pending_exception = result.IsNothing();
   4169   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4170   return result;
   4171 }
   4172 
   4173 struct v8::PropertyDescriptor::PrivateData {
   4174   PrivateData() : desc() {}
   4175   i::PropertyDescriptor desc;
   4176 };
   4177 
   4178 v8::PropertyDescriptor::PropertyDescriptor() : private_(new PrivateData()) {}
   4179 
   4180 // DataDescriptor
   4181 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value)
   4182     : private_(new PrivateData()) {
   4183   private_->desc.set_value(Utils::OpenHandle(*value, true));
   4184 }
   4185 
   4186 // DataDescriptor with writable field
   4187 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value,
   4188                                            bool writable)
   4189     : private_(new PrivateData()) {
   4190   private_->desc.set_value(Utils::OpenHandle(*value, true));
   4191   private_->desc.set_writable(writable);
   4192 }
   4193 
   4194 // AccessorDescriptor
   4195 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> get,
   4196                                            v8::Local<v8::Value> set)
   4197     : private_(new PrivateData()) {
   4198   DCHECK(get.IsEmpty() || get->IsUndefined() || get->IsFunction());
   4199   DCHECK(set.IsEmpty() || set->IsUndefined() || set->IsFunction());
   4200   private_->desc.set_get(Utils::OpenHandle(*get, true));
   4201   private_->desc.set_set(Utils::OpenHandle(*set, true));
   4202 }
   4203 
   4204 v8::PropertyDescriptor::~PropertyDescriptor() { delete private_; }
   4205 
   4206 v8::Local<Value> v8::PropertyDescriptor::value() const {
   4207   DCHECK(private_->desc.has_value());
   4208   return Utils::ToLocal(private_->desc.value());
   4209 }
   4210 
   4211 v8::Local<Value> v8::PropertyDescriptor::get() const {
   4212   DCHECK(private_->desc.has_get());
   4213   return Utils::ToLocal(private_->desc.get());
   4214 }
   4215 
   4216 v8::Local<Value> v8::PropertyDescriptor::set() const {
   4217   DCHECK(private_->desc.has_set());
   4218   return Utils::ToLocal(private_->desc.set());
   4219 }
   4220 
   4221 bool v8::PropertyDescriptor::has_value() const {
   4222   return private_->desc.has_value();
   4223 }
   4224 bool v8::PropertyDescriptor::has_get() const {
   4225   return private_->desc.has_get();
   4226 }
   4227 bool v8::PropertyDescriptor::has_set() const {
   4228   return private_->desc.has_set();
   4229 }
   4230 
   4231 bool v8::PropertyDescriptor::writable() const {
   4232   DCHECK(private_->desc.has_writable());
   4233   return private_->desc.writable();
   4234 }
   4235 
   4236 bool v8::PropertyDescriptor::has_writable() const {
   4237   return private_->desc.has_writable();
   4238 }
   4239 
   4240 void v8::PropertyDescriptor::set_enumerable(bool enumerable) {
   4241   private_->desc.set_enumerable(enumerable);
   4242 }
   4243 
   4244 bool v8::PropertyDescriptor::enumerable() const {
   4245   DCHECK(private_->desc.has_enumerable());
   4246   return private_->desc.enumerable();
   4247 }
   4248 
   4249 bool v8::PropertyDescriptor::has_enumerable() const {
   4250   return private_->desc.has_enumerable();
   4251 }
   4252 
   4253 void v8::PropertyDescriptor::set_configurable(bool configurable) {
   4254   private_->desc.set_configurable(configurable);
   4255 }
   4256 
   4257 bool v8::PropertyDescriptor::configurable() const {
   4258   DCHECK(private_->desc.has_configurable());
   4259   return private_->desc.configurable();
   4260 }
   4261 
   4262 bool v8::PropertyDescriptor::has_configurable() const {
   4263   return private_->desc.has_configurable();
   4264 }
   4265 
   4266 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
   4267                                           v8::Local<Name> key,
   4268                                           v8::Local<Value> value,
   4269                                           v8::PropertyAttribute attributes) {
   4270   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4271   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
   4272   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
   4273   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
   4274 
   4275   i::PropertyDescriptor desc;
   4276   desc.set_writable(!(attributes & v8::ReadOnly));
   4277   desc.set_enumerable(!(attributes & v8::DontEnum));
   4278   desc.set_configurable(!(attributes & v8::DontDelete));
   4279   desc.set_value(value_obj);
   4280 
   4281   if (self->IsJSProxy()) {
   4282     ENTER_V8(isolate, context, Object, DefineOwnProperty, Nothing<bool>(),
   4283              i::HandleScope);
   4284     Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
   4285         isolate, self, key_obj, &desc, i::kDontThrow);
   4286     // Even though we said kDontThrow, there might be accessors that do throw.
   4287     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4288     return success;
   4289   } else {
   4290     // If it's not a JSProxy, i::JSReceiver::DefineOwnProperty should never run
   4291     // a script.
   4292     ENTER_V8_NO_SCRIPT(isolate, context, Object, DefineOwnProperty,
   4293                        Nothing<bool>(), i::HandleScope);
   4294     Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
   4295         isolate, self, key_obj, &desc, i::kDontThrow);
   4296     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4297     return success;
   4298   }
   4299 }
   4300 
   4301 Maybe<bool> v8::Object::DefineProperty(v8::Local<v8::Context> context,
   4302                                        v8::Local<Name> key,
   4303                                        PropertyDescriptor& descriptor) {
   4304   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4305   ENTER_V8(isolate, context, Object, DefineOwnProperty, Nothing<bool>(),
   4306            i::HandleScope);
   4307   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
   4308   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
   4309 
   4310   Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
   4311       isolate, self, key_obj, &descriptor.get_private()->desc, i::kDontThrow);
   4312   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4313   return success;
   4314 }
   4315 
   4316 Maybe<bool> v8::Object::SetPrivate(Local<Context> context, Local<Private> key,
   4317                                    Local<Value> value) {
   4318   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4319   ENTER_V8_NO_SCRIPT(isolate, context, Object, SetPrivate, Nothing<bool>(),
   4320                      i::HandleScope);
   4321   auto self = Utils::OpenHandle(this);
   4322   auto key_obj = Utils::OpenHandle(reinterpret_cast<Name*>(*key));
   4323   auto value_obj = Utils::OpenHandle(*value);
   4324   if (self->IsJSProxy()) {
   4325     i::PropertyDescriptor desc;
   4326     desc.set_writable(true);
   4327     desc.set_enumerable(false);
   4328     desc.set_configurable(true);
   4329     desc.set_value(value_obj);
   4330     return i::JSProxy::SetPrivateSymbol(
   4331         isolate, i::Handle<i::JSProxy>::cast(self),
   4332         i::Handle<i::Symbol>::cast(key_obj), &desc, i::kDontThrow);
   4333   }
   4334   auto js_object = i::Handle<i::JSObject>::cast(self);
   4335   i::LookupIterator it(js_object, key_obj, js_object);
   4336   has_pending_exception = i::JSObject::DefineOwnPropertyIgnoreAttributes(
   4337                               &it, value_obj, i::DONT_ENUM)
   4338                               .is_null();
   4339   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4340   return Just(true);
   4341 }
   4342 
   4343 
   4344 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
   4345                                   Local<Value> key) {
   4346   PREPARE_FOR_EXECUTION(context, Object, Get, Value);
   4347   auto self = Utils::OpenHandle(this);
   4348   auto key_obj = Utils::OpenHandle(*key);
   4349   i::Handle<i::Object> result;
   4350   has_pending_exception =
   4351       !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
   4352   RETURN_ON_FAILED_EXECUTION(Value);
   4353   RETURN_ESCAPED(Utils::ToLocal(result));
   4354 }
   4355 
   4356 
   4357 Local<Value> v8::Object::Get(v8::Local<Value> key) {
   4358   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4359   RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
   4360 }
   4361 
   4362 
   4363 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
   4364   PREPARE_FOR_EXECUTION(context, Object, Get, Value);
   4365   auto self = Utils::OpenHandle(this);
   4366   i::Handle<i::Object> result;
   4367   has_pending_exception =
   4368       !i::JSReceiver::GetElement(isolate, self, index).ToHandle(&result);
   4369   RETURN_ON_FAILED_EXECUTION(Value);
   4370   RETURN_ESCAPED(Utils::ToLocal(result));
   4371 }
   4372 
   4373 
   4374 Local<Value> v8::Object::Get(uint32_t index) {
   4375   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4376   RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
   4377 }
   4378 
   4379 
   4380 MaybeLocal<Value> v8::Object::GetPrivate(Local<Context> context,
   4381                                          Local<Private> key) {
   4382   return Get(context, Local<Value>(reinterpret_cast<Value*>(*key)));
   4383 }
   4384 
   4385 
   4386 Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes(
   4387     Local<Context> context, Local<Value> key) {
   4388   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4389   ENTER_V8(isolate, context, Object, GetPropertyAttributes,
   4390            Nothing<PropertyAttribute>(), i::HandleScope);
   4391   auto self = Utils::OpenHandle(this);
   4392   auto key_obj = Utils::OpenHandle(*key);
   4393   if (!key_obj->IsName()) {
   4394     has_pending_exception =
   4395         !i::Object::ToString(isolate, key_obj).ToHandle(&key_obj);
   4396     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
   4397   }
   4398   auto key_name = i::Handle<i::Name>::cast(key_obj);
   4399   auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
   4400   has_pending_exception = result.IsNothing();
   4401   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
   4402   if (result.FromJust() == i::ABSENT) {
   4403     return Just(static_cast<PropertyAttribute>(i::NONE));
   4404   }
   4405   return Just(static_cast<PropertyAttribute>(result.FromJust()));
   4406 }
   4407 
   4408 
   4409 MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context,
   4410                                                        Local<Name> key) {
   4411   PREPARE_FOR_EXECUTION(context, Object, GetOwnPropertyDescriptor, Value);
   4412   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
   4413   i::Handle<i::Name> key_name = Utils::OpenHandle(*key);
   4414 
   4415   i::PropertyDescriptor desc;
   4416   Maybe<bool> found =
   4417       i::JSReceiver::GetOwnPropertyDescriptor(isolate, obj, key_name, &desc);
   4418   has_pending_exception = found.IsNothing();
   4419   RETURN_ON_FAILED_EXECUTION(Value);
   4420   if (!found.FromJust()) {
   4421     return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   4422   }
   4423   RETURN_ESCAPED(Utils::ToLocal(desc.ToObject(isolate)));
   4424 }
   4425 
   4426 
   4427 Local<Value> v8::Object::GetPrototype() {
   4428   auto isolate = Utils::OpenHandle(this)->GetIsolate();
   4429   auto self = Utils::OpenHandle(this);
   4430   i::PrototypeIterator iter(isolate, self);
   4431   return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
   4432 }
   4433 
   4434 
   4435 Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
   4436                                      Local<Value> value) {
   4437   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4438   ENTER_V8(isolate, context, Object, SetPrototype, Nothing<bool>(),
   4439            i::HandleScope);
   4440   auto self = Utils::OpenHandle(this);
   4441   auto value_obj = Utils::OpenHandle(*value);
   4442   // We do not allow exceptions thrown while setting the prototype
   4443   // to propagate outside.
   4444   TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
   4445   auto result =
   4446       i::JSReceiver::SetPrototype(self, value_obj, false, i::kThrowOnError);
   4447   has_pending_exception = result.IsNothing();
   4448   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4449   return Just(true);
   4450 }
   4451 
   4452 
   4453 Local<Object> v8::Object::FindInstanceInPrototypeChain(
   4454     v8::Local<FunctionTemplate> tmpl) {
   4455   auto self = Utils::OpenHandle(this);
   4456   auto isolate = self->GetIsolate();
   4457   i::PrototypeIterator iter(isolate, *self, i::kStartAtReceiver);
   4458   auto tmpl_info = *Utils::OpenHandle(*tmpl);
   4459   while (!tmpl_info->IsTemplateFor(iter.GetCurrent<i::JSObject>())) {
   4460     iter.Advance();
   4461     if (iter.IsAtEnd()) return Local<Object>();
   4462     if (!iter.GetCurrent()->IsJSObject()) return Local<Object>();
   4463   }
   4464   // IsTemplateFor() ensures that iter.GetCurrent() can't be a Proxy here.
   4465   return Utils::ToLocal(i::handle(iter.GetCurrent<i::JSObject>(), isolate));
   4466 }
   4467 
   4468 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
   4469   return GetPropertyNames(
   4470       context, v8::KeyCollectionMode::kIncludePrototypes,
   4471       static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS),
   4472       v8::IndexFilter::kIncludeIndices);
   4473 }
   4474 
   4475 MaybeLocal<Array> v8::Object::GetPropertyNames(
   4476     Local<Context> context, KeyCollectionMode mode,
   4477     PropertyFilter property_filter, IndexFilter index_filter,
   4478     KeyConversionMode key_conversion) {
   4479   PREPARE_FOR_EXECUTION(context, Object, GetPropertyNames, Array);
   4480   auto self = Utils::OpenHandle(this);
   4481   i::Handle<i::FixedArray> value;
   4482   i::KeyAccumulator accumulator(
   4483       isolate, static_cast<i::KeyCollectionMode>(mode),
   4484       static_cast<i::PropertyFilter>(property_filter));
   4485   accumulator.set_skip_indices(index_filter == IndexFilter::kSkipIndices);
   4486   has_pending_exception = accumulator.CollectKeys(self, self).IsNothing();
   4487   RETURN_ON_FAILED_EXECUTION(Array);
   4488   value =
   4489       accumulator.GetKeys(static_cast<i::GetKeysConversion>(key_conversion));
   4490   DCHECK(self->map()->EnumLength() == i::kInvalidEnumCacheSentinel ||
   4491          self->map()->EnumLength() == 0 ||
   4492          self->map()->instance_descriptors()->GetEnumCache()->keys() != *value);
   4493   auto result = isolate->factory()->NewJSArrayWithElements(value);
   4494   RETURN_ESCAPED(Utils::ToLocal(result));
   4495 }
   4496 
   4497 
   4498 Local<Array> v8::Object::GetPropertyNames() {
   4499   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4500   RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array);
   4501 }
   4502 
   4503 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
   4504   return GetOwnPropertyNames(
   4505       context, static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS));
   4506 }
   4507 
   4508 Local<Array> v8::Object::GetOwnPropertyNames() {
   4509   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4510   RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array);
   4511 }
   4512 
   4513 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(
   4514     Local<Context> context, PropertyFilter filter,
   4515     KeyConversionMode key_conversion) {
   4516   return GetPropertyNames(context, KeyCollectionMode::kOwnOnly, filter,
   4517                           v8::IndexFilter::kIncludeIndices, key_conversion);
   4518 }
   4519 
   4520 MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) {
   4521   PREPARE_FOR_EXECUTION(context, Object, ObjectProtoToString, String);
   4522   auto self = Utils::OpenHandle(this);
   4523   Local<Value> result;
   4524   has_pending_exception =
   4525       !ToLocal<Value>(i::Execution::Call(isolate, isolate->object_to_string(),
   4526                                          self, 0, nullptr),
   4527                       &result);
   4528   RETURN_ON_FAILED_EXECUTION(String);
   4529   RETURN_ESCAPED(Local<String>::Cast(result));
   4530 }
   4531 
   4532 
   4533 Local<String> v8::Object::GetConstructorName() {
   4534   auto self = Utils::OpenHandle(this);
   4535   i::Handle<i::String> name = i::JSReceiver::GetConstructorName(self);
   4536   return Utils::ToLocal(name);
   4537 }
   4538 
   4539 Maybe<bool> v8::Object::SetIntegrityLevel(Local<Context> context,
   4540                                           IntegrityLevel level) {
   4541   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4542   ENTER_V8(isolate, context, Object, SetIntegrityLevel, Nothing<bool>(),
   4543            i::HandleScope);
   4544   auto self = Utils::OpenHandle(this);
   4545   i::JSReceiver::IntegrityLevel i_level =
   4546       level == IntegrityLevel::kFrozen ? i::FROZEN : i::SEALED;
   4547   Maybe<bool> result =
   4548       i::JSReceiver::SetIntegrityLevel(self, i_level, i::kThrowOnError);
   4549   has_pending_exception = result.IsNothing();
   4550   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4551   return result;
   4552 }
   4553 
   4554 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
   4555   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4556   auto self = Utils::OpenHandle(this);
   4557   auto key_obj = Utils::OpenHandle(*key);
   4558   if (self->IsJSProxy()) {
   4559     ENTER_V8(isolate, context, Object, Delete, Nothing<bool>(), i::HandleScope);
   4560     Maybe<bool> result = i::Runtime::DeleteObjectProperty(
   4561         isolate, self, key_obj, i::LanguageMode::kSloppy);
   4562     has_pending_exception = result.IsNothing();
   4563     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4564     return result;
   4565   } else {
   4566     // If it's not a JSProxy, i::Runtime::DeleteObjectProperty should never run
   4567     // a script.
   4568     ENTER_V8_NO_SCRIPT(isolate, context, Object, Delete, Nothing<bool>(),
   4569                        i::HandleScope);
   4570     Maybe<bool> result = i::Runtime::DeleteObjectProperty(
   4571         isolate, self, key_obj, i::LanguageMode::kSloppy);
   4572     has_pending_exception = result.IsNothing();
   4573     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4574     return result;
   4575   }
   4576 }
   4577 
   4578 bool v8::Object::Delete(v8::Local<Value> key) {
   4579   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4580   return Delete(context, key).FromMaybe(false);
   4581 }
   4582 
   4583 Maybe<bool> v8::Object::DeletePrivate(Local<Context> context,
   4584                                       Local<Private> key) {
   4585   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4586   // In case of private symbols, i::Runtime::DeleteObjectProperty does not run
   4587   // any author script.
   4588   ENTER_V8_NO_SCRIPT(isolate, context, Object, Delete, Nothing<bool>(),
   4589                      i::HandleScope);
   4590   auto self = Utils::OpenHandle(this);
   4591   auto key_obj = Utils::OpenHandle(*key);
   4592   Maybe<bool> result = i::Runtime::DeleteObjectProperty(
   4593       isolate, self, key_obj, i::LanguageMode::kSloppy);
   4594   has_pending_exception = result.IsNothing();
   4595   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4596   return result;
   4597 }
   4598 
   4599 Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) {
   4600   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4601   ENTER_V8(isolate, context, Object, Has, Nothing<bool>(), i::HandleScope);
   4602   auto self = Utils::OpenHandle(this);
   4603   auto key_obj = Utils::OpenHandle(*key);
   4604   Maybe<bool> maybe = Nothing<bool>();
   4605   // Check if the given key is an array index.
   4606   uint32_t index = 0;
   4607   if (key_obj->ToArrayIndex(&index)) {
   4608     maybe = i::JSReceiver::HasElement(self, index);
   4609   } else {
   4610     // Convert the key to a name - possibly by calling back into JavaScript.
   4611     i::Handle<i::Name> name;
   4612     if (i::Object::ToName(isolate, key_obj).ToHandle(&name)) {
   4613       maybe = i::JSReceiver::HasProperty(self, name);
   4614     }
   4615   }
   4616   has_pending_exception = maybe.IsNothing();
   4617   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4618   return maybe;
   4619 }
   4620 
   4621 
   4622 bool v8::Object::Has(v8::Local<Value> key) {
   4623   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4624   return Has(context, key).FromMaybe(false);
   4625 }
   4626 
   4627 
   4628 Maybe<bool> v8::Object::HasPrivate(Local<Context> context, Local<Private> key) {
   4629   return HasOwnProperty(context, Local<Name>(reinterpret_cast<Name*>(*key)));
   4630 }
   4631 
   4632 
   4633 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
   4634   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4635   ENTER_V8(isolate, context, Object, Delete, Nothing<bool>(), i::HandleScope);
   4636   auto self = Utils::OpenHandle(this);
   4637   Maybe<bool> result = i::JSReceiver::DeleteElement(self, index);
   4638   has_pending_exception = result.IsNothing();
   4639   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4640   return result;
   4641 }
   4642 
   4643 
   4644 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
   4645   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4646   ENTER_V8(isolate, context, Object, Has, Nothing<bool>(), i::HandleScope);
   4647   auto self = Utils::OpenHandle(this);
   4648   auto maybe = i::JSReceiver::HasElement(self, index);
   4649   has_pending_exception = maybe.IsNothing();
   4650   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4651   return maybe;
   4652 }
   4653 
   4654 template <typename Getter, typename Setter, typename Data>
   4655 static Maybe<bool> ObjectSetAccessor(
   4656     Local<Context> context, Object* self, Local<Name> name, Getter getter,
   4657     Setter setter, Data data, AccessControl settings,
   4658     PropertyAttribute attributes, bool is_special_data_property,
   4659     bool replace_on_access,
   4660     SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect) {
   4661   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4662   ENTER_V8_NO_SCRIPT(isolate, context, Object, SetAccessor, Nothing<bool>(),
   4663                      i::HandleScope);
   4664   if (!Utils::OpenHandle(self)->IsJSObject()) return Just(false);
   4665   i::Handle<i::JSObject> obj =
   4666       i::Handle<i::JSObject>::cast(Utils::OpenHandle(self));
   4667   v8::Local<AccessorSignature> signature;
   4668   i::Handle<i::AccessorInfo> info =
   4669       MakeAccessorInfo(isolate, name, getter, setter, data, settings, signature,
   4670                        is_special_data_property, replace_on_access);
   4671   info->set_has_no_side_effect(getter_side_effect_type ==
   4672                                SideEffectType::kHasNoSideEffect);
   4673   if (info.is_null()) return Nothing<bool>();
   4674   bool fast = obj->HasFastProperties();
   4675   i::Handle<i::Object> result;
   4676 
   4677   i::Handle<i::Name> accessor_name(info->name(), isolate);
   4678   i::PropertyAttributes attrs = static_cast<i::PropertyAttributes>(attributes);
   4679   has_pending_exception =
   4680       !i::JSObject::SetAccessor(obj, accessor_name, info, attrs)
   4681            .ToHandle(&result);
   4682   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4683   if (result->IsUndefined(isolate)) return Just(false);
   4684   if (fast) {
   4685     i::JSObject::MigrateSlowToFast(obj, 0, "APISetAccessor");
   4686   }
   4687   return Just(true);
   4688 }
   4689 
   4690 Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name,
   4691                                 AccessorNameGetterCallback getter,
   4692                                 AccessorNameSetterCallback setter,
   4693                                 MaybeLocal<Value> data, AccessControl settings,
   4694                                 PropertyAttribute attribute,
   4695                                 SideEffectType getter_side_effect_type) {
   4696   return ObjectSetAccessor(context, this, name, getter, setter,
   4697                            data.FromMaybe(Local<Value>()), settings, attribute,
   4698                            i::FLAG_disable_old_api_accessors, false,
   4699                            getter_side_effect_type);
   4700 }
   4701 
   4702 
   4703 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
   4704                                  Local<Function> setter,
   4705                                  PropertyAttribute attribute,
   4706                                  AccessControl settings) {
   4707   // TODO(verwaest): Remove |settings|.
   4708   DCHECK_EQ(v8::DEFAULT, settings);
   4709   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   4710   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   4711   i::HandleScope scope(isolate);
   4712   auto self = Utils::OpenHandle(this);
   4713   if (!self->IsJSObject()) return;
   4714   i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
   4715   i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
   4716   if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
   4717   i::JSObject::DefineAccessor(i::Handle<i::JSObject>::cast(self),
   4718                               v8::Utils::OpenHandle(*name), getter_i, setter_i,
   4719                               static_cast<i::PropertyAttributes>(attribute));
   4720 }
   4721 
   4722 Maybe<bool> Object::SetNativeDataProperty(
   4723     v8::Local<v8::Context> context, v8::Local<Name> name,
   4724     AccessorNameGetterCallback getter, AccessorNameSetterCallback setter,
   4725     v8::Local<Value> data, PropertyAttribute attributes,
   4726     SideEffectType getter_side_effect_type) {
   4727   return ObjectSetAccessor(context, this, name, getter, setter, data, DEFAULT,
   4728                            attributes, true, false, getter_side_effect_type);
   4729 }
   4730 
   4731 Maybe<bool> Object::SetLazyDataProperty(
   4732     v8::Local<v8::Context> context, v8::Local<Name> name,
   4733     AccessorNameGetterCallback getter, v8::Local<Value> data,
   4734     PropertyAttribute attributes, SideEffectType getter_side_effect_type) {
   4735   return ObjectSetAccessor(context, this, name, getter,
   4736                            static_cast<AccessorNameSetterCallback>(nullptr),
   4737                            data, DEFAULT, attributes, true, true,
   4738                            getter_side_effect_type);
   4739 }
   4740 
   4741 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
   4742                                        Local<Name> key) {
   4743   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4744   ENTER_V8(isolate, context, Object, HasOwnProperty, Nothing<bool>(),
   4745            i::HandleScope);
   4746   auto self = Utils::OpenHandle(this);
   4747   auto key_val = Utils::OpenHandle(*key);
   4748   auto result = i::JSReceiver::HasOwnProperty(self, key_val);
   4749   has_pending_exception = result.IsNothing();
   4750   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4751   return result;
   4752 }
   4753 
   4754 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context, uint32_t index) {
   4755   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4756   ENTER_V8(isolate, context, Object, HasOwnProperty, Nothing<bool>(),
   4757            i::HandleScope);
   4758   auto self = Utils::OpenHandle(this);
   4759   auto result = i::JSReceiver::HasOwnProperty(self, index);
   4760   has_pending_exception = result.IsNothing();
   4761   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4762   return result;
   4763 }
   4764 
   4765 Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context,
   4766                                              Local<Name> key) {
   4767   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4768   ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealNamedProperty,
   4769                      Nothing<bool>(), i::HandleScope);
   4770   auto self = Utils::OpenHandle(this);
   4771   if (!self->IsJSObject()) return Just(false);
   4772   auto key_val = Utils::OpenHandle(*key);
   4773   auto result = i::JSObject::HasRealNamedProperty(
   4774       i::Handle<i::JSObject>::cast(self), key_val);
   4775   has_pending_exception = result.IsNothing();
   4776   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4777   return result;
   4778 }
   4779 
   4780 
   4781 bool v8::Object::HasRealNamedProperty(Local<String> key) {
   4782   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4783   return HasRealNamedProperty(context, key).FromMaybe(false);
   4784 }
   4785 
   4786 
   4787 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
   4788                                                uint32_t index) {
   4789   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4790   ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealIndexedProperty,
   4791                      Nothing<bool>(), i::HandleScope);
   4792   auto self = Utils::OpenHandle(this);
   4793   if (!self->IsJSObject()) return Just(false);
   4794   auto result = i::JSObject::HasRealElementProperty(
   4795       i::Handle<i::JSObject>::cast(self), index);
   4796   has_pending_exception = result.IsNothing();
   4797   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4798   return result;
   4799 }
   4800 
   4801 
   4802 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
   4803   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4804   return HasRealIndexedProperty(context, index).FromMaybe(false);
   4805 }
   4806 
   4807 
   4808 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
   4809                                                      Local<Name> key) {
   4810   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4811   ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealNamedCallbackProperty,
   4812                      Nothing<bool>(), i::HandleScope);
   4813   auto self = Utils::OpenHandle(this);
   4814   if (!self->IsJSObject()) return Just(false);
   4815   auto key_val = Utils::OpenHandle(*key);
   4816   auto result = i::JSObject::HasRealNamedCallbackProperty(
   4817       i::Handle<i::JSObject>::cast(self), key_val);
   4818   has_pending_exception = result.IsNothing();
   4819   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   4820   return result;
   4821 }
   4822 
   4823 
   4824 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) {
   4825   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   4826   return HasRealNamedCallbackProperty(context, key).FromMaybe(false);
   4827 }
   4828 
   4829 
   4830 bool v8::Object::HasNamedLookupInterceptor() {
   4831   auto self = Utils::OpenHandle(this);
   4832   return self->IsJSObject() &&
   4833          i::Handle<i::JSObject>::cast(self)->HasNamedInterceptor();
   4834 }
   4835 
   4836 
   4837 bool v8::Object::HasIndexedLookupInterceptor() {
   4838   auto self = Utils::OpenHandle(this);
   4839   return self->IsJSObject() &&
   4840          i::Handle<i::JSObject>::cast(self)->HasIndexedInterceptor();
   4841 }
   4842 
   4843 
   4844 MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
   4845     Local<Context> context, Local<Name> key) {
   4846   PREPARE_FOR_EXECUTION(context, Object, GetRealNamedPropertyInPrototypeChain,
   4847                         Value);
   4848   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
   4849   if (!self->IsJSObject()) return MaybeLocal<Value>();
   4850   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
   4851   i::PrototypeIterator iter(isolate, self);
   4852   if (iter.IsAtEnd()) return MaybeLocal<Value>();
   4853   i::Handle<i::JSReceiver> proto =
   4854       i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
   4855   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
   4856       isolate, self, key_obj, proto,
   4857       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
   4858   Local<Value> result;
   4859   has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
   4860   RETURN_ON_FAILED_EXECUTION(Value);
   4861   if (!it.IsFound()) return MaybeLocal<Value>();
   4862   RETURN_ESCAPED(result);
   4863 }
   4864 
   4865 
   4866 Maybe<PropertyAttribute>
   4867 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(
   4868     Local<Context> context, Local<Name> key) {
   4869   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4870   ENTER_V8_NO_SCRIPT(isolate, context, Object,
   4871                      GetRealNamedPropertyAttributesInPrototypeChain,
   4872                      Nothing<PropertyAttribute>(), i::HandleScope);
   4873   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
   4874   if (!self->IsJSObject()) return Nothing<PropertyAttribute>();
   4875   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
   4876   i::PrototypeIterator iter(isolate, self);
   4877   if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
   4878   i::Handle<i::JSReceiver> proto =
   4879       i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
   4880   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
   4881       isolate, self, key_obj, proto,
   4882       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
   4883   Maybe<i::PropertyAttributes> result =
   4884       i::JSReceiver::GetPropertyAttributes(&it);
   4885   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
   4886   if (!it.IsFound()) return Nothing<PropertyAttribute>();
   4887   if (result.FromJust() == i::ABSENT) return Just(None);
   4888   return Just(static_cast<PropertyAttribute>(result.FromJust()));
   4889 }
   4890 
   4891 
   4892 MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context,
   4893                                                    Local<Name> key) {
   4894   PREPARE_FOR_EXECUTION(context, Object, GetRealNamedProperty, Value);
   4895   auto self = Utils::OpenHandle(this);
   4896   auto key_obj = Utils::OpenHandle(*key);
   4897   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
   4898       isolate, self, key_obj, self,
   4899       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
   4900   Local<Value> result;
   4901   has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
   4902   RETURN_ON_FAILED_EXECUTION(Value);
   4903   if (!it.IsFound()) return MaybeLocal<Value>();
   4904   RETURN_ESCAPED(result);
   4905 }
   4906 
   4907 
   4908 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
   4909     Local<Context> context, Local<Name> key) {
   4910   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4911   ENTER_V8_NO_SCRIPT(isolate, context, Object, GetRealNamedPropertyAttributes,
   4912                      Nothing<PropertyAttribute>(), i::HandleScope);
   4913   auto self = Utils::OpenHandle(this);
   4914   auto key_obj = Utils::OpenHandle(*key);
   4915   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
   4916       isolate, self, key_obj, self,
   4917       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
   4918   auto result = i::JSReceiver::GetPropertyAttributes(&it);
   4919   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
   4920   if (!it.IsFound()) return Nothing<PropertyAttribute>();
   4921   if (result.FromJust() == i::ABSENT) {
   4922     return Just(static_cast<PropertyAttribute>(i::NONE));
   4923   }
   4924   return Just<PropertyAttribute>(
   4925       static_cast<PropertyAttribute>(result.FromJust()));
   4926 }
   4927 
   4928 
   4929 Local<v8::Object> v8::Object::Clone() {
   4930   auto self = i::Handle<i::JSObject>::cast(Utils::OpenHandle(this));
   4931   auto isolate = self->GetIsolate();
   4932   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   4933   auto result = isolate->factory()->CopyJSObject(self);
   4934   CHECK(!result.is_null());
   4935   return Utils::ToLocal(result);
   4936 }
   4937 
   4938 
   4939 Local<v8::Context> v8::Object::CreationContext() {
   4940   auto self = Utils::OpenHandle(this);
   4941   return Utils::ToLocal(self->GetCreationContext());
   4942 }
   4943 
   4944 
   4945 int v8::Object::GetIdentityHash() {
   4946   i::DisallowHeapAllocation no_gc;
   4947   auto isolate = Utils::OpenHandle(this)->GetIsolate();
   4948   i::HandleScope scope(isolate);
   4949   auto self = Utils::OpenHandle(this);
   4950   return self->GetOrCreateIdentityHash(isolate)->value();
   4951 }
   4952 
   4953 
   4954 bool v8::Object::IsCallable() {
   4955   auto self = Utils::OpenHandle(this);
   4956   return self->IsCallable();
   4957 }
   4958 
   4959 bool v8::Object::IsConstructor() {
   4960   auto self = Utils::OpenHandle(this);
   4961   return self->IsConstructor();
   4962 }
   4963 
   4964 MaybeLocal<Value> Object::CallAsFunction(Local<Context> context,
   4965                                          Local<Value> recv, int argc,
   4966                                          Local<Value> argv[]) {
   4967   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4968   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
   4969   ENTER_V8(isolate, context, Object, CallAsFunction, MaybeLocal<Value>(),
   4970            InternalEscapableScope);
   4971   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
   4972   auto self = Utils::OpenHandle(this);
   4973   auto recv_obj = Utils::OpenHandle(*recv);
   4974   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
   4975   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
   4976   Local<Value> result;
   4977   has_pending_exception = !ToLocal<Value>(
   4978       i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
   4979   RETURN_ON_FAILED_EXECUTION(Value);
   4980   RETURN_ESCAPED(result);
   4981 }
   4982 
   4983 
   4984 MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc,
   4985                                             Local<Value> argv[]) {
   4986   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   4987   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
   4988   ENTER_V8(isolate, context, Object, CallAsConstructor, MaybeLocal<Value>(),
   4989            InternalEscapableScope);
   4990   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
   4991   auto self = Utils::OpenHandle(this);
   4992   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
   4993   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
   4994   Local<Value> result;
   4995   has_pending_exception = !ToLocal<Value>(
   4996       i::Execution::New(isolate, self, self, argc, args), &result);
   4997   RETURN_ON_FAILED_EXECUTION(Value);
   4998   RETURN_ESCAPED(result);
   4999 }
   5000 
   5001 MaybeLocal<Function> Function::New(Local<Context> context,
   5002                                    FunctionCallback callback, Local<Value> data,
   5003                                    int length, ConstructorBehavior behavior,
   5004                                    SideEffectType side_effect_type) {
   5005   i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
   5006   LOG_API(isolate, Function, New);
   5007   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   5008   auto templ =
   5009       FunctionTemplateNew(isolate, callback, data, Local<Signature>(), length,
   5010                           true, Local<Private>(), side_effect_type);
   5011   if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype();
   5012   return templ->GetFunction(context);
   5013 }
   5014 
   5015 
   5016 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback,
   5017                               Local<Value> data, int length) {
   5018   return Function::New(v8_isolate->GetCurrentContext(), callback, data, length,
   5019                        ConstructorBehavior::kAllow)
   5020       .FromMaybe(Local<Function>());
   5021 }
   5022 
   5023 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
   5024                                          v8::Local<v8::Value> argv[]) const {
   5025   return NewInstanceWithSideEffectType(context, argc, argv,
   5026                                        SideEffectType::kHasSideEffect);
   5027 }
   5028 
   5029 MaybeLocal<Object> Function::NewInstanceWithSideEffectType(
   5030     Local<Context> context, int argc, v8::Local<v8::Value> argv[],
   5031     SideEffectType side_effect_type) const {
   5032   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   5033   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
   5034   ENTER_V8(isolate, context, Function, NewInstance, MaybeLocal<Object>(),
   5035            InternalEscapableScope);
   5036   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
   5037   auto self = Utils::OpenHandle(this);
   5038   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
   5039   bool should_set_has_no_side_effect =
   5040       side_effect_type == SideEffectType::kHasNoSideEffect &&
   5041       isolate->debug_execution_mode() == i::DebugInfo::kSideEffects;
   5042   if (should_set_has_no_side_effect) {
   5043     CHECK(self->IsJSFunction() &&
   5044           i::JSFunction::cast(*self)->shared()->IsApiFunction());
   5045     i::Object* obj =
   5046         i::JSFunction::cast(*self)->shared()->get_api_func_data()->call_code();
   5047     if (obj->IsCallHandlerInfo()) {
   5048       i::CallHandlerInfo* handler_info = i::CallHandlerInfo::cast(obj);
   5049       if (!handler_info->IsSideEffectFreeCallHandlerInfo()) {
   5050         handler_info->SetNextCallHasNoSideEffect();
   5051       }
   5052     }
   5053   }
   5054   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
   5055   Local<Object> result;
   5056   has_pending_exception = !ToLocal<Object>(
   5057       i::Execution::New(isolate, self, self, argc, args), &result);
   5058   if (should_set_has_no_side_effect) {
   5059     i::Object* obj =
   5060         i::JSFunction::cast(*self)->shared()->get_api_func_data()->call_code();
   5061     if (obj->IsCallHandlerInfo()) {
   5062       i::CallHandlerInfo* handler_info = i::CallHandlerInfo::cast(obj);
   5063       if (has_pending_exception) {
   5064         // Restore the map if an exception prevented restoration.
   5065         handler_info->NextCallHasNoSideEffect();
   5066       } else {
   5067         DCHECK(handler_info->IsSideEffectCallHandlerInfo() ||
   5068                handler_info->IsSideEffectFreeCallHandlerInfo());
   5069       }
   5070     }
   5071   }
   5072   RETURN_ON_FAILED_EXECUTION(Object);
   5073   RETURN_ESCAPED(result);
   5074 }
   5075 
   5076 
   5077 MaybeLocal<v8::Value> Function::Call(Local<Context> context,
   5078                                      v8::Local<v8::Value> recv, int argc,
   5079                                      v8::Local<v8::Value> argv[]) {
   5080   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   5081   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
   5082   ENTER_V8(isolate, context, Function, Call, MaybeLocal<Value>(),
   5083            InternalEscapableScope);
   5084   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
   5085   auto self = Utils::OpenHandle(this);
   5086   Utils::ApiCheck(!self.is_null(), "v8::Function::Call",
   5087                   "Function to be called is a null pointer");
   5088   i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
   5089   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
   5090   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
   5091   Local<Value> result;
   5092   has_pending_exception = !ToLocal<Value>(
   5093       i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
   5094   RETURN_ON_FAILED_EXECUTION(Value);
   5095   RETURN_ESCAPED(result);
   5096 }
   5097 
   5098 
   5099 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc,
   5100                                 v8::Local<v8::Value> argv[]) {
   5101   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   5102   RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value);
   5103 }
   5104 
   5105 
   5106 void Function::SetName(v8::Local<v8::String> name) {
   5107   auto self = Utils::OpenHandle(this);
   5108   if (!self->IsJSFunction()) return;
   5109   auto func = i::Handle<i::JSFunction>::cast(self);
   5110   func->shared()->SetName(*Utils::OpenHandle(*name));
   5111 }
   5112 
   5113 
   5114 Local<Value> Function::GetName() const {
   5115   auto self = Utils::OpenHandle(this);
   5116   i::Isolate* isolate = self->GetIsolate();
   5117   if (self->IsJSBoundFunction()) {
   5118     auto func = i::Handle<i::JSBoundFunction>::cast(self);
   5119     i::Handle<i::Object> name;
   5120     ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
   5121                                      i::JSBoundFunction::GetName(isolate, func),
   5122                                      Local<Value>());
   5123     return Utils::ToLocal(name);
   5124   }
   5125   if (self->IsJSFunction()) {
   5126     auto func = i::Handle<i::JSFunction>::cast(self);
   5127     return Utils::ToLocal(handle(func->shared()->Name(), isolate));
   5128   }
   5129   return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
   5130 }
   5131 
   5132 
   5133 Local<Value> Function::GetInferredName() const {
   5134   auto self = Utils::OpenHandle(this);
   5135   if (!self->IsJSFunction()) {
   5136     return ToApiHandle<Primitive>(
   5137         self->GetIsolate()->factory()->undefined_value());
   5138   }
   5139   auto func = i::Handle<i::JSFunction>::cast(self);
   5140   return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
   5141                                              func->GetIsolate()));
   5142 }
   5143 
   5144 
   5145 Local<Value> Function::GetDebugName() const {
   5146   auto self = Utils::OpenHandle(this);
   5147   if (!self->IsJSFunction()) {
   5148     return ToApiHandle<Primitive>(
   5149         self->GetIsolate()->factory()->undefined_value());
   5150   }
   5151   auto func = i::Handle<i::JSFunction>::cast(self);
   5152   i::Handle<i::String> name = i::JSFunction::GetDebugName(func);
   5153   return Utils::ToLocal(i::Handle<i::Object>(*name, self->GetIsolate()));
   5154 }
   5155 
   5156 
   5157 Local<Value> Function::GetDisplayName() const {
   5158   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   5159   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   5160   auto self = Utils::OpenHandle(this);
   5161   if (!self->IsJSFunction()) {
   5162     return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
   5163   }
   5164   auto func = i::Handle<i::JSFunction>::cast(self);
   5165   i::Handle<i::String> property_name =
   5166       isolate->factory()->NewStringFromStaticChars("displayName");
   5167   i::Handle<i::Object> value =
   5168       i::JSReceiver::GetDataProperty(func, property_name);
   5169   if (value->IsString()) {
   5170     i::Handle<i::String> name = i::Handle<i::String>::cast(value);
   5171     if (name->length() > 0) return Utils::ToLocal(name);
   5172   }
   5173   return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
   5174 }
   5175 
   5176 
   5177 ScriptOrigin Function::GetScriptOrigin() const {
   5178   auto self = Utils::OpenHandle(this);
   5179   if (!self->IsJSFunction()) {
   5180     return v8::ScriptOrigin(Local<Value>());
   5181   }
   5182   auto func = i::Handle<i::JSFunction>::cast(self);
   5183   if (func->shared()->script()->IsScript()) {
   5184     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
   5185                                 func->GetIsolate());
   5186     return GetScriptOriginForScript(func->GetIsolate(), script);
   5187   }
   5188   return v8::ScriptOrigin(Local<Value>());
   5189 }
   5190 
   5191 
   5192 const int Function::kLineOffsetNotFound = -1;
   5193 
   5194 
   5195 int Function::GetScriptLineNumber() const {
   5196   auto self = Utils::OpenHandle(this);
   5197   if (!self->IsJSFunction()) {
   5198     return kLineOffsetNotFound;
   5199   }
   5200   auto func = i::Handle<i::JSFunction>::cast(self);
   5201   if (func->shared()->script()->IsScript()) {
   5202     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
   5203                                 func->GetIsolate());
   5204     return i::Script::GetLineNumber(script, func->shared()->StartPosition());
   5205   }
   5206   return kLineOffsetNotFound;
   5207 }
   5208 
   5209 
   5210 int Function::GetScriptColumnNumber() const {
   5211   auto self = Utils::OpenHandle(this);
   5212   if (!self->IsJSFunction()) {
   5213     return kLineOffsetNotFound;
   5214   }
   5215   auto func = i::Handle<i::JSFunction>::cast(self);
   5216   if (func->shared()->script()->IsScript()) {
   5217     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
   5218                                 func->GetIsolate());
   5219     return i::Script::GetColumnNumber(script, func->shared()->StartPosition());
   5220   }
   5221   return kLineOffsetNotFound;
   5222 }
   5223 
   5224 
   5225 int Function::ScriptId() const {
   5226   auto self = Utils::OpenHandle(this);
   5227   if (!self->IsJSFunction()) {
   5228     return v8::UnboundScript::kNoScriptId;
   5229   }
   5230   auto func = i::Handle<i::JSFunction>::cast(self);
   5231   if (!func->shared()->script()->IsScript()) {
   5232     return v8::UnboundScript::kNoScriptId;
   5233   }
   5234   i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
   5235                               func->GetIsolate());
   5236   return script->id();
   5237 }
   5238 
   5239 
   5240 Local<v8::Value> Function::GetBoundFunction() const {
   5241   auto self = Utils::OpenHandle(this);
   5242   if (self->IsJSBoundFunction()) {
   5243     auto bound_function = i::Handle<i::JSBoundFunction>::cast(self);
   5244     auto bound_target_function = i::handle(
   5245         bound_function->bound_target_function(), bound_function->GetIsolate());
   5246     return Utils::CallableToLocal(bound_target_function);
   5247   }
   5248   return v8::Undefined(reinterpret_cast<v8::Isolate*>(self->GetIsolate()));
   5249 }
   5250 
   5251 int Name::GetIdentityHash() {
   5252   auto self = Utils::OpenHandle(this);
   5253   return static_cast<int>(self->Hash());
   5254 }
   5255 
   5256 
   5257 int String::Length() const {
   5258   i::Handle<i::String> str = Utils::OpenHandle(this);
   5259   return str->length();
   5260 }
   5261 
   5262 
   5263 bool String::IsOneByte() const {
   5264   i::Handle<i::String> str = Utils::OpenHandle(this);
   5265   return str->HasOnlyOneByteChars();
   5266 }
   5267 
   5268 
   5269 // Helpers for ContainsOnlyOneByteHelper
   5270 template<size_t size> struct OneByteMask;
   5271 template<> struct OneByteMask<4> {
   5272   static const uint32_t value = 0xFF00FF00;
   5273 };
   5274 template<> struct OneByteMask<8> {
   5275   static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
   5276 };
   5277 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
   5278 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
   5279 static inline bool Unaligned(const uint16_t* chars) {
   5280   return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
   5281 }
   5282 
   5283 
   5284 static inline const uint16_t* Align(const uint16_t* chars) {
   5285   return reinterpret_cast<uint16_t*>(
   5286       reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
   5287 }
   5288 
   5289 class ContainsOnlyOneByteHelper {
   5290  public:
   5291   ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
   5292   bool Check(i::String* string) {
   5293     i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
   5294     if (cons_string == nullptr) return is_one_byte_;
   5295     return CheckCons(cons_string);
   5296   }
   5297   void VisitOneByteString(const uint8_t* chars, int length) {
   5298     // Nothing to do.
   5299   }
   5300   void VisitTwoByteString(const uint16_t* chars, int length) {
   5301     // Accumulated bits.
   5302     uintptr_t acc = 0;
   5303     // Align to uintptr_t.
   5304     const uint16_t* end = chars + length;
   5305     while (Unaligned(chars) && chars != end) {
   5306       acc |= *chars++;
   5307     }
   5308     // Read word aligned in blocks,
   5309     // checking the return value at the end of each block.
   5310     const uint16_t* aligned_end = Align(end);
   5311     const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
   5312     const int inner_loops = 16;
   5313     while (chars + inner_loops*increment < aligned_end) {
   5314       for (int i = 0; i < inner_loops; i++) {
   5315         acc |= *reinterpret_cast<const uintptr_t*>(chars);
   5316         chars += increment;
   5317       }
   5318       // Check for early return.
   5319       if ((acc & kOneByteMask) != 0) {
   5320         is_one_byte_ = false;
   5321         return;
   5322       }
   5323     }
   5324     // Read the rest.
   5325     while (chars != end) {
   5326       acc |= *chars++;
   5327     }
   5328     // Check result.
   5329     if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
   5330   }
   5331 
   5332  private:
   5333   bool CheckCons(i::ConsString* cons_string) {
   5334     while (true) {
   5335       // Check left side if flat.
   5336       i::String* left = cons_string->first();
   5337       i::ConsString* left_as_cons =
   5338           i::String::VisitFlat(this, left, 0);
   5339       if (!is_one_byte_) return false;
   5340       // Check right side if flat.
   5341       i::String* right = cons_string->second();
   5342       i::ConsString* right_as_cons =
   5343           i::String::VisitFlat(this, right, 0);
   5344       if (!is_one_byte_) return false;
   5345       // Standard recurse/iterate trick.
   5346       if (left_as_cons != nullptr && right_as_cons != nullptr) {
   5347         if (left->length() < right->length()) {
   5348           CheckCons(left_as_cons);
   5349           cons_string = right_as_cons;
   5350         } else {
   5351           CheckCons(right_as_cons);
   5352           cons_string = left_as_cons;
   5353         }
   5354         // Check fast return.
   5355         if (!is_one_byte_) return false;
   5356         continue;
   5357       }
   5358       // Descend left in place.
   5359       if (left_as_cons != nullptr) {
   5360         cons_string = left_as_cons;
   5361         continue;
   5362       }
   5363       // Descend right in place.
   5364       if (right_as_cons != nullptr) {
   5365         cons_string = right_as_cons;
   5366         continue;
   5367       }
   5368       // Terminate.
   5369       break;
   5370     }
   5371     return is_one_byte_;
   5372   }
   5373   bool is_one_byte_;
   5374   DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
   5375 };
   5376 
   5377 
   5378 bool String::ContainsOnlyOneByte() const {
   5379   i::Handle<i::String> str = Utils::OpenHandle(this);
   5380   if (str->HasOnlyOneByteChars()) return true;
   5381   ContainsOnlyOneByteHelper helper;
   5382   return helper.Check(*str);
   5383 }
   5384 
   5385 int String::Utf8Length() const {
   5386   i::Isolate* isolate = UnsafeIsolateFromHeapObject(Utils::OpenHandle(this));
   5387   return Utf8Length(reinterpret_cast<Isolate*>(isolate));
   5388 }
   5389 
   5390 int String::Utf8Length(Isolate* isolate) const {
   5391   i::Handle<i::String> str = Utils::OpenHandle(this);
   5392   str = i::String::Flatten(reinterpret_cast<i::Isolate*>(isolate), str);
   5393   int length = str->length();
   5394   if (length == 0) return 0;
   5395   i::DisallowHeapAllocation no_gc;
   5396   i::String::FlatContent flat = str->GetFlatContent();
   5397   DCHECK(flat.IsFlat());
   5398   int utf8_length = 0;
   5399   if (flat.IsOneByte()) {
   5400     for (uint8_t c : flat.ToOneByteVector()) {
   5401       utf8_length += c >> 7;
   5402     }
   5403     utf8_length += length;
   5404   } else {
   5405     int last_character = unibrow::Utf16::kNoPreviousCharacter;
   5406     for (uint16_t c : flat.ToUC16Vector()) {
   5407       utf8_length += unibrow::Utf8::Length(c, last_character);
   5408       last_character = c;
   5409     }
   5410   }
   5411   return utf8_length;
   5412 }
   5413 
   5414 class Utf8WriterVisitor {
   5415  public:
   5416   Utf8WriterVisitor(
   5417       char* buffer,
   5418       int capacity,
   5419       bool skip_capacity_check,
   5420       bool replace_invalid_utf8)
   5421     : early_termination_(false),
   5422       last_character_(unibrow::Utf16::kNoPreviousCharacter),
   5423       buffer_(buffer),
   5424       start_(buffer),
   5425       capacity_(capacity),
   5426       skip_capacity_check_(capacity == -1 || skip_capacity_check),
   5427       replace_invalid_utf8_(replace_invalid_utf8),
   5428       utf16_chars_read_(0) {
   5429   }
   5430 
   5431   static int WriteEndCharacter(uint16_t character,
   5432                                int last_character,
   5433                                int remaining,
   5434                                char* const buffer,
   5435                                bool replace_invalid_utf8) {
   5436     DCHECK_GT(remaining, 0);
   5437     // We can't use a local buffer here because Encode needs to modify
   5438     // previous characters in the stream.  We know, however, that
   5439     // exactly one character will be advanced.
   5440     if (unibrow::Utf16::IsSurrogatePair(last_character, character)) {
   5441       int written = unibrow::Utf8::Encode(buffer, character, last_character,
   5442                                           replace_invalid_utf8);
   5443       DCHECK_EQ(written, 1);
   5444       return written;
   5445     }
   5446     // Use a scratch buffer to check the required characters.
   5447     char temp_buffer[unibrow::Utf8::kMaxEncodedSize];
   5448     // Can't encode using last_character as gcc has array bounds issues.
   5449     int written = unibrow::Utf8::Encode(temp_buffer, character,
   5450                                         unibrow::Utf16::kNoPreviousCharacter,
   5451                                         replace_invalid_utf8);
   5452     // Won't fit.
   5453     if (written > remaining) return 0;
   5454     // Copy over the character from temp_buffer.
   5455     for (int j = 0; j < written; j++) {
   5456       buffer[j] = temp_buffer[j];
   5457     }
   5458     return written;
   5459   }
   5460 
   5461   // Visit writes out a group of code units (chars) of a v8::String to the
   5462   // internal buffer_. This is done in two phases. The first phase calculates a
   5463   // pesimistic estimate (writable_length) on how many code units can be safely
   5464   // written without exceeding the buffer capacity and without writing the last
   5465   // code unit (it could be a lead surrogate). The estimated number of code
   5466   // units is then written out in one go, and the reported byte usage is used
   5467   // to correct the estimate. This is repeated until the estimate becomes <= 0
   5468   // or all code units have been written out. The second phase writes out code
   5469   // units until the buffer capacity is reached, would be exceeded by the next
   5470   // unit, or all units have been written out.
   5471   template<typename Char>
   5472   void Visit(const Char* chars, const int length) {
   5473     DCHECK(!early_termination_);
   5474     if (length == 0) return;
   5475     // Copy state to stack.
   5476     char* buffer = buffer_;
   5477     int last_character = sizeof(Char) == 1
   5478                              ? unibrow::Utf16::kNoPreviousCharacter
   5479                              : last_character_;
   5480     int i = 0;
   5481     // Do a fast loop where there is no exit capacity check.
   5482     while (true) {
   5483       int fast_length;
   5484       if (skip_capacity_check_) {
   5485         fast_length = length;
   5486       } else {
   5487         int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
   5488         // Need enough space to write everything but one character.
   5489         STATIC_ASSERT(unibrow::Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit ==
   5490                       3);
   5491         int max_size_per_char =  sizeof(Char) == 1 ? 2 : 3;
   5492         int writable_length =
   5493             (remaining_capacity - max_size_per_char)/max_size_per_char;
   5494         // Need to drop into slow loop.
   5495         if (writable_length <= 0) break;
   5496         fast_length = i + writable_length;
   5497         if (fast_length > length) fast_length = length;
   5498       }
   5499       // Write the characters to the stream.
   5500       if (sizeof(Char) == 1) {
   5501         for (; i < fast_length; i++) {
   5502           buffer += unibrow::Utf8::EncodeOneByte(
   5503               buffer, static_cast<uint8_t>(*chars++));
   5504           DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
   5505         }
   5506       } else {
   5507         for (; i < fast_length; i++) {
   5508           uint16_t character = *chars++;
   5509           buffer += unibrow::Utf8::Encode(buffer, character, last_character,
   5510                                           replace_invalid_utf8_);
   5511           last_character = character;
   5512           DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
   5513         }
   5514       }
   5515       // Array is fully written. Exit.
   5516       if (fast_length == length) {
   5517         // Write state back out to object.
   5518         last_character_ = last_character;
   5519         buffer_ = buffer;
   5520         utf16_chars_read_ += length;
   5521         return;
   5522       }
   5523     }
   5524     DCHECK(!skip_capacity_check_);
   5525     // Slow loop. Must check capacity on each iteration.
   5526     int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
   5527     DCHECK_GE(remaining_capacity, 0);
   5528     for (; i < length && remaining_capacity > 0; i++) {
   5529       uint16_t character = *chars++;
   5530       // remaining_capacity is <= 3 bytes at this point, so we do not write out
   5531       // an umatched lead surrogate.
   5532       if (replace_invalid_utf8_ && unibrow::Utf16::IsLeadSurrogate(character)) {
   5533         early_termination_ = true;
   5534         break;
   5535       }
   5536       int written = WriteEndCharacter(character,
   5537                                       last_character,
   5538                                       remaining_capacity,
   5539                                       buffer,
   5540                                       replace_invalid_utf8_);
   5541       if (written == 0) {
   5542         early_termination_ = true;
   5543         break;
   5544       }
   5545       buffer += written;
   5546       remaining_capacity -= written;
   5547       last_character = character;
   5548     }
   5549     // Write state back out to object.
   5550     last_character_ = last_character;
   5551     buffer_ = buffer;
   5552     utf16_chars_read_ += i;
   5553   }
   5554 
   5555   inline bool IsDone() {
   5556     return early_termination_;
   5557   }
   5558 
   5559   inline void VisitOneByteString(const uint8_t* chars, int length) {
   5560     Visit(chars, length);
   5561   }
   5562 
   5563   inline void VisitTwoByteString(const uint16_t* chars, int length) {
   5564     Visit(chars, length);
   5565   }
   5566 
   5567   int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
   5568     // Write out number of utf16 characters written to the stream.
   5569     if (utf16_chars_read_out != nullptr) {
   5570       *utf16_chars_read_out = utf16_chars_read_;
   5571     }
   5572     // Only null terminate if all of the string was written and there's space.
   5573     if (write_null &&
   5574         !early_termination_ &&
   5575         (capacity_ == -1 || (buffer_ - start_) < capacity_)) {
   5576       *buffer_++ = '\0';
   5577     }
   5578     return static_cast<int>(buffer_ - start_);
   5579   }
   5580 
   5581  private:
   5582   bool early_termination_;
   5583   int last_character_;
   5584   char* buffer_;
   5585   char* const start_;
   5586   int capacity_;
   5587   bool const skip_capacity_check_;
   5588   bool const replace_invalid_utf8_;
   5589   int utf16_chars_read_;
   5590   DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
   5591 };
   5592 
   5593 
   5594 static bool RecursivelySerializeToUtf8(i::String* current,
   5595                                        Utf8WriterVisitor* writer,
   5596                                        int recursion_budget) {
   5597   while (!writer->IsDone()) {
   5598     i::ConsString* cons_string = i::String::VisitFlat(writer, current);
   5599     if (cons_string == nullptr) return true;  // Leaf node.
   5600     if (recursion_budget <= 0) return false;
   5601     // Must write the left branch first.
   5602     i::String* first = cons_string->first();
   5603     bool success = RecursivelySerializeToUtf8(first,
   5604                                               writer,
   5605                                               recursion_budget - 1);
   5606     if (!success) return false;
   5607     // Inline tail recurse for right branch.
   5608     current = cons_string->second();
   5609   }
   5610   return true;
   5611 }
   5612 
   5613 int String::WriteUtf8(Isolate* v8_isolate, char* buffer, int capacity,
   5614                       int* nchars_ref, int options) const {
   5615   i::Handle<i::String> str = Utils::OpenHandle(this);
   5616   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   5617   LOG_API(isolate, String, WriteUtf8);
   5618   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   5619   str = i::String::Flatten(isolate, str);  // Flatten the string for efficiency.
   5620   const int string_length = str->length();
   5621   bool write_null = !(options & NO_NULL_TERMINATION);
   5622   bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
   5623   int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
   5624   // First check if we can just write the string without checking capacity.
   5625   if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
   5626     Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
   5627     const int kMaxRecursion = 100;
   5628     bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
   5629     if (success) return writer.CompleteWrite(write_null, nchars_ref);
   5630   } else if (capacity >= string_length) {
   5631     // First check that the buffer is large enough.
   5632     int utf8_bytes = Utf8Length(v8_isolate);
   5633     if (utf8_bytes <= capacity) {
   5634       // one-byte fast path.
   5635       if (utf8_bytes == string_length) {
   5636         WriteOneByte(v8_isolate, reinterpret_cast<uint8_t*>(buffer), 0,
   5637                      capacity, options);
   5638         if (nchars_ref != nullptr) *nchars_ref = string_length;
   5639         if (write_null && (utf8_bytes+1 <= capacity)) {
   5640           return string_length + 1;
   5641         }
   5642         return string_length;
   5643       }
   5644       if (write_null && (utf8_bytes+1 > capacity)) {
   5645         options |= NO_NULL_TERMINATION;
   5646       }
   5647       // Recurse once without a capacity limit.
   5648       // This will get into the first branch above.
   5649       // TODO(dcarney) Check max left rec. in Utf8Length and fall through.
   5650       return WriteUtf8(v8_isolate, buffer, -1, nchars_ref, options);
   5651     }
   5652   }
   5653   Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
   5654   i::String::VisitFlat(&writer, *str);
   5655   return writer.CompleteWrite(write_null, nchars_ref);
   5656 }
   5657 
   5658 int String::WriteUtf8(char* buffer, int capacity, int* nchars_ref,
   5659                       int options) const {
   5660   i::Handle<i::String> str = Utils::OpenHandle(this);
   5661   i::Isolate* isolate = UnsafeIsolateFromHeapObject(str);
   5662   return WriteUtf8(reinterpret_cast<Isolate*>(isolate), buffer, capacity,
   5663                    nchars_ref, options);
   5664 }
   5665 
   5666 template <typename CharType>
   5667 static inline int WriteHelper(i::Isolate* isolate, const String* string,
   5668                               CharType* buffer, int start, int length,
   5669                               int options) {
   5670   LOG_API(isolate, String, Write);
   5671   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   5672   DCHECK(start >= 0 && length >= -1);
   5673   i::Handle<i::String> str = Utils::OpenHandle(string);
   5674   str = i::String::Flatten(isolate, str);
   5675   int end = start + length;
   5676   if ((length == -1) || (length > str->length() - start) )
   5677     end = str->length();
   5678   if (end < 0) return 0;
   5679   i::String::WriteToFlat(*str, buffer, start, end);
   5680   if (!(options & String::NO_NULL_TERMINATION) &&
   5681       (length == -1 || end - start < length)) {
   5682     buffer[end - start] = '\0';
   5683   }
   5684   return end - start;
   5685 }
   5686 
   5687 int String::WriteOneByte(uint8_t* buffer, int start, int length,
   5688                          int options) const {
   5689   i::Isolate* isolate = UnsafeIsolateFromHeapObject(Utils::OpenHandle(this));
   5690   return WriteHelper(isolate, this, buffer, start, length, options);
   5691 }
   5692 
   5693 int String::WriteOneByte(Isolate* isolate, uint8_t* buffer, int start,
   5694                          int length, int options) const {
   5695   return WriteHelper(reinterpret_cast<i::Isolate*>(isolate), this, buffer,
   5696                      start, length, options);
   5697 }
   5698 
   5699 int String::Write(uint16_t* buffer, int start, int length, int options) const {
   5700   i::Isolate* isolate = UnsafeIsolateFromHeapObject(Utils::OpenHandle(this));
   5701   return WriteHelper(isolate, this, buffer, start, length, options);
   5702 }
   5703 
   5704 int String::Write(Isolate* isolate, uint16_t* buffer, int start, int length,
   5705                   int options) const {
   5706   return WriteHelper(reinterpret_cast<i::Isolate*>(isolate), this, buffer,
   5707                      start, length, options);
   5708 }
   5709 
   5710 
   5711 bool v8::String::IsExternal() const {
   5712   i::Handle<i::String> str = Utils::OpenHandle(this);
   5713   return i::StringShape(*str).IsExternalTwoByte();
   5714 }
   5715 
   5716 
   5717 bool v8::String::IsExternalOneByte() const {
   5718   i::Handle<i::String> str = Utils::OpenHandle(this);
   5719   return i::StringShape(*str).IsExternalOneByte();
   5720 }
   5721 
   5722 
   5723 void v8::String::VerifyExternalStringResource(
   5724     v8::String::ExternalStringResource* value) const {
   5725   i::DisallowHeapAllocation no_allocation;
   5726   i::String* str = *Utils::OpenHandle(this);
   5727   const v8::String::ExternalStringResource* expected;
   5728 
   5729   if (str->IsThinString()) {
   5730     str = i::ThinString::cast(str)->actual();
   5731   }
   5732 
   5733   if (i::StringShape(str).IsExternalTwoByte()) {
   5734     const void* resource = i::ExternalTwoByteString::cast(str)->resource();
   5735     expected = reinterpret_cast<const ExternalStringResource*>(resource);
   5736   } else {
   5737     expected = nullptr;
   5738   }
   5739   CHECK_EQ(expected, value);
   5740 }
   5741 
   5742 void v8::String::VerifyExternalStringResourceBase(
   5743     v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
   5744   i::DisallowHeapAllocation no_allocation;
   5745   i::String* str = *Utils::OpenHandle(this);
   5746   const v8::String::ExternalStringResourceBase* expected;
   5747   Encoding expectedEncoding;
   5748 
   5749   if (str->IsThinString()) {
   5750     str = i::ThinString::cast(str)->actual();
   5751   }
   5752 
   5753   if (i::StringShape(str).IsExternalOneByte()) {
   5754     const void* resource = i::ExternalOneByteString::cast(str)->resource();
   5755     expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
   5756     expectedEncoding = ONE_BYTE_ENCODING;
   5757   } else if (i::StringShape(str).IsExternalTwoByte()) {
   5758     const void* resource = i::ExternalTwoByteString::cast(str)->resource();
   5759     expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
   5760     expectedEncoding = TWO_BYTE_ENCODING;
   5761   } else {
   5762     expected = nullptr;
   5763     expectedEncoding =
   5764         str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
   5765   }
   5766   CHECK_EQ(expected, value);
   5767   CHECK_EQ(expectedEncoding, encoding);
   5768 }
   5769 
   5770 String::ExternalStringResource* String::GetExternalStringResourceSlow() const {
   5771   i::DisallowHeapAllocation no_allocation;
   5772   typedef internal::Internals I;
   5773   ExternalStringResource* result = nullptr;
   5774   i::String* str = *Utils::OpenHandle(this);
   5775 
   5776   if (str->IsThinString()) {
   5777     str = i::ThinString::cast(str)->actual();
   5778   }
   5779 
   5780   if (i::StringShape(str).IsExternalTwoByte()) {
   5781     void* value = I::ReadField<void*>(str, I::kStringResourceOffset);
   5782     result = reinterpret_cast<String::ExternalStringResource*>(value);
   5783   }
   5784   return result;
   5785 }
   5786 
   5787 String::ExternalStringResourceBase* String::GetExternalStringResourceBaseSlow(
   5788     String::Encoding* encoding_out) const {
   5789   i::DisallowHeapAllocation no_allocation;
   5790   typedef internal::Internals I;
   5791   ExternalStringResourceBase* resource = nullptr;
   5792   i::String* str = *Utils::OpenHandle(this);
   5793 
   5794   if (str->IsThinString()) {
   5795     str = i::ThinString::cast(str)->actual();
   5796   }
   5797 
   5798   int type = I::GetInstanceType(str) & I::kFullStringRepresentationMask;
   5799   *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
   5800   if (i::StringShape(str).IsExternalOneByte() ||
   5801       i::StringShape(str).IsExternalTwoByte()) {
   5802     void* value = I::ReadField<void*>(str, I::kStringResourceOffset);
   5803     resource = static_cast<ExternalStringResourceBase*>(value);
   5804   }
   5805   return resource;
   5806 }
   5807 
   5808 const String::ExternalOneByteStringResource*
   5809 String::GetExternalOneByteStringResourceSlow() const {
   5810   i::DisallowHeapAllocation no_allocation;
   5811   i::String* str = *Utils::OpenHandle(this);
   5812 
   5813   if (str->IsThinString()) {
   5814     str = i::ThinString::cast(str)->actual();
   5815   }
   5816 
   5817   if (i::StringShape(str).IsExternalOneByte()) {
   5818     const void* resource = i::ExternalOneByteString::cast(str)->resource();
   5819     return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
   5820   }
   5821   return nullptr;
   5822 }
   5823 
   5824 const v8::String::ExternalOneByteStringResource*
   5825 v8::String::GetExternalOneByteStringResource() const {
   5826   i::DisallowHeapAllocation no_allocation;
   5827   i::String* str = *Utils::OpenHandle(this);
   5828   if (i::StringShape(str).IsExternalOneByte()) {
   5829     const void* resource = i::ExternalOneByteString::cast(str)->resource();
   5830     return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
   5831   } else {
   5832     return GetExternalOneByteStringResourceSlow();
   5833   }
   5834 }
   5835 
   5836 
   5837 Local<Value> Symbol::Name() const {
   5838   i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
   5839 
   5840   i::Isolate* isolate;
   5841   if (!i::Isolate::FromWritableHeapObject(*sym, &isolate)) {
   5842     // If the Symbol is in RO_SPACE, then its name must be too. Since RO_SPACE
   5843     // objects are immovable we can use the Handle(T**) constructor with the
   5844     // address of the name field in the Symbol object without needing an
   5845     // isolate.
   5846     i::Handle<i::HeapObject> ro_name(reinterpret_cast<i::HeapObject**>(
   5847         sym->GetFieldAddress(i::Symbol::kNameOffset)));
   5848     return Utils::ToLocal(ro_name);
   5849   }
   5850 
   5851   i::Handle<i::Object> name(sym->name(), isolate);
   5852 
   5853   return Utils::ToLocal(name);
   5854 }
   5855 
   5856 
   5857 Local<Value> Private::Name() const {
   5858   return reinterpret_cast<const Symbol*>(this)->Name();
   5859 }
   5860 
   5861 
   5862 double Number::Value() const {
   5863   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   5864   return obj->Number();
   5865 }
   5866 
   5867 
   5868 bool Boolean::Value() const {
   5869   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   5870   return obj->IsTrue();
   5871 }
   5872 
   5873 
   5874 int64_t Integer::Value() const {
   5875   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   5876   if (obj->IsSmi()) {
   5877     return i::Smi::ToInt(*obj);
   5878   } else {
   5879     return static_cast<int64_t>(obj->Number());
   5880   }
   5881 }
   5882 
   5883 
   5884 int32_t Int32::Value() const {
   5885   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   5886   if (obj->IsSmi()) {
   5887     return i::Smi::ToInt(*obj);
   5888   } else {
   5889     return static_cast<int32_t>(obj->Number());
   5890   }
   5891 }
   5892 
   5893 
   5894 uint32_t Uint32::Value() const {
   5895   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   5896   if (obj->IsSmi()) {
   5897     return i::Smi::ToInt(*obj);
   5898   } else {
   5899     return static_cast<uint32_t>(obj->Number());
   5900   }
   5901 }
   5902 
   5903 int v8::Object::InternalFieldCount() {
   5904   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
   5905   if (!self->IsJSObject()) return 0;
   5906   return i::Handle<i::JSObject>::cast(self)->GetEmbedderFieldCount();
   5907 }
   5908 
   5909 static bool InternalFieldOK(i::Handle<i::JSReceiver> obj, int index,
   5910                             const char* location) {
   5911   return Utils::ApiCheck(
   5912       obj->IsJSObject() &&
   5913           (index < i::Handle<i::JSObject>::cast(obj)->GetEmbedderFieldCount()),
   5914       location, "Internal field out of bounds");
   5915 }
   5916 
   5917 Local<Value> v8::Object::SlowGetInternalField(int index) {
   5918   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
   5919   const char* location = "v8::Object::GetInternalField()";
   5920   if (!InternalFieldOK(obj, index, location)) return Local<Value>();
   5921   i::Handle<i::Object> value(
   5922       i::Handle<i::JSObject>::cast(obj)->GetEmbedderField(index),
   5923       obj->GetIsolate());
   5924   return Utils::ToLocal(value);
   5925 }
   5926 
   5927 void v8::Object::SetInternalField(int index, v8::Local<Value> value) {
   5928   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
   5929   const char* location = "v8::Object::SetInternalField()";
   5930   if (!InternalFieldOK(obj, index, location)) return;
   5931   i::Handle<i::Object> val = Utils::OpenHandle(*value);
   5932   i::Handle<i::JSObject>::cast(obj)->SetEmbedderField(index, *val);
   5933 }
   5934 
   5935 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
   5936   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
   5937   const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
   5938   if (!InternalFieldOK(obj, index, location)) return nullptr;
   5939   return DecodeSmiToAligned(
   5940       i::Handle<i::JSObject>::cast(obj)->GetEmbedderField(index), location);
   5941 }
   5942 
   5943 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
   5944   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
   5945   const char* location = "v8::Object::SetAlignedPointerInInternalField()";
   5946   if (!InternalFieldOK(obj, index, location)) return;
   5947   i::Handle<i::JSObject>::cast(obj)->SetEmbedderField(
   5948       index, EncodeAlignedAsSmi(value, location));
   5949   DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
   5950 }
   5951 
   5952 void v8::Object::SetAlignedPointerInInternalFields(int argc, int indices[],
   5953                                                    void* values[]) {
   5954   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
   5955   const char* location = "v8::Object::SetAlignedPointerInInternalFields()";
   5956   i::DisallowHeapAllocation no_gc;
   5957   i::JSObject* object = i::JSObject::cast(*obj);
   5958   int nof_embedder_fields = object->GetEmbedderFieldCount();
   5959   for (int i = 0; i < argc; i++) {
   5960     int index = indices[i];
   5961     if (!Utils::ApiCheck(index < nof_embedder_fields, location,
   5962                          "Internal field out of bounds")) {
   5963       return;
   5964     }
   5965     void* value = values[i];
   5966     object->SetEmbedderField(index, EncodeAlignedAsSmi(value, location));
   5967     DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
   5968   }
   5969 }
   5970 
   5971 static void* ExternalValue(i::Object* obj) {
   5972   // Obscure semantics for undefined, but somehow checked in our unit tests...
   5973   if (obj->IsUndefined()) {
   5974     return nullptr;
   5975   }
   5976   i::Object* foreign = i::JSObject::cast(obj)->GetEmbedderField(0);
   5977   return reinterpret_cast<void*>(i::Foreign::cast(foreign)->foreign_address());
   5978 }
   5979 
   5980 
   5981 // --- E n v i r o n m e n t ---
   5982 
   5983 
   5984 void v8::V8::InitializePlatform(Platform* platform) {
   5985   i::V8::InitializePlatform(platform);
   5986 }
   5987 
   5988 
   5989 void v8::V8::ShutdownPlatform() {
   5990   i::V8::ShutdownPlatform();
   5991 }
   5992 
   5993 
   5994 bool v8::V8::Initialize() {
   5995   i::V8::Initialize();
   5996 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
   5997   i::ReadNatives();
   5998 #endif
   5999   return true;
   6000 }
   6001 
   6002 #if V8_OS_POSIX
   6003 bool V8::TryHandleSignal(int signum, void* info, void* context) {
   6004 #if V8_OS_LINUX && V8_TARGET_ARCH_X64 && !V8_OS_ANDROID
   6005   return v8::internal::trap_handler::TryHandleSignal(
   6006       signum, static_cast<siginfo_t*>(info), static_cast<ucontext_t*>(context));
   6007 #else  // V8_OS_LINUX && V8_TARGET_ARCH_X64 && !V8_OS_ANDROID
   6008   return false;
   6009 #endif
   6010 }
   6011 #endif
   6012 
   6013 bool V8::RegisterDefaultSignalHandler() {
   6014   return v8::internal::trap_handler::RegisterDefaultTrapHandler();
   6015 }
   6016 
   6017 bool V8::EnableWebAssemblyTrapHandler(bool use_v8_signal_handler) {
   6018   return v8::internal::trap_handler::EnableTrapHandler(use_v8_signal_handler);
   6019 }
   6020 
   6021 void v8::V8::SetEntropySource(EntropySource entropy_source) {
   6022   base::RandomNumberGenerator::SetEntropySource(entropy_source);
   6023 }
   6024 
   6025 
   6026 void v8::V8::SetReturnAddressLocationResolver(
   6027     ReturnAddressLocationResolver return_address_resolver) {
   6028   i::StackFrame::SetReturnAddressLocationResolver(return_address_resolver);
   6029 }
   6030 
   6031 
   6032 bool v8::V8::Dispose() {
   6033   i::V8::TearDown();
   6034 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
   6035   i::DisposeNatives();
   6036 #endif
   6037   return true;
   6038 }
   6039 
   6040 HeapStatistics::HeapStatistics()
   6041     : total_heap_size_(0),
   6042       total_heap_size_executable_(0),
   6043       total_physical_size_(0),
   6044       total_available_size_(0),
   6045       used_heap_size_(0),
   6046       heap_size_limit_(0),
   6047       malloced_memory_(0),
   6048       external_memory_(0),
   6049       peak_malloced_memory_(0),
   6050       does_zap_garbage_(0),
   6051       number_of_native_contexts_(0),
   6052       number_of_detached_contexts_(0) {}
   6053 
   6054 HeapSpaceStatistics::HeapSpaceStatistics(): space_name_(0),
   6055                                             space_size_(0),
   6056                                             space_used_size_(0),
   6057                                             space_available_size_(0),
   6058                                             physical_space_size_(0) { }
   6059 
   6060 
   6061 HeapObjectStatistics::HeapObjectStatistics()
   6062     : object_type_(nullptr),
   6063       object_sub_type_(nullptr),
   6064       object_count_(0),
   6065       object_size_(0) {}
   6066 
   6067 HeapCodeStatistics::HeapCodeStatistics()
   6068     : code_and_metadata_size_(0),
   6069       bytecode_and_metadata_size_(0),
   6070       external_script_source_size_(0) {}
   6071 
   6072 bool v8::V8::InitializeICU(const char* icu_data_file) {
   6073   return i::InitializeICU(icu_data_file);
   6074 }
   6075 
   6076 bool v8::V8::InitializeICUDefaultLocation(const char* exec_path,
   6077                                           const char* icu_data_file) {
   6078   return i::InitializeICUDefaultLocation(exec_path, icu_data_file);
   6079 }
   6080 
   6081 void v8::V8::InitializeExternalStartupData(const char* directory_path) {
   6082   i::InitializeExternalStartupData(directory_path);
   6083 }
   6084 
   6085 
   6086 void v8::V8::InitializeExternalStartupData(const char* natives_blob,
   6087                                            const char* snapshot_blob) {
   6088   i::InitializeExternalStartupData(natives_blob, snapshot_blob);
   6089 }
   6090 
   6091 
   6092 const char* v8::V8::GetVersion() {
   6093   return i::Version::GetVersion();
   6094 }
   6095 
   6096 template <typename ObjectType>
   6097 struct InvokeBootstrapper;
   6098 
   6099 template <>
   6100 struct InvokeBootstrapper<i::Context> {
   6101   i::Handle<i::Context> Invoke(
   6102       i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy,
   6103       v8::Local<v8::ObjectTemplate> global_proxy_template,
   6104       v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
   6105       v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
   6106     return isolate->bootstrapper()->CreateEnvironment(
   6107         maybe_global_proxy, global_proxy_template, extensions,
   6108         context_snapshot_index, embedder_fields_deserializer);
   6109   }
   6110 };
   6111 
   6112 template <>
   6113 struct InvokeBootstrapper<i::JSGlobalProxy> {
   6114   i::Handle<i::JSGlobalProxy> Invoke(
   6115       i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy,
   6116       v8::Local<v8::ObjectTemplate> global_proxy_template,
   6117       v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
   6118       v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
   6119     USE(extensions);
   6120     USE(context_snapshot_index);
   6121     return isolate->bootstrapper()->NewRemoteContext(maybe_global_proxy,
   6122                                                      global_proxy_template);
   6123   }
   6124 };
   6125 
   6126 template <typename ObjectType>
   6127 static i::Handle<ObjectType> CreateEnvironment(
   6128     i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
   6129     v8::MaybeLocal<ObjectTemplate> maybe_global_template,
   6130     v8::MaybeLocal<Value> maybe_global_proxy, size_t context_snapshot_index,
   6131     v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
   6132   i::Handle<ObjectType> result;
   6133 
   6134   {
   6135     ENTER_V8_FOR_NEW_CONTEXT(isolate);
   6136     v8::Local<ObjectTemplate> proxy_template;
   6137     i::Handle<i::FunctionTemplateInfo> proxy_constructor;
   6138     i::Handle<i::FunctionTemplateInfo> global_constructor;
   6139     i::Handle<i::Object> named_interceptor(
   6140         isolate->factory()->undefined_value());
   6141     i::Handle<i::Object> indexed_interceptor(
   6142         isolate->factory()->undefined_value());
   6143 
   6144     if (!maybe_global_template.IsEmpty()) {
   6145       v8::Local<v8::ObjectTemplate> global_template =
   6146           maybe_global_template.ToLocalChecked();
   6147       // Make sure that the global_template has a constructor.
   6148       global_constructor = EnsureConstructor(isolate, *global_template);
   6149 
   6150       // Create a fresh template for the global proxy object.
   6151       proxy_template = ObjectTemplate::New(
   6152           reinterpret_cast<v8::Isolate*>(isolate));
   6153       proxy_constructor = EnsureConstructor(isolate, *proxy_template);
   6154 
   6155       // Set the global template to be the prototype template of
   6156       // global proxy template.
   6157       proxy_constructor->set_prototype_template(
   6158           *Utils::OpenHandle(*global_template));
   6159 
   6160       proxy_template->SetInternalFieldCount(
   6161           global_template->InternalFieldCount());
   6162 
   6163       // Migrate security handlers from global_template to
   6164       // proxy_template.  Temporarily removing access check
   6165       // information from the global template.
   6166       if (!global_constructor->access_check_info()->IsUndefined(isolate)) {
   6167         proxy_constructor->set_access_check_info(
   6168             global_constructor->access_check_info());
   6169         proxy_constructor->set_needs_access_check(
   6170             global_constructor->needs_access_check());
   6171         global_constructor->set_needs_access_check(false);
   6172         global_constructor->set_access_check_info(
   6173             i::ReadOnlyRoots(isolate).undefined_value());
   6174       }
   6175 
   6176       // Same for other interceptors. If the global constructor has
   6177       // interceptors, we need to replace them temporarily with noop
   6178       // interceptors, so the map is correctly marked as having interceptors,
   6179       // but we don't invoke any.
   6180       if (!global_constructor->named_property_handler()->IsUndefined(isolate)) {
   6181         named_interceptor =
   6182             handle(global_constructor->named_property_handler(), isolate);
   6183         global_constructor->set_named_property_handler(
   6184             i::ReadOnlyRoots(isolate).noop_interceptor_info());
   6185       }
   6186       if (!global_constructor->indexed_property_handler()->IsUndefined(
   6187               isolate)) {
   6188         indexed_interceptor =
   6189             handle(global_constructor->indexed_property_handler(), isolate);
   6190         global_constructor->set_indexed_property_handler(
   6191             i::ReadOnlyRoots(isolate).noop_interceptor_info());
   6192       }
   6193     }
   6194 
   6195     i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
   6196     if (!maybe_global_proxy.IsEmpty()) {
   6197       maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(
   6198           Utils::OpenHandle(*maybe_global_proxy.ToLocalChecked()));
   6199     }
   6200     // Create the environment.
   6201     InvokeBootstrapper<ObjectType> invoke;
   6202     result =
   6203         invoke.Invoke(isolate, maybe_proxy, proxy_template, extensions,
   6204                       context_snapshot_index, embedder_fields_deserializer);
   6205 
   6206     // Restore the access check info and interceptors on the global template.
   6207     if (!maybe_global_template.IsEmpty()) {
   6208       DCHECK(!global_constructor.is_null());
   6209       DCHECK(!proxy_constructor.is_null());
   6210       global_constructor->set_access_check_info(
   6211           proxy_constructor->access_check_info());
   6212       global_constructor->set_needs_access_check(
   6213           proxy_constructor->needs_access_check());
   6214       global_constructor->set_named_property_handler(*named_interceptor);
   6215       global_constructor->set_indexed_property_handler(*indexed_interceptor);
   6216     }
   6217   }
   6218   // Leave V8.
   6219 
   6220   return result;
   6221 }
   6222 
   6223 Local<Context> NewContext(
   6224     v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
   6225     v8::MaybeLocal<ObjectTemplate> global_template,
   6226     v8::MaybeLocal<Value> global_object, size_t context_snapshot_index,
   6227     v8::DeserializeInternalFieldsCallback embedder_fields_deserializer) {
   6228   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
   6229   // TODO(jkummerow): This is for crbug.com/713699. Remove it if it doesn't
   6230   // fail.
   6231   // Sanity-check that the isolate is initialized and usable.
   6232   CHECK(isolate->builtins()->builtin(i::Builtins::kIllegal)->IsCode());
   6233 
   6234   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.NewContext");
   6235   LOG_API(isolate, Context, New);
   6236   i::HandleScope scope(isolate);
   6237   ExtensionConfiguration no_extensions;
   6238   if (extensions == nullptr) extensions = &no_extensions;
   6239   i::Handle<i::Context> env = CreateEnvironment<i::Context>(
   6240       isolate, extensions, global_template, global_object,
   6241       context_snapshot_index, embedder_fields_deserializer);
   6242   if (env.is_null()) {
   6243     if (isolate->has_pending_exception()) isolate->clear_pending_exception();
   6244     return Local<Context>();
   6245   }
   6246   return Utils::ToLocal(scope.CloseAndEscape(env));
   6247 }
   6248 
   6249 Local<Context> v8::Context::New(
   6250     v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
   6251     v8::MaybeLocal<ObjectTemplate> global_template,
   6252     v8::MaybeLocal<Value> global_object,
   6253     DeserializeInternalFieldsCallback internal_fields_deserializer) {
   6254   return NewContext(external_isolate, extensions, global_template,
   6255                     global_object, 0, internal_fields_deserializer);
   6256 }
   6257 
   6258 MaybeLocal<Context> v8::Context::FromSnapshot(
   6259     v8::Isolate* external_isolate, size_t context_snapshot_index,
   6260     v8::DeserializeInternalFieldsCallback embedder_fields_deserializer,
   6261     v8::ExtensionConfiguration* extensions, MaybeLocal<Value> global_object) {
   6262   size_t index_including_default_context = context_snapshot_index + 1;
   6263   if (!i::Snapshot::HasContextSnapshot(
   6264           reinterpret_cast<i::Isolate*>(external_isolate),
   6265           index_including_default_context)) {
   6266     return MaybeLocal<Context>();
   6267   }
   6268   return NewContext(external_isolate, extensions, MaybeLocal<ObjectTemplate>(),
   6269                     global_object, index_including_default_context,
   6270                     embedder_fields_deserializer);
   6271 }
   6272 
   6273 MaybeLocal<Object> v8::Context::NewRemoteContext(
   6274     v8::Isolate* external_isolate, v8::Local<ObjectTemplate> global_template,
   6275     v8::MaybeLocal<v8::Value> global_object) {
   6276   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
   6277   LOG_API(isolate, Context, NewRemoteContext);
   6278   i::HandleScope scope(isolate);
   6279   i::Handle<i::FunctionTemplateInfo> global_constructor =
   6280       EnsureConstructor(isolate, *global_template);
   6281   Utils::ApiCheck(global_constructor->needs_access_check(),
   6282                   "v8::Context::NewRemoteContext",
   6283                   "Global template needs to have access checks enabled.");
   6284   i::Handle<i::AccessCheckInfo> access_check_info = i::handle(
   6285       i::AccessCheckInfo::cast(global_constructor->access_check_info()),
   6286       isolate);
   6287   Utils::ApiCheck(access_check_info->named_interceptor() != nullptr,
   6288                   "v8::Context::NewRemoteContext",
   6289                   "Global template needs to have access check handlers.");
   6290   i::Handle<i::JSGlobalProxy> global_proxy =
   6291       CreateEnvironment<i::JSGlobalProxy>(isolate, nullptr, global_template,
   6292                                           global_object, 0,
   6293                                           DeserializeInternalFieldsCallback());
   6294   if (global_proxy.is_null()) {
   6295     if (isolate->has_pending_exception()) isolate->clear_pending_exception();
   6296     return MaybeLocal<Object>();
   6297   }
   6298   return Utils::ToLocal(
   6299       scope.CloseAndEscape(i::Handle<i::JSObject>::cast(global_proxy)));
   6300 }
   6301 
   6302 void v8::Context::SetSecurityToken(Local<Value> token) {
   6303   i::Handle<i::Context> env = Utils::OpenHandle(this);
   6304   i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
   6305   env->set_security_token(*token_handle);
   6306 }
   6307 
   6308 
   6309 void v8::Context::UseDefaultSecurityToken() {
   6310   i::Handle<i::Context> env = Utils::OpenHandle(this);
   6311   env->set_security_token(env->global_object());
   6312 }
   6313 
   6314 
   6315 Local<Value> v8::Context::GetSecurityToken() {
   6316   i::Handle<i::Context> env = Utils::OpenHandle(this);
   6317   i::Isolate* isolate = env->GetIsolate();
   6318   i::Object* security_token = env->security_token();
   6319   i::Handle<i::Object> token_handle(security_token, isolate);
   6320   return Utils::ToLocal(token_handle);
   6321 }
   6322 
   6323 
   6324 v8::Isolate* Context::GetIsolate() {
   6325   i::Handle<i::Context> env = Utils::OpenHandle(this);
   6326   return reinterpret_cast<Isolate*>(env->GetIsolate());
   6327 }
   6328 
   6329 v8::Local<v8::Object> Context::Global() {
   6330   i::Handle<i::Context> context = Utils::OpenHandle(this);
   6331   i::Isolate* isolate = context->GetIsolate();
   6332   i::Handle<i::Object> global(context->global_proxy(), isolate);
   6333   // TODO(dcarney): This should always return the global proxy
   6334   // but can't presently as calls to GetProtoype will return the wrong result.
   6335   if (i::Handle<i::JSGlobalProxy>::cast(
   6336           global)->IsDetachedFrom(context->global_object())) {
   6337     global = i::Handle<i::Object>(context->global_object(), isolate);
   6338   }
   6339   return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
   6340 }
   6341 
   6342 
   6343 void Context::DetachGlobal() {
   6344   i::Handle<i::Context> context = Utils::OpenHandle(this);
   6345   i::Isolate* isolate = context->GetIsolate();
   6346   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   6347   isolate->bootstrapper()->DetachGlobal(context);
   6348 }
   6349 
   6350 
   6351 Local<v8::Object> Context::GetExtrasBindingObject() {
   6352   i::Handle<i::Context> context = Utils::OpenHandle(this);
   6353   i::Isolate* isolate = context->GetIsolate();
   6354   i::Handle<i::JSObject> binding(context->extras_binding_object(), isolate);
   6355   return Utils::ToLocal(binding);
   6356 }
   6357 
   6358 
   6359 void Context::AllowCodeGenerationFromStrings(bool allow) {
   6360   i::Handle<i::Context> context = Utils::OpenHandle(this);
   6361   i::Isolate* isolate = context->GetIsolate();
   6362   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   6363   context->set_allow_code_gen_from_strings(
   6364       allow ? i::ReadOnlyRoots(isolate).true_value()
   6365             : i::ReadOnlyRoots(isolate).false_value());
   6366 }
   6367 
   6368 
   6369 bool Context::IsCodeGenerationFromStringsAllowed() {
   6370   i::Handle<i::Context> context = Utils::OpenHandle(this);
   6371   return !context->allow_code_gen_from_strings()->IsFalse(
   6372       context->GetIsolate());
   6373 }
   6374 
   6375 
   6376 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
   6377   i::Handle<i::Context> context = Utils::OpenHandle(this);
   6378   i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
   6379   context->set_error_message_for_code_gen_from_strings(*error_handle);
   6380 }
   6381 
   6382 namespace {
   6383 i::Object** GetSerializedDataFromFixedArray(i::Isolate* isolate,
   6384                                             i::FixedArray* list, size_t index) {
   6385   if (index < static_cast<size_t>(list->length())) {
   6386     int int_index = static_cast<int>(index);
   6387     i::Object* object = list->get(int_index);
   6388     if (!object->IsTheHole(isolate)) {
   6389       list->set_the_hole(isolate, int_index);
   6390       // Shrink the list so that the last element is not the hole (unless it's
   6391       // the first element, because we don't want to end up with a non-canonical
   6392       // empty FixedArray).
   6393       int last = list->length() - 1;
   6394       while (last >= 0 && list->is_the_hole(isolate, last)) last--;
   6395       if (last != -1) list->Shrink(isolate, last + 1);
   6396       return i::Handle<i::Object>(object, isolate).location();
   6397     }
   6398   }
   6399   return nullptr;
   6400 }
   6401 }  // anonymous namespace
   6402 
   6403 i::Object** Context::GetDataFromSnapshotOnce(size_t index) {
   6404   auto context = Utils::OpenHandle(this);
   6405   i::Isolate* i_isolate = context->GetIsolate();
   6406   i::FixedArray* list = context->serialized_objects();
   6407   return GetSerializedDataFromFixedArray(i_isolate, list, index);
   6408 }
   6409 
   6410 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
   6411   PREPARE_FOR_EXECUTION(context, ObjectTemplate, NewInstance, Object);
   6412   auto self = Utils::OpenHandle(this);
   6413   Local<Object> result;
   6414   has_pending_exception = !ToLocal<Object>(
   6415       i::ApiNatives::InstantiateObject(isolate, self), &result);
   6416   RETURN_ON_FAILED_EXECUTION(Object);
   6417   RETURN_ESCAPED(result);
   6418 }
   6419 
   6420 
   6421 Local<v8::Object> ObjectTemplate::NewInstance() {
   6422   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   6423   RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object);
   6424 }
   6425 
   6426 void v8::ObjectTemplate::CheckCast(Data* that) {
   6427   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   6428   Utils::ApiCheck(obj->IsObjectTemplateInfo(), "v8::ObjectTemplate::Cast",
   6429                   "Could not convert to object template");
   6430 }
   6431 
   6432 void v8::FunctionTemplate::CheckCast(Data* that) {
   6433   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   6434   Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::FunctionTemplate::Cast",
   6435                   "Could not convert to function template");
   6436 }
   6437 
   6438 void v8::Signature::CheckCast(Data* that) {
   6439   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   6440   Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::Signature::Cast",
   6441                   "Could not convert to signature");
   6442 }
   6443 
   6444 void v8::AccessorSignature::CheckCast(Data* that) {
   6445   i::Handle<i::Object> obj = Utils::OpenHandle(that);
   6446   Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::AccessorSignature::Cast",
   6447                   "Could not convert to accessor signature");
   6448 }
   6449 
   6450 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
   6451   PREPARE_FOR_EXECUTION(context, FunctionTemplate, GetFunction, Function);
   6452   auto self = Utils::OpenHandle(this);
   6453   Local<Function> result;
   6454   has_pending_exception =
   6455       !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
   6456   RETURN_ON_FAILED_EXECUTION(Function);
   6457   RETURN_ESCAPED(result);
   6458 }
   6459 
   6460 
   6461 Local<v8::Function> FunctionTemplate::GetFunction() {
   6462   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
   6463   RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function);
   6464 }
   6465 
   6466 MaybeLocal<v8::Object> FunctionTemplate::NewRemoteInstance() {
   6467   auto self = Utils::OpenHandle(this);
   6468   i::Isolate* isolate = self->GetIsolate();
   6469   LOG_API(isolate, FunctionTemplate, NewRemoteInstance);
   6470   i::HandleScope scope(isolate);
   6471   i::Handle<i::FunctionTemplateInfo> constructor =
   6472       EnsureConstructor(isolate, *InstanceTemplate());
   6473   Utils::ApiCheck(constructor->needs_access_check(),
   6474                   "v8::FunctionTemplate::NewRemoteInstance",
   6475                   "InstanceTemplate needs to have access checks enabled.");
   6476   i::Handle<i::AccessCheckInfo> access_check_info = i::handle(
   6477       i::AccessCheckInfo::cast(constructor->access_check_info()), isolate);
   6478   Utils::ApiCheck(access_check_info->named_interceptor() != nullptr,
   6479                   "v8::FunctionTemplate::NewRemoteInstance",
   6480                   "InstanceTemplate needs to have access check handlers.");
   6481   i::Handle<i::JSObject> object;
   6482   if (!i::ApiNatives::InstantiateRemoteObject(
   6483            Utils::OpenHandle(*InstanceTemplate()))
   6484            .ToHandle(&object)) {
   6485     if (isolate->has_pending_exception()) {
   6486       isolate->OptionalRescheduleException(true);
   6487     }
   6488     return MaybeLocal<Object>();
   6489   }
   6490   return Utils::ToLocal(scope.CloseAndEscape(object));
   6491 }
   6492 
   6493 bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) {
   6494   auto self = Utils::OpenHandle(this);
   6495   auto obj = Utils::OpenHandle(*value);
   6496   if (obj->IsJSObject() && self->IsTemplateFor(i::JSObject::cast(*obj))) {
   6497     return true;
   6498   }
   6499   if (obj->IsJSGlobalProxy()) {
   6500     // If it's a global proxy, then test with the global object. Note that the
   6501     // inner global object may not necessarily be a JSGlobalObject.
   6502     i::PrototypeIterator iter(self->GetIsolate(),
   6503                               i::JSObject::cast(*obj)->map());
   6504     // The global proxy should always have a prototype, as it is a bug to call
   6505     // this on a detached JSGlobalProxy.
   6506     DCHECK(!iter.IsAtEnd());
   6507     return self->IsTemplateFor(iter.GetCurrent<i::JSObject>());
   6508   }
   6509   return false;
   6510 }
   6511 
   6512 
   6513 Local<External> v8::External::New(Isolate* isolate, void* value) {
   6514   STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
   6515   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6516   LOG_API(i_isolate, External, New);
   6517   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6518   i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
   6519   return Utils::ExternalToLocal(external);
   6520 }
   6521 
   6522 
   6523 void* External::Value() const {
   6524   return ExternalValue(*Utils::OpenHandle(this));
   6525 }
   6526 
   6527 
   6528 // anonymous namespace for string creation helper functions
   6529 namespace {
   6530 
   6531 inline int StringLength(const char* string) {
   6532   return i::StrLength(string);
   6533 }
   6534 
   6535 
   6536 inline int StringLength(const uint8_t* string) {
   6537   return i::StrLength(reinterpret_cast<const char*>(string));
   6538 }
   6539 
   6540 
   6541 inline int StringLength(const uint16_t* string) {
   6542   int length = 0;
   6543   while (string[length] != '\0')
   6544     length++;
   6545   return length;
   6546 }
   6547 
   6548 V8_WARN_UNUSED_RESULT
   6549 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
   6550                                            v8::NewStringType type,
   6551                                            i::Vector<const char> string) {
   6552   if (type == v8::NewStringType::kInternalized) {
   6553     return factory->InternalizeUtf8String(string);
   6554   }
   6555   return factory->NewStringFromUtf8(string);
   6556 }
   6557 
   6558 V8_WARN_UNUSED_RESULT
   6559 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
   6560                                            v8::NewStringType type,
   6561                                            i::Vector<const uint8_t> string) {
   6562   if (type == v8::NewStringType::kInternalized) {
   6563     return factory->InternalizeOneByteString(string);
   6564   }
   6565   return factory->NewStringFromOneByte(string);
   6566 }
   6567 
   6568 V8_WARN_UNUSED_RESULT
   6569 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
   6570                                            v8::NewStringType type,
   6571                                            i::Vector<const uint16_t> string) {
   6572   if (type == v8::NewStringType::kInternalized) {
   6573     return factory->InternalizeTwoByteString(string);
   6574   }
   6575   return factory->NewStringFromTwoByte(string);
   6576 }
   6577 
   6578 
   6579 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
   6580 
   6581 }  // anonymous namespace
   6582 
   6583 // TODO(dcarney): throw a context free exception.
   6584 #define NEW_STRING(isolate, class_name, function_name, Char, data, type,   \
   6585                    length)                                                 \
   6586   MaybeLocal<String> result;                                               \
   6587   if (length == 0) {                                                       \
   6588     result = String::Empty(isolate);                                       \
   6589   } else if (length > i::String::kMaxLength) {                             \
   6590     result = MaybeLocal<String>();                                         \
   6591   } else {                                                                 \
   6592     i::Isolate* i_isolate = reinterpret_cast<internal::Isolate*>(isolate); \
   6593     ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);                            \
   6594     LOG_API(i_isolate, class_name, function_name);                         \
   6595     if (length < 0) length = StringLength(data);                           \
   6596     i::Handle<i::String> handle_result =                                   \
   6597         NewString(i_isolate->factory(), type,                              \
   6598                   i::Vector<const Char>(data, length))                     \
   6599             .ToHandleChecked();                                            \
   6600     result = Utils::ToLocal(handle_result);                                \
   6601   }
   6602 
   6603 Local<String> String::NewFromUtf8(Isolate* isolate,
   6604                                   const char* data,
   6605                                   NewStringType type,
   6606                                   int length) {
   6607   NEW_STRING(isolate, String, NewFromUtf8, char, data,
   6608              static_cast<v8::NewStringType>(type), length);
   6609   RETURN_TO_LOCAL_UNCHECKED(result, String);
   6610 }
   6611 
   6612 
   6613 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
   6614                                        v8::NewStringType type, int length) {
   6615   NEW_STRING(isolate, String, NewFromUtf8, char, data, type, length);
   6616   return result;
   6617 }
   6618 
   6619 
   6620 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
   6621                                           v8::NewStringType type, int length) {
   6622   NEW_STRING(isolate, String, NewFromOneByte, uint8_t, data, type, length);
   6623   return result;
   6624 }
   6625 
   6626 
   6627 Local<String> String::NewFromTwoByte(Isolate* isolate,
   6628                                      const uint16_t* data,
   6629                                      NewStringType type,
   6630                                      int length) {
   6631   NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data,
   6632              static_cast<v8::NewStringType>(type), length);
   6633   RETURN_TO_LOCAL_UNCHECKED(result, String);
   6634 }
   6635 
   6636 
   6637 MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate,
   6638                                           const uint16_t* data,
   6639                                           v8::NewStringType type, int length) {
   6640   NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data, type, length);
   6641   return result;
   6642 }
   6643 
   6644 Local<String> v8::String::Concat(Isolate* v8_isolate, Local<String> left,
   6645                                  Local<String> right) {
   6646   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   6647   i::Handle<i::String> left_string = Utils::OpenHandle(*left);
   6648   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   6649   LOG_API(isolate, String, Concat);
   6650   i::Handle<i::String> right_string = Utils::OpenHandle(*right);
   6651   // If we are steering towards a range error, do not wait for the error to be
   6652   // thrown, and return the null handle instead.
   6653   if (left_string->length() + right_string->length() > i::String::kMaxLength) {
   6654     return Local<String>();
   6655   }
   6656   i::Handle<i::String> result = isolate->factory()->NewConsString(
   6657       left_string, right_string).ToHandleChecked();
   6658   return Utils::ToLocal(result);
   6659 }
   6660 
   6661 Local<String> v8::String::Concat(Local<String> left, Local<String> right) {
   6662   i::Handle<i::String> left_string = Utils::OpenHandle(*left);
   6663   i::Isolate* isolate = UnsafeIsolateFromHeapObject(left_string);
   6664   return Concat(reinterpret_cast<Isolate*>(isolate), left, right);
   6665 }
   6666 
   6667 MaybeLocal<String> v8::String::NewExternalTwoByte(
   6668     Isolate* isolate, v8::String::ExternalStringResource* resource) {
   6669   CHECK(resource && resource->data());
   6670   // TODO(dcarney): throw a context free exception.
   6671   if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
   6672     return MaybeLocal<String>();
   6673   }
   6674   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6675   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6676   LOG_API(i_isolate, String, NewExternalTwoByte);
   6677   if (resource->length() > 0) {
   6678     i::Handle<i::String> string = i_isolate->factory()
   6679                                       ->NewExternalStringFromTwoByte(resource)
   6680                                       .ToHandleChecked();
   6681     return Utils::ToLocal(string);
   6682   } else {
   6683     // The resource isn't going to be used, free it immediately.
   6684     resource->Dispose();
   6685     return Utils::ToLocal(i_isolate->factory()->empty_string());
   6686   }
   6687 }
   6688 
   6689 
   6690 MaybeLocal<String> v8::String::NewExternalOneByte(
   6691     Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
   6692   CHECK(resource && resource->data());
   6693   // TODO(dcarney): throw a context free exception.
   6694   if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
   6695     return MaybeLocal<String>();
   6696   }
   6697   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6698   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6699   LOG_API(i_isolate, String, NewExternalOneByte);
   6700   if (resource->length() > 0) {
   6701     i::Handle<i::String> string = i_isolate->factory()
   6702                                       ->NewExternalStringFromOneByte(resource)
   6703                                       .ToHandleChecked();
   6704     return Utils::ToLocal(string);
   6705   } else {
   6706     // The resource isn't going to be used, free it immediately.
   6707     resource->Dispose();
   6708     return Utils::ToLocal(i_isolate->factory()->empty_string());
   6709   }
   6710 }
   6711 
   6712 
   6713 Local<String> v8::String::NewExternal(
   6714     Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
   6715   RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
   6716 }
   6717 
   6718 
   6719 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
   6720   i::DisallowHeapAllocation no_allocation;
   6721 
   6722   i::String* obj = *Utils::OpenHandle(this);
   6723 
   6724   if (obj->IsThinString()) {
   6725     obj = i::ThinString::cast(obj)->actual();
   6726   }
   6727 
   6728   if (!obj->SupportsExternalization()) {
   6729     return false;
   6730   }
   6731 
   6732   // It is safe to call FromWritable because SupportsExternalization already
   6733   // checked that the object is writable.
   6734   i::Isolate* isolate;
   6735   i::Isolate::FromWritableHeapObject(obj, &isolate);
   6736   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   6737 
   6738   CHECK(resource && resource->data());
   6739 
   6740   bool result = obj->MakeExternal(resource);
   6741   DCHECK(result);
   6742   DCHECK(obj->IsExternalString());
   6743   return result;
   6744 }
   6745 
   6746 
   6747 bool v8::String::MakeExternal(
   6748     v8::String::ExternalOneByteStringResource* resource) {
   6749   i::DisallowHeapAllocation no_allocation;
   6750 
   6751   i::String* obj = *Utils::OpenHandle(this);
   6752 
   6753   if (obj->IsThinString()) {
   6754     obj = i::ThinString::cast(obj)->actual();
   6755   }
   6756 
   6757   if (!obj->SupportsExternalization()) {
   6758     return false;
   6759   }
   6760 
   6761   // It is safe to call FromWritable because SupportsExternalization already
   6762   // checked that the object is writable.
   6763   i::Isolate* isolate;
   6764   i::Isolate::FromWritableHeapObject(obj, &isolate);
   6765   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   6766 
   6767   CHECK(resource && resource->data());
   6768 
   6769   bool result = obj->MakeExternal(resource);
   6770   DCHECK(result);
   6771   DCHECK(obj->IsExternalString());
   6772   return result;
   6773 }
   6774 
   6775 
   6776 bool v8::String::CanMakeExternal() {
   6777   i::DisallowHeapAllocation no_allocation;
   6778   i::String* obj = *Utils::OpenHandle(this);
   6779 
   6780   if (obj->IsThinString()) {
   6781     obj = i::ThinString::cast(obj)->actual();
   6782   }
   6783 
   6784   if (!obj->SupportsExternalization()) {
   6785     return false;
   6786   }
   6787 
   6788   // Only old space strings should be externalized.
   6789   return !i::Heap::InNewSpace(obj);
   6790 }
   6791 
   6792 bool v8::String::StringEquals(Local<String> that) {
   6793   auto self = Utils::OpenHandle(this);
   6794   auto other = Utils::OpenHandle(*that);
   6795   return self->Equals(*other);
   6796 }
   6797 
   6798 Isolate* v8::Object::GetIsolate() {
   6799   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
   6800   return reinterpret_cast<Isolate*>(i_isolate);
   6801 }
   6802 
   6803 
   6804 Local<v8::Object> v8::Object::New(Isolate* isolate) {
   6805   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6806   LOG_API(i_isolate, Object, New);
   6807   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6808   i::Handle<i::JSObject> obj =
   6809       i_isolate->factory()->NewJSObject(i_isolate->object_function());
   6810   return Utils::ToLocal(obj);
   6811 }
   6812 
   6813 
   6814 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
   6815   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6816   LOG_API(i_isolate, NumberObject, New);
   6817   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6818   i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
   6819   i::Handle<i::Object> obj =
   6820       i::Object::ToObject(i_isolate, number).ToHandleChecked();
   6821   return Utils::ToLocal(obj);
   6822 }
   6823 
   6824 
   6825 double v8::NumberObject::ValueOf() const {
   6826   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   6827   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
   6828   i::Isolate* isolate = jsvalue->GetIsolate();
   6829   LOG_API(isolate, NumberObject, NumberValue);
   6830   return jsvalue->value()->Number();
   6831 }
   6832 
   6833 Local<v8::Value> v8::BigIntObject::New(Isolate* isolate, int64_t value) {
   6834   CHECK(i::FLAG_harmony_bigint);
   6835   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6836   LOG_API(i_isolate, BigIntObject, New);
   6837   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6838   i::Handle<i::Object> bigint = i::BigInt::FromInt64(i_isolate, value);
   6839   i::Handle<i::Object> obj =
   6840       i::Object::ToObject(i_isolate, bigint).ToHandleChecked();
   6841   return Utils::ToLocal(obj);
   6842 }
   6843 
   6844 Local<v8::BigInt> v8::BigIntObject::ValueOf() const {
   6845   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   6846   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
   6847   i::Isolate* isolate = jsvalue->GetIsolate();
   6848   LOG_API(isolate, BigIntObject, BigIntValue);
   6849   return Utils::ToLocal(
   6850       i::Handle<i::BigInt>(i::BigInt::cast(jsvalue->value()), isolate));
   6851 }
   6852 
   6853 Local<v8::Value> v8::BooleanObject::New(Isolate* isolate, bool value) {
   6854   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6855   LOG_API(i_isolate, BooleanObject, New);
   6856   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6857   i::Handle<i::Object> boolean(value
   6858                                    ? i::ReadOnlyRoots(i_isolate).true_value()
   6859                                    : i::ReadOnlyRoots(i_isolate).false_value(),
   6860                                i_isolate);
   6861   i::Handle<i::Object> obj =
   6862       i::Object::ToObject(i_isolate, boolean).ToHandleChecked();
   6863   return Utils::ToLocal(obj);
   6864 }
   6865 
   6866 
   6867 bool v8::BooleanObject::ValueOf() const {
   6868   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   6869   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
   6870   i::Isolate* isolate = jsvalue->GetIsolate();
   6871   LOG_API(isolate, BooleanObject, BooleanValue);
   6872   return jsvalue->value()->IsTrue(isolate);
   6873 }
   6874 
   6875 Local<v8::Value> v8::StringObject::New(Local<String> value) {
   6876   i::Handle<i::String> string = Utils::OpenHandle(*value);
   6877   i::Isolate* isolate = UnsafeIsolateFromHeapObject(string);
   6878   return New(reinterpret_cast<Isolate*>(isolate), value);
   6879 }
   6880 
   6881 Local<v8::Value> v8::StringObject::New(Isolate* v8_isolate,
   6882                                        Local<String> value) {
   6883   i::Handle<i::String> string = Utils::OpenHandle(*value);
   6884   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   6885   LOG_API(isolate, StringObject, New);
   6886   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   6887   i::Handle<i::Object> obj =
   6888       i::Object::ToObject(isolate, string).ToHandleChecked();
   6889   return Utils::ToLocal(obj);
   6890 }
   6891 
   6892 
   6893 Local<v8::String> v8::StringObject::ValueOf() const {
   6894   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   6895   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
   6896   i::Isolate* isolate = jsvalue->GetIsolate();
   6897   LOG_API(isolate, StringObject, StringValue);
   6898   return Utils::ToLocal(
   6899       i::Handle<i::String>(i::String::cast(jsvalue->value()), isolate));
   6900 }
   6901 
   6902 
   6903 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
   6904   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6905   LOG_API(i_isolate, SymbolObject, New);
   6906   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6907   i::Handle<i::Object> obj = i::Object::ToObject(
   6908       i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
   6909   return Utils::ToLocal(obj);
   6910 }
   6911 
   6912 
   6913 Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
   6914   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   6915   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
   6916   i::Isolate* isolate = jsvalue->GetIsolate();
   6917   LOG_API(isolate, SymbolObject, SymbolValue);
   6918   return Utils::ToLocal(
   6919       i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value()), isolate));
   6920 }
   6921 
   6922 
   6923 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
   6924   if (std::isnan(time)) {
   6925     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
   6926     time = std::numeric_limits<double>::quiet_NaN();
   6927   }
   6928   PREPARE_FOR_EXECUTION(context, Date, New, Value);
   6929   Local<Value> result;
   6930   has_pending_exception = !ToLocal<Value>(
   6931       i::JSDate::New(isolate->date_function(), isolate->date_function(), time),
   6932       &result);
   6933   RETURN_ON_FAILED_EXECUTION(Value);
   6934   RETURN_ESCAPED(result);
   6935 }
   6936 
   6937 
   6938 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
   6939   auto context = isolate->GetCurrentContext();
   6940   RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value);
   6941 }
   6942 
   6943 
   6944 double v8::Date::ValueOf() const {
   6945   i::Handle<i::Object> obj = Utils::OpenHandle(this);
   6946   i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
   6947   i::Isolate* isolate = jsdate->GetIsolate();
   6948   LOG_API(isolate, Date, NumberValue);
   6949   return jsdate->value()->Number();
   6950 }
   6951 
   6952 
   6953 void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) {
   6954   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   6955   LOG_API(i_isolate, Date, DateTimeConfigurationChangeNotification);
   6956   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   6957   i_isolate->date_cache()->ResetDateCache();
   6958   if (!i_isolate->eternal_handles()->Exists(
   6959           i::EternalHandles::DATE_CACHE_VERSION)) {
   6960     return;
   6961   }
   6962   i::Handle<i::FixedArray> date_cache_version =
   6963       i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton(
   6964           i::EternalHandles::DATE_CACHE_VERSION));
   6965   DCHECK_EQ(1, date_cache_version->length());
   6966   CHECK(date_cache_version->get(0)->IsSmi());
   6967   date_cache_version->set(
   6968       0, i::Smi::FromInt(i::Smi::ToInt(date_cache_version->get(0)) + 1));
   6969 }
   6970 
   6971 
   6972 MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context,
   6973                                        Local<String> pattern, Flags flags) {
   6974   PREPARE_FOR_EXECUTION(context, RegExp, New, RegExp);
   6975   Local<v8::RegExp> result;
   6976   has_pending_exception =
   6977       !ToLocal<RegExp>(i::JSRegExp::New(isolate, Utils::OpenHandle(*pattern),
   6978                                         static_cast<i::JSRegExp::Flags>(flags)),
   6979                        &result);
   6980   RETURN_ON_FAILED_EXECUTION(RegExp);
   6981   RETURN_ESCAPED(result);
   6982 }
   6983 
   6984 
   6985 Local<v8::String> v8::RegExp::GetSource() const {
   6986   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
   6987   return Utils::ToLocal(
   6988       i::Handle<i::String>(obj->Pattern(), obj->GetIsolate()));
   6989 }
   6990 
   6991 
   6992 // Assert that the static flags cast in GetFlags is valid.
   6993 #define REGEXP_FLAG_ASSERT_EQ(flag)                   \
   6994   STATIC_ASSERT(static_cast<int>(v8::RegExp::flag) == \
   6995                 static_cast<int>(i::JSRegExp::flag))
   6996 REGEXP_FLAG_ASSERT_EQ(kNone);
   6997 REGEXP_FLAG_ASSERT_EQ(kGlobal);
   6998 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase);
   6999 REGEXP_FLAG_ASSERT_EQ(kMultiline);
   7000 REGEXP_FLAG_ASSERT_EQ(kSticky);
   7001 REGEXP_FLAG_ASSERT_EQ(kUnicode);
   7002 #undef REGEXP_FLAG_ASSERT_EQ
   7003 
   7004 v8::RegExp::Flags v8::RegExp::GetFlags() const {
   7005   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
   7006   return RegExp::Flags(static_cast<int>(obj->GetFlags()));
   7007 }
   7008 
   7009 
   7010 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
   7011   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7012   LOG_API(i_isolate, Array, New);
   7013   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7014   int real_length = length > 0 ? length : 0;
   7015   i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
   7016   i::Handle<i::Object> length_obj =
   7017       i_isolate->factory()->NewNumberFromInt(real_length);
   7018   obj->set_length(*length_obj);
   7019   return Utils::ToLocal(obj);
   7020 }
   7021 
   7022 
   7023 uint32_t v8::Array::Length() const {
   7024   i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
   7025   i::Object* length = obj->length();
   7026   if (length->IsSmi()) {
   7027     return i::Smi::ToInt(length);
   7028   } else {
   7029     return static_cast<uint32_t>(length->Number());
   7030   }
   7031 }
   7032 
   7033 
   7034 Local<v8::Map> v8::Map::New(Isolate* isolate) {
   7035   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7036   LOG_API(i_isolate, Map, New);
   7037   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7038   i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
   7039   return Utils::ToLocal(obj);
   7040 }
   7041 
   7042 
   7043 size_t v8::Map::Size() const {
   7044   i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
   7045   return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
   7046 }
   7047 
   7048 
   7049 void Map::Clear() {
   7050   auto self = Utils::OpenHandle(this);
   7051   i::Isolate* isolate = self->GetIsolate();
   7052   LOG_API(isolate, Map, Clear);
   7053   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7054   i::JSMap::Clear(isolate, self);
   7055 }
   7056 
   7057 
   7058 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
   7059   PREPARE_FOR_EXECUTION(context, Map, Get, Value);
   7060   auto self = Utils::OpenHandle(this);
   7061   Local<Value> result;
   7062   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
   7063   has_pending_exception =
   7064       !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
   7065                                          arraysize(argv), argv),
   7066                       &result);
   7067   RETURN_ON_FAILED_EXECUTION(Value);
   7068   RETURN_ESCAPED(result);
   7069 }
   7070 
   7071 
   7072 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
   7073                          Local<Value> value) {
   7074   PREPARE_FOR_EXECUTION(context, Map, Set, Map);
   7075   auto self = Utils::OpenHandle(this);
   7076   i::Handle<i::Object> result;
   7077   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
   7078                                  Utils::OpenHandle(*value)};
   7079   has_pending_exception = !i::Execution::Call(isolate, isolate->map_set(), self,
   7080                                               arraysize(argv), argv)
   7081                                .ToHandle(&result);
   7082   RETURN_ON_FAILED_EXECUTION(Map);
   7083   RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
   7084 }
   7085 
   7086 
   7087 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
   7088   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   7089   ENTER_V8(isolate, context, Map, Has, Nothing<bool>(), i::HandleScope);
   7090   auto self = Utils::OpenHandle(this);
   7091   i::Handle<i::Object> result;
   7092   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
   7093   has_pending_exception = !i::Execution::Call(isolate, isolate->map_has(), self,
   7094                                               arraysize(argv), argv)
   7095                                .ToHandle(&result);
   7096   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   7097   return Just(result->IsTrue(isolate));
   7098 }
   7099 
   7100 
   7101 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
   7102   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   7103   ENTER_V8(isolate, context, Map, Delete, Nothing<bool>(), i::HandleScope);
   7104   auto self = Utils::OpenHandle(this);
   7105   i::Handle<i::Object> result;
   7106   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
   7107   has_pending_exception = !i::Execution::Call(isolate, isolate->map_delete(),
   7108                                               self, arraysize(argv), argv)
   7109                                .ToHandle(&result);
   7110   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   7111   return Just(result->IsTrue(isolate));
   7112 }
   7113 
   7114 namespace {
   7115 
   7116 enum class MapAsArrayKind {
   7117   kEntries = i::JS_MAP_KEY_VALUE_ITERATOR_TYPE,
   7118   kKeys = i::JS_MAP_KEY_ITERATOR_TYPE,
   7119   kValues = i::JS_MAP_VALUE_ITERATOR_TYPE
   7120 };
   7121 
   7122 i::Handle<i::JSArray> MapAsArray(i::Isolate* isolate, i::Object* table_obj,
   7123                                  int offset, MapAsArrayKind kind) {
   7124   i::Factory* factory = isolate->factory();
   7125   i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(table_obj),
   7126                                      isolate);
   7127   if (offset >= table->NumberOfElements()) return factory->NewJSArray(0);
   7128   int length = (table->NumberOfElements() - offset) *
   7129                (kind == MapAsArrayKind::kEntries ? 2 : 1);
   7130   i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
   7131   int result_index = 0;
   7132   {
   7133     i::DisallowHeapAllocation no_gc;
   7134     int capacity = table->UsedCapacity();
   7135     i::Oddball* the_hole = i::ReadOnlyRoots(isolate).the_hole_value();
   7136     for (int i = 0; i < capacity; ++i) {
   7137       i::Object* key = table->KeyAt(i);
   7138       if (key == the_hole) continue;
   7139       if (offset-- > 0) continue;
   7140       if (kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kKeys) {
   7141         result->set(result_index++, key);
   7142       }
   7143       if (kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kValues) {
   7144         result->set(result_index++, table->ValueAt(i));
   7145       }
   7146     }
   7147   }
   7148   DCHECK_EQ(result_index, result->length());
   7149   DCHECK_EQ(result_index, length);
   7150   return factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS, length);
   7151 }
   7152 
   7153 }  // namespace
   7154 
   7155 Local<Array> Map::AsArray() const {
   7156   i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
   7157   i::Isolate* isolate = obj->GetIsolate();
   7158   LOG_API(isolate, Map, AsArray);
   7159   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7160   return Utils::ToLocal(
   7161       MapAsArray(isolate, obj->table(), 0, MapAsArrayKind::kEntries));
   7162 }
   7163 
   7164 
   7165 Local<v8::Set> v8::Set::New(Isolate* isolate) {
   7166   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7167   LOG_API(i_isolate, Set, New);
   7168   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7169   i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
   7170   return Utils::ToLocal(obj);
   7171 }
   7172 
   7173 
   7174 size_t v8::Set::Size() const {
   7175   i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
   7176   return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
   7177 }
   7178 
   7179 
   7180 void Set::Clear() {
   7181   auto self = Utils::OpenHandle(this);
   7182   i::Isolate* isolate = self->GetIsolate();
   7183   LOG_API(isolate, Set, Clear);
   7184   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7185   i::JSSet::Clear(isolate, self);
   7186 }
   7187 
   7188 
   7189 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
   7190   PREPARE_FOR_EXECUTION(context, Set, Add, Set);
   7191   auto self = Utils::OpenHandle(this);
   7192   i::Handle<i::Object> result;
   7193   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
   7194   has_pending_exception = !i::Execution::Call(isolate, isolate->set_add(), self,
   7195                                               arraysize(argv), argv)
   7196                                .ToHandle(&result);
   7197   RETURN_ON_FAILED_EXECUTION(Set);
   7198   RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
   7199 }
   7200 
   7201 
   7202 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
   7203   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   7204   ENTER_V8(isolate, context, Set, Has, Nothing<bool>(), i::HandleScope);
   7205   auto self = Utils::OpenHandle(this);
   7206   i::Handle<i::Object> result;
   7207   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
   7208   has_pending_exception = !i::Execution::Call(isolate, isolate->set_has(), self,
   7209                                               arraysize(argv), argv)
   7210                                .ToHandle(&result);
   7211   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   7212   return Just(result->IsTrue(isolate));
   7213 }
   7214 
   7215 
   7216 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
   7217   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   7218   ENTER_V8(isolate, context, Set, Delete, Nothing<bool>(), i::HandleScope);
   7219   auto self = Utils::OpenHandle(this);
   7220   i::Handle<i::Object> result;
   7221   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
   7222   has_pending_exception = !i::Execution::Call(isolate, isolate->set_delete(),
   7223                                               self, arraysize(argv), argv)
   7224                                .ToHandle(&result);
   7225   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   7226   return Just(result->IsTrue(isolate));
   7227 }
   7228 
   7229 namespace {
   7230 i::Handle<i::JSArray> SetAsArray(i::Isolate* isolate, i::Object* table_obj,
   7231                                  int offset) {
   7232   i::Factory* factory = isolate->factory();
   7233   i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(table_obj),
   7234                                      isolate);
   7235   int length = table->NumberOfElements() - offset;
   7236   if (length <= 0) return factory->NewJSArray(0);
   7237   i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
   7238   int result_index = 0;
   7239   {
   7240     i::DisallowHeapAllocation no_gc;
   7241     int capacity = table->UsedCapacity();
   7242     i::Oddball* the_hole = i::ReadOnlyRoots(isolate).the_hole_value();
   7243     for (int i = 0; i < capacity; ++i) {
   7244       i::Object* key = table->KeyAt(i);
   7245       if (key == the_hole) continue;
   7246       if (offset-- > 0) continue;
   7247       result->set(result_index++, key);
   7248     }
   7249   }
   7250   DCHECK_EQ(result_index, result->length());
   7251   DCHECK_EQ(result_index, length);
   7252   return factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS, length);
   7253 }
   7254 }  // namespace
   7255 
   7256 Local<Array> Set::AsArray() const {
   7257   i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
   7258   i::Isolate* isolate = obj->GetIsolate();
   7259   LOG_API(isolate, Set, AsArray);
   7260   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7261   return Utils::ToLocal(SetAsArray(isolate, obj->table(), 0));
   7262 }
   7263 
   7264 
   7265 MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) {
   7266   PREPARE_FOR_EXECUTION(context, Promise_Resolver, New, Resolver);
   7267   Local<Promise::Resolver> result;
   7268   has_pending_exception =
   7269       !ToLocal<Promise::Resolver>(isolate->factory()->NewJSPromise(), &result);
   7270   RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
   7271   RETURN_ESCAPED(result);
   7272 }
   7273 
   7274 
   7275 Local<Promise> Promise::Resolver::GetPromise() {
   7276   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
   7277   return Local<Promise>::Cast(Utils::ToLocal(promise));
   7278 }
   7279 
   7280 
   7281 Maybe<bool> Promise::Resolver::Resolve(Local<Context> context,
   7282                                        Local<Value> value) {
   7283   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   7284   ENTER_V8(isolate, context, Promise_Resolver, Resolve, Nothing<bool>(),
   7285            i::HandleScope);
   7286   auto self = Utils::OpenHandle(this);
   7287   auto promise = i::Handle<i::JSPromise>::cast(self);
   7288 
   7289   if (promise->status() != Promise::kPending) {
   7290     return Just(true);
   7291   }
   7292 
   7293   has_pending_exception =
   7294       i::JSPromise::Resolve(promise, Utils::OpenHandle(*value)).is_null();
   7295   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   7296   return Just(true);
   7297 }
   7298 
   7299 
   7300 Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
   7301                                       Local<Value> value) {
   7302   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   7303   ENTER_V8(isolate, context, Promise_Resolver, Reject, Nothing<bool>(),
   7304            i::HandleScope);
   7305   auto self = Utils::OpenHandle(this);
   7306   auto promise = i::Handle<i::JSPromise>::cast(self);
   7307 
   7308   if (promise->status() != Promise::kPending) {
   7309     return Just(true);
   7310   }
   7311 
   7312   has_pending_exception =
   7313       i::JSPromise::Reject(promise, Utils::OpenHandle(*value)).is_null();
   7314   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
   7315   return Just(true);
   7316 }
   7317 
   7318 
   7319 MaybeLocal<Promise> Promise::Catch(Local<Context> context,
   7320                                    Local<Function> handler) {
   7321   PREPARE_FOR_EXECUTION(context, Promise, Catch, Promise);
   7322   auto self = Utils::OpenHandle(this);
   7323   i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
   7324   i::Handle<i::Object> result;
   7325   has_pending_exception = !i::Execution::Call(isolate, isolate->promise_catch(),
   7326                                               self, arraysize(argv), argv)
   7327                                .ToHandle(&result);
   7328   RETURN_ON_FAILED_EXECUTION(Promise);
   7329   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
   7330 }
   7331 
   7332 
   7333 MaybeLocal<Promise> Promise::Then(Local<Context> context,
   7334                                   Local<Function> handler) {
   7335   PREPARE_FOR_EXECUTION(context, Promise, Then, Promise);
   7336   auto self = Utils::OpenHandle(this);
   7337   i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
   7338   i::Handle<i::Object> result;
   7339   has_pending_exception = !i::Execution::Call(isolate, isolate->promise_then(),
   7340                                               self, arraysize(argv), argv)
   7341                                .ToHandle(&result);
   7342   RETURN_ON_FAILED_EXECUTION(Promise);
   7343   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
   7344 }
   7345 
   7346 
   7347 bool Promise::HasHandler() {
   7348   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
   7349   i::Isolate* isolate = promise->GetIsolate();
   7350   LOG_API(isolate, Promise, HasRejectHandler);
   7351   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7352   if (promise->IsJSPromise()) {
   7353     i::Handle<i::JSPromise> js_promise = i::Handle<i::JSPromise>::cast(promise);
   7354     return js_promise->has_handler();
   7355   }
   7356   return false;
   7357 }
   7358 
   7359 Local<Value> Promise::Result() {
   7360   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
   7361   i::Isolate* isolate = promise->GetIsolate();
   7362   LOG_API(isolate, Promise, Result);
   7363   i::Handle<i::JSPromise> js_promise = i::Handle<i::JSPromise>::cast(promise);
   7364   Utils::ApiCheck(js_promise->status() != kPending, "v8_Promise_Result",
   7365                   "Promise is still pending");
   7366   i::Handle<i::Object> result(js_promise->result(), isolate);
   7367   return Utils::ToLocal(result);
   7368 }
   7369 
   7370 Promise::PromiseState Promise::State() {
   7371   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
   7372   i::Isolate* isolate = promise->GetIsolate();
   7373   LOG_API(isolate, Promise, Status);
   7374   i::Handle<i::JSPromise> js_promise = i::Handle<i::JSPromise>::cast(promise);
   7375   return static_cast<PromiseState>(js_promise->status());
   7376 }
   7377 
   7378 Local<Value> Proxy::GetTarget() {
   7379   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
   7380   i::Handle<i::Object> target(self->target(), self->GetIsolate());
   7381   return Utils::ToLocal(target);
   7382 }
   7383 
   7384 
   7385 Local<Value> Proxy::GetHandler() {
   7386   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
   7387   i::Handle<i::Object> handler(self->handler(), self->GetIsolate());
   7388   return Utils::ToLocal(handler);
   7389 }
   7390 
   7391 
   7392 bool Proxy::IsRevoked() {
   7393   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
   7394   return self->IsRevoked();
   7395 }
   7396 
   7397 
   7398 void Proxy::Revoke() {
   7399   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
   7400   i::JSProxy::Revoke(self);
   7401 }
   7402 
   7403 
   7404 MaybeLocal<Proxy> Proxy::New(Local<Context> context, Local<Object> local_target,
   7405                              Local<Object> local_handler) {
   7406   PREPARE_FOR_EXECUTION(context, Proxy, New, Proxy);
   7407   i::Handle<i::JSReceiver> target = Utils::OpenHandle(*local_target);
   7408   i::Handle<i::JSReceiver> handler = Utils::OpenHandle(*local_handler);
   7409   Local<Proxy> result;
   7410   has_pending_exception =
   7411       !ToLocal<Proxy>(i::JSProxy::New(isolate, target, handler), &result);
   7412   RETURN_ON_FAILED_EXECUTION(Proxy);
   7413   RETURN_ESCAPED(result);
   7414 }
   7415 
   7416 WasmCompiledModule::BufferReference WasmCompiledModule::GetWasmWireBytesRef() {
   7417   i::Handle<i::WasmModuleObject> obj =
   7418       i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
   7419   i::Vector<const uint8_t> bytes_vec = obj->native_module()->wire_bytes();
   7420   return {bytes_vec.start(), bytes_vec.size()};
   7421 }
   7422 
   7423 Local<String> WasmCompiledModule::GetWasmWireBytes() {
   7424   BufferReference ref = GetWasmWireBytesRef();
   7425   CHECK_LE(ref.size, String::kMaxLength);
   7426   return String::NewFromOneByte(GetIsolate(), ref.start, NewStringType::kNormal,
   7427                                 static_cast<int>(ref.size))
   7428       .ToLocalChecked();
   7429 }
   7430 
   7431 WasmCompiledModule::TransferrableModule
   7432 WasmCompiledModule::GetTransferrableModule() {
   7433   if (i::FLAG_wasm_shared_code) {
   7434     i::Handle<i::WasmModuleObject> obj =
   7435         i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
   7436     return TransferrableModule(obj->managed_native_module()->get());
   7437   } else {
   7438     WasmCompiledModule::SerializedModule serialized_module = Serialize();
   7439     BufferReference wire_bytes_ref = GetWasmWireBytesRef();
   7440     size_t wire_size = wire_bytes_ref.size;
   7441     std::unique_ptr<uint8_t[]> wire_bytes_copy(new uint8_t[wire_size]);
   7442     memcpy(wire_bytes_copy.get(), wire_bytes_ref.start, wire_size);
   7443     return TransferrableModule(std::move(serialized_module),
   7444                                {std::move(wire_bytes_copy), wire_size});
   7445   }
   7446 }
   7447 
   7448 MaybeLocal<WasmCompiledModule> WasmCompiledModule::FromTransferrableModule(
   7449     Isolate* isolate,
   7450     const WasmCompiledModule::TransferrableModule& transferrable_module) {
   7451   if (i::FLAG_wasm_shared_code) {
   7452     i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7453     i::Handle<i::WasmModuleObject> module_object =
   7454         i_isolate->wasm_engine()->ImportNativeModule(
   7455             i_isolate, transferrable_module.shared_module_);
   7456     return Local<WasmCompiledModule>::Cast(
   7457         Utils::ToLocal(i::Handle<i::JSObject>::cast(module_object)));
   7458   } else {
   7459     return Deserialize(isolate, AsReference(transferrable_module.serialized_),
   7460                        AsReference(transferrable_module.wire_bytes_));
   7461   }
   7462 }
   7463 
   7464 WasmCompiledModule::SerializedModule WasmCompiledModule::Serialize() {
   7465   i::Handle<i::WasmModuleObject> obj =
   7466       i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
   7467   i::wasm::NativeModule* native_module = obj->native_module();
   7468   i::wasm::WasmSerializer wasm_serializer(obj->GetIsolate(), native_module);
   7469   size_t buffer_size = wasm_serializer.GetSerializedNativeModuleSize();
   7470   std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
   7471   if (wasm_serializer.SerializeNativeModule({buffer.get(), buffer_size}))
   7472     return {std::move(buffer), buffer_size};
   7473   return {};
   7474 }
   7475 
   7476 MaybeLocal<WasmCompiledModule> WasmCompiledModule::Deserialize(
   7477     Isolate* isolate, WasmCompiledModule::BufferReference serialized_module,
   7478     WasmCompiledModule::BufferReference wire_bytes) {
   7479   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7480   i::MaybeHandle<i::WasmModuleObject> maybe_module_object =
   7481       i::wasm::DeserializeNativeModule(
   7482           i_isolate, {serialized_module.start, serialized_module.size},
   7483           {wire_bytes.start, wire_bytes.size});
   7484   i::Handle<i::WasmModuleObject> module_object;
   7485   if (!maybe_module_object.ToHandle(&module_object)) {
   7486     return MaybeLocal<WasmCompiledModule>();
   7487   }
   7488   return Local<WasmCompiledModule>::Cast(
   7489       Utils::ToLocal(i::Handle<i::JSObject>::cast(module_object)));
   7490 }
   7491 
   7492 MaybeLocal<WasmCompiledModule> WasmCompiledModule::DeserializeOrCompile(
   7493     Isolate* isolate, WasmCompiledModule::BufferReference serialized_module,
   7494     WasmCompiledModule::BufferReference wire_bytes) {
   7495   MaybeLocal<WasmCompiledModule> ret =
   7496       Deserialize(isolate, serialized_module, wire_bytes);
   7497   if (!ret.IsEmpty()) {
   7498     return ret;
   7499   }
   7500   return Compile(isolate, wire_bytes.start, wire_bytes.size);
   7501 }
   7502 
   7503 MaybeLocal<WasmCompiledModule> WasmCompiledModule::Compile(Isolate* isolate,
   7504                                                            const uint8_t* start,
   7505                                                            size_t length) {
   7506   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7507   i::wasm::ErrorThrower thrower(i_isolate, "WasmCompiledModule::Compile()");
   7508   if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
   7509     return MaybeLocal<WasmCompiledModule>();
   7510   }
   7511   auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
   7512   i::MaybeHandle<i::JSObject> maybe_compiled =
   7513       i_isolate->wasm_engine()->SyncCompile(
   7514           i_isolate, enabled_features, &thrower,
   7515           i::wasm::ModuleWireBytes(start, start + length));
   7516   if (maybe_compiled.is_null()) return MaybeLocal<WasmCompiledModule>();
   7517   return Local<WasmCompiledModule>::Cast(
   7518       Utils::ToLocal(maybe_compiled.ToHandleChecked()));
   7519 }
   7520 
   7521 // Resolves the result of streaming compilation.
   7522 // TODO(ahaas): Refactor the streaming compilation API so that this class can
   7523 // move to wasm-js.cc.
   7524 class AsyncCompilationResolver : public i::wasm::CompilationResultResolver {
   7525  public:
   7526   AsyncCompilationResolver(Isolate* isolate, Local<Promise> promise)
   7527       : promise_(
   7528             reinterpret_cast<i::Isolate*>(isolate)->global_handles()->Create(
   7529                 *Utils::OpenHandle(*promise))) {}
   7530 
   7531   ~AsyncCompilationResolver() {
   7532     i::GlobalHandles::Destroy(i::Handle<i::Object>::cast(promise_).location());
   7533   }
   7534 
   7535   void OnCompilationSucceeded(i::Handle<i::WasmModuleObject> result) override {
   7536     i::MaybeHandle<i::Object> promise_result =
   7537         i::JSPromise::Resolve(promise_, result);
   7538     CHECK_EQ(promise_result.is_null(),
   7539              promise_->GetIsolate()->has_pending_exception());
   7540   }
   7541 
   7542   void OnCompilationFailed(i::Handle<i::Object> error_reason) override {
   7543     i::MaybeHandle<i::Object> promise_result =
   7544         i::JSPromise::Reject(promise_, error_reason);
   7545     CHECK_EQ(promise_result.is_null(),
   7546              promise_->GetIsolate()->has_pending_exception());
   7547   }
   7548 
   7549  private:
   7550   i::Handle<i::JSPromise> promise_;
   7551 };
   7552 
   7553 WasmModuleObjectBuilderStreaming::WasmModuleObjectBuilderStreaming(
   7554     Isolate* isolate) {
   7555   USE(isolate_);
   7556 }
   7557 
   7558 Local<Promise> WasmModuleObjectBuilderStreaming::GetPromise() { return {}; }
   7559 
   7560 void WasmModuleObjectBuilderStreaming::OnBytesReceived(const uint8_t* bytes,
   7561                                                        size_t size) {
   7562 }
   7563 
   7564 void WasmModuleObjectBuilderStreaming::Finish() {
   7565 }
   7566 
   7567 void WasmModuleObjectBuilderStreaming::Abort(MaybeLocal<Value> exception) {
   7568 }
   7569 
   7570 WasmModuleObjectBuilderStreaming::~WasmModuleObjectBuilderStreaming() {
   7571 }
   7572 
   7573 // static
   7574 v8::ArrayBuffer::Allocator* v8::ArrayBuffer::Allocator::NewDefaultAllocator() {
   7575   return new ArrayBufferAllocator();
   7576 }
   7577 
   7578 bool v8::ArrayBuffer::IsExternal() const {
   7579   return Utils::OpenHandle(this)->is_external();
   7580 }
   7581 
   7582 
   7583 bool v8::ArrayBuffer::IsNeuterable() const {
   7584   return Utils::OpenHandle(this)->is_neuterable();
   7585 }
   7586 
   7587 
   7588 v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
   7589   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
   7590   i::Isolate* isolate = self->GetIsolate();
   7591   Utils::ApiCheck(!self->is_external(), "v8_ArrayBuffer_Externalize",
   7592                   "ArrayBuffer already externalized");
   7593   self->set_is_external(true);
   7594 
   7595   const v8::ArrayBuffer::Contents contents = GetContents();
   7596   isolate->heap()->UnregisterArrayBuffer(*self);
   7597 
   7598   // A regular copy is good enough. No move semantics needed.
   7599   return contents;
   7600 }
   7601 
   7602 v8::ArrayBuffer::Contents::Contents(void* data, size_t byte_length,
   7603                                     void* allocation_base,
   7604                                     size_t allocation_length,
   7605                                     Allocator::AllocationMode allocation_mode,
   7606                                     DeleterCallback deleter, void* deleter_data)
   7607     : data_(data),
   7608       byte_length_(byte_length),
   7609       allocation_base_(allocation_base),
   7610       allocation_length_(allocation_length),
   7611       allocation_mode_(allocation_mode),
   7612       deleter_(deleter),
   7613       deleter_data_(deleter_data) {
   7614   DCHECK_LE(allocation_base_, data_);
   7615   DCHECK_LE(byte_length_, allocation_length_);
   7616 }
   7617 
   7618 void WasmMemoryDeleter(void* buffer, size_t lenght, void* info) {
   7619   internal::wasm::WasmEngine* engine =
   7620       reinterpret_cast<internal::wasm::WasmEngine*>(info);
   7621   CHECK(engine->memory_tracker()->FreeMemoryIfIsWasmMemory(nullptr, buffer));
   7622 }
   7623 
   7624 void ArrayBufferDeleter(void* buffer, size_t length, void* info) {
   7625   v8::ArrayBuffer::Allocator* allocator =
   7626       reinterpret_cast<v8::ArrayBuffer::Allocator*>(info);
   7627   allocator->Free(buffer, length);
   7628 }
   7629 
   7630 v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() {
   7631   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
   7632   size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
   7633   Contents contents(
   7634       self->backing_store(), byte_length, self->allocation_base(),
   7635       self->allocation_length(),
   7636       self->is_wasm_memory() ? Allocator::AllocationMode::kReservation
   7637                              : Allocator::AllocationMode::kNormal,
   7638       self->is_wasm_memory() ? WasmMemoryDeleter : ArrayBufferDeleter,
   7639       self->is_wasm_memory()
   7640           ? static_cast<void*>(self->GetIsolate()->wasm_engine())
   7641           : static_cast<void*>(self->GetIsolate()->array_buffer_allocator()));
   7642   return contents;
   7643 }
   7644 
   7645 
   7646 void v8::ArrayBuffer::Neuter() {
   7647   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
   7648   i::Isolate* isolate = obj->GetIsolate();
   7649   Utils::ApiCheck(obj->is_external(),
   7650                   "v8::ArrayBuffer::Neuter",
   7651                   "Only externalized ArrayBuffers can be neutered");
   7652   Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter",
   7653                   "Only neuterable ArrayBuffers can be neutered");
   7654   LOG_API(isolate, ArrayBuffer, Neuter);
   7655   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7656   obj->Neuter();
   7657 }
   7658 
   7659 
   7660 size_t v8::ArrayBuffer::ByteLength() const {
   7661   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
   7662   return static_cast<size_t>(obj->byte_length()->Number());
   7663 }
   7664 
   7665 
   7666 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
   7667   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7668   LOG_API(i_isolate, ArrayBuffer, New);
   7669   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7670   i::Handle<i::JSArrayBuffer> obj =
   7671       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
   7672   // TODO(jbroman): It may be useful in the future to provide a MaybeLocal
   7673   // version that throws an exception or otherwise does not crash.
   7674   if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length)) {
   7675     i::FatalProcessOutOfMemory(i_isolate, "v8::ArrayBuffer::New");
   7676   }
   7677   return Utils::ToLocal(obj);
   7678 }
   7679 
   7680 
   7681 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
   7682                                         size_t byte_length,
   7683                                         ArrayBufferCreationMode mode) {
   7684   // Embedders must guarantee that the external backing store is valid.
   7685   CHECK(byte_length == 0 || data != nullptr);
   7686   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7687   LOG_API(i_isolate, ArrayBuffer, New);
   7688   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7689   i::Handle<i::JSArrayBuffer> obj =
   7690       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
   7691   i::JSArrayBuffer::Setup(obj, i_isolate,
   7692                           mode == ArrayBufferCreationMode::kExternalized, data,
   7693                           byte_length);
   7694   return Utils::ToLocal(obj);
   7695 }
   7696 
   7697 
   7698 Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
   7699   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
   7700   i::Handle<i::JSArrayBuffer> buffer;
   7701   if (obj->IsJSDataView()) {
   7702     i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj),
   7703                                        obj->GetIsolate());
   7704     DCHECK(data_view->buffer()->IsJSArrayBuffer());
   7705     buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()),
   7706                        data_view->GetIsolate());
   7707   } else {
   7708     DCHECK(obj->IsJSTypedArray());
   7709     buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
   7710   }
   7711   return Utils::ToLocal(buffer);
   7712 }
   7713 
   7714 
   7715 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
   7716   i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
   7717   size_t byte_offset = i::NumberToSize(self->byte_offset());
   7718   size_t bytes_to_copy =
   7719       i::Min(byte_length, i::NumberToSize(self->byte_length()));
   7720   if (bytes_to_copy) {
   7721     i::DisallowHeapAllocation no_gc;
   7722     i::Isolate* isolate = self->GetIsolate();
   7723     i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()),
   7724                                        isolate);
   7725     const char* source = reinterpret_cast<char*>(buffer->backing_store());
   7726     if (source == nullptr) {
   7727       DCHECK(self->IsJSTypedArray());
   7728       i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self),
   7729                                              isolate);
   7730       i::Handle<i::FixedTypedArrayBase> fixed_array(
   7731           i::FixedTypedArrayBase::cast(typed_array->elements()), isolate);
   7732       source = reinterpret_cast<char*>(fixed_array->DataPtr());
   7733     }
   7734     memcpy(dest, source + byte_offset, bytes_to_copy);
   7735   }
   7736   return bytes_to_copy;
   7737 }
   7738 
   7739 
   7740 bool v8::ArrayBufferView::HasBuffer() const {
   7741   i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
   7742   i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()),
   7743                                      self->GetIsolate());
   7744   return buffer->backing_store() != nullptr;
   7745 }
   7746 
   7747 
   7748 size_t v8::ArrayBufferView::ByteOffset() {
   7749   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
   7750   return static_cast<size_t>(obj->byte_offset()->Number());
   7751 }
   7752 
   7753 
   7754 size_t v8::ArrayBufferView::ByteLength() {
   7755   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
   7756   return static_cast<size_t>(obj->byte_length()->Number());
   7757 }
   7758 
   7759 
   7760 size_t v8::TypedArray::Length() {
   7761   i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
   7762   return obj->length_value();
   7763 }
   7764 
   7765 static_assert(v8::TypedArray::kMaxLength == i::Smi::kMaxValue,
   7766               "v8::TypedArray::kMaxLength must match i::Smi::kMaxValue");
   7767 
   7768 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype)                           \
   7769   Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer,     \
   7770                                       size_t byte_offset, size_t length) { \
   7771     i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate();  \
   7772     LOG_API(isolate, Type##Array, New);                                    \
   7773     ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);                              \
   7774     if (!Utils::ApiCheck(length <= kMaxLength,                             \
   7775                          "v8::" #Type                                      \
   7776                          "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
   7777                          "length exceeds max allowed value")) {            \
   7778       return Local<Type##Array>();                                         \
   7779     }                                                                      \
   7780     i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \
   7781     i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray(  \
   7782         i::kExternal##Type##Array, buffer, byte_offset, length);           \
   7783     return Utils::ToLocal##Type##Array(obj);                               \
   7784   }                                                                        \
   7785   Local<Type##Array> Type##Array::New(                                     \
   7786       Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,    \
   7787       size_t length) {                                                     \
   7788     CHECK(i::FLAG_harmony_sharedarraybuffer);                              \
   7789     i::Isolate* isolate =                                                  \
   7790         Utils::OpenHandle(*shared_array_buffer)->GetIsolate();             \
   7791     LOG_API(isolate, Type##Array, New);                                    \
   7792     ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);                              \
   7793     if (!Utils::ApiCheck(                                                  \
   7794             length <= kMaxLength,                                          \
   7795             "v8::" #Type                                                   \
   7796             "Array::New(Local<SharedArrayBuffer>, size_t, size_t)",        \
   7797             "length exceeds max allowed value")) {                         \
   7798       return Local<Type##Array>();                                         \
   7799     }                                                                      \
   7800     i::Handle<i::JSArrayBuffer> buffer =                                   \
   7801         Utils::OpenHandle(*shared_array_buffer);                           \
   7802     i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray(  \
   7803         i::kExternal##Type##Array, buffer, byte_offset, length);           \
   7804     return Utils::ToLocal##Type##Array(obj);                               \
   7805   }
   7806 
   7807 TYPED_ARRAYS(TYPED_ARRAY_NEW)
   7808 #undef TYPED_ARRAY_NEW
   7809 
   7810 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
   7811                               size_t byte_offset, size_t byte_length) {
   7812   i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
   7813   i::Isolate* isolate = buffer->GetIsolate();
   7814   LOG_API(isolate, DataView, New);
   7815   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7816   i::Handle<i::JSDataView> obj =
   7817       isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
   7818   return Utils::ToLocal(obj);
   7819 }
   7820 
   7821 
   7822 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
   7823                               size_t byte_offset, size_t byte_length) {
   7824   CHECK(i::FLAG_harmony_sharedarraybuffer);
   7825   i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
   7826   i::Isolate* isolate = buffer->GetIsolate();
   7827   LOG_API(isolate, DataView, New);
   7828   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   7829   i::Handle<i::JSDataView> obj =
   7830       isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
   7831   return Utils::ToLocal(obj);
   7832 }
   7833 
   7834 
   7835 bool v8::SharedArrayBuffer::IsExternal() const {
   7836   return Utils::OpenHandle(this)->is_external();
   7837 }
   7838 
   7839 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
   7840   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
   7841   i::Isolate* isolate = self->GetIsolate();
   7842   Utils::ApiCheck(!self->is_external(), "v8_SharedArrayBuffer_Externalize",
   7843                   "SharedArrayBuffer already externalized");
   7844   self->set_is_external(true);
   7845 
   7846   const v8::SharedArrayBuffer::Contents contents = GetContents();
   7847   isolate->heap()->UnregisterArrayBuffer(*self);
   7848 
   7849   // A regular copy is good enough. No move semantics needed.
   7850   return contents;
   7851 }
   7852 
   7853 v8::SharedArrayBuffer::Contents::Contents(
   7854     void* data, size_t byte_length, void* allocation_base,
   7855     size_t allocation_length, Allocator::AllocationMode allocation_mode,
   7856     DeleterCallback deleter, void* deleter_data)
   7857     : data_(data),
   7858       byte_length_(byte_length),
   7859       allocation_base_(allocation_base),
   7860       allocation_length_(allocation_length),
   7861       allocation_mode_(allocation_mode),
   7862       deleter_(deleter),
   7863       deleter_data_(deleter_data) {
   7864   DCHECK_LE(allocation_base_, data_);
   7865   DCHECK_LE(byte_length_, allocation_length_);
   7866 }
   7867 
   7868 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
   7869   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
   7870   size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
   7871   Contents contents(
   7872       self->backing_store(), byte_length, self->allocation_base(),
   7873       self->allocation_length(),
   7874       self->is_wasm_memory()
   7875           ? ArrayBuffer::Allocator::AllocationMode::kReservation
   7876           : ArrayBuffer::Allocator::AllocationMode::kNormal,
   7877       self->is_wasm_memory()
   7878           ? reinterpret_cast<Contents::DeleterCallback>(WasmMemoryDeleter)
   7879           : reinterpret_cast<Contents::DeleterCallback>(ArrayBufferDeleter),
   7880       self->is_wasm_memory()
   7881           ? static_cast<void*>(self->GetIsolate()->wasm_engine())
   7882           : static_cast<void*>(self->GetIsolate()->array_buffer_allocator()));
   7883   return contents;
   7884 }
   7885 
   7886 size_t v8::SharedArrayBuffer::ByteLength() const {
   7887   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
   7888   return static_cast<size_t>(obj->byte_length()->Number());
   7889 }
   7890 
   7891 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate,
   7892                                                     size_t byte_length) {
   7893   CHECK(i::FLAG_harmony_sharedarraybuffer);
   7894   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7895   LOG_API(i_isolate, SharedArrayBuffer, New);
   7896   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7897   i::Handle<i::JSArrayBuffer> obj =
   7898       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
   7899   // TODO(jbroman): It may be useful in the future to provide a MaybeLocal
   7900   // version that throws an exception or otherwise does not crash.
   7901   if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length, true,
   7902                                              i::SharedFlag::kShared)) {
   7903     i::FatalProcessOutOfMemory(i_isolate, "v8::SharedArrayBuffer::New");
   7904   }
   7905   return Utils::ToLocalShared(obj);
   7906 }
   7907 
   7908 
   7909 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
   7910     Isolate* isolate, void* data, size_t byte_length,
   7911     ArrayBufferCreationMode mode) {
   7912   CHECK(i::FLAG_harmony_sharedarraybuffer);
   7913   // Embedders must guarantee that the external backing store is valid.
   7914   CHECK(byte_length == 0 || data != nullptr);
   7915   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7916   LOG_API(i_isolate, SharedArrayBuffer, New);
   7917   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7918   i::Handle<i::JSArrayBuffer> obj =
   7919       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
   7920   bool is_wasm_memory =
   7921       i_isolate->wasm_engine()->memory_tracker()->IsWasmMemory(data);
   7922   i::JSArrayBuffer::Setup(obj, i_isolate,
   7923                           mode == ArrayBufferCreationMode::kExternalized, data,
   7924                           byte_length, i::SharedFlag::kShared, is_wasm_memory);
   7925   return Utils::ToLocalShared(obj);
   7926 }
   7927 
   7928 
   7929 Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
   7930   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7931   LOG_API(i_isolate, Symbol, New);
   7932   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7933   i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
   7934   if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
   7935   return Utils::ToLocal(result);
   7936 }
   7937 
   7938 
   7939 Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
   7940   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7941   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
   7942   return Utils::ToLocal(i_isolate->SymbolFor(
   7943       i::Heap::kPublicSymbolTableRootIndex, i_name, false));
   7944 }
   7945 
   7946 
   7947 Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
   7948   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7949   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
   7950   return Utils::ToLocal(
   7951       i_isolate->SymbolFor(i::Heap::kApiSymbolTableRootIndex, i_name, false));
   7952 }
   7953 
   7954 #define WELL_KNOWN_SYMBOLS(V)                 \
   7955   V(HasInstance, has_instance)                \
   7956   V(IsConcatSpreadable, is_concat_spreadable) \
   7957   V(Iterator, iterator)                       \
   7958   V(Match, match)                             \
   7959   V(Replace, replace)                         \
   7960   V(Search, search)                           \
   7961   V(Split, split)                             \
   7962   V(ToPrimitive, to_primitive)                \
   7963   V(ToStringTag, to_string_tag)               \
   7964   V(Unscopables, unscopables)
   7965 
   7966 #define SYMBOL_GETTER(Name, name)                                   \
   7967   Local<Symbol> v8::Symbol::Get##Name(Isolate* isolate) {           \
   7968     i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); \
   7969     return Utils::ToLocal(i_isolate->factory()->name##_symbol());   \
   7970   }
   7971 
   7972 WELL_KNOWN_SYMBOLS(SYMBOL_GETTER)
   7973 
   7974 #undef SYMBOL_GETTER
   7975 #undef WELL_KNOWN_SYMBOLS
   7976 
   7977 Local<Private> v8::Private::New(Isolate* isolate, Local<String> name) {
   7978   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7979   LOG_API(i_isolate, Private, New);
   7980   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
   7981   i::Handle<i::Symbol> symbol = i_isolate->factory()->NewPrivateSymbol();
   7982   if (!name.IsEmpty()) symbol->set_name(*Utils::OpenHandle(*name));
   7983   Local<Symbol> result = Utils::ToLocal(symbol);
   7984   return v8::Local<Private>(reinterpret_cast<Private*>(*result));
   7985 }
   7986 
   7987 
   7988 Local<Private> v8::Private::ForApi(Isolate* isolate, Local<String> name) {
   7989   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7990   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
   7991   Local<Symbol> result = Utils::ToLocal(i_isolate->SymbolFor(
   7992       i::Heap::kApiPrivateSymbolTableRootIndex, i_name, true));
   7993   return v8::Local<Private>(reinterpret_cast<Private*>(*result));
   7994 }
   7995 
   7996 
   7997 Local<Number> v8::Number::New(Isolate* isolate, double value) {
   7998   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
   7999   if (std::isnan(value)) {
   8000     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
   8001     value = std::numeric_limits<double>::quiet_NaN();
   8002   }
   8003   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
   8004   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
   8005   return Utils::NumberToLocal(result);
   8006 }
   8007 
   8008 
   8009 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
   8010   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
   8011   if (i::Smi::IsValid(value)) {
   8012     return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
   8013                                                       internal_isolate));
   8014   }
   8015   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
   8016   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
   8017   return Utils::IntegerToLocal(result);
   8018 }
   8019 
   8020 
   8021 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
   8022   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
   8023   bool fits_into_int32_t = (value & (1 << 31)) == 0;
   8024   if (fits_into_int32_t) {
   8025     return Integer::New(isolate, static_cast<int32_t>(value));
   8026   }
   8027   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
   8028   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
   8029   return Utils::IntegerToLocal(result);
   8030 }
   8031 
   8032 Local<BigInt> v8::BigInt::New(Isolate* isolate, int64_t value) {
   8033   CHECK(i::FLAG_harmony_bigint);
   8034   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
   8035   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
   8036   i::Handle<i::BigInt> result = i::BigInt::FromInt64(internal_isolate, value);
   8037   return Utils::ToLocal(result);
   8038 }
   8039 
   8040 Local<BigInt> v8::BigInt::NewFromUnsigned(Isolate* isolate, uint64_t value) {
   8041   CHECK(i::FLAG_harmony_bigint);
   8042   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
   8043   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
   8044   i::Handle<i::BigInt> result = i::BigInt::FromUint64(internal_isolate, value);
   8045   return Utils::ToLocal(result);
   8046 }
   8047 
   8048 MaybeLocal<BigInt> v8::BigInt::NewFromWords(Local<Context> context,
   8049                                             int sign_bit, int word_count,
   8050                                             const uint64_t* words) {
   8051   CHECK(i::FLAG_harmony_bigint);
   8052   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   8053   ENTER_V8_NO_SCRIPT(isolate, context, BigInt, NewFromWords,
   8054                      MaybeLocal<BigInt>(), InternalEscapableScope);
   8055   i::MaybeHandle<i::BigInt> result =
   8056       i::BigInt::FromWords64(isolate, sign_bit, word_count, words);
   8057   has_pending_exception = result.is_null();
   8058   RETURN_ON_FAILED_EXECUTION(BigInt);
   8059   RETURN_ESCAPED(Utils::ToLocal(result.ToHandleChecked()));
   8060 }
   8061 
   8062 uint64_t v8::BigInt::Uint64Value(bool* lossless) const {
   8063   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
   8064   return handle->AsUint64(lossless);
   8065 }
   8066 
   8067 int64_t v8::BigInt::Int64Value(bool* lossless) const {
   8068   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
   8069   return handle->AsInt64(lossless);
   8070 }
   8071 
   8072 int BigInt::WordCount() const {
   8073   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
   8074   return handle->Words64Count();
   8075 }
   8076 
   8077 void BigInt::ToWordsArray(int* sign_bit, int* word_count,
   8078                           uint64_t* words) const {
   8079   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
   8080   return handle->ToWordsArray64(sign_bit, word_count, words);
   8081 }
   8082 
   8083 void Isolate::ReportExternalAllocationLimitReached() {
   8084   i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
   8085   if (heap->gc_state() != i::Heap::NOT_IN_GC) return;
   8086   heap->ReportExternalMemoryPressure();
   8087 }
   8088 
   8089 void Isolate::CheckMemoryPressure() {
   8090   i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
   8091   if (heap->gc_state() != i::Heap::NOT_IN_GC) return;
   8092   heap->CheckMemoryPressure();
   8093 }
   8094 
   8095 HeapProfiler* Isolate::GetHeapProfiler() {
   8096   i::HeapProfiler* heap_profiler =
   8097       reinterpret_cast<i::Isolate*>(this)->heap_profiler();
   8098   return reinterpret_cast<HeapProfiler*>(heap_profiler);
   8099 }
   8100 
   8101 void Isolate::SetIdle(bool is_idle) {
   8102   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8103   isolate->SetIdle(is_idle);
   8104 }
   8105 
   8106 bool Isolate::InContext() {
   8107   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8108   return isolate->context() != nullptr;
   8109 }
   8110 
   8111 
   8112 v8::Local<v8::Context> Isolate::GetCurrentContext() {
   8113   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8114   i::Context* context = isolate->context();
   8115   if (context == nullptr) return Local<Context>();
   8116   i::Context* native_context = context->native_context();
   8117   if (native_context == nullptr) return Local<Context>();
   8118   return Utils::ToLocal(i::Handle<i::Context>(native_context, isolate));
   8119 }
   8120 
   8121 
   8122 v8::Local<v8::Context> Isolate::GetEnteredContext() {
   8123   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8124   i::Handle<i::Object> last =
   8125       isolate->handle_scope_implementer()->LastEnteredContext();
   8126   if (last.is_null()) return Local<Context>();
   8127   return Utils::ToLocal(i::Handle<i::Context>::cast(last));
   8128 }
   8129 
   8130 v8::Local<v8::Context> Isolate::GetEnteredOrMicrotaskContext() {
   8131   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8132   i::Handle<i::Object> last;
   8133   if (isolate->handle_scope_implementer()
   8134           ->MicrotaskContextIsLastEnteredContext()) {
   8135     last = isolate->handle_scope_implementer()->MicrotaskContext();
   8136   } else {
   8137     last = isolate->handle_scope_implementer()->LastEnteredContext();
   8138   }
   8139   if (last.is_null()) return Local<Context>();
   8140   return Utils::ToLocal(i::Handle<i::Context>::cast(last));
   8141 }
   8142 
   8143 v8::Local<v8::Context> Isolate::GetIncumbentContext() {
   8144   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8145   i::Handle<i::Context> context = isolate->GetIncumbentContext();
   8146   return Utils::ToLocal(context);
   8147 }
   8148 
   8149 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
   8150   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8151   ENTER_V8_DO_NOT_USE(isolate);
   8152   // If we're passed an empty handle, we throw an undefined exception
   8153   // to deal more gracefully with out of memory situations.
   8154   if (value.IsEmpty()) {
   8155     isolate->ScheduleThrow(i::ReadOnlyRoots(isolate).undefined_value());
   8156   } else {
   8157     isolate->ScheduleThrow(*Utils::OpenHandle(*value));
   8158   }
   8159   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   8160 }
   8161 
   8162 void Isolate::AddGCPrologueCallback(GCCallbackWithData callback, void* data,
   8163                                     GCType gc_type) {
   8164   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8165   isolate->heap()->AddGCPrologueCallback(callback, gc_type, data);
   8166 }
   8167 
   8168 void Isolate::RemoveGCPrologueCallback(GCCallbackWithData callback,
   8169                                        void* data) {
   8170   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8171   isolate->heap()->RemoveGCPrologueCallback(callback, data);
   8172 }
   8173 
   8174 void Isolate::AddGCEpilogueCallback(GCCallbackWithData callback, void* data,
   8175                                     GCType gc_type) {
   8176   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8177   isolate->heap()->AddGCEpilogueCallback(callback, gc_type, data);
   8178 }
   8179 
   8180 void Isolate::RemoveGCEpilogueCallback(GCCallbackWithData callback,
   8181                                        void* data) {
   8182   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8183   isolate->heap()->RemoveGCEpilogueCallback(callback, data);
   8184 }
   8185 
   8186 static void CallGCCallbackWithoutData(Isolate* isolate, GCType type,
   8187                                       GCCallbackFlags flags, void* data) {
   8188   reinterpret_cast<Isolate::GCCallback>(data)(isolate, type, flags);
   8189 }
   8190 
   8191 void Isolate::AddGCPrologueCallback(GCCallback callback, GCType gc_type) {
   8192   void* data = reinterpret_cast<void*>(callback);
   8193   AddGCPrologueCallback(CallGCCallbackWithoutData, data, gc_type);
   8194 }
   8195 
   8196 void Isolate::RemoveGCPrologueCallback(GCCallback callback) {
   8197   void* data = reinterpret_cast<void*>(callback);
   8198   RemoveGCPrologueCallback(CallGCCallbackWithoutData, data);
   8199 }
   8200 
   8201 void Isolate::AddGCEpilogueCallback(GCCallback callback, GCType gc_type) {
   8202   void* data = reinterpret_cast<void*>(callback);
   8203   AddGCEpilogueCallback(CallGCCallbackWithoutData, data, gc_type);
   8204 }
   8205 
   8206 void Isolate::RemoveGCEpilogueCallback(GCCallback callback) {
   8207   void* data = reinterpret_cast<void*>(callback);
   8208   RemoveGCEpilogueCallback(CallGCCallbackWithoutData, data);
   8209 }
   8210 
   8211 void Isolate::SetEmbedderHeapTracer(EmbedderHeapTracer* tracer) {
   8212   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8213   isolate->heap()->SetEmbedderHeapTracer(tracer);
   8214 }
   8215 
   8216 void Isolate::SetGetExternallyAllocatedMemoryInBytesCallback(
   8217     GetExternallyAllocatedMemoryInBytesCallback callback) {
   8218   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8219   isolate->heap()->SetGetExternallyAllocatedMemoryInBytesCallback(callback);
   8220 }
   8221 
   8222 void Isolate::TerminateExecution() {
   8223   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8224   isolate->stack_guard()->RequestTerminateExecution();
   8225 }
   8226 
   8227 
   8228 bool Isolate::IsExecutionTerminating() {
   8229   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8230   return IsExecutionTerminatingCheck(isolate);
   8231 }
   8232 
   8233 
   8234 void Isolate::CancelTerminateExecution() {
   8235   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8236   isolate->stack_guard()->ClearTerminateExecution();
   8237   isolate->CancelTerminateExecution();
   8238 }
   8239 
   8240 
   8241 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
   8242   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8243   isolate->RequestInterrupt(callback, data);
   8244 }
   8245 
   8246 
   8247 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
   8248   CHECK(i::FLAG_expose_gc);
   8249   if (type == kMinorGarbageCollection) {
   8250     reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
   8251         i::NEW_SPACE, i::GarbageCollectionReason::kTesting,
   8252         kGCCallbackFlagForced);
   8253   } else {
   8254     DCHECK_EQ(kFullGarbageCollection, type);
   8255     reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
   8256         i::Heap::kAbortIncrementalMarkingMask,
   8257         i::GarbageCollectionReason::kTesting, kGCCallbackFlagForced);
   8258   }
   8259 }
   8260 
   8261 
   8262 Isolate* Isolate::GetCurrent() {
   8263   i::Isolate* isolate = i::Isolate::Current();
   8264   return reinterpret_cast<Isolate*>(isolate);
   8265 }
   8266 
   8267 // static
   8268 Isolate* Isolate::Allocate() {
   8269   return reinterpret_cast<Isolate*>(new i::Isolate());
   8270 }
   8271 
   8272 // static
   8273 // This is separate so that tests can provide a different |isolate|.
   8274 void Isolate::Initialize(Isolate* isolate,
   8275                          const v8::Isolate::CreateParams& params) {
   8276   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   8277   CHECK_NOT_NULL(params.array_buffer_allocator);
   8278   i_isolate->set_array_buffer_allocator(params.array_buffer_allocator);
   8279   if (params.snapshot_blob != nullptr) {
   8280     i_isolate->set_snapshot_blob(params.snapshot_blob);
   8281   } else {
   8282     i_isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
   8283   }
   8284   if (params.entry_hook) {
   8285 #ifdef V8_USE_SNAPSHOT
   8286     // Setting a FunctionEntryHook is only supported in no-snapshot builds.
   8287     Utils::ApiCheck(
   8288         false, "v8::Isolate::New",
   8289         "Setting a FunctionEntryHook is only supported in no-snapshot builds.");
   8290 #endif
   8291     i_isolate->set_function_entry_hook(params.entry_hook);
   8292   }
   8293   auto code_event_handler = params.code_event_handler;
   8294 #ifdef ENABLE_GDB_JIT_INTERFACE
   8295   if (code_event_handler == nullptr && i::FLAG_gdbjit) {
   8296     code_event_handler = i::GDBJITInterface::EventHandler;
   8297   }
   8298 #endif  // ENABLE_GDB_JIT_INTERFACE
   8299   if (code_event_handler) {
   8300     i_isolate->InitializeLoggingAndCounters();
   8301     i_isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
   8302                                              code_event_handler);
   8303   }
   8304   if (params.counter_lookup_callback) {
   8305     isolate->SetCounterFunction(params.counter_lookup_callback);
   8306   }
   8307 
   8308   if (params.create_histogram_callback) {
   8309     isolate->SetCreateHistogramFunction(params.create_histogram_callback);
   8310   }
   8311 
   8312   if (params.add_histogram_sample_callback) {
   8313     isolate->SetAddHistogramSampleFunction(
   8314         params.add_histogram_sample_callback);
   8315   }
   8316 
   8317   i_isolate->set_api_external_references(params.external_references);
   8318   i_isolate->set_allow_atomics_wait(params.allow_atomics_wait);
   8319 
   8320   SetResourceConstraints(i_isolate, params.constraints);
   8321   // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
   8322   Isolate::Scope isolate_scope(isolate);
   8323   if (params.entry_hook || !i::Snapshot::Initialize(i_isolate)) {
   8324     // If snapshot data was provided and we failed to deserialize it must
   8325     // have been corrupted.
   8326     CHECK_NULL(i_isolate->snapshot_blob());
   8327     base::ElapsedTimer timer;
   8328     if (i::FLAG_profile_deserialization) timer.Start();
   8329     i_isolate->Init(nullptr);
   8330     if (i::FLAG_profile_deserialization) {
   8331       double ms = timer.Elapsed().InMillisecondsF();
   8332       i::PrintF("[Initializing isolate from scratch took %0.3f ms]\n", ms);
   8333     }
   8334   }
   8335   i_isolate->set_only_terminate_in_safe_scope(
   8336       params.only_terminate_in_safe_scope);
   8337 }
   8338 
   8339 Isolate* Isolate::New(const Isolate::CreateParams& params) {
   8340   Isolate* isolate = Allocate();
   8341   Initialize(isolate, params);
   8342   return isolate;
   8343 }
   8344 
   8345 void Isolate::Dispose() {
   8346   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8347   if (!Utils::ApiCheck(!isolate->IsInUse(),
   8348                        "v8::Isolate::Dispose()",
   8349                        "Disposing the isolate that is entered by a thread.")) {
   8350     return;
   8351   }
   8352   isolate->TearDown();
   8353 }
   8354 
   8355 void Isolate::DumpAndResetStats() {
   8356   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8357   isolate->DumpAndResetStats();
   8358 }
   8359 
   8360 void Isolate::DiscardThreadSpecificMetadata() {
   8361   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8362   isolate->DiscardPerThreadDataForThisThread();
   8363 }
   8364 
   8365 
   8366 void Isolate::Enter() {
   8367   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8368   isolate->Enter();
   8369 }
   8370 
   8371 
   8372 void Isolate::Exit() {
   8373   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8374   isolate->Exit();
   8375 }
   8376 
   8377 
   8378 void Isolate::SetAbortOnUncaughtExceptionCallback(
   8379     AbortOnUncaughtExceptionCallback callback) {
   8380   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8381   isolate->SetAbortOnUncaughtExceptionCallback(callback);
   8382 }
   8383 
   8384 void Isolate::SetHostImportModuleDynamicallyCallback(
   8385     HostImportModuleDynamicallyCallback callback) {
   8386   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8387   isolate->SetHostImportModuleDynamicallyCallback(callback);
   8388 }
   8389 
   8390 void Isolate::SetHostInitializeImportMetaObjectCallback(
   8391     HostInitializeImportMetaObjectCallback callback) {
   8392   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8393   isolate->SetHostInitializeImportMetaObjectCallback(callback);
   8394 }
   8395 
   8396 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
   8397     Isolate* isolate,
   8398     Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
   8399     : on_failure_(on_failure) {
   8400   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   8401   if (on_failure_ == CRASH_ON_FAILURE) {
   8402     internal_ = reinterpret_cast<void*>(
   8403         new i::DisallowJavascriptExecution(i_isolate));
   8404   } else {
   8405     DCHECK_EQ(THROW_ON_FAILURE, on_failure);
   8406     internal_ = reinterpret_cast<void*>(
   8407         new i::ThrowOnJavascriptExecution(i_isolate));
   8408   }
   8409 }
   8410 
   8411 
   8412 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
   8413   if (on_failure_ == CRASH_ON_FAILURE) {
   8414     delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
   8415   } else {
   8416     delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
   8417   }
   8418 }
   8419 
   8420 
   8421 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
   8422     Isolate* isolate) {
   8423   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   8424   internal_assert_ = reinterpret_cast<void*>(
   8425       new i::AllowJavascriptExecution(i_isolate));
   8426   internal_throws_ = reinterpret_cast<void*>(
   8427       new i::NoThrowOnJavascriptExecution(i_isolate));
   8428 }
   8429 
   8430 
   8431 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
   8432   delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
   8433   delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
   8434 }
   8435 
   8436 
   8437 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
   8438     Isolate* isolate)
   8439     : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
   8440   isolate_->handle_scope_implementer()->IncrementCallDepth();
   8441   isolate_->handle_scope_implementer()->IncrementMicrotasksSuppressions();
   8442 }
   8443 
   8444 
   8445 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
   8446   isolate_->handle_scope_implementer()->DecrementMicrotasksSuppressions();
   8447   isolate_->handle_scope_implementer()->DecrementCallDepth();
   8448 }
   8449 
   8450 Isolate::SafeForTerminationScope::SafeForTerminationScope(v8::Isolate* isolate)
   8451     : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
   8452       prev_value_(isolate_->next_v8_call_is_safe_for_termination()) {
   8453   isolate_->set_next_v8_call_is_safe_for_termination(true);
   8454 }
   8455 
   8456 Isolate::SafeForTerminationScope::~SafeForTerminationScope() {
   8457   isolate_->set_next_v8_call_is_safe_for_termination(prev_value_);
   8458 }
   8459 
   8460 i::Object** Isolate::GetDataFromSnapshotOnce(size_t index) {
   8461   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
   8462   i::FixedArray* list = i_isolate->heap()->serialized_objects();
   8463   return GetSerializedDataFromFixedArray(i_isolate, list, index);
   8464 }
   8465 
   8466 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
   8467   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8468   i::Heap* heap = isolate->heap();
   8469   heap_statistics->total_heap_size_ = heap->CommittedMemory();
   8470   heap_statistics->total_heap_size_executable_ =
   8471       heap->CommittedMemoryExecutable();
   8472   heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
   8473   heap_statistics->total_available_size_ = heap->Available();
   8474   heap_statistics->used_heap_size_ = heap->SizeOfObjects();
   8475   heap_statistics->heap_size_limit_ = heap->MaxReserved();
   8476   // TODO(7424): There is no public API for the {WasmEngine} yet. Once such an
   8477   // API becomes available we should report the malloced memory separately. For
   8478   // now we just add the values, thereby over-approximating the peak slightly.
   8479   heap_statistics->malloced_memory_ =
   8480       isolate->allocator()->GetCurrentMemoryUsage() +
   8481       isolate->wasm_engine()->allocator()->GetCurrentMemoryUsage();
   8482   heap_statistics->external_memory_ = isolate->heap()->external_memory();
   8483   heap_statistics->peak_malloced_memory_ =
   8484       isolate->allocator()->GetMaxMemoryUsage() +
   8485       isolate->wasm_engine()->allocator()->GetMaxMemoryUsage();
   8486   heap_statistics->number_of_native_contexts_ = heap->NumberOfNativeContexts();
   8487   heap_statistics->number_of_detached_contexts_ =
   8488       heap->NumberOfDetachedContexts();
   8489   heap_statistics->does_zap_garbage_ = heap->ShouldZapGarbage();
   8490 }
   8491 
   8492 
   8493 size_t Isolate::NumberOfHeapSpaces() {
   8494   return i::LAST_SPACE - i::FIRST_SPACE + 1;
   8495 }
   8496 
   8497 
   8498 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
   8499                                      size_t index) {
   8500   if (!space_statistics) return false;
   8501   if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
   8502     return false;
   8503 
   8504   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8505   i::Heap* heap = isolate->heap();
   8506   i::Space* space = heap->space(static_cast<int>(index));
   8507 
   8508   space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
   8509   space_statistics->space_size_ = space->CommittedMemory();
   8510   space_statistics->space_used_size_ = space->SizeOfObjects();
   8511   space_statistics->space_available_size_ = space->Available();
   8512   space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
   8513   return true;
   8514 }
   8515 
   8516 
   8517 size_t Isolate::NumberOfTrackedHeapObjectTypes() {
   8518   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8519   i::Heap* heap = isolate->heap();
   8520   return heap->NumberOfTrackedHeapObjectTypes();
   8521 }
   8522 
   8523 
   8524 bool Isolate::GetHeapObjectStatisticsAtLastGC(
   8525     HeapObjectStatistics* object_statistics, size_t type_index) {
   8526   if (!object_statistics) return false;
   8527   if (V8_LIKELY(!i::FLAG_gc_stats)) return false;
   8528 
   8529   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8530   i::Heap* heap = isolate->heap();
   8531   if (type_index >= heap->NumberOfTrackedHeapObjectTypes()) return false;
   8532 
   8533   const char* object_type;
   8534   const char* object_sub_type;
   8535   size_t object_count = heap->ObjectCountAtLastGC(type_index);
   8536   size_t object_size = heap->ObjectSizeAtLastGC(type_index);
   8537   if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
   8538     // There should be no objects counted when the type is unknown.
   8539     DCHECK_EQ(object_count, 0U);
   8540     DCHECK_EQ(object_size, 0U);
   8541     return false;
   8542   }
   8543 
   8544   object_statistics->object_type_ = object_type;
   8545   object_statistics->object_sub_type_ = object_sub_type;
   8546   object_statistics->object_count_ = object_count;
   8547   object_statistics->object_size_ = object_size;
   8548   return true;
   8549 }
   8550 
   8551 bool Isolate::GetHeapCodeAndMetadataStatistics(
   8552     HeapCodeStatistics* code_statistics) {
   8553   if (!code_statistics) return false;
   8554 
   8555   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8556   isolate->heap()->CollectCodeStatistics();
   8557 
   8558   code_statistics->code_and_metadata_size_ = isolate->code_and_metadata_size();
   8559   code_statistics->bytecode_and_metadata_size_ =
   8560       isolate->bytecode_and_metadata_size();
   8561   code_statistics->external_script_source_size_ =
   8562       isolate->external_script_source_size();
   8563   return true;
   8564 }
   8565 
   8566 void Isolate::GetStackSample(const RegisterState& state, void** frames,
   8567                              size_t frames_limit, SampleInfo* sample_info) {
   8568   RegisterState regs = state;
   8569   if (TickSample::GetStackSample(this, &regs, TickSample::kSkipCEntryFrame,
   8570                                  frames, frames_limit, sample_info)) {
   8571     return;
   8572   }
   8573   sample_info->frames_count = 0;
   8574   sample_info->vm_state = OTHER;
   8575   sample_info->external_callback_entry = nullptr;
   8576 }
   8577 
   8578 size_t Isolate::NumberOfPhantomHandleResetsSinceLastCall() {
   8579   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8580   size_t result = isolate->global_handles()->NumberOfPhantomHandleResets();
   8581   isolate->global_handles()->ResetNumberOfPhantomHandleResets();
   8582   return result;
   8583 }
   8584 
   8585 void Isolate::SetEventLogger(LogEventCallback that) {
   8586   // Do not overwrite the event logger if we want to log explicitly.
   8587   if (i::FLAG_log_internal_timer_events) return;
   8588   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8589   isolate->set_event_logger(that);
   8590 }
   8591 
   8592 
   8593 void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) {
   8594   if (callback == nullptr) return;
   8595   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8596   isolate->AddBeforeCallEnteredCallback(callback);
   8597 }
   8598 
   8599 
   8600 void Isolate::RemoveBeforeCallEnteredCallback(
   8601     BeforeCallEnteredCallback callback) {
   8602   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8603   isolate->RemoveBeforeCallEnteredCallback(callback);
   8604 }
   8605 
   8606 
   8607 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
   8608   if (callback == nullptr) return;
   8609   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8610   isolate->AddCallCompletedCallback(callback);
   8611 }
   8612 
   8613 
   8614 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
   8615   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8616   isolate->RemoveCallCompletedCallback(callback);
   8617 }
   8618 
   8619 void Isolate::AtomicsWaitWakeHandle::Wake() {
   8620   reinterpret_cast<i::AtomicsWaitWakeHandle*>(this)->Wake();
   8621 }
   8622 
   8623 void Isolate::SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data) {
   8624   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8625   isolate->SetAtomicsWaitCallback(callback, data);
   8626 }
   8627 
   8628 void Isolate::SetPromiseHook(PromiseHook hook) {
   8629   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8630   isolate->SetPromiseHook(hook);
   8631 }
   8632 
   8633 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
   8634   if (callback == nullptr) return;
   8635   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8636   isolate->SetPromiseRejectCallback(callback);
   8637 }
   8638 
   8639 
   8640 void Isolate::RunMicrotasks() {
   8641   DCHECK_NE(MicrotasksPolicy::kScoped, GetMicrotasksPolicy());
   8642   reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
   8643 }
   8644 
   8645 void Isolate::EnqueueMicrotask(Local<Function> function) {
   8646   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8647   i::Handle<i::CallableTask> microtask = isolate->factory()->NewCallableTask(
   8648       Utils::OpenHandle(*function), isolate->native_context());
   8649   isolate->EnqueueMicrotask(microtask);
   8650 }
   8651 
   8652 void Isolate::EnqueueMicrotask(MicrotaskCallback callback, void* data) {
   8653   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8654   i::HandleScope scope(isolate);
   8655   i::Handle<i::CallbackTask> microtask = isolate->factory()->NewCallbackTask(
   8656       isolate->factory()->NewForeign(reinterpret_cast<i::Address>(callback)),
   8657       isolate->factory()->NewForeign(reinterpret_cast<i::Address>(data)));
   8658   isolate->EnqueueMicrotask(microtask);
   8659 }
   8660 
   8661 
   8662 void Isolate::SetMicrotasksPolicy(MicrotasksPolicy policy) {
   8663   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8664   isolate->handle_scope_implementer()->set_microtasks_policy(policy);
   8665 }
   8666 
   8667 
   8668 MicrotasksPolicy Isolate::GetMicrotasksPolicy() const {
   8669   i::Isolate* isolate =
   8670       reinterpret_cast<i::Isolate*>(const_cast<Isolate*>(this));
   8671   return isolate->handle_scope_implementer()->microtasks_policy();
   8672 }
   8673 
   8674 
   8675 void Isolate::AddMicrotasksCompletedCallback(
   8676     MicrotasksCompletedCallback callback) {
   8677   DCHECK(callback);
   8678   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8679   isolate->AddMicrotasksCompletedCallback(callback);
   8680 }
   8681 
   8682 
   8683 void Isolate::RemoveMicrotasksCompletedCallback(
   8684     MicrotasksCompletedCallback callback) {
   8685   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8686   isolate->RemoveMicrotasksCompletedCallback(callback);
   8687 }
   8688 
   8689 
   8690 void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
   8691   reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
   8692 }
   8693 
   8694 
   8695 void Isolate::SetCounterFunction(CounterLookupCallback callback) {
   8696   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8697   isolate->counters()->ResetCounterFunction(callback);
   8698 }
   8699 
   8700 
   8701 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
   8702   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8703   isolate->counters()->ResetCreateHistogramFunction(callback);
   8704 }
   8705 
   8706 
   8707 void Isolate::SetAddHistogramSampleFunction(
   8708     AddHistogramSampleCallback callback) {
   8709   reinterpret_cast<i::Isolate*>(this)
   8710       ->counters()
   8711       ->SetAddHistogramSampleFunction(callback);
   8712 }
   8713 
   8714 
   8715 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
   8716   // Returning true tells the caller that it need not
   8717   // continue to call IdleNotification.
   8718   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8719   if (!i::FLAG_use_idle_notification) return true;
   8720   return isolate->heap()->IdleNotification(deadline_in_seconds);
   8721 }
   8722 
   8723 void Isolate::LowMemoryNotification() {
   8724   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8725   {
   8726     i::HistogramTimerScope idle_notification_scope(
   8727         isolate->counters()->gc_low_memory_notification());
   8728     TRACE_EVENT0("v8", "V8.GCLowMemoryNotification");
   8729     isolate->heap()->CollectAllAvailableGarbage(
   8730         i::GarbageCollectionReason::kLowMemoryNotification);
   8731   }
   8732   {
   8733     i::HeapIterator iterator(isolate->heap());
   8734     i::HeapObject* obj;
   8735     while ((obj = iterator.next()) != nullptr) {
   8736       if (obj->IsAbstractCode()) {
   8737         i::AbstractCode::cast(obj)->DropStackFrameCache();
   8738       }
   8739     }
   8740   }
   8741 }
   8742 
   8743 
   8744 int Isolate::ContextDisposedNotification(bool dependant_context) {
   8745   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8746   if (!dependant_context) {
   8747     // We left the current context, we can abort all WebAssembly compilations on
   8748     // that isolate.
   8749     isolate->wasm_engine()->DeleteCompileJobsOnIsolate(isolate);
   8750   }
   8751   // TODO(ahaas): move other non-heap activity out of the heap call.
   8752   return isolate->heap()->NotifyContextDisposed(dependant_context);
   8753 }
   8754 
   8755 
   8756 void Isolate::IsolateInForegroundNotification() {
   8757   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8758   return isolate->IsolateInForegroundNotification();
   8759 }
   8760 
   8761 
   8762 void Isolate::IsolateInBackgroundNotification() {
   8763   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8764   return isolate->IsolateInBackgroundNotification();
   8765 }
   8766 
   8767 void Isolate::MemoryPressureNotification(MemoryPressureLevel level) {
   8768   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8769   bool on_isolate_thread =
   8770       v8::Locker::IsActive()
   8771           ? isolate->thread_manager()->IsLockedByCurrentThread()
   8772           : i::ThreadId::Current().Equals(isolate->thread_id());
   8773   isolate->heap()->MemoryPressureNotification(level, on_isolate_thread);
   8774   isolate->allocator()->MemoryPressureNotification(level);
   8775   isolate->compiler_dispatcher()->MemoryPressureNotification(level,
   8776                                                              on_isolate_thread);
   8777 }
   8778 
   8779 void Isolate::EnableMemorySavingsMode() {
   8780   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8781   isolate->EnableMemorySavingsMode();
   8782 }
   8783 
   8784 void Isolate::DisableMemorySavingsMode() {
   8785   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8786   isolate->DisableMemorySavingsMode();
   8787 }
   8788 
   8789 void Isolate::SetRAILMode(RAILMode rail_mode) {
   8790   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8791   return isolate->SetRAILMode(rail_mode);
   8792 }
   8793 
   8794 void Isolate::IncreaseHeapLimitForDebugging() {
   8795   // No-op.
   8796 }
   8797 
   8798 void Isolate::RestoreOriginalHeapLimit() {
   8799   // No-op.
   8800 }
   8801 
   8802 bool Isolate::IsHeapLimitIncreasedForDebugging() { return false; }
   8803 
   8804 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
   8805                                      JitCodeEventHandler event_handler) {
   8806   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8807   // Ensure that logging is initialized for our isolate.
   8808   isolate->InitializeLoggingAndCounters();
   8809   isolate->logger()->SetCodeEventHandler(options, event_handler);
   8810 }
   8811 
   8812 
   8813 void Isolate::SetStackLimit(uintptr_t stack_limit) {
   8814   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8815   CHECK(stack_limit);
   8816   isolate->stack_guard()->SetStackLimit(stack_limit);
   8817 }
   8818 
   8819 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
   8820   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
   8821   if (isolate->heap()->memory_allocator()->code_range()->valid()) {
   8822     *start = reinterpret_cast<void*>(
   8823         isolate->heap()->memory_allocator()->code_range()->start());
   8824     *length_in_bytes =
   8825         isolate->heap()->memory_allocator()->code_range()->size();
   8826   } else {
   8827     *start = nullptr;
   8828     *length_in_bytes = 0;
   8829   }
   8830 }
   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);
   8903   i::DisallowHeapAllocation no_gc;
   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>();
   9093   i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
   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) return std::vector<int>();
   9217   i::Isolate* isolate = script->GetIsolate();
   9218   i::HandleScope scope(isolate);
   9219   i::Script::InitLineEnds(script);
   9220   CHECK(script->line_ends()->IsFixedArray());
   9221   i::Handle<i::FixedArray> line_ends(i::FixedArray::cast(script->line_ends()),
   9222                                      isolate);
   9223   std::vector<int> result(line_ends->length());
   9224   for (int i = 0; i < line_ends->length(); ++i) {
   9225     i::Smi* line_end = i::Smi::cast(line_ends->get(i));
   9226     result[i] = line_end->value();
   9227   }
   9228   return result;
   9229 }
   9230 
   9231 MaybeLocal<String> debug::Script::Name() const {
   9232   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   9233   i::HandleScope handle_scope(isolate);
   9234   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9235   i::Handle<i::Object> value(script->name(), isolate);
   9236   if (!value->IsString()) return MaybeLocal<String>();
   9237   return Utils::ToLocal(
   9238       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
   9239 }
   9240 
   9241 MaybeLocal<String> debug::Script::SourceURL() const {
   9242   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   9243   i::HandleScope handle_scope(isolate);
   9244   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9245   i::Handle<i::Object> value(script->source_url(), isolate);
   9246   if (!value->IsString()) return MaybeLocal<String>();
   9247   return Utils::ToLocal(
   9248       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
   9249 }
   9250 
   9251 MaybeLocal<String> debug::Script::SourceMappingURL() const {
   9252   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   9253   i::HandleScope handle_scope(isolate);
   9254   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9255   i::Handle<i::Object> value(script->source_mapping_url(), isolate);
   9256   if (!value->IsString()) return MaybeLocal<String>();
   9257   return Utils::ToLocal(
   9258       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
   9259 }
   9260 
   9261 Maybe<int> debug::Script::ContextId() const {
   9262   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   9263   i::HandleScope handle_scope(isolate);
   9264   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9265   i::Object* value = script->context_data();
   9266   if (value->IsSmi()) return Just(i::Smi::ToInt(value));
   9267   return Nothing<int>();
   9268 }
   9269 
   9270 MaybeLocal<String> debug::Script::Source() const {
   9271   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
   9272   i::HandleScope handle_scope(isolate);
   9273   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9274   i::Handle<i::Object> value(script->source(), isolate);
   9275   if (!value->IsString()) return MaybeLocal<String>();
   9276   return Utils::ToLocal(
   9277       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
   9278 }
   9279 
   9280 bool debug::Script::IsWasm() const {
   9281   return Utils::OpenHandle(this)->type() == i::Script::TYPE_WASM;
   9282 }
   9283 
   9284 bool debug::Script::IsModule() const {
   9285   return Utils::OpenHandle(this)->origin_options().IsModule();
   9286 }
   9287 
   9288 namespace {
   9289 int GetSmiValue(i::Handle<i::FixedArray> array, int index) {
   9290   return i::Smi::ToInt(array->get(index));
   9291 }
   9292 
   9293 bool CompareBreakLocation(const i::BreakLocation& loc1,
   9294                           const i::BreakLocation& loc2) {
   9295   return loc1.position() < loc2.position();
   9296 }
   9297 }  // namespace
   9298 
   9299 bool debug::Script::GetPossibleBreakpoints(
   9300     const debug::Location& start, const debug::Location& end,
   9301     bool restrict_to_function,
   9302     std::vector<debug::BreakLocation>* locations) const {
   9303   CHECK(!start.IsEmpty());
   9304   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9305   if (script->type() == i::Script::TYPE_WASM) {
   9306     i::WasmModuleObject* module_object =
   9307         i::WasmModuleObject::cast(script->wasm_module_object());
   9308     return module_object->GetPossibleBreakpoints(start, end, locations);
   9309   }
   9310 
   9311   i::Script::InitLineEnds(script);
   9312   CHECK(script->line_ends()->IsFixedArray());
   9313   i::Isolate* isolate = script->GetIsolate();
   9314   i::Handle<i::FixedArray> line_ends =
   9315       i::Handle<i::FixedArray>::cast(i::handle(script->line_ends(), isolate));
   9316   CHECK(line_ends->length());
   9317 
   9318   int start_offset = GetSourceOffset(start);
   9319   int end_offset = end.IsEmpty()
   9320                        ? GetSmiValue(line_ends, line_ends->length() - 1) + 1
   9321                        : GetSourceOffset(end);
   9322   if (start_offset >= end_offset) return true;
   9323 
   9324   std::vector<i::BreakLocation> v8_locations;
   9325   if (!isolate->debug()->GetPossibleBreakpoints(
   9326           script, start_offset, end_offset, restrict_to_function,
   9327           &v8_locations)) {
   9328     return false;
   9329   }
   9330 
   9331   std::sort(v8_locations.begin(), v8_locations.end(), CompareBreakLocation);
   9332   int current_line_end_index = 0;
   9333   for (const auto& v8_location : v8_locations) {
   9334     int offset = v8_location.position();
   9335     while (offset > GetSmiValue(line_ends, current_line_end_index)) {
   9336       ++current_line_end_index;
   9337       CHECK(current_line_end_index < line_ends->length());
   9338     }
   9339     int line_offset = 0;
   9340 
   9341     if (current_line_end_index > 0) {
   9342       line_offset = GetSmiValue(line_ends, current_line_end_index - 1) + 1;
   9343     }
   9344     locations->emplace_back(
   9345         current_line_end_index + script->line_offset(),
   9346         offset - line_offset +
   9347             (current_line_end_index == 0 ? script->column_offset() : 0),
   9348         v8_location.type());
   9349   }
   9350   return true;
   9351 }
   9352 
   9353 int debug::Script::GetSourceOffset(const debug::Location& location) const {
   9354   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9355   if (script->type() == i::Script::TYPE_WASM) {
   9356     return i::WasmModuleObject::cast(script->wasm_module_object())
   9357                ->GetFunctionOffset(location.GetLineNumber()) +
   9358            location.GetColumnNumber();
   9359   }
   9360 
   9361   int line = std::max(location.GetLineNumber() - script->line_offset(), 0);
   9362   int column = location.GetColumnNumber();
   9363   if (line == 0) {
   9364     column = std::max(0, column - script->column_offset());
   9365   }
   9366 
   9367   i::Script::InitLineEnds(script);
   9368   CHECK(script->line_ends()->IsFixedArray());
   9369   i::Handle<i::FixedArray> line_ends = i::Handle<i::FixedArray>::cast(
   9370       i::handle(script->line_ends(), script->GetIsolate()));
   9371   CHECK(line_ends->length());
   9372   if (line >= line_ends->length())
   9373     return GetSmiValue(line_ends, line_ends->length() - 1);
   9374   int line_offset = GetSmiValue(line_ends, line);
   9375   if (line == 0) return std::min(column, line_offset);
   9376   int prev_line_offset = GetSmiValue(line_ends, line - 1);
   9377   return std::min(prev_line_offset + column + 1, line_offset);
   9378 }
   9379 
   9380 v8::debug::Location debug::Script::GetSourceLocation(int offset) const {
   9381   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9382   i::Script::PositionInfo info;
   9383   i::Script::GetPositionInfo(script, offset, &info, i::Script::WITH_OFFSET);
   9384   return debug::Location(info.line, info.column);
   9385 }
   9386 
   9387 bool debug::Script::SetScriptSource(v8::Local<v8::String> newSource,
   9388                                     bool preview,
   9389                                     debug::LiveEditResult* result) const {
   9390   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9391   i::Isolate* isolate = script->GetIsolate();
   9392   return isolate->debug()->SetScriptSource(
   9393       script, Utils::OpenHandle(*newSource), preview, result);
   9394 }
   9395 
   9396 bool debug::Script::SetBreakpoint(v8::Local<v8::String> condition,
   9397                                   debug::Location* location,
   9398                                   debug::BreakpointId* id) const {
   9399   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9400   i::Isolate* isolate = script->GetIsolate();
   9401   int offset = GetSourceOffset(*location);
   9402   if (!isolate->debug()->SetBreakPointForScript(
   9403           script, Utils::OpenHandle(*condition), &offset, id)) {
   9404     return false;
   9405   }
   9406   *location = GetSourceLocation(offset);
   9407   return true;
   9408 }
   9409 
   9410 void debug::RemoveBreakpoint(Isolate* v8_isolate, BreakpointId id) {
   9411   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9412   i::HandleScope handle_scope(isolate);
   9413   isolate->debug()->RemoveBreakpoint(id);
   9414 }
   9415 
   9416 v8::Platform* debug::GetCurrentPlatform() {
   9417   return i::V8::GetCurrentPlatform();
   9418 }
   9419 
   9420 debug::WasmScript* debug::WasmScript::Cast(debug::Script* script) {
   9421   CHECK(script->IsWasm());
   9422   return static_cast<WasmScript*>(script);
   9423 }
   9424 
   9425 int debug::WasmScript::NumFunctions() const {
   9426   i::DisallowHeapAllocation no_gc;
   9427   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9428   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
   9429   i::WasmModuleObject* module_object =
   9430       i::WasmModuleObject::cast(script->wasm_module_object());
   9431   const i::wasm::WasmModule* module = module_object->module();
   9432   DCHECK_GE(i::kMaxInt, module->functions.size());
   9433   return static_cast<int>(module->functions.size());
   9434 }
   9435 
   9436 int debug::WasmScript::NumImportedFunctions() const {
   9437   i::DisallowHeapAllocation no_gc;
   9438   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9439   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
   9440   i::WasmModuleObject* module_object =
   9441       i::WasmModuleObject::cast(script->wasm_module_object());
   9442   const i::wasm::WasmModule* module = module_object->module();
   9443   DCHECK_GE(i::kMaxInt, module->num_imported_functions);
   9444   return static_cast<int>(module->num_imported_functions);
   9445 }
   9446 
   9447 std::pair<int, int> debug::WasmScript::GetFunctionRange(
   9448     int function_index) const {
   9449   i::DisallowHeapAllocation no_gc;
   9450   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9451   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
   9452   i::WasmModuleObject* module_object =
   9453       i::WasmModuleObject::cast(script->wasm_module_object());
   9454   const i::wasm::WasmModule* module = module_object->module();
   9455   DCHECK_LE(0, function_index);
   9456   DCHECK_GT(module->functions.size(), function_index);
   9457   const i::wasm::WasmFunction& func = module->functions[function_index];
   9458   DCHECK_GE(i::kMaxInt, func.code.offset());
   9459   DCHECK_GE(i::kMaxInt, func.code.end_offset());
   9460   return std::make_pair(static_cast<int>(func.code.offset()),
   9461                         static_cast<int>(func.code.end_offset()));
   9462 }
   9463 
   9464 uint32_t debug::WasmScript::GetFunctionHash(int function_index) {
   9465   i::DisallowHeapAllocation no_gc;
   9466   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9467   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
   9468   i::WasmModuleObject* module_object =
   9469       i::WasmModuleObject::cast(script->wasm_module_object());
   9470   const i::wasm::WasmModule* module = module_object->module();
   9471   DCHECK_LE(0, function_index);
   9472   DCHECK_GT(module->functions.size(), function_index);
   9473   const i::wasm::WasmFunction& func = module->functions[function_index];
   9474   i::wasm::ModuleWireBytes wire_bytes(
   9475       module_object->native_module()->wire_bytes());
   9476   i::Vector<const i::byte> function_bytes = wire_bytes.GetFunctionBytes(&func);
   9477   // TODO(herhut): Maybe also take module, name and signature into account.
   9478   return i::StringHasher::HashSequentialString(function_bytes.start(),
   9479                                                function_bytes.length(), 0);
   9480 }
   9481 
   9482 debug::WasmDisassembly debug::WasmScript::DisassembleFunction(
   9483     int function_index) const {
   9484   i::DisallowHeapAllocation no_gc;
   9485   i::Handle<i::Script> script = Utils::OpenHandle(this);
   9486   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
   9487   i::WasmModuleObject* module_object =
   9488       i::WasmModuleObject::cast(script->wasm_module_object());
   9489   return module_object->DisassembleFunction(function_index);
   9490 }
   9491 
   9492 debug::Location::Location(int line_number, int column_number)
   9493     : line_number_(line_number),
   9494       column_number_(column_number),
   9495       is_empty_(false) {}
   9496 
   9497 debug::Location::Location()
   9498     : line_number_(v8::Function::kLineOffsetNotFound),
   9499       column_number_(v8::Function::kLineOffsetNotFound),
   9500       is_empty_(true) {}
   9501 
   9502 int debug::Location::GetLineNumber() const {
   9503   DCHECK(!IsEmpty());
   9504   return line_number_;
   9505 }
   9506 
   9507 int debug::Location::GetColumnNumber() const {
   9508   DCHECK(!IsEmpty());
   9509   return column_number_;
   9510 }
   9511 
   9512 bool debug::Location::IsEmpty() const { return is_empty_; }
   9513 
   9514 void debug::GetLoadedScripts(v8::Isolate* v8_isolate,
   9515                              PersistentValueVector<debug::Script>& scripts) {
   9516   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9517   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   9518   {
   9519     i::DisallowHeapAllocation no_gc;
   9520     i::Script::Iterator iterator(isolate);
   9521     i::Script* script;
   9522     while ((script = iterator.Next()) != nullptr) {
   9523       if (!script->IsUserJavaScript()) continue;
   9524       if (script->HasValidSource()) {
   9525         i::HandleScope handle_scope(isolate);
   9526         i::Handle<i::Script> script_handle(script, isolate);
   9527         scripts.Append(ToApiHandle<Script>(script_handle));
   9528       }
   9529     }
   9530   }
   9531 }
   9532 
   9533 MaybeLocal<UnboundScript> debug::CompileInspectorScript(Isolate* v8_isolate,
   9534                                                         Local<String> source) {
   9535   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9536   PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, UnboundScript);
   9537   i::Handle<i::String> str = Utils::OpenHandle(*source);
   9538   i::Handle<i::SharedFunctionInfo> result;
   9539   {
   9540     ScriptOriginOptions origin_options;
   9541     i::ScriptData* script_data = nullptr;
   9542     i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
   9543         i::Compiler::GetSharedFunctionInfoForScript(
   9544             isolate, str, i::Compiler::ScriptDetails(), origin_options, nullptr,
   9545             script_data, ScriptCompiler::kNoCompileOptions,
   9546             ScriptCompiler::kNoCacheBecauseInspector,
   9547             i::FLAG_expose_inspector_scripts ? i::NOT_NATIVES_CODE
   9548                                              : i::INSPECTOR_CODE);
   9549     has_pending_exception = !maybe_function_info.ToHandle(&result);
   9550     RETURN_ON_FAILED_EXECUTION(UnboundScript);
   9551   }
   9552   RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
   9553 }
   9554 
   9555 void debug::SetDebugDelegate(Isolate* v8_isolate,
   9556                              debug::DebugDelegate* delegate) {
   9557   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9558   isolate->debug()->SetDebugDelegate(delegate);
   9559 }
   9560 
   9561 void debug::SetAsyncEventDelegate(Isolate* v8_isolate,
   9562                                   debug::AsyncEventDelegate* delegate) {
   9563   reinterpret_cast<i::Isolate*>(v8_isolate)->set_async_event_delegate(delegate);
   9564 }
   9565 
   9566 void debug::ResetBlackboxedStateCache(Isolate* v8_isolate,
   9567                                       v8::Local<debug::Script> script) {
   9568   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9569   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   9570   i::DisallowHeapAllocation no_gc;
   9571   i::SharedFunctionInfo::ScriptIterator iter(isolate,
   9572                                              *Utils::OpenHandle(*script));
   9573   while (i::SharedFunctionInfo* info = iter.Next()) {
   9574     if (info->HasDebugInfo()) {
   9575       info->GetDebugInfo()->set_computed_debug_is_blackboxed(false);
   9576     }
   9577   }
   9578 }
   9579 
   9580 int debug::EstimatedValueSize(Isolate* v8_isolate, v8::Local<v8::Value> value) {
   9581   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9582   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   9583   i::Handle<i::Object> object = Utils::OpenHandle(*value);
   9584   if (object->IsSmi()) return i::kPointerSize;
   9585   CHECK(object->IsHeapObject());
   9586   return i::Handle<i::HeapObject>::cast(object)->Size();
   9587 }
   9588 
   9589 v8::MaybeLocal<v8::Array> v8::Object::PreviewEntries(bool* is_key_value) {
   9590   if (IsMap()) {
   9591     *is_key_value = true;
   9592     return Map::Cast(this)->AsArray();
   9593   }
   9594   if (IsSet()) {
   9595     *is_key_value = false;
   9596     return Set::Cast(this)->AsArray();
   9597   }
   9598 
   9599   i::Handle<i::JSReceiver> object = Utils::OpenHandle(this);
   9600   i::Isolate* isolate = object->GetIsolate();
   9601   Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
   9602   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   9603   if (object->IsJSWeakCollection()) {
   9604     *is_key_value = object->IsJSWeakMap();
   9605     return Utils::ToLocal(i::JSWeakCollection::GetEntries(
   9606         i::Handle<i::JSWeakCollection>::cast(object), 0));
   9607   }
   9608   if (object->IsJSMapIterator()) {
   9609     i::Handle<i::JSMapIterator> iterator =
   9610         i::Handle<i::JSMapIterator>::cast(object);
   9611     MapAsArrayKind const kind =
   9612         static_cast<MapAsArrayKind>(iterator->map()->instance_type());
   9613     *is_key_value = kind == MapAsArrayKind::kEntries;
   9614     if (!iterator->HasMore()) return v8::Array::New(v8_isolate);
   9615     return Utils::ToLocal(MapAsArray(isolate, iterator->table(),
   9616                                      i::Smi::ToInt(iterator->index()), kind));
   9617   }
   9618   if (object->IsJSSetIterator()) {
   9619     i::Handle<i::JSSetIterator> it = i::Handle<i::JSSetIterator>::cast(object);
   9620     *is_key_value = false;
   9621     if (!it->HasMore()) return v8::Array::New(v8_isolate);
   9622     return Utils::ToLocal(
   9623         SetAsArray(isolate, it->table(), i::Smi::ToInt(it->index())));
   9624   }
   9625   return v8::MaybeLocal<v8::Array>();
   9626 }
   9627 
   9628 Local<Function> debug::GetBuiltin(Isolate* v8_isolate, Builtin builtin) {
   9629   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9630   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   9631   i::HandleScope handle_scope(isolate);
   9632   i::Builtins::Name builtin_id;
   9633   switch (builtin) {
   9634     case kObjectKeys:
   9635       builtin_id = i::Builtins::kObjectKeys;
   9636       break;
   9637     case kObjectGetPrototypeOf:
   9638       builtin_id = i::Builtins::kObjectGetPrototypeOf;
   9639       break;
   9640     case kObjectGetOwnPropertyDescriptor:
   9641       builtin_id = i::Builtins::kObjectGetOwnPropertyDescriptor;
   9642       break;
   9643     case kObjectGetOwnPropertyNames:
   9644       builtin_id = i::Builtins::kObjectGetOwnPropertyNames;
   9645       break;
   9646     case kObjectGetOwnPropertySymbols:
   9647       builtin_id = i::Builtins::kObjectGetOwnPropertySymbols;
   9648       break;
   9649     default:
   9650       UNREACHABLE();
   9651   }
   9652 
   9653   i::Handle<i::String> name = isolate->factory()->empty_string();
   9654   i::NewFunctionArgs args = i::NewFunctionArgs::ForBuiltinWithoutPrototype(
   9655       name, builtin_id, i::LanguageMode::kSloppy);
   9656   i::Handle<i::JSFunction> fun = isolate->factory()->NewFunction(args);
   9657 
   9658   fun->shared()->DontAdaptArguments();
   9659   return Utils::ToLocal(handle_scope.CloseAndEscape(fun));
   9660 }
   9661 
   9662 void debug::SetConsoleDelegate(Isolate* v8_isolate, ConsoleDelegate* delegate) {
   9663   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
   9664   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
   9665   isolate->set_console_delegate(delegate);
   9666 }
   9667 
   9668 debug::ConsoleCallArguments::ConsoleCallArguments(
   9669     const v8::FunctionCallbackInfo<v8::Value>& info)
   9670     : v8::FunctionCallbackInfo<v8::Value>(nullptr, info.values_, info.length_) {
   9671 }
   9672 
   9673 debug::ConsoleCallArguments::ConsoleCallArguments(
   9674     internal::BuiltinArguments& args)
   9675     : v8::FunctionCallbackInfo<v8::Value>(nullptr, &args[0] - 1,
   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,
   9754     v8::PersistentValueVector<v8::String>* names) {
   9755   i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
   9756   i::Isolate* isolate = context->GetIsolate();
   9757   i::Handle<i::ScriptContextTable> table(
   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 int debug::GetNativeAccessorDescriptor(v8::Local<v8::Context> context,
   9781                                        v8::Local<v8::Object> v8_object,
   9782                                        v8::Local<v8::Name> v8_name) {
   9783   i::Handle<i::JSReceiver> object = Utils::OpenHandle(*v8_object);
   9784   i::Handle<i::Name> name = Utils::OpenHandle(*v8_name);
   9785   uint32_t index;
   9786   if (name->AsArrayIndex(&index)) {
   9787     return static_cast<int>(debug::NativeAccessorType::None);
   9788   }
   9789   i::LookupIterator it = i::LookupIterator(object->GetIsolate(), object, name,
   9790                                            i::LookupIterator::OWN);
   9791   if (!it.IsFound()) return static_cast<int>(debug::NativeAccessorType::None);
   9792   if (it.state() != i::LookupIterator::ACCESSOR) {
   9793     return static_cast<int>(debug::NativeAccessorType::None);
   9794   }
   9795   i::Handle<i::Object> structure = it.GetAccessors();
   9796   if (!structure->IsAccessorInfo()) {
   9797     return static_cast<int>(debug::NativeAccessorType::None);
   9798   }
   9799   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
   9800   int result = 0;
   9801 #define IS_BUILTIN_ACESSOR(name, _)                         \
   9802   if (*structure == *isolate->factory()->name##_accessor()) \
   9803     result |= static_cast<int>(debug::NativeAccessorType::IsBuiltin);
   9804   ACCESSOR_INFO_LIST(IS_BUILTIN_ACESSOR)
   9805 #undef IS_BUILTIN_ACESSOR
   9806   i::Handle<i::AccessorInfo> accessor_info =
   9807       i::Handle<i::AccessorInfo>::cast(structure);
   9808   if (accessor_info->getter())
   9809     result |= static_cast<int>(debug::NativeAccessorType::HasGetter);
   9810   if (accessor_info->setter())
   9811     result |= static_cast<int>(debug::NativeAccessorType::HasSetter);
   9812   return result;
   9813 }
   9814 
   9815 int64_t debug::GetNextRandomInt64(v8::Isolate* v8_isolate) {
   9816   return reinterpret_cast<i::Isolate*>(v8_isolate)
   9817       ->random_number_generator()
   9818       ->NextInt64();
   9819 }
   9820 
   9821 int debug::GetDebuggingId(v8::Local<v8::Function> function) {
   9822   i::Handle<i::JSReceiver> callable = v8::Utils::OpenHandle(*function);
   9823   if (!callable->IsJSFunction()) return i::DebugInfo::kNoDebuggingId;
   9824   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(callable);
   9825   int id = func->GetIsolate()->debug()->GetFunctionDebuggingId(func);
   9826   DCHECK_NE(i::DebugInfo::kNoDebuggingId, id);
   9827   return id;
   9828 }
   9829 
   9830 bool debug::SetFunctionBreakpoint(v8::Local<v8::Function> function,
   9831                                   v8::Local<v8::String> condition,
   9832                                   BreakpointId* id) {
   9833   i::Handle<i::JSReceiver> callable = Utils::OpenHandle(*function);
   9834   if (!callable->IsJSFunction()) return false;
   9835   i::Handle<i::JSFunction> jsfunction =
   9836       i::Handle<i::JSFunction>::cast(callable);
   9837   i::Isolate* isolate = jsfunction->GetIsolate();
   9838   i::Handle<i::String> condition_string =
   9839       condition.IsEmpty() ? isolate->factory()->empty_string()
   9840                           : Utils::OpenHandle(*condition);
   9841   return isolate->debug()->SetBreakpointForFunction(jsfunction,
   9842                                                     condition_string, id);
   9843 }
   9844 
   9845 debug::PostponeInterruptsScope::PostponeInterruptsScope(v8::Isolate* isolate)
   9846     : scope_(
   9847           new i::PostponeInterruptsScope(reinterpret_cast<i::Isolate*>(isolate),
   9848                                          i::StackGuard::API_INTERRUPT)) {}
   9849 
   9850 debug::PostponeInterruptsScope::~PostponeInterruptsScope() {}
   9851 
   9852 Local<String> CpuProfileNode::GetFunctionName() const {
   9853   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   9854   i::Isolate* isolate = node->isolate();
   9855   const i::CodeEntry* entry = node->entry();
   9856   i::Handle<i::String> name =
   9857       isolate->factory()->InternalizeUtf8String(entry->name());
   9858   return ToApiHandle<String>(name);
   9859 }
   9860 
   9861 int debug::Coverage::BlockData::StartOffset() const { return block_->start; }
   9862 int debug::Coverage::BlockData::EndOffset() const { return block_->end; }
   9863 uint32_t debug::Coverage::BlockData::Count() const { return block_->count; }
   9864 
   9865 int debug::Coverage::FunctionData::StartOffset() const {
   9866   return function_->start;
   9867 }
   9868 int debug::Coverage::FunctionData::EndOffset() const { return function_->end; }
   9869 uint32_t debug::Coverage::FunctionData::Count() const {
   9870   return function_->count;
   9871 }
   9872 
   9873 MaybeLocal<String> debug::Coverage::FunctionData::Name() const {
   9874   return ToApiHandle<String>(function_->name);
   9875 }
   9876 
   9877 size_t debug::Coverage::FunctionData::BlockCount() const {
   9878   return function_->blocks.size();
   9879 }
   9880 
   9881 bool debug::Coverage::FunctionData::HasBlockCoverage() const {
   9882   return function_->has_block_coverage;
   9883 }
   9884 
   9885 debug::Coverage::BlockData debug::Coverage::FunctionData::GetBlockData(
   9886     size_t i) const {
   9887   return BlockData(&function_->blocks.at(i), coverage_);
   9888 }
   9889 
   9890 Local<debug::Script> debug::Coverage::ScriptData::GetScript() const {
   9891   return ToApiHandle<debug::Script>(script_->script);
   9892 }
   9893 
   9894 size_t debug::Coverage::ScriptData::FunctionCount() const {
   9895   return script_->functions.size();
   9896 }
   9897 
   9898 debug::Coverage::FunctionData debug::Coverage::ScriptData::GetFunctionData(
   9899     size_t i) const {
   9900   return FunctionData(&script_->functions.at(i), coverage_);
   9901 }
   9902 
   9903 debug::Coverage::ScriptData::ScriptData(size_t index,
   9904                                         std::shared_ptr<i::Coverage> coverage)
   9905     : script_(&coverage->at(index)), coverage_(std::move(coverage)) {}
   9906 
   9907 size_t debug::Coverage::ScriptCount() const { return coverage_->size(); }
   9908 
   9909 debug::Coverage::ScriptData debug::Coverage::GetScriptData(size_t i) const {
   9910   return ScriptData(i, coverage_);
   9911 }
   9912 
   9913 debug::Coverage debug::Coverage::CollectPrecise(Isolate* isolate) {
   9914   return Coverage(
   9915       i::Coverage::CollectPrecise(reinterpret_cast<i::Isolate*>(isolate)));
   9916 }
   9917 
   9918 debug::Coverage debug::Coverage::CollectBestEffort(Isolate* isolate) {
   9919   return Coverage(
   9920       i::Coverage::CollectBestEffort(reinterpret_cast<i::Isolate*>(isolate)));
   9921 }
   9922 
   9923 void debug::Coverage::SelectMode(Isolate* isolate, debug::Coverage::Mode mode) {
   9924   i::Coverage::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
   9925 }
   9926 
   9927 int debug::TypeProfile::Entry::SourcePosition() const {
   9928   return entry_->position;
   9929 }
   9930 
   9931 std::vector<MaybeLocal<String>> debug::TypeProfile::Entry::Types() const {
   9932   std::vector<MaybeLocal<String>> result;
   9933   for (const internal::Handle<internal::String>& type : entry_->types) {
   9934     result.emplace_back(ToApiHandle<String>(type));
   9935   }
   9936   return result;
   9937 }
   9938 
   9939 debug::TypeProfile::ScriptData::ScriptData(
   9940     size_t index, std::shared_ptr<i::TypeProfile> type_profile)
   9941     : script_(&type_profile->at(index)),
   9942       type_profile_(std::move(type_profile)) {}
   9943 
   9944 Local<debug::Script> debug::TypeProfile::ScriptData::GetScript() const {
   9945   return ToApiHandle<debug::Script>(script_->script);
   9946 }
   9947 
   9948 std::vector<debug::TypeProfile::Entry> debug::TypeProfile::ScriptData::Entries()
   9949     const {
   9950   std::vector<debug::TypeProfile::Entry> result;
   9951   for (const internal::TypeProfileEntry& entry : script_->entries) {
   9952     result.push_back(debug::TypeProfile::Entry(&entry, type_profile_));
   9953   }
   9954   return result;
   9955 }
   9956 
   9957 debug::TypeProfile debug::TypeProfile::Collect(Isolate* isolate) {
   9958   return TypeProfile(
   9959       i::TypeProfile::Collect(reinterpret_cast<i::Isolate*>(isolate)));
   9960 }
   9961 
   9962 void debug::TypeProfile::SelectMode(Isolate* isolate,
   9963                                     debug::TypeProfile::Mode mode) {
   9964   i::TypeProfile::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
   9965 }
   9966 
   9967 size_t debug::TypeProfile::ScriptCount() const { return type_profile_->size(); }
   9968 
   9969 debug::TypeProfile::ScriptData debug::TypeProfile::GetScriptData(
   9970     size_t i) const {
   9971   return ScriptData(i, type_profile_);
   9972 }
   9973 
   9974 const char* CpuProfileNode::GetFunctionNameStr() const {
   9975   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   9976   return node->entry()->name();
   9977 }
   9978 
   9979 int CpuProfileNode::GetScriptId() const {
   9980   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   9981   const i::CodeEntry* entry = node->entry();
   9982   return entry->script_id();
   9983 }
   9984 
   9985 Local<String> CpuProfileNode::GetScriptResourceName() const {
   9986   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   9987   i::Isolate* isolate = node->isolate();
   9988   return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
   9989       node->entry()->resource_name()));
   9990 }
   9991 
   9992 const char* CpuProfileNode::GetScriptResourceNameStr() const {
   9993   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   9994   return node->entry()->resource_name();
   9995 }
   9996 
   9997 int CpuProfileNode::GetLineNumber() const {
   9998   return reinterpret_cast<const i::ProfileNode*>(this)->line_number();
   9999 }
   10000 
   10001 
   10002 int CpuProfileNode::GetColumnNumber() const {
   10003   return reinterpret_cast<const i::ProfileNode*>(this)->
   10004       entry()->column_number();
   10005 }
   10006 
   10007 
   10008 unsigned int CpuProfileNode::GetHitLineCount() const {
   10009   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10010   return node->GetHitLineCount();
   10011 }
   10012 
   10013 
   10014 bool CpuProfileNode::GetLineTicks(LineTick* entries,
   10015                                   unsigned int length) const {
   10016   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10017   return node->GetLineTicks(entries, length);
   10018 }
   10019 
   10020 
   10021 const char* CpuProfileNode::GetBailoutReason() const {
   10022   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10023   return node->entry()->bailout_reason();
   10024 }
   10025 
   10026 
   10027 unsigned CpuProfileNode::GetHitCount() const {
   10028   return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
   10029 }
   10030 
   10031 
   10032 unsigned CpuProfileNode::GetCallUid() const {
   10033   return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
   10034 }
   10035 
   10036 
   10037 unsigned CpuProfileNode::GetNodeId() const {
   10038   return reinterpret_cast<const i::ProfileNode*>(this)->id();
   10039 }
   10040 
   10041 
   10042 int CpuProfileNode::GetChildrenCount() const {
   10043   return static_cast<int>(
   10044       reinterpret_cast<const i::ProfileNode*>(this)->children()->size());
   10045 }
   10046 
   10047 
   10048 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
   10049   const i::ProfileNode* child =
   10050       reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
   10051   return reinterpret_cast<const CpuProfileNode*>(child);
   10052 }
   10053 
   10054 
   10055 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
   10056   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10057   return node->deopt_infos();
   10058 }
   10059 
   10060 
   10061 void CpuProfile::Delete() {
   10062   i::CpuProfile* profile = reinterpret_cast<i::CpuProfile*>(this);
   10063   i::CpuProfiler* profiler = profile->cpu_profiler();
   10064   DCHECK_NOT_NULL(profiler);
   10065   profiler->DeleteProfile(profile);
   10066 }
   10067 
   10068 
   10069 Local<String> CpuProfile::GetTitle() const {
   10070   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10071   i::Isolate* isolate = profile->top_down()->isolate();
   10072   return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
   10073       profile->title()));
   10074 }
   10075 
   10076 
   10077 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
   10078   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10079   return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
   10080 }
   10081 
   10082 
   10083 const CpuProfileNode* CpuProfile::GetSample(int index) const {
   10084   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10085   return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
   10086 }
   10087 
   10088 
   10089 int64_t CpuProfile::GetSampleTimestamp(int index) const {
   10090   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10091   return (profile->sample_timestamp(index) - base::TimeTicks())
   10092       .InMicroseconds();
   10093 }
   10094 
   10095 
   10096 int64_t CpuProfile::GetStartTime() const {
   10097   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10098   return (profile->start_time() - base::TimeTicks()).InMicroseconds();
   10099 }
   10100 
   10101 
   10102 int64_t CpuProfile::GetEndTime() const {
   10103   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10104   return (profile->end_time() - base::TimeTicks()).InMicroseconds();
   10105 }
   10106 
   10107 
   10108 int CpuProfile::GetSamplesCount() const {
   10109   return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
   10110 }
   10111 
   10112 CpuProfiler* CpuProfiler::New(Isolate* isolate) {
   10113   return reinterpret_cast<CpuProfiler*>(
   10114       new i::CpuProfiler(reinterpret_cast<i::Isolate*>(isolate)));
   10115 }
   10116 
   10117 void CpuProfiler::Dispose() { delete reinterpret_cast<i::CpuProfiler*>(this); }
   10118 
   10119 // static
   10120 void CpuProfiler::CollectSample(Isolate* isolate) {
   10121   i::CpuProfiler::CollectSample(reinterpret_cast<i::Isolate*>(isolate));
   10122 }
   10123 
   10124 void CpuProfiler::SetSamplingInterval(int us) {
   10125   DCHECK_GE(us, 0);
   10126   return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
   10127       base::TimeDelta::FromMicroseconds(us));
   10128 }
   10129 
   10130 void CpuProfiler::CollectSample() {
   10131   reinterpret_cast<i::CpuProfiler*>(this)->CollectSample();
   10132 }
   10133 
   10134 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
   10135   reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
   10136       *Utils::OpenHandle(*title), record_samples, kLeafNodeLineNumbers);
   10137 }
   10138 
   10139 void CpuProfiler::StartProfiling(Local<String> title, CpuProfilingMode mode,
   10140                                  bool record_samples) {
   10141   reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
   10142       *Utils::OpenHandle(*title), record_samples, mode);
   10143 }
   10144 
   10145 CpuProfile* CpuProfiler::StopProfiling(Local<String> title) {
   10146   return reinterpret_cast<CpuProfile*>(
   10147       reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
   10148           *Utils::OpenHandle(*title)));
   10149 }
   10150 
   10151 
   10152 void CpuProfiler::SetIdle(bool is_idle) {
   10153   i::CpuProfiler* profiler = reinterpret_cast<i::CpuProfiler*>(this);
   10154   i::Isolate* isolate = profiler->isolate();
   10155   isolate->SetIdle(is_idle);
   10156 }
   10157 
   10158 uintptr_t CodeEvent::GetCodeStartAddress() {
   10159   return reinterpret_cast<i::CodeEvent*>(this)->code_start_address;
   10160 }
   10161 
   10162 size_t CodeEvent::GetCodeSize() {
   10163   return reinterpret_cast<i::CodeEvent*>(this)->code_size;
   10164 }
   10165 
   10166 Local<String> CodeEvent::GetFunctionName() {
   10167   return ToApiHandle<String>(
   10168       reinterpret_cast<i::CodeEvent*>(this)->function_name);
   10169 }
   10170 
   10171 Local<String> CodeEvent::GetScriptName() {
   10172   return ToApiHandle<String>(
   10173       reinterpret_cast<i::CodeEvent*>(this)->script_name);
   10174 }
   10175 
   10176 int CodeEvent::GetScriptLine() {
   10177   return reinterpret_cast<i::CodeEvent*>(this)->script_line;
   10178 }
   10179 
   10180 int CodeEvent::GetScriptColumn() {
   10181   return reinterpret_cast<i::CodeEvent*>(this)->script_column;
   10182 }
   10183 
   10184 CodeEventType CodeEvent::GetCodeType() {
   10185   return reinterpret_cast<i::CodeEvent*>(this)->code_type;
   10186 }
   10187 
   10188 const char* CodeEvent::GetComment() {
   10189   return reinterpret_cast<i::CodeEvent*>(this)->comment;
   10190 }
   10191 
   10192 const char* CodeEvent::GetCodeEventTypeName(CodeEventType code_event_type) {
   10193   switch (code_event_type) {
   10194     case kUnknownType:
   10195       return "Unknown";
   10196 #define V(Name)       \
   10197   case k##Name##Type: \
   10198     return #Name;
   10199       CODE_EVENTS_LIST(V)
   10200 #undef V
   10201   }
   10202   // The execution should never pass here
   10203   UNREACHABLE();
   10204   // NOTE(mmarchini): Workaround to fix a compiler failure on GCC 4.9
   10205   return "Unknown";
   10206 }
   10207 
   10208 CodeEventHandler::CodeEventHandler(Isolate* isolate) {
   10209   internal_listener_ =
   10210       new i::ExternalCodeEventListener(reinterpret_cast<i::Isolate*>(isolate));
   10211 }
   10212 
   10213 CodeEventHandler::~CodeEventHandler() {
   10214   delete reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_);
   10215 }
   10216 
   10217 void CodeEventHandler::Enable() {
   10218   reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_)
   10219       ->StartListening(this);
   10220 }
   10221 
   10222 void CodeEventHandler::Disable() {
   10223   reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_)
   10224       ->StopListening();
   10225 }
   10226 
   10227 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
   10228   return const_cast<i::HeapGraphEdge*>(
   10229       reinterpret_cast<const i::HeapGraphEdge*>(edge));
   10230 }
   10231 
   10232 
   10233 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
   10234   return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
   10235 }
   10236 
   10237 
   10238 Local<Value> HeapGraphEdge::GetName() const {
   10239   i::HeapGraphEdge* edge = ToInternal(this);
   10240   i::Isolate* isolate = edge->isolate();
   10241   switch (edge->type()) {
   10242     case i::HeapGraphEdge::kContextVariable:
   10243     case i::HeapGraphEdge::kInternal:
   10244     case i::HeapGraphEdge::kProperty:
   10245     case i::HeapGraphEdge::kShortcut:
   10246     case i::HeapGraphEdge::kWeak:
   10247       return ToApiHandle<String>(
   10248           isolate->factory()->InternalizeUtf8String(edge->name()));
   10249     case i::HeapGraphEdge::kElement:
   10250     case i::HeapGraphEdge::kHidden:
   10251       return ToApiHandle<Number>(
   10252           isolate->factory()->NewNumberFromInt(edge->index()));
   10253     default: UNREACHABLE();
   10254   }
   10255   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   10256 }
   10257 
   10258 
   10259 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
   10260   const i::HeapEntry* from = ToInternal(this)->from();
   10261   return reinterpret_cast<const HeapGraphNode*>(from);
   10262 }
   10263 
   10264 
   10265 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
   10266   const i::HeapEntry* to = ToInternal(this)->to();
   10267   return reinterpret_cast<const HeapGraphNode*>(to);
   10268 }
   10269 
   10270 
   10271 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
   10272   return const_cast<i::HeapEntry*>(
   10273       reinterpret_cast<const i::HeapEntry*>(entry));
   10274 }
   10275 
   10276 
   10277 HeapGraphNode::Type HeapGraphNode::GetType() const {
   10278   return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
   10279 }
   10280 
   10281 
   10282 Local<String> HeapGraphNode::GetName() const {
   10283   i::Isolate* isolate = ToInternal(this)->isolate();
   10284   return ToApiHandle<String>(
   10285       isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
   10286 }
   10287 
   10288 
   10289 SnapshotObjectId HeapGraphNode::GetId() const {
   10290   return ToInternal(this)->id();
   10291 }
   10292 
   10293 
   10294 size_t HeapGraphNode::GetShallowSize() const {
   10295   return ToInternal(this)->self_size();
   10296 }
   10297 
   10298 
   10299 int HeapGraphNode::GetChildrenCount() const {
   10300   return ToInternal(this)->children_count();
   10301 }
   10302 
   10303 
   10304 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
   10305   return reinterpret_cast<const HeapGraphEdge*>(ToInternal(this)->child(index));
   10306 }
   10307 
   10308 
   10309 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
   10310   return const_cast<i::HeapSnapshot*>(
   10311       reinterpret_cast<const i::HeapSnapshot*>(snapshot));
   10312 }
   10313 
   10314 
   10315 void HeapSnapshot::Delete() {
   10316   i::Isolate* isolate = ToInternal(this)->profiler()->isolate();
   10317   if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
   10318     ToInternal(this)->Delete();
   10319   } else {
   10320     // If this is the last snapshot, clean up all accessory data as well.
   10321     isolate->heap_profiler()->DeleteAllSnapshots();
   10322   }
   10323 }
   10324 
   10325 
   10326 const HeapGraphNode* HeapSnapshot::GetRoot() const {
   10327   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
   10328 }
   10329 
   10330 
   10331 const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
   10332   return reinterpret_cast<const HeapGraphNode*>(
   10333       ToInternal(this)->GetEntryById(id));
   10334 }
   10335 
   10336 
   10337 int HeapSnapshot::GetNodesCount() const {
   10338   return static_cast<int>(ToInternal(this)->entries().size());
   10339 }
   10340 
   10341 
   10342 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
   10343   return reinterpret_cast<const HeapGraphNode*>(
   10344       &ToInternal(this)->entries().at(index));
   10345 }
   10346 
   10347 
   10348 SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
   10349   return ToInternal(this)->max_snapshot_js_object_id();
   10350 }
   10351 
   10352 
   10353 void HeapSnapshot::Serialize(OutputStream* stream,
   10354                              HeapSnapshot::SerializationFormat format) const {
   10355   Utils::ApiCheck(format == kJSON,
   10356                   "v8::HeapSnapshot::Serialize",
   10357                   "Unknown serialization format");
   10358   Utils::ApiCheck(stream->GetChunkSize() > 0,
   10359                   "v8::HeapSnapshot::Serialize",
   10360                   "Invalid stream chunk size");
   10361   i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
   10362   serializer.Serialize(stream);
   10363 }
   10364 
   10365 
   10366 // static
   10367 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
   10368     HeapProfiler::kUnknownObjectId;
   10369 
   10370 
   10371 int HeapProfiler::GetSnapshotCount() {
   10372   return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
   10373 }
   10374 
   10375 
   10376 const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
   10377   return reinterpret_cast<const HeapSnapshot*>(
   10378       reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
   10379 }
   10380 
   10381 
   10382 SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) {
   10383   i::Handle<i::Object> obj = Utils::OpenHandle(*value);
   10384   return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
   10385 }
   10386 
   10387 
   10388 Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
   10389   i::Handle<i::Object> obj =
   10390       reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
   10391   if (obj.is_null()) return Local<Value>();
   10392   return Utils::ToLocal(obj);
   10393 }
   10394 
   10395 
   10396 void HeapProfiler::ClearObjectIds() {
   10397   reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
   10398 }
   10399 
   10400 
   10401 const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
   10402     ActivityControl* control, ObjectNameResolver* resolver) {
   10403   return reinterpret_cast<const HeapSnapshot*>(
   10404       reinterpret_cast<i::HeapProfiler*>(this)
   10405           ->TakeSnapshot(control, resolver));
   10406 }
   10407 
   10408 
   10409 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
   10410   reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
   10411       track_allocations);
   10412 }
   10413 
   10414 
   10415 void HeapProfiler::StopTrackingHeapObjects() {
   10416   reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
   10417 }
   10418 
   10419 
   10420 SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream,
   10421                                             int64_t* timestamp_us) {
   10422   i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
   10423   return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
   10424 }
   10425 
   10426 bool HeapProfiler::StartSamplingHeapProfiler(uint64_t sample_interval,
   10427                                              int stack_depth,
   10428                                              SamplingFlags flags) {
   10429   return reinterpret_cast<i::HeapProfiler*>(this)->StartSamplingHeapProfiler(
   10430       sample_interval, stack_depth, flags);
   10431 }
   10432 
   10433 
   10434 void HeapProfiler::StopSamplingHeapProfiler() {
   10435   reinterpret_cast<i::HeapProfiler*>(this)->StopSamplingHeapProfiler();
   10436 }
   10437 
   10438 
   10439 AllocationProfile* HeapProfiler::GetAllocationProfile() {
   10440   return reinterpret_cast<i::HeapProfiler*>(this)->GetAllocationProfile();
   10441 }
   10442 
   10443 
   10444 void HeapProfiler::DeleteAllHeapSnapshots() {
   10445   reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
   10446 }
   10447 
   10448 
   10449 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
   10450                                                WrapperInfoCallback callback) {
   10451   reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
   10452                                                                callback);
   10453 }
   10454 
   10455 void HeapProfiler::SetGetRetainerInfosCallback(
   10456     GetRetainerInfosCallback callback) {
   10457   reinterpret_cast<i::HeapProfiler*>(this)->SetGetRetainerInfosCallback(
   10458       callback);
   10459 }
   10460 
   10461 void HeapProfiler::SetBuildEmbedderGraphCallback(
   10462     LegacyBuildEmbedderGraphCallback callback) {
   10463   reinterpret_cast<i::HeapProfiler*>(this)->AddBuildEmbedderGraphCallback(
   10464       [](v8::Isolate* isolate, v8::EmbedderGraph* graph, void* data) {
   10465         reinterpret_cast<LegacyBuildEmbedderGraphCallback>(data)(isolate,
   10466                                                                  graph);
   10467       },
   10468       reinterpret_cast<void*>(callback));
   10469 }
   10470 
   10471 void HeapProfiler::AddBuildEmbedderGraphCallback(
   10472     BuildEmbedderGraphCallback callback, void* data) {
   10473   reinterpret_cast<i::HeapProfiler*>(this)->AddBuildEmbedderGraphCallback(
   10474       callback, data);
   10475 }
   10476 
   10477 void HeapProfiler::RemoveBuildEmbedderGraphCallback(
   10478     BuildEmbedderGraphCallback callback, void* data) {
   10479   reinterpret_cast<i::HeapProfiler*>(this)->RemoveBuildEmbedderGraphCallback(
   10480       callback, data);
   10481 }
   10482 
   10483 v8::Testing::StressType internal::Testing::stress_type_ =
   10484     v8::Testing::kStressTypeOpt;
   10485 
   10486 
   10487 void Testing::SetStressRunType(Testing::StressType type) {
   10488   internal::Testing::set_stress_type(type);
   10489 }
   10490 
   10491 
   10492 int Testing::GetStressRuns() {
   10493   if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
   10494 #ifdef DEBUG
   10495   // In debug mode the code runs much slower so stressing will only make two
   10496   // runs.
   10497   return 2;
   10498 #else
   10499   return 5;
   10500 #endif
   10501 }
   10502 
   10503 
   10504 static void SetFlagsFromString(const char* flags) {
   10505   V8::SetFlagsFromString(flags, i::StrLength(flags));
   10506 }
   10507 
   10508 
   10509 void Testing::PrepareStressRun(int run) {
   10510   static const char* kLazyOptimizations =
   10511       "--prepare-always-opt "
   10512       "--max-inlined-bytecode-size=999999 "
   10513       "--max-inlined-bytecode-size-cumulative=999999 "
   10514       "--noalways-opt";
   10515   static const char* kForcedOptimizations = "--always-opt";
   10516 
   10517   // If deoptimization stressed turn on frequent deoptimization. If no value
   10518   // is spefified through --deopt-every-n-times use a default default value.
   10519   static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
   10520   if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
   10521       internal::FLAG_deopt_every_n_times == 0) {
   10522     SetFlagsFromString(kDeoptEvery13Times);
   10523   }
   10524 
   10525 #ifdef DEBUG
   10526   // As stressing in debug mode only make two runs skip the deopt stressing
   10527   // here.
   10528   if (run == GetStressRuns() - 1) {
   10529     SetFlagsFromString(kForcedOptimizations);
   10530   } else {
   10531     SetFlagsFromString(kLazyOptimizations);
   10532   }
   10533 #else
   10534   if (run == GetStressRuns() - 1) {
   10535     SetFlagsFromString(kForcedOptimizations);
   10536   } else if (run != GetStressRuns() - 2) {
   10537     SetFlagsFromString(kLazyOptimizations);
   10538   }
   10539 #endif
   10540 }
   10541 
   10542 
   10543 void Testing::DeoptimizeAll(Isolate* isolate) {
   10544   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   10545   i::HandleScope scope(i_isolate);
   10546   i::Deoptimizer::DeoptimizeAll(i_isolate);
   10547 }
   10548 
   10549 void EmbedderHeapTracer::FinalizeTracing() {
   10550   if (isolate_) {
   10551     i::Isolate* isolate = reinterpret_cast<i::Isolate*>(isolate_);
   10552     if (isolate->heap()->incremental_marking()->IsMarking()) {
   10553       isolate->heap()->FinalizeIncrementalMarkingAtomically(
   10554           i::GarbageCollectionReason::kExternalFinalize);
   10555     }
   10556   }
   10557 }
   10558 
   10559 void EmbedderHeapTracer::GarbageCollectionForTesting(
   10560     EmbedderStackState stack_state) {
   10561   CHECK(isolate_);
   10562   CHECK(i::FLAG_expose_gc);
   10563   i::Heap* const heap = reinterpret_cast<i::Isolate*>(isolate_)->heap();
   10564   heap->SetEmbedderStackStateForNextFinalizaton(stack_state);
   10565   heap->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask,
   10566                           i::GarbageCollectionReason::kTesting,
   10567                           kGCCallbackFlagForced);
   10568 }
   10569 
   10570 bool EmbedderHeapTracer::AdvanceTracing(double deadline_in_ms) {
   10571 #if __clang__
   10572 #pragma clang diagnostic push
   10573 #pragma clang diagnostic ignored "-Wdeprecated"
   10574 #endif
   10575   return !this->AdvanceTracing(
   10576       deadline_in_ms, AdvanceTracingActions(std::isinf(deadline_in_ms)
   10577                                                 ? FORCE_COMPLETION
   10578                                                 : DO_NOT_FORCE_COMPLETION));
   10579 #if __clang__
   10580 #pragma clang diagnostic pop
   10581 #endif
   10582 }
   10583 
   10584 void EmbedderHeapTracer::EnterFinalPause(EmbedderStackState stack_state) {
   10585 #if __clang__
   10586 #pragma clang diagnostic push
   10587 #pragma clang diagnostic ignored "-Wdeprecated"
   10588 #endif
   10589   this->EnterFinalPause();
   10590 #if __clang__
   10591 #pragma clang diagnostic pop
   10592 #endif
   10593 }
   10594 
   10595 bool EmbedderHeapTracer::IsTracingDone() {
   10596 // TODO(mlippautz): Implement using "return true" after removing the deprecated
   10597 // call.
   10598 #if __clang__
   10599 #pragma clang diagnostic push
   10600 #pragma clang diagnostic ignored "-Wdeprecated"
   10601 #endif
   10602   return NumberOfWrappersToTrace() == 0;
   10603 #if __clang__
   10604 #pragma clang diagnostic pop
   10605 #endif
   10606 }
   10607 
   10608 namespace internal {
   10609 
   10610 void HandleScopeImplementer::FreeThreadResources() {
   10611   Free();
   10612 }
   10613 
   10614 
   10615 char* HandleScopeImplementer::ArchiveThread(char* storage) {
   10616   HandleScopeData* current = isolate_->handle_scope_data();
   10617   handle_scope_data_ = *current;
   10618   MemCopy(storage, this, sizeof(*this));
   10619 
   10620   ResetAfterArchive();
   10621   current->Initialize();
   10622 
   10623   return storage + ArchiveSpacePerThread();
   10624 }
   10625 
   10626 
   10627 int HandleScopeImplementer::ArchiveSpacePerThread() {
   10628   return sizeof(HandleScopeImplementer);
   10629 }
   10630 
   10631 
   10632 char* HandleScopeImplementer::RestoreThread(char* storage) {
   10633   MemCopy(this, storage, sizeof(*this));
   10634   *isolate_->handle_scope_data() = handle_scope_data_;
   10635   return storage + ArchiveSpacePerThread();
   10636 }
   10637 
   10638 void HandleScopeImplementer::IterateThis(RootVisitor* v) {
   10639 #ifdef DEBUG
   10640   bool found_block_before_deferred = false;
   10641 #endif
   10642   // Iterate over all handles in the blocks except for the last.
   10643   for (int i = static_cast<int>(blocks()->size()) - 2; i >= 0; --i) {
   10644     Object** block = blocks()->at(i);
   10645     if (last_handle_before_deferred_block_ != nullptr &&
   10646         (last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) &&
   10647         (last_handle_before_deferred_block_ >= block)) {
   10648       v->VisitRootPointers(Root::kHandleScope, nullptr, block,
   10649                            last_handle_before_deferred_block_);
   10650       DCHECK(!found_block_before_deferred);
   10651 #ifdef DEBUG
   10652       found_block_before_deferred = true;
   10653 #endif
   10654     } else {
   10655       v->VisitRootPointers(Root::kHandleScope, nullptr, block,
   10656                            &block[kHandleBlockSize]);
   10657     }
   10658   }
   10659 
   10660   DCHECK(last_handle_before_deferred_block_ == nullptr ||
   10661          found_block_before_deferred);
   10662 
   10663   // Iterate over live handles in the last block (if any).
   10664   if (!blocks()->empty()) {
   10665     v->VisitRootPointers(Root::kHandleScope, nullptr, blocks()->back(),
   10666                          handle_scope_data_.next);
   10667   }
   10668 
   10669   DetachableVector<Context*>* context_lists[2] = {&saved_contexts_,
   10670                                                   &entered_contexts_};
   10671   for (unsigned i = 0; i < arraysize(context_lists); i++) {
   10672     if (context_lists[i]->empty()) continue;
   10673     Object** start = reinterpret_cast<Object**>(&context_lists[i]->front());
   10674     v->VisitRootPointers(Root::kHandleScope, nullptr, start,
   10675                          start + context_lists[i]->size());
   10676   }
   10677   if (microtask_context_) {
   10678     v->VisitRootPointer(Root::kHandleScope, nullptr,
   10679                         reinterpret_cast<Object**>(&microtask_context_));
   10680   }
   10681 }
   10682 
   10683 void HandleScopeImplementer::Iterate(RootVisitor* v) {
   10684   HandleScopeData* current = isolate_->handle_scope_data();
   10685   handle_scope_data_ = *current;
   10686   IterateThis(v);
   10687 }
   10688 
   10689 char* HandleScopeImplementer::Iterate(RootVisitor* v, char* storage) {
   10690   HandleScopeImplementer* scope_implementer =
   10691       reinterpret_cast<HandleScopeImplementer*>(storage);
   10692   scope_implementer->IterateThis(v);
   10693   return storage + ArchiveSpacePerThread();
   10694 }
   10695 
   10696 
   10697 DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) {
   10698   DeferredHandles* deferred =
   10699       new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
   10700 
   10701   while (!blocks_.empty()) {
   10702     Object** block_start = blocks_.back();
   10703     Object** block_limit = &block_start[kHandleBlockSize];
   10704     // We should not need to check for SealHandleScope here. Assert this.
   10705     DCHECK(prev_limit == block_limit ||
   10706            !(block_start <= prev_limit && prev_limit <= block_limit));
   10707     if (prev_limit == block_limit) break;
   10708     deferred->blocks_.push_back(blocks_.back());
   10709     blocks_.pop_back();
   10710   }
   10711 
   10712   // deferred->blocks_ now contains the blocks installed on the
   10713   // HandleScope stack since BeginDeferredScope was called, but in
   10714   // reverse order.
   10715 
   10716   DCHECK(prev_limit == nullptr || !blocks_.empty());
   10717 
   10718   DCHECK(!blocks_.empty() && prev_limit != nullptr);
   10719   DCHECK_NOT_NULL(last_handle_before_deferred_block_);
   10720   last_handle_before_deferred_block_ = nullptr;
   10721   return deferred;
   10722 }
   10723 
   10724 
   10725 void HandleScopeImplementer::BeginDeferredScope() {
   10726   DCHECK_NULL(last_handle_before_deferred_block_);
   10727   last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
   10728 }
   10729 
   10730 
   10731 DeferredHandles::~DeferredHandles() {
   10732   isolate_->UnlinkDeferredHandles(this);
   10733 
   10734   for (size_t i = 0; i < blocks_.size(); i++) {
   10735 #ifdef ENABLE_HANDLE_ZAPPING
   10736     HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
   10737 #endif
   10738     isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
   10739   }
   10740 }
   10741 
   10742 void DeferredHandles::Iterate(RootVisitor* v) {
   10743   DCHECK(!blocks_.empty());
   10744 
   10745   DCHECK((first_block_limit_ >= blocks_.front()) &&
   10746          (first_block_limit_ <= &(blocks_.front())[kHandleBlockSize]));
   10747 
   10748   v->VisitRootPointers(Root::kHandleScope, nullptr, blocks_.front(),
   10749                        first_block_limit_);
   10750 
   10751   for (size_t i = 1; i < blocks_.size(); i++) {
   10752     v->VisitRootPointers(Root::kHandleScope, nullptr, blocks_[i],
   10753                          &blocks_[i][kHandleBlockSize]);
   10754   }
   10755 }
   10756 
   10757 
   10758 void InvokeAccessorGetterCallback(
   10759     v8::Local<v8::Name> property,
   10760     const v8::PropertyCallbackInfo<v8::Value>& info,
   10761     v8::AccessorNameGetterCallback getter) {
   10762   // Leaving JavaScript.
   10763   Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
   10764   RuntimeCallTimerScope timer(isolate,
   10765                               RuntimeCallCounterId::kAccessorGetterCallback);
   10766   Address getter_address = reinterpret_cast<Address>(getter);
   10767   VMState<EXTERNAL> state(isolate);
   10768   ExternalCallbackScope call_scope(isolate, getter_address);
   10769   getter(property, info);
   10770 }
   10771 
   10772 
   10773 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
   10774                             v8::FunctionCallback callback) {
   10775   Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
   10776   RuntimeCallTimerScope timer(isolate,
   10777                               RuntimeCallCounterId::kInvokeFunctionCallback);
   10778   Address callback_address = reinterpret_cast<Address>(callback);
   10779   VMState<EXTERNAL> state(isolate);
   10780   ExternalCallbackScope call_scope(isolate, callback_address);
   10781   callback(info);
   10782 }
   10783 
   10784 // Undefine macros for jumbo build.
   10785 #undef LOG_API
   10786 #undef ENTER_V8_DO_NOT_USE
   10787 #undef ENTER_V8_HELPER_DO_NOT_USE
   10788 #undef PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE
   10789 #undef PREPARE_FOR_EXECUTION_WITH_CONTEXT
   10790 #undef PREPARE_FOR_EXECUTION
   10791 #undef ENTER_V8
   10792 #undef ENTER_V8_NO_SCRIPT
   10793 #undef ENTER_V8_NO_SCRIPT_NO_EXCEPTION
   10794 #undef ENTER_V8_FOR_NEW_CONTEXT
   10795 #undef EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE
   10796 #undef RETURN_ON_FAILED_EXECUTION
   10797 #undef RETURN_ON_FAILED_EXECUTION_PRIMITIVE
   10798 #undef RETURN_TO_LOCAL_UNCHECKED
   10799 #undef RETURN_ESCAPED
   10800 #undef SET_FIELD_WRAPPED
   10801 #undef NEW_STRING
   10802 #undef CALLBACK_SETTER
   10803 
   10804 }  // namespace internal
   10805 }  // namespace v8
   10806