LCOV - code coverage report
Current view: top level - src - api.cc (source / functions) Hit Total Coverage
Test: app.info Lines: 3531 4052 87.1 %
Date: 2019-04-18 Functions: 903 1089 82.9 %

          Line data    Source code
       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/compiler-dispatcher/compiler-dispatcher.h"
      30             : #include "src/compiler.h"
      31             : #include "src/contexts.h"
      32             : #include "src/conversions-inl.h"
      33             : #include "src/counters.h"
      34             : #include "src/cpu-features.h"
      35             : #include "src/date.h"
      36             : #include "src/debug/debug-coverage.h"
      37             : #include "src/debug/debug-evaluate.h"
      38             : #include "src/debug/debug-type-profile.h"
      39             : #include "src/debug/debug.h"
      40             : #include "src/debug/liveedit.h"
      41             : #include "src/deoptimizer.h"
      42             : #include "src/detachable-vector.h"
      43             : #include "src/execution.h"
      44             : #include "src/frames-inl.h"
      45             : #include "src/gdb-jit.h"
      46             : #include "src/global-handles.h"
      47             : #include "src/globals.h"
      48             : #include "src/heap/heap-inl.h"
      49             : #include "src/icu_util.h"
      50             : #include "src/isolate-inl.h"
      51             : #include "src/json-parser.h"
      52             : #include "src/json-stringifier.h"
      53             : #include "src/messages.h"
      54             : #include "src/microtask-queue.h"
      55             : #include "src/objects-inl.h"
      56             : #include "src/objects/api-callbacks.h"
      57             : #include "src/objects/embedder-data-array-inl.h"
      58             : #include "src/objects/embedder-data-slot-inl.h"
      59             : #include "src/objects/frame-array-inl.h"
      60             : #include "src/objects/hash-table-inl.h"
      61             : #include "src/objects/heap-object.h"
      62             : #include "src/objects/js-array-inl.h"
      63             : #include "src/objects/js-collection-inl.h"
      64             : #include "src/objects/js-generator-inl.h"
      65             : #include "src/objects/js-promise-inl.h"
      66             : #include "src/objects/js-regexp-inl.h"
      67             : #include "src/objects/module-inl.h"
      68             : #include "src/objects/oddball.h"
      69             : #include "src/objects/ordered-hash-table-inl.h"
      70             : #include "src/objects/slots.h"
      71             : #include "src/objects/smi.h"
      72             : #include "src/objects/stack-frame-info-inl.h"
      73             : #include "src/objects/templates.h"
      74             : #include "src/parsing/parse-info.h"
      75             : #include "src/parsing/parser.h"
      76             : #include "src/parsing/scanner-character-streams.h"
      77             : #include "src/pending-compilation-error-handler.h"
      78             : #include "src/profiler/cpu-profiler.h"
      79             : #include "src/profiler/heap-profiler.h"
      80             : #include "src/profiler/heap-snapshot-generator-inl.h"
      81             : #include "src/profiler/profile-generator-inl.h"
      82             : #include "src/profiler/tick-sample.h"
      83             : #include "src/property-descriptor.h"
      84             : #include "src/property-details.h"
      85             : #include "src/property.h"
      86             : #include "src/prototype.h"
      87             : #include "src/runtime-profiler.h"
      88             : #include "src/runtime/runtime.h"
      89             : #include "src/simulator.h"
      90             : #include "src/snapshot/code-serializer.h"
      91             : #include "src/snapshot/natives.h"
      92             : #include "src/snapshot/partial-serializer.h"
      93             : #include "src/snapshot/read-only-serializer.h"
      94             : #include "src/snapshot/snapshot.h"
      95             : #include "src/snapshot/startup-serializer.h"
      96             : #include "src/startup-data-util.h"
      97             : #include "src/string-hasher.h"
      98             : #include "src/tracing/trace-event.h"
      99             : #include "src/trap-handler/trap-handler.h"
     100             : #include "src/unicode-inl.h"
     101             : #include "src/v8.h"
     102             : #include "src/v8threads.h"
     103             : #include "src/value-serializer.h"
     104             : #include "src/version.h"
     105             : #include "src/vm-state-inl.h"
     106             : #include "src/wasm/streaming-decoder.h"
     107             : #include "src/wasm/wasm-engine.h"
     108             : #include "src/wasm/wasm-objects-inl.h"
     109             : #include "src/wasm/wasm-result.h"
     110             : #include "src/wasm/wasm-serialization.h"
     111             : 
     112             : #if V8_OS_LINUX || V8_OS_MACOSX
     113             : #include <signal.h>
     114             : #include "include/v8-wasm-trap-handler-posix.h"
     115             : #include "src/trap-handler/handler-inside-posix.h"
     116             : #endif
     117             : 
     118             : #if V8_OS_WIN
     119             : #include <versionhelpers.h>
     120             : #include <windows.h>
     121             : #include "include/v8-wasm-trap-handler-win.h"
     122             : #include "src/trap-handler/handler-inside-win.h"
     123             : #if V8_TARGET_ARCH_X64
     124             : #include "src/unwinding-info-win64.h"
     125             : #endif  // V8_TARGET_ARCH_X64
     126             : #endif  // V8_OS_WIN
     127             : 
     128             : namespace v8 {
     129             : 
     130             : /*
     131             :  * Most API methods should use one of the three macros:
     132             :  *
     133             :  * ENTER_V8, ENTER_V8_NO_SCRIPT, ENTER_V8_NO_SCRIPT_NO_EXCEPTION.
     134             :  *
     135             :  * The latter two assume that no script is executed, and no exceptions are
     136             :  * scheduled in addition (respectively). Creating a pending exception and
     137             :  * removing it before returning is ok.
     138             :  *
     139             :  * Exceptions should be handled either by invoking one of the
     140             :  * RETURN_ON_FAILED_EXECUTION* macros.
     141             :  *
     142             :  * Don't use macros with DO_NOT_USE in their name.
     143             :  *
     144             :  * TODO(jochen): Document debugger specific macros.
     145             :  * TODO(jochen): Document LOG_API and other RuntimeCallStats macros.
     146             :  * TODO(jochen): All API methods should invoke one of the ENTER_V8* macros.
     147             :  * TODO(jochen): Remove calls form API methods to DO_NOT_USE macros.
     148             :  */
     149             : 
     150             : #define LOG_API(isolate, class_name, function_name)                           \
     151             :   i::RuntimeCallTimerScope _runtime_timer(                                    \
     152             :       isolate, i::RuntimeCallCounterId::kAPI_##class_name##_##function_name); \
     153             :   LOG(isolate, ApiEntryCall("v8::" #class_name "::" #function_name))
     154             : 
     155             : #define ENTER_V8_DO_NOT_USE(isolate) i::VMState<v8::OTHER> __state__((isolate))
     156             : 
     157             : #define ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name,  \
     158             :                                    function_name, bailout_value,  \
     159             :                                    HandleScopeClass, do_callback) \
     160             :   if (IsExecutionTerminatingCheck(isolate)) {                     \
     161             :     return bailout_value;                                         \
     162             :   }                                                               \
     163             :   HandleScopeClass handle_scope(isolate);                         \
     164             :   CallDepthScope<do_callback> call_depth_scope(isolate, context); \
     165             :   LOG_API(isolate, class_name, function_name);                    \
     166             :   i::VMState<v8::OTHER> __state__((isolate));                     \
     167             :   bool has_pending_exception = false
     168             : 
     169             : #define PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, T)       \
     170             :   if (IsExecutionTerminatingCheck(isolate)) {                                \
     171             :     return MaybeLocal<T>();                                                  \
     172             :   }                                                                          \
     173             :   InternalEscapableScope handle_scope(isolate);                              \
     174             :   CallDepthScope<false> call_depth_scope(isolate, v8::Local<v8::Context>()); \
     175             :   i::VMState<v8::OTHER> __state__((isolate));                                \
     176             :   bool has_pending_exception = false
     177             : 
     178             : #define PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \
     179             :                                            bailout_value, HandleScopeClass,    \
     180             :                                            do_callback)                        \
     181             :   auto isolate = context.IsEmpty()                                             \
     182             :                      ? i::Isolate::Current()                                   \
     183             :                      : reinterpret_cast<i::Isolate*>(context->GetIsolate());   \
     184             :   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name,      \
     185             :                              bailout_value, HandleScopeClass, do_callback);
     186             : 
     187             : #define PREPARE_FOR_EXECUTION(context, class_name, function_name, T)          \
     188             :   PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name,      \
     189             :                                      MaybeLocal<T>(), InternalEscapableScope, \
     190             :                                      false)
     191             : 
     192             : #define ENTER_V8(isolate, context, class_name, function_name, bailout_value, \
     193             :                  HandleScopeClass)                                           \
     194             :   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name,    \
     195             :                              bailout_value, HandleScopeClass, true)
     196             : 
     197             : #ifdef DEBUG
     198             : #define ENTER_V8_NO_SCRIPT(isolate, context, class_name, function_name,   \
     199             :                            bailout_value, HandleScopeClass)               \
     200             :   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
     201             :                              bailout_value, HandleScopeClass, false);     \
     202             :   i::DisallowJavascriptExecutionDebugOnly __no_script__((isolate))
     203             : 
     204             : #define ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate)                    \
     205             :   i::VMState<v8::OTHER> __state__((isolate));                       \
     206             :   i::DisallowJavascriptExecutionDebugOnly __no_script__((isolate)); \
     207             :   i::DisallowExceptions __no_exceptions__((isolate))
     208             : 
     209             : #define ENTER_V8_FOR_NEW_CONTEXT(isolate)     \
     210             :   i::VMState<v8::OTHER> __state__((isolate)); \
     211             :   i::DisallowExceptions __no_exceptions__((isolate))
     212             : #else
     213             : #define ENTER_V8_NO_SCRIPT(isolate, context, class_name, function_name,   \
     214             :                            bailout_value, HandleScopeClass)               \
     215             :   ENTER_V8_HELPER_DO_NOT_USE(isolate, context, class_name, function_name, \
     216             :                              bailout_value, HandleScopeClass, false)
     217             : 
     218             : #define ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate) \
     219             :   i::VMState<v8::OTHER> __state__((isolate));
     220             : 
     221             : #define ENTER_V8_FOR_NEW_CONTEXT(isolate) \
     222             :   i::VMState<v8::OTHER> __state__((isolate));
     223             : #endif  // DEBUG
     224             : 
     225             : #define EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, value) \
     226             :   do {                                                            \
     227             :     if (has_pending_exception) {                                  \
     228             :       call_depth_scope.Escape();                                  \
     229             :       return value;                                               \
     230             :     }                                                             \
     231             :   } while (false)
     232             : 
     233             : #define RETURN_ON_FAILED_EXECUTION(T) \
     234             :   EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, MaybeLocal<T>())
     235             : 
     236             : #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \
     237             :   EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE(isolate, Nothing<T>())
     238             : 
     239             : #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \
     240             :   return maybe_local.FromMaybe(Local<T>());
     241             : 
     242             : 
     243             : #define RETURN_ESCAPED(value) return handle_scope.Escape(value);
     244             : 
     245             : namespace {
     246             : 
     247             : Local<Context> ContextFromNeverReadOnlySpaceObject(
     248             :     i::Handle<i::JSReceiver> obj) {
     249           0 :   return reinterpret_cast<v8::Isolate*>(obj->GetIsolate())->GetCurrentContext();
     250             : }
     251             : 
     252     7332482 : class InternalEscapableScope : public v8::EscapableHandleScope {
     253             :  public:
     254             :   explicit inline InternalEscapableScope(i::Isolate* isolate)
     255     7332484 :       : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {}
     256             : };
     257             : 
     258             : // TODO(jochen): This should be #ifdef DEBUG
     259             : #ifdef V8_CHECK_MICROTASKS_SCOPES_CONSISTENCY
     260             : void CheckMicrotasksScopesConsistency(i::MicrotaskQueue* microtask_queue) {
     261             :   if (microtask_queue &&
     262             :       microtask_queue->microtasks_policy() == v8::MicrotasksPolicy::kScoped) {
     263             :     DCHECK(microtask_queue->GetMicrotasksScopeDepth() ||
     264             :            !microtask_queue->DebugMicrotasksScopeDepthIsZero());
     265             :   }
     266             : }
     267             : #endif
     268             : 
     269             : template <bool do_callback>
     270             : class CallDepthScope {
     271             :  public:
     272    12414864 :   explicit CallDepthScope(i::Isolate* isolate, Local<Context> context)
     273             :       : isolate_(isolate),
     274             :         context_(context),
     275             :         escaped_(false),
     276             :         safe_for_termination_(isolate->next_v8_call_is_safe_for_termination()),
     277             :         interrupts_scope_(isolate_, i::StackGuard::TERMINATE_EXECUTION,
     278             :                           isolate_->only_terminate_in_safe_scope()
     279             :                               ? (safe_for_termination_
     280             :                                      ? i::InterruptsScope::kRunInterrupts
     281             :                                      : i::InterruptsScope::kPostponeInterrupts)
     282    12414864 :                               : i::InterruptsScope::kNoop) {
     283    12414867 :     isolate_->handle_scope_implementer()->IncrementCallDepth();
     284    12414867 :     isolate_->set_next_v8_call_is_safe_for_termination(false);
     285    12414867 :     if (!context.IsEmpty()) {
     286             :       i::Handle<i::Context> env = Utils::OpenHandle(*context);
     287             :       i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
     288    24810178 :       if (!isolate->context().is_null() &&
     289             :           isolate->context()->native_context() == env->native_context()) {
     290    12404653 :         context_ = Local<Context>();
     291             :       } else {
     292             :         impl->SaveContext(isolate->context());
     293             :         isolate->set_context(*env);
     294             :       }
     295             :     }
     296     5428279 :     if (do_callback) isolate_->FireBeforeCallEnteredCallback();
     297    12414868 :   }
     298    12414855 :   ~CallDepthScope() {
     299    12414855 :     i::MicrotaskQueue* microtask_queue = isolate_->default_microtask_queue();
     300    12414855 :     if (!context_.IsEmpty()) {
     301             :       i::HandleScopeImplementer* impl = isolate_->handle_scope_implementer();
     302         662 :       isolate_->set_context(impl->RestoreContext());
     303             : 
     304             :       i::Handle<i::Context> env = Utils::OpenHandle(*context_);
     305             :       microtask_queue = env->native_context()->microtask_queue();
     306             :     }
     307    12414855 :     if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth();
     308     5428266 :     if (do_callback) isolate_->FireCallCompletedCallback(microtask_queue);
     309             : // TODO(jochen): This should be #ifdef DEBUG
     310             : #ifdef V8_CHECK_MICROTASKS_SCOPES_CONSISTENCY
     311             :     if (do_callback) CheckMicrotasksScopesConsistency(microtask_queue);
     312             : #endif
     313    12414854 :     isolate_->set_next_v8_call_is_safe_for_termination(safe_for_termination_);
     314    12414863 :   }
     315             : 
     316       12590 :   void Escape() {
     317             :     DCHECK(!escaped_);
     318       12590 :     escaped_ = true;
     319       12590 :     auto handle_scope_implementer = isolate_->handle_scope_implementer();
     320             :     handle_scope_implementer->DecrementCallDepth();
     321             :     bool clear_exception =
     322             :         handle_scope_implementer->CallDepthIsZero() &&
     323       12590 :         isolate_->thread_local_top()->try_catch_handler_ == nullptr;
     324       12590 :     isolate_->OptionalRescheduleException(clear_exception);
     325       12590 :   }
     326             : 
     327             :  private:
     328             :   i::Isolate* const isolate_;
     329             :   Local<Context> context_;
     330             :   bool escaped_;
     331             :   bool do_callback_;
     332             :   bool safe_for_termination_;
     333             :   i::InterruptsScope interrupts_scope_;
     334             : };
     335             : 
     336             : }  // namespace
     337             : 
     338             : 
     339       16109 : static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate,
     340             :                                              i::Handle<i::Script> script) {
     341       32218 :   i::Handle<i::Object> scriptName(script->GetNameOrSourceURL(), isolate);
     342             :   i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate);
     343             :   i::Handle<i::FixedArray> host_defined_options(script->host_defined_options(),
     344             :                                                 isolate);
     345             :   v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
     346             :   ScriptOriginOptions options(script->origin_options());
     347             :   v8::ScriptOrigin origin(
     348             :       Utils::ToLocal(scriptName),
     349             :       v8::Integer::New(v8_isolate, script->line_offset()),
     350             :       v8::Integer::New(v8_isolate, script->column_offset()),
     351             :       v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()),
     352             :       v8::Integer::New(v8_isolate, script->id()),
     353             :       Utils::ToLocal(source_map_url),
     354             :       v8::Boolean::New(v8_isolate, options.IsOpaque()),
     355             :       v8::Boolean::New(v8_isolate, script->type() == i::Script::TYPE_WASM),
     356             :       v8::Boolean::New(v8_isolate, options.IsModule()),
     357       48327 :       Utils::ToLocal(host_defined_options));
     358       16109 :   return origin;
     359             : }
     360             : 
     361             : 
     362             : // --- E x c e p t i o n   B e h a v i o r ---
     363             : 
     364           5 : void i::FatalProcessOutOfMemory(i::Isolate* isolate, const char* location) {
     365           5 :   i::V8::FatalProcessOutOfMemory(isolate, location, false);
     366             : }
     367             : 
     368             : // When V8 cannot allocate memory FatalProcessOutOfMemory is called. The default
     369             : // OOM error handler is called and execution is stopped.
     370          15 : void i::V8::FatalProcessOutOfMemory(i::Isolate* isolate, const char* location,
     371             :                                     bool is_heap_oom) {
     372             :   char last_few_messages[Heap::kTraceRingBufferSize + 1];
     373             :   char js_stacktrace[Heap::kStacktraceBufferSize + 1];
     374             :   i::HeapStats heap_stats;
     375             : 
     376          15 :   if (isolate == nullptr) {
     377             :     isolate = Isolate::TryGetCurrent();
     378             :   }
     379             : 
     380          15 :   if (isolate == nullptr) {
     381             :     // If the Isolate is not available for the current thread we cannot retrieve
     382             :     // memory information from the Isolate. Write easy-to-recognize values on
     383             :     // the stack.
     384             :     memset(last_few_messages, 0x0BADC0DE, Heap::kTraceRingBufferSize + 1);
     385             :     memset(js_stacktrace, 0x0BADC0DE, Heap::kStacktraceBufferSize + 1);
     386             :     memset(&heap_stats, 0xBADC0DE, sizeof(heap_stats));
     387             :     // Note that the embedder's oom handler is also not available and therefore
     388             :     // won't be called in this case. We just crash.
     389           0 :     FATAL("Fatal process out of memory: %s", location);
     390             :     UNREACHABLE();
     391             :   }
     392             : 
     393             :   memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
     394             :   memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1);
     395             : 
     396             :   intptr_t start_marker;
     397          15 :   heap_stats.start_marker = &start_marker;
     398             :   size_t ro_space_size;
     399          15 :   heap_stats.ro_space_size = &ro_space_size;
     400             :   size_t ro_space_capacity;
     401          15 :   heap_stats.ro_space_capacity = &ro_space_capacity;
     402             :   size_t new_space_size;
     403          15 :   heap_stats.new_space_size = &new_space_size;
     404             :   size_t new_space_capacity;
     405          15 :   heap_stats.new_space_capacity = &new_space_capacity;
     406             :   size_t old_space_size;
     407          15 :   heap_stats.old_space_size = &old_space_size;
     408             :   size_t old_space_capacity;
     409          15 :   heap_stats.old_space_capacity = &old_space_capacity;
     410             :   size_t code_space_size;
     411          15 :   heap_stats.code_space_size = &code_space_size;
     412             :   size_t code_space_capacity;
     413          15 :   heap_stats.code_space_capacity = &code_space_capacity;
     414             :   size_t map_space_size;
     415          15 :   heap_stats.map_space_size = &map_space_size;
     416             :   size_t map_space_capacity;
     417          15 :   heap_stats.map_space_capacity = &map_space_capacity;
     418             :   size_t lo_space_size;
     419          15 :   heap_stats.lo_space_size = &lo_space_size;
     420             :   size_t code_lo_space_size;
     421          15 :   heap_stats.code_lo_space_size = &code_lo_space_size;
     422             :   size_t global_handle_count;
     423          15 :   heap_stats.global_handle_count = &global_handle_count;
     424             :   size_t weak_global_handle_count;
     425          15 :   heap_stats.weak_global_handle_count = &weak_global_handle_count;
     426             :   size_t pending_global_handle_count;
     427          15 :   heap_stats.pending_global_handle_count = &pending_global_handle_count;
     428             :   size_t near_death_global_handle_count;
     429          15 :   heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
     430             :   size_t free_global_handle_count;
     431          15 :   heap_stats.free_global_handle_count = &free_global_handle_count;
     432             :   size_t memory_allocator_size;
     433          15 :   heap_stats.memory_allocator_size = &memory_allocator_size;
     434             :   size_t memory_allocator_capacity;
     435          15 :   heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
     436             :   size_t malloced_memory;
     437          15 :   heap_stats.malloced_memory = &malloced_memory;
     438             :   size_t malloced_peak_memory;
     439          15 :   heap_stats.malloced_peak_memory = &malloced_peak_memory;
     440          15 :   size_t objects_per_type[LAST_TYPE + 1] = {0};
     441          15 :   heap_stats.objects_per_type = objects_per_type;
     442          15 :   size_t size_per_type[LAST_TYPE + 1] = {0};
     443          15 :   heap_stats.size_per_type = size_per_type;
     444             :   int os_error;
     445          15 :   heap_stats.os_error = &os_error;
     446          15 :   heap_stats.last_few_messages = last_few_messages;
     447          15 :   heap_stats.js_stacktrace = js_stacktrace;
     448             :   intptr_t end_marker;
     449          15 :   heap_stats.end_marker = &end_marker;
     450          15 :   if (isolate->heap()->HasBeenSetUp()) {
     451             :     // BUG(1718): Don't use the take_snapshot since we don't support
     452             :     // HeapIterator here without doing a special GC.
     453          15 :     isolate->heap()->RecordStats(&heap_stats, false);
     454             :     char* first_newline = strchr(last_few_messages, '\n');
     455          15 :     if (first_newline == nullptr || first_newline[1] == '\0')
     456             :       first_newline = last_few_messages;
     457          15 :     PrintF("\n<--- Last few GCs --->\n%s\n", first_newline);
     458          15 :     PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace);
     459             :   }
     460          15 :   Utils::ReportOOMFailure(isolate, location, is_heap_oom);
     461             :   // If the fatal error handler returns, we stop execution.
     462           0 :   FATAL("API fatal error handler returned after process out of memory");
     463             : }
     464             : 
     465             : 
     466          10 : void Utils::ReportApiFailure(const char* location, const char* message) {
     467             :   i::Isolate* isolate = i::Isolate::Current();
     468             :   FatalErrorCallback callback = nullptr;
     469          10 :   if (isolate != nullptr) {
     470             :     callback = isolate->exception_behavior();
     471             :   }
     472          10 :   if (callback == nullptr) {
     473             :     base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
     474           0 :                          message);
     475           0 :     base::OS::Abort();
     476             :   } else {
     477          10 :     callback(location, message);
     478             :   }
     479             :   isolate->SignalFatalError();
     480          10 : }
     481             : 
     482          15 : void Utils::ReportOOMFailure(i::Isolate* isolate, const char* location,
     483             :                              bool is_heap_oom) {
     484             :   OOMErrorCallback oom_callback = isolate->oom_behavior();
     485          15 :   if (oom_callback == nullptr) {
     486             :     // TODO(wfh): Remove this fallback once Blink is setting OOM handler. See
     487             :     // crbug.com/614440.
     488             :     FatalErrorCallback fatal_callback = isolate->exception_behavior();
     489          15 :     if (fatal_callback == nullptr) {
     490           0 :       base::OS::PrintError("\n#\n# Fatal %s OOM in %s\n#\n\n",
     491           0 :                            is_heap_oom ? "javascript" : "process", location);
     492           0 :       base::OS::Abort();
     493             :     } else {
     494          15 :       fatal_callback(location,
     495             :                      is_heap_oom
     496             :                          ? "Allocation failed - JavaScript heap out of memory"
     497          15 :                          : "Allocation failed - process out of memory");
     498             :     }
     499             :   } else {
     500           0 :     oom_callback(location, is_heap_oom);
     501             :   }
     502             :   isolate->SignalFatalError();
     503           0 : }
     504             : 
     505             : static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
     506    12416405 :   if (isolate->has_scheduled_exception()) {
     507             :     return isolate->scheduled_exception() ==
     508             :            i::ReadOnlyRoots(isolate).termination_exception();
     509             :   }
     510             :   return false;
     511             : }
     512             : 
     513             : 
     514       61017 : void V8::SetNativesDataBlob(StartupData* natives_blob) {
     515       61017 :   i::V8::SetNativesBlob(natives_blob);
     516       61017 : }
     517             : 
     518             : 
     519       61017 : void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
     520       61017 :   i::V8::SetSnapshotBlob(snapshot_blob);
     521       61017 : }
     522             : 
     523             : namespace {
     524             : 
     525      304375 : class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
     526             :  public:
     527      321171 :   void* Allocate(size_t length) override {
     528             : #if V8_OS_AIX && _LINUX_SOURCE_COMPAT
     529             :     // Work around for GCC bug on AIX
     530             :     // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79839
     531             :     void* data = __linux_calloc(length, 1);
     532             : #else
     533      321171 :     void* data = calloc(length, 1);
     534             : #endif
     535      321171 :     return data;
     536             :   }
     537             : 
     538       18576 :   void* AllocateUninitialized(size_t length) override {
     539             : #if V8_OS_AIX && _LINUX_SOURCE_COMPAT
     540             :     // Work around for GCC bug on AIX
     541             :     // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79839
     542             :     void* data = __linux_malloc(length);
     543             : #else
     544       18576 :     void* data = malloc(length);
     545             : #endif
     546       18576 :     return data;
     547             :   }
     548             : 
     549      339540 :   void Free(void* data, size_t) override { free(data); }
     550             : };
     551             : 
     552         588 : struct SnapshotCreatorData {
     553             :   explicit SnapshotCreatorData(Isolate* isolate)
     554             :       : isolate_(isolate),
     555             :         default_context_(),
     556             :         contexts_(isolate),
     557         392 :         created_(false) {}
     558             : 
     559             :   static SnapshotCreatorData* cast(void* data) {
     560             :     return reinterpret_cast<SnapshotCreatorData*>(data);
     561             :   }
     562             : 
     563             :   ArrayBufferAllocator allocator_;
     564             :   Isolate* isolate_;
     565             :   Persistent<Context> default_context_;
     566             :   SerializeInternalFieldsCallback default_embedder_fields_serializer_;
     567             :   PersistentValueVector<Context> contexts_;
     568             :   std::vector<SerializeInternalFieldsCallback> embedder_fields_serializers_;
     569             :   bool created_;
     570             : };
     571             : 
     572             : }  // namespace
     573             : 
     574         196 : SnapshotCreator::SnapshotCreator(Isolate* isolate,
     575             :                                  const intptr_t* external_references,
     576             :                                  StartupData* existing_snapshot) {
     577         196 :   SnapshotCreatorData* data = new SnapshotCreatorData(isolate);
     578             :   data->isolate_ = isolate;
     579             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
     580         196 :   internal_isolate->set_array_buffer_allocator(&data->allocator_);
     581             :   internal_isolate->set_api_external_references(external_references);
     582             :   internal_isolate->enable_serializer();
     583             :   isolate->Enter();
     584             :   const StartupData* blob = existing_snapshot
     585             :                                 ? existing_snapshot
     586         196 :                                 : i::Snapshot::DefaultSnapshotBlob();
     587         196 :   if (blob && blob->raw_size > 0) {
     588             :     internal_isolate->set_snapshot_blob(blob);
     589         195 :     i::Snapshot::Initialize(internal_isolate);
     590             :   } else {
     591           1 :     internal_isolate->InitWithoutSnapshot();
     592             :   }
     593         196 :   data_ = data;
     594         196 : }
     595             : 
     596         195 : SnapshotCreator::SnapshotCreator(const intptr_t* external_references,
     597             :                                  StartupData* existing_snapshot)
     598             :     : SnapshotCreator(Isolate::Allocate(), external_references,
     599         195 :                       existing_snapshot) {}
     600             : 
     601         392 : SnapshotCreator::~SnapshotCreator() {
     602         196 :   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
     603             :   DCHECK(data->created_);
     604         196 :   Isolate* isolate = data->isolate_;
     605             :   isolate->Exit();
     606         196 :   isolate->Dispose();
     607         196 :   delete data;
     608         196 : }
     609             : 
     610         196 : Isolate* SnapshotCreator::GetIsolate() {
     611         196 :   return SnapshotCreatorData::cast(data_)->isolate_;
     612             : }
     613             : 
     614         196 : void SnapshotCreator::SetDefaultContext(
     615             :     Local<Context> context, SerializeInternalFieldsCallback callback) {
     616             :   DCHECK(!context.IsEmpty());
     617         196 :   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
     618             :   DCHECK(!data->created_);
     619             :   DCHECK(data->default_context_.IsEmpty());
     620         196 :   Isolate* isolate = data->isolate_;
     621         196 :   CHECK_EQ(isolate, context->GetIsolate());
     622             :   data->default_context_.Reset(isolate, context);
     623         196 :   data->default_embedder_fields_serializer_ = callback;
     624         196 : }
     625             : 
     626          35 : size_t SnapshotCreator::AddContext(Local<Context> context,
     627             :                                    SerializeInternalFieldsCallback callback) {
     628             :   DCHECK(!context.IsEmpty());
     629          35 :   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
     630             :   DCHECK(!data->created_);
     631          35 :   Isolate* isolate = data->isolate_;
     632          35 :   CHECK_EQ(isolate, context->GetIsolate());
     633             :   size_t index = data->contexts_.Size();
     634          35 :   data->contexts_.Append(context);
     635          35 :   data->embedder_fields_serializers_.push_back(callback);
     636          35 :   return index;
     637             : }
     638             : 
     639          10 : size_t SnapshotCreator::AddTemplate(Local<Template> template_obj) {
     640          10 :   return AddData(template_obj);
     641             : }
     642             : 
     643          50 : size_t SnapshotCreator::AddData(i::Address object) {
     644             :   DCHECK_NE(object, i::kNullAddress);
     645          50 :   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
     646             :   DCHECK(!data->created_);
     647          50 :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_);
     648             :   i::HandleScope scope(isolate);
     649             :   i::Handle<i::Object> obj(i::Object(object), isolate);
     650             :   i::Handle<i::ArrayList> list;
     651         100 :   if (!isolate->heap()->serialized_objects()->IsArrayList()) {
     652           5 :     list = i::ArrayList::New(isolate, 1);
     653             :   } else {
     654             :     list = i::Handle<i::ArrayList>(
     655             :         i::ArrayList::cast(isolate->heap()->serialized_objects()), isolate);
     656             :   }
     657          50 :   size_t index = static_cast<size_t>(list->Length());
     658          50 :   list = i::ArrayList::Add(isolate, list, obj);
     659          50 :   isolate->heap()->SetSerializedObjects(*list);
     660          50 :   return index;
     661             : }
     662             : 
     663          35 : size_t SnapshotCreator::AddData(Local<Context> context, i::Address object) {
     664             :   DCHECK_NE(object, i::kNullAddress);
     665             :   DCHECK(!SnapshotCreatorData::cast(data_)->created_);
     666             :   i::Handle<i::Context> ctx = Utils::OpenHandle(*context);
     667             :   i::Isolate* isolate = ctx->GetIsolate();
     668             :   i::HandleScope scope(isolate);
     669             :   i::Handle<i::Object> obj(i::Object(object), isolate);
     670             :   i::Handle<i::ArrayList> list;
     671          70 :   if (!ctx->serialized_objects()->IsArrayList()) {
     672           5 :     list = i::ArrayList::New(isolate, 1);
     673             :   } else {
     674             :     list = i::Handle<i::ArrayList>(
     675          60 :         i::ArrayList::cast(ctx->serialized_objects()), isolate);
     676             :   }
     677          35 :   size_t index = static_cast<size_t>(list->Length());
     678          35 :   list = i::ArrayList::Add(isolate, list, obj);
     679          70 :   ctx->set_serialized_objects(*list);
     680          35 :   return index;
     681             : }
     682             : 
     683             : namespace {
     684         231 : void ConvertSerializedObjectsToFixedArray(Local<Context> context) {
     685             :   i::Handle<i::Context> ctx = Utils::OpenHandle(*context);
     686             :   i::Isolate* isolate = ctx->GetIsolate();
     687         462 :   if (!ctx->serialized_objects()->IsArrayList()) {
     688           5 :     ctx->set_serialized_objects(i::ReadOnlyRoots(isolate).empty_fixed_array());
     689             :   } else {
     690         452 :     i::Handle<i::ArrayList> list(i::ArrayList::cast(ctx->serialized_objects()),
     691             :                                  isolate);
     692         226 :     i::Handle<i::FixedArray> elements = i::ArrayList::Elements(isolate, list);
     693         226 :     ctx->set_serialized_objects(*elements);
     694             :   }
     695         231 : }
     696             : 
     697         196 : void ConvertSerializedObjectsToFixedArray(i::Isolate* isolate) {
     698         392 :   if (!isolate->heap()->serialized_objects()->IsArrayList()) {
     699             :     isolate->heap()->SetSerializedObjects(
     700           0 :         i::ReadOnlyRoots(isolate).empty_fixed_array());
     701             :   } else {
     702             :     i::Handle<i::ArrayList> list(
     703             :         i::ArrayList::cast(isolate->heap()->serialized_objects()), isolate);
     704         196 :     i::Handle<i::FixedArray> elements = i::ArrayList::Elements(isolate, list);
     705         196 :     isolate->heap()->SetSerializedObjects(*elements);
     706             :   }
     707         196 : }
     708             : }  // anonymous namespace
     709             : 
     710         196 : StartupData SnapshotCreator::CreateBlob(
     711             :     SnapshotCreator::FunctionCodeHandling function_code_handling) {
     712         196 :   SnapshotCreatorData* data = SnapshotCreatorData::cast(data_);
     713         196 :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_);
     714             :   DCHECK(!data->created_);
     715             :   DCHECK(!data->default_context_.IsEmpty());
     716             : 
     717         196 :   int num_additional_contexts = static_cast<int>(data->contexts_.Size());
     718             : 
     719             :   {
     720             :     i::HandleScope scope(isolate);
     721             :     // Convert list of context-independent data to FixedArray.
     722         196 :     ConvertSerializedObjectsToFixedArray(isolate);
     723             : 
     724             :     // Convert lists of context-dependent data to FixedArray.
     725         196 :     ConvertSerializedObjectsToFixedArray(
     726         196 :         data->default_context_.Get(data->isolate_));
     727         266 :     for (int i = 0; i < num_additional_contexts; i++) {
     728          35 :       ConvertSerializedObjectsToFixedArray(data->contexts_.Get(i));
     729             :     }
     730             : 
     731             :     // We need to store the global proxy size upfront in case we need the
     732             :     // bootstrapper to create a global proxy before we deserialize the context.
     733             :     i::Handle<i::FixedArray> global_proxy_sizes =
     734             :         isolate->factory()->NewFixedArray(num_additional_contexts,
     735         196 :                                           i::AllocationType::kOld);
     736         266 :     for (int i = 0; i < num_additional_contexts; i++) {
     737             :       i::Handle<i::Context> context =
     738          70 :           v8::Utils::OpenHandle(*data->contexts_.Get(i));
     739          35 :       global_proxy_sizes->set(i,
     740          70 :                               i::Smi::FromInt(context->global_proxy()->Size()));
     741             :     }
     742         392 :     isolate->heap()->SetSerializedGlobalProxySizes(*global_proxy_sizes);
     743             :   }
     744             : 
     745             :   // We might rehash strings and re-sort descriptors. Clear the lookup cache.
     746         196 :   isolate->descriptor_lookup_cache()->Clear();
     747             : 
     748             :   // If we don't do this then we end up with a stray root pointing at the
     749             :   // context even after we have disposed of the context.
     750         196 :   isolate->heap()->CollectAllAvailableGarbage(
     751         196 :       i::GarbageCollectionReason::kSnapshotCreator);
     752             :   {
     753         196 :     i::HandleScope scope(isolate);
     754         196 :     isolate->heap()->CompactWeakArrayLists(internal::AllocationType::kOld);
     755             :   }
     756             : 
     757         196 :   isolate->heap()->read_only_space()->ClearStringPaddingIfNeeded();
     758             : 
     759         196 :   if (function_code_handling == FunctionCodeHandling::kClear) {
     760             :     // Clear out re-compilable data from all shared function infos. Any
     761             :     // JSFunctions using these SFIs will have their code pointers reset by the
     762             :     // partial serializer.
     763             :     //
     764             :     // We have to iterate the heap and collect handles to each clearable SFI,
     765             :     // before we disable allocation, since we have to allocate UncompiledDatas
     766             :     // to be able to recompile them.
     767             :     //
     768             :     // Compiled irregexp code is also flushed by collecting and clearing any
     769             :     // seen JSRegExp objects.
     770         166 :     i::HandleScope scope(isolate);
     771             :     std::vector<i::Handle<i::SharedFunctionInfo>> sfis_to_clear;
     772             : 
     773             :     {  // Heap allocation is disallowed within this scope.
     774         332 :       i::HeapIterator heap_iterator(isolate->heap());
     775     1421734 :       for (i::HeapObject current_obj = heap_iterator.next();
     776             :            !current_obj.is_null(); current_obj = heap_iterator.next()) {
     777     1421568 :         if (current_obj->IsSharedFunctionInfo()) {
     778             :           i::SharedFunctionInfo shared =
     779      153626 :               i::SharedFunctionInfo::cast(current_obj);
     780      153626 :           if (shared->CanDiscardCompiled()) {
     781          37 :             sfis_to_clear.emplace_back(shared, isolate);
     782             :           }
     783     1267942 :         } else if (current_obj->IsJSRegExp()) {
     784          10 :           i::JSRegExp regexp = i::JSRegExp::cast(current_obj);
     785          10 :           if (regexp->HasCompiledCode()) {
     786           5 :             regexp->DiscardCompiledCodeForSerialization();
     787             :           }
     788             :         }
     789             :       }
     790             :     }
     791             : 
     792             :     // Must happen after heap iteration since SFI::DiscardCompiled may allocate.
     793         203 :     for (i::Handle<i::SharedFunctionInfo> shared : sfis_to_clear) {
     794          37 :       i::SharedFunctionInfo::DiscardCompiled(isolate, shared);
     795             :     }
     796             :   }
     797             : 
     798             :   i::DisallowHeapAllocation no_gc_from_here_on;
     799             : 
     800         196 :   int num_contexts = num_additional_contexts + 1;
     801             :   std::vector<i::Context> contexts;
     802         196 :   contexts.reserve(num_contexts);
     803             :   {
     804         196 :     i::HandleScope scope(isolate);
     805         392 :     contexts.push_back(
     806         196 :         *v8::Utils::OpenHandle(*data->default_context_.Get(data->isolate_)));
     807             :     data->default_context_.Reset();
     808         266 :     for (int i = 0; i < num_additional_contexts; i++) {
     809             :       i::Handle<i::Context> context =
     810          70 :           v8::Utils::OpenHandle(*data->contexts_.Get(i));
     811          70 :       contexts.push_back(*context);
     812             :     }
     813         196 :     data->contexts_.Clear();
     814             :   }
     815             : 
     816             :   // Check that values referenced by global/eternal handles are accounted for.
     817         196 :   i::SerializedHandleChecker handle_checker(isolate, &contexts);
     818         196 :   CHECK(handle_checker.CheckGlobalAndEternalHandles());
     819             : 
     820         588 :   i::HeapIterator heap_iterator(isolate->heap());
     821     1615181 :   for (i::HeapObject current_obj = heap_iterator.next(); !current_obj.is_null();
     822             :        current_obj = heap_iterator.next()) {
     823     1614985 :     if (current_obj->IsJSFunction()) {
     824      189533 :       i::JSFunction fun = i::JSFunction::cast(current_obj);
     825             : 
     826             :       // Complete in-object slack tracking for all functions.
     827      189533 :       fun->CompleteInobjectSlackTrackingIfActive();
     828             : 
     829             :       // Also, clear out feedback vectors, or any optimized code.
     830      189533 :       if (!fun->raw_feedback_cell()->value()->IsUndefined()) {
     831         120 :         fun->raw_feedback_cell()->set_value(
     832         240 :             i::ReadOnlyRoots(isolate).undefined_value());
     833         120 :         fun->set_code(isolate->builtins()->builtin(i::Builtins::kCompileLazy));
     834             :       }
     835             :       if (function_code_handling == FunctionCodeHandling::kClear) {
     836             :         DCHECK(fun->shared()->HasWasmExportedFunctionData() ||
     837             :                fun->shared()->HasBuiltinId() ||
     838             :                fun->shared()->IsApiFunction() ||
     839             :                fun->shared()->HasUncompiledDataWithoutPreparseData());
     840             :       }
     841             :     }
     842             :   }
     843             : 
     844         392 :   i::ReadOnlySerializer read_only_serializer(isolate);
     845         196 :   read_only_serializer.SerializeReadOnlyRoots();
     846             : 
     847         392 :   i::StartupSerializer startup_serializer(isolate, &read_only_serializer);
     848         196 :   startup_serializer.SerializeStrongReferences();
     849             : 
     850             :   // Serialize each context with a new partial serializer.
     851             :   std::vector<i::SnapshotData*> context_snapshots;
     852         196 :   context_snapshots.reserve(num_contexts);
     853             : 
     854             :   // TODO(6593): generalize rehashing, and remove this flag.
     855             :   bool can_be_rehashed = true;
     856             : 
     857         658 :   for (int i = 0; i < num_contexts; i++) {
     858             :     bool is_default_context = i == 0;
     859             :     i::PartialSerializer partial_serializer(
     860             :         isolate, &startup_serializer,
     861             :         is_default_context ? data->default_embedder_fields_serializer_
     862         693 :                            : data->embedder_fields_serializers_[i - 1]);
     863         462 :     partial_serializer.Serialize(&contexts[i], !is_default_context);
     864         231 :     can_be_rehashed = can_be_rehashed && partial_serializer.can_be_rehashed();
     865         462 :     context_snapshots.push_back(new i::SnapshotData(&partial_serializer));
     866             :   }
     867             : 
     868         196 :   startup_serializer.SerializeWeakReferencesAndDeferred();
     869         196 :   can_be_rehashed = can_be_rehashed && startup_serializer.can_be_rehashed();
     870             : 
     871         196 :   read_only_serializer.FinalizeSerialization();
     872         196 :   can_be_rehashed = can_be_rehashed && read_only_serializer.can_be_rehashed();
     873             : 
     874         196 :   i::SnapshotData read_only_snapshot(&read_only_serializer);
     875         196 :   i::SnapshotData startup_snapshot(&startup_serializer);
     876             :   StartupData result =
     877             :       i::Snapshot::CreateSnapshotBlob(&startup_snapshot, &read_only_snapshot,
     878         196 :                                       context_snapshots, can_be_rehashed);
     879             : 
     880             :   // Delete heap-allocated context snapshot instances.
     881         427 :   for (const auto context_snapshot : context_snapshots) {
     882         231 :     delete context_snapshot;
     883             :   }
     884         196 :   data->created_ = true;
     885             : 
     886             :   DCHECK(i::Snapshot::VerifyChecksum(&result));
     887         392 :   return result;
     888             : }
     889             : 
     890           5 : void V8::SetDcheckErrorHandler(DcheckErrorCallback that) {
     891           5 :   v8::base::SetDcheckFunction(that);
     892           5 : }
     893             : 
     894       90313 : void V8::SetFlagsFromString(const char* str, int length) {
     895      112213 :   i::FlagList::SetFlagsFromString(str, length);
     896      112213 :   i::FlagList::EnforceFlagImplications();
     897       90313 : }
     898             : 
     899             : 
     900       34360 : void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
     901       34360 :   i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
     902       34360 : }
     903             : 
     904             : RegisteredExtension* RegisteredExtension::first_extension_ = nullptr;
     905             : 
     906           0 : RegisteredExtension::RegisteredExtension(std::unique_ptr<Extension> extension)
     907      446208 :     : extension_(std::move(extension)) {}
     908             : 
     909             : // static
     910           0 : void RegisteredExtension::Register(std::unique_ptr<Extension> extension) {
     911             :   RegisteredExtension* new_extension =
     912      446208 :       new RegisteredExtension(std::move(extension));
     913      446208 :   new_extension->next_ = first_extension_;
     914      446208 :   first_extension_ = new_extension;
     915           0 : }
     916             : 
     917             : // static
     918       59903 : void RegisteredExtension::UnregisterAll() {
     919       59903 :   RegisteredExtension* re = first_extension_;
     920      499121 :   while (re != nullptr) {
     921             :     RegisteredExtension* next = re->next();
     922      878436 :     delete re;
     923             :     re = next;
     924             :   }
     925       59903 :   first_extension_ = nullptr;
     926       59903 : }
     927             : 
     928             : namespace {
     929      878436 : class ExtensionResource : public String::ExternalOneByteStringResource {
     930             :  public:
     931             :   ExtensionResource() : data_(nullptr), length_(0) {}
     932             :   ExtensionResource(const char* data, size_t length)
     933      446208 :       : data_(data), length_(length) {}
     934       13023 :   const char* data() const override { return data_; }
     935        9267 :   size_t length() const override { return length_; }
     936        4632 :   void Dispose() override {}
     937             : 
     938             :  private:
     939             :   const char* data_;
     940             :   size_t length_;
     941             : };
     942             : }  // anonymous namespace
     943             : 
     944      446208 : void RegisterExtension(std::unique_ptr<Extension> extension) {
     945             :   RegisteredExtension::Register(std::move(extension));
     946      446208 : }
     947             : 
     948      446208 : Extension::Extension(const char* name,
     949             :                      const char* source,
     950             :                      int dep_count,
     951             :                      const char** deps,
     952             :                      int source_length)
     953             :     : name_(name),
     954             :       source_length_(source_length >= 0 ?
     955             :                      source_length :
     956      446188 :                      (source ? static_cast<int>(strlen(source)) : 0)),
     957             :       dep_count_(dep_count),
     958             :       deps_(deps),
     959      892396 :       auto_enable_(false) {
     960      892416 :   source_ = new ExtensionResource(source, source_length_);
     961      446208 :   CHECK(source != nullptr || source_length_ == 0);
     962      446208 : }
     963             : 
     964       61812 : ResourceConstraints::ResourceConstraints()
     965             :     : max_semi_space_size_in_kb_(0),
     966             :       max_old_space_size_(0),
     967             :       stack_limit_(nullptr),
     968             :       code_range_size_(0),
     969       61812 :       max_zone_pool_size_(0) {}
     970             : 
     971       30106 : void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
     972             :                                             uint64_t virtual_memory_limit) {
     973             :   set_max_semi_space_size_in_kb(
     974             :       i::Heap::ComputeMaxSemiSpaceSize(physical_memory));
     975       30106 :   set_max_old_space_size(i::Heap::ComputeMaxOldGenerationSize(physical_memory));
     976             : 
     977       30106 :   if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
     978             :     // Reserve no more than 1/8 of the memory for the code range, but at most
     979             :     // kMaximalCodeRangeSize.
     980           0 :     set_code_range_size(
     981             :         i::Min(i::kMaximalCodeRangeSize / i::MB,
     982           0 :                static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
     983             :   }
     984       30106 : }
     985             : 
     986       62136 : void SetResourceConstraints(i::Isolate* isolate,
     987             :                             const ResourceConstraints& constraints) {
     988             :   size_t semi_space_size = constraints.max_semi_space_size_in_kb();
     989             :   size_t old_space_size = constraints.max_old_space_size();
     990             :   size_t code_range_size = constraints.code_range_size();
     991       62136 :   if (semi_space_size != 0 || old_space_size != 0 || code_range_size != 0) {
     992             :     isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
     993       30122 :                                    code_range_size);
     994             :   }
     995             : 
     996       62136 :   if (constraints.stack_limit() != nullptr) {
     997           0 :     uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
     998           0 :     isolate->stack_guard()->SetStackLimit(limit);
     999             :   }
    1000       62136 : }
    1001             : 
    1002     3049968 : i::Address* V8::GlobalizeReference(i::Isolate* isolate, i::Address* obj) {
    1003     3049968 :   LOG_API(isolate, Persistent, New);
    1004     3049968 :   i::Handle<i::Object> result = isolate->global_handles()->Create(*obj);
    1005             : #ifdef VERIFY_HEAP
    1006             :   if (i::FLAG_verify_heap) {
    1007             :     i::Object(*obj)->ObjectVerify(isolate);
    1008             :   }
    1009             : #endif  // VERIFY_HEAP
    1010     3049968 :   return result.location();
    1011             : }
    1012             : 
    1013          70 : i::Address* V8::GlobalizeTracedReference(i::Isolate* isolate, i::Address* obj,
    1014             :                                          internal::Address* slot) {
    1015          70 :   LOG_API(isolate, TracedGlobal, New);
    1016             :   i::Handle<i::Object> result =
    1017          70 :       isolate->global_handles()->CreateTraced(*obj, slot);
    1018             : #ifdef VERIFY_HEAP
    1019             :   if (i::FLAG_verify_heap) {
    1020             :     i::Object(*obj)->ObjectVerify(isolate);
    1021             :   }
    1022             : #endif  // VERIFY_HEAP
    1023          70 :   return result.location();
    1024             : }
    1025             : 
    1026          10 : i::Address* V8::CopyGlobalReference(i::Address* from) {
    1027          10 :   i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(from);
    1028          10 :   return result.location();
    1029             : }
    1030             : 
    1031        5836 : void V8::MoveGlobalReference(internal::Address** from, internal::Address** to) {
    1032        5836 :   i::GlobalHandles::MoveGlobal(from, to);
    1033        5836 : }
    1034             : 
    1035          55 : void V8::MoveTracedGlobalReference(internal::Address** from,
    1036             :                                    internal::Address** to) {
    1037          55 :   i::GlobalHandles::MoveTracedGlobal(from, to);
    1038          55 : }
    1039             : 
    1040           0 : void V8::RegisterExternallyReferencedObject(i::Address* location,
    1041             :                                             i::Isolate* isolate) {
    1042           0 :   isolate->heap()->RegisterExternallyReferencedObject(location);
    1043           0 : }
    1044             : 
    1045      166991 : void V8::MakeWeak(i::Address* location, void* parameter,
    1046             :                   WeakCallbackInfo<void>::Callback weak_callback,
    1047             :                   WeakCallbackType type) {
    1048      166991 :   i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type);
    1049      166991 : }
    1050             : 
    1051          36 : void V8::MakeWeak(i::Address** location_addr) {
    1052          36 :   i::GlobalHandles::MakeWeak(location_addr);
    1053          36 : }
    1054             : 
    1055       21093 : void* V8::ClearWeak(i::Address* location) {
    1056       21093 :   return i::GlobalHandles::ClearWeakness(location);
    1057             : }
    1058             : 
    1059     2813371 : void V8::AnnotateStrongRetainer(i::Address* location, const char* label) {
    1060     2813371 :   i::GlobalHandles::AnnotateStrongRetainer(location, label);
    1061     2813371 : }
    1062             : 
    1063     3047250 : void V8::DisposeGlobal(i::Address* location) {
    1064     3047481 :   i::GlobalHandles::Destroy(location);
    1065     3047250 : }
    1066             : 
    1067          50 : void V8::DisposeTracedGlobal(internal::Address* location) {
    1068          50 :   i::GlobalHandles::DestroyTraced(location);
    1069          50 : }
    1070             : 
    1071          10 : void V8::SetFinalizationCallbackTraced(
    1072             :     internal::Address* location, void* parameter,
    1073             :     WeakCallbackInfo<void>::Callback callback) {
    1074             :   i::GlobalHandles::SetFinalizationCallbackForTraced(location, parameter,
    1075          10 :                                                      callback);
    1076          10 : }
    1077             : 
    1078       10245 : Value* V8::Eternalize(Isolate* v8_isolate, Value* value) {
    1079             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    1080       10245 :   i::Object object = *Utils::OpenHandle(value);
    1081       10245 :   int index = -1;
    1082       10245 :   isolate->eternal_handles()->Create(isolate, object, &index);
    1083             :   return reinterpret_cast<Value*>(
    1084       20490 :       isolate->eternal_handles()->Get(index).location());
    1085             : }
    1086             : 
    1087             : 
    1088           0 : void V8::FromJustIsNothing() {
    1089             :   Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing.");
    1090           0 : }
    1091             : 
    1092             : 
    1093           0 : void V8::ToLocalEmpty() {
    1094             :   Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal.");
    1095           0 : }
    1096             : 
    1097           0 : void V8::InternalFieldOutOfBounds(int index) {
    1098           0 :   Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback,
    1099             :                   "WeakCallbackInfo::GetInternalField",
    1100             :                   "Internal field out of bounds.");
    1101           0 : }
    1102             : 
    1103             : 
    1104             : // --- H a n d l e s ---
    1105             : 
    1106             : 
    1107   476297940 : HandleScope::HandleScope(Isolate* isolate) {
    1108   476298061 :   Initialize(isolate);
    1109   476297933 : }
    1110             : 
    1111             : 
    1112   484023149 : void HandleScope::Initialize(Isolate* isolate) {
    1113             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    1114             :   // We do not want to check the correct usage of the Locker class all over the
    1115             :   // place, so we do it only here: Without a HandleScope, an embedder can do
    1116             :   // almost nothing, so it is enough to check in this central place.
    1117             :   // We make an exception if the serializer is enabled, which means that the
    1118             :   // Isolate is exclusively used to create a snapshot.
    1119             :   Utils::ApiCheck(
    1120   484082347 :       !v8::Locker::IsActive() ||
    1121   484023119 :           internal_isolate->thread_manager()->IsLockedByCurrentThread() ||
    1122             :           internal_isolate->serializer_enabled(),
    1123             :       "HandleScope::HandleScope",
    1124             :       "Entering the V8 API without proper locking in place");
    1125             :   i::HandleScopeData* current = internal_isolate->handle_scope_data();
    1126   484023104 :   isolate_ = internal_isolate;
    1127   484023104 :   prev_next_ = current->next;
    1128   484023104 :   prev_limit_ = current->limit;
    1129   484023104 :   current->level++;
    1130   484023104 : }
    1131             : 
    1132             : 
    1133   967706941 : HandleScope::~HandleScope() {
    1134   484023186 :   i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
    1135   483683755 : }
    1136             : 
    1137           0 : void* HandleScope::operator new(size_t) { base::OS::Abort(); }
    1138           0 : void* HandleScope::operator new[](size_t) { base::OS::Abort(); }
    1139           0 : void HandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
    1140           0 : void HandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }
    1141             : 
    1142        6036 : int HandleScope::NumberOfHandles(Isolate* isolate) {
    1143             :   return i::HandleScope::NumberOfHandles(
    1144        6036 :       reinterpret_cast<i::Isolate*>(isolate));
    1145             : }
    1146             : 
    1147     5256990 : i::Address* HandleScope::CreateHandle(i::Isolate* isolate, i::Address value) {
    1148     5256983 :   return i::HandleScope::CreateHandle(isolate, value);
    1149             : }
    1150             : 
    1151     7725162 : EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
    1152             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    1153             :   escape_slot_ =
    1154     7725162 :       CreateHandle(isolate, i::ReadOnlyRoots(isolate).the_hole_value()->ptr());
    1155     7725162 :   Initialize(v8_isolate);
    1156     7725150 : }
    1157             : 
    1158     6851279 : i::Address* EscapableHandleScope::Escape(i::Address* escape_value) {
    1159             :   i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
    1160     6851279 :   Utils::ApiCheck(i::Object(*escape_slot_)->IsTheHole(heap->isolate()),
    1161             :                   "EscapableHandleScope::Escape", "Escape value set twice");
    1162     6851280 :   if (escape_value == nullptr) {
    1163          10 :     *escape_slot_ = i::ReadOnlyRoots(heap).undefined_value()->ptr();
    1164           5 :     return nullptr;
    1165             :   }
    1166     6851275 :   *escape_slot_ = *escape_value;
    1167     6851275 :   return escape_slot_;
    1168             : }
    1169             : 
    1170           0 : void* EscapableHandleScope::operator new(size_t) { base::OS::Abort(); }
    1171           0 : void* EscapableHandleScope::operator new[](size_t) { base::OS::Abort(); }
    1172           0 : void EscapableHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
    1173           0 : void EscapableHandleScope::operator delete[](void*, size_t) {
    1174           0 :   base::OS::Abort();
    1175             : }
    1176             : 
    1177      340884 : SealHandleScope::SealHandleScope(Isolate* isolate)
    1178      340884 :     : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
    1179             :   i::HandleScopeData* current = isolate_->handle_scope_data();
    1180      340884 :   prev_limit_ = current->limit;
    1181      340884 :   current->limit = current->next;
    1182      340884 :   prev_sealed_level_ = current->sealed_level;
    1183      340884 :   current->sealed_level = current->level;
    1184      340884 : }
    1185             : 
    1186             : 
    1187      681768 : SealHandleScope::~SealHandleScope() {
    1188      340884 :   i::HandleScopeData* current = isolate_->handle_scope_data();
    1189             :   DCHECK_EQ(current->next, current->limit);
    1190      340884 :   current->limit = prev_limit_;
    1191             :   DCHECK_EQ(current->level, current->sealed_level);
    1192      340884 :   current->sealed_level = prev_sealed_level_;
    1193      340884 : }
    1194             : 
    1195           0 : void* SealHandleScope::operator new(size_t) { base::OS::Abort(); }
    1196           0 : void* SealHandleScope::operator new[](size_t) { base::OS::Abort(); }
    1197           0 : void SealHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
    1198           0 : void SealHandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }
    1199             : 
    1200     4375753 : void Context::Enter() {
    1201             :   i::Handle<i::Context> env = Utils::OpenHandle(this);
    1202             :   i::Isolate* isolate = env->GetIsolate();
    1203             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1204             :   i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
    1205             :   impl->EnterContext(*env);
    1206             :   impl->SaveContext(isolate->context());
    1207             :   isolate->set_context(*env);
    1208     4375731 : }
    1209             : 
    1210     4358469 : void Context::Exit() {
    1211             :   i::Handle<i::Context> env = Utils::OpenHandle(this);
    1212             :   i::Isolate* isolate = env->GetIsolate();
    1213             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1214             :   i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
    1215     4358481 :   if (!Utils::ApiCheck(impl->LastEnteredContextWas(*env), "v8::Context::Exit()",
    1216             :                        "Cannot exit non-entered context")) {
    1217             :     return;
    1218             :   }
    1219             :   impl->LeaveContext();
    1220             :   isolate->set_context(impl->RestoreContext());
    1221             : }
    1222             : 
    1223           2 : Context::BackupIncumbentScope::BackupIncumbentScope(
    1224             :     Local<Context> backup_incumbent_context)
    1225           2 :     : backup_incumbent_context_(backup_incumbent_context) {
    1226             :   DCHECK(!backup_incumbent_context_.IsEmpty());
    1227             : 
    1228             :   i::Handle<i::Context> env = Utils::OpenHandle(*backup_incumbent_context_);
    1229             :   i::Isolate* isolate = env->GetIsolate();
    1230             : 
    1231             :   js_stack_comparable_address_ =
    1232           2 :       i::SimulatorStack::RegisterJSStackComparableAddress(isolate);
    1233             : 
    1234           2 :   prev_ = isolate->top_backup_incumbent_scope();
    1235             :   isolate->set_top_backup_incumbent_scope(this);
    1236           2 : }
    1237             : 
    1238           4 : Context::BackupIncumbentScope::~BackupIncumbentScope() {
    1239             :   i::Handle<i::Context> env = Utils::OpenHandle(*backup_incumbent_context_);
    1240             :   i::Isolate* isolate = env->GetIsolate();
    1241             : 
    1242             :   i::SimulatorStack::UnregisterJSStackComparableAddress(isolate);
    1243             : 
    1244           2 :   isolate->set_top_backup_incumbent_scope(prev_);
    1245           2 : }
    1246             : 
    1247             : STATIC_ASSERT(i::Internals::kEmbedderDataSlotSize == i::kEmbedderDataSlotSize);
    1248             : 
    1249      114399 : static i::Handle<i::EmbedderDataArray> EmbedderDataFor(Context* context,
    1250             :                                                        int index, bool can_grow,
    1251             :                                                        const char* location) {
    1252             :   i::Handle<i::Context> env = Utils::OpenHandle(context);
    1253             :   i::Isolate* isolate = env->GetIsolate();
    1254             :   bool ok =
    1255      228798 :       Utils::ApiCheck(env->IsNativeContext(),
    1256             :                       location,
    1257      228798 :                       "Not a native context") &&
    1258             :       Utils::ApiCheck(index >= 0, location, "Negative index");
    1259      114399 :   if (!ok) return i::Handle<i::EmbedderDataArray>();
    1260             :   // TODO(ishell): remove cast once embedder_data slot has a proper type.
    1261             :   i::Handle<i::EmbedderDataArray> data(
    1262      228798 :       i::EmbedderDataArray::cast(env->embedder_data()), isolate);
    1263      114399 :   if (index < data->length()) return data;
    1264      122260 :   if (!Utils::ApiCheck(can_grow && index < i::EmbedderDataArray::kMaxLength,
    1265             :                        location, "Index too large")) {
    1266           0 :     return i::Handle<i::EmbedderDataArray>();
    1267             :   }
    1268       61130 :   data = i::EmbedderDataArray::EnsureCapacity(isolate, data, index);
    1269      122260 :   env->set_embedder_data(*data);
    1270       61130 :   return data;
    1271             : }
    1272             : 
    1273          75 : uint32_t Context::GetNumberOfEmbedderDataFields() {
    1274             :   i::Handle<i::Context> context = Utils::OpenHandle(this);
    1275         150 :   CHECK(context->IsNativeContext());
    1276             :   // TODO(ishell): remove cast once embedder_data slot has a proper type.
    1277             :   return static_cast<uint32_t>(
    1278         150 :       i::EmbedderDataArray::cast(context->embedder_data())->length());
    1279             : }
    1280             : 
    1281           0 : v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
    1282             :   const char* location = "v8::Context::GetEmbedderData()";
    1283             :   i::Handle<i::EmbedderDataArray> data =
    1284           0 :       EmbedderDataFor(this, index, false, location);
    1285           0 :   if (data.is_null()) return Local<Value>();
    1286             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    1287             :   i::Handle<i::Object> result(i::EmbedderDataSlot(*data, index).load_tagged(),
    1288             :                               isolate);
    1289             :   return Utils::ToLocal(result);
    1290             : }
    1291             : 
    1292             : 
    1293          60 : void Context::SetEmbedderData(int index, v8::Local<Value> value) {
    1294             :   const char* location = "v8::Context::SetEmbedderData()";
    1295             :   i::Handle<i::EmbedderDataArray> data =
    1296          60 :       EmbedderDataFor(this, index, true, location);
    1297          60 :   if (data.is_null()) return;
    1298             :   i::Handle<i::Object> val = Utils::OpenHandle(*value);
    1299             :   i::EmbedderDataSlot::store_tagged(*data, index, *val);
    1300             :   DCHECK_EQ(*Utils::OpenHandle(*value),
    1301             :             *Utils::OpenHandle(*GetEmbedderData(index)));
    1302             : }
    1303             : 
    1304             : 
    1305           0 : void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
    1306             :   const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
    1307             :   i::Handle<i::EmbedderDataArray> data =
    1308           0 :       EmbedderDataFor(this, index, false, location);
    1309           0 :   if (data.is_null()) return nullptr;
    1310             :   void* result;
    1311             :   Utils::ApiCheck(i::EmbedderDataSlot(*data, index).ToAlignedPointer(&result),
    1312             :                   location, "Pointer is not aligned");
    1313           0 :   return result;
    1314             : }
    1315             : 
    1316             : 
    1317      114340 : void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
    1318             :   const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
    1319             :   i::Handle<i::EmbedderDataArray> data =
    1320      114340 :       EmbedderDataFor(this, index, true, location);
    1321             :   bool ok = i::EmbedderDataSlot(*data, index).store_aligned_pointer(value);
    1322             :   Utils::ApiCheck(ok, location, "Pointer is not aligned");
    1323             :   DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
    1324      114339 : }
    1325             : 
    1326             : 
    1327             : // --- T e m p l a t e ---
    1328             : 
    1329             : 
    1330     4543681 : static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
    1331             :   that->set_number_of_properties(0);
    1332     9087362 :   that->set_tag(i::Smi::FromInt(type));
    1333     4543683 : }
    1334             : 
    1335             : 
    1336     2135885 : void Template::Set(v8::Local<Name> name, v8::Local<Data> value,
    1337             :                    v8::PropertyAttribute attribute) {
    1338             :   auto templ = Utils::OpenHandle(this);
    1339             :   i::Isolate* isolate = templ->GetIsolate();
    1340             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1341             :   i::HandleScope scope(isolate);
    1342             :   auto value_obj = Utils::OpenHandle(*value);
    1343     2135885 :   CHECK(!value_obj->IsJSReceiver() || value_obj->IsTemplateInfo());
    1344     2135885 :   if (value_obj->IsObjectTemplateInfo()) {
    1345      215376 :     templ->set_serial_number(i::Smi::kZero);
    1346      215376 :     if (templ->IsFunctionTemplateInfo()) {
    1347           0 :       i::Handle<i::FunctionTemplateInfo>::cast(templ)->set_do_not_cache(true);
    1348             :     }
    1349             :   }
    1350             :   i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
    1351             :                                  value_obj,
    1352     2135885 :                                  static_cast<i::PropertyAttributes>(attribute));
    1353     2135885 : }
    1354             : 
    1355           0 : void Template::SetPrivate(v8::Local<Private> name, v8::Local<Data> value,
    1356             :                           v8::PropertyAttribute attribute) {
    1357             :   Set(Utils::ToLocal(Utils::OpenHandle(reinterpret_cast<Name*>(*name))), value,
    1358           0 :       attribute);
    1359           0 : }
    1360             : 
    1361         114 : void Template::SetAccessorProperty(
    1362             :     v8::Local<v8::Name> name,
    1363             :     v8::Local<FunctionTemplate> getter,
    1364             :     v8::Local<FunctionTemplate> setter,
    1365             :     v8::PropertyAttribute attribute,
    1366             :     v8::AccessControl access_control) {
    1367             :   // TODO(verwaest): Remove |access_control|.
    1368             :   DCHECK_EQ(v8::DEFAULT, access_control);
    1369             :   auto templ = Utils::OpenHandle(this);
    1370             :   auto isolate = templ->GetIsolate();
    1371             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1372             :   DCHECK(!name.IsEmpty());
    1373             :   DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
    1374             :   i::HandleScope scope(isolate);
    1375             :   i::ApiNatives::AddAccessorProperty(
    1376             :       isolate, templ, Utils::OpenHandle(*name),
    1377             :       Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true),
    1378         114 :       static_cast<i::PropertyAttributes>(attribute));
    1379         114 : }
    1380             : 
    1381             : 
    1382             : // --- F u n c t i o n   T e m p l a t e ---
    1383     3697083 : static void InitializeFunctionTemplate(
    1384             :     i::Handle<i::FunctionTemplateInfo> info) {
    1385     3697083 :   InitializeTemplate(info, Consts::FUNCTION_TEMPLATE);
    1386             :   info->set_flag(0);
    1387     3697084 : }
    1388             : 
    1389             : static Local<ObjectTemplate> ObjectTemplateNew(
    1390             :     i::Isolate* isolate, v8::Local<FunctionTemplate> constructor,
    1391             :     bool do_not_cache);
    1392             : 
    1393      159952 : Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
    1394             :   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
    1395             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    1396             :   i::Handle<i::Object> result(Utils::OpenHandle(this)->GetPrototypeTemplate(),
    1397             :                               i_isolate);
    1398      159952 :   if (result->IsUndefined(i_isolate)) {
    1399             :     // Do not cache prototype objects.
    1400             :     result = Utils::OpenHandle(
    1401      106980 :         *ObjectTemplateNew(i_isolate, Local<FunctionTemplate>(), true));
    1402             :     i::FunctionTemplateInfo::SetPrototypeTemplate(
    1403       53490 :         i_isolate, Utils::OpenHandle(this), result);
    1404             :   }
    1405      159952 :   return ToApiHandle<ObjectTemplate>(result);
    1406             : }
    1407             : 
    1408           5 : void FunctionTemplate::SetPrototypeProviderTemplate(
    1409             :     Local<FunctionTemplate> prototype_provider) {
    1410             :   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
    1411             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    1412             :   i::Handle<i::Object> result = Utils::OpenHandle(*prototype_provider);
    1413             :   auto info = Utils::OpenHandle(this);
    1414           5 :   CHECK(info->GetPrototypeTemplate()->IsUndefined(i_isolate));
    1415           5 :   CHECK(info->GetParentTemplate()->IsUndefined(i_isolate));
    1416             :   i::FunctionTemplateInfo::SetPrototypeProviderTemplate(i_isolate, info,
    1417           5 :                                                         result);
    1418           5 : }
    1419             : 
    1420     5412782 : static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info,
    1421             :                                   const char* func) {
    1422    10825572 :   Utils::ApiCheck(!info->instantiated(), func,
    1423             :                   "FunctionTemplate already instantiated");
    1424     5412790 : }
    1425             : 
    1426             : 
    1427         239 : void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) {
    1428             :   auto info = Utils::OpenHandle(this);
    1429         239 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit");
    1430             :   i::Isolate* i_isolate = info->GetIsolate();
    1431             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    1432         239 :   CHECK(info->GetPrototypeProviderTemplate()->IsUndefined(i_isolate));
    1433         239 :   i::FunctionTemplateInfo::SetParentTemplate(i_isolate, info,
    1434         239 :                                              Utils::OpenHandle(*value));
    1435         239 : }
    1436             : 
    1437     3697084 : static Local<FunctionTemplate> FunctionTemplateNew(
    1438             :     i::Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
    1439             :     v8::Local<Signature> signature, int length, bool do_not_cache,
    1440             :     v8::Local<Private> cached_property_name = v8::Local<Private>(),
    1441             :     SideEffectType side_effect_type = SideEffectType::kHasSideEffect) {
    1442             :   i::Handle<i::Struct> struct_obj = isolate->factory()->NewStruct(
    1443     3697084 :       i::FUNCTION_TEMPLATE_INFO_TYPE, i::AllocationType::kOld);
    1444             :   i::Handle<i::FunctionTemplateInfo> obj =
    1445             :       i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
    1446     3697090 :   InitializeFunctionTemplate(obj);
    1447     7394170 :   obj->set_do_not_cache(do_not_cache);
    1448             :   int next_serial_number = i::FunctionTemplateInfo::kInvalidSerialNumber;
    1449     3697086 :   if (!do_not_cache) {
    1450             :     next_serial_number = isolate->heap()->GetNextTemplateSerialNumber();
    1451             :   }
    1452     7394172 :   obj->set_serial_number(i::Smi::FromInt(next_serial_number));
    1453     3697086 :   if (callback != nullptr) {
    1454     3582318 :     Utils::ToLocal(obj)->SetCallHandler(callback, data, side_effect_type);
    1455             :   }
    1456             :   obj->set_length(length);
    1457     3697092 :   obj->set_undetectable(false);
    1458     3697092 :   obj->set_needs_access_check(false);
    1459     3697095 :   obj->set_accept_any_receiver(true);
    1460     3697095 :   if (!signature.IsEmpty()) {
    1461      319494 :     obj->set_signature(*Utils::OpenHandle(*signature));
    1462             :   }
    1463    14788346 :   obj->set_cached_property_name(
    1464             :       cached_property_name.IsEmpty()
    1465             :           ? i::ReadOnlyRoots(isolate).the_hole_value()
    1466     3697095 :           : *Utils::OpenHandle(*cached_property_name));
    1467     3697091 :   return Utils::ToLocal(obj);
    1468             : }
    1469             : 
    1470     3691643 : Local<FunctionTemplate> FunctionTemplate::New(
    1471             :     Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
    1472             :     v8::Local<Signature> signature, int length, ConstructorBehavior behavior,
    1473             :     SideEffectType side_effect_type) {
    1474             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    1475             :   // Changes to the environment cannot be captured in the snapshot. Expect no
    1476             :   // function templates when the isolate is created for serialization.
    1477     3691643 :   LOG_API(i_isolate, FunctionTemplate, New);
    1478             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    1479             :   auto templ = FunctionTemplateNew(i_isolate, callback, data, signature, length,
    1480     3691645 :                                    false, Local<Private>(), side_effect_type);
    1481     3691657 :   if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype();
    1482     7383314 :   return templ;
    1483             : }
    1484             : 
    1485          10 : MaybeLocal<FunctionTemplate> FunctionTemplate::FromSnapshot(Isolate* isolate,
    1486             :                                                             size_t index) {
    1487             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    1488             :   i::FixedArray serialized_objects = i_isolate->heap()->serialized_objects();
    1489          10 :   int int_index = static_cast<int>(index);
    1490          10 :   if (int_index < serialized_objects->length()) {
    1491             :     i::Object info = serialized_objects->get(int_index);
    1492           5 :     if (info->IsFunctionTemplateInfo()) {
    1493             :       return Utils::ToLocal(i::Handle<i::FunctionTemplateInfo>(
    1494           5 :           i::FunctionTemplateInfo::cast(info), i_isolate));
    1495             :     }
    1496             :   }
    1497           5 :   return Local<FunctionTemplate>();
    1498             : }
    1499             : 
    1500          30 : Local<FunctionTemplate> FunctionTemplate::NewWithCache(
    1501             :     Isolate* isolate, FunctionCallback callback, Local<Private> cache_property,
    1502             :     Local<Value> data, Local<Signature> signature, int length,
    1503             :     SideEffectType side_effect_type) {
    1504             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    1505          30 :   LOG_API(i_isolate, FunctionTemplate, NewWithCache);
    1506             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    1507             :   return FunctionTemplateNew(i_isolate, callback, data, signature, length,
    1508          60 :                              false, cache_property, side_effect_type);
    1509             : }
    1510             : 
    1511       53296 : Local<Signature> Signature::New(Isolate* isolate,
    1512             :                                 Local<FunctionTemplate> receiver) {
    1513       53296 :   return Utils::SignatureToLocal(Utils::OpenHandle(*receiver));
    1514             : }
    1515             : 
    1516             : 
    1517          23 : Local<AccessorSignature> AccessorSignature::New(
    1518             :     Isolate* isolate, Local<FunctionTemplate> receiver) {
    1519          23 :   return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
    1520             : }
    1521             : 
    1522             : #define SET_FIELD_WRAPPED(isolate, obj, setter, cdata)        \
    1523             :   do {                                                        \
    1524             :     i::Handle<i::Object> foreign = FromCData(isolate, cdata); \
    1525             :     (obj)->setter(*foreign);                                  \
    1526             :   } while (false)
    1527             : 
    1528     3582348 : void FunctionTemplate::SetCallHandler(FunctionCallback callback,
    1529             :                                       v8::Local<Value> data,
    1530             :                                       SideEffectType side_effect_type) {
    1531             :   auto info = Utils::OpenHandle(this);
    1532     3582348 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler");
    1533             :   i::Isolate* isolate = info->GetIsolate();
    1534             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1535             :   i::HandleScope scope(isolate);
    1536             :   i::Handle<i::CallHandlerInfo> obj = isolate->factory()->NewCallHandlerInfo(
    1537     3582352 :       side_effect_type == SideEffectType::kHasNoSideEffect);
    1538     7164690 :   SET_FIELD_WRAPPED(isolate, obj, set_callback, callback);
    1539     7164712 :   SET_FIELD_WRAPPED(isolate, obj, set_js_callback, obj->redirected_callback());
    1540     3582365 :   if (data.IsEmpty()) {
    1541             :     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    1542             :   }
    1543     3582365 :   obj->set_data(*Utils::OpenHandle(*data));
    1544     7164728 :   info->set_call_code(*obj);
    1545     3582358 : }
    1546             : 
    1547             : 
    1548             : namespace {
    1549             : 
    1550             : template <typename Getter, typename Setter>
    1551       62059 : i::Handle<i::AccessorInfo> MakeAccessorInfo(
    1552             :     i::Isolate* isolate, v8::Local<Name> name, Getter getter, Setter setter,
    1553             :     v8::Local<Value> data, v8::AccessControl settings,
    1554             :     v8::Local<AccessorSignature> signature, bool is_special_data_property,
    1555             :     bool replace_on_access) {
    1556       62059 :   i::Handle<i::AccessorInfo> obj = isolate->factory()->NewAccessorInfo();
    1557      124118 :   SET_FIELD_WRAPPED(isolate, obj, set_getter, getter);
    1558             :   DCHECK_IMPLIES(replace_on_access,
    1559             :                  is_special_data_property && setter == nullptr);
    1560       62059 :   if (is_special_data_property && setter == nullptr) {
    1561             :     setter = reinterpret_cast<Setter>(&i::Accessors::ReconfigureToDataProperty);
    1562             :   }
    1563      124118 :   SET_FIELD_WRAPPED(isolate, obj, set_setter, setter);
    1564       62059 :   i::Address redirected = obj->redirected_getter();
    1565       62059 :   if (redirected != i::kNullAddress) {
    1566      124074 :     SET_FIELD_WRAPPED(isolate, obj, set_js_getter, redirected);
    1567             :   }
    1568       62059 :   if (data.IsEmpty()) {
    1569             :     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    1570             :   }
    1571       62059 :   obj->set_data(*Utils::OpenHandle(*data));
    1572      124118 :   obj->set_is_special_data_property(is_special_data_property);
    1573      124118 :   obj->set_replace_on_access(replace_on_access);
    1574             :   i::Handle<i::Name> accessor_name = Utils::OpenHandle(*name);
    1575       62059 :   if (!accessor_name->IsUniqueName()) {
    1576       53975 :     accessor_name = isolate->factory()->InternalizeString(
    1577             :         i::Handle<i::String>::cast(accessor_name));
    1578             :   }
    1579       62059 :   obj->set_name(*accessor_name);
    1580       62096 :   if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
    1581       62075 :   if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
    1582       62059 :   obj->set_initial_property_attributes(i::NONE);
    1583       62059 :   if (!signature.IsEmpty()) {
    1584          36 :     obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
    1585             :   }
    1586       62059 :   return obj;
    1587             : }
    1588             : 
    1589             : }  // namespace
    1590             : 
    1591       60756 : Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
    1592             :   i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
    1593       60756 :   if (!Utils::ApiCheck(!handle.is_null(),
    1594             :                        "v8::FunctionTemplate::InstanceTemplate()",
    1595             :                        "Reading from empty handle")) {
    1596           0 :     return Local<ObjectTemplate>();
    1597             :   }
    1598             :   i::Isolate* isolate = handle->GetIsolate();
    1599             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1600       60756 :   if (handle->GetInstanceTemplate()->IsUndefined(isolate)) {
    1601             :     Local<ObjectTemplate> templ =
    1602             :         ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
    1603       54364 :     i::FunctionTemplateInfo::SetInstanceTemplate(isolate, handle,
    1604       54364 :                                                  Utils::OpenHandle(*templ));
    1605             :   }
    1606             :   i::Handle<i::ObjectTemplateInfo> result(
    1607             :       i::ObjectTemplateInfo::cast(handle->GetInstanceTemplate()), isolate);
    1608             :   return Utils::ToLocal(result);
    1609             : }
    1610             : 
    1611             : 
    1612          12 : void FunctionTemplate::SetLength(int length) {
    1613             :   auto info = Utils::OpenHandle(this);
    1614          12 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength");
    1615             :   auto isolate = info->GetIsolate();
    1616             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1617             :   info->set_length(length);
    1618          12 : }
    1619             : 
    1620             : 
    1621       53473 : void FunctionTemplate::SetClassName(Local<String> name) {
    1622             :   auto info = Utils::OpenHandle(this);
    1623       53473 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName");
    1624             :   auto isolate = info->GetIsolate();
    1625             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1626      106946 :   info->set_class_name(*Utils::OpenHandle(*name));
    1627       53473 : }
    1628             : 
    1629             : 
    1630           7 : void FunctionTemplate::SetAcceptAnyReceiver(bool value) {
    1631             :   auto info = Utils::OpenHandle(this);
    1632           7 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
    1633             :   auto isolate = info->GetIsolate();
    1634             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1635          14 :   info->set_accept_any_receiver(value);
    1636           7 : }
    1637             : 
    1638             : 
    1639           0 : void FunctionTemplate::SetHiddenPrototype(bool value) {
    1640             :   auto info = Utils::OpenHandle(this);
    1641           0 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype");
    1642             :   auto isolate = info->GetIsolate();
    1643             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1644           0 :   info->set_hidden_prototype(value);
    1645           0 : }
    1646             : 
    1647             : 
    1648     1770152 : void FunctionTemplate::ReadOnlyPrototype() {
    1649             :   auto info = Utils::OpenHandle(this);
    1650     1770152 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype");
    1651             :   auto isolate = info->GetIsolate();
    1652             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1653     1770154 :   info->set_read_only_prototype(true);
    1654     1770156 : }
    1655             : 
    1656             : 
    1657        4892 : void FunctionTemplate::RemovePrototype() {
    1658             :   auto info = Utils::OpenHandle(this);
    1659        4892 :   EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype");
    1660             :   auto isolate = info->GetIsolate();
    1661             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1662        4892 :   info->set_remove_prototype(true);
    1663        4892 : }
    1664             : 
    1665             : 
    1666             : // --- O b j e c t T e m p l a t e ---
    1667             : 
    1668             : 
    1669      682422 : Local<ObjectTemplate> ObjectTemplate::New(
    1670             :     Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
    1671      682424 :   return New(reinterpret_cast<i::Isolate*>(isolate), constructor);
    1672             : }
    1673             : 
    1674             : 
    1675      846605 : static Local<ObjectTemplate> ObjectTemplateNew(
    1676             :     i::Isolate* isolate, v8::Local<FunctionTemplate> constructor,
    1677             :     bool do_not_cache) {
    1678      846605 :   LOG_API(isolate, ObjectTemplate, New);
    1679             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1680             :   i::Handle<i::Struct> struct_obj = isolate->factory()->NewStruct(
    1681      846605 :       i::OBJECT_TEMPLATE_INFO_TYPE, i::AllocationType::kOld);
    1682             :   i::Handle<i::ObjectTemplateInfo> obj =
    1683             :       i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
    1684      846606 :   InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
    1685             :   int next_serial_number = 0;
    1686      846607 :   if (!do_not_cache) {
    1687             :     next_serial_number = isolate->heap()->GetNextTemplateSerialNumber();
    1688             :   }
    1689     1693214 :   obj->set_serial_number(i::Smi::FromInt(next_serial_number));
    1690      846607 :   if (!constructor.IsEmpty())
    1691      109452 :     obj->set_constructor(*Utils::OpenHandle(*constructor));
    1692      846607 :   obj->set_data(i::Smi::kZero);
    1693      846608 :   return Utils::ToLocal(obj);
    1694             : }
    1695             : 
    1696           0 : Local<ObjectTemplate> ObjectTemplate::New(
    1697             :     i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
    1698      793116 :   return ObjectTemplateNew(isolate, constructor, false);
    1699             : }
    1700             : 
    1701          10 : MaybeLocal<ObjectTemplate> ObjectTemplate::FromSnapshot(Isolate* isolate,
    1702             :                                                         size_t index) {
    1703             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    1704             :   i::FixedArray serialized_objects = i_isolate->heap()->serialized_objects();
    1705          10 :   int int_index = static_cast<int>(index);
    1706          10 :   if (int_index < serialized_objects->length()) {
    1707             :     i::Object info = serialized_objects->get(int_index);
    1708           5 :     if (info->IsObjectTemplateInfo()) {
    1709             :       return Utils::ToLocal(i::Handle<i::ObjectTemplateInfo>(
    1710           5 :           i::ObjectTemplateInfo::cast(info), i_isolate));
    1711             :     }
    1712             :   }
    1713           5 :   return Local<ObjectTemplate>();
    1714             : }
    1715             : 
    1716             : // Ensure that the object template has a constructor.  If no
    1717             : // constructor is available we create one.
    1718      167958 : static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
    1719             :     i::Isolate* isolate,
    1720             :     ObjectTemplate* object_template) {
    1721             :   i::Object obj = Utils::OpenHandle(object_template)->constructor();
    1722      167958 :   if (!obj->IsUndefined(isolate)) {
    1723             :     i::FunctionTemplateInfo info = i::FunctionTemplateInfo::cast(obj);
    1724       54678 :     return i::Handle<i::FunctionTemplateInfo>(info, isolate);
    1725             :   }
    1726             :   Local<FunctionTemplate> templ =
    1727      113280 :       FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
    1728             :   i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
    1729      113280 :   i::FunctionTemplateInfo::SetInstanceTemplate(
    1730      113280 :       isolate, constructor, Utils::OpenHandle(object_template));
    1731      226560 :   Utils::OpenHandle(object_template)->set_constructor(*constructor);
    1732      113280 :   return constructor;
    1733             : }
    1734             : 
    1735             : template <typename Getter, typename Setter, typename Data, typename Template>
    1736       54149 : static void TemplateSetAccessor(
    1737             :     Template* template_obj, v8::Local<Name> name, Getter getter, Setter setter,
    1738             :     Data data, AccessControl settings, PropertyAttribute attribute,
    1739             :     v8::Local<AccessorSignature> signature, bool is_special_data_property,
    1740             :     bool replace_on_access, SideEffectType getter_side_effect_type,
    1741             :     SideEffectType setter_side_effect_type) {
    1742             :   auto info = Utils::OpenHandle(template_obj);
    1743             :   auto isolate = info->GetIsolate();
    1744             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1745             :   i::HandleScope scope(isolate);
    1746             :   i::Handle<i::AccessorInfo> accessor_info =
    1747       54149 :       MakeAccessorInfo(isolate, name, getter, setter, data, settings, signature,
    1748       54149 :                        is_special_data_property, replace_on_access);
    1749       54149 :   accessor_info->set_initial_property_attributes(
    1750             :       static_cast<i::PropertyAttributes>(attribute));
    1751       54149 :   accessor_info->set_getter_side_effect_type(getter_side_effect_type);
    1752       54149 :   accessor_info->set_setter_side_effect_type(setter_side_effect_type);
    1753       54149 :   i::ApiNatives::AddNativeDataProperty(isolate, info, accessor_info);
    1754       54149 : }
    1755             : 
    1756         179 : void Template::SetNativeDataProperty(
    1757             :     v8::Local<String> name, AccessorGetterCallback getter,
    1758             :     AccessorSetterCallback setter, v8::Local<Value> data,
    1759             :     PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
    1760             :     AccessControl settings, SideEffectType getter_side_effect_type,
    1761             :     SideEffectType setter_side_effect_type) {
    1762         179 :   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
    1763             :                       signature, true, false, getter_side_effect_type,
    1764         179 :                       setter_side_effect_type);
    1765         179 : }
    1766             : 
    1767          10 : void Template::SetNativeDataProperty(
    1768             :     v8::Local<Name> name, AccessorNameGetterCallback getter,
    1769             :     AccessorNameSetterCallback setter, v8::Local<Value> data,
    1770             :     PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
    1771             :     AccessControl settings, SideEffectType getter_side_effect_type,
    1772             :     SideEffectType setter_side_effect_type) {
    1773             :   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
    1774             :                       signature, true, false, getter_side_effect_type,
    1775          10 :                       setter_side_effect_type);
    1776          10 : }
    1777             : 
    1778          10 : void Template::SetLazyDataProperty(v8::Local<Name> name,
    1779             :                                    AccessorNameGetterCallback getter,
    1780             :                                    v8::Local<Value> data,
    1781             :                                    PropertyAttribute attribute,
    1782             :                                    SideEffectType getter_side_effect_type,
    1783             :                                    SideEffectType setter_side_effect_type) {
    1784          10 :   TemplateSetAccessor(this, name, getter,
    1785             :                       static_cast<AccessorNameSetterCallback>(nullptr), data,
    1786             :                       DEFAULT, attribute, Local<AccessorSignature>(), true,
    1787          10 :                       true, getter_side_effect_type, setter_side_effect_type);
    1788          10 : }
    1789             : 
    1790          55 : void Template::SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
    1791             :                                         PropertyAttribute attribute) {
    1792             :   auto templ = Utils::OpenHandle(this);
    1793             :   i::Isolate* isolate = templ->GetIsolate();
    1794             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1795             :   i::HandleScope scope(isolate);
    1796             :   i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
    1797             :                                  intrinsic,
    1798          55 :                                  static_cast<i::PropertyAttributes>(attribute));
    1799          55 : }
    1800             : 
    1801       53856 : void ObjectTemplate::SetAccessor(v8::Local<String> name,
    1802             :                                  AccessorGetterCallback getter,
    1803             :                                  AccessorSetterCallback setter,
    1804             :                                  v8::Local<Value> data, AccessControl settings,
    1805             :                                  PropertyAttribute attribute,
    1806             :                                  v8::Local<AccessorSignature> signature,
    1807             :                                  SideEffectType getter_side_effect_type,
    1808             :                                  SideEffectType setter_side_effect_type) {
    1809      107712 :   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
    1810             :                       signature, i::FLAG_disable_old_api_accessors, false,
    1811       53856 :                       getter_side_effect_type, setter_side_effect_type);
    1812       53856 : }
    1813             : 
    1814          94 : void ObjectTemplate::SetAccessor(v8::Local<Name> name,
    1815             :                                  AccessorNameGetterCallback getter,
    1816             :                                  AccessorNameSetterCallback setter,
    1817             :                                  v8::Local<Value> data, AccessControl settings,
    1818             :                                  PropertyAttribute attribute,
    1819             :                                  v8::Local<AccessorSignature> signature,
    1820             :                                  SideEffectType getter_side_effect_type,
    1821             :                                  SideEffectType setter_side_effect_type) {
    1822          94 :   TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
    1823             :                       signature, i::FLAG_disable_old_api_accessors, false,
    1824          94 :                       getter_side_effect_type, setter_side_effect_type);
    1825          94 : }
    1826             : 
    1827             : template <typename Getter, typename Setter, typename Query, typename Descriptor,
    1828             :           typename Deleter, typename Enumerator, typename Definer>
    1829        1225 : static i::Handle<i::InterceptorInfo> CreateInterceptorInfo(
    1830             :     i::Isolate* isolate, Getter getter, Setter setter, Query query,
    1831             :     Descriptor descriptor, Deleter remover, Enumerator enumerator,
    1832             :     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
    1833        1225 :   auto obj = i::Handle<i::InterceptorInfo>::cast(isolate->factory()->NewStruct(
    1834             :       i::INTERCEPTOR_INFO_TYPE, i::AllocationType::kOld));
    1835             :   obj->set_flags(0);
    1836             : 
    1837        2226 :   if (getter != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_getter, getter);
    1838        1652 :   if (setter != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_setter, setter);
    1839        1485 :   if (query != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_query, query);
    1840        1225 :   if (descriptor != nullptr)
    1841          60 :     SET_FIELD_WRAPPED(isolate, obj, set_descriptor, descriptor);
    1842        1309 :   if (remover != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_deleter, remover);
    1843        1225 :   if (enumerator != nullptr)
    1844         322 :     SET_FIELD_WRAPPED(isolate, obj, set_enumerator, enumerator);
    1845        1315 :   if (definer != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_definer, definer);
    1846        2450 :   obj->set_can_intercept_symbols(
    1847             :       !(static_cast<int>(flags) &
    1848             :         static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings)));
    1849        2450 :   obj->set_all_can_read(static_cast<int>(flags) &
    1850             :                         static_cast<int>(PropertyHandlerFlags::kAllCanRead));
    1851        2450 :   obj->set_non_masking(static_cast<int>(flags) &
    1852             :                        static_cast<int>(PropertyHandlerFlags::kNonMasking));
    1853        2450 :   obj->set_has_no_side_effect(
    1854             :       static_cast<int>(flags) &
    1855             :       static_cast<int>(PropertyHandlerFlags::kHasNoSideEffect));
    1856             : 
    1857        1225 :   if (data.IsEmpty()) {
    1858             :     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    1859             :   }
    1860        1225 :   obj->set_data(*Utils::OpenHandle(*data));
    1861        1225 :   return obj;
    1862             : }
    1863             : 
    1864             : template <typename Getter, typename Setter, typename Query, typename Descriptor,
    1865             :           typename Deleter, typename Enumerator, typename Definer>
    1866         977 : static i::Handle<i::InterceptorInfo> CreateNamedInterceptorInfo(
    1867             :     i::Isolate* isolate, Getter getter, Setter setter, Query query,
    1868             :     Descriptor descriptor, Deleter remover, Enumerator enumerator,
    1869             :     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
    1870             :   auto interceptor =
    1871             :       CreateInterceptorInfo(isolate, getter, setter, query, descriptor, remover,
    1872         977 :                             enumerator, definer, data, flags);
    1873         977 :   interceptor->set_is_named(true);
    1874         977 :   return interceptor;
    1875             : }
    1876             : 
    1877             : template <typename Getter, typename Setter, typename Query, typename Descriptor,
    1878             :           typename Deleter, typename Enumerator, typename Definer>
    1879         248 : static i::Handle<i::InterceptorInfo> CreateIndexedInterceptorInfo(
    1880             :     i::Isolate* isolate, Getter getter, Setter setter, Query query,
    1881             :     Descriptor descriptor, Deleter remover, Enumerator enumerator,
    1882             :     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
    1883             :   auto interceptor =
    1884             :       CreateInterceptorInfo(isolate, getter, setter, query, descriptor, remover,
    1885         248 :                             enumerator, definer, data, flags);
    1886         248 :   interceptor->set_is_named(false);
    1887         248 :   return interceptor;
    1888             : }
    1889             : 
    1890             : template <typename Getter, typename Setter, typename Query, typename Descriptor,
    1891             :           typename Deleter, typename Enumerator, typename Definer>
    1892         946 : static void ObjectTemplateSetNamedPropertyHandler(
    1893             :     ObjectTemplate* templ, Getter getter, Setter setter, Query query,
    1894             :     Descriptor descriptor, Deleter remover, Enumerator enumerator,
    1895             :     Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
    1896             :   i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate();
    1897             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1898             :   i::HandleScope scope(isolate);
    1899         946 :   auto cons = EnsureConstructor(isolate, templ);
    1900         946 :   EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler");
    1901             :   auto obj =
    1902             :       CreateNamedInterceptorInfo(isolate, getter, setter, query, descriptor,
    1903         946 :                                  remover, enumerator, definer, data, flags);
    1904         946 :   i::FunctionTemplateInfo::SetNamedPropertyHandler(isolate, cons, obj);
    1905         946 : }
    1906             : 
    1907         946 : void ObjectTemplate::SetHandler(
    1908             :     const NamedPropertyHandlerConfiguration& config) {
    1909             :   ObjectTemplateSetNamedPropertyHandler(
    1910         946 :       this, config.getter, config.setter, config.query, config.descriptor,
    1911         946 :       config.deleter, config.enumerator, config.definer, config.data,
    1912        1892 :       config.flags);
    1913         946 : }
    1914             : 
    1915             : 
    1916         149 : void ObjectTemplate::MarkAsUndetectable() {
    1917             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    1918             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1919             :   i::HandleScope scope(isolate);
    1920         149 :   auto cons = EnsureConstructor(isolate, this);
    1921         149 :   EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable");
    1922         149 :   cons->set_undetectable(true);
    1923         149 : }
    1924             : 
    1925             : 
    1926         134 : void ObjectTemplate::SetAccessCheckCallback(AccessCheckCallback callback,
    1927             :                                             Local<Value> data) {
    1928             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    1929             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1930             :   i::HandleScope scope(isolate);
    1931         134 :   auto cons = EnsureConstructor(isolate, this);
    1932         134 :   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallback");
    1933             : 
    1934             :   i::Handle<i::Struct> struct_info = isolate->factory()->NewStruct(
    1935         134 :       i::ACCESS_CHECK_INFO_TYPE, i::AllocationType::kOld);
    1936             :   i::Handle<i::AccessCheckInfo> info =
    1937             :       i::Handle<i::AccessCheckInfo>::cast(struct_info);
    1938             : 
    1939         268 :   SET_FIELD_WRAPPED(isolate, info, set_callback, callback);
    1940         134 :   info->set_named_interceptor(i::Object());
    1941         134 :   info->set_indexed_interceptor(i::Object());
    1942             : 
    1943         134 :   if (data.IsEmpty()) {
    1944             :     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    1945             :   }
    1946         134 :   info->set_data(*Utils::OpenHandle(*data));
    1947             : 
    1948         134 :   i::FunctionTemplateInfo::SetAccessCheckInfo(isolate, cons, info);
    1949         134 :   cons->set_needs_access_check(true);
    1950         134 : }
    1951             : 
    1952          31 : void ObjectTemplate::SetAccessCheckCallbackAndHandler(
    1953             :     AccessCheckCallback callback,
    1954             :     const NamedPropertyHandlerConfiguration& named_handler,
    1955             :     const IndexedPropertyHandlerConfiguration& indexed_handler,
    1956             :     Local<Value> data) {
    1957             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    1958             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1959             :   i::HandleScope scope(isolate);
    1960          31 :   auto cons = EnsureConstructor(isolate, this);
    1961             :   EnsureNotInstantiated(
    1962          31 :       cons, "v8::ObjectTemplate::SetAccessCheckCallbackWithHandler");
    1963             : 
    1964             :   i::Handle<i::Struct> struct_info = isolate->factory()->NewStruct(
    1965          31 :       i::ACCESS_CHECK_INFO_TYPE, i::AllocationType::kOld);
    1966             :   i::Handle<i::AccessCheckInfo> info =
    1967             :       i::Handle<i::AccessCheckInfo>::cast(struct_info);
    1968             : 
    1969          62 :   SET_FIELD_WRAPPED(isolate, info, set_callback, callback);
    1970             :   auto named_interceptor = CreateNamedInterceptorInfo(
    1971          31 :       isolate, named_handler.getter, named_handler.setter, named_handler.query,
    1972          31 :       named_handler.descriptor, named_handler.deleter, named_handler.enumerator,
    1973          62 :       named_handler.definer, named_handler.data, named_handler.flags);
    1974          62 :   info->set_named_interceptor(*named_interceptor);
    1975             :   auto indexed_interceptor = CreateIndexedInterceptorInfo(
    1976          31 :       isolate, indexed_handler.getter, indexed_handler.setter,
    1977          31 :       indexed_handler.query, indexed_handler.descriptor,
    1978          31 :       indexed_handler.deleter, indexed_handler.enumerator,
    1979          62 :       indexed_handler.definer, indexed_handler.data, indexed_handler.flags);
    1980          62 :   info->set_indexed_interceptor(*indexed_interceptor);
    1981             : 
    1982          31 :   if (data.IsEmpty()) {
    1983             :     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    1984             :   }
    1985          31 :   info->set_data(*Utils::OpenHandle(*data));
    1986             : 
    1987          31 :   i::FunctionTemplateInfo::SetAccessCheckInfo(isolate, cons, info);
    1988          31 :   cons->set_needs_access_check(true);
    1989          31 : }
    1990             : 
    1991         217 : void ObjectTemplate::SetHandler(
    1992             :     const IndexedPropertyHandlerConfiguration& config) {
    1993             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    1994             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    1995             :   i::HandleScope scope(isolate);
    1996         217 :   auto cons = EnsureConstructor(isolate, this);
    1997         217 :   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler");
    1998             :   auto obj = CreateIndexedInterceptorInfo(
    1999         217 :       isolate, config.getter, config.setter, config.query, config.descriptor,
    2000         217 :       config.deleter, config.enumerator, config.definer, config.data,
    2001         434 :       config.flags);
    2002         217 :   i::FunctionTemplateInfo::SetIndexedPropertyHandler(isolate, cons, obj);
    2003         217 : }
    2004             : 
    2005         197 : void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
    2006             :                                               Local<Value> data) {
    2007             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2008             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2009             :   i::HandleScope scope(isolate);
    2010         197 :   auto cons = EnsureConstructor(isolate, this);
    2011         197 :   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
    2012         197 :   i::Handle<i::CallHandlerInfo> obj = isolate->factory()->NewCallHandlerInfo();
    2013         394 :   SET_FIELD_WRAPPED(isolate, obj, set_callback, callback);
    2014         394 :   SET_FIELD_WRAPPED(isolate, obj, set_js_callback, obj->redirected_callback());
    2015         197 :   if (data.IsEmpty()) {
    2016             :     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    2017             :   }
    2018         197 :   obj->set_data(*Utils::OpenHandle(*data));
    2019         197 :   i::FunctionTemplateInfo::SetInstanceCallHandler(isolate, cons, obj);
    2020         197 : }
    2021             : 
    2022       56303 : int ObjectTemplate::InternalFieldCount() {
    2023       56303 :   return Utils::OpenHandle(this)->embedder_field_count();
    2024             : }
    2025             : 
    2026      109907 : void ObjectTemplate::SetInternalFieldCount(int value) {
    2027             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2028             :   if (!Utils::ApiCheck(i::Smi::IsValid(value),
    2029             :                        "v8::ObjectTemplate::SetInternalFieldCount()",
    2030             :                        "Invalid embedder field count")) {
    2031             :     return;
    2032             :   }
    2033             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2034      109907 :   if (value > 0) {
    2035             :     // The embedder field count is set by the constructor function's
    2036             :     // construct code, so we ensure that there is a constructor
    2037             :     // function to do the setting.
    2038       53598 :     EnsureConstructor(isolate, this);
    2039             :   }
    2040      109907 :   Utils::OpenHandle(this)->set_embedder_field_count(value);
    2041             : }
    2042             : 
    2043           0 : bool ObjectTemplate::IsImmutableProto() {
    2044           0 :   return Utils::OpenHandle(this)->immutable_proto();
    2045             : }
    2046             : 
    2047          18 : void ObjectTemplate::SetImmutableProto() {
    2048             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2049             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2050          18 :   Utils::OpenHandle(this)->set_immutable_proto(true);
    2051          18 : }
    2052             : 
    2053             : // --- S c r i p t s ---
    2054             : 
    2055             : 
    2056             : // Internally, UnboundScript is a SharedFunctionInfo, and Script is a
    2057             : // JSFunction.
    2058             : 
    2059         712 : ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
    2060             :                                        BufferPolicy buffer_policy_)
    2061             :     : data(data_),
    2062             :       length(length_),
    2063             :       rejected(false),
    2064         712 :       buffer_policy(buffer_policy_) {}
    2065             : 
    2066             : 
    2067        1424 : ScriptCompiler::CachedData::~CachedData() {
    2068         712 :   if (buffer_policy == BufferOwned) {
    2069         702 :     delete[] data;
    2070             :   }
    2071         712 : }
    2072             : 
    2073           0 : bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; }
    2074             : 
    2075           0 : void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); }
    2076             : 
    2077           0 : ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
    2078             :                                                Encoding encoding)
    2079           0 :     : StreamedSource(std::unique_ptr<ExternalSourceStream>(stream), encoding) {}
    2080             : 
    2081       13402 : ScriptCompiler::StreamedSource::StreamedSource(
    2082             :     std::unique_ptr<ExternalSourceStream> stream, Encoding encoding)
    2083       26804 :     : impl_(new i::ScriptStreamingData(std::move(stream), encoding)) {}
    2084             : 
    2085             : ScriptCompiler::StreamedSource::~StreamedSource() = default;
    2086             : 
    2087      271603 : Local<Script> UnboundScript::BindToCurrentContext() {
    2088             :   auto function_info =
    2089             :       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
    2090             :   i::Isolate* isolate = function_info->GetIsolate();
    2091             :   i::Handle<i::JSFunction> function =
    2092             :       isolate->factory()->NewFunctionFromSharedFunctionInfo(
    2093      543206 :           function_info, isolate->native_context());
    2094      271603 :   return ToApiHandle<Script>(function);
    2095             : }
    2096             : 
    2097         258 : int UnboundScript::GetId() {
    2098             :   auto function_info =
    2099             :       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
    2100             :   i::Isolate* isolate = function_info->GetIsolate();
    2101         258 :   LOG_API(isolate, UnboundScript, GetId);
    2102             :   i::HandleScope scope(isolate);
    2103             :   i::Handle<i::Script> script(i::Script::cast(function_info->script()),
    2104         516 :                               isolate);
    2105         258 :   return script->id();
    2106             : }
    2107             : 
    2108             : 
    2109           5 : int UnboundScript::GetLineNumber(int code_pos) {
    2110             :   i::Handle<i::SharedFunctionInfo> obj =
    2111             :       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
    2112             :   i::Isolate* isolate = obj->GetIsolate();
    2113           5 :   LOG_API(isolate, UnboundScript, GetLineNumber);
    2114          10 :   if (obj->script()->IsScript()) {
    2115          10 :     i::Handle<i::Script> script(i::Script::cast(obj->script()), isolate);
    2116           5 :     return i::Script::GetLineNumber(script, code_pos);
    2117             :   } else {
    2118             :     return -1;
    2119             :   }
    2120             : }
    2121             : 
    2122             : 
    2123           5 : Local<Value> UnboundScript::GetScriptName() {
    2124             :   i::Handle<i::SharedFunctionInfo> obj =
    2125             :       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
    2126             :   i::Isolate* isolate = obj->GetIsolate();
    2127           5 :   LOG_API(isolate, UnboundScript, GetName);
    2128          10 :   if (obj->script()->IsScript()) {
    2129          10 :     i::Object name = i::Script::cast(obj->script())->name();
    2130             :     return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
    2131             :   } else {
    2132           0 :     return Local<String>();
    2133             :   }
    2134             : }
    2135             : 
    2136             : 
    2137         155 : Local<Value> UnboundScript::GetSourceURL() {
    2138             :   i::Handle<i::SharedFunctionInfo> obj =
    2139             :       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
    2140             :   i::Isolate* isolate = obj->GetIsolate();
    2141         155 :   LOG_API(isolate, UnboundScript, GetSourceURL);
    2142         310 :   if (obj->script()->IsScript()) {
    2143         310 :     i::Object url = i::Script::cast(obj->script())->source_url();
    2144             :     return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
    2145             :   } else {
    2146           0 :     return Local<String>();
    2147             :   }
    2148             : }
    2149             : 
    2150             : 
    2151         155 : Local<Value> UnboundScript::GetSourceMappingURL() {
    2152             :   i::Handle<i::SharedFunctionInfo> obj =
    2153             :       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
    2154             :   i::Isolate* isolate = obj->GetIsolate();
    2155         155 :   LOG_API(isolate, UnboundScript, GetSourceMappingURL);
    2156         310 :   if (obj->script()->IsScript()) {
    2157         310 :     i::Object url = i::Script::cast(obj->script())->source_mapping_url();
    2158             :     return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
    2159             :   } else {
    2160           0 :     return Local<String>();
    2161             :   }
    2162             : }
    2163             : 
    2164             : 
    2165      269581 : MaybeLocal<Value> Script::Run(Local<Context> context) {
    2166             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    2167      539162 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
    2168      808743 :   ENTER_V8(isolate, context, Script, Run, MaybeLocal<Value>(),
    2169             :            InternalEscapableScope);
    2170             :   i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true);
    2171             :   i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
    2172             :   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
    2173             :   auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this));
    2174             : 
    2175      269581 :   i::Handle<i::Object> receiver = isolate->global_proxy();
    2176             :   Local<Value> result;
    2177      539162 :   has_pending_exception = !ToLocal<Value>(
    2178             :       i::Execution::Call(isolate, fun, receiver, 0, nullptr), &result);
    2179             : 
    2180      269581 :   RETURN_ON_FAILED_EXECUTION(Value);
    2181      260865 :   RETURN_ESCAPED(result);
    2182             : }
    2183             : 
    2184             : 
    2185         410 : Local<Value> ScriptOrModule::GetResourceName() {
    2186             :   i::Handle<i::Script> obj = Utils::OpenHandle(this);
    2187             :   i::Isolate* isolate = obj->GetIsolate();
    2188             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2189             :   i::Handle<i::Object> val(obj->name(), isolate);
    2190         410 :   return ToApiHandle<Value>(val);
    2191             : }
    2192             : 
    2193           5 : Local<PrimitiveArray> ScriptOrModule::GetHostDefinedOptions() {
    2194             :   i::Handle<i::Script> obj = Utils::OpenHandle(this);
    2195             :   i::Isolate* isolate = obj->GetIsolate();
    2196             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2197             :   i::Handle<i::FixedArray> val(obj->host_defined_options(), isolate);
    2198           5 :   return ToApiHandle<PrimitiveArray>(val);
    2199             : }
    2200             : 
    2201         835 : Local<UnboundScript> Script::GetUnboundScript() {
    2202             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    2203             :   i::SharedFunctionInfo sfi = i::JSFunction::cast(*obj)->shared();
    2204             :   i::Isolate* isolate = sfi->GetIsolate();
    2205         835 :   return ToApiHandle<UnboundScript>(i::handle(sfi, isolate));
    2206             : }
    2207             : 
    2208             : // static
    2209          11 : Local<PrimitiveArray> PrimitiveArray::New(Isolate* v8_isolate, int length) {
    2210             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    2211             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2212             :   Utils::ApiCheck(length >= 0, "v8::PrimitiveArray::New",
    2213             :                   "length must be equal or greater than zero");
    2214          11 :   i::Handle<i::FixedArray> array = isolate->factory()->NewFixedArray(length);
    2215          11 :   return ToApiHandle<PrimitiveArray>(array);
    2216             : }
    2217             : 
    2218           5 : int PrimitiveArray::Length() const {
    2219             :   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
    2220           5 :   return array->length();
    2221             : }
    2222             : 
    2223          31 : void PrimitiveArray::Set(Isolate* v8_isolate, int index,
    2224             :                          Local<Primitive> item) {
    2225             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    2226             :   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
    2227             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2228          62 :   Utils::ApiCheck(index >= 0 && index < array->length(),
    2229             :                   "v8::PrimitiveArray::Set",
    2230             :                   "index must be greater than or equal to 0 and less than the "
    2231             :                   "array length");
    2232             :   i::Handle<i::Object> i_item = Utils::OpenHandle(*item);
    2233          31 :   array->set(index, *i_item);
    2234          31 : }
    2235             : 
    2236         117 : Local<Primitive> PrimitiveArray::Get(Isolate* v8_isolate, int index) {
    2237             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    2238             :   i::Handle<i::FixedArray> array = Utils::OpenHandle(this);
    2239             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2240         234 :   Utils::ApiCheck(index >= 0 && index < array->length(),
    2241             :                   "v8::PrimitiveArray::Get",
    2242             :                   "index must be greater than or equal to 0 and less than the "
    2243             :                   "array length");
    2244             :   i::Handle<i::Object> i_item(array->get(index), isolate);
    2245         117 :   return ToApiHandle<Primitive>(i_item);
    2246             : }
    2247             : 
    2248        1036 : Module::Status Module::GetStatus() const {
    2249             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2250        1036 :   switch (self->status()) {
    2251             :     case i::Module::kUninstantiated:
    2252             :     case i::Module::kPreInstantiating:
    2253             :       return kUninstantiated;
    2254             :     case i::Module::kInstantiating:
    2255           0 :       return kInstantiating;
    2256             :     case i::Module::kInstantiated:
    2257         220 :       return kInstantiated;
    2258             :     case i::Module::kEvaluating:
    2259           0 :       return kEvaluating;
    2260             :     case i::Module::kEvaluated:
    2261         561 :       return kEvaluated;
    2262             :     case i::Module::kErrored:
    2263          20 :       return kErrored;
    2264             :   }
    2265           0 :   UNREACHABLE();
    2266             : }
    2267             : 
    2268          10 : Local<Value> Module::GetException() const {
    2269          10 :   Utils::ApiCheck(GetStatus() == kErrored, "v8::Module::GetException",
    2270             :                   "Module status must be kErrored");
    2271             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2272             :   i::Isolate* isolate = self->GetIsolate();
    2273          20 :   return ToApiHandle<Value>(i::handle(self->GetException(), isolate));
    2274             : }
    2275             : 
    2276        1387 : int Module::GetModuleRequestsLength() const {
    2277             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2278        2774 :   return self->info()->module_requests()->length();
    2279             : }
    2280             : 
    2281        1003 : Local<String> Module::GetModuleRequest(int i) const {
    2282        1003 :   CHECK_GE(i, 0);
    2283             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2284             :   i::Isolate* isolate = self->GetIsolate();
    2285        2006 :   i::Handle<i::FixedArray> module_requests(self->info()->module_requests(),
    2286             :                                            isolate);
    2287        1003 :   CHECK_LT(i, module_requests->length());
    2288        1003 :   return ToApiHandle<String>(i::handle(module_requests->get(i), isolate));
    2289             : }
    2290             : 
    2291          10 : Location Module::GetModuleRequestLocation(int i) const {
    2292          10 :   CHECK_GE(i, 0);
    2293             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2294             :   i::HandleScope scope(isolate);
    2295             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2296             :   i::Handle<i::FixedArray> module_request_positions(
    2297          20 :       self->info()->module_request_positions(), isolate);
    2298          10 :   CHECK_LT(i, module_request_positions->length());
    2299             :   int position = i::Smi::ToInt(module_request_positions->get(i));
    2300             :   i::Handle<i::Script> script(self->script(), isolate);
    2301             :   i::Script::PositionInfo info;
    2302          10 :   i::Script::GetPositionInfo(script, position, &info, i::Script::WITH_OFFSET);
    2303          20 :   return v8::Location(info.line, info.column);
    2304             : }
    2305             : 
    2306         226 : Local<Value> Module::GetModuleNamespace() {
    2307         226 :   Utils::ApiCheck(
    2308         226 :       GetStatus() >= kInstantiated, "v8::Module::GetModuleNamespace",
    2309             :       "v8::Module::GetModuleNamespace must be used on an instantiated module");
    2310             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2311             :   i::Handle<i::JSModuleNamespace> module_namespace =
    2312         226 :       i::Module::GetModuleNamespace(self->GetIsolate(), self);
    2313         226 :   return ToApiHandle<Value>(module_namespace);
    2314             : }
    2315             : 
    2316          20 : Local<UnboundModuleScript> Module::GetUnboundModuleScript() {
    2317          20 :   Utils::ApiCheck(
    2318          20 :       GetStatus() < kEvaluating, "v8::Module::GetUnboundScript",
    2319             :       "v8::Module::GetUnboundScript must be used on an unevaluated module");
    2320             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2321             :   return ToApiHandle<UnboundModuleScript>(i::Handle<i::SharedFunctionInfo>(
    2322          40 :       self->GetSharedFunctionInfo(), self->GetIsolate()));
    2323             : }
    2324             : 
    2325        4804 : int Module::GetIdentityHash() const { return Utils::OpenHandle(this)->hash(); }
    2326             : 
    2327        1187 : Maybe<bool> Module::InstantiateModule(Local<Context> context,
    2328             :                                       Module::ResolveCallback callback) {
    2329             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    2330        3561 :   ENTER_V8(isolate, context, Module, InstantiateModule, Nothing<bool>(),
    2331             :            i::HandleScope);
    2332        1187 :   has_pending_exception = !i::Module::Instantiate(
    2333             :       isolate, Utils::OpenHandle(this), context, callback);
    2334        1187 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    2335             :   return Just(true);
    2336             : }
    2337             : 
    2338        1225 : MaybeLocal<Value> Module::Evaluate(Local<Context> context) {
    2339             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    2340        2450 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
    2341        3675 :   ENTER_V8(isolate, context, Module, Evaluate, MaybeLocal<Value>(),
    2342             :            InternalEscapableScope);
    2343             :   i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true);
    2344             :   i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
    2345             :   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
    2346             : 
    2347             :   i::Handle<i::Module> self = Utils::OpenHandle(this);
    2348             :   // It's an API error to call Evaluate before Instantiate.
    2349        1225 :   CHECK_GE(self->status(), i::Module::kInstantiated);
    2350             : 
    2351             :   Local<Value> result;
    2352        1225 :   has_pending_exception = !ToLocal(i::Module::Evaluate(isolate, self), &result);
    2353        1225 :   RETURN_ON_FAILED_EXECUTION(Value);
    2354        1179 :   RETURN_ESCAPED(result);
    2355             : }
    2356             : 
    2357             : namespace {
    2358             : 
    2359      275455 : i::Compiler::ScriptDetails GetScriptDetails(
    2360             :     i::Isolate* isolate, Local<Value> resource_name,
    2361             :     Local<Integer> resource_line_offset, Local<Integer> resource_column_offset,
    2362             :     Local<Value> source_map_url, Local<PrimitiveArray> host_defined_options) {
    2363             :   i::Compiler::ScriptDetails script_details;
    2364      275455 :   if (!resource_name.IsEmpty()) {
    2365      142092 :     script_details.name_obj = Utils::OpenHandle(*(resource_name));
    2366             :   }
    2367      275455 :   if (!resource_line_offset.IsEmpty()) {
    2368             :     script_details.line_offset =
    2369        4761 :         static_cast<int>(resource_line_offset->Value());
    2370             :   }
    2371      275455 :   if (!resource_column_offset.IsEmpty()) {
    2372             :     script_details.column_offset =
    2373        4740 :         static_cast<int>(resource_column_offset->Value());
    2374             :   }
    2375      275455 :   script_details.host_defined_options = isolate->factory()->empty_fixed_array();
    2376      275455 :   if (!host_defined_options.IsEmpty()) {
    2377             :     script_details.host_defined_options =
    2378           6 :         Utils::OpenHandle(*(host_defined_options));
    2379             :   }
    2380      275455 :   if (!source_map_url.IsEmpty()) {
    2381         954 :     script_details.source_map_url = Utils::OpenHandle(*(source_map_url));
    2382             :   }
    2383      275455 :   return script_details;
    2384             : }
    2385             : 
    2386             : }  // namespace
    2387             : 
    2388      261984 : MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal(
    2389             :     Isolate* v8_isolate, Source* source, CompileOptions options,
    2390             :     NoCacheReason no_cache_reason) {
    2391             :   auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    2392      523968 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
    2393      785932 :   ENTER_V8_NO_SCRIPT(isolate, v8_isolate->GetCurrentContext(), ScriptCompiler,
    2394             :                      CompileUnbound, MaybeLocal<UnboundScript>(),
    2395             :                      InternalEscapableScope);
    2396             : 
    2397             :   i::ScriptData* script_data = nullptr;
    2398      261974 :   if (options == kConsumeCodeCache) {
    2399             :     DCHECK(source->cached_data);
    2400             :     // ScriptData takes care of pointer-aligning the data.
    2401             :     script_data = new i::ScriptData(source->cached_data->data,
    2402         164 :                                     source->cached_data->length);
    2403             :   }
    2404             : 
    2405      261974 :   i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
    2406             :   i::Handle<i::SharedFunctionInfo> result;
    2407      785922 :   TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileScript");
    2408             :   i::Compiler::ScriptDetails script_details = GetScriptDetails(
    2409             :       isolate, source->resource_name, source->resource_line_offset,
    2410             :       source->resource_column_offset, source->source_map_url,
    2411      261974 :       source->host_defined_options);
    2412             :   i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
    2413             :       i::Compiler::GetSharedFunctionInfoForScript(
    2414             :           isolate, str, script_details, source->resource_options, nullptr,
    2415      261974 :           script_data, options, no_cache_reason, i::NOT_NATIVES_CODE);
    2416      261974 :   if (options == kConsumeCodeCache) {
    2417         328 :     source->cached_data->rejected = script_data->rejected();
    2418             :   }
    2419      262138 :   delete script_data;
    2420             :   has_pending_exception = !maybe_function_info.ToHandle(&result);
    2421      261974 :   RETURN_ON_FAILED_EXECUTION(UnboundScript);
    2422      259845 :   RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
    2423             : }
    2424             : 
    2425        9222 : MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript(
    2426             :     Isolate* v8_isolate, Source* source, CompileOptions options,
    2427             :     NoCacheReason no_cache_reason) {
    2428             :   Utils::ApiCheck(
    2429             :       !source->GetResourceOptions().IsModule(),
    2430             :       "v8::ScriptCompiler::CompileUnboundScript",
    2431             :       "v8::ScriptCompiler::CompileModule must be used to compile modules");
    2432        9222 :   return CompileUnboundInternal(v8_isolate, source, options, no_cache_reason);
    2433             : }
    2434             : 
    2435      250747 : MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
    2436             :                                            Source* source,
    2437             :                                            CompileOptions options,
    2438             :                                            NoCacheReason no_cache_reason) {
    2439             :   Utils::ApiCheck(
    2440             :       !source->GetResourceOptions().IsModule(), "v8::ScriptCompiler::Compile",
    2441             :       "v8::ScriptCompiler::CompileModule must be used to compile modules");
    2442             :   auto isolate = context->GetIsolate();
    2443             :   auto maybe =
    2444      250747 :       CompileUnboundInternal(isolate, source, options, no_cache_reason);
    2445             :   Local<UnboundScript> result;
    2446      250747 :   if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
    2447             :   v8::Context::Scope scope(context);
    2448      248810 :   return result->BindToCurrentContext();
    2449             : }
    2450             : 
    2451        2015 : MaybeLocal<Module> ScriptCompiler::CompileModule(
    2452             :     Isolate* isolate, Source* source, CompileOptions options,
    2453             :     NoCacheReason no_cache_reason) {
    2454        2015 :   CHECK(options == kNoCompileOptions || options == kConsumeCodeCache);
    2455             : 
    2456             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    2457             : 
    2458             :   Utils::ApiCheck(source->GetResourceOptions().IsModule(),
    2459             :                   "v8::ScriptCompiler::CompileModule",
    2460             :                   "Invalid ScriptOrigin: is_module must be true");
    2461             :   auto maybe =
    2462        2015 :       CompileUnboundInternal(isolate, source, options, no_cache_reason);
    2463             :   Local<UnboundScript> unbound;
    2464        2015 :   if (!maybe.ToLocal(&unbound)) return MaybeLocal<Module>();
    2465             : 
    2466        1822 :   i::Handle<i::SharedFunctionInfo> shared = Utils::OpenHandle(*unbound);
    2467        1822 :   return ToApiHandle<Module>(i_isolate->factory()->NewModule(shared));
    2468             : }
    2469             : 
    2470             : namespace {
    2471          30 : bool IsIdentifier(i::Isolate* isolate, i::Handle<i::String> string) {
    2472          30 :   string = i::String::Flatten(isolate, string);
    2473             :   const int length = string->length();
    2474          30 :   if (length == 0) return false;
    2475          60 :   if (!i::IsIdentifierStart(string->Get(0))) return false;
    2476             :   i::DisallowHeapAllocation no_gc;
    2477          30 :   i::String::FlatContent flat = string->GetFlatContent(no_gc);
    2478          30 :   if (flat.IsOneByte()) {
    2479             :     auto vector = flat.ToOneByteVector();
    2480          85 :     for (int i = 1; i < length; i++) {
    2481         105 :       if (!i::IsIdentifierPart(vector[i])) return false;
    2482             :     }
    2483             :   } else {
    2484             :     auto vector = flat.ToUC16Vector();
    2485          15 :     for (int i = 1; i < length; i++) {
    2486          15 :       if (!i::IsIdentifierPart(vector[i])) return false;
    2487             :     }
    2488             :   }
    2489             :   return true;
    2490             : }
    2491             : }  // anonymous namespace
    2492             : 
    2493          84 : MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext(
    2494             :     Local<Context> v8_context, Source* source, size_t arguments_count,
    2495             :     Local<String> arguments[], size_t context_extension_count,
    2496             :     Local<Object> context_extensions[], CompileOptions options,
    2497             :     NoCacheReason no_cache_reason) {
    2498         336 :   PREPARE_FOR_EXECUTION(v8_context, ScriptCompiler, CompileFunctionInContext,
    2499             :                         Function);
    2500         168 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
    2501             : 
    2502             :   DCHECK(options == CompileOptions::kConsumeCodeCache ||
    2503             :          options == CompileOptions::kEagerCompile ||
    2504             :          options == CompileOptions::kNoCompileOptions);
    2505             : 
    2506             :   i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
    2507             : 
    2508             :   DCHECK(context->IsNativeContext());
    2509             :   i::Handle<i::SharedFunctionInfo> outer_info(
    2510         168 :       context->empty_function()->shared(), isolate);
    2511             : 
    2512             :   i::Handle<i::JSFunction> fun;
    2513             :   i::Handle<i::FixedArray> arguments_list =
    2514          84 :       isolate->factory()->NewFixedArray(static_cast<int>(arguments_count));
    2515         134 :   for (int i = 0; i < static_cast<int>(arguments_count); i++) {
    2516          30 :     i::Handle<i::String> argument = Utils::OpenHandle(*arguments[i]);
    2517          30 :     if (!IsIdentifier(isolate, argument)) return Local<Function>();
    2518          50 :     arguments_list->set(i, *argument);
    2519             :   }
    2520             : 
    2521         127 :   for (size_t i = 0; i < context_extension_count; ++i) {
    2522             :     i::Handle<i::JSReceiver> extension =
    2523          24 :         Utils::OpenHandle(*context_extensions[i]);
    2524          24 :     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          53 :         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          79 :       source->host_defined_options);
    2539             : 
    2540             :   i::ScriptData* script_data = nullptr;
    2541          79 :   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           5 :                                     source->cached_data->length);
    2546             :   }
    2547             : 
    2548             :   i::Handle<i::JSFunction> result;
    2549             :   has_pending_exception =
    2550         158 :       !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          79 :   if (options == kConsumeCodeCache) {
    2556          10 :     source->cached_data->rejected = script_data->rejected();
    2557             :   }
    2558          84 :   delete script_data;
    2559          79 :   RETURN_ON_FAILED_EXECUTION(Function);
    2560          69 :   RETURN_ESCAPED(Utils::CallableToLocal(result));
    2561             : }
    2562             : 
    2563       26804 : void ScriptCompiler::ScriptStreamingTask::Run() { data_->task->Run(); }
    2564             : 
    2565       13402 : ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript(
    2566             :     Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
    2567       13402 :   if (!i::FLAG_script_streaming) {
    2568             :     return nullptr;
    2569             :   }
    2570             :   // We don't support other compile options on streaming background compiles.
    2571             :   // TODO(rmcilroy): remove CompileOptions from the API.
    2572       13402 :   CHECK(options == ScriptCompiler::kNoCompileOptions);
    2573       13402 :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    2574       13402 :   i::ScriptStreamingData* data = source->impl();
    2575             :   std::unique_ptr<i::BackgroundCompileTask> task =
    2576       26804 :       base::make_unique<i::BackgroundCompileTask>(data, isolate);
    2577       13402 :   data->task = std::move(task);
    2578       13402 :   return new ScriptCompiler::ScriptStreamingTask(data);
    2579             : }
    2580             : 
    2581       13402 : MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
    2582             :                                            StreamedSource* v8_source,
    2583             :                                            Local<String> full_source_string,
    2584             :                                            const ScriptOrigin& origin) {
    2585       53608 :   PREPARE_FOR_EXECUTION(context, ScriptCompiler, Compile, Script);
    2586       26804 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler");
    2587       40206 :   TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"),
    2588             :                "V8.CompileStreamedScript");
    2589             : 
    2590       13402 :   i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
    2591             :   i::Compiler::ScriptDetails script_details = GetScriptDetails(
    2592             :       isolate, origin.ResourceName(), origin.ResourceLineOffset(),
    2593             :       origin.ResourceColumnOffset(), origin.SourceMapUrl(),
    2594       13402 :       origin.HostDefinedOptions());
    2595             :   i::ScriptStreamingData* data = v8_source->impl();
    2596             : 
    2597             :   i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
    2598             :       i::Compiler::GetSharedFunctionInfoForStreamedScript(
    2599       13402 :           isolate, str, script_details, origin.Options(), data);
    2600             : 
    2601             :   i::Handle<i::SharedFunctionInfo> result;
    2602       13402 :   has_pending_exception = !maybe_function_info.ToHandle(&result);
    2603       13402 :   if (has_pending_exception) isolate->ReportPendingMessages();
    2604             : 
    2605       13402 :   RETURN_ON_FAILED_EXECUTION(Script);
    2606             : 
    2607             :   Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
    2608       13293 :   if (generic.IsEmpty()) return Local<Script>();
    2609       13293 :   Local<Script> bound = generic->BindToCurrentContext();
    2610       13293 :   if (bound.IsEmpty()) return Local<Script>();
    2611       13293 :   RETURN_ESCAPED(bound);
    2612             : }
    2613             : 
    2614           0 : uint32_t ScriptCompiler::CachedDataVersionTag() {
    2615             :   return static_cast<uint32_t>(base::hash_combine(
    2616           0 :       internal::Version::Hash(), internal::FlagList::Hash(),
    2617           0 :       static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures())));
    2618             : }
    2619             : 
    2620         362 : ScriptCompiler::CachedData* ScriptCompiler::CreateCodeCache(
    2621             :     Local<UnboundScript> unbound_script) {
    2622             :   i::Handle<i::SharedFunctionInfo> shared =
    2623             :       i::Handle<i::SharedFunctionInfo>::cast(
    2624         362 :           Utils::OpenHandle(*unbound_script));
    2625             :   DCHECK(shared->is_toplevel());
    2626         362 :   return i::CodeSerializer::Serialize(shared);
    2627             : }
    2628             : 
    2629             : // static
    2630          10 : ScriptCompiler::CachedData* ScriptCompiler::CreateCodeCache(
    2631             :     Local<UnboundModuleScript> unbound_module_script) {
    2632             :   i::Handle<i::SharedFunctionInfo> shared =
    2633             :       i::Handle<i::SharedFunctionInfo>::cast(
    2634          10 :           Utils::OpenHandle(*unbound_module_script));
    2635             :   DCHECK(shared->is_toplevel());
    2636          10 :   return i::CodeSerializer::Serialize(shared);
    2637             : }
    2638             : 
    2639           5 : ScriptCompiler::CachedData* ScriptCompiler::CreateCodeCacheForFunction(
    2640             :     Local<Function> function) {
    2641             :   auto js_function =
    2642             :       i::Handle<i::JSFunction>::cast(Utils::OpenHandle(*function));
    2643             :   i::Handle<i::SharedFunctionInfo> shared(js_function->shared(),
    2644             :                                           js_function->GetIsolate());
    2645           5 :   CHECK(shared->is_wrapped());
    2646           5 :   return i::CodeSerializer::Serialize(shared);
    2647             : }
    2648             : 
    2649      129193 : MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source,
    2650             :                                    ScriptOrigin* origin) {
    2651      129193 :   if (origin) {
    2652             :     ScriptCompiler::Source script_source(source, *origin);
    2653        5090 :     return ScriptCompiler::Compile(context, &script_source);
    2654             :   }
    2655             :   ScriptCompiler::Source script_source(source);
    2656      124103 :   return ScriptCompiler::Compile(context, &script_source);
    2657             : }
    2658             : 
    2659             : 
    2660             : // --- E x c e p t i o n s ---
    2661             : 
    2662    20997122 : v8::TryCatch::TryCatch(v8::Isolate* isolate)
    2663             :     : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
    2664             :       next_(isolate_->try_catch_handler()),
    2665             :       is_verbose_(false),
    2666             :       can_continue_(true),
    2667             :       capture_message_(true),
    2668             :       rethrow_(false),
    2669    41994244 :       has_terminated_(false) {
    2670             :   ResetInternal();
    2671             :   // Special handling for simulators which have a separate JS stack.
    2672             :   js_stack_comparable_address_ = reinterpret_cast<void*>(
    2673    20997121 :       i::SimulatorStack::RegisterJSStackComparableAddress(isolate_));
    2674    20997121 :   isolate_->RegisterTryCatchHandler(this);
    2675    20997112 : }
    2676             : 
    2677             : 
    2678    41994237 : v8::TryCatch::~TryCatch() {
    2679    20997120 :   if (rethrow_) {
    2680         121 :     v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
    2681             :     v8::HandleScope scope(isolate);
    2682         242 :     v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
    2683         121 :     if (HasCaught() && capture_message_) {
    2684             :       // If an exception was caught and rethrow_ is indicated, the saved
    2685             :       // message, script, and location need to be restored to Isolate TLS
    2686             :       // for reuse.  capture_message_ needs to be disabled so that Throw()
    2687             :       // does not create a new message.
    2688         121 :       isolate_->thread_local_top()->rethrowing_message_ = true;
    2689         121 :       isolate_->RestorePendingMessageFromTryCatch(this);
    2690             :     }
    2691         121 :     isolate_->UnregisterTryCatchHandler(this);
    2692             :     i::SimulatorStack::UnregisterJSStackComparableAddress(isolate_);
    2693         121 :     reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
    2694             :     DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
    2695             :   } else {
    2696    21010104 :     if (HasCaught() && isolate_->has_scheduled_exception()) {
    2697             :       // If an exception was caught but is still scheduled because no API call
    2698             :       // promoted it, then it is canceled to prevent it from being propagated.
    2699             :       // Note that this will not cancel termination exceptions.
    2700         268 :       isolate_->CancelScheduledExceptionFromTryCatch(this);
    2701             :     }
    2702    20996999 :     isolate_->UnregisterTryCatchHandler(this);
    2703             :     i::SimulatorStack::UnregisterJSStackComparableAddress(isolate_);
    2704             :   }
    2705    20997117 : }
    2706             : 
    2707           0 : void* v8::TryCatch::operator new(size_t) { base::OS::Abort(); }
    2708           0 : void* v8::TryCatch::operator new[](size_t) { base::OS::Abort(); }
    2709           0 : void v8::TryCatch::operator delete(void*, size_t) { base::OS::Abort(); }
    2710           0 : void v8::TryCatch::operator delete[](void*, size_t) { base::OS::Abort(); }
    2711             : 
    2712      127996 : bool v8::TryCatch::HasCaught() const {
    2713    21151415 :   return !i::Object(reinterpret_cast<i::Address>(exception_))
    2714    42430826 :               ->IsTheHole(isolate_);
    2715             : }
    2716             : 
    2717             : 
    2718        1604 : bool v8::TryCatch::CanContinue() const {
    2719        1604 :   return can_continue_;
    2720             : }
    2721             : 
    2722             : 
    2723       22069 : bool v8::TryCatch::HasTerminated() const {
    2724       22069 :   return has_terminated_;
    2725             : }
    2726             : 
    2727             : 
    2728         121 : v8::Local<v8::Value> v8::TryCatch::ReThrow() {
    2729         121 :   if (!HasCaught()) return v8::Local<v8::Value>();
    2730         121 :   rethrow_ = true;
    2731         121 :   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
    2732             : }
    2733             : 
    2734             : 
    2735       10516 : v8::Local<Value> v8::TryCatch::Exception() const {
    2736       10516 :   if (HasCaught()) {
    2737             :     // Check for out of memory exception.
    2738             :     i::Object exception(reinterpret_cast<i::Address>(exception_));
    2739             :     return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
    2740             :   } else {
    2741           0 :     return v8::Local<Value>();
    2742             :   }
    2743             : }
    2744             : 
    2745             : 
    2746        6432 : MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const {
    2747        6432 :   if (!HasCaught()) return v8::Local<Value>();
    2748             :   i::Object raw_obj(reinterpret_cast<i::Address>(exception_));
    2749        6432 :   if (!raw_obj->IsJSObject()) return v8::Local<Value>();
    2750       10344 :   PREPARE_FOR_EXECUTION(context, TryCatch, StackTrace, Value);
    2751        2586 :   i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
    2752             :   i::Handle<i::String> name = isolate->factory()->stack_string();
    2753        2586 :   Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
    2754             :   has_pending_exception = maybe.IsNothing();
    2755        2586 :   RETURN_ON_FAILED_EXECUTION(Value);
    2756        2586 :   if (!maybe.FromJust()) return v8::Local<Value>();
    2757             :   Local<Value> result;
    2758             :   has_pending_exception =
    2759        5172 :       !ToLocal<Value>(i::JSReceiver::GetProperty(isolate, obj, name), &result);
    2760        2586 :   RETURN_ON_FAILED_EXECUTION(Value);
    2761        2586 :   RETURN_ESCAPED(result);
    2762             : }
    2763             : 
    2764             : 
    2765        8516 : v8::Local<v8::Message> v8::TryCatch::Message() const {
    2766        8516 :   i::Object message(reinterpret_cast<i::Address>(message_obj_));
    2767             :   DCHECK(message->IsJSMessageObject() || message->IsTheHole(isolate_));
    2768        8516 :   if (HasCaught() && !message->IsTheHole(isolate_)) {
    2769             :     return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
    2770             :   } else {
    2771          60 :     return v8::Local<v8::Message>();
    2772             :   }
    2773             : }
    2774             : 
    2775             : 
    2776         714 : void v8::TryCatch::Reset() {
    2777        1896 :   if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
    2778             :     // If an exception was caught but is still scheduled because no API call
    2779             :     // promoted it, then it is canceled to prevent it from being propagated.
    2780             :     // Note that this will not cancel termination exceptions.
    2781           5 :     isolate_->CancelScheduledExceptionFromTryCatch(this);
    2782             :   }
    2783             :   ResetInternal();
    2784         714 : }
    2785             : 
    2786             : 
    2787           0 : void v8::TryCatch::ResetInternal() {
    2788         714 :   i::Object the_hole = i::ReadOnlyRoots(isolate_).the_hole_value();
    2789    20997836 :   exception_ = reinterpret_cast<void*>(the_hole->ptr());
    2790    20997836 :   message_obj_ = reinterpret_cast<void*>(the_hole->ptr());
    2791           0 : }
    2792             : 
    2793             : 
    2794      177233 : void v8::TryCatch::SetVerbose(bool value) {
    2795      177233 :   is_verbose_ = value;
    2796      177233 : }
    2797             : 
    2798           0 : bool v8::TryCatch::IsVerbose() const { return is_verbose_; }
    2799             : 
    2800       53638 : void v8::TryCatch::SetCaptureMessage(bool value) {
    2801       53638 :   capture_message_ = value;
    2802       53638 : }
    2803             : 
    2804             : 
    2805             : // --- M e s s a g e ---
    2806             : 
    2807             : 
    2808        2823 : Local<String> Message::Get() const {
    2809             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2810             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2811        2823 :   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
    2812             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    2813        2823 :   i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
    2814             :   Local<String> result = Utils::ToLocal(raw_result);
    2815        2823 :   return scope.Escape(result);
    2816             : }
    2817             : 
    2818          50 : v8::Isolate* Message::GetIsolate() const {
    2819             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2820          50 :   return reinterpret_cast<Isolate*>(isolate);
    2821             : }
    2822             : 
    2823       16097 : ScriptOrigin Message::GetScriptOrigin() const {
    2824             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2825             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2826             :   auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
    2827             :   i::Handle<i::Script> script(message->script(), isolate);
    2828       32194 :   return GetScriptOriginForScript(isolate, script);
    2829             : }
    2830             : 
    2831             : 
    2832           0 : v8::Local<Value> Message::GetScriptResourceName() const {
    2833           0 :   return GetScriptOrigin().ResourceName();
    2834             : }
    2835             : 
    2836             : 
    2837        2028 : v8::Local<v8::StackTrace> Message::GetStackTrace() const {
    2838             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2839             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2840        2028 :   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
    2841             :   auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
    2842             :   i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
    2843        2028 :   if (!stackFramesObj->IsFixedArray()) return v8::Local<v8::StackTrace>();
    2844             :   auto stackTrace = i::Handle<i::FixedArray>::cast(stackFramesObj);
    2845             :   return scope.Escape(Utils::StackTraceToLocal(stackTrace));
    2846             : }
    2847             : 
    2848             : 
    2849        9101 : Maybe<int> Message::GetLineNumber(Local<Context> context) const {
    2850             :   auto self = Utils::OpenHandle(this);
    2851             :   i::Isolate* isolate = self->GetIsolate();
    2852             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2853        9101 :   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
    2854             :   auto msg = i::Handle<i::JSMessageObject>::cast(self);
    2855       18202 :   return Just(msg->GetLineNumber());
    2856             : }
    2857             : 
    2858             : 
    2859          30 : int Message::GetStartPosition() const {
    2860             :   auto self = Utils::OpenHandle(this);
    2861          30 :   return self->start_position();
    2862             : }
    2863             : 
    2864             : 
    2865          18 : int Message::GetEndPosition() const {
    2866             :   auto self = Utils::OpenHandle(this);
    2867          18 :   return self->end_position();
    2868             : }
    2869             : 
    2870       24568 : int Message::ErrorLevel() const {
    2871             :   auto self = Utils::OpenHandle(this);
    2872       24568 :   return self->error_level();
    2873             : }
    2874             : 
    2875        8817 : int Message::GetStartColumn() const {
    2876             :   auto self = Utils::OpenHandle(this);
    2877             :   i::Isolate* isolate = self->GetIsolate();
    2878             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2879        8817 :   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
    2880             :   auto msg = i::Handle<i::JSMessageObject>::cast(self);
    2881       17634 :   return msg->GetColumnNumber();
    2882             : }
    2883             : 
    2884        8817 : Maybe<int> Message::GetStartColumn(Local<Context> context) const {
    2885        8817 :   return Just(GetStartColumn());
    2886             : }
    2887             : 
    2888        6411 : int Message::GetEndColumn() const {
    2889             :   auto self = Utils::OpenHandle(this);
    2890             :   i::Isolate* isolate = self->GetIsolate();
    2891             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2892        6411 :   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
    2893             :   auto msg = i::Handle<i::JSMessageObject>::cast(self);
    2894        6411 :   const int column_number = msg->GetColumnNumber();
    2895        6411 :   if (column_number == -1) return -1;
    2896             :   const int start = self->start_position();
    2897             :   const int end = self->end_position();
    2898        6411 :   return column_number + (end - start);
    2899             : }
    2900             : 
    2901        6411 : Maybe<int> Message::GetEndColumn(Local<Context> context) const {
    2902        6411 :   return Just(GetEndColumn());
    2903             : }
    2904             : 
    2905             : 
    2906         131 : bool Message::IsSharedCrossOrigin() const {
    2907             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2908             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2909             :   return Utils::OpenHandle(this)
    2910             :       ->script()
    2911             :       ->origin_options()
    2912         131 :       .IsSharedCrossOrigin();
    2913             : }
    2914             : 
    2915           0 : bool Message::IsOpaque() const {
    2916             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2917             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2918           0 :   return Utils::OpenHandle(this)->script()->origin_options().IsOpaque();
    2919             : }
    2920             : 
    2921             : 
    2922        6422 : MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
    2923             :   auto self = Utils::OpenHandle(this);
    2924             :   i::Isolate* isolate = self->GetIsolate();
    2925             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2926        6422 :   EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate));
    2927             :   auto msg = i::Handle<i::JSMessageObject>::cast(self);
    2928       19266 :   RETURN_ESCAPED(Utils::ToLocal(msg->GetSourceLine()));
    2929             : }
    2930             : 
    2931             : 
    2932           0 : void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
    2933             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    2934             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    2935           0 :   i_isolate->PrintCurrentStackTrace(out);
    2936           0 : }
    2937             : 
    2938             : 
    2939             : // --- S t a c k T r a c e ---
    2940             : 
    2941       62199 : Local<StackFrame> StackTrace::GetFrame(Isolate* v8_isolate,
    2942             :                                        uint32_t index) const {
    2943             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    2944             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    2945       62199 :   EscapableHandleScope scope(v8_isolate);
    2946       62199 :   auto obj = handle(Utils::OpenHandle(this)->get(index), isolate);
    2947             :   auto frame = i::Handle<i::StackTraceFrame>::cast(obj);
    2948       62199 :   return scope.Escape(Utils::StackFrameToLocal(frame));
    2949             : }
    2950             : 
    2951      120904 : int StackTrace::GetFrameCount() const {
    2952      120904 :   return Utils::OpenHandle(this)->length();
    2953             : }
    2954             : 
    2955             : 
    2956       64520 : Local<StackTrace> StackTrace::CurrentStackTrace(
    2957             :     Isolate* isolate,
    2958             :     int frame_limit,
    2959             :     StackTraceOptions options) {
    2960             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    2961             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    2962             :   i::Handle<i::FixedArray> stackTrace =
    2963       64520 :       i_isolate->CaptureCurrentStackTrace(frame_limit, options);
    2964       64520 :   return Utils::StackTraceToLocal(stackTrace);
    2965             : }
    2966             : 
    2967             : 
    2968             : // --- S t a c k F r a m e ---
    2969             : 
    2970       60665 : int StackFrame::GetLineNumber() const {
    2971       60665 :   return i::StackTraceFrame::GetLineNumber(Utils::OpenHandle(this));
    2972             : }
    2973             : 
    2974             : 
    2975       60630 : int StackFrame::GetColumn() const {
    2976       60630 :   return i::StackTraceFrame::GetColumnNumber(Utils::OpenHandle(this));
    2977             : }
    2978             : 
    2979             : 
    2980       60246 : int StackFrame::GetScriptId() const {
    2981       60246 :   return i::StackTraceFrame::GetScriptId(Utils::OpenHandle(this));
    2982             : }
    2983             : 
    2984       60433 : Local<String> StackFrame::GetScriptName() const {
    2985             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2986       60433 :   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
    2987             :   i::Handle<i::Object> name =
    2988       60433 :       i::StackTraceFrame::GetFileName(Utils::OpenHandle(this));
    2989             :   return name->IsString()
    2990             :              ? scope.Escape(Local<String>::Cast(Utils::ToLocal(name)))
    2991      180448 :              : Local<String>();
    2992             : }
    2993             : 
    2994             : 
    2995      120432 : Local<String> StackFrame::GetScriptNameOrSourceURL() const {
    2996             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    2997      120432 :   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
    2998             :   i::Handle<i::Object> name =
    2999      120432 :       i::StackTraceFrame::GetScriptNameOrSourceUrl(Utils::OpenHandle(this));
    3000             :   return name->IsString()
    3001             :              ? scope.Escape(Local<String>::Cast(Utils::ToLocal(name)))
    3002      360098 :              : Local<String>();
    3003             : }
    3004             : 
    3005             : 
    3006       60595 : Local<String> StackFrame::GetFunctionName() const {
    3007             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    3008       60595 :   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
    3009             :   i::Handle<i::Object> name =
    3010       60595 :       i::StackTraceFrame::GetFunctionName(Utils::OpenHandle(this));
    3011             :   return name->IsString()
    3012             :              ? scope.Escape(Local<String>::Cast(Utils::ToLocal(name)))
    3013      181785 :              : Local<String>();
    3014             : }
    3015             : 
    3016         100 : bool StackFrame::IsEval() const {
    3017         100 :   return i::StackTraceFrame::IsEval(Utils::OpenHandle(this));
    3018             : }
    3019             : 
    3020         100 : bool StackFrame::IsConstructor() const {
    3021         100 :   return i::StackTraceFrame::IsConstructor(Utils::OpenHandle(this));
    3022             : }
    3023             : 
    3024       60171 : bool StackFrame::IsWasm() const {
    3025       60171 :   return i::StackTraceFrame::IsWasm(Utils::OpenHandle(this));
    3026             : }
    3027             : 
    3028             : // --- J S O N ---
    3029             : 
    3030         135 : MaybeLocal<Value> JSON::Parse(Local<Context> context,
    3031             :                               Local<String> json_string) {
    3032         540 :   PREPARE_FOR_EXECUTION(context, JSON, Parse, Value);
    3033         135 :   i::Handle<i::String> string = Utils::OpenHandle(*json_string);
    3034         135 :   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         135 :                    : i::JsonParser<false>::Parse(isolate, source, undefined);
    3039             :   Local<Value> result;
    3040             :   has_pending_exception = !ToLocal<Value>(maybe, &result);
    3041         135 :   RETURN_ON_FAILED_EXECUTION(Value);
    3042         134 :   RETURN_ESCAPED(result);
    3043             : }
    3044             : 
    3045         109 : MaybeLocal<String> JSON::Stringify(Local<Context> context,
    3046             :                                    Local<Value> json_object,
    3047             :                                    Local<String> gap) {
    3048         436 :   PREPARE_FOR_EXECUTION(context, JSON, Stringify, String);
    3049         109 :   i::Handle<i::Object> object = Utils::OpenHandle(*json_object);
    3050             :   i::Handle<i::Object> replacer = isolate->factory()->undefined_value();
    3051             :   i::Handle<i::String> gap_string = gap.IsEmpty()
    3052             :                                         ? isolate->factory()->empty_string()
    3053         109 :                                         : Utils::OpenHandle(*gap);
    3054             :   i::Handle<i::Object> maybe;
    3055             :   has_pending_exception =
    3056         218 :       !i::JsonStringify(isolate, object, replacer, gap_string).ToHandle(&maybe);
    3057         109 :   RETURN_ON_FAILED_EXECUTION(String);
    3058             :   Local<String> result;
    3059             :   has_pending_exception =
    3060         109 :       !ToLocal<String>(i::Object::ToString(isolate, maybe), &result);
    3061         109 :   RETURN_ON_FAILED_EXECUTION(String);
    3062         109 :   RETURN_ESCAPED(result);
    3063             : }
    3064             : 
    3065             : // --- V a l u e   S e r i a l i z a t i o n ---
    3066             : 
    3067           0 : Maybe<bool> ValueSerializer::Delegate::WriteHostObject(Isolate* v8_isolate,
    3068             :                                                        Local<Object> object) {
    3069             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    3070           0 :   isolate->ScheduleThrow(*isolate->factory()->NewError(
    3071             :       isolate->error_function(), i::MessageTemplate::kDataCloneError,
    3072           0 :       Utils::OpenHandle(*object)));
    3073           0 :   return Nothing<bool>();
    3074             : }
    3075             : 
    3076           0 : Maybe<uint32_t> ValueSerializer::Delegate::GetSharedArrayBufferId(
    3077             :     Isolate* v8_isolate, Local<SharedArrayBuffer> shared_array_buffer) {
    3078             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    3079           0 :   isolate->ScheduleThrow(*isolate->factory()->NewError(
    3080             :       isolate->error_function(), i::MessageTemplate::kDataCloneError,
    3081           0 :       Utils::OpenHandle(*shared_array_buffer)));
    3082           0 :   return Nothing<uint32_t>();
    3083             : }
    3084             : 
    3085           0 : Maybe<uint32_t> ValueSerializer::Delegate::GetWasmModuleTransferId(
    3086             :     Isolate* v8_isolate, Local<WasmModuleObject> module) {
    3087           0 :   return Nothing<uint32_t>();
    3088             : }
    3089             : 
    3090          20 : void* ValueSerializer::Delegate::ReallocateBufferMemory(void* old_buffer,
    3091             :                                                         size_t size,
    3092             :                                                         size_t* actual_size) {
    3093          20 :   *actual_size = size;
    3094          20 :   return realloc(old_buffer, size);
    3095             : }
    3096             : 
    3097          20 : void ValueSerializer::Delegate::FreeBufferMemory(void* buffer) {
    3098          20 :   return free(buffer);
    3099             : }
    3100             : 
    3101        2027 : struct ValueSerializer::PrivateData {
    3102             :   explicit PrivateData(i::Isolate* i, ValueSerializer::Delegate* delegate)
    3103        2028 :       : isolate(i), serializer(i, delegate) {}
    3104             :   i::Isolate* isolate;
    3105             :   i::ValueSerializer serializer;
    3106             : };
    3107             : 
    3108           0 : ValueSerializer::ValueSerializer(Isolate* isolate)
    3109           0 :     : ValueSerializer(isolate, nullptr) {}
    3110             : 
    3111        2022 : ValueSerializer::ValueSerializer(Isolate* isolate, Delegate* delegate)
    3112             :     : private_(
    3113        4046 :           new PrivateData(reinterpret_cast<i::Isolate*>(isolate), delegate)) {}
    3114             : 
    3115        4055 : ValueSerializer::~ValueSerializer() { delete private_; }
    3116             : 
    3117        1861 : void ValueSerializer::WriteHeader() { private_->serializer.WriteHeader(); }
    3118             : 
    3119           1 : void ValueSerializer::SetTreatArrayBufferViewsAsHostObjects(bool mode) {
    3120           1 :   private_->serializer.SetTreatArrayBufferViewsAsHostObjects(mode);
    3121           1 : }
    3122             : 
    3123        1858 : Maybe<bool> ValueSerializer::WriteValue(Local<Context> context,
    3124             :                                         Local<Value> value) {
    3125             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    3126        5572 :   ENTER_V8(isolate, context, ValueSerializer, WriteValue, Nothing<bool>(),
    3127             :            i::HandleScope);
    3128        1862 :   i::Handle<i::Object> object = Utils::OpenHandle(*value);
    3129        1862 :   Maybe<bool> result = private_->serializer.WriteObject(object);
    3130             :   has_pending_exception = result.IsNothing();
    3131        1856 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    3132        1829 :   return result;
    3133             : }
    3134             : 
    3135        1822 : std::pair<uint8_t*, size_t> ValueSerializer::Release() {
    3136        1822 :   return private_->serializer.Release();
    3137             : }
    3138             : 
    3139          47 : void ValueSerializer::TransferArrayBuffer(uint32_t transfer_id,
    3140             :                                           Local<ArrayBuffer> array_buffer) {
    3141          47 :   private_->serializer.TransferArrayBuffer(transfer_id,
    3142          47 :                                            Utils::OpenHandle(*array_buffer));
    3143          47 : }
    3144             : 
    3145           2 : void ValueSerializer::WriteUint32(uint32_t value) {
    3146           2 :   private_->serializer.WriteUint32(value);
    3147           2 : }
    3148             : 
    3149           2 : void ValueSerializer::WriteUint64(uint64_t value) {
    3150           2 :   private_->serializer.WriteUint64(value);
    3151           2 : }
    3152             : 
    3153           4 : void ValueSerializer::WriteDouble(double value) {
    3154           4 :   private_->serializer.WriteDouble(value);
    3155           4 : }
    3156             : 
    3157          15 : void ValueSerializer::WriteRawBytes(const void* source, size_t length) {
    3158          15 :   private_->serializer.WriteRawBytes(source, length);
    3159          15 : }
    3160             : 
    3161           0 : MaybeLocal<Object> ValueDeserializer::Delegate::ReadHostObject(
    3162             :     Isolate* v8_isolate) {
    3163             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    3164           0 :   isolate->ScheduleThrow(*isolate->factory()->NewError(
    3165             :       isolate->error_function(),
    3166           0 :       i::MessageTemplate::kDataCloneDeserializationError));
    3167           0 :   return MaybeLocal<Object>();
    3168             : }
    3169             : 
    3170           1 : MaybeLocal<WasmModuleObject> ValueDeserializer::Delegate::GetWasmModuleFromId(
    3171             :     Isolate* v8_isolate, uint32_t id) {
    3172             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    3173           2 :   isolate->ScheduleThrow(*isolate->factory()->NewError(
    3174             :       isolate->error_function(),
    3175           3 :       i::MessageTemplate::kDataCloneDeserializationError));
    3176           1 :   return MaybeLocal<WasmModuleObject>();
    3177             : }
    3178             : 
    3179             : MaybeLocal<SharedArrayBuffer>
    3180           0 : ValueDeserializer::Delegate::GetSharedArrayBufferFromId(Isolate* v8_isolate,
    3181             :                                                         uint32_t id) {
    3182             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    3183           0 :   isolate->ScheduleThrow(*isolate->factory()->NewError(
    3184             :       isolate->error_function(),
    3185           0 :       i::MessageTemplate::kDataCloneDeserializationError));
    3186           0 :   return MaybeLocal<SharedArrayBuffer>();
    3187             : }
    3188             : 
    3189        1917 : struct ValueDeserializer::PrivateData {
    3190             :   PrivateData(i::Isolate* i, i::Vector<const uint8_t> data, Delegate* delegate)
    3191        1917 :       : isolate(i), deserializer(i, data, delegate) {}
    3192             :   i::Isolate* isolate;
    3193             :   i::ValueDeserializer deserializer;
    3194             :   bool has_aborted = false;
    3195             :   bool supports_legacy_wire_format = false;
    3196             : };
    3197             : 
    3198           0 : ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data,
    3199             :                                      size_t size)
    3200           0 :     : ValueDeserializer(isolate, data, size, nullptr) {}
    3201             : 
    3202        1917 : ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data,
    3203             :                                      size_t size, Delegate* delegate) {
    3204        1917 :   if (base::IsValueInRangeForNumericType<int>(size)) {
    3205             :     private_ = new PrivateData(
    3206             :         reinterpret_cast<i::Isolate*>(isolate),
    3207        3834 :         i::Vector<const uint8_t>(data, static_cast<int>(size)), delegate);
    3208             :   } else {
    3209             :     private_ = new PrivateData(reinterpret_cast<i::Isolate*>(isolate),
    3210           0 :                                i::Vector<const uint8_t>(nullptr, 0), nullptr);
    3211           0 :     private_->has_aborted = true;
    3212             :   }
    3213        1917 : }
    3214             : 
    3215        3834 : ValueDeserializer::~ValueDeserializer() { delete private_; }
    3216             : 
    3217        1917 : Maybe<bool> ValueDeserializer::ReadHeader(Local<Context> context) {
    3218             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    3219        5751 :   ENTER_V8_NO_SCRIPT(isolate, context, ValueDeserializer, ReadHeader,
    3220             :                      Nothing<bool>(), i::HandleScope);
    3221             : 
    3222             :   // We could have aborted during the constructor.
    3223             :   // If so, ReadHeader is where we report it.
    3224        1917 :   if (private_->has_aborted) {
    3225           0 :     isolate->Throw(*isolate->factory()->NewError(
    3226           0 :         i::MessageTemplate::kDataCloneDeserializationError));
    3227             :     has_pending_exception = true;
    3228           0 :     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    3229             :   }
    3230             : 
    3231             :   bool read_header = false;
    3232        3834 :   has_pending_exception = !private_->deserializer.ReadHeader().To(&read_header);
    3233        1917 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    3234             :   DCHECK(read_header);
    3235             : 
    3236             :   static const uint32_t kMinimumNonLegacyVersion = 13;
    3237        2035 :   if (GetWireFormatVersion() < kMinimumNonLegacyVersion &&
    3238         120 :       !private_->supports_legacy_wire_format) {
    3239           0 :     isolate->Throw(*isolate->factory()->NewError(
    3240           0 :         i::MessageTemplate::kDataCloneDeserializationVersionError));
    3241             :     has_pending_exception = true;
    3242           0 :     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    3243             :   }
    3244             : 
    3245             :   return Just(true);
    3246             : }
    3247             : 
    3248        1917 : void ValueDeserializer::SetSupportsLegacyWireFormat(
    3249             :     bool supports_legacy_wire_format) {
    3250        1917 :   private_->supports_legacy_wire_format = supports_legacy_wire_format;
    3251        1917 : }
    3252             : 
    3253         262 : void ValueDeserializer::SetExpectInlineWasm(bool expect_inline_wasm) {
    3254         262 :   private_->deserializer.set_expect_inline_wasm(expect_inline_wasm);
    3255         262 : }
    3256             : 
    3257           8 : uint32_t ValueDeserializer::GetWireFormatVersion() const {
    3258        3838 :   CHECK(!private_->has_aborted);
    3259           8 :   return private_->deserializer.GetWireFormatVersion();
    3260             : }
    3261             : 
    3262        1915 : MaybeLocal<Value> ValueDeserializer::ReadValue(Local<Context> context) {
    3263        1915 :   CHECK(!private_->has_aborted);
    3264        7660 :   PREPARE_FOR_EXECUTION(context, ValueDeserializer, ReadValue, Value);
    3265             :   i::MaybeHandle<i::Object> result;
    3266        1915 :   if (GetWireFormatVersion() > 0) {
    3267        1903 :     result = private_->deserializer.ReadObject();
    3268             :   } else {
    3269             :     result =
    3270          12 :         private_->deserializer.ReadObjectUsingEntireBufferForLegacyFormat();
    3271             :   }
    3272             :   Local<Value> value;
    3273             :   has_pending_exception = !ToLocal(result, &value);
    3274        1915 :   RETURN_ON_FAILED_EXECUTION(Value);
    3275        1886 :   RETURN_ESCAPED(value);
    3276             : }
    3277             : 
    3278          29 : void ValueDeserializer::TransferArrayBuffer(uint32_t transfer_id,
    3279             :                                             Local<ArrayBuffer> array_buffer) {
    3280          29 :   CHECK(!private_->has_aborted);
    3281          29 :   private_->deserializer.TransferArrayBuffer(transfer_id,
    3282          29 :                                              Utils::OpenHandle(*array_buffer));
    3283          29 : }
    3284             : 
    3285           0 : void ValueDeserializer::TransferSharedArrayBuffer(
    3286             :     uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) {
    3287           0 :   CHECK(!private_->has_aborted);
    3288           0 :   private_->deserializer.TransferArrayBuffer(
    3289           0 :       transfer_id, Utils::OpenHandle(*shared_array_buffer));
    3290           0 : }
    3291             : 
    3292           2 : bool ValueDeserializer::ReadUint32(uint32_t* value) {
    3293           2 :   return private_->deserializer.ReadUint32(value);
    3294             : }
    3295             : 
    3296           2 : bool ValueDeserializer::ReadUint64(uint64_t* value) {
    3297           2 :   return private_->deserializer.ReadUint64(value);
    3298             : }
    3299             : 
    3300           4 : bool ValueDeserializer::ReadDouble(double* value) {
    3301           4 :   return private_->deserializer.ReadDouble(value);
    3302             : }
    3303             : 
    3304          13 : bool ValueDeserializer::ReadRawBytes(size_t length, const void** data) {
    3305          13 :   return private_->deserializer.ReadRawBytes(length, data);
    3306             : }
    3307             : 
    3308             : // --- D a t a ---
    3309             : 
    3310           0 : bool Value::FullIsUndefined() const {
    3311             :   i::Handle<i::Object> object = Utils::OpenHandle(this);
    3312             :   bool result = object->IsUndefined();
    3313             :   DCHECK_EQ(result, QuickIsUndefined());
    3314           0 :   return result;
    3315             : }
    3316             : 
    3317             : 
    3318           0 : bool Value::FullIsNull() const {
    3319             :   i::Handle<i::Object> object = Utils::OpenHandle(this);
    3320             :   bool result = object->IsNull();
    3321             :   DCHECK_EQ(result, QuickIsNull());
    3322           0 :   return result;
    3323             : }
    3324             : 
    3325             : 
    3326        7783 : bool Value::IsTrue() const {
    3327             :   i::Handle<i::Object> object = Utils::OpenHandle(this);
    3328       72219 :   if (object->IsSmi()) return false;
    3329             :   return object->IsTrue();
    3330             : }
    3331             : 
    3332             : 
    3333         118 : bool Value::IsFalse() const {
    3334             :   i::Handle<i::Object> object = Utils::OpenHandle(this);
    3335         118 :   if (object->IsSmi()) return false;
    3336             :   return object->IsFalse();
    3337             : }
    3338             : 
    3339             : 
    3340     7490470 : bool Value::IsFunction() const { return Utils::OpenHandle(this)->IsCallable(); }
    3341             : 
    3342             : 
    3343       16635 : bool Value::IsName() const {
    3344       16635 :   return Utils::OpenHandle(this)->IsName();
    3345             : }
    3346             : 
    3347             : 
    3348           0 : bool Value::FullIsString() const {
    3349             :   bool result = Utils::OpenHandle(this)->IsString();
    3350             :   DCHECK_EQ(result, QuickIsString());
    3351           0 :   return result;
    3352             : }
    3353             : 
    3354             : 
    3355     9312503 : bool Value::IsSymbol() const {
    3356     9312503 :   return Utils::OpenHandle(this)->IsSymbol();
    3357             : }
    3358             : 
    3359             : 
    3360     1884332 : bool Value::IsArray() const {
    3361     1884332 :   return Utils::OpenHandle(this)->IsJSArray();
    3362             : }
    3363             : 
    3364             : 
    3365     1268077 : bool Value::IsArrayBuffer() const {
    3366             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3367     1522404 :   return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
    3368             : }
    3369             : 
    3370             : 
    3371          99 : bool Value::IsArrayBufferView() const {
    3372          99 :   return Utils::OpenHandle(this)->IsJSArrayBufferView();
    3373             : }
    3374             : 
    3375             : 
    3376      923984 : bool Value::IsTypedArray() const {
    3377      923986 :   return Utils::OpenHandle(this)->IsJSTypedArray();
    3378             : }
    3379             : 
    3380             : #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype)                    \
    3381             :   bool Value::Is##Type##Array() const {                                      \
    3382             :     i::Handle<i::Object> obj = Utils::OpenHandle(this);                      \
    3383             :     return obj->IsJSTypedArray() &&                                          \
    3384             :            i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
    3385             :   }
    3386             : 
    3387         222 : TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
    3388             : 
    3389             : #undef VALUE_IS_TYPED_ARRAY
    3390             : 
    3391             : 
    3392      895370 : bool Value::IsDataView() const {
    3393      895370 :   return Utils::OpenHandle(this)->IsJSDataView();
    3394             : }
    3395             : 
    3396             : 
    3397     1267177 : bool Value::IsSharedArrayBuffer() const {
    3398             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3399     1548901 :   return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
    3400             : }
    3401             : 
    3402             : 
    3403    16672716 : bool Value::IsObject() const { return Utils::OpenHandle(this)->IsJSReceiver(); }
    3404             : 
    3405             : 
    3406     3710370 : bool Value::IsNumber() const {
    3407     3710370 :   return Utils::OpenHandle(this)->IsNumber();
    3408             : }
    3409             : 
    3410     6721194 : bool Value::IsBigInt() const { return Utils::OpenHandle(this)->IsBigInt(); }
    3411             : 
    3412     1981480 : bool Value::IsProxy() const { return Utils::OpenHandle(this)->IsJSProxy(); }
    3413             : 
    3414             : #define VALUE_IS_SPECIFIC_TYPE(Type, Check)             \
    3415             :   bool Value::Is##Type() const {                        \
    3416             :     i::Handle<i::Object> obj = Utils::OpenHandle(this); \
    3417             :     return obj->Is##Check();                            \
    3418             :   }
    3419             : 
    3420     1681036 : VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, JSArgumentsObject)
    3421       43690 : VALUE_IS_SPECIFIC_TYPE(BigIntObject, BigIntWrapper)
    3422       43806 : VALUE_IS_SPECIFIC_TYPE(BooleanObject, BooleanWrapper)
    3423       43722 : VALUE_IS_SPECIFIC_TYPE(NumberObject, NumberWrapper)
    3424       66924 : VALUE_IS_SPECIFIC_TYPE(StringObject, StringWrapper)
    3425       43676 : VALUE_IS_SPECIFIC_TYPE(SymbolObject, SymbolWrapper)
    3426     1800966 : VALUE_IS_SPECIFIC_TYPE(Date, JSDate)
    3427     1973160 : VALUE_IS_SPECIFIC_TYPE(Map, JSMap)
    3428     1972638 : VALUE_IS_SPECIFIC_TYPE(Set, JSSet)
    3429     1792174 : VALUE_IS_SPECIFIC_TYPE(WeakMap, JSWeakMap)
    3430     1792076 : VALUE_IS_SPECIFIC_TYPE(WeakSet, JSWeakSet)
    3431          92 : VALUE_IS_SPECIFIC_TYPE(WebAssemblyCompiledModule, WasmModuleObject)
    3432             : 
    3433             : #undef VALUE_IS_SPECIFIC_TYPE
    3434             : 
    3435             : 
    3436     3754246 : bool Value::IsBoolean() const {
    3437     3754246 :   return Utils::OpenHandle(this)->IsBoolean();
    3438             : }
    3439             : 
    3440          97 : bool Value::IsExternal() const {
    3441             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3442          97 :   if (!obj->IsHeapObject()) return false;
    3443             :   i::Handle<i::HeapObject> heap_obj = i::Handle<i::HeapObject>::cast(obj);
    3444             :   // Check the instance type is JS_OBJECT (instance type of Externals) before
    3445             :   // attempting to get the Isolate since that guarantees the object is writable
    3446             :   // and GetIsolate will work.
    3447          97 :   if (heap_obj->map()->instance_type() != i::JS_OBJECT_TYPE) return false;
    3448             :   i::Isolate* isolate = i::JSObject::cast(*heap_obj)->GetIsolate();
    3449          52 :   return heap_obj->IsExternal(isolate);
    3450             : }
    3451             : 
    3452             : 
    3453      534639 : bool Value::IsInt32() const {
    3454             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3455      534639 :   if (obj->IsSmi()) return true;
    3456          36 :   if (obj->IsNumber()) {
    3457             :     return i::IsInt32Double(obj->Number());
    3458             :   }
    3459             :   return false;
    3460             : }
    3461             : 
    3462             : 
    3463        9904 : bool Value::IsUint32() const {
    3464             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3465       17544 :   if (obj->IsSmi()) return i::Smi::ToInt(*obj) >= 0;
    3466        2264 :   if (obj->IsNumber()) {
    3467             :     double value = obj->Number();
    3468         107 :     return !i::IsMinusZero(value) &&
    3469          95 :         value >= 0 &&
    3470         202 :         value <= i::kMaxUInt32 &&
    3471             :         value == i::FastUI2D(i::FastD2UI(value));
    3472             :   }
    3473             :   return false;
    3474             : }
    3475             : 
    3476             : 
    3477      903028 : bool Value::IsNativeError() const {
    3478      903028 :   return Utils::OpenHandle(this)->IsJSError();
    3479             : }
    3480             : 
    3481             : 
    3482     3242713 : bool Value::IsRegExp() const {
    3483             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3484     3242713 :   return obj->IsJSRegExp();
    3485             : }
    3486             : 
    3487          12 : bool Value::IsAsyncFunction() const {
    3488             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3489          12 :   if (!obj->IsJSFunction()) return false;
    3490             :   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
    3491             :   return i::IsAsyncFunction(func->shared()->kind());
    3492             : }
    3493             : 
    3494          95 : bool Value::IsGeneratorFunction() const {
    3495             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3496          95 :   if (!obj->IsJSFunction()) return false;
    3497             :   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
    3498             :   return i::IsGeneratorFunction(func->shared()->kind());
    3499             : }
    3500             : 
    3501             : 
    3502     1065226 : bool Value::IsGeneratorObject() const {
    3503     1065226 :   return Utils::OpenHandle(this)->IsJSGeneratorObject();
    3504             : }
    3505             : 
    3506             : 
    3507      895959 : bool Value::IsMapIterator() const {
    3508      895959 :   return Utils::OpenHandle(this)->IsJSMapIterator();
    3509             : }
    3510             : 
    3511             : 
    3512      895847 : bool Value::IsSetIterator() const {
    3513      895847 :   return Utils::OpenHandle(this)->IsJSSetIterator();
    3514             : }
    3515             : 
    3516     1822994 : bool Value::IsPromise() const { return Utils::OpenHandle(this)->IsJSPromise(); }
    3517             : 
    3518           5 : bool Value::IsModuleNamespaceObject() const {
    3519           5 :   return Utils::OpenHandle(this)->IsJSModuleNamespace();
    3520             : }
    3521             : 
    3522    13341036 : MaybeLocal<String> Value::ToString(Local<Context> context) const {
    3523             :   auto obj = Utils::OpenHandle(this);
    3524    13341036 :   if (obj->IsString()) return ToApiHandle<String>(obj);
    3525     7516796 :   PREPARE_FOR_EXECUTION(context, Object, ToString, String);
    3526             :   Local<String> result;
    3527             :   has_pending_exception =
    3528     1879199 :       !ToLocal<String>(i::Object::ToString(isolate, obj), &result);
    3529     1879199 :   RETURN_ON_FAILED_EXECUTION(String);
    3530     1879091 :   RETURN_ESCAPED(result);
    3531             : }
    3532             : 
    3533             : 
    3534           0 : Local<String> Value::ToString(Isolate* isolate) const {
    3535           0 :   RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
    3536             : }
    3537             : 
    3538             : 
    3539          15 : MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
    3540             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3541          15 :   if (obj->IsString()) return ToApiHandle<String>(obj);
    3542          60 :   PREPARE_FOR_EXECUTION(context, Object, ToDetailString, String);
    3543             :   Local<String> result =
    3544          15 :       Utils::ToLocal(i::Object::NoSideEffectsToString(isolate, obj));
    3545             :   RETURN_ON_FAILED_EXECUTION(String);
    3546          15 :   RETURN_ESCAPED(result);
    3547             : }
    3548             : 
    3549             : 
    3550         424 : MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
    3551             :   auto obj = Utils::OpenHandle(this);
    3552         424 :   if (obj->IsJSReceiver()) return ToApiHandle<Object>(obj);
    3553         164 :   PREPARE_FOR_EXECUTION(context, Object, ToObject, Object);
    3554             :   Local<Object> result;
    3555             :   has_pending_exception =
    3556          41 :       !ToLocal<Object>(i::Object::ToObject(isolate, obj), &result);
    3557          41 :   RETURN_ON_FAILED_EXECUTION(Object);
    3558          35 :   RETURN_ESCAPED(result);
    3559             : }
    3560             : 
    3561             : 
    3562           0 : Local<v8::Object> Value::ToObject(Isolate* isolate) const {
    3563           0 :   RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
    3564             : }
    3565             : 
    3566          56 : MaybeLocal<BigInt> Value::ToBigInt(Local<Context> context) const {
    3567             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    3568          56 :   if (obj->IsBigInt()) return ToApiHandle<BigInt>(obj);
    3569         128 :   PREPARE_FOR_EXECUTION(context, Object, ToBigInt, BigInt);
    3570             :   Local<BigInt> result;
    3571             :   has_pending_exception =
    3572          32 :       !ToLocal<BigInt>(i::BigInt::FromObject(isolate, obj), &result);
    3573          32 :   RETURN_ON_FAILED_EXECUTION(BigInt);
    3574          16 :   RETURN_ESCAPED(result);
    3575             : }
    3576             : 
    3577       32033 : bool Value::BooleanValue(Isolate* v8_isolate) const {
    3578       64186 :   return Utils::OpenHandle(this)->BooleanValue(
    3579       64126 :       reinterpret_cast<i::Isolate*>(v8_isolate));
    3580             : }
    3581             : 
    3582           0 : MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
    3583           0 :   return ToBoolean(context->GetIsolate());
    3584             : }
    3585             : 
    3586             : 
    3587          60 : Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
    3588             :   auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    3589             :   return ToApiHandle<Boolean>(
    3590          60 :       isolate->factory()->ToBoolean(BooleanValue(v8_isolate)));
    3591             : }
    3592             : 
    3593             : 
    3594        4167 : MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
    3595             :   auto obj = Utils::OpenHandle(this);
    3596        4167 :   if (obj->IsNumber()) return ToApiHandle<Number>(obj);
    3597         536 :   PREPARE_FOR_EXECUTION(context, Object, ToNumber, Number);
    3598             :   Local<Number> result;
    3599             :   has_pending_exception =
    3600         134 :       !ToLocal<Number>(i::Object::ToNumber(isolate, obj), &result);
    3601         134 :   RETURN_ON_FAILED_EXECUTION(Number);
    3602         128 :   RETURN_ESCAPED(result);
    3603             : }
    3604             : 
    3605             : 
    3606           0 : Local<Number> Value::ToNumber(Isolate* isolate) const {
    3607           0 :   RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
    3608             : }
    3609             : 
    3610             : 
    3611           6 : MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
    3612             :   auto obj = Utils::OpenHandle(this);
    3613           6 :   if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
    3614          24 :   PREPARE_FOR_EXECUTION(context, Object, ToInteger, Integer);
    3615             :   Local<Integer> result;
    3616             :   has_pending_exception =
    3617             :       !ToLocal<Integer>(i::Object::ToInteger(isolate, obj), &result);
    3618           6 :   RETURN_ON_FAILED_EXECUTION(Integer);
    3619           0 :   RETURN_ESCAPED(result);
    3620             : }
    3621             : 
    3622             : 
    3623           0 : Local<Integer> Value::ToInteger(Isolate* isolate) const {
    3624           0 :   RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
    3625             : }
    3626             : 
    3627             : 
    3628        2634 : MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
    3629             :   auto obj = Utils::OpenHandle(this);
    3630        2634 :   if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
    3631             :   Local<Int32> result;
    3632        4068 :   PREPARE_FOR_EXECUTION(context, Object, ToInt32, Int32);
    3633             :   has_pending_exception =
    3634             :       !ToLocal<Int32>(i::Object::ToInt32(isolate, obj), &result);
    3635        1017 :   RETURN_ON_FAILED_EXECUTION(Int32);
    3636        1011 :   RETURN_ESCAPED(result);
    3637             : }
    3638             : 
    3639             : 
    3640           0 : Local<Int32> Value::ToInt32(Isolate* isolate) const {
    3641           0 :   RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
    3642             : }
    3643             : 
    3644             : 
    3645          48 : MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
    3646             :   auto obj = Utils::OpenHandle(this);
    3647          48 :   if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
    3648             :   Local<Uint32> result;
    3649         144 :   PREPARE_FOR_EXECUTION(context, Object, ToUint32, Uint32);
    3650             :   has_pending_exception =
    3651          36 :       !ToLocal<Uint32>(i::Object::ToUint32(isolate, obj), &result);
    3652          36 :   RETURN_ON_FAILED_EXECUTION(Uint32);
    3653          30 :   RETURN_ESCAPED(result);
    3654             : }
    3655             : 
    3656         959 : i::Isolate* i::IsolateFromNeverReadOnlySpaceObject(i::Address obj) {
    3657             :   return i::NeverReadOnlySpaceObject::GetIsolate(
    3658         959 :       i::HeapObject::cast(i::Object(obj)));
    3659             : }
    3660             : 
    3661         100 : bool i::ShouldThrowOnError(i::Isolate* isolate) {
    3662         100 :   return i::GetShouldThrow(isolate, Nothing<i::ShouldThrow>()) ==
    3663         100 :          i::ShouldThrow::kThrowOnError;
    3664             : }
    3665             : 
    3666           0 : void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
    3667             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
    3668           0 :   Utils::ApiCheck(isolate != nullptr && !isolate->IsDead(),
    3669             :                   "v8::internal::Internals::CheckInitialized",
    3670             :                   "Isolate is not initialized or V8 has died");
    3671           0 : }
    3672             : 
    3673             : 
    3674           0 : void External::CheckCast(v8::Value* that) {
    3675           0 :   Utils::ApiCheck(that->IsExternal(), "v8::External::Cast",
    3676             :                   "Could not convert to external");
    3677           0 : }
    3678             : 
    3679             : 
    3680           0 : void v8::Object::CheckCast(Value* that) {
    3681             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3682             :   Utils::ApiCheck(obj->IsJSReceiver(), "v8::Object::Cast",
    3683             :                   "Could not convert to object");
    3684           0 : }
    3685             : 
    3686             : 
    3687           0 : void v8::Function::CheckCast(Value* that) {
    3688             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3689             :   Utils::ApiCheck(obj->IsCallable(), "v8::Function::Cast",
    3690             :                   "Could not convert to function");
    3691           0 : }
    3692             : 
    3693             : 
    3694           0 : void v8::Boolean::CheckCast(v8::Value* that) {
    3695             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3696             :   Utils::ApiCheck(obj->IsBoolean(), "v8::Boolean::Cast",
    3697             :                   "Could not convert to boolean");
    3698           0 : }
    3699             : 
    3700             : 
    3701           0 : void v8::Name::CheckCast(v8::Value* that) {
    3702             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3703             :   Utils::ApiCheck(obj->IsName(), "v8::Name::Cast", "Could not convert to name");
    3704           0 : }
    3705             : 
    3706             : 
    3707           0 : void v8::String::CheckCast(v8::Value* that) {
    3708             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3709             :   Utils::ApiCheck(obj->IsString(), "v8::String::Cast",
    3710             :                   "Could not convert to string");
    3711           0 : }
    3712             : 
    3713             : 
    3714           0 : void v8::Symbol::CheckCast(v8::Value* that) {
    3715             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3716             :   Utils::ApiCheck(obj->IsSymbol(), "v8::Symbol::Cast",
    3717             :                   "Could not convert to symbol");
    3718           0 : }
    3719             : 
    3720             : 
    3721           0 : void v8::Private::CheckCast(v8::Data* that) {
    3722             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3723           0 :   Utils::ApiCheck(obj->IsSymbol() &&
    3724             :                   i::Handle<i::Symbol>::cast(obj)->is_private(),
    3725             :                   "v8::Private::Cast",
    3726             :                   "Could not convert to private");
    3727           0 : }
    3728             : 
    3729             : 
    3730           0 : void v8::Number::CheckCast(v8::Value* that) {
    3731             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3732             :   Utils::ApiCheck(obj->IsNumber(),
    3733             :                   "v8::Number::Cast()",
    3734             :                   "Could not convert to number");
    3735           0 : }
    3736             : 
    3737             : 
    3738           0 : void v8::Integer::CheckCast(v8::Value* that) {
    3739             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3740             :   Utils::ApiCheck(obj->IsNumber(), "v8::Integer::Cast",
    3741             :                   "Could not convert to number");
    3742           0 : }
    3743             : 
    3744             : 
    3745           0 : void v8::Int32::CheckCast(v8::Value* that) {
    3746           0 :   Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast",
    3747             :                   "Could not convert to 32-bit signed integer");
    3748           0 : }
    3749             : 
    3750             : 
    3751           0 : void v8::Uint32::CheckCast(v8::Value* that) {
    3752           0 :   Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast",
    3753             :                   "Could not convert to 32-bit unsigned integer");
    3754           0 : }
    3755             : 
    3756           0 : void v8::BigInt::CheckCast(v8::Value* that) {
    3757           0 :   Utils::ApiCheck(that->IsBigInt(), "v8::BigInt::Cast",
    3758             :                   "Could not convert to BigInt");
    3759           0 : }
    3760             : 
    3761           0 : void v8::Array::CheckCast(Value* that) {
    3762             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3763             :   Utils::ApiCheck(obj->IsJSArray(), "v8::Array::Cast",
    3764             :                   "Could not convert to array");
    3765           0 : }
    3766             : 
    3767             : 
    3768           0 : void v8::Map::CheckCast(Value* that) {
    3769             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3770             :   Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast", "Could not convert to Map");
    3771           0 : }
    3772             : 
    3773             : 
    3774           0 : void v8::Set::CheckCast(Value* that) {
    3775             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3776             :   Utils::ApiCheck(obj->IsJSSet(), "v8_Set_Cast", "Could not convert to Set");
    3777           0 : }
    3778             : 
    3779             : 
    3780           0 : void v8::Promise::CheckCast(Value* that) {
    3781           0 :   Utils::ApiCheck(that->IsPromise(), "v8::Promise::Cast",
    3782             :                   "Could not convert to promise");
    3783           0 : }
    3784             : 
    3785             : 
    3786           0 : void v8::Promise::Resolver::CheckCast(Value* that) {
    3787           0 :   Utils::ApiCheck(that->IsPromise(), "v8::Promise::Resolver::Cast",
    3788             :                   "Could not convert to promise resolver");
    3789           0 : }
    3790             : 
    3791             : 
    3792           0 : void v8::Proxy::CheckCast(Value* that) {
    3793           0 :   Utils::ApiCheck(that->IsProxy(), "v8::Proxy::Cast",
    3794             :                   "Could not convert to proxy");
    3795           0 : }
    3796             : 
    3797           0 : void v8::WasmModuleObject::CheckCast(Value* that) {
    3798           0 :   Utils::ApiCheck(that->IsWebAssemblyCompiledModule(),
    3799             :                   "v8::WasmModuleObject::Cast",
    3800             :                   "Could not convert to wasm module object");
    3801           0 : }
    3802             : 
    3803           0 : void v8::ArrayBuffer::CheckCast(Value* that) {
    3804             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3805             :   Utils::ApiCheck(
    3806           0 :       obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
    3807             :       "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
    3808           0 : }
    3809             : 
    3810             : 
    3811           0 : void v8::ArrayBufferView::CheckCast(Value* that) {
    3812             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3813             :   Utils::ApiCheck(obj->IsJSArrayBufferView(),
    3814             :                   "v8::ArrayBufferView::Cast()",
    3815             :                   "Could not convert to ArrayBufferView");
    3816           0 : }
    3817             : 
    3818             : 
    3819           0 : void v8::TypedArray::CheckCast(Value* that) {
    3820             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3821             :   Utils::ApiCheck(obj->IsJSTypedArray(),
    3822             :                   "v8::TypedArray::Cast()",
    3823             :                   "Could not convert to TypedArray");
    3824           0 : }
    3825             : 
    3826             : #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype)                   \
    3827             :   void v8::Type##Array::CheckCast(Value* that) {                              \
    3828             :     i::Handle<i::Object> obj = Utils::OpenHandle(that);                       \
    3829             :     Utils::ApiCheck(                                                          \
    3830             :         obj->IsJSTypedArray() &&                                              \
    3831             :             i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
    3832             :         "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
    3833             :   }
    3834             : 
    3835           0 : TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
    3836             : 
    3837             : #undef CHECK_TYPED_ARRAY_CAST
    3838             : 
    3839             : 
    3840           0 : void v8::DataView::CheckCast(Value* that) {
    3841             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3842             :   Utils::ApiCheck(obj->IsJSDataView(),
    3843             :                   "v8::DataView::Cast()",
    3844             :                   "Could not convert to DataView");
    3845           0 : }
    3846             : 
    3847             : 
    3848           0 : void v8::SharedArrayBuffer::CheckCast(Value* that) {
    3849             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3850             :   Utils::ApiCheck(
    3851           0 :       obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
    3852             :       "v8::SharedArrayBuffer::Cast()",
    3853             :       "Could not convert to SharedArrayBuffer");
    3854           0 : }
    3855             : 
    3856             : 
    3857           0 : void v8::Date::CheckCast(v8::Value* that) {
    3858             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3859             :   Utils::ApiCheck(obj->IsJSDate(), "v8::Date::Cast()",
    3860             :                   "Could not convert to date");
    3861           0 : }
    3862             : 
    3863             : 
    3864           0 : void v8::StringObject::CheckCast(v8::Value* that) {
    3865             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3866             :   Utils::ApiCheck(obj->IsStringWrapper(), "v8::StringObject::Cast()",
    3867             :                   "Could not convert to StringObject");
    3868           0 : }
    3869             : 
    3870             : 
    3871           0 : void v8::SymbolObject::CheckCast(v8::Value* that) {
    3872             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3873             :   Utils::ApiCheck(obj->IsSymbolWrapper(), "v8::SymbolObject::Cast()",
    3874             :                   "Could not convert to SymbolObject");
    3875           0 : }
    3876             : 
    3877             : 
    3878           0 : void v8::NumberObject::CheckCast(v8::Value* that) {
    3879             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3880             :   Utils::ApiCheck(obj->IsNumberWrapper(), "v8::NumberObject::Cast()",
    3881             :                   "Could not convert to NumberObject");
    3882           0 : }
    3883             : 
    3884           0 : void v8::BigIntObject::CheckCast(v8::Value* that) {
    3885             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3886             :   Utils::ApiCheck(obj->IsBigIntWrapper(), "v8::BigIntObject::Cast()",
    3887             :                   "Could not convert to BigIntObject");
    3888           0 : }
    3889             : 
    3890           0 : void v8::BooleanObject::CheckCast(v8::Value* that) {
    3891             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3892             :   Utils::ApiCheck(obj->IsBooleanWrapper(), "v8::BooleanObject::Cast()",
    3893             :                   "Could not convert to BooleanObject");
    3894           0 : }
    3895             : 
    3896             : 
    3897           0 : void v8::RegExp::CheckCast(v8::Value* that) {
    3898             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    3899             :   Utils::ApiCheck(obj->IsJSRegExp(),
    3900             :                   "v8::RegExp::Cast()",
    3901             :                   "Could not convert to regular expression");
    3902           0 : }
    3903             : 
    3904             : 
    3905           0 : Maybe<bool> Value::BooleanValue(Local<Context> context) const {
    3906             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    3907           0 :   return Just(Utils::OpenHandle(this)->BooleanValue(isolate));
    3908             : }
    3909             : 
    3910             : 
    3911       36580 : Maybe<double> Value::NumberValue(Local<Context> context) const {
    3912             :   auto obj = Utils::OpenHandle(this);
    3913       36580 :   if (obj->IsNumber()) return Just(obj->Number());
    3914             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    3915        3129 :   ENTER_V8(isolate, context, Value, NumberValue, Nothing<double>(),
    3916             :            i::HandleScope);
    3917             :   i::Handle<i::Object> num;
    3918        2086 :   has_pending_exception = !i::Object::ToNumber(isolate, obj).ToHandle(&num);
    3919        1043 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
    3920             :   return Just(num->Number());
    3921             : }
    3922             : 
    3923             : 
    3924        2154 : Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
    3925             :   auto obj = Utils::OpenHandle(this);
    3926        2154 :   if (obj->IsNumber()) {
    3927             :     return Just(NumberToInt64(*obj));
    3928             :   }
    3929             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    3930          54 :   ENTER_V8(isolate, context, Value, IntegerValue, Nothing<int64_t>(),
    3931             :            i::HandleScope);
    3932             :   i::Handle<i::Object> num;
    3933             :   has_pending_exception = !i::Object::ToInteger(isolate, obj).ToHandle(&num);
    3934          18 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
    3935             :   return Just(NumberToInt64(*num));
    3936             : }
    3937             : 
    3938             : 
    3939      538898 : Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
    3940             :   auto obj = Utils::OpenHandle(this);
    3941     1077706 :   if (obj->IsNumber()) return Just(NumberToInt32(*obj));
    3942             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    3943         270 :   ENTER_V8(isolate, context, Value, Int32Value, Nothing<int32_t>(),
    3944             :            i::HandleScope);
    3945             :   i::Handle<i::Object> num;
    3946             :   has_pending_exception = !i::Object::ToInt32(isolate, obj).ToHandle(&num);
    3947          90 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
    3948             :   return Just(num->IsSmi() ? i::Smi::ToInt(*num)
    3949          84 :                            : static_cast<int32_t>(num->Number()));
    3950             : }
    3951             : 
    3952             : 
    3953         206 : Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
    3954             :   auto obj = Utils::OpenHandle(this);
    3955         406 :   if (obj->IsNumber()) return Just(NumberToUint32(*obj));
    3956             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    3957          18 :   ENTER_V8(isolate, context, Value, Uint32Value, Nothing<uint32_t>(),
    3958             :            i::HandleScope);
    3959             :   i::Handle<i::Object> num;
    3960          12 :   has_pending_exception = !i::Object::ToUint32(isolate, obj).ToHandle(&num);
    3961           6 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
    3962             :   return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::ToInt(*num))
    3963           0 :                            : static_cast<uint32_t>(num->Number()));
    3964             : }
    3965             : 
    3966             : 
    3967          42 : MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const {
    3968             :   auto self = Utils::OpenHandle(this);
    3969          42 :   if (self->IsSmi()) {
    3970          12 :     if (i::Smi::ToInt(*self) >= 0) return Utils::Uint32ToLocal(self);
    3971           6 :     return Local<Uint32>();
    3972             :   }
    3973         120 :   PREPARE_FOR_EXECUTION(context, Object, ToArrayIndex, Uint32);
    3974             :   i::Handle<i::Object> string_obj;
    3975             :   has_pending_exception =
    3976          60 :       !i::Object::ToString(isolate, self).ToHandle(&string_obj);
    3977          30 :   RETURN_ON_FAILED_EXECUTION(Uint32);
    3978             :   i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
    3979             :   uint32_t index;
    3980          30 :   if (str->AsArrayIndex(&index)) {
    3981             :     i::Handle<i::Object> value;
    3982          12 :     if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
    3983             :       value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
    3984             :     } else {
    3985           6 :       value = isolate->factory()->NewNumber(index);
    3986             :     }
    3987          12 :     RETURN_ESCAPED(Utils::Uint32ToLocal(value));
    3988             :   }
    3989          18 :   return Local<Uint32>();
    3990             : }
    3991             : 
    3992             : 
    3993      168374 : Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const {
    3994             :   i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
    3995      168374 :   auto self = Utils::OpenHandle(this);
    3996      168374 :   auto other = Utils::OpenHandle(*that);
    3997      168374 :   return i::Object::Equals(isolate, self, other);
    3998             : }
    3999             : 
    4000             : 
    4001        1544 : bool Value::StrictEquals(Local<Value> that) const {
    4002             :   auto self = Utils::OpenHandle(this);
    4003             :   auto other = Utils::OpenHandle(*that);
    4004        1544 :   return self->StrictEquals(*other);
    4005             : }
    4006             : 
    4007             : 
    4008      123304 : bool Value::SameValue(Local<Value> that) const {
    4009             :   auto self = Utils::OpenHandle(this);
    4010             :   auto other = Utils::OpenHandle(*that);
    4011      123304 :   return self->SameValue(*other);
    4012             : }
    4013             : 
    4014          50 : Local<String> Value::TypeOf(v8::Isolate* external_isolate) {
    4015             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
    4016             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    4017          50 :   LOG_API(isolate, Value, TypeOf);
    4018         100 :   return Utils::ToLocal(i::Object::TypeOf(isolate, Utils::OpenHandle(this)));
    4019             : }
    4020             : 
    4021          82 : Maybe<bool> Value::InstanceOf(v8::Local<v8::Context> context,
    4022             :                               v8::Local<v8::Object> object) {
    4023             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4024         246 :   ENTER_V8(isolate, context, Value, InstanceOf, Nothing<bool>(),
    4025             :            i::HandleScope);
    4026          82 :   auto left = Utils::OpenHandle(this);
    4027             :   auto right = Utils::OpenHandle(*object);
    4028             :   i::Handle<i::Object> result;
    4029             :   has_pending_exception =
    4030         164 :       !i::Object::InstanceOf(isolate, left, right).ToHandle(&result);
    4031          82 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4032             :   return Just(result->IsTrue(isolate));
    4033             : }
    4034             : 
    4035      188530 : Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
    4036             :                             v8::Local<Value> key, v8::Local<Value> value) {
    4037             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4038      565590 :   ENTER_V8(isolate, context, Object, Set, Nothing<bool>(), i::HandleScope);
    4039             :   auto self = Utils::OpenHandle(this);
    4040      188530 :   auto key_obj = Utils::OpenHandle(*key);
    4041      188530 :   auto value_obj = Utils::OpenHandle(*value);
    4042             :   has_pending_exception =
    4043      377060 :       i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
    4044             :                                     i::StoreOrigin::kMaybeKeyed,
    4045      188530 :                                     Just(i::ShouldThrow::kDontThrow))
    4046             :           .is_null();
    4047      188530 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4048             :   return Just(true);
    4049             : }
    4050             : 
    4051             : 
    4052           0 : bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
    4053           0 :   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
    4054           0 :   return Set(context, key, value).FromMaybe(false);
    4055             : }
    4056             : 
    4057             : 
    4058       10988 : Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
    4059             :                             v8::Local<Value> value) {
    4060             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4061       32964 :   ENTER_V8(isolate, context, Object, Set, Nothing<bool>(), i::HandleScope);
    4062             :   auto self = Utils::OpenHandle(this);
    4063       10988 :   auto value_obj = Utils::OpenHandle(*value);
    4064       21976 :   has_pending_exception = i::Object::SetElement(isolate, self, index, value_obj,
    4065       10988 :                                                 i::ShouldThrow::kDontThrow)
    4066             :                               .is_null();
    4067       10988 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4068             :   return Just(true);
    4069             : }
    4070             : 
    4071             : 
    4072           0 : bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
    4073           0 :   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
    4074           0 :   return Set(context, index, value).FromMaybe(false);
    4075             : }
    4076             : 
    4077             : 
    4078       18319 : Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
    4079             :                                            v8::Local<Name> key,
    4080             :                                            v8::Local<Value> value) {
    4081             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4082       54957 :   ENTER_V8(isolate, context, Object, CreateDataProperty, Nothing<bool>(),
    4083             :            i::HandleScope);
    4084       18319 :   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
    4085       18319 :   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
    4086       18319 :   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
    4087             : 
    4088             :   Maybe<bool> result = i::JSReceiver::CreateDataProperty(
    4089       18319 :       isolate, self, key_obj, value_obj, Just(i::kDontThrow));
    4090             :   has_pending_exception = result.IsNothing();
    4091       18319 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4092       18314 :   return result;
    4093             : }
    4094             : 
    4095             : 
    4096       11755 : Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
    4097             :                                            uint32_t index,
    4098             :                                            v8::Local<Value> value) {
    4099             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4100       35265 :   ENTER_V8(isolate, context, Object, CreateDataProperty, Nothing<bool>(),
    4101             :            i::HandleScope);
    4102             :   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
    4103       11755 :   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
    4104             : 
    4105             :   i::LookupIterator it(isolate, self, index, self, i::LookupIterator::OWN);
    4106             :   Maybe<bool> result =
    4107       11755 :       i::JSReceiver::CreateDataProperty(&it, value_obj, Just(i::kDontThrow));
    4108             :   has_pending_exception = result.IsNothing();
    4109       11755 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4110       11755 :   return result;
    4111             : }
    4112             : 
    4113             : struct v8::PropertyDescriptor::PrivateData {
    4114             :   PrivateData() : desc() {}
    4115             :   i::PropertyDescriptor desc;
    4116             : };
    4117             : 
    4118         216 : v8::PropertyDescriptor::PropertyDescriptor() : private_(new PrivateData()) {}
    4119             : 
    4120             : // DataDescriptor
    4121          83 : v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value)
    4122         166 :     : private_(new PrivateData()) {
    4123             :   private_->desc.set_value(Utils::OpenHandle(*value, true));
    4124          83 : }
    4125             : 
    4126             : // DataDescriptor with writable field
    4127          26 : v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value,
    4128             :                                            bool writable)
    4129          52 :     : private_(new PrivateData()) {
    4130             :   private_->desc.set_value(Utils::OpenHandle(*value, true));
    4131             :   private_->desc.set_writable(writable);
    4132          26 : }
    4133             : 
    4134             : // AccessorDescriptor
    4135          68 : v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> get,
    4136             :                                            v8::Local<v8::Value> set)
    4137         136 :     : private_(new PrivateData()) {
    4138             :   DCHECK(get.IsEmpty() || get->IsUndefined() || get->IsFunction());
    4139             :   DCHECK(set.IsEmpty() || set->IsUndefined() || set->IsFunction());
    4140             :   private_->desc.set_get(Utils::OpenHandle(*get, true));
    4141             :   private_->desc.set_set(Utils::OpenHandle(*set, true));
    4142          68 : }
    4143             : 
    4144         285 : v8::PropertyDescriptor::~PropertyDescriptor() { delete private_; }
    4145             : 
    4146          32 : v8::Local<Value> v8::PropertyDescriptor::value() const {
    4147             :   DCHECK(private_->desc.has_value());
    4148          32 :   return Utils::ToLocal(private_->desc.value());
    4149             : }
    4150             : 
    4151          22 : v8::Local<Value> v8::PropertyDescriptor::get() const {
    4152             :   DCHECK(private_->desc.has_get());
    4153          22 :   return Utils::ToLocal(private_->desc.get());
    4154             : }
    4155             : 
    4156          22 : v8::Local<Value> v8::PropertyDescriptor::set() const {
    4157             :   DCHECK(private_->desc.has_set());
    4158          22 :   return Utils::ToLocal(private_->desc.set());
    4159             : }
    4160             : 
    4161          69 : bool v8::PropertyDescriptor::has_value() const {
    4162         138 :   return private_->desc.has_value();
    4163             : }
    4164          69 : bool v8::PropertyDescriptor::has_get() const {
    4165         138 :   return private_->desc.has_get();
    4166             : }
    4167          69 : bool v8::PropertyDescriptor::has_set() const {
    4168         138 :   return private_->desc.has_set();
    4169             : }
    4170             : 
    4171          16 : bool v8::PropertyDescriptor::writable() const {
    4172             :   DCHECK(private_->desc.has_writable());
    4173          32 :   return private_->desc.writable();
    4174             : }
    4175             : 
    4176          69 : bool v8::PropertyDescriptor::has_writable() const {
    4177         138 :   return private_->desc.has_writable();
    4178             : }
    4179             : 
    4180          37 : void v8::PropertyDescriptor::set_enumerable(bool enumerable) {
    4181          37 :   private_->desc.set_enumerable(enumerable);
    4182          37 : }
    4183             : 
    4184          17 : bool v8::PropertyDescriptor::enumerable() const {
    4185             :   DCHECK(private_->desc.has_enumerable());
    4186          34 :   return private_->desc.enumerable();
    4187             : }
    4188             : 
    4189          63 : bool v8::PropertyDescriptor::has_enumerable() const {
    4190         126 :   return private_->desc.has_enumerable();
    4191             : }
    4192             : 
    4193          38 : void v8::PropertyDescriptor::set_configurable(bool configurable) {
    4194          38 :   private_->desc.set_configurable(configurable);
    4195          38 : }
    4196             : 
    4197          32 : bool v8::PropertyDescriptor::configurable() const {
    4198             :   DCHECK(private_->desc.has_configurable());
    4199          64 :   return private_->desc.configurable();
    4200             : }
    4201             : 
    4202          63 : bool v8::PropertyDescriptor::has_configurable() const {
    4203         126 :   return private_->desc.has_configurable();
    4204             : }
    4205             : 
    4206        3336 : Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
    4207             :                                           v8::Local<Name> key,
    4208             :                                           v8::Local<Value> value,
    4209             :                                           v8::PropertyAttribute attributes) {
    4210             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4211             :   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
    4212             :   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
    4213             :   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
    4214             : 
    4215             :   i::PropertyDescriptor desc;
    4216        3336 :   desc.set_writable(!(attributes & v8::ReadOnly));
    4217        3336 :   desc.set_enumerable(!(attributes & v8::DontEnum));
    4218        3336 :   desc.set_configurable(!(attributes & v8::DontDelete));
    4219             :   desc.set_value(value_obj);
    4220             : 
    4221        3336 :   if (self->IsJSProxy()) {
    4222           0 :     ENTER_V8(isolate, context, Object, DefineOwnProperty, Nothing<bool>(),
    4223             :              i::HandleScope);
    4224             :     Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
    4225           0 :         isolate, self, key_obj, &desc, Just(i::kDontThrow));
    4226             :     // Even though we said kDontThrow, there might be accessors that do throw.
    4227             :     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4228           0 :     return success;
    4229             :   } else {
    4230             :     // If it's not a JSProxy, i::JSReceiver::DefineOwnProperty should never run
    4231             :     // a script.
    4232       10008 :     ENTER_V8_NO_SCRIPT(isolate, context, Object, DefineOwnProperty,
    4233             :                        Nothing<bool>(), i::HandleScope);
    4234             :     Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
    4235        3336 :         isolate, self, key_obj, &desc, Just(i::kDontThrow));
    4236             :     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4237        3336 :     return success;
    4238             :   }
    4239             : }
    4240             : 
    4241         126 : Maybe<bool> v8::Object::DefineProperty(v8::Local<v8::Context> context,
    4242             :                                        v8::Local<Name> key,
    4243             :                                        PropertyDescriptor& descriptor) {
    4244             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4245         378 :   ENTER_V8(isolate, context, Object, DefineOwnProperty, Nothing<bool>(),
    4246             :            i::HandleScope);
    4247         126 :   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
    4248             :   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
    4249             : 
    4250             :   Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
    4251             :       isolate, self, key_obj, &descriptor.get_private()->desc,
    4252         252 :       Just(i::kDontThrow));
    4253             :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4254         126 :   return success;
    4255             : }
    4256             : 
    4257      241048 : Maybe<bool> v8::Object::SetPrivate(Local<Context> context, Local<Private> key,
    4258             :                                    Local<Value> value) {
    4259             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4260      723144 :   ENTER_V8_NO_SCRIPT(isolate, context, Object, SetPrivate, Nothing<bool>(),
    4261             :                      i::HandleScope);
    4262             :   auto self = Utils::OpenHandle(this);
    4263             :   auto key_obj = Utils::OpenHandle(reinterpret_cast<Name*>(*key));
    4264             :   auto value_obj = Utils::OpenHandle(*value);
    4265      241048 :   if (self->IsJSProxy()) {
    4266             :     i::PropertyDescriptor desc;
    4267             :     desc.set_writable(true);
    4268             :     desc.set_enumerable(false);
    4269             :     desc.set_configurable(true);
    4270             :     desc.set_value(value_obj);
    4271             :     return i::JSProxy::SetPrivateSymbol(
    4272             :         isolate, i::Handle<i::JSProxy>::cast(self),
    4273          18 :         i::Handle<i::Symbol>::cast(key_obj), &desc, Just(i::kDontThrow));
    4274             :   }
    4275             :   auto js_object = i::Handle<i::JSObject>::cast(self);
    4276             :   i::LookupIterator it(js_object, key_obj, js_object);
    4277      482060 :   has_pending_exception = i::JSObject::DefineOwnPropertyIgnoreAttributes(
    4278             :                               &it, value_obj, i::DONT_ENUM)
    4279             :                               .is_null();
    4280      241030 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4281             :   return Just(true);
    4282             : }
    4283             : 
    4284             : 
    4285      421097 : MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
    4286             :                                   Local<Value> key) {
    4287     1684388 :   PREPARE_FOR_EXECUTION(context, Object, Get, Value);
    4288             :   auto self = Utils::OpenHandle(this);
    4289      421097 :   auto key_obj = Utils::OpenHandle(*key);
    4290             :   i::Handle<i::Object> result;
    4291             :   has_pending_exception =
    4292      842194 :       !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
    4293      421097 :   RETURN_ON_FAILED_EXECUTION(Value);
    4294      421031 :   RETURN_ESCAPED(Utils::ToLocal(result));
    4295             : }
    4296             : 
    4297             : 
    4298           0 : Local<Value> v8::Object::Get(v8::Local<Value> key) {
    4299           0 :   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
    4300           0 :   RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
    4301             : }
    4302             : 
    4303             : 
    4304      158126 : MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
    4305      632504 :   PREPARE_FOR_EXECUTION(context, Object, Get, Value);
    4306      158126 :   auto self = Utils::OpenHandle(this);
    4307             :   i::Handle<i::Object> result;
    4308             :   has_pending_exception =
    4309      316252 :       !i::JSReceiver::GetElement(isolate, self, index).ToHandle(&result);
    4310      158126 :   RETURN_ON_FAILED_EXECUTION(Value);
    4311      158107 :   RETURN_ESCAPED(Utils::ToLocal(result));
    4312             : }
    4313             : 
    4314             : 
    4315           0 : Local<Value> v8::Object::Get(uint32_t index) {
    4316           0 :   auto context = ContextFromNeverReadOnlySpaceObject(Utils::OpenHandle(this));
    4317           0 :   RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
    4318             : }
    4319             : 
    4320             : 
    4321        2462 : MaybeLocal<Value> v8::Object::GetPrivate(Local<Context> context,
    4322             :                                          Local<Private> key) {
    4323        2462 :   return Get(context, Local<Value>(reinterpret_cast<Value*>(*key)));
    4324             : }
    4325             : 
    4326             : 
    4327          58 : Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes(
    4328             :     Local<Context> context, Local<Value> key) {
    4329             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4330         174 :   ENTER_V8(isolate, context, Object, GetPropertyAttributes,
    4331             :            Nothing<PropertyAttribute>(), i::HandleScope);
    4332          58 :   auto self = Utils::OpenHandle(this);
    4333             :   auto key_obj = Utils::OpenHandle(*key);
    4334          58 :   if (!key_obj->IsName()) {
    4335             :     has_pending_exception =
    4336          24 :         !i::Object::ToString(isolate, key_obj).ToHandle(&key_obj);
    4337          12 :     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
    4338             :   }
    4339          52 :   auto key_name = i::Handle<i::Name>::cast(key_obj);
    4340          52 :   auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
    4341             :   has_pending_exception = result.IsNothing();
    4342          52 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
    4343          52 :   if (result.FromJust() == i::ABSENT) {
    4344             :     return Just(static_cast<PropertyAttribute>(i::NONE));
    4345             :   }
    4346             :   return Just(static_cast<PropertyAttribute>(result.FromJust()));
    4347             : }
    4348             : 
    4349             : 
    4350        7730 : MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context,
    4351             :                                                        Local<Name> key) {
    4352       30920 :   PREPARE_FOR_EXECUTION(context, Object, GetOwnPropertyDescriptor, Value);
    4353        7730 :   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
    4354             :   i::Handle<i::Name> key_name = Utils::OpenHandle(*key);
    4355             : 
    4356             :   i::PropertyDescriptor desc;
    4357             :   Maybe<bool> found =
    4358        7730 :       i::JSReceiver::GetOwnPropertyDescriptor(isolate, obj, key_name, &desc);
    4359             :   has_pending_exception = found.IsNothing();
    4360        7730 :   RETURN_ON_FAILED_EXECUTION(Value);
    4361        7730 :   if (!found.FromJust()) {
    4362           5 :     return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    4363             :   }
    4364       15450 :   RETURN_ESCAPED(Utils::ToLocal(desc.ToObject(isolate)));
    4365             : }
    4366             : 
    4367             : 
    4368      263875 : Local<Value> v8::Object::GetPrototype() {
    4369             :   auto isolate = Utils::OpenHandle(this)->GetIsolate();
    4370      263875 :   auto self = Utils::OpenHandle(this);
    4371      263875 :   i::PrototypeIterator iter(isolate, self);
    4372      263875 :   return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
    4373             : }
    4374             : 
    4375             : 
    4376       11193 : Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
    4377             :                                      Local<Value> value) {
    4378             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4379       33579 :   ENTER_V8(isolate, context, Object, SetPrototype, Nothing<bool>(),
    4380             :            i::HandleScope);
    4381       11193 :   auto self = Utils::OpenHandle(this);
    4382       11193 :   auto value_obj = Utils::OpenHandle(*value);
    4383             :   // We do not allow exceptions thrown while setting the prototype
    4384             :   // to propagate outside.
    4385       22386 :   TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
    4386             :   auto result =
    4387       11193 :       i::JSReceiver::SetPrototype(self, value_obj, false, i::kThrowOnError);
    4388             :   has_pending_exception = result.IsNothing();
    4389       11193 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4390             :   return Just(true);
    4391             : }
    4392             : 
    4393             : 
    4394          54 : Local<Object> v8::Object::FindInstanceInPrototypeChain(
    4395             :     v8::Local<FunctionTemplate> tmpl) {
    4396             :   auto self = Utils::OpenHandle(this);
    4397             :   auto isolate = self->GetIsolate();
    4398             :   i::PrototypeIterator iter(isolate, *self, i::kStartAtReceiver);
    4399          54 :   auto tmpl_info = *Utils::OpenHandle(*tmpl);
    4400         108 :   while (!tmpl_info->IsTemplateFor(iter.GetCurrent<i::JSObject>())) {
    4401          72 :     iter.Advance();
    4402          72 :     if (iter.IsAtEnd()) return Local<Object>();
    4403          54 :     if (!iter.GetCurrent()->IsJSObject()) return Local<Object>();
    4404             :   }
    4405             :   // IsTemplateFor() ensures that iter.GetCurrent() can't be a Proxy here.
    4406             :   return Utils::ToLocal(i::handle(iter.GetCurrent<i::JSObject>(), isolate));
    4407             : }
    4408             : 
    4409        5907 : MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
    4410             :   return GetPropertyNames(
    4411             :       context, v8::KeyCollectionMode::kIncludePrototypes,
    4412             :       static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS),
    4413        5907 :       v8::IndexFilter::kIncludeIndices);
    4414             : }
    4415             : 
    4416        6618 : MaybeLocal<Array> v8::Object::GetPropertyNames(
    4417             :     Local<Context> context, KeyCollectionMode mode,
    4418             :     PropertyFilter property_filter, IndexFilter index_filter,
    4419             :     KeyConversionMode key_conversion) {
    4420       26472 :   PREPARE_FOR_EXECUTION(context, Object, GetPropertyNames, Array);
    4421        6618 :   auto self = Utils::OpenHandle(this);
    4422             :   i::Handle<i::FixedArray> value;
    4423             :   i::KeyAccumulator accumulator(
    4424             :       isolate, static_cast<i::KeyCollectionMode>(mode),
    4425             :       static_cast<i::PropertyFilter>(property_filter));
    4426        6618 :   accumulator.set_skip_indices(index_filter == IndexFilter::kSkipIndices);
    4427       13236 :   has_pending_exception = accumulator.CollectKeys(self, self).IsNothing();
    4428        6618 :   RETURN_ON_FAILED_EXECUTION(Array);
    4429             :   value =
    4430        6618 :       accumulator.GetKeys(static_cast<i::GetKeysConversion>(key_conversion));
    4431             :   DCHECK(self->map()->EnumLength() == i::kInvalidEnumCacheSentinel ||
    4432             :          self->map()->EnumLength() == 0 ||
    4433             :          self->map()->instance_descriptors()->enum_cache()->keys() != *value);
    4434             :   auto result = isolate->factory()->NewJSArrayWithElements(value);
    4435        6618 :   RETURN_ESCAPED(Utils::ToLocal(result));
    4436             : }
    4437             : 
    4438         591 : MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
    4439             :   return GetOwnPropertyNames(
    4440         591 :       context, static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS));
    4441             : }
    4442             : 
    4443          24 : MaybeLocal<Array> v8::Object::GetOwnPropertyNames(
    4444             :     Local<Context> context, PropertyFilter filter,
    4445             :     KeyConversionMode key_conversion) {
    4446             :   return GetPropertyNames(context, KeyCollectionMode::kOwnOnly, filter,
    4447         615 :                           v8::IndexFilter::kIncludeIndices, key_conversion);
    4448             : }
    4449             : 
    4450         468 : MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) {
    4451        1872 :   PREPARE_FOR_EXECUTION(context, Object, ObjectProtoToString, String);
    4452             :   auto self = Utils::OpenHandle(this);
    4453             :   Local<Value> result;
    4454             :   has_pending_exception =
    4455        1404 :       !ToLocal<Value>(i::Execution::Call(isolate, isolate->object_to_string(),
    4456             :                                          self, 0, nullptr),
    4457             :                       &result);
    4458         468 :   RETURN_ON_FAILED_EXECUTION(String);
    4459         458 :   RETURN_ESCAPED(Local<String>::Cast(result));
    4460             : }
    4461             : 
    4462             : 
    4463     3631994 : Local<String> v8::Object::GetConstructorName() {
    4464     3631994 :   auto self = Utils::OpenHandle(this);
    4465     3631994 :   i::Handle<i::String> name = i::JSReceiver::GetConstructorName(self);
    4466     3631994 :   return Utils::ToLocal(name);
    4467             : }
    4468             : 
    4469           6 : Maybe<bool> v8::Object::SetIntegrityLevel(Local<Context> context,
    4470             :                                           IntegrityLevel level) {
    4471             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4472          18 :   ENTER_V8(isolate, context, Object, SetIntegrityLevel, Nothing<bool>(),
    4473             :            i::HandleScope);
    4474           6 :   auto self = Utils::OpenHandle(this);
    4475             :   i::JSReceiver::IntegrityLevel i_level =
    4476           6 :       level == IntegrityLevel::kFrozen ? i::FROZEN : i::SEALED;
    4477             :   Maybe<bool> result =
    4478           6 :       i::JSReceiver::SetIntegrityLevel(self, i_level, i::kThrowOnError);
    4479             :   has_pending_exception = result.IsNothing();
    4480           6 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4481           5 :   return result;
    4482             : }
    4483             : 
    4484        7991 : Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
    4485             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4486             :   auto self = Utils::OpenHandle(this);
    4487        7991 :   auto key_obj = Utils::OpenHandle(*key);
    4488        7991 :   if (self->IsJSProxy()) {
    4489           0 :     ENTER_V8(isolate, context, Object, Delete, Nothing<bool>(), i::HandleScope);
    4490             :     Maybe<bool> result = i::Runtime::DeleteObjectProperty(
    4491           0 :         isolate, self, key_obj, i::LanguageMode::kSloppy);
    4492             :     has_pending_exception = result.IsNothing();
    4493           0 :     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4494           0 :     return result;
    4495             :   } else {
    4496             :     // If it's not a JSProxy, i::Runtime::DeleteObjectProperty should never run
    4497             :     // a script.
    4498       23973 :     ENTER_V8_NO_SCRIPT(isolate, context, Object, Delete, Nothing<bool>(),
    4499             :                        i::HandleScope);
    4500             :     Maybe<bool> result = i::Runtime::DeleteObjectProperty(
    4501        7991 :         isolate, self, key_obj, i::LanguageMode::kSloppy);
    4502             :     has_pending_exception = result.IsNothing();
    4503        7991 :     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4504        7991 :     return result;
    4505             :   }
    4506             : }
    4507             : 
    4508          42 : Maybe<bool> v8::Object::DeletePrivate(Local<Context> context,
    4509             :                                       Local<Private> key) {
    4510             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4511             :   // In case of private symbols, i::Runtime::DeleteObjectProperty does not run
    4512             :   // any author script.
    4513         126 :   ENTER_V8_NO_SCRIPT(isolate, context, Object, Delete, Nothing<bool>(),
    4514             :                      i::HandleScope);
    4515          42 :   auto self = Utils::OpenHandle(this);
    4516          42 :   auto key_obj = Utils::OpenHandle(*key);
    4517             :   Maybe<bool> result = i::Runtime::DeleteObjectProperty(
    4518          42 :       isolate, self, key_obj, i::LanguageMode::kSloppy);
    4519             :   has_pending_exception = result.IsNothing();
    4520          42 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4521          42 :   return result;
    4522             : }
    4523             : 
    4524        9130 : Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) {
    4525             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4526       27390 :   ENTER_V8(isolate, context, Object, Has, Nothing<bool>(), i::HandleScope);
    4527        9130 :   auto self = Utils::OpenHandle(this);
    4528             :   auto key_obj = Utils::OpenHandle(*key);
    4529             :   Maybe<bool> maybe = Nothing<bool>();
    4530             :   // Check if the given key is an array index.
    4531        9130 :   uint32_t index = 0;
    4532       18260 :   if (key_obj->ToArrayIndex(&index)) {
    4533           0 :     maybe = i::JSReceiver::HasElement(self, index);
    4534             :   } else {
    4535             :     // Convert the key to a name - possibly by calling back into JavaScript.
    4536             :     i::Handle<i::Name> name;
    4537       18260 :     if (i::Object::ToName(isolate, key_obj).ToHandle(&name)) {
    4538        9130 :       maybe = i::JSReceiver::HasProperty(self, name);
    4539             :     }
    4540             :   }
    4541             :   has_pending_exception = maybe.IsNothing();
    4542        9130 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4543        9130 :   return maybe;
    4544             : }
    4545             : 
    4546             : 
    4547       79707 : Maybe<bool> v8::Object::HasPrivate(Local<Context> context, Local<Private> key) {
    4548       79707 :   return HasOwnProperty(context, Local<Name>(reinterpret_cast<Name*>(*key)));
    4549             : }
    4550             : 
    4551             : 
    4552          10 : Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
    4553             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4554          30 :   ENTER_V8(isolate, context, Object, Delete, Nothing<bool>(), i::HandleScope);
    4555          10 :   auto self = Utils::OpenHandle(this);
    4556          10 :   Maybe<bool> result = i::JSReceiver::DeleteElement(self, index);
    4557             :   has_pending_exception = result.IsNothing();
    4558          10 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4559           5 :   return result;
    4560             : }
    4561             : 
    4562             : 
    4563          30 : Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
    4564             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4565          90 :   ENTER_V8(isolate, context, Object, Has, Nothing<bool>(), i::HandleScope);
    4566          30 :   auto self = Utils::OpenHandle(this);
    4567          30 :   auto maybe = i::JSReceiver::HasElement(self, index);
    4568             :   has_pending_exception = maybe.IsNothing();
    4569          30 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4570          30 :   return maybe;
    4571             : }
    4572             : 
    4573             : template <typename Getter, typename Setter, typename Data>
    4574        7910 : static Maybe<bool> ObjectSetAccessor(
    4575             :     Local<Context> context, Object* self, Local<Name> name, Getter getter,
    4576             :     Setter setter, Data data, AccessControl settings,
    4577             :     PropertyAttribute attributes, bool is_special_data_property,
    4578             :     bool replace_on_access, SideEffectType getter_side_effect_type,
    4579             :     SideEffectType setter_side_effect_type) {
    4580             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4581       23730 :   ENTER_V8_NO_SCRIPT(isolate, context, Object, SetAccessor, Nothing<bool>(),
    4582             :                      i::HandleScope);
    4583        7910 :   if (!Utils::OpenHandle(self)->IsJSObject()) return Just(false);
    4584             :   i::Handle<i::JSObject> obj =
    4585             :       i::Handle<i::JSObject>::cast(Utils::OpenHandle(self));
    4586             :   v8::Local<AccessorSignature> signature;
    4587             :   i::Handle<i::AccessorInfo> info =
    4588        7910 :       MakeAccessorInfo(isolate, name, getter, setter, data, settings, signature,
    4589        7910 :                        is_special_data_property, replace_on_access);
    4590        7910 :   info->set_getter_side_effect_type(getter_side_effect_type);
    4591        7910 :   info->set_setter_side_effect_type(setter_side_effect_type);
    4592        7910 :   if (info.is_null()) return Nothing<bool>();
    4593        7910 :   bool fast = obj->HasFastProperties();
    4594             :   i::Handle<i::Object> result;
    4595             : 
    4596             :   i::Handle<i::Name> accessor_name(info->name(), isolate);
    4597             :   i::PropertyAttributes attrs = static_cast<i::PropertyAttributes>(attributes);
    4598             :   has_pending_exception =
    4599             :       !i::JSObject::SetAccessor(obj, accessor_name, info, attrs)
    4600       15820 :            .ToHandle(&result);
    4601        7910 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4602        7905 :   if (result->IsUndefined(isolate)) return Just(false);
    4603        7880 :   if (fast) {
    4604        7868 :     i::JSObject::MigrateSlowToFast(obj, 0, "APISetAccessor");
    4605             :   }
    4606             :   return Just(true);
    4607             : }
    4608             : 
    4609        7874 : Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name,
    4610             :                                 AccessorNameGetterCallback getter,
    4611             :                                 AccessorNameSetterCallback setter,
    4612             :                                 MaybeLocal<Value> data, AccessControl settings,
    4613             :                                 PropertyAttribute attribute,
    4614             :                                 SideEffectType getter_side_effect_type,
    4615             :                                 SideEffectType setter_side_effect_type) {
    4616             :   return ObjectSetAccessor(context, this, name, getter, setter,
    4617             :                            data.FromMaybe(Local<Value>()), settings, attribute,
    4618             :                            i::FLAG_disable_old_api_accessors, false,
    4619       15748 :                            getter_side_effect_type, setter_side_effect_type);
    4620             : }
    4621             : 
    4622             : 
    4623      328225 : void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
    4624             :                                  Local<Function> setter,
    4625             :                                  PropertyAttribute attribute,
    4626             :                                  AccessControl settings) {
    4627             :   // TODO(verwaest): Remove |settings|.
    4628             :   DCHECK_EQ(v8::DEFAULT, settings);
    4629             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    4630             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    4631             :   i::HandleScope scope(isolate);
    4632             :   auto self = Utils::OpenHandle(this);
    4633      328225 :   if (!self->IsJSObject()) return;
    4634             :   i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
    4635             :   i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
    4636      328225 :   if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
    4637             :   i::JSObject::DefineAccessor(i::Handle<i::JSObject>::cast(self),
    4638             :                               v8::Utils::OpenHandle(*name), getter_i, setter_i,
    4639      328225 :                               static_cast<i::PropertyAttributes>(attribute));
    4640             : }
    4641             : 
    4642          16 : Maybe<bool> Object::SetNativeDataProperty(
    4643             :     v8::Local<v8::Context> context, v8::Local<Name> name,
    4644             :     AccessorNameGetterCallback getter, AccessorNameSetterCallback setter,
    4645             :     v8::Local<Value> data, PropertyAttribute attributes,
    4646             :     SideEffectType getter_side_effect_type,
    4647             :     SideEffectType setter_side_effect_type) {
    4648             :   return ObjectSetAccessor(context, this, name, getter, setter, data, DEFAULT,
    4649             :                            attributes, true, false, getter_side_effect_type,
    4650          16 :                            setter_side_effect_type);
    4651             : }
    4652             : 
    4653          20 : Maybe<bool> Object::SetLazyDataProperty(
    4654             :     v8::Local<v8::Context> context, v8::Local<Name> name,
    4655             :     AccessorNameGetterCallback getter, v8::Local<Value> data,
    4656             :     PropertyAttribute attributes, SideEffectType getter_side_effect_type,
    4657             :     SideEffectType setter_side_effect_type) {
    4658             :   return ObjectSetAccessor(context, this, name, getter,
    4659             :                            static_cast<AccessorNameSetterCallback>(nullptr),
    4660             :                            data, DEFAULT, attributes, true, true,
    4661          20 :                            getter_side_effect_type, setter_side_effect_type);
    4662             : }
    4663             : 
    4664       87066 : Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
    4665             :                                        Local<Name> key) {
    4666             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4667      261198 :   ENTER_V8(isolate, context, Object, HasOwnProperty, Nothing<bool>(),
    4668             :            i::HandleScope);
    4669       87066 :   auto self = Utils::OpenHandle(this);
    4670       87066 :   auto key_val = Utils::OpenHandle(*key);
    4671       87066 :   auto result = i::JSReceiver::HasOwnProperty(self, key_val);
    4672             :   has_pending_exception = result.IsNothing();
    4673       87066 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4674       87061 :   return result;
    4675             : }
    4676             : 
    4677          25 : Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context, uint32_t index) {
    4678             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4679          75 :   ENTER_V8(isolate, context, Object, HasOwnProperty, Nothing<bool>(),
    4680             :            i::HandleScope);
    4681          25 :   auto self = Utils::OpenHandle(this);
    4682          25 :   auto result = i::JSReceiver::HasOwnProperty(self, index);
    4683             :   has_pending_exception = result.IsNothing();
    4684          25 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4685          25 :   return result;
    4686             : }
    4687             : 
    4688        5847 : Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context,
    4689             :                                              Local<Name> key) {
    4690             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4691       17541 :   ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealNamedProperty,
    4692             :                      Nothing<bool>(), i::HandleScope);
    4693             :   auto self = Utils::OpenHandle(this);
    4694        5847 :   if (!self->IsJSObject()) return Just(false);
    4695        5842 :   auto key_val = Utils::OpenHandle(*key);
    4696             :   auto result = i::JSObject::HasRealNamedProperty(
    4697        5842 :       i::Handle<i::JSObject>::cast(self), key_val);
    4698             :   has_pending_exception = result.IsNothing();
    4699        5842 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4700        5837 :   return result;
    4701             : }
    4702             : 
    4703             : 
    4704          17 : Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
    4705             :                                                uint32_t index) {
    4706             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4707          51 :   ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealIndexedProperty,
    4708             :                      Nothing<bool>(), i::HandleScope);
    4709             :   auto self = Utils::OpenHandle(this);
    4710          17 :   if (!self->IsJSObject()) return Just(false);
    4711             :   auto result = i::JSObject::HasRealElementProperty(
    4712          17 :       i::Handle<i::JSObject>::cast(self), index);
    4713             :   has_pending_exception = result.IsNothing();
    4714          17 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4715          12 :   return result;
    4716             : }
    4717             : 
    4718           5 : Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
    4719             :                                                      Local<Name> key) {
    4720             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4721          15 :   ENTER_V8_NO_SCRIPT(isolate, context, Object, HasRealNamedCallbackProperty,
    4722             :                      Nothing<bool>(), i::HandleScope);
    4723             :   auto self = Utils::OpenHandle(this);
    4724           5 :   if (!self->IsJSObject()) return Just(false);
    4725           5 :   auto key_val = Utils::OpenHandle(*key);
    4726             :   auto result = i::JSObject::HasRealNamedCallbackProperty(
    4727           5 :       i::Handle<i::JSObject>::cast(self), key_val);
    4728             :   has_pending_exception = result.IsNothing();
    4729           5 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    4730           0 :   return result;
    4731             : }
    4732             : 
    4733           0 : bool v8::Object::HasNamedLookupInterceptor() {
    4734             :   auto self = Utils::OpenHandle(this);
    4735           0 :   return self->IsJSObject() &&
    4736           0 :          i::Handle<i::JSObject>::cast(self)->HasNamedInterceptor();
    4737             : }
    4738             : 
    4739             : 
    4740           0 : bool v8::Object::HasIndexedLookupInterceptor() {
    4741             :   auto self = Utils::OpenHandle(this);
    4742           0 :   return self->IsJSObject() &&
    4743           0 :          i::Handle<i::JSObject>::cast(self)->HasIndexedInterceptor();
    4744             : }
    4745             : 
    4746             : 
    4747           6 : MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
    4748             :     Local<Context> context, Local<Name> key) {
    4749          24 :   PREPARE_FOR_EXECUTION(context, Object, GetRealNamedPropertyInPrototypeChain,
    4750             :                         Value);
    4751             :   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
    4752           6 :   if (!self->IsJSObject()) return MaybeLocal<Value>();
    4753           6 :   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
    4754           6 :   i::PrototypeIterator iter(isolate, self);
    4755           6 :   if (iter.IsAtEnd()) return MaybeLocal<Value>();
    4756             :   i::Handle<i::JSReceiver> proto =
    4757           6 :       i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
    4758             :   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
    4759             :       isolate, self, key_obj, proto,
    4760           6 :       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
    4761             :   Local<Value> result;
    4762           6 :   has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
    4763           6 :   RETURN_ON_FAILED_EXECUTION(Value);
    4764           0 :   if (!it.IsFound()) return MaybeLocal<Value>();
    4765           0 :   RETURN_ESCAPED(result);
    4766             : }
    4767             : 
    4768             : 
    4769             : Maybe<PropertyAttribute>
    4770           6 : v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(
    4771             :     Local<Context> context, Local<Name> key) {
    4772             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4773          18 :   ENTER_V8_NO_SCRIPT(isolate, context, Object,
    4774             :                      GetRealNamedPropertyAttributesInPrototypeChain,
    4775             :                      Nothing<PropertyAttribute>(), i::HandleScope);
    4776             :   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
    4777           6 :   if (!self->IsJSObject()) return Nothing<PropertyAttribute>();
    4778           6 :   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
    4779           6 :   i::PrototypeIterator iter(isolate, self);
    4780           6 :   if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
    4781             :   i::Handle<i::JSReceiver> proto =
    4782           6 :       i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
    4783             :   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
    4784             :       isolate, self, key_obj, proto,
    4785           6 :       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
    4786             :   Maybe<i::PropertyAttributes> result =
    4787           6 :       i::JSReceiver::GetPropertyAttributes(&it);
    4788             :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
    4789           6 :   if (!it.IsFound()) return Nothing<PropertyAttribute>();
    4790           6 :   if (result.FromJust() == i::ABSENT) return Just(None);
    4791             :   return Just(static_cast<PropertyAttribute>(result.FromJust()));
    4792             : }
    4793             : 
    4794             : 
    4795      833569 : MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context,
    4796             :                                                    Local<Name> key) {
    4797     3334276 :   PREPARE_FOR_EXECUTION(context, Object, GetRealNamedProperty, Value);
    4798             :   auto self = Utils::OpenHandle(this);
    4799      833569 :   auto key_obj = Utils::OpenHandle(*key);
    4800             :   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
    4801             :       isolate, self, key_obj, self,
    4802      833569 :       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
    4803             :   Local<Value> result;
    4804      833569 :   has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
    4805      833569 :   RETURN_ON_FAILED_EXECUTION(Value);
    4806      833551 :   if (!it.IsFound()) return MaybeLocal<Value>();
    4807         258 :   RETURN_ESCAPED(result);
    4808             : }
    4809             : 
    4810             : 
    4811          18 : Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
    4812             :     Local<Context> context, Local<Name> key) {
    4813             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4814          54 :   ENTER_V8_NO_SCRIPT(isolate, context, Object, GetRealNamedPropertyAttributes,
    4815             :                      Nothing<PropertyAttribute>(), i::HandleScope);
    4816             :   auto self = Utils::OpenHandle(this);
    4817          18 :   auto key_obj = Utils::OpenHandle(*key);
    4818             :   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
    4819             :       isolate, self, key_obj, self,
    4820          18 :       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
    4821          18 :   auto result = i::JSReceiver::GetPropertyAttributes(&it);
    4822             :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
    4823          18 :   if (!it.IsFound()) return Nothing<PropertyAttribute>();
    4824          18 :   if (result.FromJust() == i::ABSENT) {
    4825             :     return Just(static_cast<PropertyAttribute>(i::NONE));
    4826             :   }
    4827             :   return Just<PropertyAttribute>(
    4828             :       static_cast<PropertyAttribute>(result.FromJust()));
    4829             : }
    4830             : 
    4831             : 
    4832          16 : Local<v8::Object> v8::Object::Clone() {
    4833             :   auto self = i::Handle<i::JSObject>::cast(Utils::OpenHandle(this));
    4834             :   auto isolate = self->GetIsolate();
    4835             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    4836          16 :   auto result = isolate->factory()->CopyJSObject(self);
    4837          16 :   CHECK(!result.is_null());
    4838          16 :   return Utils::ToLocal(result);
    4839             : }
    4840             : 
    4841             : 
    4842      304925 : Local<v8::Context> v8::Object::CreationContext() {
    4843             :   auto self = Utils::OpenHandle(this);
    4844      304925 :   i::Handle<i::Context> context = self->GetCreationContext();
    4845      304925 :   return Utils::ToLocal(context);
    4846             : }
    4847             : 
    4848             : 
    4849          94 : int v8::Object::GetIdentityHash() {
    4850             :   i::DisallowHeapAllocation no_gc;
    4851             :   auto isolate = Utils::OpenHandle(this)->GetIsolate();
    4852             :   i::HandleScope scope(isolate);
    4853             :   auto self = Utils::OpenHandle(this);
    4854         282 :   return self->GetOrCreateIdentityHash(isolate)->value();
    4855             : }
    4856             : 
    4857             : 
    4858          24 : bool v8::Object::IsCallable() {
    4859             :   auto self = Utils::OpenHandle(this);
    4860          48 :   return self->IsCallable();
    4861             : }
    4862             : 
    4863           6 : bool v8::Object::IsConstructor() {
    4864             :   auto self = Utils::OpenHandle(this);
    4865          12 :   return self->IsConstructor();
    4866             : }
    4867             : 
    4868         114 : MaybeLocal<Value> Object::CallAsFunction(Local<Context> context,
    4869             :                                          Local<Value> recv, int argc,
    4870             :                                          Local<Value> argv[]) {
    4871             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4872         228 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
    4873         342 :   ENTER_V8(isolate, context, Object, CallAsFunction, MaybeLocal<Value>(),
    4874             :            InternalEscapableScope);
    4875             :   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
    4876             :   auto self = Utils::OpenHandle(this);
    4877         114 :   auto recv_obj = Utils::OpenHandle(*recv);
    4878             :   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
    4879             :   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
    4880             :   Local<Value> result;
    4881         228 :   has_pending_exception = !ToLocal<Value>(
    4882             :       i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
    4883         114 :   RETURN_ON_FAILED_EXECUTION(Value);
    4884         102 :   RETURN_ESCAPED(result);
    4885             : }
    4886             : 
    4887             : 
    4888           0 : MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc,
    4889             :                                             Local<Value> argv[]) {
    4890             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4891           0 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
    4892           0 :   ENTER_V8(isolate, context, Object, CallAsConstructor, MaybeLocal<Value>(),
    4893             :            InternalEscapableScope);
    4894             :   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
    4895             :   auto self = Utils::OpenHandle(this);
    4896             :   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
    4897             :   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
    4898             :   Local<Value> result;
    4899           0 :   has_pending_exception = !ToLocal<Value>(
    4900             :       i::Execution::New(isolate, self, self, argc, args), &result);
    4901           0 :   RETURN_ON_FAILED_EXECUTION(Value);
    4902           0 :   RETURN_ESCAPED(result);
    4903             : }
    4904             : 
    4905        5403 : MaybeLocal<Function> Function::New(Local<Context> context,
    4906             :                                    FunctionCallback callback, Local<Value> data,
    4907             :                                    int length, ConstructorBehavior behavior,
    4908             :                                    SideEffectType side_effect_type) {
    4909             :   i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
    4910        5403 :   LOG_API(isolate, Function, New);
    4911             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    4912             :   auto templ =
    4913             :       FunctionTemplateNew(isolate, callback, data, Local<Signature>(), length,
    4914        5403 :                           true, Local<Private>(), side_effect_type);
    4915        5403 :   if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype();
    4916       10806 :   return templ->GetFunction(context);
    4917             : }
    4918             : 
    4919         789 : MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
    4920             :                                          v8::Local<v8::Value> argv[]) const {
    4921             :   return NewInstanceWithSideEffectType(context, argc, argv,
    4922         789 :                                        SideEffectType::kHasSideEffect);
    4923             : }
    4924             : 
    4925         804 : MaybeLocal<Object> Function::NewInstanceWithSideEffectType(
    4926             :     Local<Context> context, int argc, v8::Local<v8::Value> argv[],
    4927             :     SideEffectType side_effect_type) const {
    4928             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4929        1608 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
    4930        2412 :   ENTER_V8(isolate, context, Function, NewInstance, MaybeLocal<Object>(),
    4931             :            InternalEscapableScope);
    4932             :   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
    4933             :   auto self = Utils::OpenHandle(this);
    4934             :   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
    4935             :   bool should_set_has_no_side_effect =
    4936         804 :       side_effect_type == SideEffectType::kHasNoSideEffect &&
    4937             :       isolate->debug_execution_mode() == i::DebugInfo::kSideEffects;
    4938         804 :   if (should_set_has_no_side_effect) {
    4939          20 :     CHECK(self->IsJSFunction() &&
    4940             :           i::JSFunction::cast(*self)->shared()->IsApiFunction());
    4941             :     i::Object obj =
    4942             :         i::JSFunction::cast(*self)->shared()->get_api_func_data()->call_code();
    4943          10 :     if (obj->IsCallHandlerInfo()) {
    4944          10 :       i::CallHandlerInfo handler_info = i::CallHandlerInfo::cast(obj);
    4945          10 :       if (!handler_info->IsSideEffectFreeCallHandlerInfo()) {
    4946          10 :         handler_info->SetNextCallHasNoSideEffect();
    4947             :       }
    4948             :     }
    4949             :   }
    4950             :   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
    4951             :   Local<Object> result;
    4952        1608 :   has_pending_exception = !ToLocal<Object>(
    4953         804 :       i::Execution::New(isolate, self, self, argc, args), &result);
    4954         804 :   if (should_set_has_no_side_effect) {
    4955             :     i::Object obj =
    4956             :         i::JSFunction::cast(*self)->shared()->get_api_func_data()->call_code();
    4957          10 :     if (obj->IsCallHandlerInfo()) {
    4958          10 :       i::CallHandlerInfo handler_info = i::CallHandlerInfo::cast(obj);
    4959          10 :       if (has_pending_exception) {
    4960             :         // Restore the map if an exception prevented restoration.
    4961           0 :         handler_info->NextCallHasNoSideEffect();
    4962             :       } else {
    4963             :         DCHECK(handler_info->IsSideEffectCallHandlerInfo() ||
    4964             :                handler_info->IsSideEffectFreeCallHandlerInfo());
    4965             :       }
    4966             :     }
    4967             :   }
    4968         804 :   RETURN_ON_FAILED_EXECUTION(Object);
    4969         788 :   RETURN_ESCAPED(result);
    4970             : }
    4971             : 
    4972             : 
    4973      342309 : MaybeLocal<v8::Value> Function::Call(Local<Context> context,
    4974             :                                      v8::Local<v8::Value> recv, int argc,
    4975             :                                      v8::Local<v8::Value> argv[]) {
    4976             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    4977      684618 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
    4978     1026921 :   ENTER_V8(isolate, context, Function, Call, MaybeLocal<Value>(),
    4979             :            InternalEscapableScope);
    4980             :   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
    4981             :   auto self = Utils::OpenHandle(this);
    4982             :   Utils::ApiCheck(!self.is_null(), "v8::Function::Call",
    4983             :                   "Function to be called is a null pointer");
    4984      342308 :   i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
    4985             :   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
    4986             :   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
    4987             :   Local<Value> result;
    4988      684615 :   has_pending_exception = !ToLocal<Value>(
    4989             :       i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
    4990      342307 :   RETURN_ON_FAILED_EXECUTION(Value);
    4991      341965 :   RETURN_ESCAPED(result);
    4992             : }
    4993             : 
    4994         640 : void Function::SetName(v8::Local<v8::String> name) {
    4995             :   auto self = Utils::OpenHandle(this);
    4996         640 :   if (!self->IsJSFunction()) return;
    4997             :   auto func = i::Handle<i::JSFunction>::cast(self);
    4998         640 :   func->shared()->SetName(*Utils::OpenHandle(*name));
    4999             : }
    5000             : 
    5001             : 
    5002          42 : Local<Value> Function::GetName() const {
    5003             :   auto self = Utils::OpenHandle(this);
    5004             :   i::Isolate* isolate = self->GetIsolate();
    5005          42 :   if (self->IsJSBoundFunction()) {
    5006           0 :     auto func = i::Handle<i::JSBoundFunction>::cast(self);
    5007             :     i::Handle<i::Object> name;
    5008           0 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
    5009             :                                      i::JSBoundFunction::GetName(isolate, func),
    5010             :                                      Local<Value>());
    5011             :     return Utils::ToLocal(name);
    5012             :   }
    5013          42 :   if (self->IsJSFunction()) {
    5014             :     auto func = i::Handle<i::JSFunction>::cast(self);
    5015          84 :     return Utils::ToLocal(handle(func->shared()->Name(), isolate));
    5016             :   }
    5017           0 :   return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
    5018             : }
    5019             : 
    5020             : 
    5021           6 : Local<Value> Function::GetInferredName() const {
    5022             :   auto self = Utils::OpenHandle(this);
    5023           6 :   if (!self->IsJSFunction()) {
    5024             :     return ToApiHandle<Primitive>(
    5025           0 :         self->GetIsolate()->factory()->undefined_value());
    5026             :   }
    5027             :   auto func = i::Handle<i::JSFunction>::cast(self);
    5028          12 :   return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
    5029             :                                              func->GetIsolate()));
    5030             : }
    5031             : 
    5032             : 
    5033          72 : Local<Value> Function::GetDebugName() const {
    5034             :   auto self = Utils::OpenHandle(this);
    5035          72 :   if (!self->IsJSFunction()) {
    5036             :     return ToApiHandle<Primitive>(
    5037           0 :         self->GetIsolate()->factory()->undefined_value());
    5038             :   }
    5039          72 :   auto func = i::Handle<i::JSFunction>::cast(self);
    5040          72 :   i::Handle<i::String> name = i::JSFunction::GetDebugName(func);
    5041             :   return Utils::ToLocal(i::Handle<i::Object>(*name, self->GetIsolate()));
    5042             : }
    5043             : 
    5044             : 
    5045          42 : Local<Value> Function::GetDisplayName() const {
    5046             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    5047             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    5048             :   auto self = Utils::OpenHandle(this);
    5049          42 :   if (!self->IsJSFunction()) {
    5050           0 :     return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
    5051             :   }
    5052             :   auto func = i::Handle<i::JSFunction>::cast(self);
    5053             :   i::Handle<i::String> property_name =
    5054          42 :       isolate->factory()->NewStringFromStaticChars("displayName");
    5055             :   i::Handle<i::Object> value =
    5056          42 :       i::JSReceiver::GetDataProperty(func, property_name);
    5057          42 :   if (value->IsString()) {
    5058             :     i::Handle<i::String> name = i::Handle<i::String>::cast(value);
    5059          18 :     if (name->length() > 0) return Utils::ToLocal(name);
    5060             :   }
    5061          24 :   return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
    5062             : }
    5063             : 
    5064             : 
    5065          12 : ScriptOrigin Function::GetScriptOrigin() const {
    5066             :   auto self = Utils::OpenHandle(this);
    5067          12 :   if (!self->IsJSFunction()) {
    5068             :     return v8::ScriptOrigin(Local<Value>());
    5069             :   }
    5070             :   auto func = i::Handle<i::JSFunction>::cast(self);
    5071          24 :   if (func->shared()->script()->IsScript()) {
    5072          24 :     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
    5073          12 :                                 func->GetIsolate());
    5074          12 :     return GetScriptOriginForScript(func->GetIsolate(), script);
    5075             :   }
    5076             :   return v8::ScriptOrigin(Local<Value>());
    5077             : }
    5078             : 
    5079             : 
    5080             : const int Function::kLineOffsetNotFound = -1;
    5081             : 
    5082             : 
    5083      151698 : int Function::GetScriptLineNumber() const {
    5084             :   auto self = Utils::OpenHandle(this);
    5085      151698 :   if (!self->IsJSFunction()) {
    5086             :     return kLineOffsetNotFound;
    5087             :   }
    5088             :   auto func = i::Handle<i::JSFunction>::cast(self);
    5089      303376 :   if (func->shared()->script()->IsScript()) {
    5090      303376 :     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
    5091      151688 :                                 func->GetIsolate());
    5092      151688 :     return i::Script::GetLineNumber(script, func->shared()->StartPosition());
    5093             :   }
    5094             :   return kLineOffsetNotFound;
    5095             : }
    5096             : 
    5097             : 
    5098      146698 : int Function::GetScriptColumnNumber() const {
    5099             :   auto self = Utils::OpenHandle(this);
    5100      146698 :   if (!self->IsJSFunction()) {
    5101             :     return kLineOffsetNotFound;
    5102             :   }
    5103             :   auto func = i::Handle<i::JSFunction>::cast(self);
    5104      293376 :   if (func->shared()->script()->IsScript()) {
    5105      293376 :     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
    5106      146688 :                                 func->GetIsolate());
    5107      146688 :     return i::Script::GetColumnNumber(script, func->shared()->StartPosition());
    5108             :   }
    5109             :   return kLineOffsetNotFound;
    5110             : }
    5111             : 
    5112             : 
    5113      178386 : int Function::ScriptId() const {
    5114             :   auto self = Utils::OpenHandle(this);
    5115      178386 :   if (!self->IsJSFunction()) {
    5116             :     return v8::UnboundScript::kNoScriptId;
    5117             :   }
    5118             :   auto func = i::Handle<i::JSFunction>::cast(self);
    5119      356752 :   if (!func->shared()->script()->IsScript()) {
    5120             :     return v8::UnboundScript::kNoScriptId;
    5121             :   }
    5122      333932 :   i::Handle<i::Script> script(i::Script::cast(func->shared()->script()),
    5123      166966 :                               func->GetIsolate());
    5124             :   return script->id();
    5125             : }
    5126             : 
    5127             : 
    5128         252 : Local<v8::Value> Function::GetBoundFunction() const {
    5129             :   auto self = Utils::OpenHandle(this);
    5130         252 :   if (self->IsJSBoundFunction()) {
    5131             :     auto bound_function = i::Handle<i::JSBoundFunction>::cast(self);
    5132             :     auto bound_target_function = i::handle(
    5133             :         bound_function->bound_target_function(), bound_function->GetIsolate());
    5134         102 :     return Utils::CallableToLocal(bound_target_function);
    5135             :   }
    5136         150 :   return v8::Undefined(reinterpret_cast<v8::Isolate*>(self->GetIsolate()));
    5137             : }
    5138             : 
    5139          50 : int Name::GetIdentityHash() {
    5140             :   auto self = Utils::OpenHandle(this);
    5141          50 :   return static_cast<int>(self->Hash());
    5142             : }
    5143             : 
    5144             : 
    5145    27579701 : int String::Length() const {
    5146             :   i::Handle<i::String> str = Utils::OpenHandle(this);
    5147    27579701 :   return str->length();
    5148             : }
    5149             : 
    5150             : 
    5151          67 : bool String::IsOneByte() const {
    5152             :   i::Handle<i::String> str = Utils::OpenHandle(this);
    5153          67 :   return str->IsOneByteRepresentation();
    5154             : }
    5155             : 
    5156             : 
    5157             : // Helpers for ContainsOnlyOneByteHelper
    5158             : template<size_t size> struct OneByteMask;
    5159             : template<> struct OneByteMask<4> {
    5160             :   static const uint32_t value = 0xFF00FF00;
    5161             : };
    5162             : template<> struct OneByteMask<8> {
    5163             :   static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
    5164             : };
    5165             : static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
    5166             : static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
    5167             : static inline bool Unaligned(const uint16_t* chars) {
    5168       45915 :   return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
    5169             : }
    5170             : 
    5171             : 
    5172             : static inline const uint16_t* Align(const uint16_t* chars) {
    5173             :   return reinterpret_cast<uint16_t*>(
    5174       17885 :       reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
    5175             : }
    5176             : 
    5177             : class ContainsOnlyOneByteHelper {
    5178             :  public:
    5179       17885 :   ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
    5180       17885 :   bool Check(i::String string) {
    5181       17885 :     i::ConsString cons_string = i::String::VisitFlat(this, string, 0);
    5182       17885 :     if (cons_string.is_null()) return is_one_byte_;
    5183          30 :     return CheckCons(cons_string);
    5184             :   }
    5185             :   void VisitOneByteString(const uint8_t* chars, int length) {
    5186             :     // Nothing to do.
    5187             :   }
    5188       17885 :   void VisitTwoByteString(const uint16_t* chars, int length) {
    5189             :     // Accumulated bits.
    5190             :     uintptr_t acc = 0;
    5191             :     // Align to uintptr_t.
    5192       17885 :     const uint16_t* end = chars + length;
    5193       73945 :     while (Unaligned(chars) && chars != end) {
    5194       28030 :       acc |= *chars++;
    5195             :     }
    5196             :     // Read word aligned in blocks,
    5197             :     // checking the return value at the end of each block.
    5198             :     const uint16_t* aligned_end = Align(end);
    5199             :     const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
    5200             :     const int inner_loops = 16;
    5201       33590 :     while (chars + inner_loops*increment < aligned_end) {
    5202      817575 :       for (int i = 0; i < inner_loops; i++) {
    5203      396400 :         acc |= *reinterpret_cast<const uintptr_t*>(chars);
    5204      396400 :         chars += increment;
    5205             :       }
    5206             :       // Check for early return.
    5207       24775 :       if ((acc & kOneByteMask) != 0) {
    5208        9070 :         is_one_byte_ = false;
    5209        9070 :         return;
    5210             :       }
    5211             :     }
    5212             :     // Read the rest.
    5213      927425 :     while (chars != end) {
    5214      459305 :       acc |= *chars++;
    5215             :     }
    5216             :     // Check result.
    5217        8815 :     if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
    5218             :   }
    5219             : 
    5220             :  private:
    5221          40 :   bool CheckCons(i::ConsString cons_string) {
    5222             :     while (true) {
    5223             :       // Check left side if flat.
    5224             :       i::String left = cons_string->first();
    5225       39610 :       i::ConsString left_as_cons = i::String::VisitFlat(this, left, 0);
    5226       39610 :       if (!is_one_byte_) return false;
    5227             :       // Check right side if flat.
    5228             :       i::String right = cons_string->second();
    5229       39610 :       i::ConsString right_as_cons = i::String::VisitFlat(this, right, 0);
    5230       39610 :       if (!is_one_byte_) return false;
    5231             :       // Standard recurse/iterate trick.
    5232       39610 :       if (!left_as_cons.is_null() && !right_as_cons.is_null()) {
    5233          10 :         if (left->length() < right->length()) {
    5234           0 :           CheckCons(left_as_cons);
    5235             :           cons_string = right_as_cons;
    5236             :         } else {
    5237          10 :           CheckCons(right_as_cons);
    5238             :           cons_string = left_as_cons;
    5239             :         }
    5240             :         // Check fast return.
    5241          10 :         if (!is_one_byte_) return false;
    5242             :         continue;
    5243             :       }
    5244             :       // Descend left in place.
    5245       39600 :       if (!left_as_cons.is_null()) {
    5246             :         cons_string = left_as_cons;
    5247             :         continue;
    5248             :       }
    5249             :       // Descend right in place.
    5250       19815 :       if (!right_as_cons.is_null()) {
    5251             :         cons_string = right_as_cons;
    5252             :         continue;
    5253             :       }
    5254             :       // Terminate.
    5255             :       break;
    5256             :     }
    5257             :     return is_one_byte_;
    5258             :   }
    5259             :   bool is_one_byte_;
    5260             :   DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
    5261             : };
    5262             : 
    5263             : 
    5264       17905 : bool String::ContainsOnlyOneByte() const {
    5265             :   i::Handle<i::String> str = Utils::OpenHandle(this);
    5266       17905 :   if (str->IsOneByteRepresentation()) return true;
    5267             :   ContainsOnlyOneByteHelper helper;
    5268       17885 :   return helper.Check(*str);
    5269             : }
    5270             : 
    5271     9068087 : int String::Utf8Length(Isolate* isolate) const {
    5272             :   i::Handle<i::String> str = Utils::OpenHandle(this);
    5273     9068087 :   str = i::String::Flatten(reinterpret_cast<i::Isolate*>(isolate), str);
    5274             :   int length = str->length();
    5275     9068087 :   if (length == 0) return 0;
    5276             :   i::DisallowHeapAllocation no_gc;
    5277     9061948 :   i::String::FlatContent flat = str->GetFlatContent(no_gc);
    5278             :   DCHECK(flat.IsFlat());
    5279             :   int utf8_length = 0;
    5280     9061948 :   if (flat.IsOneByte()) {
    5281   572742065 :     for (uint8_t c : flat.ToOneByteVector()) {
    5282   281842402 :       utf8_length += c >> 7;
    5283             :     }
    5284     9057261 :     utf8_length += length;
    5285             :   } else {
    5286             :     int last_character = unibrow::Utf16::kNoPreviousCharacter;
    5287     2430411 :     for (uint16_t c : flat.ToUC16Vector()) {
    5288     2425724 :       utf8_length += unibrow::Utf8::Length(c, last_character);
    5289     1212862 :       last_character = c;
    5290             :     }
    5291             :   }
    5292             :   return utf8_length;
    5293             : }
    5294             : 
    5295             : namespace {
    5296             : // Writes the flat content of a string to a buffer. This is done in two phases.
    5297             : // The first phase calculates a pessimistic estimate (writable_length) on how
    5298             : // many code units can be safely written without exceeding the buffer capacity
    5299             : // and without leaving at a lone surrogate. The estimated number of code units
    5300             : // is then written out in one go, and the reported byte usage is used to
    5301             : // correct the estimate. This is repeated until the estimate becomes <= 0 or
    5302             : // all code units have been written out. The second phase writes out code
    5303             : // units until the buffer capacity is reached, would be exceeded by the next
    5304             : // unit, or all code units have been written out.
    5305             : template <typename Char>
    5306     9067658 : static int WriteUtf8Impl(i::Vector<const Char> string, char* write_start,
    5307             :                          int write_capacity, int options,
    5308             :                          int* utf16_chars_read_out) {
    5309     9067658 :   bool write_null = !(options & v8::String::NO_NULL_TERMINATION);
    5310     9067658 :   bool replace_invalid_utf8 = (options & v8::String::REPLACE_INVALID_UTF8);
    5311             :   char* current_write = write_start;
    5312             :   const Char* read_start = string.start();
    5313             :   int read_index = 0;
    5314             :   int read_length = string.length();
    5315             :   int prev_char = unibrow::Utf16::kNoPreviousCharacter;
    5316             :   // Do a fast loop where there is no exit capacity check.
    5317             :   // Need enough space to write everything but one character.
    5318             :   STATIC_ASSERT(unibrow::Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 3);
    5319             :   static const int kMaxSizePerChar = sizeof(Char) == 1 ? 2 : 3;
    5320    27499888 :   while (read_index < read_length) {
    5321     9229589 :     int up_to = read_length;
    5322     9229589 :     if (write_capacity != -1) {
    5323             :       int remaining_capacity =
    5324      181592 :           write_capacity - static_cast<int>(current_write - write_start);
    5325             :       int writable_length =
    5326      181592 :           (remaining_capacity - kMaxSizePerChar) / kMaxSizePerChar;
    5327             :       // Need to drop into slow loop.
    5328      181592 :       if (writable_length <= 0) break;
    5329      336236 :       up_to = std::min(up_to, read_index + writable_length);
    5330             :     }
    5331             :     // Write the characters to the stream.
    5332             :     if (sizeof(Char) == 1) {
    5333             :       // Simply memcpy if we only have ASCII characters.
    5334             :       uint8_t char_mask = 0;
    5335   336011202 :       for (int i = read_index; i < up_to; i++) char_mask |= read_start[i];
    5336     9210273 :       if ((char_mask & 0x80) == 0) {
    5337     9210064 :         int copy_length = up_to - read_index;
    5338     9210064 :         memcpy(current_write, read_start + read_index, copy_length);
    5339     9210064 :         current_write += copy_length;
    5340             :         read_index = up_to;
    5341             :       } else {
    5342       16455 :         for (; read_index < up_to; read_index++) {
    5343        8123 :           current_write += unibrow::Utf8::EncodeOneByte(
    5344        8123 :               current_write, static_cast<uint8_t>(read_start[read_index]));
    5345             :           DCHECK(write_capacity == -1 ||
    5346             :                  (current_write - write_start) <= write_capacity);
    5347             :         }
    5348             :       }
    5349             :     } else {
    5350   272402516 :       for (; read_index < up_to; read_index++) {
    5351   136198337 :         uint16_t character = read_start[read_index];
    5352   136198337 :         current_write += unibrow::Utf8::Encode(current_write, character,
    5353             :                                                prev_char, replace_invalid_utf8);
    5354   136198337 :         prev_char = character;
    5355             :         DCHECK(write_capacity == -1 ||
    5356             :                (current_write - write_start) <= write_capacity);
    5357             :       }
    5358             :     }
    5359             :   }
    5360     9067658 :   if (read_index < read_length) {
    5361             :     DCHECK_NE(-1, write_capacity);
    5362             :     // Aborted due to limited capacity. Check capacity on each iteration.
    5363             :     int remaining_capacity =
    5364       13474 :         write_capacity - static_cast<int>(current_write - write_start);
    5365             :     DCHECK_GE(remaining_capacity, 0);
    5366       94286 :     for (; read_index < read_length && remaining_capacity > 0; read_index++) {
    5367       40455 :       uint32_t character = read_start[read_index];
    5368             :       int written = 0;
    5369             :       // We can't use a local buffer here because Encode needs to modify
    5370             :       // previous characters in the stream.  We know, however, that
    5371             :       // exactly one character will be advanced.
    5372       80166 :       if (unibrow::Utf16::IsSurrogatePair(prev_char, character)) {
    5373           0 :         written = unibrow::Utf8::Encode(current_write, character, prev_char,
    5374             :                                         replace_invalid_utf8);
    5375             :         DCHECK_EQ(written, 1);
    5376             :       } else {
    5377             :         // Use a scratch buffer to check the required characters.
    5378             :         char temp_buffer[unibrow::Utf8::kMaxEncodedSize];
    5379             :         // Encoding a surrogate pair to Utf8 always takes 4 bytes.
    5380             :         static const int kSurrogatePairEncodedSize =
    5381             :             static_cast<int>(unibrow::Utf8::kMaxEncodedSize);
    5382             :         // For REPLACE_INVALID_UTF8, catch the case where we cut off in the
    5383             :         // middle of a surrogate pair. Abort before encoding the pair instead.
    5384       40461 :         if (replace_invalid_utf8 &&
    5385             :             remaining_capacity < kSurrogatePairEncodedSize &&
    5386             :             unibrow::Utf16::IsLeadSurrogate(character) &&
    5387             :             read_index + 1 < read_length &&
    5388           6 :             unibrow::Utf16::IsTrailSurrogate(read_start[read_index + 1])) {
    5389             :           write_null = false;
    5390          49 :           break;
    5391             :         }
    5392             :         // Can't encode using prev_char as gcc has array bounds issues.
    5393       40449 :         written = unibrow::Utf8::Encode(temp_buffer, character,
    5394             :                                         unibrow::Utf16::kNoPreviousCharacter,
    5395             :                                         replace_invalid_utf8);
    5396       40449 :         if (written > remaining_capacity) {
    5397             :           // Won't fit. Abort and do not null-terminate the result.
    5398             :           write_null = false;
    5399             :           break;
    5400             :         }
    5401             :         // Copy over the character from temp_buffer.
    5402       80950 :         for (int i = 0; i < written; i++) current_write[i] = temp_buffer[i];
    5403             :       }
    5404             : 
    5405       40406 :       current_write += written;
    5406       40406 :       remaining_capacity -= written;
    5407         695 :       prev_char = character;
    5408             :     }
    5409             :   }
    5410             : 
    5411             :   // Write out number of utf16 characters written to the stream.
    5412     9067658 :   if (utf16_chars_read_out != nullptr) *utf16_chars_read_out = read_index;
    5413             : 
    5414             :   // Only null-terminate if there's space.
    5415     9067658 :   if (write_null && (write_capacity == -1 ||
    5416             :                      (current_write - write_start) < write_capacity)) {
    5417     9054218 :     *current_write++ = '\0';
    5418             :   }
    5419     9067658 :   return static_cast<int>(current_write - write_start);
    5420             : }
    5421             : }  // anonymous namespace
    5422             : 
    5423     9067658 : int String::WriteUtf8(Isolate* v8_isolate, char* buffer, int capacity,
    5424             :                       int* nchars_ref, int options) const {
    5425             :   i::Handle<i::String> str = Utils::OpenHandle(this);
    5426             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    5427     9067658 :   LOG_API(isolate, String, WriteUtf8);
    5428             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    5429     9067658 :   str = i::String::Flatten(isolate, str);
    5430             :   i::DisallowHeapAllocation no_gc;
    5431     9067658 :   i::String::FlatContent content = str->GetFlatContent(no_gc);
    5432     9067658 :   if (content.IsOneByte()) {
    5433             :     return WriteUtf8Impl<uint8_t>(content.ToOneByteVector(), buffer, capacity,
    5434     9063305 :                                   options, nchars_ref);
    5435             :   } else {
    5436             :     return WriteUtf8Impl<uint16_t>(content.ToUC16Vector(), buffer, capacity,
    5437        4353 :                                    options, nchars_ref);
    5438             :   }
    5439             : }
    5440             : 
    5441             : template <typename CharType>
    5442     9267882 : static inline int WriteHelper(i::Isolate* isolate, const String* string,
    5443             :                               CharType* buffer, int start, int length,
    5444             :                               int options) {
    5445     9267882 :   LOG_API(isolate, String, Write);
    5446             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    5447             :   DCHECK(start >= 0 && length >= -1);
    5448             :   i::Handle<i::String> str = Utils::OpenHandle(string);
    5449     9267882 :   str = i::String::Flatten(isolate, str);
    5450     9267879 :   int end = start + length;
    5451    18535656 :   if ((length == -1) || (length > str->length() - start) )
    5452             :     end = str->length();
    5453     9267879 :   if (end < 0) return 0;
    5454     9267879 :   i::String::WriteToFlat(*str, buffer, start, end);
    5455     9267879 :   if (!(options & String::NO_NULL_TERMINATION) &&
    5456             :       (length == -1 || end - start < length)) {
    5457          66 :     buffer[end - start] = '\0';
    5458             :   }
    5459     9267879 :   return end - start;
    5460             : }
    5461             : 
    5462             : 
    5463          67 : int String::WriteOneByte(Isolate* isolate, uint8_t* buffer, int start,
    5464             :                          int length, int options) const {
    5465             :   return WriteHelper(reinterpret_cast<i::Isolate*>(isolate), this, buffer,
    5466          67 :                      start, length, options);
    5467             : }
    5468             : 
    5469             : 
    5470     9267809 : int String::Write(Isolate* isolate, uint16_t* buffer, int start, int length,
    5471             :                   int options) const {
    5472             :   return WriteHelper(reinterpret_cast<i::Isolate*>(isolate), this, buffer,
    5473     9267815 :                      start, length, options);
    5474             : }
    5475             : 
    5476             : 
    5477          67 : bool v8::String::IsExternal() const {
    5478             :   i::Handle<i::String> str = Utils::OpenHandle(this);
    5479          67 :   return i::StringShape(*str).IsExternalTwoByte();
    5480             : }
    5481             : 
    5482             : 
    5483          27 : bool v8::String::IsExternalOneByte() const {
    5484             :   i::Handle<i::String> str = Utils::OpenHandle(this);
    5485          27 :   return i::StringShape(*str).IsExternalOneByte();
    5486             : }
    5487             : 
    5488             : 
    5489           0 : void v8::String::VerifyExternalStringResource(
    5490             :     v8::String::ExternalStringResource* value) const {
    5491             :   i::DisallowHeapAllocation no_allocation;
    5492             :   i::String str = *Utils::OpenHandle(this);
    5493             :   const v8::String::ExternalStringResource* expected;
    5494             : 
    5495           0 :   if (str->IsThinString()) {
    5496             :     str = i::ThinString::cast(str)->actual();
    5497             :   }
    5498             : 
    5499           0 :   if (i::StringShape(str).IsExternalTwoByte()) {
    5500             :     const void* resource = i::ExternalTwoByteString::cast(str)->resource();
    5501             :     expected = reinterpret_cast<const ExternalStringResource*>(resource);
    5502             :   } else {
    5503             :     expected = nullptr;
    5504             :   }
    5505           0 :   CHECK_EQ(expected, value);
    5506           0 : }
    5507             : 
    5508           0 : void v8::String::VerifyExternalStringResourceBase(
    5509             :     v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
    5510             :   i::DisallowHeapAllocation no_allocation;
    5511             :   i::String str = *Utils::OpenHandle(this);
    5512             :   const v8::String::ExternalStringResourceBase* expected;
    5513             :   Encoding expectedEncoding;
    5514             : 
    5515           0 :   if (str->IsThinString()) {
    5516             :     str = i::ThinString::cast(str)->actual();
    5517             :   }
    5518             : 
    5519           0 :   if (i::StringShape(str).IsExternalOneByte()) {
    5520             :     const void* resource = i::ExternalOneByteString::cast(str)->resource();
    5521             :     expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
    5522             :     expectedEncoding = ONE_BYTE_ENCODING;
    5523           0 :   } else if (i::StringShape(str).IsExternalTwoByte()) {
    5524             :     const void* resource = i::ExternalTwoByteString::cast(str)->resource();
    5525             :     expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
    5526             :     expectedEncoding = TWO_BYTE_ENCODING;
    5527             :   } else {
    5528             :     expected = nullptr;
    5529             :     expectedEncoding =
    5530           0 :         str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
    5531             :   }
    5532           0 :   CHECK_EQ(expected, value);
    5533           0 :   CHECK_EQ(expectedEncoding, encoding);
    5534           0 : }
    5535             : 
    5536           0 : String::ExternalStringResource* String::GetExternalStringResourceSlow() const {
    5537             :   i::DisallowHeapAllocation no_allocation;
    5538             :   typedef internal::Internals I;
    5539             :   i::String str = *Utils::OpenHandle(this);
    5540             : 
    5541           0 :   if (str->IsThinString()) {
    5542             :     str = i::ThinString::cast(str)->actual();
    5543             :   }
    5544             : 
    5545           0 :   if (i::StringShape(str).IsExternalTwoByte()) {
    5546             :     void* value = I::ReadRawField<void*>(str.ptr(), I::kStringResourceOffset);
    5547           0 :     return reinterpret_cast<String::ExternalStringResource*>(value);
    5548             :   }
    5549             :   return nullptr;
    5550             : }
    5551             : 
    5552           6 : String::ExternalStringResourceBase* String::GetExternalStringResourceBaseSlow(
    5553             :     String::Encoding* encoding_out) const {
    5554             :   i::DisallowHeapAllocation no_allocation;
    5555             :   typedef internal::Internals I;
    5556             :   ExternalStringResourceBase* resource = nullptr;
    5557             :   i::String str = *Utils::OpenHandle(this);
    5558             : 
    5559           6 :   if (str->IsThinString()) {
    5560             :     str = i::ThinString::cast(str)->actual();
    5561             :   }
    5562             : 
    5563             :   internal::Address string = str.ptr();
    5564             :   int type = I::GetInstanceType(string) & I::kFullStringRepresentationMask;
    5565           6 :   *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
    5566          12 :   if (i::StringShape(str).IsExternalOneByte() ||
    5567             :       i::StringShape(str).IsExternalTwoByte()) {
    5568             :     void* value = I::ReadRawField<void*>(string, I::kStringResourceOffset);
    5569             :     resource = static_cast<ExternalStringResourceBase*>(value);
    5570             :   }
    5571           6 :   return resource;
    5572             : }
    5573             : 
    5574             : const v8::String::ExternalOneByteStringResource*
    5575          11 : v8::String::GetExternalOneByteStringResource() const {
    5576             :   i::DisallowHeapAllocation no_allocation;
    5577             :   i::String str = *Utils::OpenHandle(this);
    5578          11 :   if (i::StringShape(str).IsExternalOneByte()) {
    5579             :     return i::ExternalOneByteString::cast(str)->resource();
    5580           0 :   } else if (str->IsThinString()) {
    5581             :     str = i::ThinString::cast(str)->actual();
    5582           0 :     if (i::StringShape(str).IsExternalOneByte()) {
    5583             :       return i::ExternalOneByteString::cast(str)->resource();
    5584             :     }
    5585             :   }
    5586             :   return nullptr;
    5587             : }
    5588             : 
    5589             : 
    5590       57891 : Local<Value> Symbol::Name() const {
    5591             :   i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
    5592             : 
    5593             :   i::Isolate* isolate;
    5594       57891 :   if (!i::GetIsolateFromWritableObject(*sym, &isolate)) {
    5595             :     // If the Symbol is in RO_SPACE, then its name must be too. Since RO_SPACE
    5596             :     // objects are immovable we can use the Handle(Address*) constructor with
    5597             :     // the address of the name field in the Symbol object without needing an
    5598             :     // isolate.
    5599             : #ifdef V8_COMPRESS_POINTERS
    5600             :     // Compressed fields can't serve as handle locations.
    5601             :     // TODO(ishell): get Isolate as a parameter.
    5602             :     isolate = i::Isolate::Current();
    5603             : #else
    5604             :     i::Handle<i::HeapObject> ro_name(reinterpret_cast<i::Address*>(
    5605       57555 :         sym->GetFieldAddress(i::Symbol::kNameOffset)));
    5606             :     return Utils::ToLocal(ro_name);
    5607             : #endif
    5608             :   }
    5609             : 
    5610             :   i::Handle<i::Object> name(sym->name(), isolate);
    5611             : 
    5612             :   return Utils::ToLocal(name);
    5613             : }
    5614             : 
    5615             : 
    5616          72 : Local<Value> Private::Name() const {
    5617          72 :   return reinterpret_cast<const Symbol*>(this)->Name();
    5618             : }
    5619             : 
    5620             : 
    5621      330007 : double Number::Value() const {
    5622             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    5623      330007 :   return obj->Number();
    5624             : }
    5625             : 
    5626             : 
    5627       21822 : bool Boolean::Value() const {
    5628             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    5629       21822 :   return obj->IsTrue();
    5630             : }
    5631             : 
    5632             : 
    5633        2243 : int64_t Integer::Value() const {
    5634             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    5635       11744 :   if (obj->IsSmi()) {
    5636       11708 :     return i::Smi::ToInt(*obj);
    5637             :   } else {
    5638          36 :     return static_cast<int64_t>(obj->Number());
    5639             :   }
    5640             : }
    5641             : 
    5642             : 
    5643       33645 : int32_t Int32::Value() const {
    5644             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    5645       33645 :   if (obj->IsSmi()) {
    5646       33645 :     return i::Smi::ToInt(*obj);
    5647             :   } else {
    5648           0 :     return static_cast<int32_t>(obj->Number());
    5649             :   }
    5650             : }
    5651             : 
    5652             : 
    5653        7291 : uint32_t Uint32::Value() const {
    5654             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    5655        7291 :   if (obj->IsSmi()) {
    5656        7273 :     return i::Smi::ToInt(*obj);
    5657             :   } else {
    5658          18 :     return static_cast<uint32_t>(obj->Number());
    5659             :   }
    5660             : }
    5661             : 
    5662        4545 : int v8::Object::InternalFieldCount() {
    5663             :   i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
    5664        4545 :   if (!self->IsJSObject()) return 0;
    5665        4545 :   return i::Handle<i::JSObject>::cast(self)->GetEmbedderFieldCount();
    5666             : }
    5667             : 
    5668        2753 : static bool InternalFieldOK(i::Handle<i::JSReceiver> obj, int index,
    5669             :                             const char* location) {
    5670             :   return Utils::ApiCheck(
    5671        5506 :       obj->IsJSObject() &&
    5672        2753 :           (index < i::Handle<i::JSObject>::cast(obj)->GetEmbedderFieldCount()),
    5673        2753 :       location, "Internal field out of bounds");
    5674             : }
    5675             : 
    5676         576 : Local<Value> v8::Object::SlowGetInternalField(int index) {
    5677             :   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
    5678             :   const char* location = "v8::Object::GetInternalField()";
    5679         576 :   if (!InternalFieldOK(obj, index, location)) return Local<Value>();
    5680        1152 :   i::Handle<i::Object> value(i::JSObject::cast(*obj)->GetEmbedderField(index),
    5681         576 :                              obj->GetIsolate());
    5682             :   return Utils::ToLocal(value);
    5683             : }
    5684             : 
    5685         524 : void v8::Object::SetInternalField(int index, v8::Local<Value> value) {
    5686             :   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
    5687             :   const char* location = "v8::Object::SetInternalField()";
    5688         524 :   if (!InternalFieldOK(obj, index, location)) return;
    5689             :   i::Handle<i::Object> val = Utils::OpenHandle(*value);
    5690         524 :   i::Handle<i::JSObject>::cast(obj)->SetEmbedderField(index, *val);
    5691             : }
    5692             : 
    5693         135 : void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
    5694             :   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
    5695             :   const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
    5696         135 :   if (!InternalFieldOK(obj, index, location)) return nullptr;
    5697             :   void* result;
    5698             :   Utils::ApiCheck(i::EmbedderDataSlot(i::JSObject::cast(*obj), index)
    5699             :                       .ToAlignedPointer(&result),
    5700             :                   location, "Unaligned pointer");
    5701         135 :   return result;
    5702             : }
    5703             : 
    5704        1518 : void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
    5705             :   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
    5706             :   const char* location = "v8::Object::SetAlignedPointerInInternalField()";
    5707        1518 :   if (!InternalFieldOK(obj, index, location)) return;
    5708             :   Utils::ApiCheck(i::EmbedderDataSlot(i::JSObject::cast(*obj), index)
    5709             :                       .store_aligned_pointer(value),
    5710             :                   location, "Unaligned pointer");
    5711             :   DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
    5712             : }
    5713             : 
    5714          12 : void v8::Object::SetAlignedPointerInInternalFields(int argc, int indices[],
    5715             :                                                    void* values[]) {
    5716             :   i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this);
    5717             :   const char* location = "v8::Object::SetAlignedPointerInInternalFields()";
    5718             :   i::DisallowHeapAllocation no_gc;
    5719          12 :   i::JSObject js_obj = i::JSObject::cast(*obj);
    5720          12 :   int nof_embedder_fields = js_obj->GetEmbedderFieldCount();
    5721          60 :   for (int i = 0; i < argc; i++) {
    5722          24 :     int index = indices[i];
    5723          24 :     if (!Utils::ApiCheck(index < nof_embedder_fields, location,
    5724             :                          "Internal field out of bounds")) {
    5725           0 :       return;
    5726             :     }
    5727          24 :     void* value = values[i];
    5728             :     Utils::ApiCheck(
    5729             :         i::EmbedderDataSlot(js_obj, index).store_aligned_pointer(value),
    5730             :         location, "Unaligned pointer");
    5731             :     DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
    5732             :   }
    5733             : }
    5734             : 
    5735     1154445 : static void* ExternalValue(i::Object obj) {
    5736             :   // Obscure semantics for undefined, but somehow checked in our unit tests...
    5737     1154445 :   if (obj->IsUndefined()) {
    5738             :     return nullptr;
    5739             :   }
    5740     1154446 :   i::Object foreign = i::JSObject::cast(obj)->GetEmbedderField(0);
    5741     1154444 :   return reinterpret_cast<void*>(i::Foreign::cast(foreign)->foreign_address());
    5742             : }
    5743             : 
    5744             : // --- E n v i r o n m e n t ---
    5745             : 
    5746             : 
    5747       61008 : void v8::V8::InitializePlatform(Platform* platform) {
    5748       61008 :   i::V8::InitializePlatform(platform);
    5749       61008 : }
    5750             : 
    5751             : 
    5752       59859 : void v8::V8::ShutdownPlatform() {
    5753       59859 :   i::V8::ShutdownPlatform();
    5754       59859 : }
    5755             : 
    5756             : 
    5757       61332 : bool v8::V8::Initialize() {
    5758       61332 :   i::V8::Initialize();
    5759             : #ifdef V8_USE_EXTERNAL_STARTUP_DATA
    5760       61332 :   i::ReadNatives();
    5761             : #endif
    5762       61332 :   return true;
    5763             : }
    5764             : 
    5765             : #if V8_OS_LINUX || V8_OS_MACOSX
    5766           7 : bool TryHandleWebAssemblyTrapPosix(int sig_code, siginfo_t* info,
    5767             :                                    void* context) {
    5768             : #if V8_TARGET_ARCH_X64 && !V8_OS_ANDROID
    5769           7 :   return i::trap_handler::TryHandleSignal(sig_code, info, context);
    5770             : #else
    5771             :   return false;
    5772             : #endif
    5773             : }
    5774             : 
    5775           0 : bool V8::TryHandleSignal(int signum, void* info, void* context) {
    5776             :   return TryHandleWebAssemblyTrapPosix(
    5777           0 :       signum, reinterpret_cast<siginfo_t*>(info), context);
    5778             : }
    5779             : #endif
    5780             : 
    5781             : #if V8_OS_WIN
    5782             : bool TryHandleWebAssemblyTrapWindows(EXCEPTION_POINTERS* exception) {
    5783             : #if V8_TARGET_ARCH_X64
    5784             :   return i::trap_handler::TryHandleWasmTrap(exception);
    5785             : #endif
    5786             :   return false;
    5787             : }
    5788             : #endif
    5789             : 
    5790       56767 : bool V8::EnableWebAssemblyTrapHandler(bool use_v8_signal_handler) {
    5791       56767 :   return v8::internal::trap_handler::EnableTrapHandler(use_v8_signal_handler);
    5792             : }
    5793             : 
    5794             : #if defined(V8_OS_WIN)
    5795             : void V8::SetUnhandledExceptionCallback(
    5796             :     UnhandledExceptionCallback unhandled_exception_callback) {
    5797             : #if defined(V8_TARGET_ARCH_X64)
    5798             :   v8::internal::win64_unwindinfo::SetUnhandledExceptionCallback(
    5799             :       unhandled_exception_callback);
    5800             : #else
    5801             :   // Not implemented on ARM64.
    5802             : #endif
    5803             : }
    5804             : #endif
    5805             : 
    5806           0 : void v8::V8::SetEntropySource(EntropySource entropy_source) {
    5807           0 :   base::RandomNumberGenerator::SetEntropySource(entropy_source);
    5808           0 : }
    5809             : 
    5810             : 
    5811           0 : void v8::V8::SetReturnAddressLocationResolver(
    5812             :     ReturnAddressLocationResolver return_address_resolver) {
    5813           0 :   i::StackFrame::SetReturnAddressLocationResolver(return_address_resolver);
    5814           0 : }
    5815             : 
    5816       59903 : bool v8::V8::Dispose() {
    5817       59903 :   i::V8::TearDown();
    5818             : #ifdef V8_USE_EXTERNAL_STARTUP_DATA
    5819       59903 :   i::DisposeNatives();
    5820             : #endif
    5821       59903 :   return true;
    5822             : }
    5823             : 
    5824          31 : HeapStatistics::HeapStatistics()
    5825             :     : total_heap_size_(0),
    5826             :       total_heap_size_executable_(0),
    5827             :       total_physical_size_(0),
    5828             :       total_available_size_(0),
    5829             :       used_heap_size_(0),
    5830             :       heap_size_limit_(0),
    5831             :       malloced_memory_(0),
    5832             :       external_memory_(0),
    5833             :       peak_malloced_memory_(0),
    5834             :       does_zap_garbage_(false),
    5835             :       number_of_native_contexts_(0),
    5836          31 :       number_of_detached_contexts_(0) {}
    5837             : 
    5838          40 : HeapSpaceStatistics::HeapSpaceStatistics()
    5839             :     : space_name_(nullptr),
    5840             :       space_size_(0),
    5841             :       space_used_size_(0),
    5842             :       space_available_size_(0),
    5843          40 :       physical_space_size_(0) {}
    5844             : 
    5845           0 : HeapObjectStatistics::HeapObjectStatistics()
    5846             :     : object_type_(nullptr),
    5847             :       object_sub_type_(nullptr),
    5848             :       object_count_(0),
    5849           0 :       object_size_(0) {}
    5850             : 
    5851           0 : HeapCodeStatistics::HeapCodeStatistics()
    5852             :     : code_and_metadata_size_(0),
    5853             :       bytecode_and_metadata_size_(0),
    5854           0 :       external_script_source_size_(0) {}
    5855             : 
    5856           0 : bool v8::V8::InitializeICU(const char* icu_data_file) {
    5857           0 :   return i::InitializeICU(icu_data_file);
    5858             : }
    5859             : 
    5860       57934 : bool v8::V8::InitializeICUDefaultLocation(const char* exec_path,
    5861             :                                           const char* icu_data_file) {
    5862       57934 :   return i::InitializeICUDefaultLocation(exec_path, icu_data_file);
    5863             : }
    5864             : 
    5865       61017 : void v8::V8::InitializeExternalStartupData(const char* directory_path) {
    5866       61017 :   i::InitializeExternalStartupData(directory_path);
    5867       61017 : }
    5868             : 
    5869             : 
    5870           0 : void v8::V8::InitializeExternalStartupData(const char* natives_blob,
    5871             :                                            const char* snapshot_blob) {
    5872           0 :   i::InitializeExternalStartupData(natives_blob, snapshot_blob);
    5873           0 : }
    5874             : 
    5875             : 
    5876          33 : const char* v8::V8::GetVersion() {
    5877          33 :   return i::Version::GetVersion();
    5878             : }
    5879             : 
    5880             : template <typename ObjectType>
    5881             : struct InvokeBootstrapper;
    5882             : 
    5883             : template <>
    5884             : struct InvokeBootstrapper<i::Context> {
    5885             :   i::Handle<i::Context> Invoke(
    5886             :       i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy,
    5887             :       v8::Local<v8::ObjectTemplate> global_proxy_template,
    5888             :       v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
    5889             :       v8::DeserializeInternalFieldsCallback embedder_fields_deserializer,
    5890             :       v8::MicrotaskQueue* microtask_queue) {
    5891             :     return isolate->bootstrapper()->CreateEnvironment(
    5892             :         maybe_global_proxy, global_proxy_template, extensions,
    5893       91772 :         context_snapshot_index, embedder_fields_deserializer, microtask_queue);
    5894             :   }
    5895             : };
    5896             : 
    5897             : template <>
    5898             : struct InvokeBootstrapper<i::JSGlobalProxy> {
    5899             :   i::Handle<i::JSGlobalProxy> Invoke(
    5900             :       i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy,
    5901             :       v8::Local<v8::ObjectTemplate> global_proxy_template,
    5902             :       v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
    5903             :       v8::DeserializeInternalFieldsCallback embedder_fields_deserializer,
    5904             :       v8::MicrotaskQueue* microtask_queue) {
    5905             :     USE(extensions);
    5906             :     USE(context_snapshot_index);
    5907             :     return isolate->bootstrapper()->NewRemoteContext(maybe_global_proxy,
    5908          18 :                                                      global_proxy_template);
    5909             :   }
    5910             : };
    5911             : 
    5912             : template <typename ObjectType>
    5913       91790 : static i::Handle<ObjectType> CreateEnvironment(
    5914             :     i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
    5915             :     v8::MaybeLocal<ObjectTemplate> maybe_global_template,
    5916             :     v8::MaybeLocal<Value> maybe_global_proxy, size_t context_snapshot_index,
    5917             :     v8::DeserializeInternalFieldsCallback embedder_fields_deserializer,
    5918             :     v8::MicrotaskQueue* microtask_queue) {
    5919             :   i::Handle<ObjectType> result;
    5920             : 
    5921             :   {
    5922             :     ENTER_V8_FOR_NEW_CONTEXT(isolate);
    5923             :     v8::Local<ObjectTemplate> proxy_template;
    5924             :     i::Handle<i::FunctionTemplateInfo> proxy_constructor;
    5925             :     i::Handle<i::FunctionTemplateInfo> global_constructor;
    5926             :     i::Handle<i::Object> named_interceptor(
    5927             :         isolate->factory()->undefined_value());
    5928             :     i::Handle<i::Object> indexed_interceptor(
    5929             :         isolate->factory()->undefined_value());
    5930             : 
    5931       91790 :     if (!maybe_global_template.IsEmpty()) {
    5932             :       v8::Local<v8::ObjectTemplate> global_template =
    5933             :           maybe_global_template.ToLocalChecked();
    5934             :       // Make sure that the global_template has a constructor.
    5935       56330 :       global_constructor = EnsureConstructor(isolate, *global_template);
    5936             : 
    5937             :       // Create a fresh template for the global proxy object.
    5938             :       proxy_template = ObjectTemplate::New(
    5939             :           reinterpret_cast<v8::Isolate*>(isolate));
    5940       56330 :       proxy_constructor = EnsureConstructor(isolate, *proxy_template);
    5941             : 
    5942             :       // Set the global template to be the prototype template of
    5943             :       // global proxy template.
    5944       56330 :       i::FunctionTemplateInfo::SetPrototypeTemplate(
    5945             :           isolate, proxy_constructor, Utils::OpenHandle(*global_template));
    5946             : 
    5947       56330 :       proxy_template->SetInternalFieldCount(
    5948             :           global_template->InternalFieldCount());
    5949             : 
    5950             :       // Migrate security handlers from global_template to
    5951             :       // proxy_template.  Temporarily removing access check
    5952             :       // information from the global template.
    5953       56330 :       if (!global_constructor->GetAccessCheckInfo()->IsUndefined(isolate)) {
    5954         141 :         i::FunctionTemplateInfo::SetAccessCheckInfo(
    5955             :             isolate, proxy_constructor,
    5956             :             i::handle(global_constructor->GetAccessCheckInfo(), isolate));
    5957         282 :         proxy_constructor->set_needs_access_check(
    5958             :             global_constructor->needs_access_check());
    5959         141 :         global_constructor->set_needs_access_check(false);
    5960         141 :         i::FunctionTemplateInfo::SetAccessCheckInfo(
    5961             :             isolate, global_constructor,
    5962             :             i::ReadOnlyRoots(isolate).undefined_value_handle());
    5963             :       }
    5964             : 
    5965             :       // Same for other interceptors. If the global constructor has
    5966             :       // interceptors, we need to replace them temporarily with noop
    5967             :       // interceptors, so the map is correctly marked as having interceptors,
    5968             :       // but we don't invoke any.
    5969       56330 :       if (!global_constructor->GetNamedPropertyHandler()->IsUndefined(
    5970             :               isolate)) {
    5971         144 :         named_interceptor =
    5972             :             handle(global_constructor->GetNamedPropertyHandler(), isolate);
    5973         144 :         i::FunctionTemplateInfo::SetNamedPropertyHandler(
    5974             :             isolate, global_constructor,
    5975             :             i::ReadOnlyRoots(isolate).noop_interceptor_info_handle());
    5976             :       }
    5977       56330 :       if (!global_constructor->GetIndexedPropertyHandler()->IsUndefined(
    5978             :               isolate)) {
    5979           0 :         indexed_interceptor =
    5980             :             handle(global_constructor->GetIndexedPropertyHandler(), isolate);
    5981           0 :         i::FunctionTemplateInfo::SetIndexedPropertyHandler(
    5982             :             isolate, global_constructor,
    5983             :             i::ReadOnlyRoots(isolate).noop_interceptor_info_handle());
    5984             :       }
    5985             :     }
    5986             : 
    5987             :     i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
    5988       91790 :     if (!maybe_global_proxy.IsEmpty()) {
    5989             :       maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(
    5990             :           Utils::OpenHandle(*maybe_global_proxy.ToLocalChecked()));
    5991             :     }
    5992             :     // Create the environment.
    5993             :     InvokeBootstrapper<ObjectType> invoke;
    5994             :     result = invoke.Invoke(isolate, maybe_proxy, proxy_template, extensions,
    5995             :                            context_snapshot_index, embedder_fields_deserializer,
    5996             :                            microtask_queue);
    5997             : 
    5998             :     // Restore the access check info and interceptors on the global template.
    5999       91790 :     if (!maybe_global_template.IsEmpty()) {
    6000             :       DCHECK(!global_constructor.is_null());
    6001             :       DCHECK(!proxy_constructor.is_null());
    6002       56330 :       i::FunctionTemplateInfo::SetAccessCheckInfo(
    6003             :           isolate, global_constructor,
    6004             :           i::handle(proxy_constructor->GetAccessCheckInfo(), isolate));
    6005      112660 :       global_constructor->set_needs_access_check(
    6006             :           proxy_constructor->needs_access_check());
    6007       56330 :       i::FunctionTemplateInfo::SetNamedPropertyHandler(
    6008             :           isolate, global_constructor, named_interceptor);
    6009       56330 :       i::FunctionTemplateInfo::SetIndexedPropertyHandler(
    6010             :           isolate, global_constructor, indexed_interceptor);
    6011             :     }
    6012             :   }
    6013             :   // Leave V8.
    6014             : 
    6015       91790 :   return result;
    6016             : }
    6017             : 
    6018       91772 : Local<Context> NewContext(
    6019             :     v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
    6020             :     v8::MaybeLocal<ObjectTemplate> global_template,
    6021             :     v8::MaybeLocal<Value> global_object, size_t context_snapshot_index,
    6022             :     v8::DeserializeInternalFieldsCallback embedder_fields_deserializer,
    6023             :     v8::MicrotaskQueue* microtask_queue) {
    6024             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
    6025             :   // TODO(jkummerow): This is for crbug.com/713699. Remove it if it doesn't
    6026             :   // fail.
    6027             :   // Sanity-check that the isolate is initialized and usable.
    6028      183544 :   CHECK(isolate->builtins()->builtin(i::Builtins::kIllegal)->IsCode());
    6029             : 
    6030      183544 :   TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.NewContext");
    6031       91772 :   LOG_API(isolate, Context, New);
    6032             :   i::HandleScope scope(isolate);
    6033             :   ExtensionConfiguration no_extensions;
    6034       91772 :   if (extensions == nullptr) extensions = &no_extensions;
    6035             :   i::Handle<i::Context> env = CreateEnvironment<i::Context>(
    6036             :       isolate, extensions, global_template, global_object,
    6037       91772 :       context_snapshot_index, embedder_fields_deserializer, microtask_queue);
    6038       91772 :   if (env.is_null()) {
    6039          40 :     if (isolate->has_pending_exception()) isolate->clear_pending_exception();
    6040          40 :     return Local<Context>();
    6041             :   }
    6042       91732 :   return Utils::ToLocal(scope.CloseAndEscape(env));
    6043             : }
    6044             : 
    6045       91732 : Local<Context> v8::Context::New(
    6046             :     v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
    6047             :     v8::MaybeLocal<ObjectTemplate> global_template,
    6048             :     v8::MaybeLocal<Value> global_object,
    6049             :     DeserializeInternalFieldsCallback internal_fields_deserializer,
    6050             :     v8::MicrotaskQueue* microtask_queue) {
    6051             :   return NewContext(external_isolate, extensions, global_template,
    6052             :                     global_object, 0, internal_fields_deserializer,
    6053       91732 :                     microtask_queue);
    6054             : }
    6055             : 
    6056          45 : MaybeLocal<Context> v8::Context::FromSnapshot(
    6057             :     v8::Isolate* external_isolate, size_t context_snapshot_index,
    6058             :     v8::DeserializeInternalFieldsCallback embedder_fields_deserializer,
    6059             :     v8::ExtensionConfiguration* extensions, MaybeLocal<Value> global_object,
    6060             :     v8::MicrotaskQueue* microtask_queue) {
    6061          45 :   size_t index_including_default_context = context_snapshot_index + 1;
    6062          45 :   if (!i::Snapshot::HasContextSnapshot(
    6063             :           reinterpret_cast<i::Isolate*>(external_isolate),
    6064             :           index_including_default_context)) {
    6065           5 :     return MaybeLocal<Context>();
    6066             :   }
    6067             :   return NewContext(external_isolate, extensions, MaybeLocal<ObjectTemplate>(),
    6068             :                     global_object, index_including_default_context,
    6069          40 :                     embedder_fields_deserializer, microtask_queue);
    6070             : }
    6071             : 
    6072          18 : MaybeLocal<Object> v8::Context::NewRemoteContext(
    6073             :     v8::Isolate* external_isolate, v8::Local<ObjectTemplate> global_template,
    6074             :     v8::MaybeLocal<v8::Value> global_object) {
    6075             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
    6076          18 :   LOG_API(isolate, Context, NewRemoteContext);
    6077             :   i::HandleScope scope(isolate);
    6078             :   i::Handle<i::FunctionTemplateInfo> global_constructor =
    6079          18 :       EnsureConstructor(isolate, *global_template);
    6080             :   Utils::ApiCheck(global_constructor->needs_access_check(),
    6081             :                   "v8::Context::NewRemoteContext",
    6082             :                   "Global template needs to have access checks enabled.");
    6083             :   i::Handle<i::AccessCheckInfo> access_check_info = i::handle(
    6084             :       i::AccessCheckInfo::cast(global_constructor->GetAccessCheckInfo()),
    6085             :       isolate);
    6086             :   Utils::ApiCheck(access_check_info->named_interceptor() != i::Object(),
    6087             :                   "v8::Context::NewRemoteContext",
    6088             :                   "Global template needs to have access check handlers.");
    6089             :   i::Handle<i::JSObject> global_proxy = CreateEnvironment<i::JSGlobalProxy>(
    6090             :       isolate, nullptr, global_template, global_object, 0,
    6091          18 :       DeserializeInternalFieldsCallback(), nullptr);
    6092          18 :   if (global_proxy.is_null()) {
    6093           0 :     if (isolate->has_pending_exception()) isolate->clear_pending_exception();
    6094           0 :     return MaybeLocal<Object>();
    6095             :   }
    6096          18 :   return Utils::ToLocal(scope.CloseAndEscape(global_proxy));
    6097             : }
    6098             : 
    6099         263 : void v8::Context::SetSecurityToken(Local<Value> token) {
    6100             :   i::Handle<i::Context> env = Utils::OpenHandle(this);
    6101             :   i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
    6102         263 :   env->set_security_token(*token_handle);
    6103         263 : }
    6104             : 
    6105             : 
    6106           0 : void v8::Context::UseDefaultSecurityToken() {
    6107             :   i::Handle<i::Context> env = Utils::OpenHandle(this);
    6108           0 :   env->set_security_token(env->global_object());
    6109           0 : }
    6110             : 
    6111             : 
    6112          17 : Local<Value> v8::Context::GetSecurityToken() {
    6113             :   i::Handle<i::Context> env = Utils::OpenHandle(this);
    6114             :   i::Isolate* isolate = env->GetIsolate();
    6115          17 :   i::Object security_token = env->security_token();
    6116             :   i::Handle<i::Object> token_handle(security_token, isolate);
    6117          17 :   return Utils::ToLocal(token_handle);
    6118             : }
    6119             : 
    6120             : 
    6121    16686708 : v8::Isolate* Context::GetIsolate() {
    6122             :   i::Handle<i::Context> env = Utils::OpenHandle(this);
    6123    16686708 :   return reinterpret_cast<Isolate*>(env->GetIsolate());
    6124             : }
    6125             : 
    6126      421963 : v8::Local<v8::Object> Context::Global() {
    6127             :   i::Handle<i::Context> context = Utils::OpenHandle(this);
    6128             :   i::Isolate* isolate = context->GetIsolate();
    6129      843925 :   i::Handle<i::Object> global(context->global_proxy(), isolate);
    6130             :   // TODO(dcarney): This should always return the global proxy
    6131             :   // but can't presently as calls to GetProtoype will return the wrong result.
    6132      843924 :   if (i::Handle<i::JSGlobalProxy>::cast(
    6133     1265886 :           global)->IsDetachedFrom(context->global_object())) {
    6134         130 :     global = i::Handle<i::Object>(context->global_object(), isolate);
    6135             :   }
    6136      421963 :   return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
    6137             : }
    6138             : 
    6139             : 
    6140         126 : void Context::DetachGlobal() {
    6141             :   i::Handle<i::Context> context = Utils::OpenHandle(this);
    6142             :   i::Isolate* isolate = context->GetIsolate();
    6143             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    6144         126 :   isolate->bootstrapper()->DetachGlobal(context);
    6145         126 : }
    6146             : 
    6147             : 
    6148          45 : Local<v8::Object> Context::GetExtrasBindingObject() {
    6149             :   i::Handle<i::Context> context = Utils::OpenHandle(this);
    6150             :   i::Isolate* isolate = context->GetIsolate();
    6151          90 :   i::Handle<i::JSObject> binding(context->extras_binding_object(), isolate);
    6152          45 :   return Utils::ToLocal(binding);
    6153             : }
    6154             : 
    6155             : 
    6156         158 : void Context::AllowCodeGenerationFromStrings(bool allow) {
    6157             :   i::Handle<i::Context> context = Utils::OpenHandle(this);
    6158             :   i::Isolate* isolate = context->GetIsolate();
    6159             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    6160         632 :   context->set_allow_code_gen_from_strings(
    6161             :       allow ? i::ReadOnlyRoots(isolate).true_value()
    6162         158 :             : i::ReadOnlyRoots(isolate).false_value());
    6163         158 : }
    6164             : 
    6165             : 
    6166        9673 : bool Context::IsCodeGenerationFromStringsAllowed() {
    6167             :   i::Handle<i::Context> context = Utils::OpenHandle(this);
    6168       19346 :   return !context->allow_code_gen_from_strings()->IsFalse(
    6169       19346 :       context->GetIsolate());
    6170             : }
    6171             : 
    6172             : 
    6173           5 : void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
    6174             :   i::Handle<i::Context> context = Utils::OpenHandle(this);
    6175             :   i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
    6176          10 :   context->set_error_message_for_code_gen_from_strings(*error_handle);
    6177           5 : }
    6178             : 
    6179             : namespace {
    6180         175 : i::Address* GetSerializedDataFromFixedArray(i::Isolate* isolate,
    6181             :                                             i::FixedArray list, size_t index) {
    6182         175 :   if (index < static_cast<size_t>(list->length())) {
    6183         150 :     int int_index = static_cast<int>(index);
    6184             :     i::Object object = list->get(int_index);
    6185         150 :     if (!object->IsTheHole(isolate)) {
    6186             :       list->set_the_hole(isolate, int_index);
    6187             :       // Shrink the list so that the last element is not the hole (unless it's
    6188             :       // the first element, because we don't want to end up with a non-canonical
    6189             :       // empty FixedArray).
    6190          80 :       int last = list->length() - 1;
    6191         280 :       while (last >= 0 && list->is_the_hole(isolate, last)) last--;
    6192          80 :       if (last != -1) list->Shrink(isolate, last + 1);
    6193             :       return i::Handle<i::Object>(object, isolate).location();
    6194             :     }
    6195             :   }
    6196             :   return nullptr;
    6197             : }
    6198             : }  // anonymous namespace
    6199             : 
    6200          90 : i::Address* Context::GetDataFromSnapshotOnce(size_t index) {
    6201             :   auto context = Utils::OpenHandle(this);
    6202             :   i::Isolate* i_isolate = context->GetIsolate();
    6203          90 :   i::FixedArray list = context->serialized_objects();
    6204          90 :   return GetSerializedDataFromFixedArray(i_isolate, list, index);
    6205             : }
    6206             : 
    6207        2574 : MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
    6208       10296 :   PREPARE_FOR_EXECUTION(context, ObjectTemplate, NewInstance, Object);
    6209        2574 :   auto self = Utils::OpenHandle(this);
    6210             :   Local<Object> result;
    6211        5148 :   has_pending_exception = !ToLocal<Object>(
    6212             :       i::ApiNatives::InstantiateObject(isolate, self), &result);
    6213        2574 :   RETURN_ON_FAILED_EXECUTION(Object);
    6214        2574 :   RETURN_ESCAPED(result);
    6215             : }
    6216             : 
    6217           0 : void v8::ObjectTemplate::CheckCast(Data* that) {
    6218             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    6219             :   Utils::ApiCheck(obj->IsObjectTemplateInfo(), "v8::ObjectTemplate::Cast",
    6220             :                   "Could not convert to object template");
    6221           0 : }
    6222             : 
    6223           0 : void v8::FunctionTemplate::CheckCast(Data* that) {
    6224             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    6225             :   Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::FunctionTemplate::Cast",
    6226             :                   "Could not convert to function template");
    6227           0 : }
    6228             : 
    6229           0 : void v8::Signature::CheckCast(Data* that) {
    6230             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    6231             :   Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::Signature::Cast",
    6232             :                   "Could not convert to signature");
    6233           0 : }
    6234             : 
    6235           0 : void v8::AccessorSignature::CheckCast(Data* that) {
    6236             :   i::Handle<i::Object> obj = Utils::OpenHandle(that);
    6237             :   Utils::ApiCheck(obj->IsFunctionTemplateInfo(), "v8::AccessorSignature::Cast",
    6238             :                   "Could not convert to accessor signature");
    6239           0 : }
    6240             : 
    6241       10949 : MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
    6242       43796 :   PREPARE_FOR_EXECUTION(context, FunctionTemplate, GetFunction, Function);
    6243       10949 :   auto self = Utils::OpenHandle(this);
    6244             :   Local<Function> result;
    6245             :   has_pending_exception =
    6246       21898 :       !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
    6247       10949 :   RETURN_ON_FAILED_EXECUTION(Function);
    6248       10949 :   RETURN_ESCAPED(result);
    6249             : }
    6250             : 
    6251           8 : MaybeLocal<v8::Object> FunctionTemplate::NewRemoteInstance() {
    6252             :   auto self = Utils::OpenHandle(this);
    6253             :   i::Isolate* isolate = self->GetIsolate();
    6254           8 :   LOG_API(isolate, FunctionTemplate, NewRemoteInstance);
    6255             :   i::HandleScope scope(isolate);
    6256             :   i::Handle<i::FunctionTemplateInfo> constructor =
    6257          16 :       EnsureConstructor(isolate, *InstanceTemplate());
    6258             :   Utils::ApiCheck(constructor->needs_access_check(),
    6259             :                   "v8::FunctionTemplate::NewRemoteInstance",
    6260             :                   "InstanceTemplate needs to have access checks enabled.");
    6261             :   i::Handle<i::AccessCheckInfo> access_check_info = i::handle(
    6262             :       i::AccessCheckInfo::cast(constructor->GetAccessCheckInfo()), isolate);
    6263             :   Utils::ApiCheck(access_check_info->named_interceptor() != i::Object(),
    6264             :                   "v8::FunctionTemplate::NewRemoteInstance",
    6265             :                   "InstanceTemplate needs to have access check handlers.");
    6266             :   i::Handle<i::JSObject> object;
    6267          24 :   if (!i::ApiNatives::InstantiateRemoteObject(
    6268          16 :            Utils::OpenHandle(*InstanceTemplate()))
    6269             :            .ToHandle(&object)) {
    6270           0 :     if (isolate->has_pending_exception()) {
    6271           0 :       isolate->OptionalRescheduleException(true);
    6272             :     }
    6273           0 :     return MaybeLocal<Object>();
    6274             :   }
    6275           8 :   return Utils::ToLocal(scope.CloseAndEscape(object));
    6276             : }
    6277             : 
    6278         152 : bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) {
    6279             :   auto self = Utils::OpenHandle(this);
    6280             :   auto obj = Utils::OpenHandle(*value);
    6281         304 :   if (obj->IsJSObject() && self->IsTemplateFor(i::JSObject::cast(*obj))) {
    6282             :     return true;
    6283             :   }
    6284          38 :   if (obj->IsJSGlobalProxy()) {
    6285             :     // If it's a global proxy, then test with the global object. Note that the
    6286             :     // inner global object may not necessarily be a JSGlobalObject.
    6287             :     i::PrototypeIterator iter(self->GetIsolate(),
    6288           2 :                               i::JSObject::cast(*obj)->map());
    6289             :     // The global proxy should always have a prototype, as it is a bug to call
    6290             :     // this on a detached JSGlobalProxy.
    6291             :     DCHECK(!iter.IsAtEnd());
    6292           2 :     return self->IsTemplateFor(iter.GetCurrent<i::JSObject>());
    6293             :   }
    6294             :   return false;
    6295             : }
    6296             : 
    6297             : 
    6298        3914 : Local<External> v8::External::New(Isolate* isolate, void* value) {
    6299             :   STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
    6300             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6301        3914 :   LOG_API(i_isolate, External, New);
    6302             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6303        3914 :   i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
    6304        3914 :   return Utils::ExternalToLocal(external);
    6305             : }
    6306             : 
    6307             : 
    6308     1154445 : void* External::Value() const {
    6309     1154445 :   return ExternalValue(*Utils::OpenHandle(this));
    6310             : }
    6311             : 
    6312             : 
    6313             : // anonymous namespace for string creation helper functions
    6314             : namespace {
    6315             : 
    6316             : inline int StringLength(const char* string) {
    6317             :   return i::StrLength(string);
    6318             : }
    6319             : 
    6320             : 
    6321             : inline int StringLength(const uint8_t* string) {
    6322             :   return i::StrLength(reinterpret_cast<const char*>(string));
    6323             : }
    6324             : 
    6325             : 
    6326             : inline int StringLength(const uint16_t* string) {
    6327             :   int length = 0;
    6328        4083 :   while (string[length] != '\0')
    6329        4025 :     length++;
    6330             :   return length;
    6331             : }
    6332             : 
    6333             : V8_WARN_UNUSED_RESULT
    6334     9528651 : inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
    6335             :                                            v8::NewStringType type,
    6336             :                                            i::Vector<const char> string) {
    6337     9528651 :   if (type == v8::NewStringType::kInternalized) {
    6338       72928 :     return factory->InternalizeUtf8String(string);
    6339             :   }
    6340     9455723 :   return factory->NewStringFromUtf8(string);
    6341             : }
    6342             : 
    6343             : V8_WARN_UNUSED_RESULT
    6344          24 : inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
    6345             :                                            v8::NewStringType type,
    6346             :                                            i::Vector<const uint8_t> string) {
    6347          24 :   if (type == v8::NewStringType::kInternalized) {
    6348           0 :     return factory->InternalizeOneByteString(string);
    6349             :   }
    6350          24 :   return factory->NewStringFromOneByte(string);
    6351             : }
    6352             : 
    6353             : V8_WARN_UNUSED_RESULT
    6354     1209909 : inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
    6355             :                                            v8::NewStringType type,
    6356             :                                            i::Vector<const uint16_t> string) {
    6357     1209909 :   if (type == v8::NewStringType::kInternalized) {
    6358           0 :     return factory->InternalizeTwoByteString(string);
    6359             :   }
    6360     1209909 :   return factory->NewStringFromTwoByte(string);
    6361             : }
    6362             : 
    6363             : 
    6364             : STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
    6365             : 
    6366             : }  // anonymous namespace
    6367             : 
    6368             : // TODO(dcarney): throw a context free exception.
    6369             : #define NEW_STRING(isolate, class_name, function_name, Char, data, type,   \
    6370             :                    length)                                                 \
    6371             :   MaybeLocal<String> result;                                               \
    6372             :   if (length == 0) {                                                       \
    6373             :     result = String::Empty(isolate);                                       \
    6374             :   } else if (length > i::String::kMaxLength) {                             \
    6375             :     result = MaybeLocal<String>();                                         \
    6376             :   } else {                                                                 \
    6377             :     i::Isolate* i_isolate = reinterpret_cast<internal::Isolate*>(isolate); \
    6378             :     ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);                            \
    6379             :     LOG_API(i_isolate, class_name, function_name);                         \
    6380             :     if (length < 0) length = StringLength(data);                           \
    6381             :     i::Handle<i::String> handle_result =                                   \
    6382             :         NewString(i_isolate->factory(), type,                              \
    6383             :                   i::Vector<const Char>(data, length))                     \
    6384             :             .ToHandleChecked();                                            \
    6385             :     result = Utils::ToLocal(handle_result);                                \
    6386             :   }
    6387             : 
    6388           0 : Local<String> String::NewFromUtf8(Isolate* isolate,
    6389             :                                   const char* data,
    6390             :                                   NewStringType type,
    6391             :                                   int length) {
    6392           0 :   NEW_STRING(isolate, String, NewFromUtf8, char, data,
    6393             :              static_cast<v8::NewStringType>(type), length);
    6394           0 :   RETURN_TO_LOCAL_UNCHECKED(result, String);
    6395             : }
    6396             : 
    6397             : 
    6398     9528670 : MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
    6399             :                                        v8::NewStringType type, int length) {
    6400    57171929 :   NEW_STRING(isolate, String, NewFromUtf8, char, data, type, length);
    6401     9528669 :   return result;
    6402             : }
    6403             : 
    6404             : 
    6405          39 : MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
    6406             :                                           v8::NewStringType type, int length) {
    6407         164 :   NEW_STRING(isolate, String, NewFromOneByte, uint8_t, data, type, length);
    6408          39 :   return result;
    6409             : }
    6410             : 
    6411             : 
    6412           0 : Local<String> String::NewFromTwoByte(Isolate* isolate,
    6413             :                                      const uint16_t* data,
    6414             :                                      NewStringType type,
    6415             :                                      int length) {
    6416           0 :   NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data,
    6417             :              static_cast<v8::NewStringType>(type), length);
    6418           0 :   RETURN_TO_LOCAL_UNCHECKED(result, String);
    6419             : }
    6420             : 
    6421             : 
    6422     1213364 : MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate,
    6423             :                                           const uint16_t* data,
    6424             :                                           v8::NewStringType type, int length) {
    6425     7262915 :   NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data, type, length);
    6426     1213367 :   return result;
    6427             : }
    6428             : 
    6429      140624 : Local<String> v8::String::Concat(Isolate* v8_isolate, Local<String> left,
    6430             :                                  Local<String> right) {
    6431             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    6432             :   i::Handle<i::String> left_string = Utils::OpenHandle(*left);
    6433             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    6434      140624 :   LOG_API(isolate, String, Concat);
    6435             :   i::Handle<i::String> right_string = Utils::OpenHandle(*right);
    6436             :   // If we are steering towards a range error, do not wait for the error to be
    6437             :   // thrown, and return the null handle instead.
    6438      140624 :   if (left_string->length() + right_string->length() > i::String::kMaxLength) {
    6439          10 :     return Local<String>();
    6440             :   }
    6441      281228 :   i::Handle<i::String> result = isolate->factory()->NewConsString(
    6442             :       left_string, right_string).ToHandleChecked();
    6443             :   return Utils::ToLocal(result);
    6444             : }
    6445             : 
    6446       18910 : MaybeLocal<String> v8::String::NewExternalTwoByte(
    6447             :     Isolate* isolate, v8::String::ExternalStringResource* resource) {
    6448       18910 :   CHECK(resource && resource->data());
    6449             :   // TODO(dcarney): throw a context free exception.
    6450       18910 :   if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
    6451           6 :     return MaybeLocal<String>();
    6452             :   }
    6453             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6454             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6455       18904 :   LOG_API(i_isolate, String, NewExternalTwoByte);
    6456       18904 :   if (resource->length() > 0) {
    6457             :     i::Handle<i::String> string = i_isolate->factory()
    6458       37788 :                                       ->NewExternalStringFromTwoByte(resource)
    6459             :                                       .ToHandleChecked();
    6460       18894 :     return Utils::ToLocal(string);
    6461             :   } else {
    6462             :     // The resource isn't going to be used, free it immediately.
    6463          10 :     resource->Dispose();
    6464          10 :     return Utils::ToLocal(i_isolate->factory()->empty_string());
    6465             :   }
    6466             : }
    6467             : 
    6468             : 
    6469        1292 : MaybeLocal<String> v8::String::NewExternalOneByte(
    6470             :     Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
    6471        1292 :   CHECK(resource && resource->data());
    6472             :   // TODO(dcarney): throw a context free exception.
    6473        1292 :   if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
    6474           6 :     return MaybeLocal<String>();
    6475             :   }
    6476             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6477             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6478        1286 :   LOG_API(i_isolate, String, NewExternalOneByte);
    6479        1286 :   if (resource->length() > 0) {
    6480             :     i::Handle<i::String> string = i_isolate->factory()
    6481        2562 :                                       ->NewExternalStringFromOneByte(resource)
    6482             :                                       .ToHandleChecked();
    6483        1281 :     return Utils::ToLocal(string);
    6484             :   } else {
    6485             :     // The resource isn't going to be used, free it immediately.
    6486           5 :     resource->Dispose();
    6487           5 :     return Utils::ToLocal(i_isolate->factory()->empty_string());
    6488             :   }
    6489             : }
    6490             : 
    6491             : 
    6492           0 : Local<String> v8::String::NewExternal(
    6493             :     Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
    6494           0 :   RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
    6495             : }
    6496             : 
    6497             : 
    6498         300 : bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
    6499             :   i::DisallowHeapAllocation no_allocation;
    6500             : 
    6501         300 :   i::String obj = *Utils::OpenHandle(this);
    6502             : 
    6503         300 :   if (obj->IsThinString()) {
    6504           0 :     obj = i::ThinString::cast(obj)->actual();
    6505             :   }
    6506             : 
    6507         300 :   if (!obj->SupportsExternalization()) {
    6508             :     return false;
    6509             :   }
    6510             : 
    6511             :   // It is safe to call GetIsolateFromWritableHeapObject because
    6512             :   // SupportsExternalization already checked that the object is writable.
    6513             :   i::Isolate* isolate;
    6514             :   i::GetIsolateFromWritableObject(obj, &isolate);
    6515             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    6516             : 
    6517         300 :   CHECK(resource && resource->data());
    6518             : 
    6519         300 :   bool result = obj->MakeExternal(resource);
    6520             :   DCHECK(result);
    6521             :   DCHECK(obj->IsExternalString());
    6522             :   return result;
    6523             : }
    6524             : 
    6525             : 
    6526         300 : bool v8::String::MakeExternal(
    6527             :     v8::String::ExternalOneByteStringResource* resource) {
    6528             :   i::DisallowHeapAllocation no_allocation;
    6529             : 
    6530         300 :   i::String obj = *Utils::OpenHandle(this);
    6531             : 
    6532         300 :   if (obj->IsThinString()) {
    6533           0 :     obj = i::ThinString::cast(obj)->actual();
    6534             :   }
    6535             : 
    6536         300 :   if (!obj->SupportsExternalization()) {
    6537             :     return false;
    6538             :   }
    6539             : 
    6540             :   // It is safe to call GetIsolateFromWritableHeapObject because
    6541             :   // SupportsExternalization already checked that the object is writable.
    6542             :   i::Isolate* isolate;
    6543             :   i::GetIsolateFromWritableObject(obj, &isolate);
    6544             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    6545             : 
    6546         300 :   CHECK(resource && resource->data());
    6547             : 
    6548         300 :   bool result = obj->MakeExternal(resource);
    6549             :   DCHECK_IMPLIES(result, obj->IsExternalString());
    6550             :   return result;
    6551             : }
    6552             : 
    6553             : 
    6554          40 : bool v8::String::CanMakeExternal() {
    6555             :   i::DisallowHeapAllocation no_allocation;
    6556          40 :   i::String obj = *Utils::OpenHandle(this);
    6557             : 
    6558          40 :   if (obj->IsThinString()) {
    6559           0 :     obj = i::ThinString::cast(obj)->actual();
    6560             :   }
    6561             : 
    6562          40 :   if (!obj->SupportsExternalization()) {
    6563             :     return false;
    6564             :   }
    6565             : 
    6566             :   // Only old space strings should be externalized.
    6567          40 :   return !i::Heap::InYoungGeneration(obj);
    6568             : }
    6569             : 
    6570       18632 : bool v8::String::StringEquals(Local<String> that) {
    6571             :   auto self = Utils::OpenHandle(this);
    6572             :   auto other = Utils::OpenHandle(*that);
    6573       18632 :   return self->Equals(*other);
    6574             : }
    6575             : 
    6576       80060 : Isolate* v8::Object::GetIsolate() {
    6577             :   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
    6578       80060 :   return reinterpret_cast<Isolate*>(i_isolate);
    6579             : }
    6580             : 
    6581             : 
    6582      107886 : Local<v8::Object> v8::Object::New(Isolate* isolate) {
    6583             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6584      107886 :   LOG_API(i_isolate, Object, New);
    6585             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6586             :   i::Handle<i::JSObject> obj =
    6587      107886 :       i_isolate->factory()->NewJSObject(i_isolate->object_function());
    6588      107886 :   return Utils::ToLocal(obj);
    6589             : }
    6590             : 
    6591          48 : Local<v8::Object> v8::Object::New(Isolate* isolate,
    6592             :                                   Local<Value> prototype_or_null,
    6593             :                                   Local<Name>* names, Local<Value>* values,
    6594             :                                   size_t length) {
    6595             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6596             :   i::Handle<i::Object> proto = Utils::OpenHandle(*prototype_or_null);
    6597         108 :   if (!Utils::ApiCheck(proto->IsNull() || proto->IsJSReceiver(),
    6598             :                        "v8::Object::New", "prototype must be null or object")) {
    6599           0 :     return Local<v8::Object>();
    6600             :   }
    6601          48 :   LOG_API(i_isolate, Object, New);
    6602             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6603             : 
    6604             :   // We assume that this API is mostly used to create objects with named
    6605             :   // properties, and so we default to creating a properties backing store
    6606             :   // large enough to hold all of them, while we start with no elements
    6607             :   // (see http://bit.ly/v8-fast-object-create-cpp for the motivation).
    6608             :   i::Handle<i::NameDictionary> properties =
    6609          48 :       i::NameDictionary::New(i_isolate, static_cast<int>(length));
    6610             :   i::Handle<i::FixedArrayBase> elements =
    6611             :       i_isolate->factory()->empty_fixed_array();
    6612      123084 :   for (size_t i = 0; i < length; ++i) {
    6613       61518 :     i::Handle<i::Name> name = Utils::OpenHandle(*names[i]);
    6614       61518 :     i::Handle<i::Object> value = Utils::OpenHandle(*values[i]);
    6615             : 
    6616             :     // See if the {name} is a valid array index, in which case we need to
    6617             :     // add the {name}/{value} pair to the {elements}, otherwise they end
    6618             :     // up in the {properties} backing store.
    6619             :     uint32_t index;
    6620       61518 :     if (name->AsArrayIndex(&index)) {
    6621             :       // If this is the first element, allocate a proper
    6622             :       // dictionary elements backing store for {elements}.
    6623          18 :       if (!elements->IsNumberDictionary()) {
    6624             :         elements =
    6625          12 :             i::NumberDictionary::New(i_isolate, static_cast<int>(length));
    6626             :       }
    6627             :       elements = i::NumberDictionary::Set(
    6628             :           i_isolate, i::Handle<i::NumberDictionary>::cast(elements), index,
    6629          18 :           value);
    6630             :     } else {
    6631             :       // Internalize the {name} first.
    6632       61500 :       name = i_isolate->factory()->InternalizeName(name);
    6633       61500 :       int const entry = properties->FindEntry(i_isolate, name);
    6634       61500 :       if (entry == i::NameDictionary::kNotFound) {
    6635             :         // Add the {name}/{value} pair as a new entry.
    6636             :         properties = i::NameDictionary::Add(i_isolate, properties, name, value,
    6637       61488 :                                             i::PropertyDetails::Empty());
    6638             :       } else {
    6639             :         // Overwrite the {entry} with the {value}.
    6640          24 :         properties->ValueAtPut(entry, *value);
    6641             :       }
    6642             :     }
    6643             :   }
    6644             :   i::Handle<i::JSObject> obj =
    6645             :       i_isolate->factory()->NewSlowJSObjectWithPropertiesAndElements(
    6646          48 :           i::Handle<i::HeapObject>::cast(proto), properties, elements);
    6647             :   return Utils::ToLocal(obj);
    6648             : }
    6649             : 
    6650           6 : Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
    6651             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6652           6 :   LOG_API(i_isolate, NumberObject, New);
    6653             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6654           6 :   i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
    6655             :   i::Handle<i::Object> obj =
    6656          12 :       i::Object::ToObject(i_isolate, number).ToHandleChecked();
    6657           6 :   return Utils::ToLocal(obj);
    6658             : }
    6659             : 
    6660             : 
    6661          29 : double v8::NumberObject::ValueOf() const {
    6662             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    6663             :   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
    6664             :   i::Isolate* isolate = jsvalue->GetIsolate();
    6665          29 :   LOG_API(isolate, NumberObject, NumberValue);
    6666          29 :   return jsvalue->value()->Number();
    6667             : }
    6668             : 
    6669           7 : Local<v8::Value> v8::BigIntObject::New(Isolate* isolate, int64_t value) {
    6670             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6671           7 :   LOG_API(i_isolate, BigIntObject, New);
    6672             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6673           7 :   i::Handle<i::Object> bigint = i::BigInt::FromInt64(i_isolate, value);
    6674             :   i::Handle<i::Object> obj =
    6675          14 :       i::Object::ToObject(i_isolate, bigint).ToHandleChecked();
    6676           7 :   return Utils::ToLocal(obj);
    6677             : }
    6678             : 
    6679          11 : Local<v8::BigInt> v8::BigIntObject::ValueOf() const {
    6680             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    6681             :   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
    6682             :   i::Isolate* isolate = jsvalue->GetIsolate();
    6683          11 :   LOG_API(isolate, BigIntObject, BigIntValue);
    6684             :   return Utils::ToLocal(
    6685          11 :       i::Handle<i::BigInt>(i::BigInt::cast(jsvalue->value()), isolate));
    6686             : }
    6687             : 
    6688          24 : Local<v8::Value> v8::BooleanObject::New(Isolate* isolate, bool value) {
    6689             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6690          24 :   LOG_API(i_isolate, BooleanObject, New);
    6691             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6692             :   i::Handle<i::Object> boolean(value
    6693             :                                    ? i::ReadOnlyRoots(i_isolate).true_value()
    6694             :                                    : i::ReadOnlyRoots(i_isolate).false_value(),
    6695          24 :                                i_isolate);
    6696             :   i::Handle<i::Object> obj =
    6697          48 :       i::Object::ToObject(i_isolate, boolean).ToHandleChecked();
    6698          24 :   return Utils::ToLocal(obj);
    6699             : }
    6700             : 
    6701             : 
    6702          47 : bool v8::BooleanObject::ValueOf() const {
    6703             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    6704             :   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
    6705             :   i::Isolate* isolate = jsvalue->GetIsolate();
    6706          47 :   LOG_API(isolate, BooleanObject, BooleanValue);
    6707          47 :   return jsvalue->value()->IsTrue(isolate);
    6708             : }
    6709             : 
    6710             : 
    6711          12 : Local<v8::Value> v8::StringObject::New(Isolate* v8_isolate,
    6712             :                                        Local<String> value) {
    6713             :   i::Handle<i::String> string = Utils::OpenHandle(*value);
    6714             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    6715          12 :   LOG_API(isolate, StringObject, New);
    6716             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    6717             :   i::Handle<i::Object> obj =
    6718          24 :       i::Object::ToObject(isolate, string).ToHandleChecked();
    6719          12 :   return Utils::ToLocal(obj);
    6720             : }
    6721             : 
    6722             : 
    6723          34 : Local<v8::String> v8::StringObject::ValueOf() const {
    6724             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    6725             :   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
    6726             :   i::Isolate* isolate = jsvalue->GetIsolate();
    6727          34 :   LOG_API(isolate, StringObject, StringValue);
    6728             :   return Utils::ToLocal(
    6729          34 :       i::Handle<i::String>(i::String::cast(jsvalue->value()), isolate));
    6730             : }
    6731             : 
    6732             : 
    6733           6 : Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
    6734             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6735           6 :   LOG_API(i_isolate, SymbolObject, New);
    6736             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6737          12 :   i::Handle<i::Object> obj = i::Object::ToObject(
    6738           6 :       i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
    6739           6 :   return Utils::ToLocal(obj);
    6740             : }
    6741             : 
    6742             : 
    6743          11 : Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
    6744             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    6745             :   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
    6746             :   i::Isolate* isolate = jsvalue->GetIsolate();
    6747          11 :   LOG_API(isolate, SymbolObject, SymbolValue);
    6748             :   return Utils::ToLocal(
    6749          11 :       i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value()), isolate));
    6750             : }
    6751             : 
    6752             : 
    6753         132 : MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
    6754         132 :   if (std::isnan(time)) {
    6755             :     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
    6756             :     time = std::numeric_limits<double>::quiet_NaN();
    6757             :   }
    6758         528 :   PREPARE_FOR_EXECUTION(context, Date, New, Value);
    6759             :   Local<Value> result;
    6760         396 :   has_pending_exception = !ToLocal<Value>(
    6761             :       i::JSDate::New(isolate->date_function(), isolate->date_function(), time),
    6762             :       &result);
    6763         132 :   RETURN_ON_FAILED_EXECUTION(Value);
    6764         132 :   RETURN_ESCAPED(result);
    6765             : }
    6766             : 
    6767             : 
    6768          10 : double v8::Date::ValueOf() const {
    6769             :   i::Handle<i::Object> obj = Utils::OpenHandle(this);
    6770             :   i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
    6771             :   i::Isolate* isolate = jsdate->GetIsolate();
    6772          10 :   LOG_API(isolate, Date, NumberValue);
    6773          10 :   return jsdate->value()->Number();
    6774             : }
    6775             : 
    6776             : // Assert that the static TimeZoneDetection cast in
    6777             : // DateTimeConfigurationChangeNotification is valid.
    6778             : #define TIME_ZONE_DETECTION_ASSERT_EQ(value)                               \
    6779             :   STATIC_ASSERT(                                                           \
    6780             :       static_cast<int>(v8::Isolate::TimeZoneDetection::value) ==           \
    6781             :       static_cast<int>(base::TimezoneCache::TimeZoneDetection::value));    \
    6782             :   STATIC_ASSERT(static_cast<int>(v8::Isolate::TimeZoneDetection::value) == \
    6783             :                 static_cast<int>(v8::Date::TimeZoneDetection::value));
    6784             : TIME_ZONE_DETECTION_ASSERT_EQ(kSkip)
    6785             : TIME_ZONE_DETECTION_ASSERT_EQ(kRedetect)
    6786             : #undef TIME_ZONE_DETECTION_ASSERT_EQ
    6787             : 
    6788             : // static
    6789           0 : void v8::Date::DateTimeConfigurationChangeNotification(
    6790             :     Isolate* isolate, TimeZoneDetection time_zone_detection) {
    6791             :   isolate->DateTimeConfigurationChangeNotification(
    6792           0 :       static_cast<v8::Isolate::TimeZoneDetection>(time_zone_detection));
    6793           0 : }
    6794             : 
    6795         210 : MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context,
    6796             :                                        Local<String> pattern, Flags flags) {
    6797         840 :   PREPARE_FOR_EXECUTION(context, RegExp, New, RegExp);
    6798             :   Local<v8::RegExp> result;
    6799             :   has_pending_exception =
    6800         630 :       !ToLocal<RegExp>(i::JSRegExp::New(isolate, Utils::OpenHandle(*pattern),
    6801             :                                         static_cast<i::JSRegExp::Flags>(flags)),
    6802             :                        &result);
    6803         210 :   RETURN_ON_FAILED_EXECUTION(RegExp);
    6804         200 :   RETURN_ESCAPED(result);
    6805             : }
    6806             : 
    6807             : 
    6808         120 : Local<v8::String> v8::RegExp::GetSource() const {
    6809             :   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
    6810             :   return Utils::ToLocal(
    6811         120 :       i::Handle<i::String>(obj->Pattern(), obj->GetIsolate()));
    6812             : }
    6813             : 
    6814             : 
    6815             : // Assert that the static flags cast in GetFlags is valid.
    6816             : #define REGEXP_FLAG_ASSERT_EQ(flag)                   \
    6817             :   STATIC_ASSERT(static_cast<int>(v8::RegExp::flag) == \
    6818             :                 static_cast<int>(i::JSRegExp::flag))
    6819             : REGEXP_FLAG_ASSERT_EQ(kNone);
    6820             : REGEXP_FLAG_ASSERT_EQ(kGlobal);
    6821             : REGEXP_FLAG_ASSERT_EQ(kIgnoreCase);
    6822             : REGEXP_FLAG_ASSERT_EQ(kMultiline);
    6823             : REGEXP_FLAG_ASSERT_EQ(kSticky);
    6824             : REGEXP_FLAG_ASSERT_EQ(kUnicode);
    6825             : #undef REGEXP_FLAG_ASSERT_EQ
    6826             : 
    6827         120 : v8::RegExp::Flags v8::RegExp::GetFlags() const {
    6828             :   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
    6829         120 :   return RegExp::Flags(static_cast<int>(obj->GetFlags()));
    6830             : }
    6831             : 
    6832             : 
    6833       69706 : Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
    6834             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6835       69706 :   LOG_API(i_isolate, Array, New);
    6836             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6837       69706 :   int real_length = length > 0 ? length : 0;
    6838             :   i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
    6839             :   i::Handle<i::Object> length_obj =
    6840       69706 :       i_isolate->factory()->NewNumberFromInt(real_length);
    6841       69706 :   obj->set_length(*length_obj);
    6842       69706 :   return Utils::ToLocal(obj);
    6843             : }
    6844             : 
    6845           6 : Local<v8::Array> v8::Array::New(Isolate* isolate, Local<Value>* elements,
    6846             :                                 size_t length) {
    6847             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6848             :   i::Factory* factory = i_isolate->factory();
    6849           6 :   LOG_API(i_isolate, Array, New);
    6850             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6851           6 :   int len = static_cast<int>(length);
    6852             : 
    6853           6 :   i::Handle<i::FixedArray> result = factory->NewFixedArray(len);
    6854          42 :   for (int i = 0; i < len; i++) {
    6855          18 :     i::Handle<i::Object> element = Utils::OpenHandle(*elements[i]);
    6856          18 :     result->set(i, *element);
    6857             :   }
    6858             : 
    6859             :   return Utils::ToLocal(
    6860          12 :       factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS, len));
    6861             : }
    6862             : 
    6863      274736 : uint32_t v8::Array::Length() const {
    6864             :   i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
    6865             :   i::Object length = obj->length();
    6866      274736 :   if (length->IsSmi()) {
    6867      274736 :     return i::Smi::ToInt(length);
    6868             :   } else {
    6869           0 :     return static_cast<uint32_t>(length->Number());
    6870             :   }
    6871             : }
    6872             : 
    6873             : 
    6874           5 : Local<v8::Map> v8::Map::New(Isolate* isolate) {
    6875             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    6876           5 :   LOG_API(i_isolate, Map, New);
    6877             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    6878           5 :   i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
    6879           5 :   return Utils::ToLocal(obj);
    6880             : }
    6881             : 
    6882             : 
    6883         188 : size_t v8::Map::Size() const {
    6884             :   i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
    6885         188 :   return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
    6886             : }
    6887             : 
    6888             : 
    6889           5 : void Map::Clear() {
    6890             :   auto self = Utils::OpenHandle(this);
    6891             :   i::Isolate* isolate = self->GetIsolate();
    6892           5 :   LOG_API(isolate, Map, Clear);
    6893             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    6894           5 :   i::JSMap::Clear(isolate, self);
    6895           5 : }
    6896             : 
    6897             : 
    6898          15 : MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
    6899          60 :   PREPARE_FOR_EXECUTION(context, Map, Get, Value);
    6900             :   auto self = Utils::OpenHandle(this);
    6901             :   Local<Value> result;
    6902          15 :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
    6903             :   has_pending_exception =
    6904          45 :       !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
    6905             :                                          arraysize(argv), argv),
    6906             :                       &result);
    6907          15 :   RETURN_ON_FAILED_EXECUTION(Value);
    6908          15 :   RETURN_ESCAPED(result);
    6909             : }
    6910             : 
    6911             : 
    6912           5 : MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
    6913             :                          Local<Value> value) {
    6914          20 :   PREPARE_FOR_EXECUTION(context, Map, Set, Map);
    6915             :   auto self = Utils::OpenHandle(this);
    6916             :   i::Handle<i::Object> result;
    6917             :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
    6918          10 :                                  Utils::OpenHandle(*value)};
    6919          10 :   has_pending_exception = !i::Execution::Call(isolate, isolate->map_set(), self,
    6920          10 :                                               arraysize(argv), argv)
    6921             :                                .ToHandle(&result);
    6922           5 :   RETURN_ON_FAILED_EXECUTION(Map);
    6923           5 :   RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
    6924             : }
    6925             : 
    6926             : 
    6927          30 : Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
    6928             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    6929          90 :   ENTER_V8(isolate, context, Map, Has, Nothing<bool>(), i::HandleScope);
    6930             :   auto self = Utils::OpenHandle(this);
    6931             :   i::Handle<i::Object> result;
    6932          30 :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
    6933          60 :   has_pending_exception = !i::Execution::Call(isolate, isolate->map_has(), self,
    6934          60 :                                               arraysize(argv), argv)
    6935             :                                .ToHandle(&result);
    6936          30 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    6937             :   return Just(result->IsTrue(isolate));
    6938             : }
    6939             : 
    6940             : 
    6941          15 : Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
    6942             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    6943          45 :   ENTER_V8(isolate, context, Map, Delete, Nothing<bool>(), i::HandleScope);
    6944             :   auto self = Utils::OpenHandle(this);
    6945             :   i::Handle<i::Object> result;
    6946          15 :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
    6947          30 :   has_pending_exception = !i::Execution::Call(isolate, isolate->map_delete(),
    6948          30 :                                               self, arraysize(argv), argv)
    6949             :                                .ToHandle(&result);
    6950          15 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    6951             :   return Just(result->IsTrue(isolate));
    6952             : }
    6953             : 
    6954             : namespace {
    6955             : 
    6956             : enum class MapAsArrayKind {
    6957             :   kEntries = i::JS_MAP_KEY_VALUE_ITERATOR_TYPE,
    6958             :   kKeys = i::JS_MAP_KEY_ITERATOR_TYPE,
    6959             :   kValues = i::JS_MAP_VALUE_ITERATOR_TYPE
    6960             : };
    6961             : 
    6962             : enum class SetAsArrayKind {
    6963             :   kEntries = i::JS_SET_KEY_VALUE_ITERATOR_TYPE,
    6964             :   kValues = i::JS_SET_VALUE_ITERATOR_TYPE
    6965             : };
    6966             : 
    6967         245 : i::Handle<i::JSArray> MapAsArray(i::Isolate* isolate, i::Object table_obj,
    6968             :                                  int offset, MapAsArrayKind kind) {
    6969             :   i::Factory* factory = isolate->factory();
    6970             :   i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(table_obj),
    6971             :                                      isolate);
    6972             :   const bool collect_keys =
    6973         245 :       kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kKeys;
    6974             :   const bool collect_values =
    6975         245 :       kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kValues;
    6976         245 :   int capacity = table->UsedCapacity();
    6977             :   int max_length =
    6978         245 :       (capacity - offset) * ((collect_keys && collect_values) ? 2 : 1);
    6979         245 :   i::Handle<i::FixedArray> result = factory->NewFixedArray(max_length);
    6980             :   int result_index = 0;
    6981             :   {
    6982             :     i::DisallowHeapAllocation no_gc;
    6983             :     i::Oddball the_hole = i::ReadOnlyRoots(isolate).the_hole_value();
    6984       11121 :     for (int i = offset; i < capacity; ++i) {
    6985        5438 :       i::Object key = table->KeyAt(i);
    6986        5443 :       if (key == the_hole) continue;
    6987       10723 :       if (collect_keys) result->set(result_index++, key);
    6988       16203 :       if (collect_values) result->set(result_index++, table->ValueAt(i));
    6989             :     }
    6990             :   }
    6991             :   DCHECK_GE(max_length, result_index);
    6992         245 :   if (result_index == 0) return factory->NewJSArray(0);
    6993         221 :   result->Shrink(isolate, result_index);
    6994             :   return factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS,
    6995         221 :                                          result_index);
    6996             : }
    6997             : 
    6998             : }  // namespace
    6999             : 
    7000         123 : Local<Array> Map::AsArray() const {
    7001             :   i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
    7002             :   i::Isolate* isolate = obj->GetIsolate();
    7003         123 :   LOG_API(isolate, Map, AsArray);
    7004             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    7005             :   return Utils::ToLocal(
    7006         246 :       MapAsArray(isolate, obj->table(), 0, MapAsArrayKind::kEntries));
    7007             : }
    7008             : 
    7009             : 
    7010       79698 : Local<v8::Set> v8::Set::New(Isolate* isolate) {
    7011             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7012       79698 :   LOG_API(i_isolate, Set, New);
    7013             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    7014       79698 :   i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
    7015       79698 :   return Utils::ToLocal(obj);
    7016             : }
    7017             : 
    7018             : 
    7019         124 : size_t v8::Set::Size() const {
    7020             :   i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
    7021         124 :   return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
    7022             : }
    7023             : 
    7024             : 
    7025           5 : void Set::Clear() {
    7026             :   auto self = Utils::OpenHandle(this);
    7027             :   i::Isolate* isolate = self->GetIsolate();
    7028           5 :   LOG_API(isolate, Set, Clear);
    7029             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    7030           5 :   i::JSSet::Clear(isolate, self);
    7031           5 : }
    7032             : 
    7033             : 
    7034     3003088 : MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
    7035    12012352 :   PREPARE_FOR_EXECUTION(context, Set, Add, Set);
    7036             :   auto self = Utils::OpenHandle(this);
    7037             :   i::Handle<i::Object> result;
    7038     3003088 :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
    7039     6006176 :   has_pending_exception = !i::Execution::Call(isolate, isolate->set_add(), self,
    7040     6006176 :                                               arraysize(argv), argv)
    7041             :                                .ToHandle(&result);
    7042     3003088 :   RETURN_ON_FAILED_EXECUTION(Set);
    7043     3003088 :   RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
    7044             : }
    7045             : 
    7046             : 
    7047     4471308 : Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
    7048             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    7049    13413924 :   ENTER_V8(isolate, context, Set, Has, Nothing<bool>(), i::HandleScope);
    7050             :   auto self = Utils::OpenHandle(this);
    7051             :   i::Handle<i::Object> result;
    7052     4471308 :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
    7053     8942616 :   has_pending_exception = !i::Execution::Call(isolate, isolate->set_has(), self,
    7054     8942616 :                                               arraysize(argv), argv)
    7055             :                                .ToHandle(&result);
    7056     4471308 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    7057             :   return Just(result->IsTrue(isolate));
    7058             : }
    7059             : 
    7060             : 
    7061          70 : Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
    7062             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    7063         210 :   ENTER_V8(isolate, context, Set, Delete, Nothing<bool>(), i::HandleScope);
    7064             :   auto self = Utils::OpenHandle(this);
    7065             :   i::Handle<i::Object> result;
    7066          70 :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
    7067         140 :   has_pending_exception = !i::Execution::Call(isolate, isolate->set_delete(),
    7068         140 :                                               self, arraysize(argv), argv)
    7069             :                                .ToHandle(&result);
    7070          70 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    7071             :   return Just(result->IsTrue(isolate));
    7072             : }
    7073             : 
    7074             : namespace {
    7075         656 : i::Handle<i::JSArray> SetAsArray(i::Isolate* isolate, i::Object table_obj,
    7076             :                                  int offset, SetAsArrayKind kind) {
    7077             :   i::Factory* factory = isolate->factory();
    7078             :   i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(table_obj),
    7079             :                                      isolate);
    7080             :   // Elements skipped by |offset| may already be deleted.
    7081         656 :   int capacity = table->UsedCapacity();
    7082             :   const bool collect_key_values = kind == SetAsArrayKind::kEntries;
    7083         656 :   int max_length = (capacity - offset) * (collect_key_values ? 2 : 1);
    7084         656 :   if (max_length == 0) return factory->NewJSArray(0);
    7085         642 :   i::Handle<i::FixedArray> result = factory->NewFixedArray(max_length);
    7086             :   int result_index = 0;
    7087             :   {
    7088             :     i::DisallowHeapAllocation no_gc;
    7089             :     i::Oddball the_hole = i::ReadOnlyRoots(isolate).the_hole_value();
    7090       27790 :     for (int i = offset; i < capacity; ++i) {
    7091       13574 :       i::Object key = table->KeyAt(i);
    7092       13639 :       if (key == the_hole) continue;
    7093       27018 :       result->set(result_index++, key);
    7094       13567 :       if (collect_key_values) result->set(result_index++, key);
    7095             :     }
    7096             :   }
    7097             :   DCHECK_GE(max_length, result_index);
    7098         642 :   if (result_index == 0) return factory->NewJSArray(0);
    7099         642 :   result->Shrink(isolate, result_index);
    7100             :   return factory->NewJSArrayWithElements(result, i::PACKED_ELEMENTS,
    7101         642 :                                          result_index);
    7102             : }
    7103             : }  // namespace
    7104             : 
    7105         529 : Local<Array> Set::AsArray() const {
    7106             :   i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
    7107             :   i::Isolate* isolate = obj->GetIsolate();
    7108         529 :   LOG_API(isolate, Set, AsArray);
    7109             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    7110             :   return Utils::ToLocal(
    7111        1058 :       SetAsArray(isolate, obj->table(), 0, SetAsArrayKind::kValues));
    7112             : }
    7113             : 
    7114             : 
    7115        9544 : MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) {
    7116       38176 :   PREPARE_FOR_EXECUTION(context, Promise_Resolver, New, Resolver);
    7117             :   Local<Promise::Resolver> result;
    7118             :   has_pending_exception =
    7119        9544 :       !ToLocal<Promise::Resolver>(isolate->factory()->NewJSPromise(), &result);
    7120        9544 :   RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
    7121        9544 :   RETURN_ESCAPED(result);
    7122             : }
    7123             : 
    7124             : 
    7125        9539 : Local<Promise> Promise::Resolver::GetPromise() {
    7126             :   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
    7127        9539 :   return Local<Promise>::Cast(Utils::ToLocal(promise));
    7128             : }
    7129             : 
    7130             : 
    7131        1020 : Maybe<bool> Promise::Resolver::Resolve(Local<Context> context,
    7132             :                                        Local<Value> value) {
    7133             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    7134        3060 :   ENTER_V8(isolate, context, Promise_Resolver, Resolve, Nothing<bool>(),
    7135             :            i::HandleScope);
    7136             :   auto self = Utils::OpenHandle(this);
    7137             :   auto promise = i::Handle<i::JSPromise>::cast(self);
    7138             : 
    7139        1020 :   if (promise->status() != Promise::kPending) {
    7140             :     return Just(true);
    7141             :   }
    7142             : 
    7143             :   has_pending_exception =
    7144        2020 :       i::JSPromise::Resolve(promise, Utils::OpenHandle(*value)).is_null();
    7145        1010 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    7146             :   return Just(true);
    7147             : }
    7148             : 
    7149             : 
    7150         281 : Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
    7151             :                                       Local<Value> value) {
    7152             :   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    7153         843 :   ENTER_V8(isolate, context, Promise_Resolver, Reject, Nothing<bool>(),
    7154             :            i::HandleScope);
    7155             :   auto self = Utils::OpenHandle(this);
    7156             :   auto promise = i::Handle<i::JSPromise>::cast(self);
    7157             : 
    7158         281 :   if (promise->status() != Promise::kPending) {
    7159             :     return Just(true);
    7160             :   }
    7161             : 
    7162             :   has_pending_exception =
    7163         542 :       i::JSPromise::Reject(promise, Utils::OpenHandle(*value)).is_null();
    7164         271 :   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
    7165             :   return Just(true);
    7166             : }
    7167             : 
    7168             : 
    7169         655 : MaybeLocal<Promise> Promise::Catch(Local<Context> context,
    7170             :                                    Local<Function> handler) {
    7171        2620 :   PREPARE_FOR_EXECUTION(context, Promise, Catch, Promise);
    7172             :   auto self = Utils::OpenHandle(this);
    7173             :   i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
    7174             :   i::Handle<i::Object> result;
    7175        1310 :   has_pending_exception = !i::Execution::Call(isolate, isolate->promise_catch(),
    7176        1310 :                                               self, arraysize(argv), argv)
    7177             :                                .ToHandle(&result);
    7178         655 :   RETURN_ON_FAILED_EXECUTION(Promise);
    7179         655 :   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
    7180             : }
    7181             : 
    7182             : 
    7183         675 : MaybeLocal<Promise> Promise::Then(Local<Context> context,
    7184             :                                   Local<Function> handler) {
    7185        2700 :   PREPARE_FOR_EXECUTION(context, Promise, Then, Promise);
    7186             :   auto self = Utils::OpenHandle(this);
    7187             :   i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
    7188             :   i::Handle<i::Object> result;
    7189        1350 :   has_pending_exception = !i::Execution::Call(isolate, isolate->promise_then(),
    7190        1350 :                                               self, arraysize(argv), argv)
    7191             :                                .ToHandle(&result);
    7192         675 :   RETURN_ON_FAILED_EXECUTION(Promise);
    7193         675 :   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
    7194             : }
    7195             : 
    7196         139 : MaybeLocal<Promise> Promise::Then(Local<Context> context,
    7197             :                                   Local<Function> on_fulfilled,
    7198             :                                   Local<Function> on_rejected) {
    7199         556 :   PREPARE_FOR_EXECUTION(context, Promise, Then, Promise);
    7200             :   auto self = Utils::OpenHandle(this);
    7201             :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*on_fulfilled),
    7202             :                                  Utils::OpenHandle(*on_rejected)};
    7203             :   i::Handle<i::Object> result;
    7204         278 :   has_pending_exception = !i::Execution::Call(isolate, isolate->promise_then(),
    7205         278 :                                               self, arraysize(argv), argv)
    7206             :                                .ToHandle(&result);
    7207         139 :   RETURN_ON_FAILED_EXECUTION(Promise);
    7208         139 :   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
    7209             : }
    7210             : 
    7211         345 : bool Promise::HasHandler() {
    7212             :   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
    7213             :   i::Isolate* isolate = promise->GetIsolate();
    7214         345 :   LOG_API(isolate, Promise, HasRejectHandler);
    7215             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    7216         345 :   if (promise->IsJSPromise()) {
    7217             :     i::Handle<i::JSPromise> js_promise = i::Handle<i::JSPromise>::cast(promise);
    7218             :     return js_promise->has_handler();
    7219             :   }
    7220             :   return false;
    7221             : }
    7222             : 
    7223          50 : Local<Value> Promise::Result() {
    7224             :   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
    7225             :   i::Isolate* isolate = promise->GetIsolate();
    7226          50 :   LOG_API(isolate, Promise, Result);
    7227             :   i::Handle<i::JSPromise> js_promise = i::Handle<i::JSPromise>::cast(promise);
    7228         100 :   Utils::ApiCheck(js_promise->status() != kPending, "v8_Promise_Result",
    7229             :                   "Promise is still pending");
    7230             :   i::Handle<i::Object> result(js_promise->result(), isolate);
    7231          50 :   return Utils::ToLocal(result);
    7232             : }
    7233             : 
    7234         289 : Promise::PromiseState Promise::State() {
    7235             :   i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this);
    7236             :   i::Isolate* isolate = promise->GetIsolate();
    7237         289 :   LOG_API(isolate, Promise, Status);
    7238             :   i::Handle<i::JSPromise> js_promise = i::Handle<i::JSPromise>::cast(promise);
    7239         578 :   return static_cast<PromiseState>(js_promise->status());
    7240             : }
    7241             : 
    7242           5 : void Promise::MarkAsHandled() {
    7243             :   i::Handle<i::JSPromise> js_promise = Utils::OpenHandle(this);
    7244           5 :   js_promise->set_has_handler(true);
    7245           5 : }
    7246             : 
    7247          35 : Local<Value> Proxy::GetTarget() {
    7248             :   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
    7249             :   i::Handle<i::Object> target(self->target(), self->GetIsolate());
    7250          35 :   return Utils::ToLocal(target);
    7251             : }
    7252             : 
    7253             : 
    7254          10 : Local<Value> Proxy::GetHandler() {
    7255             :   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
    7256             :   i::Handle<i::Object> handler(self->handler(), self->GetIsolate());
    7257          10 :   return Utils::ToLocal(handler);
    7258             : }
    7259             : 
    7260             : 
    7261          10 : bool Proxy::IsRevoked() {
    7262             :   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
    7263          10 :   return self->IsRevoked();
    7264             : }
    7265             : 
    7266             : 
    7267           5 : void Proxy::Revoke() {
    7268           5 :   i::Handle<i::JSProxy> self = Utils::OpenHandle(this);
    7269           5 :   i::JSProxy::Revoke(self);
    7270           5 : }
    7271             : 
    7272             : 
    7273          17 : MaybeLocal<Proxy> Proxy::New(Local<Context> context, Local<Object> local_target,
    7274             :                              Local<Object> local_handler) {
    7275          68 :   PREPARE_FOR_EXECUTION(context, Proxy, New, Proxy);
    7276             :   i::Handle<i::JSReceiver> target = Utils::OpenHandle(*local_target);
    7277             :   i::Handle<i::JSReceiver> handler = Utils::OpenHandle(*local_handler);
    7278             :   Local<Proxy> result;
    7279             :   has_pending_exception =
    7280          34 :       !ToLocal<Proxy>(i::JSProxy::New(isolate, target, handler), &result);
    7281          17 :   RETURN_ON_FAILED_EXECUTION(Proxy);
    7282          17 :   RETURN_ESCAPED(result);
    7283             : }
    7284             : 
    7285          48 : CompiledWasmModule::CompiledWasmModule(
    7286             :     std::shared_ptr<internal::wasm::NativeModule> native_module)
    7287             :     : native_module_(std::move(native_module)) {
    7288          48 :   CHECK_NOT_NULL(native_module_);
    7289          48 : }
    7290             : 
    7291          28 : OwnedBuffer CompiledWasmModule::Serialize() {
    7292          28 :   i::wasm::WasmSerializer wasm_serializer(native_module_.get());
    7293          28 :   size_t buffer_size = wasm_serializer.GetSerializedNativeModuleSize();
    7294          28 :   std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
    7295          28 :   if (!wasm_serializer.SerializeNativeModule({buffer.get(), buffer_size}))
    7296           0 :     return {};
    7297             :   return {std::move(buffer), buffer_size};
    7298             : }
    7299             : 
    7300          44 : MemorySpan<const uint8_t> CompiledWasmModule::GetWireBytesRef() {
    7301             :   i::Vector<const uint8_t> bytes_vec = native_module_->wire_bytes();
    7302          44 :   return {bytes_vec.start(), bytes_vec.size()};
    7303             : }
    7304             : 
    7305             : WasmModuleObject::TransferrableModule
    7306         126 : WasmModuleObject::GetTransferrableModule() {
    7307         126 :   if (i::FLAG_wasm_shared_code) {
    7308             :     i::Handle<i::WasmModuleObject> obj =
    7309             :         i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
    7310         122 :     return TransferrableModule(obj->shared_native_module());
    7311             :   } else {
    7312           4 :     CompiledWasmModule compiled_module = GetCompiledModule();
    7313           4 :     OwnedBuffer serialized_module = compiled_module.Serialize();
    7314             :     MemorySpan<const uint8_t> wire_bytes_ref =
    7315             :         compiled_module.GetWireBytesRef();
    7316             :     size_t wire_size = wire_bytes_ref.size();
    7317           4 :     std::unique_ptr<uint8_t[]> wire_bytes_copy(new uint8_t[wire_size]);
    7318             :     memcpy(wire_bytes_copy.get(), wire_bytes_ref.data(), wire_size);
    7319             :     return TransferrableModule(std::move(serialized_module),
    7320             :                                {std::move(wire_bytes_copy), wire_size});
    7321             :   }
    7322             : }
    7323             : 
    7324          48 : CompiledWasmModule WasmModuleObject::GetCompiledModule() {
    7325             :   i::Handle<i::WasmModuleObject> obj =
    7326             :       i::Handle<i::WasmModuleObject>::cast(Utils::OpenHandle(this));
    7327          96 :   return Utils::Convert(obj->shared_native_module());
    7328             : }
    7329             : 
    7330         124 : MaybeLocal<WasmModuleObject> WasmModuleObject::FromTransferrableModule(
    7331             :     Isolate* isolate,
    7332             :     const WasmModuleObject::TransferrableModule& transferrable_module) {
    7333         124 :   if (i::FLAG_wasm_shared_code) {
    7334             :     i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7335             :     i::Handle<i::WasmModuleObject> module_object =
    7336             :         i_isolate->wasm_engine()->ImportNativeModule(
    7337         240 :             i_isolate, transferrable_module.shared_module_);
    7338             :     return Local<WasmModuleObject>::Cast(
    7339         120 :         Utils::ToLocal(i::Handle<i::JSObject>::cast(module_object)));
    7340             :   } else {
    7341             :     return Deserialize(isolate, AsReference(transferrable_module.serialized_),
    7342           4 :                        AsReference(transferrable_module.wire_bytes_));
    7343             :   }
    7344             : }
    7345             : 
    7346          81 : MaybeLocal<WasmModuleObject> WasmModuleObject::Deserialize(
    7347             :     Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
    7348             :     MemorySpan<const uint8_t> wire_bytes) {
    7349             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7350             :   i::MaybeHandle<i::WasmModuleObject> maybe_module_object =
    7351             :       i::wasm::DeserializeNativeModule(
    7352             :           i_isolate, {serialized_module.data(), serialized_module.size()},
    7353          81 :           {wire_bytes.data(), wire_bytes.size()});
    7354             :   i::Handle<i::WasmModuleObject> module_object;
    7355          81 :   if (!maybe_module_object.ToHandle(&module_object)) {
    7356          69 :     return MaybeLocal<WasmModuleObject>();
    7357             :   }
    7358             :   return Local<WasmModuleObject>::Cast(
    7359          12 :       Utils::ToLocal(i::Handle<i::JSObject>::cast(module_object)));
    7360             : }
    7361             : 
    7362          77 : MaybeLocal<WasmModuleObject> WasmModuleObject::DeserializeOrCompile(
    7363             :     Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
    7364             :     MemorySpan<const uint8_t> wire_bytes) {
    7365             :   MaybeLocal<WasmModuleObject> ret =
    7366          77 :       Deserialize(isolate, serialized_module, wire_bytes);
    7367          77 :   if (!ret.IsEmpty()) {
    7368           8 :     return ret;
    7369             :   }
    7370          69 :   return Compile(isolate, wire_bytes.data(), wire_bytes.size());
    7371             : }
    7372             : 
    7373          69 : MaybeLocal<WasmModuleObject> WasmModuleObject::Compile(Isolate* isolate,
    7374             :                                                        const uint8_t* start,
    7375             :                                                        size_t length) {
    7376             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7377         138 :   if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
    7378          20 :     return MaybeLocal<WasmModuleObject>();
    7379             :   }
    7380             :   i::MaybeHandle<i::JSObject> maybe_compiled;
    7381             :   {
    7382          49 :     i::wasm::ErrorThrower thrower(i_isolate, "WasmModuleObject::Compile()");
    7383          49 :     auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
    7384             :     maybe_compiled = i_isolate->wasm_engine()->SyncCompile(
    7385             :         i_isolate, enabled_features, &thrower,
    7386          49 :         i::wasm::ModuleWireBytes(start, start + length));
    7387             :   }
    7388          49 :   CHECK_EQ(maybe_compiled.is_null(), i_isolate->has_pending_exception());
    7389          49 :   if (maybe_compiled.is_null()) {
    7390           9 :     i_isolate->OptionalRescheduleException(false);
    7391           9 :     return MaybeLocal<WasmModuleObject>();
    7392             :   }
    7393             :   return Local<WasmModuleObject>::Cast(
    7394          40 :       Utils::ToLocal(maybe_compiled.ToHandleChecked()));
    7395             : }
    7396             : 
    7397             : // Resolves the result of streaming compilation.
    7398             : // TODO(ahaas): Refactor the streaming compilation API so that this class can
    7399             : // move to wasm-js.cc.
    7400             : class AsyncCompilationResolver : public i::wasm::CompilationResultResolver {
    7401             :  public:
    7402             :   AsyncCompilationResolver(Isolate* isolate, Local<Promise> promise)
    7403             :       : promise_(
    7404             :             reinterpret_cast<i::Isolate*>(isolate)->global_handles()->Create(
    7405             :                 *Utils::OpenHandle(*promise))) {}
    7406             : 
    7407             :   ~AsyncCompilationResolver() override {
    7408             :     i::GlobalHandles::Destroy(promise_.location());
    7409             :   }
    7410             : 
    7411             :   void OnCompilationSucceeded(i::Handle<i::WasmModuleObject> result) override {
    7412             :     i::MaybeHandle<i::Object> promise_result =
    7413             :         i::JSPromise::Resolve(promise_, result);
    7414             :     CHECK_EQ(promise_result.is_null(),
    7415             :              promise_->GetIsolate()->has_pending_exception());
    7416             :   }
    7417             : 
    7418             :   void OnCompilationFailed(i::Handle<i::Object> error_reason) override {
    7419             :     i::MaybeHandle<i::Object> promise_result =
    7420             :         i::JSPromise::Reject(promise_, error_reason);
    7421             :     CHECK_EQ(promise_result.is_null(),
    7422             :              promise_->GetIsolate()->has_pending_exception());
    7423             :   }
    7424             : 
    7425             :  private:
    7426             :   i::Handle<i::JSPromise> promise_;
    7427             : };
    7428             : 
    7429           0 : WasmModuleObjectBuilderStreaming::WasmModuleObjectBuilderStreaming(
    7430           0 :     Isolate* isolate) {
    7431             :   USE(isolate_);
    7432           0 : }
    7433             : 
    7434           0 : Local<Promise> WasmModuleObjectBuilderStreaming::GetPromise() { return {}; }
    7435             : 
    7436           0 : void WasmModuleObjectBuilderStreaming::OnBytesReceived(const uint8_t* bytes,
    7437             :                                                        size_t size) {
    7438           0 : }
    7439             : 
    7440           0 : void WasmModuleObjectBuilderStreaming::Finish() {
    7441           0 : }
    7442             : 
    7443           0 : void WasmModuleObjectBuilderStreaming::Abort(MaybeLocal<Value> exception) {
    7444           0 : }
    7445             : 
    7446             : // static
    7447      120545 : v8::ArrayBuffer::Allocator* v8::ArrayBuffer::Allocator::NewDefaultAllocator() {
    7448      241090 :   return new ArrayBufferAllocator();
    7449             : }
    7450             : 
    7451          89 : bool v8::ArrayBuffer::IsExternal() const {
    7452          89 :   return Utils::OpenHandle(this)->is_external();
    7453             : }
    7454             : 
    7455          56 : bool v8::ArrayBuffer::IsDetachable() const {
    7456          56 :   return Utils::OpenHandle(this)->is_detachable();
    7457             : }
    7458             : 
    7459          89 : v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
    7460             :   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
    7461             :   i::Isolate* isolate = self->GetIsolate();
    7462             :   Utils::ApiCheck(!self->is_external(), "v8_ArrayBuffer_Externalize",
    7463             :                   "ArrayBuffer already externalized");
    7464             :   self->set_is_external(true);
    7465             : 
    7466          89 :   const v8::ArrayBuffer::Contents contents = GetContents();
    7467          89 :   isolate->heap()->UnregisterArrayBuffer(*self);
    7468             : 
    7469             :   // A regular copy is good enough. No move semantics needed.
    7470          89 :   return contents;
    7471             : }
    7472             : 
    7473           0 : v8::ArrayBuffer::Contents::Contents(void* data, size_t byte_length,
    7474             :                                     void* allocation_base,
    7475             :                                     size_t allocation_length,
    7476             :                                     Allocator::AllocationMode allocation_mode,
    7477             :                                     DeleterCallback deleter, void* deleter_data)
    7478             :     : data_(data),
    7479             :       byte_length_(byte_length),
    7480             :       allocation_base_(allocation_base),
    7481             :       allocation_length_(allocation_length),
    7482             :       allocation_mode_(allocation_mode),
    7483             :       deleter_(deleter),
    7484      282389 :       deleter_data_(deleter_data) {
    7485             :   DCHECK_LE(allocation_base_, data_);
    7486             :   DCHECK_LE(byte_length_, allocation_length_);
    7487           0 : }
    7488             : 
    7489          89 : void WasmMemoryDeleter(void* buffer, size_t lenght, void* info) {
    7490             :   internal::wasm::WasmEngine* engine =
    7491             :       reinterpret_cast<internal::wasm::WasmEngine*>(info);
    7492          89 :   CHECK(engine->memory_tracker()->FreeMemoryIfIsWasmMemory(nullptr, buffer));
    7493          89 : }
    7494             : 
    7495          99 : void ArrayBufferDeleter(void* buffer, size_t length, void* info) {
    7496             :   v8::ArrayBuffer::Allocator* allocator =
    7497             :       reinterpret_cast<v8::ArrayBuffer::Allocator*>(info);
    7498          99 :   allocator->Free(buffer, length);
    7499          99 : }
    7500             : 
    7501      282387 : v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() {
    7502             :   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
    7503             :   Contents contents(
    7504             :       self->backing_store(), self->byte_length(), self->allocation_base(),
    7505             :       self->allocation_length(),
    7506             :       self->is_wasm_memory() ? Allocator::AllocationMode::kReservation
    7507             :                              : Allocator::AllocationMode::kNormal,
    7508             :       self->is_wasm_memory() ? WasmMemoryDeleter : ArrayBufferDeleter,
    7509             :       self->is_wasm_memory()
    7510             :           ? static_cast<void*>(self->GetIsolate()->wasm_engine())
    7511     1129553 :           : static_cast<void*>(self->GetIsolate()->array_buffer_allocator()));
    7512      282389 :   return contents;
    7513             : }
    7514             : 
    7515          43 : void v8::ArrayBuffer::Detach() {
    7516             :   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
    7517             :   i::Isolate* isolate = obj->GetIsolate();
    7518             :   Utils::ApiCheck(obj->is_external(), "v8::ArrayBuffer::Detach",
    7519             :                   "Only externalized ArrayBuffers can be detached");
    7520             :   Utils::ApiCheck(obj->is_detachable(), "v8::ArrayBuffer::Detach",
    7521             :                   "Only detachable ArrayBuffers can be detached");
    7522          43 :   LOG_API(isolate, ArrayBuffer, Detach);
    7523             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    7524          43 :   obj->Detach();
    7525          43 : }
    7526             : 
    7527         243 : size_t v8::ArrayBuffer::ByteLength() const {
    7528             :   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
    7529         243 :   return obj->byte_length();
    7530             : }
    7531             : 
    7532             : 
    7533         200 : Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
    7534             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7535         200 :   LOG_API(i_isolate, ArrayBuffer, New);
    7536             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    7537             :   i::Handle<i::JSArrayBuffer> obj =
    7538         200 :       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
    7539             :   // TODO(jbroman): It may be useful in the future to provide a MaybeLocal
    7540             :   // version that throws an exception or otherwise does not crash.
    7541         200 :   if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length)) {
    7542           0 :     i::FatalProcessOutOfMemory(i_isolate, "v8::ArrayBuffer::New");
    7543             :   }
    7544         200 :   return Utils::ToLocal(obj);
    7545             : }
    7546             : 
    7547             : 
    7548         140 : Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
    7549             :                                         size_t byte_length,
    7550             :                                         ArrayBufferCreationMode mode) {
    7551             :   // Embedders must guarantee that the external backing store is valid.
    7552         140 :   CHECK(byte_length == 0 || data != nullptr);
    7553         140 :   CHECK_LE(byte_length, i::JSArrayBuffer::kMaxByteLength);
    7554             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7555         140 :   LOG_API(i_isolate, ArrayBuffer, New);
    7556             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    7557             :   i::Handle<i::JSArrayBuffer> obj =
    7558         140 :       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
    7559         140 :   i::JSArrayBuffer::Setup(obj, i_isolate,
    7560             :                           mode == ArrayBufferCreationMode::kExternalized, data,
    7561         140 :                           byte_length);
    7562         140 :   return Utils::ToLocal(obj);
    7563             : }
    7564             : 
    7565             : 
    7566       27909 : Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
    7567             :   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
    7568             :   i::Handle<i::JSArrayBuffer> buffer;
    7569       27909 :   if (obj->IsJSDataView()) {
    7570             :     i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj),
    7571             :                                        obj->GetIsolate());
    7572             :     DCHECK(data_view->buffer()->IsJSArrayBuffer());
    7573             :     buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()),
    7574             :                        data_view->GetIsolate());
    7575             :   } else {
    7576             :     DCHECK(obj->IsJSTypedArray());
    7577       27895 :     buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
    7578             :   }
    7579       27909 :   return Utils::ToLocal(buffer);
    7580             : }
    7581             : 
    7582             : 
    7583          15 : size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
    7584             :   i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
    7585             :   size_t byte_offset = self->byte_offset();
    7586             :   size_t bytes_to_copy = i::Min(byte_length, self->byte_length());
    7587          15 :   if (bytes_to_copy) {
    7588             :     i::DisallowHeapAllocation no_gc;
    7589             :     i::Isolate* isolate = self->GetIsolate();
    7590             :     i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()),
    7591             :                                        isolate);
    7592             :     const char* source = reinterpret_cast<char*>(buffer->backing_store());
    7593          15 :     if (source == nullptr) {
    7594             :       DCHECK(self->IsJSTypedArray());
    7595             :       i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self),
    7596             :                                              isolate);
    7597             :       i::Handle<i::FixedTypedArrayBase> fixed_array(
    7598             :           i::FixedTypedArrayBase::cast(typed_array->elements()), isolate);
    7599             :       source = reinterpret_cast<char*>(fixed_array->DataPtr());
    7600             :     }
    7601          15 :     memcpy(dest, source + byte_offset, bytes_to_copy);
    7602             :   }
    7603          15 :   return bytes_to_copy;
    7604             : }
    7605             : 
    7606             : 
    7607          30 : bool v8::ArrayBufferView::HasBuffer() const {
    7608             :   i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
    7609             :   i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()),
    7610             :                                      self->GetIsolate());
    7611          30 :   return buffer->backing_store() != nullptr;
    7612             : }
    7613             : 
    7614             : 
    7615       28085 : size_t v8::ArrayBufferView::ByteOffset() {
    7616             :   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
    7617       56170 :   return obj->WasDetached() ? 0 : obj->byte_offset();
    7618             : }
    7619             : 
    7620             : 
    7621       28169 : size_t v8::ArrayBufferView::ByteLength() {
    7622             :   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
    7623       56338 :   return obj->WasDetached() ? 0 : obj->byte_length();
    7624             : }
    7625             : 
    7626             : 
    7627         528 : size_t v8::TypedArray::Length() {
    7628             :   i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
    7629        1056 :   return obj->WasDetached() ? 0 : obj->length();
    7630             : }
    7631             : 
    7632             : static_assert(v8::TypedArray::kMaxLength == i::Smi::kMaxValue,
    7633             :               "v8::TypedArray::kMaxLength must match i::Smi::kMaxValue");
    7634             : 
    7635             : #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype)                           \
    7636             :   Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer,     \
    7637             :                                       size_t byte_offset, size_t length) { \
    7638             :     i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate();  \
    7639             :     LOG_API(isolate, Type##Array, New);                                    \
    7640             :     ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);                              \
    7641             :     if (!Utils::ApiCheck(length <= kMaxLength,                             \
    7642             :                          "v8::" #Type                                      \
    7643             :                          "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
    7644             :                          "length exceeds max allowed value")) {            \
    7645             :       return Local<Type##Array>();                                         \
    7646             :     }                                                                      \
    7647             :     i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \
    7648             :     i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray(  \
    7649             :         i::kExternal##Type##Array, buffer, byte_offset, length);           \
    7650             :     return Utils::ToLocal##Type##Array(obj);                               \
    7651             :   }                                                                        \
    7652             :   Local<Type##Array> Type##Array::New(                                     \
    7653             :       Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,    \
    7654             :       size_t length) {                                                     \
    7655             :     CHECK(i::FLAG_harmony_sharedarraybuffer);                              \
    7656             :     i::Isolate* isolate =                                                  \
    7657             :         Utils::OpenHandle(*shared_array_buffer)->GetIsolate();             \
    7658             :     LOG_API(isolate, Type##Array, New);                                    \
    7659             :     ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);                              \
    7660             :     if (!Utils::ApiCheck(                                                  \
    7661             :             length <= kMaxLength,                                          \
    7662             :             "v8::" #Type                                                   \
    7663             :             "Array::New(Local<SharedArrayBuffer>, size_t, size_t)",        \
    7664             :             "length exceeds max allowed value")) {                         \
    7665             :       return Local<Type##Array>();                                         \
    7666             :     }                                                                      \
    7667             :     i::Handle<i::JSArrayBuffer> buffer =                                   \
    7668             :         Utils::OpenHandle(*shared_array_buffer);                           \
    7669             :     i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray(  \
    7670             :         i::kExternal##Type##Array, buffer, byte_offset, length);           \
    7671             :     return Utils::ToLocal##Type##Array(obj);                               \
    7672             :   }
    7673             : 
    7674         930 : TYPED_ARRAYS(TYPED_ARRAY_NEW)
    7675             : #undef TYPED_ARRAY_NEW
    7676             : 
    7677          17 : Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
    7678             :                               size_t byte_offset, size_t byte_length) {
    7679             :   i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
    7680             :   i::Isolate* isolate = buffer->GetIsolate();
    7681          17 :   LOG_API(isolate, DataView, New);
    7682             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    7683             :   i::Handle<i::JSDataView> obj =
    7684          17 :       isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
    7685          17 :   return Utils::ToLocal(obj);
    7686             : }
    7687             : 
    7688             : 
    7689           6 : Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
    7690             :                               size_t byte_offset, size_t byte_length) {
    7691           6 :   CHECK(i::FLAG_harmony_sharedarraybuffer);
    7692             :   i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
    7693             :   i::Isolate* isolate = buffer->GetIsolate();
    7694           6 :   LOG_API(isolate, DataView, New);
    7695             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    7696             :   i::Handle<i::JSDataView> obj =
    7697           6 :       isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
    7698           6 :   return Utils::ToLocal(obj);
    7699             : }
    7700             : 
    7701             : namespace {
    7702         483 : i::Handle<i::JSArrayBuffer> SetupSharedArrayBuffer(
    7703             :     Isolate* isolate, void* data, size_t byte_length,
    7704             :     ArrayBufferCreationMode mode) {
    7705         483 :   CHECK(i::FLAG_harmony_sharedarraybuffer);
    7706             :   // Embedders must guarantee that the external backing store is valid.
    7707         483 :   CHECK(byte_length == 0 || data != nullptr);
    7708             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7709         483 :   LOG_API(i_isolate, SharedArrayBuffer, New);
    7710             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    7711             :   i::Handle<i::JSArrayBuffer> obj =
    7712         483 :       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
    7713             :   bool is_wasm_memory =
    7714         483 :       i_isolate->wasm_engine()->memory_tracker()->IsWasmMemory(data);
    7715         483 :   i::JSArrayBuffer::Setup(obj, i_isolate,
    7716             :                           mode == ArrayBufferCreationMode::kExternalized, data,
    7717         483 :                           byte_length, i::SharedFlag::kShared, is_wasm_memory);
    7718         966 :   return obj;
    7719             : }
    7720             : 
    7721             : }  // namespace
    7722             : 
    7723         443 : bool v8::SharedArrayBuffer::IsExternal() const {
    7724         443 :   return Utils::OpenHandle(this)->is_external();
    7725             : }
    7726             : 
    7727         197 : v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
    7728             :   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
    7729             :   i::Isolate* isolate = self->GetIsolate();
    7730             :   Utils::ApiCheck(!self->is_external(), "v8_SharedArrayBuffer_Externalize",
    7731             :                   "SharedArrayBuffer already externalized");
    7732             :   self->set_is_external(true);
    7733             : 
    7734         197 :   const v8::SharedArrayBuffer::Contents contents = GetContents();
    7735         197 :   isolate->heap()->UnregisterArrayBuffer(*self);
    7736             : 
    7737             :   // A regular copy is good enough. No move semantics needed.
    7738         197 :   return contents;
    7739             : }
    7740             : 
    7741           0 : v8::SharedArrayBuffer::Contents::Contents(
    7742             :     void* data, size_t byte_length, void* allocation_base,
    7743             :     size_t allocation_length, Allocator::AllocationMode allocation_mode,
    7744             :     DeleterCallback deleter, void* deleter_data)
    7745             :     : data_(data),
    7746             :       byte_length_(byte_length),
    7747             :       allocation_base_(allocation_base),
    7748             :       allocation_length_(allocation_length),
    7749             :       allocation_mode_(allocation_mode),
    7750             :       deleter_(deleter),
    7751         431 :       deleter_data_(deleter_data) {
    7752             :   DCHECK_LE(allocation_base_, data_);
    7753             :   DCHECK_LE(byte_length_, allocation_length_);
    7754           0 : }
    7755             : 
    7756         431 : v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
    7757             :   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
    7758             :   Contents contents(
    7759             :       self->backing_store(), self->byte_length(), self->allocation_base(),
    7760             :       self->allocation_length(),
    7761             :       self->is_wasm_memory()
    7762             :           ? ArrayBuffer::Allocator::AllocationMode::kReservation
    7763             :           : ArrayBuffer::Allocator::AllocationMode::kNormal,
    7764             :       self->is_wasm_memory()
    7765             :           ? reinterpret_cast<Contents::DeleterCallback>(WasmMemoryDeleter)
    7766             :           : reinterpret_cast<Contents::DeleterCallback>(ArrayBufferDeleter),
    7767             :       self->is_wasm_memory()
    7768             :           ? static_cast<void*>(self->GetIsolate()->wasm_engine())
    7769        1724 :           : static_cast<void*>(self->GetIsolate()->array_buffer_allocator()));
    7770         431 :   return contents;
    7771             : }
    7772             : 
    7773          38 : size_t v8::SharedArrayBuffer::ByteLength() const {
    7774             :   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
    7775          38 :   return obj->byte_length();
    7776             : }
    7777             : 
    7778          12 : Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate,
    7779             :                                                     size_t byte_length) {
    7780          12 :   CHECK(i::FLAG_harmony_sharedarraybuffer);
    7781             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7782          12 :   LOG_API(i_isolate, SharedArrayBuffer, New);
    7783             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    7784             :   i::Handle<i::JSArrayBuffer> obj =
    7785          12 :       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
    7786             :   // TODO(jbroman): It may be useful in the future to provide a MaybeLocal
    7787             :   // version that throws an exception or otherwise does not crash.
    7788          12 :   if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length, true,
    7789             :                                              i::SharedFlag::kShared)) {
    7790           0 :     i::FatalProcessOutOfMemory(i_isolate, "v8::SharedArrayBuffer::New");
    7791             :   }
    7792          12 :   return Utils::ToLocalShared(obj);
    7793             : }
    7794             : 
    7795             : 
    7796         483 : Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
    7797             :     Isolate* isolate, void* data, size_t byte_length,
    7798             :     ArrayBufferCreationMode mode) {
    7799             :   i::Handle<i::JSArrayBuffer> buffer =
    7800         483 :       SetupSharedArrayBuffer(isolate, data, byte_length, mode);
    7801         483 :   return Utils::ToLocalShared(buffer);
    7802             : }
    7803             : 
    7804           0 : Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
    7805             :     Isolate* isolate, const SharedArrayBuffer::Contents& contents,
    7806             :     ArrayBufferCreationMode mode) {
    7807             :   i::Handle<i::JSArrayBuffer> buffer = SetupSharedArrayBuffer(
    7808           0 :       isolate, contents.Data(), contents.ByteLength(), mode);
    7809           0 :   return Utils::ToLocalShared(buffer);
    7810             : }
    7811             : 
    7812         125 : Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
    7813             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7814         125 :   LOG_API(i_isolate, Symbol, New);
    7815             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    7816         125 :   i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
    7817         207 :   if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
    7818         125 :   return Utils::ToLocal(result);
    7819             : }
    7820             : 
    7821             : 
    7822          24 : Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
    7823             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7824          24 :   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
    7825             :   return Utils::ToLocal(
    7826          24 :       i_isolate->SymbolFor(i::RootIndex::kPublicSymbolTable, i_name, false));
    7827             : }
    7828             : 
    7829             : 
    7830          24 : Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
    7831             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7832          24 :   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
    7833             :   return Utils::ToLocal(
    7834          24 :       i_isolate->SymbolFor(i::RootIndex::kApiSymbolTable, i_name, false));
    7835             : }
    7836             : 
    7837             : #define WELL_KNOWN_SYMBOLS(V)                 \
    7838             :   V(AsyncIterator, async_iterator)            \
    7839             :   V(HasInstance, has_instance)                \
    7840             :   V(IsConcatSpreadable, is_concat_spreadable) \
    7841             :   V(Iterator, iterator)                       \
    7842             :   V(Match, match)                             \
    7843             :   V(Replace, replace)                         \
    7844             :   V(Search, search)                           \
    7845             :   V(Split, split)                             \
    7846             :   V(ToPrimitive, to_primitive)                \
    7847             :   V(ToStringTag, to_string_tag)               \
    7848             :   V(Unscopables, unscopables)
    7849             : 
    7850             : #define SYMBOL_GETTER(Name, name)                                   \
    7851             :   Local<Symbol> v8::Symbol::Get##Name(Isolate* isolate) {           \
    7852             :     i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); \
    7853             :     return Utils::ToLocal(i_isolate->factory()->name##_symbol());   \
    7854             :   }
    7855             : 
    7856      106664 : WELL_KNOWN_SYMBOLS(SYMBOL_GETTER)
    7857             : 
    7858             : #undef SYMBOL_GETTER
    7859             : #undef WELL_KNOWN_SYMBOLS
    7860             : 
    7861         153 : Local<Private> v8::Private::New(Isolate* isolate, Local<String> name) {
    7862             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7863         153 :   LOG_API(i_isolate, Private, New);
    7864             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    7865         153 :   i::Handle<i::Symbol> symbol = i_isolate->factory()->NewPrivateSymbol();
    7866         235 :   if (!name.IsEmpty()) symbol->set_name(*Utils::OpenHandle(*name));
    7867             :   Local<Symbol> result = Utils::ToLocal(symbol);
    7868         306 :   return v8::Local<Private>(reinterpret_cast<Private*>(*result));
    7869             : }
    7870             : 
    7871             : 
    7872      254827 : Local<Private> v8::Private::ForApi(Isolate* isolate, Local<String> name) {
    7873             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7874      254827 :   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
    7875             :   Local<Symbol> result = Utils::ToLocal(
    7876      254827 :       i_isolate->SymbolFor(i::RootIndex::kApiPrivateSymbolTable, i_name, true));
    7877      254827 :   return v8::Local<Private>(reinterpret_cast<Private*>(*result));
    7878             : }
    7879             : 
    7880             : 
    7881      100548 : Local<Number> v8::Number::New(Isolate* isolate, double value) {
    7882             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7883      100548 :   if (std::isnan(value)) {
    7884             :     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
    7885             :     value = std::numeric_limits<double>::quiet_NaN();
    7886             :   }
    7887             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
    7888      100548 :   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
    7889      100548 :   return Utils::NumberToLocal(result);
    7890             : }
    7891             : 
    7892             : 
    7893      786665 : Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
    7894             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7895             :   if (i::Smi::IsValid(value)) {
    7896             :     return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
    7897             :                                                       internal_isolate));
    7898             :   }
    7899             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
    7900             :   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
    7901             :   return Utils::IntegerToLocal(result);
    7902             : }
    7903             : 
    7904             : 
    7905         285 : Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
    7906             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7907         285 :   bool fits_into_int32_t = (value & (1 << 31)) == 0;
    7908         285 :   if (fits_into_int32_t) {
    7909         194 :     return Integer::New(isolate, static_cast<int32_t>(value));
    7910             :   }
    7911             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
    7912          91 :   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
    7913             :   return Utils::IntegerToLocal(result);
    7914             : }
    7915             : 
    7916          81 : Local<BigInt> v8::BigInt::New(Isolate* isolate, int64_t value) {
    7917             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7918             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
    7919          81 :   i::Handle<i::BigInt> result = i::BigInt::FromInt64(internal_isolate, value);
    7920          81 :   return Utils::ToLocal(result);
    7921             : }
    7922             : 
    7923           0 : Local<BigInt> v8::BigInt::NewFromUnsigned(Isolate* isolate, uint64_t value) {
    7924             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    7925             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(internal_isolate);
    7926           0 :   i::Handle<i::BigInt> result = i::BigInt::FromUint64(internal_isolate, value);
    7927           0 :   return Utils::ToLocal(result);
    7928             : }
    7929             : 
    7930          30 : MaybeLocal<BigInt> v8::BigInt::NewFromWords(Local<Context> context,
    7931             :                                             int sign_bit, int word_count,
    7932             :                                             const uint64_t* words) {
    7933             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
    7934          90 :   ENTER_V8_NO_SCRIPT(isolate, context, BigInt, NewFromWords,
    7935             :                      MaybeLocal<BigInt>(), InternalEscapableScope);
    7936             :   i::MaybeHandle<i::BigInt> result =
    7937          30 :       i::BigInt::FromWords64(isolate, sign_bit, word_count, words);
    7938             :   has_pending_exception = result.is_null();
    7939          30 :   RETURN_ON_FAILED_EXECUTION(BigInt);
    7940          15 :   RETURN_ESCAPED(Utils::ToLocal(result.ToHandleChecked()));
    7941             : }
    7942             : 
    7943          55 : uint64_t v8::BigInt::Uint64Value(bool* lossless) const {
    7944             :   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
    7945          55 :   return handle->AsUint64(lossless);
    7946             : }
    7947             : 
    7948          90 : int64_t v8::BigInt::Int64Value(bool* lossless) const {
    7949             :   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
    7950          90 :   return handle->AsInt64(lossless);
    7951             : }
    7952             : 
    7953          15 : int BigInt::WordCount() const {
    7954             :   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
    7955          15 :   return handle->Words64Count();
    7956             : }
    7957             : 
    7958          10 : void BigInt::ToWordsArray(int* sign_bit, int* word_count,
    7959             :                           uint64_t* words) const {
    7960             :   i::Handle<i::BigInt> handle = Utils::OpenHandle(this);
    7961          10 :   return handle->ToWordsArray64(sign_bit, word_count, words);
    7962             : }
    7963             : 
    7964      993804 : void Isolate::ReportExternalAllocationLimitReached() {
    7965             :   i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
    7966      993804 :   if (heap->gc_state() != i::Heap::NOT_IN_GC) return;
    7967      993804 :   heap->ReportExternalMemoryPressure();
    7968             : }
    7969             : 
    7970     1832517 : void Isolate::CheckMemoryPressure() {
    7971             :   i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
    7972     1832517 :   if (heap->gc_state() != i::Heap::NOT_IN_GC) return;
    7973     1832517 :   heap->CheckMemoryPressure();
    7974             : }
    7975             : 
    7976        8212 : HeapProfiler* Isolate::GetHeapProfiler() {
    7977             :   i::HeapProfiler* heap_profiler =
    7978             :       reinterpret_cast<i::Isolate*>(this)->heap_profiler();
    7979        8212 :   return reinterpret_cast<HeapProfiler*>(heap_profiler);
    7980             : }
    7981             : 
    7982           0 : void Isolate::SetIdle(bool is_idle) {
    7983             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    7984           0 :   isolate->SetIdle(is_idle);
    7985           0 : }
    7986             : 
    7987           5 : ArrayBuffer::Allocator* Isolate::GetArrayBufferAllocator() {
    7988             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    7989           5 :   return isolate->array_buffer_allocator();
    7990             : }
    7991             : 
    7992       84452 : bool Isolate::InContext() {
    7993             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    7994       84452 :   return !isolate->context().is_null();
    7995             : }
    7996             : 
    7997             : 
    7998    13102294 : v8::Local<v8::Context> Isolate::GetCurrentContext() {
    7999             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8000             :   i::Context context = isolate->context();
    8001    13102294 :   if (context.is_null()) return Local<Context>();
    8002             :   i::Context native_context = context->native_context();
    8003    13102256 :   if (native_context.is_null()) return Local<Context>();
    8004             :   return Utils::ToLocal(i::Handle<i::Context>(native_context, isolate));
    8005             : }
    8006             : 
    8007             : 
    8008           0 : v8::Local<v8::Context> Isolate::GetEnteredContext() {
    8009             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8010             :   i::Handle<i::Object> last =
    8011           0 :       isolate->handle_scope_implementer()->LastEnteredContext();
    8012           0 :   if (last.is_null()) return Local<Context>();
    8013             :   return Utils::ToLocal(i::Handle<i::Context>::cast(last));
    8014             : }
    8015             : 
    8016       53589 : v8::Local<v8::Context> Isolate::GetEnteredOrMicrotaskContext() {
    8017             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8018             :   i::Handle<i::Object> last =
    8019       53589 :       isolate->handle_scope_implementer()->LastEnteredOrMicrotaskContext();
    8020       53589 :   if (last.is_null()) return Local<Context>();
    8021             :   DCHECK(last->IsNativeContext());
    8022             :   return Utils::ToLocal(i::Handle<i::Context>::cast(last));
    8023             : }
    8024             : 
    8025           4 : v8::Local<v8::Context> Isolate::GetIncumbentContext() {
    8026             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8027           4 :   i::Handle<i::Context> context = isolate->GetIncumbentContext();
    8028           4 :   return Utils::ToLocal(context);
    8029             : }
    8030             : 
    8031        5273 : v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
    8032             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8033             :   ENTER_V8_DO_NOT_USE(isolate);
    8034             :   // If we're passed an empty handle, we throw an undefined exception
    8035             :   // to deal more gracefully with out of memory situations.
    8036        5273 :   if (value.IsEmpty()) {
    8037          24 :     isolate->ScheduleThrow(i::ReadOnlyRoots(isolate).undefined_value());
    8038             :   } else {
    8039        5249 :     isolate->ScheduleThrow(*Utils::OpenHandle(*value));
    8040             :   }
    8041       10546 :   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
    8042             : }
    8043             : 
    8044          10 : void Isolate::AddGCPrologueCallback(GCCallbackWithData callback, void* data,
    8045             :                                     GCType gc_type) {
    8046             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8047          35 :   isolate->heap()->AddGCPrologueCallback(callback, gc_type, data);
    8048          10 : }
    8049             : 
    8050          10 : void Isolate::RemoveGCPrologueCallback(GCCallbackWithData callback,
    8051             :                                        void* data) {
    8052             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8053          35 :   isolate->heap()->RemoveGCPrologueCallback(callback, data);
    8054          10 : }
    8055             : 
    8056          10 : void Isolate::AddGCEpilogueCallback(GCCallbackWithData callback, void* data,
    8057             :                                     GCType gc_type) {
    8058             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8059          35 :   isolate->heap()->AddGCEpilogueCallback(callback, gc_type, data);
    8060          10 : }
    8061             : 
    8062          10 : void Isolate::RemoveGCEpilogueCallback(GCCallbackWithData callback,
    8063             :                                        void* data) {
    8064             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8065          35 :   isolate->heap()->RemoveGCEpilogueCallback(callback, data);
    8066          10 : }
    8067             : 
    8068          90 : static void CallGCCallbackWithoutData(Isolate* isolate, GCType type,
    8069             :                                       GCCallbackFlags flags, void* data) {
    8070          90 :   reinterpret_cast<Isolate::GCCallback>(data)(isolate, type, flags);
    8071          90 : }
    8072             : 
    8073          25 : void Isolate::AddGCPrologueCallback(GCCallback callback, GCType gc_type) {
    8074             :   void* data = reinterpret_cast<void*>(callback);
    8075             :   AddGCPrologueCallback(CallGCCallbackWithoutData, data, gc_type);
    8076          25 : }
    8077             : 
    8078          25 : void Isolate::RemoveGCPrologueCallback(GCCallback callback) {
    8079             :   void* data = reinterpret_cast<void*>(callback);
    8080             :   RemoveGCPrologueCallback(CallGCCallbackWithoutData, data);
    8081          25 : }
    8082             : 
    8083          25 : void Isolate::AddGCEpilogueCallback(GCCallback callback, GCType gc_type) {
    8084             :   void* data = reinterpret_cast<void*>(callback);
    8085             :   AddGCEpilogueCallback(CallGCCallbackWithoutData, data, gc_type);
    8086          25 : }
    8087             : 
    8088          25 : void Isolate::RemoveGCEpilogueCallback(GCCallback callback) {
    8089             :   void* data = reinterpret_cast<void*>(callback);
    8090             :   RemoveGCEpilogueCallback(CallGCCallbackWithoutData, data);
    8091          25 : }
    8092             : 
    8093         150 : void Isolate::SetEmbedderHeapTracer(EmbedderHeapTracer* tracer) {
    8094             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8095         150 :   isolate->heap()->SetEmbedderHeapTracer(tracer);
    8096         150 : }
    8097             : 
    8098           0 : EmbedderHeapTracer* Isolate::GetEmbedderHeapTracer() {
    8099             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8100           0 :   return isolate->heap()->GetEmbedderHeapTracer();
    8101             : }
    8102             : 
    8103           0 : void Isolate::SetGetExternallyAllocatedMemoryInBytesCallback(
    8104             :     GetExternallyAllocatedMemoryInBytesCallback callback) {
    8105             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8106             :   isolate->heap()->SetGetExternallyAllocatedMemoryInBytesCallback(callback);
    8107           0 : }
    8108             : 
    8109        1287 : void Isolate::TerminateExecution() {
    8110             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8111             :   isolate->stack_guard()->RequestTerminateExecution();
    8112        1287 : }
    8113             : 
    8114             : 
    8115        1530 : bool Isolate::IsExecutionTerminating() {
    8116             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8117        1530 :   return IsExecutionTerminatingCheck(isolate);
    8118             : }
    8119             : 
    8120             : 
    8121          85 : void Isolate::CancelTerminateExecution() {
    8122             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8123             :   isolate->stack_guard()->ClearTerminateExecution();
    8124          85 :   isolate->CancelTerminateExecution();
    8125          85 : }
    8126             : 
    8127             : 
    8128       60065 : void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
    8129             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8130       60065 :   isolate->RequestInterrupt(callback, data);
    8131       60065 : }
    8132             : 
    8133             : 
    8134       20396 : void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
    8135       20396 :   CHECK(i::FLAG_expose_gc);
    8136       20396 :   if (type == kMinorGarbageCollection) {
    8137             :     reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
    8138             :         i::NEW_SPACE, i::GarbageCollectionReason::kTesting,
    8139         108 :         kGCCallbackFlagForced);
    8140             :   } else {
    8141             :     DCHECK_EQ(kFullGarbageCollection, type);
    8142             :     reinterpret_cast<i::Isolate*>(this)->heap()->PreciseCollectAllGarbage(
    8143             :         i::Heap::kNoGCFlags, i::GarbageCollectionReason::kTesting,
    8144       20288 :         kGCCallbackFlagForced);
    8145             :   }
    8146       20396 : }
    8147             : 
    8148             : 
    8149      920436 : Isolate* Isolate::GetCurrent() {
    8150             :   i::Isolate* isolate = i::Isolate::Current();
    8151      920436 :   return reinterpret_cast<Isolate*>(isolate);
    8152             : }
    8153             : 
    8154             : // static
    8155          85 : Isolate* Isolate::Allocate() {
    8156       62175 :   return reinterpret_cast<Isolate*>(i::Isolate::New());
    8157             : }
    8158             : 
    8159             : // static
    8160             : // This is separate so that tests can provide a different |isolate|.
    8161       62134 : void Isolate::Initialize(Isolate* isolate,
    8162             :                          const v8::Isolate::CreateParams& params) {
    8163             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    8164       62134 :   CHECK_NOT_NULL(params.array_buffer_allocator);
    8165             :   i_isolate->set_array_buffer_allocator(params.array_buffer_allocator);
    8166       62134 :   if (params.snapshot_blob != nullptr) {
    8167             :     i_isolate->set_snapshot_blob(params.snapshot_blob);
    8168             :   } else {
    8169       61959 :     i_isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
    8170             :   }
    8171       62136 :   auto code_event_handler = params.code_event_handler;
    8172             : #ifdef ENABLE_GDB_JIT_INTERFACE
    8173       62136 :   if (code_event_handler == nullptr && i::FLAG_gdbjit) {
    8174             :     code_event_handler = i::GDBJITInterface::EventHandler;
    8175             :   }
    8176             : #endif  // ENABLE_GDB_JIT_INTERFACE
    8177       62136 :   if (code_event_handler) {
    8178           0 :     i_isolate->InitializeLoggingAndCounters();
    8179             :     i_isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
    8180           0 :                                              code_event_handler);
    8181             :   }
    8182       62136 :   if (params.counter_lookup_callback) {
    8183             :     isolate->SetCounterFunction(params.counter_lookup_callback);
    8184             :   }
    8185             : 
    8186       62136 :   if (params.create_histogram_callback) {
    8187             :     isolate->SetCreateHistogramFunction(params.create_histogram_callback);
    8188             :   }
    8189             : 
    8190       62136 :   if (params.add_histogram_sample_callback) {
    8191             :     isolate->SetAddHistogramSampleFunction(
    8192             :         params.add_histogram_sample_callback);
    8193             :   }
    8194             : 
    8195       62136 :   i_isolate->set_api_external_references(params.external_references);
    8196       62136 :   i_isolate->set_allow_atomics_wait(params.allow_atomics_wait);
    8197             : 
    8198       62136 :   SetResourceConstraints(i_isolate, params.constraints);
    8199             :   // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
    8200             :   Isolate::Scope isolate_scope(isolate);
    8201       62135 :   if (!i::Snapshot::Initialize(i_isolate)) {
    8202             :     // If snapshot data was provided and we failed to deserialize it must
    8203             :     // have been corrupted.
    8204           0 :     if (i_isolate->snapshot_blob() != nullptr) {
    8205             :       FATAL(
    8206             :           "Failed to deserialize the V8 snapshot blob. This can mean that the "
    8207           0 :           "snapshot blob file is corrupted or missing.");
    8208             :     }
    8209             :     base::ElapsedTimer timer;
    8210           0 :     if (i::FLAG_profile_deserialization) timer.Start();
    8211           0 :     i_isolate->InitWithoutSnapshot();
    8212           0 :     if (i::FLAG_profile_deserialization) {
    8213           0 :       double ms = timer.Elapsed().InMillisecondsF();
    8214           0 :       i::PrintF("[Initializing isolate from scratch took %0.3f ms]\n", ms);
    8215             :     }
    8216             :   }
    8217             :   i_isolate->set_only_terminate_in_safe_scope(
    8218       62136 :       params.only_terminate_in_safe_scope);
    8219       62136 : }
    8220             : 
    8221       61895 : Isolate* Isolate::New(const Isolate::CreateParams& params) {
    8222             :   Isolate* isolate = Allocate();
    8223       61894 :   Initialize(isolate, params);
    8224       61896 :   return isolate;
    8225             : }
    8226             : 
    8227       62429 : void Isolate::Dispose() {
    8228             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8229       62429 :   if (!Utils::ApiCheck(!isolate->IsInUse(),
    8230             :                        "v8::Isolate::Dispose()",
    8231             :                        "Disposing the isolate that is entered by a thread.")) {
    8232             :     return;
    8233             :   }
    8234       62424 :   i::Isolate::Delete(isolate);
    8235             : }
    8236             : 
    8237           0 : void Isolate::DumpAndResetStats() {
    8238             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8239           0 :   isolate->DumpAndResetStats();
    8240           0 : }
    8241             : 
    8242        1500 : void Isolate::DiscardThreadSpecificMetadata() {
    8243             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8244        1500 :   isolate->DiscardPerThreadDataForThisThread();
    8245        1500 : }
    8246             : 
    8247             : 
    8248      161744 : void Isolate::Enter() {
    8249             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8250      224076 :   isolate->Enter();
    8251      161715 : }
    8252             : 
    8253             : 
    8254      161730 : void Isolate::Exit() {
    8255             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8256      224062 :   isolate->Exit();
    8257      161725 : }
    8258             : 
    8259             : 
    8260           5 : void Isolate::SetAbortOnUncaughtExceptionCallback(
    8261             :     AbortOnUncaughtExceptionCallback callback) {
    8262             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8263           5 :   isolate->SetAbortOnUncaughtExceptionCallback(callback);
    8264           5 : }
    8265             : 
    8266       30797 : void Isolate::SetHostImportModuleDynamicallyCallback(
    8267             :     HostImportModuleDynamicallyCallback callback) {
    8268             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8269       30797 :   isolate->SetHostImportModuleDynamicallyCallback(callback);
    8270       30797 : }
    8271             : 
    8272       30797 : void Isolate::SetHostInitializeImportMetaObjectCallback(
    8273             :     HostInitializeImportMetaObjectCallback callback) {
    8274             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8275       30797 :   isolate->SetHostInitializeImportMetaObjectCallback(callback);
    8276       30797 : }
    8277             : 
    8278          12 : void Isolate::SetPrepareStackTraceCallback(PrepareStackTraceCallback callback) {
    8279             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8280          12 :   isolate->SetPrepareStackTraceCallback(callback);
    8281          12 : }
    8282             : 
    8283       28952 : Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
    8284             :     Isolate* isolate,
    8285             :     Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
    8286       28952 :     : on_failure_(on_failure) {
    8287             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    8288       28952 :   switch (on_failure_) {
    8289             :     case CRASH_ON_FAILURE:
    8290             :       internal_ = reinterpret_cast<void*>(
    8291           5 :           new i::DisallowJavascriptExecution(i_isolate));
    8292           5 :       break;
    8293             :     case THROW_ON_FAILURE:
    8294             :       DCHECK_EQ(THROW_ON_FAILURE, on_failure);
    8295             :       internal_ =
    8296       28942 :           reinterpret_cast<void*>(new i::ThrowOnJavascriptExecution(i_isolate));
    8297       28942 :       break;
    8298             :     case DUMP_ON_FAILURE:
    8299             :       internal_ =
    8300           5 :           reinterpret_cast<void*>(new i::DumpOnJavascriptExecution(i_isolate));
    8301           5 :       break;
    8302             :     default:
    8303           0 :       UNREACHABLE();
    8304             :       break;
    8305             :   }
    8306       28952 : }
    8307             : 
    8308             : 
    8309       57904 : Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
    8310       28952 :   switch (on_failure_) {
    8311             :     case CRASH_ON_FAILURE:
    8312           5 :       delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
    8313             :       break;
    8314             :     case THROW_ON_FAILURE:
    8315       28942 :       delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
    8316             :       break;
    8317             :     case DUMP_ON_FAILURE:
    8318           5 :       delete reinterpret_cast<i::DumpOnJavascriptExecution*>(internal_);
    8319             :       break;
    8320             :     default:
    8321           0 :       UNREACHABLE();
    8322             :       break;
    8323             :   }
    8324       28952 : }
    8325             : 
    8326             : 
    8327      271797 : Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
    8328             :     Isolate* isolate) {
    8329             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    8330             :   internal_assert_ = reinterpret_cast<void*>(
    8331      271797 :       new i::AllowJavascriptExecution(i_isolate));
    8332             :   internal_throws_ = reinterpret_cast<void*>(
    8333      271797 :       new i::NoThrowOnJavascriptExecution(i_isolate));
    8334             :   internal_dump_ =
    8335      271797 :       reinterpret_cast<void*>(new i::NoDumpOnJavascriptExecution(i_isolate));
    8336      271797 : }
    8337             : 
    8338             : 
    8339      543594 : Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
    8340      271797 :   delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
    8341      271797 :   delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
    8342      271797 :   delete reinterpret_cast<i::NoDumpOnJavascriptExecution*>(internal_dump_);
    8343      271797 : }
    8344             : 
    8345       38113 : Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
    8346             :     Isolate* isolate)
    8347             :     : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
    8348       38113 :       microtask_queue_(isolate_->default_microtask_queue()) {
    8349             :   isolate_->handle_scope_implementer()->IncrementCallDepth();
    8350       38113 :   microtask_queue_->IncrementMicrotasksSuppressions();
    8351       38113 : }
    8352             : 
    8353       76226 : Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
    8354       38113 :   microtask_queue_->DecrementMicrotasksSuppressions();
    8355       38113 :   isolate_->handle_scope_implementer()->DecrementCallDepth();
    8356       38113 : }
    8357             : 
    8358       24272 : Isolate::SafeForTerminationScope::SafeForTerminationScope(v8::Isolate* isolate)
    8359             :     : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
    8360       24272 :       prev_value_(isolate_->next_v8_call_is_safe_for_termination()) {
    8361             :   isolate_->set_next_v8_call_is_safe_for_termination(true);
    8362       24272 : }
    8363             : 
    8364       48544 : Isolate::SafeForTerminationScope::~SafeForTerminationScope() {
    8365       24272 :   isolate_->set_next_v8_call_is_safe_for_termination(prev_value_);
    8366       24272 : }
    8367             : 
    8368          85 : i::Address* Isolate::GetDataFromSnapshotOnce(size_t index) {
    8369             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
    8370          85 :   i::FixedArray list = i_isolate->heap()->serialized_objects();
    8371          85 :   return GetSerializedDataFromFixedArray(i_isolate, list, index);
    8372             : }
    8373             : 
    8374         246 : void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
    8375             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8376             :   i::Heap* heap = isolate->heap();
    8377         246 :   heap_statistics->total_heap_size_ = heap->CommittedMemory();
    8378             :   heap_statistics->total_heap_size_executable_ =
    8379         246 :       heap->CommittedMemoryExecutable();
    8380         246 :   heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
    8381         246 :   heap_statistics->total_available_size_ = heap->Available();
    8382         246 :   heap_statistics->used_heap_size_ = heap->SizeOfObjects();
    8383         246 :   heap_statistics->heap_size_limit_ = heap->MaxReserved();
    8384             :   // TODO(7424): There is no public API for the {WasmEngine} yet. Once such an
    8385             :   // API becomes available we should report the malloced memory separately. For
    8386             :   // now we just add the values, thereby over-approximating the peak slightly.
    8387             :   heap_statistics->malloced_memory_ =
    8388         246 :       isolate->allocator()->GetCurrentMemoryUsage() +
    8389         246 :       isolate->wasm_engine()->allocator()->GetCurrentMemoryUsage();
    8390         246 :   heap_statistics->external_memory_ = isolate->heap()->backing_store_bytes();
    8391             :   heap_statistics->peak_malloced_memory_ =
    8392         246 :       isolate->allocator()->GetMaxMemoryUsage() +
    8393         246 :       isolate->wasm_engine()->allocator()->GetMaxMemoryUsage();
    8394         246 :   heap_statistics->number_of_native_contexts_ = heap->NumberOfNativeContexts();
    8395             :   heap_statistics->number_of_detached_contexts_ =
    8396         246 :       heap->NumberOfDetachedContexts();
    8397         246 :   heap_statistics->does_zap_garbage_ = heap->ShouldZapGarbage();
    8398         246 : }
    8399             : 
    8400             : 
    8401          45 : size_t Isolate::NumberOfHeapSpaces() {
    8402          45 :   return i::LAST_SPACE - i::FIRST_SPACE + 1;
    8403             : }
    8404             : 
    8405             : 
    8406          40 : bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
    8407             :                                      size_t index) {
    8408          40 :   if (!space_statistics) return false;
    8409          40 :   if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
    8410             :     return false;
    8411             : 
    8412             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8413             :   i::Heap* heap = isolate->heap();
    8414          40 :   i::Space* space = heap->space(static_cast<int>(index));
    8415             : 
    8416             :   space_statistics->space_name_ =
    8417          40 :       i::Heap::GetSpaceName(static_cast<i::AllocationSpace>(index));
    8418          40 :   space_statistics->space_size_ = space->CommittedMemory();
    8419          40 :   space_statistics->space_used_size_ = space->SizeOfObjects();
    8420          40 :   space_statistics->space_available_size_ = space->Available();
    8421          40 :   space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
    8422          40 :   return true;
    8423             : }
    8424             : 
    8425             : 
    8426           0 : size_t Isolate::NumberOfTrackedHeapObjectTypes() {
    8427             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8428             :   i::Heap* heap = isolate->heap();
    8429           0 :   return heap->NumberOfTrackedHeapObjectTypes();
    8430             : }
    8431             : 
    8432             : 
    8433           0 : bool Isolate::GetHeapObjectStatisticsAtLastGC(
    8434             :     HeapObjectStatistics* object_statistics, size_t type_index) {
    8435           0 :   if (!object_statistics) return false;
    8436           0 :   if (V8_LIKELY(!i::TracingFlags::is_gc_stats_enabled())) return false;
    8437             : 
    8438             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8439             :   i::Heap* heap = isolate->heap();
    8440           0 :   if (type_index >= heap->NumberOfTrackedHeapObjectTypes()) return false;
    8441             : 
    8442             :   const char* object_type;
    8443             :   const char* object_sub_type;
    8444           0 :   size_t object_count = heap->ObjectCountAtLastGC(type_index);
    8445           0 :   size_t object_size = heap->ObjectSizeAtLastGC(type_index);
    8446           0 :   if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
    8447             :     // There should be no objects counted when the type is unknown.
    8448             :     DCHECK_EQ(object_count, 0U);
    8449             :     DCHECK_EQ(object_size, 0U);
    8450             :     return false;
    8451             :   }
    8452             : 
    8453           0 :   object_statistics->object_type_ = object_type;
    8454           0 :   object_statistics->object_sub_type_ = object_sub_type;
    8455           0 :   object_statistics->object_count_ = object_count;
    8456           0 :   object_statistics->object_size_ = object_size;
    8457           0 :   return true;
    8458             : }
    8459             : 
    8460           0 : bool Isolate::GetHeapCodeAndMetadataStatistics(
    8461             :     HeapCodeStatistics* code_statistics) {
    8462           0 :   if (!code_statistics) return false;
    8463             : 
    8464             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8465           0 :   isolate->heap()->CollectCodeStatistics();
    8466             : 
    8467           0 :   code_statistics->code_and_metadata_size_ = isolate->code_and_metadata_size();
    8468             :   code_statistics->bytecode_and_metadata_size_ =
    8469           0 :       isolate->bytecode_and_metadata_size();
    8470             :   code_statistics->external_script_source_size_ =
    8471           0 :       isolate->external_script_source_size();
    8472           0 :   return true;
    8473             : }
    8474             : 
    8475          15 : void Isolate::GetStackSample(const RegisterState& state, void** frames,
    8476             :                              size_t frames_limit, SampleInfo* sample_info) {
    8477          15 :   RegisterState regs = state;
    8478          15 :   if (TickSample::GetStackSample(this, &regs, TickSample::kSkipCEntryFrame,
    8479             :                                  frames, frames_limit, sample_info)) {
    8480          15 :     return;
    8481             :   }
    8482           0 :   sample_info->frames_count = 0;
    8483           0 :   sample_info->vm_state = OTHER;
    8484           0 :   sample_info->external_callback_entry = nullptr;
    8485             : }
    8486             : 
    8487          15 : size_t Isolate::NumberOfPhantomHandleResetsSinceLastCall() {
    8488             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8489          15 :   return isolate->global_handles()->GetAndResetGlobalHandleResetCount();
    8490             : }
    8491             : 
    8492           5 : void Isolate::SetEventLogger(LogEventCallback that) {
    8493             :   // Do not overwrite the event logger if we want to log explicitly.
    8494           5 :   if (i::FLAG_log_internal_timer_events) return;
    8495             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8496             :   isolate->set_event_logger(that);
    8497             : }
    8498             : 
    8499             : 
    8500          15 : void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) {
    8501          15 :   if (callback == nullptr) return;
    8502             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8503          15 :   isolate->AddBeforeCallEnteredCallback(callback);
    8504             : }
    8505             : 
    8506             : 
    8507           5 : void Isolate::RemoveBeforeCallEnteredCallback(
    8508             :     BeforeCallEnteredCallback callback) {
    8509             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8510           5 :   isolate->RemoveBeforeCallEnteredCallback(callback);
    8511           5 : }
    8512             : 
    8513             : 
    8514          65 : void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
    8515          65 :   if (callback == nullptr) return;
    8516             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8517          65 :   isolate->AddCallCompletedCallback(callback);
    8518             : }
    8519             : 
    8520             : 
    8521        3730 : void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
    8522             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8523        3730 :   isolate->RemoveCallCompletedCallback(callback);
    8524        3730 : }
    8525             : 
    8526          52 : void Isolate::AtomicsWaitWakeHandle::Wake() {
    8527          52 :   reinterpret_cast<i::AtomicsWaitWakeHandle*>(this)->Wake();
    8528          52 : }
    8529             : 
    8530          13 : void Isolate::SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data) {
    8531             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8532          13 :   isolate->SetAtomicsWaitCallback(callback, data);
    8533          13 : }
    8534             : 
    8535         111 : void Isolate::SetPromiseHook(PromiseHook hook) {
    8536             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8537         111 :   isolate->SetPromiseHook(hook);
    8538         111 : }
    8539             : 
    8540        1154 : void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
    8541        1154 :   if (callback == nullptr) return;
    8542             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8543        1154 :   isolate->SetPromiseRejectCallback(callback);
    8544             : }
    8545             : 
    8546             : 
    8547         127 : void Isolate::RunMicrotasks() {
    8548             :   DCHECK_NE(MicrotasksPolicy::kScoped, GetMicrotasksPolicy());
    8549             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8550         127 :   isolate->default_microtask_queue()->RunMicrotasks(isolate);
    8551         127 : }
    8552             : 
    8553         121 : void Isolate::EnqueueMicrotask(Local<Function> v8_function) {
    8554             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8555         121 :   i::Handle<i::JSReceiver> function = Utils::OpenHandle(*v8_function);
    8556             :   i::Handle<i::NativeContext> handler_context;
    8557         242 :   if (!i::JSReceiver::GetContextForMicrotask(function).ToHandle(
    8558             :           &handler_context))
    8559           0 :     handler_context = isolate->native_context();
    8560             :   MicrotaskQueue* microtask_queue = handler_context->microtask_queue();
    8561         121 :   if (microtask_queue) microtask_queue->EnqueueMicrotask(this, v8_function);
    8562         121 : }
    8563             : 
    8564         441 : void Isolate::EnqueueMicrotask(MicrotaskCallback callback, void* data) {
    8565             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8566             :   i::HandleScope scope(isolate);
    8567             :   i::Handle<i::CallbackTask> microtask = isolate->factory()->NewCallbackTask(
    8568             :       isolate->factory()->NewForeign(reinterpret_cast<i::Address>(callback)),
    8569         441 :       isolate->factory()->NewForeign(reinterpret_cast<i::Address>(data)));
    8570         441 :   isolate->default_microtask_queue()->EnqueueMicrotask(*microtask);
    8571         441 : }
    8572             : 
    8573             : 
    8574        2328 : void Isolate::SetMicrotasksPolicy(MicrotasksPolicy policy) {
    8575             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8576             :   isolate->default_microtask_queue()->set_microtasks_policy(policy);
    8577        2328 : }
    8578             : 
    8579             : 
    8580           0 : MicrotasksPolicy Isolate::GetMicrotasksPolicy() const {
    8581             :   i::Isolate* isolate =
    8582             :       reinterpret_cast<i::Isolate*>(const_cast<Isolate*>(this));
    8583           0 :   return isolate->default_microtask_queue()->microtasks_policy();
    8584             : }
    8585             : 
    8586             : namespace {
    8587             : 
    8588           0 : void MicrotasksCompletedCallbackAdapter(v8::Isolate* isolate, void* data) {
    8589           0 :   auto callback = reinterpret_cast<void (*)(v8::Isolate*)>(data);
    8590           0 :   callback(isolate);
    8591           0 : }
    8592             : 
    8593             : }  // namespace
    8594             : 
    8595           0 : void Isolate::AddMicrotasksCompletedCallback(
    8596             :     MicrotasksCompletedCallback callback) {
    8597             :   DCHECK(callback);
    8598             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8599             :   isolate->default_microtask_queue()->AddMicrotasksCompletedCallback(
    8600           0 :       &MicrotasksCompletedCallbackAdapter, reinterpret_cast<void*>(callback));
    8601           0 : }
    8602             : 
    8603          45 : void Isolate::AddMicrotasksCompletedCallback(
    8604             :     MicrotasksCompletedCallbackWithData callback, void* data) {
    8605             :   DCHECK(callback);
    8606             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8607             :   isolate->default_microtask_queue()->AddMicrotasksCompletedCallback(callback,
    8608          45 :                                                                      data);
    8609          45 : }
    8610             : 
    8611           0 : void Isolate::RemoveMicrotasksCompletedCallback(
    8612             :     MicrotasksCompletedCallback callback) {
    8613             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8614             :   isolate->default_microtask_queue()->RemoveMicrotasksCompletedCallback(
    8615           0 :       &MicrotasksCompletedCallbackAdapter, reinterpret_cast<void*>(callback));
    8616           0 : }
    8617             : 
    8618        3730 : void Isolate::RemoveMicrotasksCompletedCallback(
    8619             :     MicrotasksCompletedCallbackWithData callback, void* data) {
    8620             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8621             :   isolate->default_microtask_queue()->RemoveMicrotasksCompletedCallback(
    8622        3730 :       callback, data);
    8623        3730 : }
    8624             : 
    8625          55 : void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
    8626          55 :   reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
    8627          55 : }
    8628             : 
    8629             : 
    8630           5 : void Isolate::SetCounterFunction(CounterLookupCallback callback) {
    8631             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8632        1271 :   isolate->counters()->ResetCounterFunction(callback);
    8633           5 : }
    8634             : 
    8635             : 
    8636           8 : void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
    8637             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8638           8 :   isolate->counters()->ResetCreateHistogramFunction(callback);
    8639           8 : }
    8640             : 
    8641             : 
    8642           8 : void Isolate::SetAddHistogramSampleFunction(
    8643             :     AddHistogramSampleCallback callback) {
    8644             :   reinterpret_cast<i::Isolate*>(this)
    8645             :       ->counters()
    8646             :       ->SetAddHistogramSampleFunction(callback);
    8647           8 : }
    8648             : 
    8649             : 
    8650         479 : bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
    8651             :   // Returning true tells the caller that it need not
    8652             :   // continue to call IdleNotification.
    8653             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8654         479 :   if (!i::FLAG_use_idle_notification) return true;
    8655         479 :   return isolate->heap()->IdleNotification(deadline_in_seconds);
    8656             : }
    8657             : 
    8658         519 : void Isolate::LowMemoryNotification() {
    8659             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8660             :   {
    8661             :     i::HistogramTimerScope idle_notification_scope(
    8662             :         isolate->counters()->gc_low_memory_notification());
    8663        1557 :     TRACE_EVENT0("v8", "V8.GCLowMemoryNotification");
    8664             :     isolate->heap()->CollectAllAvailableGarbage(
    8665         519 :         i::GarbageCollectionReason::kLowMemoryNotification);
    8666             :   }
    8667             :   {
    8668        1038 :     i::HeapIterator iterator(isolate->heap());
    8669     6696864 :     for (i::HeapObject obj = iterator.next(); !obj.is_null();
    8670             :          obj = iterator.next()) {
    8671     3347913 :       if (obj->IsAbstractCode()) {
    8672      792059 :         i::AbstractCode::cast(obj)->DropStackFrameCache();
    8673             :       }
    8674             :     }
    8675             :   }
    8676         519 : }
    8677             : 
    8678             : 
    8679         593 : int Isolate::ContextDisposedNotification(bool dependant_context) {
    8680             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8681         593 :   if (!dependant_context) {
    8682             :     // We left the current context, we can abort all WebAssembly compilations on
    8683             :     // that isolate.
    8684          10 :     isolate->wasm_engine()->DeleteCompileJobsOnIsolate(isolate);
    8685             :   }
    8686             :   // TODO(ahaas): move other non-heap activity out of the heap call.
    8687        1186 :   return isolate->heap()->NotifyContextDisposed(dependant_context);
    8688             : }
    8689             : 
    8690             : 
    8691           0 : void Isolate::IsolateInForegroundNotification() {
    8692             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8693           0 :   return isolate->IsolateInForegroundNotification();
    8694             : }
    8695             : 
    8696             : 
    8697           0 : void Isolate::IsolateInBackgroundNotification() {
    8698             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8699           0 :   return isolate->IsolateInBackgroundNotification();
    8700             : }
    8701             : 
    8702          81 : void Isolate::MemoryPressureNotification(MemoryPressureLevel level) {
    8703             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8704             :   bool on_isolate_thread =
    8705          81 :       v8::Locker::IsActive()
    8706             :           ? isolate->thread_manager()->IsLockedByCurrentThread()
    8707          81 :           : i::ThreadId::Current() == isolate->thread_id();
    8708         162 :   isolate->heap()->MemoryPressureNotification(level, on_isolate_thread);
    8709          81 : }
    8710             : 
    8711           5 : void Isolate::EnableMemorySavingsMode() {
    8712             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8713             :   isolate->EnableMemorySavingsMode();
    8714           5 : }
    8715             : 
    8716           5 : void Isolate::DisableMemorySavingsMode() {
    8717             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8718             :   isolate->DisableMemorySavingsMode();
    8719           5 : }
    8720             : 
    8721           0 : void Isolate::SetRAILMode(RAILMode rail_mode) {
    8722             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8723           0 :   return isolate->SetRAILMode(rail_mode);
    8724             : }
    8725             : 
    8726           0 : void Isolate::IncreaseHeapLimitForDebugging() {
    8727             :   // No-op.
    8728           0 : }
    8729             : 
    8730           5 : void Isolate::RestoreOriginalHeapLimit() {
    8731             :   // No-op.
    8732           5 : }
    8733             : 
    8734           0 : bool Isolate::IsHeapLimitIncreasedForDebugging() { return false; }
    8735             : 
    8736          60 : void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
    8737             :                                      JitCodeEventHandler event_handler) {
    8738             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8739             :   // Ensure that logging is initialized for our isolate.
    8740          60 :   isolate->InitializeLoggingAndCounters();
    8741          60 :   isolate->logger()->SetCodeEventHandler(options, event_handler);
    8742          60 : }
    8743             : 
    8744             : 
    8745          10 : void Isolate::SetStackLimit(uintptr_t stack_limit) {
    8746             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8747          10 :   CHECK(stack_limit);
    8748          10 :   isolate->stack_guard()->SetStackLimit(stack_limit);
    8749          10 : }
    8750             : 
    8751           0 : void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
    8752             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8753             :   const base::AddressRegion& code_range =
    8754             :       isolate->heap()->memory_allocator()->code_range();
    8755          70 :   *start = reinterpret_cast<void*>(code_range.begin());
    8756          70 :   *length_in_bytes = code_range.size();
    8757           0 : }
    8758             : 
    8759          70 : UnwindState Isolate::GetUnwindState() {
    8760          70 :   UnwindState unwind_state;
    8761             :   void* code_range_start;
    8762             :   GetCodeRange(&code_range_start, &unwind_state.code_range.length_in_bytes);
    8763          70 :   unwind_state.code_range.start = code_range_start;
    8764             : 
    8765             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8766             :   unwind_state.embedded_code_range.start =
    8767          70 :       reinterpret_cast<const void*>(isolate->embedded_blob());
    8768             :   unwind_state.embedded_code_range.length_in_bytes =
    8769          70 :       isolate->embedded_blob_size();
    8770             : 
    8771          70 :   i::Code js_entry = isolate->heap()->builtin(i::Builtins::kJSEntry);
    8772             :   unwind_state.js_entry_stub.code.start =
    8773          70 :       reinterpret_cast<const void*>(js_entry->InstructionStart());
    8774          70 :   unwind_state.js_entry_stub.code.length_in_bytes = js_entry->InstructionSize();
    8775             : 
    8776          70 :   return unwind_state;
    8777             : }
    8778             : 
    8779             : #define CALLBACK_SETTER(ExternalName, Type, InternalName)      \
    8780             :   void Isolate::Set##ExternalName(Type callback) {             \
    8781             :     i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); \
    8782             :     isolate->set_##InternalName(callback);                     \
    8783             :   }
    8784             : 
    8785          80 : CALLBACK_SETTER(FatalErrorHandler, FatalErrorCallback, exception_behavior)
    8786           0 : CALLBACK_SETTER(OOMErrorHandler, OOMErrorCallback, oom_behavior)
    8787         340 : CALLBACK_SETTER(AllowCodeGenerationFromStringsCallback,
    8788             :                 AllowCodeGenerationFromStringsCallback, allow_code_gen_callback)
    8789         272 : CALLBACK_SETTER(AllowWasmCodeGenerationCallback,
    8790             :                 AllowWasmCodeGenerationCallback, allow_wasm_code_gen_callback)
    8791             : 
    8792          96 : CALLBACK_SETTER(WasmModuleCallback, ExtensionCallback, wasm_module_callback)
    8793          16 : CALLBACK_SETTER(WasmInstanceCallback, ExtensionCallback, wasm_instance_callback)
    8794             : 
    8795          48 : CALLBACK_SETTER(WasmStreamingCallback, WasmStreamingCallback,
    8796             :                 wasm_streaming_callback)
    8797             : 
    8798          58 : CALLBACK_SETTER(WasmThreadsEnabledCallback, WasmThreadsEnabledCallback,
    8799             :                 wasm_threads_enabled_callback)
    8800             : 
    8801        3431 : void Isolate::AddNearHeapLimitCallback(v8::NearHeapLimitCallback callback,
    8802             :                                        void* data) {
    8803             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8804        3431 :   isolate->heap()->AddNearHeapLimitCallback(callback, data);
    8805        3431 : }
    8806             : 
    8807        3431 : void Isolate::RemoveNearHeapLimitCallback(v8::NearHeapLimitCallback callback,
    8808             :                                           size_t heap_limit) {
    8809             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8810        3431 :   isolate->heap()->RemoveNearHeapLimitCallback(callback, heap_limit);
    8811        3431 : }
    8812             : 
    8813           0 : void Isolate::AutomaticallyRestoreInitialHeapLimit(double threshold_percent) {
    8814             :   DCHECK_GT(threshold_percent, 0.0);
    8815             :   DCHECK_LT(threshold_percent, 1.0);
    8816             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8817           0 :   isolate->heap()->AutomaticallyRestoreInitialHeapLimit(threshold_percent);
    8818           0 : }
    8819             : 
    8820           0 : bool Isolate::IsDead() {
    8821             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8822           0 :   return isolate->IsDead();
    8823             : }
    8824             : 
    8825        1275 : bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
    8826        1275 :   return AddMessageListenerWithErrorLevel(that, kMessageError, data);
    8827             : }
    8828             : 
    8829       31436 : bool Isolate::AddMessageListenerWithErrorLevel(MessageCallback that,
    8830             :                                                int message_levels,
    8831             :                                                Local<Value> data) {
    8832             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8833             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    8834             :   i::HandleScope scope(isolate);
    8835             :   i::Handle<i::TemplateList> list = isolate->factory()->message_listeners();
    8836       31436 :   i::Handle<i::FixedArray> listener = isolate->factory()->NewFixedArray(3);
    8837             :   i::Handle<i::Foreign> foreign =
    8838       31436 :       isolate->factory()->NewForeign(FUNCTION_ADDR(that));
    8839       62872 :   listener->set(0, *foreign);
    8840      125728 :   listener->set(1, data.IsEmpty() ? i::ReadOnlyRoots(isolate).undefined_value()
    8841       31436 :                                   : *Utils::OpenHandle(*data));
    8842             :   listener->set(2, i::Smi::FromInt(message_levels));
    8843       31436 :   list = i::TemplateList::Add(isolate, list, listener);
    8844             :   isolate->heap()->SetMessageListeners(*list);
    8845       31436 :   return true;
    8846             : }
    8847             : 
    8848             : 
    8849         151 : void Isolate::RemoveMessageListeners(MessageCallback that) {
    8850             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8851             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    8852             :   i::HandleScope scope(isolate);
    8853             :   i::DisallowHeapAllocation no_gc;
    8854             :   i::TemplateList listeners = isolate->heap()->message_listeners();
    8855         344 :   for (int i = 0; i < listeners->length(); i++) {
    8856         193 :     if (listeners->get(i)->IsUndefined(isolate)) continue;  // skip deleted ones
    8857             :     i::FixedArray listener = i::FixedArray::cast(listeners->get(i));
    8858             :     i::Foreign callback_obj = i::Foreign::cast(listener->get(0));
    8859         151 :     if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
    8860             :       listeners->set(i, i::ReadOnlyRoots(isolate).undefined_value());
    8861             :     }
    8862             :   }
    8863         151 : }
    8864             : 
    8865             : 
    8866          26 : void Isolate::SetFailedAccessCheckCallbackFunction(
    8867             :     FailedAccessCheckCallback callback) {
    8868             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8869          26 :   isolate->SetFailedAccessCheckCallback(callback);
    8870          26 : }
    8871             : 
    8872             : 
    8873        1311 : void Isolate::SetCaptureStackTraceForUncaughtExceptions(
    8874             :     bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
    8875             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8876        1311 :   isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
    8877        1311 :                                                      options);
    8878        1311 : }
    8879             : 
    8880             : 
    8881           5 : void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) {
    8882             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8883           5 :   isolate->heap()->VisitExternalResources(visitor);
    8884           5 : }
    8885             : 
    8886             : 
    8887       64518 : bool Isolate::IsInUse() {
    8888             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8889       64518 :   return isolate->IsInUse();
    8890             : }
    8891             : 
    8892             : 
    8893          10 : void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
    8894             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8895             :   i::DisallowHeapAllocation no_allocation;
    8896          10 :   isolate->global_handles()->IterateAllRootsWithClassIds(visitor);
    8897          10 : }
    8898             : 
    8899           0 : void Isolate::VisitWeakHandles(PersistentHandleVisitor* visitor) {
    8900             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8901             :   i::DisallowHeapAllocation no_allocation;
    8902           0 :   isolate->global_handles()->IterateYoungWeakRootsWithClassIds(visitor);
    8903           0 : }
    8904             : 
    8905           5 : void Isolate::SetAllowAtomicsWait(bool allow) {
    8906             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
    8907             :   isolate->set_allow_atomics_wait(allow);
    8908           5 : }
    8909             : 
    8910           0 : void v8::Isolate::DateTimeConfigurationChangeNotification(
    8911             :     TimeZoneDetection time_zone_detection) {
    8912             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
    8913           0 :   LOG_API(i_isolate, Isolate, DateTimeConfigurationChangeNotification);
    8914             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    8915             :   i_isolate->date_cache()->ResetDateCache(
    8916           0 :       static_cast<base::TimezoneCache::TimeZoneDetection>(time_zone_detection));
    8917             : #ifdef V8_INTL_SUPPORT
    8918             :   i_isolate->clear_cached_icu_object(
    8919           0 :       i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormat);
    8920             :   i_isolate->clear_cached_icu_object(
    8921           0 :       i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForTime);
    8922             :   i_isolate->clear_cached_icu_object(
    8923           0 :       i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForDate);
    8924             : #endif  // V8_INTL_SUPPORT
    8925           0 : }
    8926             : 
    8927           0 : void v8::Isolate::LocaleConfigurationChangeNotification() {
    8928             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
    8929           0 :   LOG_API(i_isolate, Isolate, LocaleConfigurationChangeNotification);
    8930             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    8931             : 
    8932             : #ifdef V8_INTL_SUPPORT
    8933             :   i_isolate->ResetDefaultLocale();
    8934             : #endif  // V8_INTL_SUPPORT
    8935           0 : }
    8936             : 
    8937             : // static
    8938           0 : std::unique_ptr<MicrotaskQueue> MicrotaskQueue::New(Isolate* isolate,
    8939             :                                                     MicrotasksPolicy policy) {
    8940             :   auto microtask_queue =
    8941           0 :       i::MicrotaskQueue::New(reinterpret_cast<i::Isolate*>(isolate));
    8942             :   microtask_queue->set_microtasks_policy(policy);
    8943           0 :   return microtask_queue;
    8944             : }
    8945             : 
    8946     1291311 : MicrotasksScope::MicrotasksScope(Isolate* isolate, MicrotasksScope::Type type)
    8947     1291311 :     : MicrotasksScope(isolate, nullptr, type) {}
    8948             : 
    8949           1 : MicrotasksScope::MicrotasksScope(Isolate* isolate,
    8950             :                                  MicrotaskQueue* microtask_queue,
    8951             :                                  MicrotasksScope::Type type)
    8952             :     : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
    8953             :       microtask_queue_(microtask_queue
    8954             :                            ? static_cast<i::MicrotaskQueue*>(microtask_queue)
    8955             :                            : isolate_->default_microtask_queue()),
    8956     1291312 :       run_(type == MicrotasksScope::kRunMicrotasks) {
    8957     1291312 :   if (run_) microtask_queue_->IncrementMicrotasksScopeDepth();
    8958             : #ifdef DEBUG
    8959             :   if (!run_) microtask_queue_->IncrementDebugMicrotasksScopeDepth();
    8960             : #endif
    8961           1 : }
    8962             : 
    8963     2582613 : MicrotasksScope::~MicrotasksScope() {
    8964     1291307 :   if (run_) {
    8965      143117 :     microtask_queue_->DecrementMicrotasksScopeDepth();
    8966      143117 :     if (MicrotasksPolicy::kScoped == microtask_queue_->microtasks_policy()) {
    8967       75236 :       microtask_queue_->PerformCheckpoint(reinterpret_cast<Isolate*>(isolate_));
    8968             :     }
    8969             :   }
    8970             : #ifdef DEBUG
    8971             :   if (!run_) microtask_queue_->DecrementDebugMicrotasksScopeDepth();
    8972             : #endif
    8973     1291306 : }
    8974             : 
    8975       45733 : void MicrotasksScope::PerformCheckpoint(Isolate* v8_isolate) {
    8976             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    8977             :   auto* microtask_queue = isolate->default_microtask_queue();
    8978       45733 :   microtask_queue->PerformCheckpoint(v8_isolate);
    8979       45733 : }
    8980             : 
    8981           0 : int MicrotasksScope::GetCurrentDepth(Isolate* v8_isolate) {
    8982             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    8983             :   auto* microtask_queue = isolate->default_microtask_queue();
    8984           0 :   return microtask_queue->GetMicrotasksScopeDepth();
    8985             : }
    8986             : 
    8987         100 : bool MicrotasksScope::IsRunningMicrotasks(Isolate* v8_isolate) {
    8988             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    8989             :   auto* microtask_queue = isolate->default_microtask_queue();
    8990         100 :   return microtask_queue->IsRunningMicrotasks();
    8991             : }
    8992             : 
    8993     9054022 : String::Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> obj)
    8994     9054022 :     : str_(nullptr), length_(0) {
    8995     9054065 :   if (obj.IsEmpty()) return;
    8996             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    8997             :   ENTER_V8_DO_NOT_USE(i_isolate);
    8998             :   i::HandleScope scope(i_isolate);
    8999     9053987 :   Local<Context> context = isolate->GetCurrentContext();
    9000    18107966 :   TryCatch try_catch(isolate);
    9001             :   Local<String> str;
    9002    18107982 :   if (!obj->ToString(context).ToLocal(&str)) return;
    9003     9053979 :   length_ = str->Utf8Length(isolate);
    9004     9053979 :   str_ = i::NewArray<char>(length_ + 1);
    9005     9053979 :   str->WriteUtf8(isolate, str_);
    9006             : }
    9007             : 
    9008    18108044 : String::Utf8Value::~Utf8Value() {
    9009     9054022 :   i::DeleteArray(str_);
    9010     9054022 : }
    9011             : 
    9012           6 : String::Value::Value(v8::Isolate* isolate, v8::Local<v8::Value> obj)
    9013           6 :     : str_(nullptr), length_(0) {
    9014           6 :   if (obj.IsEmpty()) return;
    9015             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    9016             :   ENTER_V8_DO_NOT_USE(i_isolate);
    9017             :   i::HandleScope scope(i_isolate);
    9018           6 :   Local<Context> context = isolate->GetCurrentContext();
    9019          12 :   TryCatch try_catch(isolate);
    9020             :   Local<String> str;
    9021          12 :   if (!obj->ToString(context).ToLocal(&str)) return;
    9022           6 :   length_ = str->Length();
    9023           6 :   str_ = i::NewArray<uint16_t>(length_ + 1);
    9024             :   str->Write(isolate, str_);
    9025             : }
    9026             : 
    9027          12 : String::Value::~Value() {
    9028           6 :   i::DeleteArray(str_);
    9029           6 : }
    9030             : 
    9031             : #define DEFINE_ERROR(NAME, name)                                         \
    9032             :   Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) {      \
    9033             :     i::Isolate* isolate = i::Isolate::Current();                         \
    9034             :     LOG_API(isolate, NAME, New);                                         \
    9035             :     ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);                            \
    9036             :     i::Object error;                                                     \
    9037             :     {                                                                    \
    9038             :       i::HandleScope scope(isolate);                                     \
    9039             :       i::Handle<i::String> message = Utils::OpenHandle(*raw_message);    \
    9040             :       i::Handle<i::JSFunction> constructor = isolate->name##_function(); \
    9041             :       error = *isolate->factory()->NewError(constructor, message);       \
    9042             :     }                                                                    \
    9043             :     i::Handle<i::Object> result(error, isolate);                         \
    9044             :     return Utils::ToLocal(result);                                       \
    9045             :   }
    9046             : 
    9047         110 : DEFINE_ERROR(RangeError, range_error)
    9048          30 : DEFINE_ERROR(ReferenceError, reference_error)
    9049          30 : DEFINE_ERROR(SyntaxError, syntax_error)
    9050          30 : DEFINE_ERROR(TypeError, type_error)
    9051        1215 : DEFINE_ERROR(Error, error)
    9052             : 
    9053             : #undef DEFINE_ERROR
    9054             : 
    9055             : 
    9056         328 : Local<Message> Exception::CreateMessage(Isolate* isolate,
    9057             :                                         Local<Value> exception) {
    9058         328 :   i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
    9059             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    9060             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    9061             :   i::HandleScope scope(i_isolate);
    9062             :   return Utils::MessageToLocal(
    9063         656 :       scope.CloseAndEscape(i_isolate->CreateMessage(obj, nullptr)));
    9064             : }
    9065             : 
    9066             : 
    9067          77 : Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) {
    9068             :   i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
    9069          77 :   if (!obj->IsJSObject()) return Local<StackTrace>();
    9070             :   i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
    9071             :   i::Isolate* isolate = js_obj->GetIsolate();
    9072             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9073          77 :   return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj));
    9074             : }
    9075             : 
    9076             : 
    9077             : // --- D e b u g   S u p p o r t ---
    9078             : 
    9079        3784 : void debug::SetContextId(Local<Context> context, int id) {
    9080        7568 :   Utils::OpenHandle(*context)->set_debug_context_id(i::Smi::FromInt(id));
    9081        3784 : }
    9082             : 
    9083     3881947 : int debug::GetContextId(Local<Context> context) {
    9084     3881947 :   i::Object value = Utils::OpenHandle(*context)->debug_context_id();
    9085     7763894 :   return (value->IsSmi()) ? i::Smi::ToInt(value) : 0;
    9086             : }
    9087             : 
    9088        7370 : void debug::SetInspector(Isolate* isolate,
    9089             :                          v8_inspector::V8Inspector* inspector) {
    9090             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    9091             :   i_isolate->set_inspector(inspector);
    9092        7370 : }
    9093             : 
    9094     7194405 : v8_inspector::V8Inspector* debug::GetInspector(Isolate* isolate) {
    9095     7194405 :   return reinterpret_cast<i::Isolate*>(isolate)->inspector();
    9096             : }
    9097             : 
    9098        6615 : void debug::SetBreakOnNextFunctionCall(Isolate* isolate) {
    9099        6615 :   reinterpret_cast<i::Isolate*>(isolate)->debug()->SetBreakOnNextFunctionCall();
    9100        6615 : }
    9101             : 
    9102          30 : void debug::ClearBreakOnNextFunctionCall(Isolate* isolate) {
    9103             :   reinterpret_cast<i::Isolate*>(isolate)
    9104             :       ->debug()
    9105          30 :       ->ClearBreakOnNextFunctionCall();
    9106          30 : }
    9107             : 
    9108       79258 : MaybeLocal<Array> debug::GetInternalProperties(Isolate* v8_isolate,
    9109             :                                                Local<Value> value) {
    9110             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9111             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9112       79258 :   i::Handle<i::Object> val = Utils::OpenHandle(*value);
    9113             :   i::Handle<i::JSArray> result;
    9114      158516 :   if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
    9115           0 :     return MaybeLocal<Array>();
    9116       79258 :   return Utils::ToLocal(result);
    9117             : }
    9118             : 
    9119       79273 : MaybeLocal<Array> debug::GetPrivateFields(Local<Context> context,
    9120             :                                           Local<Object> value) {
    9121      317092 :   PREPARE_FOR_EXECUTION(context, debug, GetPrivateFields, Array);
    9122       79273 :   i::Handle<i::JSReceiver> val = Utils::OpenHandle(*value);
    9123             :   i::Handle<i::JSArray> result;
    9124             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    9125             :   has_pending_exception =
    9126      158546 :       !(internal_isolate->debug()->GetPrivateFields(val).ToHandle(&result));
    9127       79273 :   RETURN_ON_FAILED_EXECUTION(Array);
    9128       79273 :   RETURN_ESCAPED(Utils::ToLocal(result));
    9129             : }
    9130             : 
    9131        7506 : void debug::ChangeBreakOnException(Isolate* isolate, ExceptionBreakState type) {
    9132             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    9133        7506 :   internal_isolate->debug()->ChangeBreakOnException(
    9134        7506 :       i::BreakException, type == BreakOnAnyException);
    9135        7506 :   internal_isolate->debug()->ChangeBreakOnException(i::BreakUncaughtException,
    9136        7506 :                                                     type != NoBreakOnException);
    9137        7506 : }
    9138             : 
    9139        7102 : void debug::SetBreakPointsActive(Isolate* v8_isolate, bool is_active) {
    9140             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9141             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9142             :   isolate->debug()->set_break_points_active(is_active);
    9143        7102 : }
    9144             : 
    9145       44423 : void debug::PrepareStep(Isolate* v8_isolate, StepAction action) {
    9146             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9147             :   ENTER_V8_DO_NOT_USE(isolate);
    9148       44423 :   CHECK(isolate->debug()->CheckExecutionState());
    9149             :   // Clear all current stepping setup.
    9150       44423 :   isolate->debug()->ClearStepping();
    9151             :   // Prepare step.
    9152       44423 :   isolate->debug()->PrepareStep(static_cast<i::StepAction>(action));
    9153       44423 : }
    9154             : 
    9155           0 : void debug::ClearStepping(Isolate* v8_isolate) {
    9156             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9157             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9158             :   // Clear all current stepping setup.
    9159           0 :   isolate->debug()->ClearStepping();
    9160           0 : }
    9161             : 
    9162       60221 : void debug::BreakRightNow(Isolate* v8_isolate) {
    9163             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9164             :   ENTER_V8_DO_NOT_USE(isolate);
    9165       60221 :   isolate->debug()->HandleDebugBreak(i::kIgnoreIfAllFramesBlackboxed);
    9166       60221 : }
    9167             : 
    9168         370 : bool debug::AllFramesOnStackAreBlackboxed(Isolate* v8_isolate) {
    9169             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9170             :   ENTER_V8_DO_NOT_USE(isolate);
    9171         740 :   return isolate->debug()->AllFramesOnStackAreBlackboxed();
    9172             : }
    9173             : 
    9174           0 : v8::Isolate* debug::Script::GetIsolate() const {
    9175           0 :   return reinterpret_cast<v8::Isolate*>(Utils::OpenHandle(this)->GetIsolate());
    9176             : }
    9177             : 
    9178           0 : ScriptOriginOptions debug::Script::OriginOptions() const {
    9179           0 :   return Utils::OpenHandle(this)->origin_options();
    9180             : }
    9181             : 
    9182       33907 : bool debug::Script::WasCompiled() const {
    9183             :   return Utils::OpenHandle(this)->compilation_state() ==
    9184       33907 :          i::Script::COMPILATION_STATE_COMPILED;
    9185             : }
    9186             : 
    9187       33804 : bool debug::Script::IsEmbedded() const {
    9188             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9189             :   return script->context_data() ==
    9190       33804 :          script->GetReadOnlyRoots().uninitialized_symbol();
    9191             : }
    9192             : 
    9193      723926 : int debug::Script::Id() const { return Utils::OpenHandle(this)->id(); }
    9194             : 
    9195       56042 : int debug::Script::LineOffset() const {
    9196       56042 :   return Utils::OpenHandle(this)->line_offset();
    9197             : }
    9198             : 
    9199       56042 : int debug::Script::ColumnOffset() const {
    9200       56042 :   return Utils::OpenHandle(this)->column_offset();
    9201             : }
    9202             : 
    9203       56042 : std::vector<int> debug::Script::LineEnds() const {
    9204             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9205       56046 :   if (script->type() == i::Script::TYPE_WASM &&
    9206           4 :       this->SourceMappingURL().IsEmpty()) {
    9207             :     return std::vector<int>();
    9208             :   }
    9209             :   i::Isolate* isolate = script->GetIsolate();
    9210             :   i::HandleScope scope(isolate);
    9211       56042 :   i::Script::InitLineEnds(script);
    9212       56042 :   CHECK(script->line_ends()->IsFixedArray());
    9213             :   i::Handle<i::FixedArray> line_ends(i::FixedArray::cast(script->line_ends()),
    9214             :                                      isolate);
    9215       56042 :   std::vector<int> result(line_ends->length());
    9216    17756592 :   for (int i = 0; i < line_ends->length(); ++i) {
    9217             :     i::Smi line_end = i::Smi::cast(line_ends->get(i));
    9218    17700550 :     result[i] = line_end->value();
    9219             :   }
    9220             :   return result;
    9221             : }
    9222             : 
    9223       54071 : MaybeLocal<String> debug::Script::Name() const {
    9224             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    9225             :   i::HandleScope handle_scope(isolate);
    9226             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9227             :   i::Handle<i::Object> value(script->name(), isolate);
    9228       54071 :   if (!value->IsString()) return MaybeLocal<String>();
    9229             :   return Utils::ToLocal(
    9230       22962 :       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
    9231             : }
    9232             : 
    9233      112251 : MaybeLocal<String> debug::Script::SourceURL() const {
    9234             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    9235             :   i::HandleScope handle_scope(isolate);
    9236             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9237             :   i::Handle<i::Object> value(script->source_url(), isolate);
    9238      112251 :   if (!value->IsString()) return MaybeLocal<String>();
    9239             :   return Utils::ToLocal(
    9240        4440 :       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
    9241             : }
    9242             : 
    9243       56218 : MaybeLocal<String> debug::Script::SourceMappingURL() const {
    9244             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    9245             :   i::HandleScope handle_scope(isolate);
    9246             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9247             :   i::Handle<i::Object> value(script->source_mapping_url(), isolate);
    9248       56218 :   if (!value->IsString()) return MaybeLocal<String>();
    9249             :   return Utils::ToLocal(
    9250         538 :       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
    9251             : }
    9252             : 
    9253      123397 : Maybe<int> debug::Script::ContextId() const {
    9254             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    9255             :   i::HandleScope handle_scope(isolate);
    9256             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9257             :   i::Object value = script->context_data();
    9258      123397 :   if (value->IsSmi()) return Just(i::Smi::ToInt(value));
    9259             :   return Nothing<int>();
    9260             : }
    9261             : 
    9262      134735 : MaybeLocal<String> debug::Script::Source() const {
    9263             :   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
    9264             :   i::HandleScope handle_scope(isolate);
    9265             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9266             :   i::Handle<i::Object> value(script->source(), isolate);
    9267      134735 :   if (!value->IsString()) return MaybeLocal<String>();
    9268             :   return Utils::ToLocal(
    9269      134735 :       handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
    9270             : }
    9271             : 
    9272       22368 : bool debug::Script::IsWasm() const {
    9273       22368 :   return Utils::OpenHandle(this)->type() == i::Script::TYPE_WASM;
    9274             : }
    9275             : 
    9276       56042 : bool debug::Script::IsModule() const {
    9277       56042 :   return Utils::OpenHandle(this)->origin_options().IsModule();
    9278             : }
    9279             : 
    9280             : namespace {
    9281             : int GetSmiValue(i::Handle<i::FixedArray> array, int index) {
    9282             :   return i::Smi::ToInt(array->get(index));
    9283             : }
    9284             : 
    9285       42030 : bool CompareBreakLocation(const i::BreakLocation& loc1,
    9286             :                           const i::BreakLocation& loc2) {
    9287       42030 :   return loc1.position() < loc2.position();
    9288             : }
    9289             : }  // namespace
    9290             : 
    9291         264 : bool debug::Script::GetPossibleBreakpoints(
    9292             :     const debug::Location& start, const debug::Location& end,
    9293             :     bool restrict_to_function,
    9294             :     std::vector<debug::BreakLocation>* locations) const {
    9295         264 :   CHECK(!start.IsEmpty());
    9296             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9297         288 :   if (script->type() == i::Script::TYPE_WASM &&
    9298          24 :       this->SourceMappingURL().IsEmpty()) {
    9299             :     i::WasmModuleObject module_object =
    9300          24 :         i::WasmModuleObject::cast(script->wasm_module_object());
    9301          24 :     return module_object->GetPossibleBreakpoints(start, end, locations);
    9302             :   }
    9303             : 
    9304         240 :   i::Script::InitLineEnds(script);
    9305         240 :   CHECK(script->line_ends()->IsFixedArray());
    9306             :   i::Isolate* isolate = script->GetIsolate();
    9307             :   i::Handle<i::FixedArray> line_ends =
    9308             :       i::Handle<i::FixedArray>::cast(i::handle(script->line_ends(), isolate));
    9309         240 :   CHECK(line_ends->length());
    9310             : 
    9311         240 :   int start_offset = GetSourceOffset(start);
    9312             :   int end_offset = end.IsEmpty()
    9313         155 :                        ? GetSmiValue(line_ends, line_ends->length() - 1) + 1
    9314         395 :                        : GetSourceOffset(end);
    9315         240 :   if (start_offset >= end_offset) return true;
    9316             : 
    9317             :   std::vector<i::BreakLocation> v8_locations;
    9318         215 :   if (!isolate->debug()->GetPossibleBreakpoints(
    9319             :           script, start_offset, end_offset, restrict_to_function,
    9320             :           &v8_locations)) {
    9321             :     return false;
    9322             :   }
    9323             : 
    9324             :   std::sort(v8_locations.begin(), v8_locations.end(), CompareBreakLocation);
    9325             :   int current_line_end_index = 0;
    9326        5210 :   for (const auto& v8_location : v8_locations) {
    9327             :     int offset = v8_location.position();
    9328        8165 :     while (offset > GetSmiValue(line_ends, current_line_end_index)) {
    9329        3165 :       ++current_line_end_index;
    9330        3165 :       CHECK(current_line_end_index < line_ends->length());
    9331             :     }
    9332             :     int line_offset = 0;
    9333             : 
    9334        5000 :     if (current_line_end_index > 0) {
    9335        9100 :       line_offset = GetSmiValue(line_ends, current_line_end_index - 1) + 1;
    9336             :     }
    9337       20000 :     locations->emplace_back(
    9338        5000 :         current_line_end_index + script->line_offset(),
    9339       10000 :         offset - line_offset +
    9340             :             (current_line_end_index == 0 ? script->column_offset() : 0),
    9341       10000 :         v8_location.type());
    9342             :   }
    9343             :   return true;
    9344             : }
    9345             : 
    9346        2941 : int debug::Script::GetSourceOffset(const debug::Location& location) const {
    9347             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9348        2941 :   if (script->type() == i::Script::TYPE_WASM) {
    9349         168 :     if (this->SourceMappingURL().IsEmpty()) {
    9350         160 :       return i::WasmModuleObject::cast(script->wasm_module_object())
    9351         160 :                  ->GetFunctionOffset(location.GetLineNumber()) +
    9352          80 :              location.GetColumnNumber();
    9353             :     }
    9354             :     DCHECK_EQ(0, location.GetLineNumber());
    9355           4 :     return location.GetColumnNumber();
    9356             :   }
    9357             : 
    9358        8571 :   int line = std::max(location.GetLineNumber() - script->line_offset(), 0);
    9359        2857 :   int column = location.GetColumnNumber();
    9360        2857 :   if (line == 0) {
    9361         788 :     column = std::max(0, column - script->column_offset());
    9362             :   }
    9363             : 
    9364        2857 :   i::Script::InitLineEnds(script);
    9365        2857 :   CHECK(script->line_ends()->IsFixedArray());
    9366             :   i::Handle<i::FixedArray> line_ends = i::Handle<i::FixedArray>::cast(
    9367             :       i::handle(script->line_ends(), script->GetIsolate()));
    9368        2857 :   CHECK(line_ends->length());
    9369        2857 :   if (line >= line_ends->length())
    9370          15 :     return GetSmiValue(line_ends, line_ends->length() - 1);
    9371        2842 :   int line_offset = GetSmiValue(line_ends, line);
    9372        3236 :   if (line == 0) return std::min(column, line_offset);
    9373        2448 :   int prev_line_offset = GetSmiValue(line_ends, line - 1);
    9374        4896 :   return std::min(prev_line_offset + column + 1, line_offset);
    9375             : }
    9376             : 
    9377      461427 : v8::debug::Location debug::Script::GetSourceLocation(int offset) const {
    9378      461427 :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9379             :   i::Script::PositionInfo info;
    9380      461427 :   i::Script::GetPositionInfo(script, offset, &info, i::Script::WITH_OFFSET);
    9381      461427 :   return debug::Location(info.line, info.column);
    9382             : }
    9383             : 
    9384          50 : bool debug::Script::SetScriptSource(v8::Local<v8::String> newSource,
    9385             :                                     bool preview,
    9386             :                                     debug::LiveEditResult* result) const {
    9387             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9388             :   i::Isolate* isolate = script->GetIsolate();
    9389          50 :   return isolate->debug()->SetScriptSource(
    9390          50 :       script, Utils::OpenHandle(*newSource), preview, result);
    9391             : }
    9392             : 
    9393        2156 : bool debug::Script::SetBreakpoint(v8::Local<v8::String> condition,
    9394             :                                   debug::Location* location,
    9395             :                                   debug::BreakpointId* id) const {
    9396             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9397             :   i::Isolate* isolate = script->GetIsolate();
    9398        2156 :   int offset = GetSourceOffset(*location);
    9399        2156 :   if (!isolate->debug()->SetBreakPointForScript(
    9400             :           script, Utils::OpenHandle(*condition), &offset, id)) {
    9401             :     return false;
    9402             :   }
    9403        2126 :   *location = GetSourceLocation(offset);
    9404        2126 :   return true;
    9405             : }
    9406             : 
    9407        2216 : void debug::RemoveBreakpoint(Isolate* v8_isolate, BreakpointId id) {
    9408             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9409             :   i::HandleScope handle_scope(isolate);
    9410        2216 :   isolate->debug()->RemoveBreakpoint(id);
    9411        2216 : }
    9412             : 
    9413          30 : v8::Platform* debug::GetCurrentPlatform() {
    9414          30 :   return i::V8::GetCurrentPlatform();
    9415             : }
    9416             : 
    9417          60 : debug::WasmScript* debug::WasmScript::Cast(debug::Script* script) {
    9418          60 :   CHECK(script->IsWasm());
    9419          60 :   return static_cast<WasmScript*>(script);
    9420             : }
    9421             : 
    9422         152 : int debug::WasmScript::NumFunctions() const {
    9423             :   i::DisallowHeapAllocation no_gc;
    9424             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9425             :   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
    9426             :   i::WasmModuleObject module_object =
    9427             :       i::WasmModuleObject::cast(script->wasm_module_object());
    9428             :   const i::wasm::WasmModule* module = module_object->module();
    9429             :   DCHECK_GE(i::kMaxInt, module->functions.size());
    9430         152 :   return static_cast<int>(module->functions.size());
    9431             : }
    9432             : 
    9433         152 : int debug::WasmScript::NumImportedFunctions() const {
    9434             :   i::DisallowHeapAllocation no_gc;
    9435             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9436             :   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
    9437             :   i::WasmModuleObject module_object =
    9438             :       i::WasmModuleObject::cast(script->wasm_module_object());
    9439             :   const i::wasm::WasmModule* module = module_object->module();
    9440             :   DCHECK_GE(i::kMaxInt, module->num_imported_functions);
    9441         152 :   return static_cast<int>(module->num_imported_functions);
    9442             : }
    9443             : 
    9444           4 : std::pair<int, int> debug::WasmScript::GetFunctionRange(
    9445             :     int function_index) const {
    9446             :   i::DisallowHeapAllocation no_gc;
    9447             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9448             :   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
    9449             :   i::WasmModuleObject module_object =
    9450             :       i::WasmModuleObject::cast(script->wasm_module_object());
    9451             :   const i::wasm::WasmModule* module = module_object->module();
    9452             :   DCHECK_LE(0, function_index);
    9453             :   DCHECK_GT(module->functions.size(), function_index);
    9454           4 :   const i::wasm::WasmFunction& func = module->functions[function_index];
    9455             :   DCHECK_GE(i::kMaxInt, func.code.offset());
    9456             :   DCHECK_GE(i::kMaxInt, func.code.end_offset());
    9457             :   return std::make_pair(static_cast<int>(func.code.offset()),
    9458           4 :                         static_cast<int>(func.code.end_offset()));
    9459             : }
    9460             : 
    9461          92 : uint32_t debug::WasmScript::GetFunctionHash(int function_index) {
    9462             :   i::DisallowHeapAllocation no_gc;
    9463             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9464             :   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
    9465             :   i::WasmModuleObject module_object =
    9466             :       i::WasmModuleObject::cast(script->wasm_module_object());
    9467             :   const i::wasm::WasmModule* module = module_object->module();
    9468             :   DCHECK_LE(0, function_index);
    9469             :   DCHECK_GT(module->functions.size(), function_index);
    9470          92 :   const i::wasm::WasmFunction& func = module->functions[function_index];
    9471             :   i::wasm::ModuleWireBytes wire_bytes(
    9472             :       module_object->native_module()->wire_bytes());
    9473             :   i::Vector<const i::byte> function_bytes = wire_bytes.GetFunctionBytes(&func);
    9474             :   // TODO(herhut): Maybe also take module, name and signature into account.
    9475             :   return i::StringHasher::HashSequentialString(function_bytes.start(),
    9476          92 :                                                function_bytes.length(), 0);
    9477             : }
    9478             : 
    9479          84 : debug::WasmDisassembly debug::WasmScript::DisassembleFunction(
    9480             :     int function_index) const {
    9481             :   i::DisallowHeapAllocation no_gc;
    9482             :   i::Handle<i::Script> script = Utils::OpenHandle(this);
    9483             :   DCHECK_EQ(i::Script::TYPE_WASM, script->type());
    9484             :   i::WasmModuleObject module_object =
    9485          84 :       i::WasmModuleObject::cast(script->wasm_module_object());
    9486          84 :   return module_object->DisassembleFunction(function_index);
    9487             : }
    9488             : 
    9489       28373 : debug::Location::Location(int line_number, int column_number)
    9490             :     : line_number_(line_number),
    9491             :       column_number_(column_number),
    9492       33373 :       is_empty_(false) {}
    9493             : 
    9494         274 : debug::Location::Location()
    9495             :     : line_number_(v8::Function::kLineOffsetNotFound),
    9496             :       column_number_(v8::Function::kLineOffsetNotFound),
    9497         274 :       is_empty_(true) {}
    9498             : 
    9499      476716 : int debug::Location::GetLineNumber() const {
    9500             :   DCHECK(!IsEmpty());
    9501      479653 :   return line_number_;
    9502             : }
    9503             : 
    9504      472815 : int debug::Location::GetColumnNumber() const {
    9505             :   DCHECK(!IsEmpty());
    9506      475756 :   return column_number_;
    9507             : }
    9508             : 
    9509         940 : bool debug::Location::IsEmpty() const { return is_empty_; }
    9510             : 
    9511        3505 : void debug::GetLoadedScripts(v8::Isolate* v8_isolate,
    9512             :                              PersistentValueVector<debug::Script>& scripts) {
    9513             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9514             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9515             :   {
    9516             :     i::DisallowHeapAllocation no_gc;
    9517        3505 :     i::Script::Iterator iterator(isolate);
    9518       96094 :     for (i::Script script = iterator.Next(); !script.is_null();
    9519             :          script = iterator.Next()) {
    9520       44542 :       if (!script->IsUserJavaScript()) continue;
    9521       33912 :       if (script->HasValidSource()) {
    9522             :         i::HandleScope handle_scope(isolate);
    9523             :         i::Handle<i::Script> script_handle(script, isolate);
    9524       33912 :         scripts.Append(ToApiHandle<Script>(script_handle));
    9525             :       }
    9526             :     }
    9527             :   }
    9528        3505 : }
    9529             : 
    9530         306 : MaybeLocal<UnboundScript> debug::CompileInspectorScript(Isolate* v8_isolate,
    9531             :                                                         Local<String> source) {
    9532             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9533         918 :   PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, UnboundScript);
    9534         306 :   i::Handle<i::String> str = Utils::OpenHandle(*source);
    9535             :   i::Handle<i::SharedFunctionInfo> result;
    9536             :   {
    9537             :     ScriptOriginOptions origin_options;
    9538             :     i::ScriptData* script_data = nullptr;
    9539             :     i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
    9540             :         i::Compiler::GetSharedFunctionInfoForScript(
    9541             :             isolate, str, i::Compiler::ScriptDetails(), origin_options, nullptr,
    9542             :             script_data, ScriptCompiler::kNoCompileOptions,
    9543             :             ScriptCompiler::kNoCacheBecauseInspector,
    9544             :             i::FLAG_expose_inspector_scripts ? i::NOT_NATIVES_CODE
    9545         612 :                                              : i::INSPECTOR_CODE);
    9546             :     has_pending_exception = !maybe_function_info.ToHandle(&result);
    9547         306 :     RETURN_ON_FAILED_EXECUTION(UnboundScript);
    9548             :   }
    9549         301 :   RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
    9550             : }
    9551             : 
    9552        7899 : void debug::SetDebugDelegate(Isolate* v8_isolate,
    9553             :                              debug::DebugDelegate* delegate) {
    9554             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9555        7899 :   isolate->debug()->SetDebugDelegate(delegate);
    9556        7899 : }
    9557             : 
    9558         460 : void debug::SetAsyncEventDelegate(Isolate* v8_isolate,
    9559             :                                   debug::AsyncEventDelegate* delegate) {
    9560             :   reinterpret_cast<i::Isolate*>(v8_isolate)->set_async_event_delegate(delegate);
    9561         460 : }
    9562             : 
    9563      112250 : void debug::ResetBlackboxedStateCache(Isolate* v8_isolate,
    9564             :                                       v8::Local<debug::Script> script) {
    9565             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9566             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9567             :   i::DisallowHeapAllocation no_gc;
    9568             :   i::SharedFunctionInfo::ScriptIterator iter(isolate,
    9569      112250 :                                              *Utils::OpenHandle(*script));
    9570     2546972 :   for (i::SharedFunctionInfo info = iter.Next(); !info.is_null();
    9571             :        info = iter.Next()) {
    9572     1161236 :     if (info->HasDebugInfo()) {
    9573       18393 :       info->GetDebugInfo()->set_computed_debug_is_blackboxed(false);
    9574             :     }
    9575             :   }
    9576      112250 : }
    9577             : 
    9578        7055 : int debug::EstimatedValueSize(Isolate* v8_isolate, v8::Local<v8::Value> value) {
    9579             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9580             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9581             :   i::Handle<i::Object> object = Utils::OpenHandle(*value);
    9582        7055 :   if (object->IsSmi()) return i::kTaggedSize;
    9583        6310 :   CHECK(object->IsHeapObject());
    9584        6310 :   return i::Handle<i::HeapObject>::cast(object)->Size();
    9585             : }
    9586             : 
    9587       90233 : v8::MaybeLocal<v8::Array> v8::Object::PreviewEntries(bool* is_key_value) {
    9588       90233 :   if (IsMap()) {
    9589         108 :     *is_key_value = true;
    9590         108 :     return Map::Cast(this)->AsArray();
    9591             :   }
    9592       90125 :   if (IsSet()) {
    9593          89 :     *is_key_value = false;
    9594          89 :     return Set::Cast(this)->AsArray();
    9595             :   }
    9596             : 
    9597             :   i::Handle<i::JSReceiver> object = Utils::OpenHandle(this);
    9598             :   i::Isolate* isolate = object->GetIsolate();
    9599             :   Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
    9600             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9601       90036 :   if (object->IsJSWeakCollection()) {
    9602          98 :     *is_key_value = object->IsJSWeakMap();
    9603             :     return Utils::ToLocal(i::JSWeakCollection::GetEntries(
    9604          98 :         i::Handle<i::JSWeakCollection>::cast(object), 0));
    9605             :   }
    9606       89938 :   if (object->IsJSMapIterator()) {
    9607             :     i::Handle<i::JSMapIterator> it = i::Handle<i::JSMapIterator>::cast(object);
    9608             :     MapAsArrayKind const kind =
    9609         157 :         static_cast<MapAsArrayKind>(it->map()->instance_type());
    9610         157 :     *is_key_value = kind == MapAsArrayKind::kEntries;
    9611         157 :     if (!it->HasMore()) return v8::Array::New(v8_isolate);
    9612             :     return Utils::ToLocal(
    9613         122 :         MapAsArray(isolate, it->table(), i::Smi::ToInt(it->index()), kind));
    9614             :   }
    9615       89781 :   if (object->IsJSSetIterator()) {
    9616             :     i::Handle<i::JSSetIterator> it = i::Handle<i::JSSetIterator>::cast(object);
    9617             :     SetAsArrayKind const kind =
    9618         142 :         static_cast<SetAsArrayKind>(it->map()->instance_type());
    9619         142 :     *is_key_value = kind == SetAsArrayKind::kEntries;
    9620         142 :     if (!it->HasMore()) return v8::Array::New(v8_isolate);
    9621             :     return Utils::ToLocal(
    9622         127 :         SetAsArray(isolate, it->table(), i::Smi::ToInt(it->index()), kind));
    9623             :   }
    9624       89639 :   return v8::MaybeLocal<v8::Array>();
    9625             : }
    9626             : 
    9627           0 : Local<Function> debug::GetBuiltin(Isolate* v8_isolate, Builtin builtin) {
    9628             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9629             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9630             :   i::HandleScope handle_scope(isolate);
    9631             :   i::Builtins::Name builtin_id;
    9632           0 :   switch (builtin) {
    9633             :     case kStringToLowerCase:
    9634             :       builtin_id = i::Builtins::kStringPrototypeToLocaleLowerCase;
    9635             :       break;
    9636             :     default:
    9637           0 :       UNREACHABLE();
    9638             :   }
    9639             : 
    9640           0 :   i::Handle<i::String> name = isolate->factory()->empty_string();
    9641             :   i::NewFunctionArgs args = i::NewFunctionArgs::ForBuiltinWithoutPrototype(
    9642           0 :       name, builtin_id, i::LanguageMode::kStrict);
    9643           0 :   i::Handle<i::JSFunction> fun = isolate->factory()->NewFunction(args);
    9644             : 
    9645             :   fun->shared()->set_internal_formal_parameter_count(0);
    9646             :   fun->shared()->set_length(0);
    9647           0 :   return Utils::ToLocal(handle_scope.CloseAndEscape(fun));
    9648             : }
    9649             : 
    9650       38167 : void debug::SetConsoleDelegate(Isolate* v8_isolate, ConsoleDelegate* delegate) {
    9651             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9652             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9653             :   isolate->set_console_delegate(delegate);
    9654       38167 : }
    9655             : 
    9656         425 : debug::ConsoleCallArguments::ConsoleCallArguments(
    9657             :     const v8::FunctionCallbackInfo<v8::Value>& info)
    9658         425 :     : v8::FunctionCallbackInfo<v8::Value>(nullptr, info.values_, info.length_) {
    9659         425 : }
    9660             : 
    9661       12850 : debug::ConsoleCallArguments::ConsoleCallArguments(
    9662             :     internal::BuiltinArguments& args)
    9663             :     : v8::FunctionCallbackInfo<v8::Value>(
    9664             :           nullptr,
    9665             :           // Drop the first argument (receiver, i.e. the "console" object).
    9666             :           args.address_of_arg_at(args.length() > 1 ? 1 : 0),
    9667       25700 :           args.length() - 1) {}
    9668             : 
    9669        5760 : int debug::GetStackFrameId(v8::Local<v8::StackFrame> frame) {
    9670        5760 :   return Utils::OpenHandle(*frame)->id();
    9671             : }
    9672             : 
    9673          15 : v8::Local<v8::StackTrace> debug::GetDetailedStackTrace(
    9674             :     Isolate* v8_isolate, v8::Local<v8::Object> v8_error) {
    9675             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9676             :   i::Handle<i::JSReceiver> error = Utils::OpenHandle(*v8_error);
    9677          15 :   if (!error->IsJSObject()) {
    9678           0 :     return v8::Local<v8::StackTrace>();
    9679             :   }
    9680             :   i::Handle<i::FixedArray> stack_trace =
    9681          15 :       isolate->GetDetailedStackTrace(i::Handle<i::JSObject>::cast(error));
    9682             :   return Utils::StackTraceToLocal(stack_trace);
    9683             : }
    9684             : 
    9685          40 : MaybeLocal<debug::Script> debug::GeneratorObject::Script() {
    9686             :   i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
    9687          40 :   i::Object maybe_script = obj->function()->shared()->script();
    9688          40 :   if (!maybe_script->IsScript()) return MaybeLocal<debug::Script>();
    9689             :   i::Handle<i::Script> script(i::Script::cast(maybe_script), obj->GetIsolate());
    9690          40 :   return ToApiHandle<debug::Script>(script);
    9691             : }
    9692             : 
    9693          10 : Local<Function> debug::GeneratorObject::Function() {
    9694             :   i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
    9695          10 :   return Utils::ToLocal(handle(obj->function(), obj->GetIsolate()));
    9696             : }
    9697             : 
    9698          40 : debug::Location debug::GeneratorObject::SuspendedLocation() {
    9699             :   i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
    9700          40 :   CHECK(obj->is_suspended());
    9701          40 :   i::Object maybe_script = obj->function()->shared()->script();
    9702          40 :   if (!maybe_script->IsScript()) return debug::Location();
    9703             :   i::Isolate* isolate = obj->GetIsolate();
    9704             :   i::Handle<i::Script> script(i::Script::cast(maybe_script), isolate);
    9705             :   i::Script::PositionInfo info;
    9706             :   i::SharedFunctionInfo::EnsureSourcePositionsAvailable(
    9707          40 :       isolate, i::handle(obj->function()->shared(), isolate));
    9708          80 :   i::Script::GetPositionInfo(script, obj->source_position(), &info,
    9709          40 :                              i::Script::WITH_OFFSET);
    9710          40 :   return debug::Location(info.line, info.column);
    9711             : }
    9712             : 
    9713         100 : bool debug::GeneratorObject::IsSuspended() {
    9714         100 :   return Utils::OpenHandle(this)->is_suspended();
    9715             : }
    9716             : 
    9717         100 : v8::Local<debug::GeneratorObject> debug::GeneratorObject::Cast(
    9718             :     v8::Local<v8::Value> value) {
    9719         100 :   CHECK(value->IsGeneratorObject());
    9720         100 :   return ToApiHandle<debug::GeneratorObject>(Utils::OpenHandle(*value));
    9721             : }
    9722             : 
    9723        9248 : MaybeLocal<v8::Value> debug::EvaluateGlobal(v8::Isolate* isolate,
    9724             :                                             v8::Local<v8::String> source,
    9725             :                                             bool throw_on_side_effect) {
    9726             :   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
    9727       27744 :   PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(internal_isolate, Value);
    9728             :   Local<Value> result;
    9729       18496 :   has_pending_exception = !ToLocal<Value>(
    9730             :       i::DebugEvaluate::Global(internal_isolate, Utils::OpenHandle(*source),
    9731             :                                throw_on_side_effect),
    9732             :       &result);
    9733        9248 :   RETURN_ON_FAILED_EXECUTION(Value);
    9734        8716 :   RETURN_ESCAPED(result);
    9735             : }
    9736             : 
    9737          85 : void debug::QueryObjects(v8::Local<v8::Context> v8_context,
    9738             :                          QueryObjectPredicate* predicate,
    9739             :                          PersistentValueVector<v8::Object>* objects) {
    9740             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_context->GetIsolate());
    9741             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
    9742             :   isolate->heap_profiler()->QueryObjects(Utils::OpenHandle(*v8_context),
    9743          85 :                                          predicate, objects);
    9744          85 : }
    9745             : 
    9746          35 : void debug::GlobalLexicalScopeNames(
    9747             :     v8::Local<v8::Context> v8_context,
    9748             :     v8::PersistentValueVector<v8::String>* names) {
    9749             :   i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
    9750             :   i::Isolate* isolate = context->GetIsolate();
    9751             :   i::Handle<i::ScriptContextTable> table(
    9752         105 :       context->global_object()->native_context()->script_context_table(),
    9753          35 :       isolate);
    9754         305 :   for (int i = 0; i < table->used(); i++) {
    9755             :     i::Handle<i::Context> context =
    9756         135 :         i::ScriptContextTable::GetContext(isolate, table, i);
    9757             :     DCHECK(context->IsScriptContext());
    9758         270 :     i::Handle<i::ScopeInfo> scope_info(context->scope_info(), isolate);
    9759         135 :     int local_count = scope_info->ContextLocalCount();
    9760         435 :     for (int j = 0; j < local_count; ++j) {
    9761         150 :       i::String name = scope_info->ContextLocalName(j);
    9762         185 :       if (i::ScopeInfo::VariableIsSynthetic(name)) continue;
    9763         115 :       names->Append(Utils::ToLocal(handle(name, isolate)));
    9764             :     }
    9765             :   }
    9766          35 : }
    9767             : 
    9768          10 : void debug::SetReturnValue(v8::Isolate* v8_isolate,
    9769             :                            v8::Local<v8::Value> value) {
    9770             :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
    9771             :   isolate->debug()->set_return_value(*Utils::OpenHandle(*value));
    9772          10 : }
    9773             : 
    9774       10311 : int64_t debug::GetNextRandomInt64(v8::Isolate* v8_isolate) {
    9775             :   return reinterpret_cast<i::Isolate*>(v8_isolate)
    9776             :       ->random_number_generator()
    9777       10311 :       ->NextInt64();
    9778             : }
    9779             : 
    9780         170 : int debug::GetDebuggingId(v8::Local<v8::Function> function) {
    9781             :   i::Handle<i::JSReceiver> callable = v8::Utils::OpenHandle(*function);
    9782         170 :   if (!callable->IsJSFunction()) return i::DebugInfo::kNoDebuggingId;
    9783             :   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(callable);
    9784         170 :   int id = func->GetIsolate()->debug()->GetFunctionDebuggingId(func);
    9785             :   DCHECK_NE(i::DebugInfo::kNoDebuggingId, id);
    9786         170 :   return id;
    9787             : }
    9788             : 
    9789          95 : bool debug::SetFunctionBreakpoint(v8::Local<v8::Function> function,
    9790             :                                   v8::Local<v8::String> condition,
    9791             :                                   BreakpointId* id) {
    9792             :   i::Handle<i::JSReceiver> callable = Utils::OpenHandle(*function);
    9793          95 :   if (!callable->IsJSFunction()) return false;
    9794             :   i::Handle<i::JSFunction> jsfunction =
    9795             :       i::Handle<i::JSFunction>::cast(callable);
    9796             :   i::Isolate* isolate = jsfunction->GetIsolate();
    9797             :   i::Handle<i::String> condition_string =
    9798             :       condition.IsEmpty() ? isolate->factory()->empty_string()
    9799         140 :                           : Utils::OpenHandle(*condition);
    9800             :   return isolate->debug()->SetBreakpointForFunction(jsfunction,
    9801          95 :                                                     condition_string, id);
    9802             : }
    9803             : 
    9804           0 : debug::PostponeInterruptsScope::PostponeInterruptsScope(v8::Isolate* isolate)
    9805             :     : scope_(
    9806             :           new i::PostponeInterruptsScope(reinterpret_cast<i::Isolate*>(isolate),
    9807           0 :                                          i::StackGuard::API_INTERRUPT)) {}
    9808             : 
    9809             : debug::PostponeInterruptsScope::~PostponeInterruptsScope() = default;
    9810             : 
    9811        1989 : Local<String> CpuProfileNode::GetFunctionName() const {
    9812             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
    9813             :   i::Isolate* isolate = node->isolate();
    9814             :   const i::CodeEntry* entry = node->entry();
    9815             :   i::Handle<i::String> name =
    9816        1989 :       isolate->factory()->InternalizeUtf8String(entry->name());
    9817        1989 :   return ToApiHandle<String>(name);
    9818             : }
    9819             : 
    9820          32 : int debug::Coverage::BlockData::StartOffset() const { return block_->start; }
    9821          32 : int debug::Coverage::BlockData::EndOffset() const { return block_->end; }
    9822          32 : uint32_t debug::Coverage::BlockData::Count() const { return block_->count; }
    9823             : 
    9824         420 : int debug::Coverage::FunctionData::StartOffset() const {
    9825         420 :   return function_->start;
    9826             : }
    9827         420 : int debug::Coverage::FunctionData::EndOffset() const { return function_->end; }
    9828         410 : uint32_t debug::Coverage::FunctionData::Count() const {
    9829         410 :   return function_->count;
    9830             : }
    9831             : 
    9832         380 : MaybeLocal<String> debug::Coverage::FunctionData::Name() const {
    9833         380 :   return ToApiHandle<String>(function_->name);
    9834             : }
    9835             : 
    9836         412 : size_t debug::Coverage::FunctionData::BlockCount() const {
    9837         824 :   return function_->blocks.size();
    9838             : }
    9839             : 
    9840         380 : bool debug::Coverage::FunctionData::HasBlockCoverage() const {
    9841         380 :   return function_->has_block_coverage;
    9842             : }
    9843             : 
    9844          32 : debug::Coverage::BlockData debug::Coverage::FunctionData::GetBlockData(
    9845             :     size_t i) const {
    9846          64 :   return BlockData(&function_->blocks.at(i), coverage_);
    9847             : }
    9848             : 
    9849         170 : Local<debug::Script> debug::Coverage::ScriptData::GetScript() const {
    9850         170 :   return ToApiHandle<debug::Script>(script_->script);
    9851             : }
    9852             : 
    9853         555 : size_t debug::Coverage::ScriptData::FunctionCount() const {
    9854        1110 :   return script_->functions.size();
    9855             : }
    9856             : 
    9857         405 : debug::Coverage::FunctionData debug::Coverage::ScriptData::GetFunctionData(
    9858             :     size_t i) const {
    9859         810 :   return FunctionData(&script_->functions.at(i), coverage_);
    9860             : }
    9861             : 
    9862         175 : debug::Coverage::ScriptData::ScriptData(size_t index,
    9863             :                                         std::shared_ptr<i::Coverage> coverage)
    9864         350 :     : script_(&coverage->at(index)), coverage_(std::move(coverage)) {}
    9865             : 
    9866         622 : size_t debug::Coverage::ScriptCount() const { return coverage_->size(); }
    9867             : 
    9868         175 : debug::Coverage::ScriptData debug::Coverage::GetScriptData(size_t i) const {
    9869         350 :   return ScriptData(i, coverage_);
    9870             : }
    9871             : 
    9872         103 : debug::Coverage debug::Coverage::CollectPrecise(Isolate* isolate) {
    9873             :   return Coverage(
    9874         206 :       i::Coverage::CollectPrecise(reinterpret_cast<i::Isolate*>(isolate)));
    9875             : }
    9876             : 
    9877          48 : debug::Coverage debug::Coverage::CollectBestEffort(Isolate* isolate) {
    9878             :   return Coverage(
    9879          96 :       i::Coverage::CollectBestEffort(reinterpret_cast<i::Isolate*>(isolate)));
    9880             : }
    9881             : 
    9882         309 : void debug::Coverage::SelectMode(Isolate* isolate, debug::CoverageMode mode) {
    9883         309 :   i::Coverage::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
    9884         309 : }
    9885             : 
    9886         148 : int debug::TypeProfile::Entry::SourcePosition() const {
    9887         148 :   return entry_->position;
    9888             : }
    9889             : 
    9890         148 : std::vector<MaybeLocal<String>> debug::TypeProfile::Entry::Types() const {
    9891             :   std::vector<MaybeLocal<String>> result;
    9892         148 :   for (const internal::Handle<internal::String>& type : entry_->types) {
    9893         196 :     result.emplace_back(ToApiHandle<String>(type));
    9894             :   }
    9895         148 :   return result;
    9896             : }
    9897             : 
    9898          32 : debug::TypeProfile::ScriptData::ScriptData(
    9899             :     size_t index, std::shared_ptr<i::TypeProfile> type_profile)
    9900             :     : script_(&type_profile->at(index)),
    9901          64 :       type_profile_(std::move(type_profile)) {}
    9902             : 
    9903          32 : Local<debug::Script> debug::TypeProfile::ScriptData::GetScript() const {
    9904          32 :   return ToApiHandle<debug::Script>(script_->script);
    9905             : }
    9906             : 
    9907          32 : std::vector<debug::TypeProfile::Entry> debug::TypeProfile::ScriptData::Entries()
    9908             :     const {
    9909             :   std::vector<debug::TypeProfile::Entry> result;
    9910         212 :   for (const internal::TypeProfileEntry& entry : script_->entries) {
    9911         296 :     result.push_back(debug::TypeProfile::Entry(&entry, type_profile_));
    9912             :   }
    9913          32 :   return result;
    9914             : }
    9915             : 
    9916          40 : debug::TypeProfile debug::TypeProfile::Collect(Isolate* isolate) {
    9917             :   return TypeProfile(
    9918          80 :       i::TypeProfile::Collect(reinterpret_cast<i::Isolate*>(isolate)));
    9919             : }
    9920             : 
    9921         100 : void debug::TypeProfile::SelectMode(Isolate* isolate,
    9922             :                                     debug::TypeProfileMode mode) {
    9923         100 :   i::TypeProfile::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
    9924         100 : }
    9925             : 
    9926         144 : size_t debug::TypeProfile::ScriptCount() const { return type_profile_->size(); }
    9927             : 
    9928          32 : debug::TypeProfile::ScriptData debug::TypeProfile::GetScriptData(
    9929             :     size_t i) const {
    9930          64 :   return ScriptData(i, type_profile_);
    9931             : }
    9932             : 
    9933        2431 : v8::MaybeLocal<v8::Value> debug::WeakMap::Get(v8::Local<v8::Context> context,
    9934             :                                               v8::Local<v8::Value> key) {
    9935        9724 :   PREPARE_FOR_EXECUTION(context, WeakMap, Get, Value);
    9936             :   auto self = Utils::OpenHandle(this);
    9937             :   Local<Value> result;
    9938        2431 :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
    9939             :   has_pending_exception =
    9940        7293 :       !ToLocal<Value>(i::Execution::Call(isolate, isolate->weakmap_get(), self,
    9941             :                                          arraysize(argv), argv),
    9942             :                       &result);
    9943        2431 :   RETURN_ON_FAILED_EXECUTION(Value);
    9944        2431 :   RETURN_ESCAPED(result);
    9945             : }
    9946             : 
    9947       10832 : v8::MaybeLocal<debug::WeakMap> debug::WeakMap::Set(
    9948             :     v8::Local<v8::Context> context, v8::Local<v8::Value> key,
    9949             :     v8::Local<v8::Value> value) {
    9950       43328 :   PREPARE_FOR_EXECUTION(context, WeakMap, Set, WeakMap);
    9951             :   auto self = Utils::OpenHandle(this);
    9952             :   i::Handle<i::Object> result;
    9953             :   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
    9954       21664 :                                  Utils::OpenHandle(*value)};
    9955       21664 :   has_pending_exception = !i::Execution::Call(isolate, isolate->weakmap_set(),
    9956       21664 :                                               self, arraysize(argv), argv)
    9957             :                                .ToHandle(&result);
    9958       10832 :   RETURN_ON_FAILED_EXECUTION(WeakMap);
    9959       10832 :   RETURN_ESCAPED(Local<WeakMap>::Cast(Utils::ToLocal(result)));
    9960             : }
    9961             : 
    9962          64 : Local<debug::WeakMap> debug::WeakMap::New(v8::Isolate* isolate) {
    9963             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    9964          64 :   LOG_API(i_isolate, WeakMap, New);
    9965             :   ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
    9966          64 :   i::Handle<i::JSWeakMap> obj = i_isolate->factory()->NewJSWeakMap();
    9967          64 :   return ToApiHandle<debug::WeakMap>(obj);
    9968             : }
    9969             : 
    9970             : debug::WeakMap* debug::WeakMap::Cast(v8::Value* value) {
    9971             :   return static_cast<debug::WeakMap*>(value);
    9972             : }
    9973             : 
    9974         270 : const char* CpuProfileNode::GetFunctionNameStr() const {
    9975             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
    9976         270 :   return node->entry()->name();
    9977             : }
    9978             : 
    9979         430 : int CpuProfileNode::GetScriptId() const {
    9980             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
    9981             :   const i::CodeEntry* entry = node->entry();
    9982         430 :   return entry->script_id();
    9983             : }
    9984             : 
    9985         420 : 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         420 :       node->entry()->resource_name()));
    9990             : }
    9991             : 
    9992          28 : const char* CpuProfileNode::GetScriptResourceNameStr() const {
    9993             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
    9994          28 :   return node->entry()->resource_name();
    9995             : }
    9996             : 
    9997           0 : bool CpuProfileNode::IsScriptSharedCrossOrigin() const {
    9998             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
    9999           0 :   return node->entry()->is_shared_cross_origin();
   10000             : }
   10001             : 
   10002         615 : int CpuProfileNode::GetLineNumber() const {
   10003         615 :   return reinterpret_cast<const i::ProfileNode*>(this)->line_number();
   10004             : }
   10005             : 
   10006             : 
   10007         420 : int CpuProfileNode::GetColumnNumber() const {
   10008             :   return reinterpret_cast<const i::ProfileNode*>(this)->
   10009         420 :       entry()->column_number();
   10010             : }
   10011             : 
   10012             : 
   10013         392 : unsigned int CpuProfileNode::GetHitLineCount() const {
   10014             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10015         392 :   return node->GetHitLineCount();
   10016             : }
   10017             : 
   10018             : 
   10019          19 : bool CpuProfileNode::GetLineTicks(LineTick* entries,
   10020             :                                   unsigned int length) const {
   10021             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10022          19 :   return node->GetLineTicks(entries, length);
   10023             : }
   10024             : 
   10025             : 
   10026         397 : const char* CpuProfileNode::GetBailoutReason() const {
   10027             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10028         397 :   return node->entry()->bailout_reason();
   10029             : }
   10030             : 
   10031             : 
   10032         402 : unsigned CpuProfileNode::GetHitCount() const {
   10033         402 :   return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
   10034             : }
   10035             : 
   10036             : 
   10037           0 : unsigned CpuProfileNode::GetCallUid() const {
   10038           0 :   return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
   10039             : }
   10040             : 
   10041             : 
   10042         852 : unsigned CpuProfileNode::GetNodeId() const {
   10043         852 :   return reinterpret_cast<const i::ProfileNode*>(this)->id();
   10044             : }
   10045             : 
   10046          28 : CpuProfileNode::SourceType CpuProfileNode::GetSourceType() const {
   10047          28 :   return reinterpret_cast<const i::ProfileNode*>(this)->source_type();
   10048             : }
   10049             : 
   10050        2450 : int CpuProfileNode::GetChildrenCount() const {
   10051             :   return static_cast<int>(
   10052        2450 :       reinterpret_cast<const i::ProfileNode*>(this)->children()->size());
   10053             : }
   10054             : 
   10055             : 
   10056        2315 : const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
   10057             :   const i::ProfileNode* child =
   10058        4630 :       reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
   10059        2315 :   return reinterpret_cast<const CpuProfileNode*>(child);
   10060             : }
   10061             : 
   10062          36 : const CpuProfileNode* CpuProfileNode::GetParent() const {
   10063             :   const i::ProfileNode* parent =
   10064             :       reinterpret_cast<const i::ProfileNode*>(this)->parent();
   10065          36 :   return reinterpret_cast<const CpuProfileNode*>(parent);
   10066             : }
   10067             : 
   10068           0 : const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
   10069             :   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
   10070           0 :   return node->deopt_infos();
   10071             : }
   10072             : 
   10073             : 
   10074         754 : void CpuProfile::Delete() {
   10075             :   i::CpuProfile* profile = reinterpret_cast<i::CpuProfile*>(this);
   10076             :   i::CpuProfiler* profiler = profile->cpu_profiler();
   10077             :   DCHECK_NOT_NULL(profiler);
   10078         754 :   profiler->DeleteProfile(profile);
   10079         754 : }
   10080             : 
   10081             : 
   10082           0 : Local<String> CpuProfile::GetTitle() const {
   10083             :   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10084             :   i::Isolate* isolate = profile->top_down()->isolate();
   10085             :   return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
   10086           0 :       profile->title()));
   10087             : }
   10088             : 
   10089             : 
   10090         237 : const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
   10091             :   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10092         237 :   return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
   10093             : }
   10094             : 
   10095             : 
   10096        8491 : const CpuProfileNode* CpuProfile::GetSample(int index) const {
   10097             :   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10098        8491 :   return reinterpret_cast<const CpuProfileNode*>(profile->sample(index).node);
   10099             : }
   10100             : 
   10101             : 
   10102        8491 : int64_t CpuProfile::GetSampleTimestamp(int index) const {
   10103             :   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10104       16982 :   return (profile->sample(index).timestamp - base::TimeTicks())
   10105       16982 :       .InMicroseconds();
   10106             : }
   10107             : 
   10108             : 
   10109         290 : int64_t CpuProfile::GetStartTime() const {
   10110             :   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10111         290 :   return (profile->start_time() - base::TimeTicks()).InMicroseconds();
   10112             : }
   10113             : 
   10114             : 
   10115         150 : int64_t CpuProfile::GetEndTime() const {
   10116             :   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
   10117         150 :   return (profile->end_time() - base::TimeTicks()).InMicroseconds();
   10118             : }
   10119             : 
   10120             : 
   10121        8578 : int CpuProfile::GetSamplesCount() const {
   10122        8578 :   return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
   10123             : }
   10124             : 
   10125         198 : CpuProfiler* CpuProfiler::New(Isolate* isolate) {
   10126             :   return reinterpret_cast<CpuProfiler*>(
   10127         198 :       new i::CpuProfiler(reinterpret_cast<i::Isolate*>(isolate)));
   10128             : }
   10129             : 
   10130         198 : void CpuProfiler::Dispose() { delete reinterpret_cast<i::CpuProfiler*>(this); }
   10131             : 
   10132             : // static
   10133          10 : void CpuProfiler::CollectSample(Isolate* isolate) {
   10134          10 :   i::CpuProfiler::CollectSample(reinterpret_cast<i::Isolate*>(isolate));
   10135          10 : }
   10136             : 
   10137         560 : void CpuProfiler::SetSamplingInterval(int us) {
   10138             :   DCHECK_GE(us, 0);
   10139         560 :   return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
   10140         560 :       base::TimeDelta::FromMicroseconds(us));
   10141             : }
   10142             : 
   10143           5 : void CpuProfiler::SetUsePreciseSampling(bool use_precise_sampling) {
   10144           5 :   reinterpret_cast<i::CpuProfiler*>(this)->set_use_precise_sampling(
   10145           5 :       use_precise_sampling);
   10146           5 : }
   10147             : 
   10148           0 : void CpuProfiler::CollectSample() {
   10149           0 :   reinterpret_cast<i::CpuProfiler*>(this)->CollectSample();
   10150           0 : }
   10151             : 
   10152         278 : void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
   10153         278 :   reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
   10154         278 :       *Utils::OpenHandle(*title), record_samples, kLeafNodeLineNumbers);
   10155         278 : }
   10156             : 
   10157         565 : void CpuProfiler::StartProfiling(Local<String> title, CpuProfilingMode mode,
   10158             :                                  bool record_samples) {
   10159         565 :   reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
   10160         565 :       *Utils::OpenHandle(*title), record_samples, mode);
   10161         565 : }
   10162             : 
   10163         808 : CpuProfile* CpuProfiler::StopProfiling(Local<String> title) {
   10164             :   return reinterpret_cast<CpuProfile*>(
   10165             :       reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
   10166         808 :           *Utils::OpenHandle(*title)));
   10167             : }
   10168             : 
   10169             : 
   10170           0 : void CpuProfiler::SetIdle(bool is_idle) {
   10171             :   i::CpuProfiler* profiler = reinterpret_cast<i::CpuProfiler*>(this);
   10172             :   i::Isolate* isolate = profiler->isolate();
   10173           0 :   isolate->SetIdle(is_idle);
   10174           0 : }
   10175             : 
   10176          10 : void CpuProfiler::UseDetailedSourcePositionsForProfiling(Isolate* isolate) {
   10177             :   reinterpret_cast<i::Isolate*>(isolate)
   10178             :       ->set_detailed_source_positions_for_profiling(true);
   10179          10 : }
   10180             : 
   10181           0 : uintptr_t CodeEvent::GetCodeStartAddress() {
   10182           0 :   return reinterpret_cast<i::CodeEvent*>(this)->code_start_address;
   10183             : }
   10184             : 
   10185           0 : size_t CodeEvent::GetCodeSize() {
   10186           0 :   return reinterpret_cast<i::CodeEvent*>(this)->code_size;
   10187             : }
   10188             : 
   10189         111 : Local<String> CodeEvent::GetFunctionName() {
   10190             :   return ToApiHandle<String>(
   10191         111 :       reinterpret_cast<i::CodeEvent*>(this)->function_name);
   10192             : }
   10193             : 
   10194           0 : Local<String> CodeEvent::GetScriptName() {
   10195             :   return ToApiHandle<String>(
   10196           0 :       reinterpret_cast<i::CodeEvent*>(this)->script_name);
   10197             : }
   10198             : 
   10199           0 : int CodeEvent::GetScriptLine() {
   10200           0 :   return reinterpret_cast<i::CodeEvent*>(this)->script_line;
   10201             : }
   10202             : 
   10203           0 : int CodeEvent::GetScriptColumn() {
   10204           0 :   return reinterpret_cast<i::CodeEvent*>(this)->script_column;
   10205             : }
   10206             : 
   10207       20029 : CodeEventType CodeEvent::GetCodeType() {
   10208       20029 :   return reinterpret_cast<i::CodeEvent*>(this)->code_type;
   10209             : }
   10210             : 
   10211       20029 : const char* CodeEvent::GetComment() {
   10212       20029 :   return reinterpret_cast<i::CodeEvent*>(this)->comment;
   10213             : }
   10214             : 
   10215       20029 : const char* CodeEvent::GetCodeEventTypeName(CodeEventType code_event_type) {
   10216       20029 :   switch (code_event_type) {
   10217             :     case kUnknownType:
   10218             :       return "Unknown";
   10219             : #define V(Name)       \
   10220             :   case k##Name##Type: \
   10221             :     return #Name;
   10222       19912 :       CODE_EVENTS_LIST(V)
   10223             : #undef V
   10224             :   }
   10225             :   // The execution should never pass here
   10226           0 :   UNREACHABLE();
   10227             :   // NOTE(mmarchini): Workaround to fix a compiler failure on GCC 4.9
   10228             :   return "Unknown";
   10229             : }
   10230             : 
   10231          19 : CodeEventHandler::CodeEventHandler(Isolate* isolate) {
   10232             :   internal_listener_ =
   10233          19 :       new i::ExternalCodeEventListener(reinterpret_cast<i::Isolate*>(isolate));
   10234          19 : }
   10235             : 
   10236          38 : CodeEventHandler::~CodeEventHandler() {
   10237          19 :   delete reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_);
   10238          19 : }
   10239             : 
   10240          19 : void CodeEventHandler::Enable() {
   10241          19 :   reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_)
   10242          19 :       ->StartListening(this);
   10243          19 : }
   10244             : 
   10245           0 : void CodeEventHandler::Disable() {
   10246           0 :   reinterpret_cast<i::ExternalCodeEventListener*>(internal_listener_)
   10247           0 :       ->StopListening();
   10248           0 : }
   10249             : 
   10250             : static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
   10251             :   return const_cast<i::HeapGraphEdge*>(
   10252             :       reinterpret_cast<const i::HeapGraphEdge*>(edge));
   10253             : }
   10254             : 
   10255             : 
   10256     6053370 : HeapGraphEdge::Type HeapGraphEdge::GetType() const {
   10257     6053370 :   return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
   10258             : }
   10259             : 
   10260             : 
   10261     6004336 : Local<Value> HeapGraphEdge::GetName() const {
   10262             :   i::HeapGraphEdge* edge = ToInternal(this);
   10263             :   i::Isolate* isolate = edge->isolate();
   10264             :   switch (edge->type()) {
   10265             :     case i::HeapGraphEdge::kContextVariable:
   10266             :     case i::HeapGraphEdge::kInternal:
   10267             :     case i::HeapGraphEdge::kProperty:
   10268             :     case i::HeapGraphEdge::kShortcut:
   10269             :     case i::HeapGraphEdge::kWeak:
   10270             :       return ToApiHandle<String>(
   10271     6004090 :           isolate->factory()->InternalizeUtf8String(edge->name()));
   10272             :     case i::HeapGraphEdge::kElement:
   10273             :     case i::HeapGraphEdge::kHidden:
   10274             :       return ToApiHandle<Number>(
   10275         246 :           isolate->factory()->NewNumberFromInt(edge->index()));
   10276           0 :     default: UNREACHABLE();
   10277             :   }
   10278             :   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
   10279             : }
   10280             : 
   10281             : 
   10282         339 : const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
   10283             :   const i::HeapEntry* from = ToInternal(this)->from();
   10284         339 :   return reinterpret_cast<const HeapGraphNode*>(from);
   10285             : }
   10286             : 
   10287             : 
   10288      658131 : const HeapGraphNode* HeapGraphEdge::GetToNode() const {
   10289             :   const i::HeapEntry* to = ToInternal(this)->to();
   10290      658131 :   return reinterpret_cast<const HeapGraphNode*>(to);
   10291             : }
   10292             : 
   10293             : 
   10294             : static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
   10295             :   return const_cast<i::HeapEntry*>(
   10296             :       reinterpret_cast<const i::HeapEntry*>(entry));
   10297             : }
   10298             : 
   10299             : 
   10300         370 : HeapGraphNode::Type HeapGraphNode::GetType() const {
   10301         370 :   return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
   10302             : }
   10303             : 
   10304             : 
   10305        1125 : Local<String> HeapGraphNode::GetName() const {
   10306             :   i::Isolate* isolate = ToInternal(this)->isolate();
   10307             :   return ToApiHandle<String>(
   10308        1125 :       isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
   10309             : }
   10310             : 
   10311             : 
   10312      553451 : SnapshotObjectId HeapGraphNode::GetId() const {
   10313      553451 :   return ToInternal(this)->id();
   10314             : }
   10315             : 
   10316             : 
   10317          20 : size_t HeapGraphNode::GetShallowSize() const {
   10318          20 :   return ToInternal(this)->self_size();
   10319             : }
   10320             : 
   10321             : 
   10322       60982 : int HeapGraphNode::GetChildrenCount() const {
   10323       60982 :   return ToInternal(this)->children_count();
   10324             : }
   10325             : 
   10326             : 
   10327     6339269 : const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
   10328     6339269 :   return reinterpret_cast<const HeapGraphEdge*>(ToInternal(this)->child(index));
   10329             : }
   10330             : 
   10331             : 
   10332             : static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
   10333             :   return const_cast<i::HeapSnapshot*>(
   10334             :       reinterpret_cast<const i::HeapSnapshot*>(snapshot));
   10335             : }
   10336             : 
   10337             : 
   10338          40 : void HeapSnapshot::Delete() {
   10339          40 :   i::Isolate* isolate = ToInternal(this)->profiler()->isolate();
   10340          40 :   if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
   10341           5 :     ToInternal(this)->Delete();
   10342             :   } else {
   10343             :     // If this is the last snapshot, clean up all accessory data as well.
   10344          35 :     isolate->heap_profiler()->DeleteAllSnapshots();
   10345             :   }
   10346          40 : }
   10347             : 
   10348             : 
   10349         299 : const HeapGraphNode* HeapSnapshot::GetRoot() const {
   10350         299 :   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
   10351             : }
   10352             : 
   10353             : 
   10354      183299 : const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
   10355             :   return reinterpret_cast<const HeapGraphNode*>(
   10356      183299 :       ToInternal(this)->GetEntryById(id));
   10357             : }
   10358             : 
   10359             : 
   10360          10 : int HeapSnapshot::GetNodesCount() const {
   10361          10 :   return static_cast<int>(ToInternal(this)->entries().size());
   10362             : }
   10363             : 
   10364             : 
   10365       67472 : const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
   10366             :   return reinterpret_cast<const HeapGraphNode*>(
   10367      134944 :       &ToInternal(this)->entries().at(index));
   10368             : }
   10369             : 
   10370             : 
   10371          20 : SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
   10372          20 :   return ToInternal(this)->max_snapshot_js_object_id();
   10373             : }
   10374             : 
   10375             : 
   10376          35 : void HeapSnapshot::Serialize(OutputStream* stream,
   10377             :                              HeapSnapshot::SerializationFormat format) const {
   10378             :   Utils::ApiCheck(format == kJSON,
   10379             :                   "v8::HeapSnapshot::Serialize",
   10380             :                   "Unknown serialization format");
   10381          35 :   Utils::ApiCheck(stream->GetChunkSize() > 0,
   10382             :                   "v8::HeapSnapshot::Serialize",
   10383             :                   "Invalid stream chunk size");
   10384             :   i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
   10385          35 :   serializer.Serialize(stream);
   10386          35 : }
   10387             : 
   10388             : 
   10389             : // static
   10390             : STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
   10391             :     HeapProfiler::kUnknownObjectId;
   10392             : 
   10393             : 
   10394         115 : int HeapProfiler::GetSnapshotCount() {
   10395         115 :   return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
   10396             : }
   10397             : 
   10398             : 
   10399          30 : const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
   10400             :   return reinterpret_cast<const HeapSnapshot*>(
   10401          30 :       reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
   10402             : }
   10403             : 
   10404             : 
   10405         155 : SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) {
   10406         155 :   i::Handle<i::Object> obj = Utils::OpenHandle(*value);
   10407         155 :   return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
   10408             : }
   10409             : 
   10410             : 
   10411         140 : Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
   10412             :   i::Handle<i::Object> obj =
   10413         140 :       reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
   10414         140 :   if (obj.is_null()) return Local<Value>();
   10415             :   return Utils::ToLocal(obj);
   10416             : }
   10417             : 
   10418             : 
   10419        3884 : void HeapProfiler::ClearObjectIds() {
   10420        3884 :   reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
   10421        3884 : }
   10422             : 
   10423             : 
   10424         398 : const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
   10425             :     ActivityControl* control, ObjectNameResolver* resolver) {
   10426             :   return reinterpret_cast<const HeapSnapshot*>(
   10427             :       reinterpret_cast<i::HeapProfiler*>(this)
   10428         398 :           ->TakeSnapshot(control, resolver));
   10429             : }
   10430             : 
   10431             : 
   10432          45 : void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
   10433          45 :   reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
   10434          45 :       track_allocations);
   10435          45 : }
   10436             : 
   10437             : 
   10438        3924 : void HeapProfiler::StopTrackingHeapObjects() {
   10439        3924 :   reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
   10440        3924 : }
   10441             : 
   10442             : 
   10443          55 : SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream,
   10444             :                                             int64_t* timestamp_us) {
   10445             :   i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
   10446          55 :   return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
   10447             : }
   10448             : 
   10449          59 : bool HeapProfiler::StartSamplingHeapProfiler(uint64_t sample_interval,
   10450             :                                              int stack_depth,
   10451             :                                              SamplingFlags flags) {
   10452             :   return reinterpret_cast<i::HeapProfiler*>(this)->StartSamplingHeapProfiler(
   10453          59 :       sample_interval, stack_depth, flags);
   10454             : }
   10455             : 
   10456             : 
   10457          59 : void HeapProfiler::StopSamplingHeapProfiler() {
   10458          59 :   reinterpret_cast<i::HeapProfiler*>(this)->StopSamplingHeapProfiler();
   10459          59 : }
   10460             : 
   10461             : 
   10462          77 : AllocationProfile* HeapProfiler::GetAllocationProfile() {
   10463          77 :   return reinterpret_cast<i::HeapProfiler*>(this)->GetAllocationProfile();
   10464             : }
   10465             : 
   10466          35 : void HeapProfiler::DeleteAllHeapSnapshots() {
   10467          35 :   reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
   10468          35 : }
   10469             : 
   10470          35 : void HeapProfiler::AddBuildEmbedderGraphCallback(
   10471             :     BuildEmbedderGraphCallback callback, void* data) {
   10472             :   reinterpret_cast<i::HeapProfiler*>(this)->AddBuildEmbedderGraphCallback(
   10473          35 :       callback, data);
   10474          35 : }
   10475             : 
   10476           5 : void HeapProfiler::RemoveBuildEmbedderGraphCallback(
   10477             :     BuildEmbedderGraphCallback callback, void* data) {
   10478             :   reinterpret_cast<i::HeapProfiler*>(this)->RemoveBuildEmbedderGraphCallback(
   10479           5 :       callback, data);
   10480           5 : }
   10481             : 
   10482             : v8::Testing::StressType internal::Testing::stress_type_ =
   10483             :     v8::Testing::kStressTypeOpt;
   10484             : 
   10485             : 
   10486        5655 : void Testing::SetStressRunType(Testing::StressType type) {
   10487             :   internal::Testing::set_stress_type(type);
   10488        5655 : }
   10489             : 
   10490             : 
   10491        5655 : int Testing::GetStressRuns() {
   10492       54869 :   if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
   10493             : #ifdef DEBUG
   10494             :   // In debug mode the code runs much slower so stressing will only make two
   10495             :   // runs.
   10496             :   return 2;
   10497             : #else
   10498             :   return 5;
   10499             : #endif
   10500             : }
   10501             : 
   10502             : 
   10503       21900 : static void SetFlagsFromString(const char* flags) {
   10504             :   V8::SetFlagsFromString(flags, i::StrLength(flags));
   10505       21900 : }
   10506             : 
   10507             : 
   10508       27315 : void Testing::PrepareStressRun(int run) {
   10509             :   static const char* kLazyOptimizations =
   10510             :       "--prepare-always-opt "
   10511             :       "--max-inlined-bytecode-size=999999 "
   10512             :       "--max-inlined-bytecode-size-cumulative=999999 "
   10513             :       "--noalways-opt";
   10514             :   static const char* kForcedOptimizations = "--always-opt";
   10515             : 
   10516             :   // If deoptimization stressed turn on frequent deoptimization. If no value
   10517             :   // is spefified through --deopt-every-n-times use a default default value.
   10518             :   static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
   10519       27315 :   if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
   10520           0 :       internal::FLAG_deopt_every_n_times == 0) {
   10521           0 :     SetFlagsFromString(kDeoptEvery13Times);
   10522             :   }
   10523             : 
   10524             : #ifdef DEBUG
   10525             :   // As stressing in debug mode only make two runs skip the deopt stressing
   10526             :   // here.
   10527             :   if (run == GetStressRuns() - 1) {
   10528             :     SetFlagsFromString(kForcedOptimizations);
   10529             :   } else {
   10530             :     SetFlagsFromString(kLazyOptimizations);
   10531             :   }
   10532             : #else
   10533       27315 :   if (run == GetStressRuns() - 1) {
   10534        5416 :     SetFlagsFromString(kForcedOptimizations);
   10535       21899 :   } else if (run != GetStressRuns() - 2) {
   10536       16484 :     SetFlagsFromString(kLazyOptimizations);
   10537             :   }
   10538             : #endif
   10539       27315 : }
   10540             : 
   10541             : 
   10542        5655 : void Testing::DeoptimizeAll(Isolate* isolate) {
   10543             :   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
   10544             :   i::HandleScope scope(i_isolate);
   10545        5655 :   i::Deoptimizer::DeoptimizeAll(i_isolate);
   10546        5655 : }
   10547             : 
   10548          10 : void EmbedderHeapTracer::FinalizeTracing() {
   10549          10 :   if (isolate_) {
   10550             :     i::Isolate* isolate = reinterpret_cast<i::Isolate*>(isolate_);
   10551          10 :     if (isolate->heap()->incremental_marking()->IsMarking()) {
   10552             :       isolate->heap()->FinalizeIncrementalMarkingAtomically(
   10553           5 :           i::GarbageCollectionReason::kExternalFinalize);
   10554             :     }
   10555             :   }
   10556          10 : }
   10557             : 
   10558           5 : void EmbedderHeapTracer::GarbageCollectionForTesting(
   10559             :     EmbedderStackState stack_state) {
   10560           5 :   CHECK(isolate_);
   10561           5 :   CHECK(i::FLAG_expose_gc);
   10562             :   i::Heap* const heap = reinterpret_cast<i::Isolate*>(isolate_)->heap();
   10563           5 :   heap->SetEmbedderStackStateForNextFinalizaton(stack_state);
   10564             :   heap->PreciseCollectAllGarbage(i::Heap::kNoGCFlags,
   10565             :                                  i::GarbageCollectionReason::kTesting,
   10566           5 :                                  kGCCallbackFlagForced);
   10567           5 : }
   10568             : 
   10569           5 : void EmbedderHeapTracer::RegisterEmbedderReference(
   10570             :     const TracedGlobal<v8::Value>& ref) {
   10571           5 :   if (ref.IsEmpty()) return;
   10572             : 
   10573           5 :   i::Heap* const heap = reinterpret_cast<i::Isolate*>(isolate_)->heap();
   10574             :   heap->RegisterExternallyReferencedObject(
   10575           5 :       reinterpret_cast<i::Address*>(ref.val_));
   10576             : }
   10577             : 
   10578           5 : void EmbedderHeapTracer::IterateTracedGlobalHandles(
   10579             :     TracedGlobalHandleVisitor* visitor) {
   10580           5 :   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(isolate_);
   10581             :   i::DisallowHeapAllocation no_allocation;
   10582           5 :   isolate->global_handles()->IterateTracedNodes(visitor);
   10583           5 : }
   10584             : 
   10585             : namespace internal {
   10586             : 
   10587             : const size_t HandleScopeImplementer::kEnteredContextsOffset =
   10588             :     offsetof(HandleScopeImplementer, entered_contexts_);
   10589             : const size_t HandleScopeImplementer::kIsMicrotaskContextOffset =
   10590             :     offsetof(HandleScopeImplementer, is_microtask_context_);
   10591             : 
   10592        5918 : void HandleScopeImplementer::FreeThreadResources() {
   10593        5918 :   Free();
   10594        5918 : }
   10595             : 
   10596             : 
   10597       32430 : char* HandleScopeImplementer::ArchiveThread(char* storage) {
   10598       32430 :   HandleScopeData* current = isolate_->handle_scope_data();
   10599       32430 :   handle_scope_data_ = *current;
   10600             :   MemCopy(storage, this, sizeof(*this));
   10601             : 
   10602             :   ResetAfterArchive();
   10603             :   current->Initialize();
   10604             : 
   10605       32430 :   return storage + ArchiveSpacePerThread();
   10606             : }
   10607             : 
   10608             : 
   10609        1321 : int HandleScopeImplementer::ArchiveSpacePerThread() {
   10610        1321 :   return sizeof(HandleScopeImplementer);
   10611             : }
   10612             : 
   10613             : 
   10614       32430 : char* HandleScopeImplementer::RestoreThread(char* storage) {
   10615             :   MemCopy(this, storage, sizeof(*this));
   10616       32430 :   *isolate_->handle_scope_data() = handle_scope_data_;
   10617       32430 :   return storage + ArchiveSpacePerThread();
   10618             : }
   10619             : 
   10620      562696 : void HandleScopeImplementer::IterateThis(RootVisitor* v) {
   10621             : #ifdef DEBUG
   10622             :   bool found_block_before_deferred = false;
   10623             : #endif
   10624             :   // Iterate over all handles in the blocks except for the last.
   10625      691823 :   for (int i = static_cast<int>(blocks()->size()) - 2; i >= 0; --i) {
   10626      258254 :     Address* block = blocks()->at(i);
   10627             :     // Cast possibly-unrelated pointers to plain Address before comparing them
   10628             :     // to avoid undefined behavior.
   10629      129138 :     if (last_handle_before_deferred_block_ != nullptr &&
   10630          22 :         (reinterpret_cast<Address>(last_handle_before_deferred_block_) <=
   10631          22 :          reinterpret_cast<Address>(&block[kHandleBlockSize])) &&
   10632          11 :         (reinterpret_cast<Address>(last_handle_before_deferred_block_) >=
   10633             :          reinterpret_cast<Address>(block))) {
   10634          11 :       v->VisitRootPointers(Root::kHandleScope, nullptr, FullObjectSlot(block),
   10635          22 :                            FullObjectSlot(last_handle_before_deferred_block_));
   10636          11 :       DCHECK(!found_block_before_deferred);
   10637             : #ifdef DEBUG
   10638             :       found_block_before_deferred = true;
   10639             : #endif
   10640             :     } else {
   10641      258232 :       v->VisitRootPointers(Root::kHandleScope, nullptr, FullObjectSlot(block),
   10642      258232 :                            FullObjectSlot(&block[kHandleBlockSize]));
   10643             :     }
   10644             :   }
   10645             : 
   10646             :   DCHECK(last_handle_before_deferred_block_ == nullptr ||
   10647             :          found_block_before_deferred);
   10648             : 
   10649             :   // Iterate over live handles in the last block (if any).
   10650      562696 :   if (!blocks()->empty()) {
   10651      747332 :     v->VisitRootPointers(Root::kHandleScope, nullptr,
   10652             :                          FullObjectSlot(blocks()->back()),
   10653      747332 :                          FullObjectSlot(handle_scope_data_.next));
   10654             :   }
   10655             : 
   10656             :   DetachableVector<Context>* context_lists[2] = {&saved_contexts_,
   10657      562696 :                                                  &entered_contexts_};
   10658     2813488 :   for (unsigned i = 0; i < arraysize(context_lists); i++) {
   10659     1125394 :     context_lists[i]->shrink_to_fit();
   10660     1125395 :     if (context_lists[i]->empty()) continue;
   10661             :     FullObjectSlot start(&context_lists[i]->front());
   10662      787510 :     v->VisitRootPointers(Root::kHandleScope, nullptr, start,
   10663     1575020 :                          start + static_cast<int>(context_lists[i]->size()));
   10664             :   }
   10665      562698 : }
   10666             : 
   10667      556324 : void HandleScopeImplementer::Iterate(RootVisitor* v) {
   10668      556324 :   HandleScopeData* current = isolate_->handle_scope_data();
   10669      556324 :   handle_scope_data_ = *current;
   10670      556324 :   IterateThis(v);
   10671      556325 : }
   10672             : 
   10673        6373 : char* HandleScopeImplementer::Iterate(RootVisitor* v, char* storage) {
   10674             :   HandleScopeImplementer* scope_implementer =
   10675             :       reinterpret_cast<HandleScopeImplementer*>(storage);
   10676        6373 :   scope_implementer->IterateThis(v);
   10677        6373 :   return storage + ArchiveSpacePerThread();
   10678             : }
   10679             : 
   10680        6854 : DeferredHandles* HandleScopeImplementer::Detach(Address* prev_limit) {
   10681             :   DeferredHandles* deferred =
   10682        6854 :       new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
   10683             : 
   10684       13708 :   while (!blocks_.empty()) {
   10685       13708 :     Address* block_start = blocks_.back();
   10686       13708 :     Address* block_limit = &block_start[kHandleBlockSize];
   10687             :     // We should not need to check for SealHandleScope here. Assert this.
   10688             :     DCHECK(prev_limit == block_limit ||
   10689             :            !(block_start <= prev_limit && prev_limit <= block_limit));
   10690       13708 :     if (prev_limit == block_limit) break;
   10691        6854 :     deferred->blocks_.push_back(blocks_.back());
   10692             :     blocks_.pop_back();
   10693             :   }
   10694             : 
   10695             :   // deferred->blocks_ now contains the blocks installed on the
   10696             :   // HandleScope stack since BeginDeferredScope was called, but in
   10697             :   // reverse order.
   10698             : 
   10699             :   DCHECK(prev_limit == nullptr || !blocks_.empty());
   10700             : 
   10701             :   DCHECK(!blocks_.empty() && prev_limit != nullptr);
   10702             :   DCHECK_NOT_NULL(last_handle_before_deferred_block_);
   10703        6854 :   last_handle_before_deferred_block_ = nullptr;
   10704        6854 :   return deferred;
   10705             : }
   10706             : 
   10707             : 
   10708        6854 : void HandleScopeImplementer::BeginDeferredScope() {
   10709             :   DCHECK_NULL(last_handle_before_deferred_block_);
   10710        6854 :   last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
   10711        6854 : }
   10712             : 
   10713             : 
   10714       13708 : DeferredHandles::~DeferredHandles() {
   10715        6854 :   isolate_->UnlinkDeferredHandles(this);
   10716             : 
   10717       20562 :   for (size_t i = 0; i < blocks_.size(); i++) {
   10718             : #ifdef ENABLE_HANDLE_ZAPPING
   10719        6854 :     HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
   10720             : #endif
   10721        6854 :     isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
   10722             :   }
   10723        6854 : }
   10724             : 
   10725        3724 : void DeferredHandles::Iterate(RootVisitor* v) {
   10726             :   DCHECK(!blocks_.empty());
   10727             : 
   10728             :   // Comparing pointers that do not point into the same array is undefined
   10729             :   // behavior, which means if we didn't cast everything to plain Address
   10730             :   // before comparing, the compiler would be allowed to assume that all
   10731             :   // comparisons evaluate to true and drop the entire check.
   10732             :   DCHECK((reinterpret_cast<Address>(first_block_limit_) >=
   10733             :           reinterpret_cast<Address>(blocks_.front())) &&
   10734             :          (reinterpret_cast<Address>(first_block_limit_) <=
   10735             :           reinterpret_cast<Address>(&(blocks_.front())[kHandleBlockSize])));
   10736             : 
   10737        7448 :   v->VisitRootPointers(Root::kHandleScope, nullptr,
   10738             :                        FullObjectSlot(blocks_.front()),
   10739        7448 :                        FullObjectSlot(first_block_limit_));
   10740             : 
   10741        3724 :   for (size_t i = 1; i < blocks_.size(); i++) {
   10742           0 :     v->VisitRootPointers(Root::kHandleScope, nullptr,
   10743             :                          FullObjectSlot(blocks_[i]),
   10744           0 :                          FullObjectSlot(&blocks_[i][kHandleBlockSize]));
   10745             :   }
   10746        3724 : }
   10747             : 
   10748             : 
   10749         645 : void InvokeAccessorGetterCallback(
   10750             :     v8::Local<v8::Name> property,
   10751             :     const v8::PropertyCallbackInfo<v8::Value>& info,
   10752             :     v8::AccessorNameGetterCallback getter) {
   10753             :   // Leaving JavaScript.
   10754             :   Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
   10755             :   RuntimeCallTimerScope timer(isolate,
   10756         645 :                               RuntimeCallCounterId::kAccessorGetterCallback);
   10757         645 :   Address getter_address = reinterpret_cast<Address>(getter);
   10758        1290 :   VMState<EXTERNAL> state(isolate);
   10759        1290 :   ExternalCallbackScope call_scope(isolate, getter_address);
   10760         645 :   getter(property, info);
   10761         645 : }
   10762             : 
   10763             : 
   10764           0 : void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
   10765             :                             v8::FunctionCallback callback) {
   10766             :   Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
   10767             :   RuntimeCallTimerScope timer(isolate,
   10768           0 :                               RuntimeCallCounterId::kInvokeFunctionCallback);
   10769           0 :   Address callback_address = reinterpret_cast<Address>(callback);
   10770           0 :   VMState<EXTERNAL> state(isolate);
   10771           0 :   ExternalCallbackScope call_scope(isolate, callback_address);
   10772           0 :   callback(info);
   10773           0 : }
   10774             : 
   10775             : // Undefine macros for jumbo build.
   10776             : #undef LOG_API
   10777             : #undef ENTER_V8_DO_NOT_USE
   10778             : #undef ENTER_V8_HELPER_DO_NOT_USE
   10779             : #undef PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE
   10780             : #undef PREPARE_FOR_EXECUTION_WITH_CONTEXT
   10781             : #undef PREPARE_FOR_EXECUTION
   10782             : #undef ENTER_V8
   10783             : #undef ENTER_V8_NO_SCRIPT
   10784             : #undef ENTER_V8_NO_SCRIPT_NO_EXCEPTION
   10785             : #undef ENTER_V8_FOR_NEW_CONTEXT
   10786             : #undef EXCEPTION_BAILOUT_CHECK_SCOPED_DO_NOT_USE
   10787             : #undef RETURN_ON_FAILED_EXECUTION
   10788             : #undef RETURN_ON_FAILED_EXECUTION_PRIMITIVE
   10789             : #undef RETURN_TO_LOCAL_UNCHECKED
   10790             : #undef RETURN_ESCAPED
   10791             : #undef SET_FIELD_WRAPPED
   10792             : #undef NEW_STRING
   10793             : #undef CALLBACK_SETTER
   10794             : 
   10795             : }  // namespace internal
   10796      122036 : }  // namespace v8

Generated by: LCOV version 1.10