deps: backport 1ee712a from V8 upstream
[platform/upstream/nodejs.git] / deps / v8 / src / api.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/api.h"
6
7 #include <string.h>  // For memcpy, strlen.
8 #ifdef V8_USE_ADDRESS_SANITIZER
9 #include <sanitizer/asan_interface.h>
10 #endif  // V8_USE_ADDRESS_SANITIZER
11 #include <cmath>  // For isnan.
12 #include "include/v8-debug.h"
13 #include "include/v8-profiler.h"
14 #include "include/v8-testing.h"
15 #include "src/api-natives.h"
16 #include "src/assert-scope.h"
17 #include "src/background-parsing-task.h"
18 #include "src/base/functional.h"
19 #include "src/base/platform/platform.h"
20 #include "src/base/platform/time.h"
21 #include "src/base/utils/random-number-generator.h"
22 #include "src/bootstrapper.h"
23 #include "src/code-stubs.h"
24 #include "src/compiler.h"
25 #include "src/contexts.h"
26 #include "src/conversions-inl.h"
27 #include "src/counters.h"
28 #include "src/cpu-profiler.h"
29 #include "src/debug.h"
30 #include "src/deoptimizer.h"
31 #include "src/execution.h"
32 #include "src/global-handles.h"
33 #include "src/heap/spaces.h"
34 #include "src/heap-profiler.h"
35 #include "src/heap-snapshot-generator-inl.h"
36 #include "src/icu_util.h"
37 #include "src/json-parser.h"
38 #include "src/messages.h"
39 #include "src/parser.h"
40 #include "src/pending-compilation-error-handler.h"
41 #include "src/profile-generator-inl.h"
42 #include "src/property.h"
43 #include "src/property-details.h"
44 #include "src/prototype.h"
45 #include "src/runtime/runtime.h"
46 #include "src/runtime-profiler.h"
47 #include "src/sampler.h"
48 #include "src/scanner-character-streams.h"
49 #include "src/simulator.h"
50 #include "src/snapshot/natives.h"
51 #include "src/snapshot/snapshot.h"
52 #include "src/startup-data-util.h"
53 #include "src/unicode-inl.h"
54 #include "src/v8threads.h"
55 #include "src/version.h"
56 #include "src/vm-state-inl.h"
57
58
59 namespace v8 {
60
61 #define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
62
63
64 #define ENTER_V8(isolate) i::VMState<v8::OTHER> __state__((isolate))
65
66
67 #define PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name, \
68                                       bailout_value, HandleScopeClass, \
69                                       do_callback)                     \
70   if (IsExecutionTerminatingCheck(isolate)) {                          \
71     return bailout_value;                                              \
72   }                                                                    \
73   HandleScopeClass handle_scope(isolate);                              \
74   CallDepthScope call_depth_scope(isolate, context, do_callback);      \
75   LOG_API(isolate, function_name);                                     \
76   ENTER_V8(isolate);                                                   \
77   bool has_pending_exception = false
78
79
80 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT(                                  \
81     context, function_name, bailout_value, HandleScopeClass, do_callback)    \
82   auto isolate = context.IsEmpty()                                           \
83                      ? i::Isolate::Current()                                 \
84                      : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \
85   PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name,             \
86                                 bailout_value, HandleScopeClass, do_callback);
87
88
89 #define PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, function_name, T)     \
90   PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(), function_name, \
91                                 MaybeLocal<T>(), InternalEscapableScope,  \
92                                 false);
93
94
95 #define PREPARE_FOR_EXECUTION(context, function_name, T)                      \
96   PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
97                                      InternalEscapableScope, false)
98
99
100 #define PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, function_name, T)        \
101   PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
102                                      InternalEscapableScope, true)
103
104
105 #define PREPARE_FOR_EXECUTION_PRIMITIVE(context, function_name, T)         \
106   PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, Nothing<T>(), \
107                                      i::HandleScope, false)
108
109
110 #define EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, value) \
111   do {                                                 \
112     if (has_pending_exception) {                       \
113       call_depth_scope.Escape();                       \
114       return value;                                    \
115     }                                                  \
116   } while (false)
117
118
119 #define RETURN_ON_FAILED_EXECUTION(T) \
120   EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, MaybeLocal<T>())
121
122
123 #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \
124   EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, Nothing<T>())
125
126
127 #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \
128   return maybe_local.FromMaybe(Local<T>());
129
130
131 #define RETURN_ESCAPED(value) return handle_scope.Escape(value);
132
133
134 namespace {
135
136 Local<Context> ContextFromHeapObject(i::Handle<i::Object> obj) {
137   return reinterpret_cast<v8::Isolate*>(i::HeapObject::cast(*obj)->GetIsolate())
138       ->GetCurrentContext();
139 }
140
141 class InternalEscapableScope : public v8::EscapableHandleScope {
142  public:
143   explicit inline InternalEscapableScope(i::Isolate* isolate)
144       : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {}
145 };
146
147
148 class CallDepthScope {
149  public:
150   explicit CallDepthScope(i::Isolate* isolate, Local<Context> context,
151                           bool do_callback)
152       : isolate_(isolate),
153         context_(context),
154         escaped_(false),
155         do_callback_(do_callback) {
156     // TODO(dcarney): remove this when blink stops crashing.
157     DCHECK(!isolate_->external_caught_exception());
158     isolate_->handle_scope_implementer()->IncrementCallDepth();
159     if (!context_.IsEmpty()) context_->Enter();
160   }
161   ~CallDepthScope() {
162     if (!context_.IsEmpty()) context_->Exit();
163     if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth();
164     if (do_callback_) isolate_->FireCallCompletedCallback();
165   }
166
167   void Escape() {
168     DCHECK(!escaped_);
169     escaped_ = true;
170     auto handle_scope_implementer = isolate_->handle_scope_implementer();
171     handle_scope_implementer->DecrementCallDepth();
172     bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero();
173     isolate_->OptionalRescheduleException(call_depth_is_zero);
174   }
175
176  private:
177   i::Isolate* const isolate_;
178   Local<Context> context_;
179   bool escaped_;
180   bool do_callback_;
181 };
182
183 }  // namespace
184
185
186 static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate,
187                                              i::Handle<i::Script> script) {
188   i::Handle<i::Object> scriptName(i::Script::GetNameOrSourceURL(script));
189   i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate);
190   v8::Isolate* v8_isolate =
191       reinterpret_cast<v8::Isolate*>(script->GetIsolate());
192   ScriptOriginOptions options(script->origin_options());
193   v8::ScriptOrigin origin(
194       Utils::ToLocal(scriptName),
195       v8::Integer::New(v8_isolate, script->line_offset()->value()),
196       v8::Integer::New(v8_isolate, script->column_offset()->value()),
197       v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()),
198       v8::Integer::New(v8_isolate, script->id()->value()),
199       v8::Boolean::New(v8_isolate, options.IsEmbedderDebugScript()),
200       Utils::ToLocal(source_map_url),
201       v8::Boolean::New(v8_isolate, options.IsOpaque()));
202   return origin;
203 }
204
205
206 // --- E x c e p t i o n   B e h a v i o r ---
207
208
209 void i::FatalProcessOutOfMemory(const char* location) {
210   i::V8::FatalProcessOutOfMemory(location, false);
211 }
212
213
214 // When V8 cannot allocated memory FatalProcessOutOfMemory is called.
215 // The default fatal error handler is called and execution is stopped.
216 void i::V8::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
217   i::Isolate* isolate = i::Isolate::Current();
218   char last_few_messages[Heap::kTraceRingBufferSize + 1];
219   char js_stacktrace[Heap::kStacktraceBufferSize + 1];
220   memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
221   memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1);
222
223   i::HeapStats heap_stats;
224   int start_marker;
225   heap_stats.start_marker = &start_marker;
226   int new_space_size;
227   heap_stats.new_space_size = &new_space_size;
228   int new_space_capacity;
229   heap_stats.new_space_capacity = &new_space_capacity;
230   intptr_t old_space_size;
231   heap_stats.old_space_size = &old_space_size;
232   intptr_t old_space_capacity;
233   heap_stats.old_space_capacity = &old_space_capacity;
234   intptr_t code_space_size;
235   heap_stats.code_space_size = &code_space_size;
236   intptr_t code_space_capacity;
237   heap_stats.code_space_capacity = &code_space_capacity;
238   intptr_t map_space_size;
239   heap_stats.map_space_size = &map_space_size;
240   intptr_t map_space_capacity;
241   heap_stats.map_space_capacity = &map_space_capacity;
242   intptr_t lo_space_size;
243   heap_stats.lo_space_size = &lo_space_size;
244   int global_handle_count;
245   heap_stats.global_handle_count = &global_handle_count;
246   int weak_global_handle_count;
247   heap_stats.weak_global_handle_count = &weak_global_handle_count;
248   int pending_global_handle_count;
249   heap_stats.pending_global_handle_count = &pending_global_handle_count;
250   int near_death_global_handle_count;
251   heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
252   int free_global_handle_count;
253   heap_stats.free_global_handle_count = &free_global_handle_count;
254   intptr_t memory_allocator_size;
255   heap_stats.memory_allocator_size = &memory_allocator_size;
256   intptr_t memory_allocator_capacity;
257   heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
258   int objects_per_type[LAST_TYPE + 1] = {0};
259   heap_stats.objects_per_type = objects_per_type;
260   int size_per_type[LAST_TYPE + 1] = {0};
261   heap_stats.size_per_type = size_per_type;
262   int os_error;
263   heap_stats.os_error = &os_error;
264   heap_stats.last_few_messages = last_few_messages;
265   heap_stats.js_stacktrace = js_stacktrace;
266   int end_marker;
267   heap_stats.end_marker = &end_marker;
268   if (isolate->heap()->HasBeenSetUp()) {
269     // BUG(1718): Don't use the take_snapshot since we don't support
270     // HeapIterator here without doing a special GC.
271     isolate->heap()->RecordStats(&heap_stats, false);
272     char* first_newline = strchr(last_few_messages, '\n');
273     if (first_newline == NULL || first_newline[1] == '\0')
274       first_newline = last_few_messages;
275     PrintF("\n<--- Last few GCs --->\n%s\n", first_newline);
276     PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace);
277   }
278   Utils::ApiCheck(false, location, "Allocation failed - process out of memory");
279   // If the fatal error handler returns, we stop execution.
280   FATAL("API fatal error handler returned after process out of memory");
281 }
282
283
284 void Utils::ReportApiFailure(const char* location, const char* message) {
285   i::Isolate* isolate = i::Isolate::Current();
286   FatalErrorCallback callback = isolate->exception_behavior();
287   if (callback == NULL) {
288     base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
289                          message);
290     base::OS::Abort();
291   } else {
292     callback(location, message);
293   }
294   isolate->SignalFatalError();
295 }
296
297
298 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
299   if (isolate->has_scheduled_exception()) {
300     return isolate->scheduled_exception() ==
301         isolate->heap()->termination_exception();
302   }
303   return false;
304 }
305
306
307 void V8::SetNativesDataBlob(StartupData* natives_blob) {
308   i::V8::SetNativesBlob(natives_blob);
309 }
310
311
312 void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
313   i::V8::SetSnapshotBlob(snapshot_blob);
314 }
315
316
317 bool RunExtraCode(Isolate* isolate, Local<Context> context,
318                   const char* utf8_source) {
319   // Run custom script if provided.
320   base::ElapsedTimer timer;
321   timer.Start();
322   TryCatch try_catch(isolate);
323   Local<String> source_string;
324   if (!String::NewFromUtf8(isolate, utf8_source, NewStringType::kNormal)
325            .ToLocal(&source_string)) {
326     return false;
327   }
328   Local<String> resource_name =
329       String::NewFromUtf8(isolate, "<embedded script>", NewStringType::kNormal)
330           .ToLocalChecked();
331   ScriptOrigin origin(resource_name);
332   ScriptCompiler::Source source(source_string, origin);
333   Local<Script> script;
334   if (!ScriptCompiler::Compile(context, &source).ToLocal(&script)) return false;
335   if (script->Run(context).IsEmpty()) return false;
336   if (i::FLAG_profile_deserialization) {
337     i::PrintF("Executing custom snapshot script took %0.3f ms\n",
338               timer.Elapsed().InMillisecondsF());
339   }
340   timer.Stop();
341   CHECK(!try_catch.HasCaught());
342   return true;
343 }
344
345
346 namespace {
347
348 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
349  public:
350   virtual void* Allocate(size_t length) {
351     void* data = AllocateUninitialized(length);
352     return data == NULL ? data : memset(data, 0, length);
353   }
354   virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
355   virtual void Free(void* data, size_t) { free(data); }
356 };
357
358 }  // namespace
359
360
361 StartupData V8::CreateSnapshotDataBlob(const char* custom_source) {
362   i::Isolate* internal_isolate = new i::Isolate(true);
363   ArrayBufferAllocator allocator;
364   internal_isolate->set_array_buffer_allocator(&allocator);
365   Isolate* isolate = reinterpret_cast<Isolate*>(internal_isolate);
366   StartupData result = {NULL, 0};
367   {
368     base::ElapsedTimer timer;
369     timer.Start();
370     Isolate::Scope isolate_scope(isolate);
371     internal_isolate->set_creating_default_snapshot(true);
372     internal_isolate->Init(NULL);
373     Persistent<Context> context;
374     i::Snapshot::Metadata metadata;
375     {
376       HandleScope handle_scope(isolate);
377       Local<Context> new_context = Context::New(isolate);
378       internal_isolate->set_creating_default_snapshot(false);
379       context.Reset(isolate, new_context);
380       if (custom_source != NULL) {
381         metadata.set_embeds_script(true);
382         Context::Scope context_scope(new_context);
383         if (!RunExtraCode(isolate, new_context, custom_source)) context.Reset();
384       }
385     }
386     if (!context.IsEmpty()) {
387       // Make sure all builtin scripts are cached.
388       {
389         HandleScope scope(isolate);
390         for (int i = 0; i < i::Natives::GetBuiltinsCount(); i++) {
391           internal_isolate->bootstrapper()->SourceLookup<i::Natives>(i);
392         }
393       }
394       // If we don't do this then we end up with a stray root pointing at the
395       // context even after we have disposed of the context.
396       internal_isolate->heap()->CollectAllAvailableGarbage("mksnapshot");
397       i::Object* raw_context = *v8::Utils::OpenPersistent(context);
398       context.Reset();
399
400       i::SnapshotByteSink snapshot_sink;
401       i::StartupSerializer ser(internal_isolate, &snapshot_sink);
402       ser.SerializeStrongReferences();
403
404       i::SnapshotByteSink context_sink;
405       i::PartialSerializer context_ser(internal_isolate, &ser, &context_sink);
406       context_ser.Serialize(&raw_context);
407       ser.SerializeWeakReferencesAndDeferred();
408
409       result = i::Snapshot::CreateSnapshotBlob(ser, context_ser, metadata);
410     }
411     if (i::FLAG_profile_deserialization) {
412       i::PrintF("Creating snapshot took %0.3f ms\n",
413                 timer.Elapsed().InMillisecondsF());
414     }
415     timer.Stop();
416   }
417   isolate->Dispose();
418   return result;
419 }
420
421
422 void V8::SetFlagsFromString(const char* str, int length) {
423   i::FlagList::SetFlagsFromString(str, length);
424 }
425
426
427 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
428   i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
429 }
430
431
432 RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
433
434
435 RegisteredExtension::RegisteredExtension(Extension* extension)
436     : extension_(extension) { }
437
438
439 void RegisteredExtension::Register(RegisteredExtension* that) {
440   that->next_ = first_extension_;
441   first_extension_ = that;
442 }
443
444
445 void RegisteredExtension::UnregisterAll() {
446   RegisteredExtension* re = first_extension_;
447   while (re != NULL) {
448     RegisteredExtension* next = re->next();
449     delete re;
450     re = next;
451   }
452   first_extension_ = NULL;
453 }
454
455
456 void RegisterExtension(Extension* that) {
457   RegisteredExtension* extension = new RegisteredExtension(that);
458   RegisteredExtension::Register(extension);
459 }
460
461
462 Extension::Extension(const char* name,
463                      const char* source,
464                      int dep_count,
465                      const char** deps,
466                      int source_length)
467     : name_(name),
468       source_length_(source_length >= 0 ?
469                      source_length :
470                      (source ? static_cast<int>(strlen(source)) : 0)),
471       source_(source, source_length_),
472       dep_count_(dep_count),
473       deps_(deps),
474       auto_enable_(false) {
475   CHECK(source != NULL || source_length_ == 0);
476 }
477
478
479 ResourceConstraints::ResourceConstraints()
480     : max_semi_space_size_(0),
481       max_old_space_size_(0),
482       max_executable_size_(0),
483       stack_limit_(NULL),
484       max_available_threads_(0),
485       code_range_size_(0) { }
486
487 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
488                                             uint64_t virtual_memory_limit,
489                                             uint32_t number_of_processors) {
490   ConfigureDefaults(physical_memory, virtual_memory_limit);
491 }
492
493 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
494                                             uint64_t virtual_memory_limit) {
495 #if V8_OS_ANDROID
496   // Android has higher physical memory requirements before raising the maximum
497   // heap size limits since it has no swap space.
498   const uint64_t low_limit = 512ul * i::MB;
499   const uint64_t medium_limit = 1ul * i::GB;
500   const uint64_t high_limit = 2ul * i::GB;
501 #else
502   const uint64_t low_limit = 512ul * i::MB;
503   const uint64_t medium_limit = 768ul * i::MB;
504   const uint64_t high_limit = 1ul  * i::GB;
505 #endif
506
507   if (physical_memory <= low_limit) {
508     set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeLowMemoryDevice);
509     set_max_old_space_size(i::Heap::kMaxOldSpaceSizeLowMemoryDevice);
510     set_max_executable_size(i::Heap::kMaxExecutableSizeLowMemoryDevice);
511   } else if (physical_memory <= medium_limit) {
512     set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeMediumMemoryDevice);
513     set_max_old_space_size(i::Heap::kMaxOldSpaceSizeMediumMemoryDevice);
514     set_max_executable_size(i::Heap::kMaxExecutableSizeMediumMemoryDevice);
515   } else if (physical_memory <= high_limit) {
516     set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHighMemoryDevice);
517     set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHighMemoryDevice);
518     set_max_executable_size(i::Heap::kMaxExecutableSizeHighMemoryDevice);
519   } else {
520     set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHugeMemoryDevice);
521     set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHugeMemoryDevice);
522     set_max_executable_size(i::Heap::kMaxExecutableSizeHugeMemoryDevice);
523   }
524
525   if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
526     // Reserve no more than 1/8 of the memory for the code range, but at most
527     // kMaximalCodeRangeSize.
528     set_code_range_size(
529         i::Min(i::kMaximalCodeRangeSize / i::MB,
530                static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
531   }
532 }
533
534
535 void SetResourceConstraints(i::Isolate* isolate,
536                             const ResourceConstraints& constraints) {
537   int semi_space_size = constraints.max_semi_space_size();
538   int old_space_size = constraints.max_old_space_size();
539   int max_executable_size = constraints.max_executable_size();
540   size_t code_range_size = constraints.code_range_size();
541   if (semi_space_size != 0 || old_space_size != 0 ||
542       max_executable_size != 0 || code_range_size != 0) {
543     isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
544                                    max_executable_size, code_range_size);
545   }
546   if (constraints.stack_limit() != NULL) {
547     uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
548     isolate->stack_guard()->SetStackLimit(limit);
549   }
550 }
551
552
553 i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** obj) {
554   LOG_API(isolate, "Persistent::New");
555   i::Handle<i::Object> result = isolate->global_handles()->Create(*obj);
556 #ifdef VERIFY_HEAP
557   if (i::FLAG_verify_heap) {
558     (*obj)->ObjectVerify();
559   }
560 #endif  // VERIFY_HEAP
561   return result.location();
562 }
563
564
565 i::Object** V8::CopyPersistent(i::Object** obj) {
566   i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj);
567 #ifdef VERIFY_HEAP
568   if (i::FLAG_verify_heap) {
569     (*obj)->ObjectVerify();
570   }
571 #endif  // VERIFY_HEAP
572   return result.location();
573 }
574
575
576 void V8::MakeWeak(i::Object** object, void* parameter,
577                   WeakCallback weak_callback) {
578   i::GlobalHandles::MakeWeak(object, parameter, weak_callback);
579 }
580
581
582 void V8::MakeWeak(i::Object** object, void* parameter,
583                   int internal_field_index1, int internal_field_index2,
584                   WeakCallbackInfo<void>::Callback weak_callback) {
585   WeakCallbackType type = WeakCallbackType::kParameter;
586   if (internal_field_index1 == 0) {
587     if (internal_field_index2 == 1) {
588       type = WeakCallbackType::kInternalFields;
589     } else {
590       DCHECK_EQ(internal_field_index2, -1);
591       type = WeakCallbackType::kInternalFields;
592     }
593   } else {
594     DCHECK_EQ(internal_field_index1, -1);
595     DCHECK_EQ(internal_field_index2, -1);
596   }
597   i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
598 }
599
600
601 void V8::MakeWeak(i::Object** object, void* parameter,
602                   WeakCallbackInfo<void>::Callback weak_callback,
603                   WeakCallbackType type) {
604   i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
605 }
606
607
608 void* V8::ClearWeak(i::Object** obj) {
609   return i::GlobalHandles::ClearWeakness(obj);
610 }
611
612
613 void V8::DisposeGlobal(i::Object** obj) {
614   i::GlobalHandles::Destroy(obj);
615 }
616
617
618 void V8::Eternalize(Isolate* v8_isolate, Value* value, int* index) {
619   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
620   i::Object* object = *Utils::OpenHandle(value);
621   isolate->eternal_handles()->Create(isolate, object, index);
622 }
623
624
625 Local<Value> V8::GetEternal(Isolate* v8_isolate, int index) {
626   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
627   return Utils::ToLocal(isolate->eternal_handles()->Get(index));
628 }
629
630
631 void V8::FromJustIsNothing() {
632   Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing.");
633 }
634
635
636 void V8::ToLocalEmpty() {
637   Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal.");
638 }
639
640
641 void V8::InternalFieldOutOfBounds(int index) {
642   Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback,
643                   "WeakCallbackInfo::GetInternalField",
644                   "Internal field out of bounds.");
645 }
646
647
648 // --- H a n d l e s ---
649
650
651 HandleScope::HandleScope(Isolate* isolate) {
652   Initialize(isolate);
653 }
654
655
656 void HandleScope::Initialize(Isolate* isolate) {
657   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
658   // We do not want to check the correct usage of the Locker class all over the
659   // place, so we do it only here: Without a HandleScope, an embedder can do
660   // almost nothing, so it is enough to check in this central place.
661   // We make an exception if the serializer is enabled, which means that the
662   // Isolate is exclusively used to create a snapshot.
663   Utils::ApiCheck(
664       !v8::Locker::IsActive() ||
665           internal_isolate->thread_manager()->IsLockedByCurrentThread() ||
666           internal_isolate->serializer_enabled(),
667       "HandleScope::HandleScope",
668       "Entering the V8 API without proper locking in place");
669   i::HandleScopeData* current = internal_isolate->handle_scope_data();
670   isolate_ = internal_isolate;
671   prev_next_ = current->next;
672   prev_limit_ = current->limit;
673   current->level++;
674 }
675
676
677 HandleScope::~HandleScope() {
678   i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
679 }
680
681
682 int HandleScope::NumberOfHandles(Isolate* isolate) {
683   return i::HandleScope::NumberOfHandles(
684       reinterpret_cast<i::Isolate*>(isolate));
685 }
686
687
688 i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) {
689   return i::HandleScope::CreateHandle(isolate, value);
690 }
691
692
693 i::Object** HandleScope::CreateHandle(i::HeapObject* heap_object,
694                                       i::Object* value) {
695   DCHECK(heap_object->IsHeapObject());
696   return i::HandleScope::CreateHandle(heap_object->GetIsolate(), value);
697 }
698
699
700 EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
701   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
702   escape_slot_ = CreateHandle(isolate, isolate->heap()->the_hole_value());
703   Initialize(v8_isolate);
704 }
705
706
707 i::Object** EscapableHandleScope::Escape(i::Object** escape_value) {
708   i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
709   Utils::ApiCheck(*escape_slot_ == heap->the_hole_value(),
710                   "EscapeableHandleScope::Escape",
711                   "Escape value set twice");
712   if (escape_value == NULL) {
713     *escape_slot_ = heap->undefined_value();
714     return NULL;
715   }
716   *escape_slot_ = *escape_value;
717   return escape_slot_;
718 }
719
720
721 SealHandleScope::SealHandleScope(Isolate* isolate) {
722   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
723
724   isolate_ = internal_isolate;
725   i::HandleScopeData* current = internal_isolate->handle_scope_data();
726   prev_limit_ = current->limit;
727   current->limit = current->next;
728   prev_level_ = current->level;
729   current->level = 0;
730 }
731
732
733 SealHandleScope::~SealHandleScope() {
734   i::HandleScopeData* current = isolate_->handle_scope_data();
735   DCHECK_EQ(0, current->level);
736   current->level = prev_level_;
737   DCHECK_EQ(current->next, current->limit);
738   current->limit = prev_limit_;
739 }
740
741
742 void Context::Enter() {
743   i::Handle<i::Context> env = Utils::OpenHandle(this);
744   i::Isolate* isolate = env->GetIsolate();
745   ENTER_V8(isolate);
746   i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
747   impl->EnterContext(env);
748   impl->SaveContext(isolate->context());
749   isolate->set_context(*env);
750 }
751
752
753 void Context::Exit() {
754   i::Handle<i::Context> env = Utils::OpenHandle(this);
755   i::Isolate* isolate = env->GetIsolate();
756   ENTER_V8(isolate);
757   i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
758   if (!Utils::ApiCheck(impl->LastEnteredContextWas(env),
759                        "v8::Context::Exit()",
760                        "Cannot exit non-entered context")) {
761     return;
762   }
763   impl->LeaveContext();
764   isolate->set_context(impl->RestoreContext());
765 }
766
767
768 static void* DecodeSmiToAligned(i::Object* value, const char* location) {
769   Utils::ApiCheck(value->IsSmi(), location, "Not a Smi");
770   return reinterpret_cast<void*>(value);
771 }
772
773
774 static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) {
775   i::Smi* smi = reinterpret_cast<i::Smi*>(value);
776   Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned");
777   return smi;
778 }
779
780
781 static i::Handle<i::FixedArray> EmbedderDataFor(Context* context,
782                                                 int index,
783                                                 bool can_grow,
784                                                 const char* location) {
785   i::Handle<i::Context> env = Utils::OpenHandle(context);
786   bool ok =
787       Utils::ApiCheck(env->IsNativeContext(),
788                       location,
789                       "Not a native context") &&
790       Utils::ApiCheck(index >= 0, location, "Negative index");
791   if (!ok) return i::Handle<i::FixedArray>();
792   i::Handle<i::FixedArray> data(env->embedder_data());
793   if (index < data->length()) return data;
794   if (!Utils::ApiCheck(can_grow, location, "Index too large")) {
795     return i::Handle<i::FixedArray>();
796   }
797   int new_size = i::Max(index, data->length() << 1) + 1;
798   data = i::FixedArray::CopySize(data, new_size);
799   env->set_embedder_data(*data);
800   return data;
801 }
802
803
804 v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
805   const char* location = "v8::Context::GetEmbedderData()";
806   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
807   if (data.is_null()) return Local<Value>();
808   i::Handle<i::Object> result(data->get(index), data->GetIsolate());
809   return Utils::ToLocal(result);
810 }
811
812
813 void Context::SetEmbedderData(int index, v8::Local<Value> value) {
814   const char* location = "v8::Context::SetEmbedderData()";
815   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
816   if (data.is_null()) return;
817   i::Handle<i::Object> val = Utils::OpenHandle(*value);
818   data->set(index, *val);
819   DCHECK_EQ(*Utils::OpenHandle(*value),
820             *Utils::OpenHandle(*GetEmbedderData(index)));
821 }
822
823
824 void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
825   const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
826   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
827   if (data.is_null()) return NULL;
828   return DecodeSmiToAligned(data->get(index), location);
829 }
830
831
832 void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
833   const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
834   i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
835   data->set(index, EncodeAlignedAsSmi(value, location));
836   DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
837 }
838
839
840 // --- N e a n d e r ---
841
842
843 // A constructor cannot easily return an error value, therefore it is necessary
844 // to check for a dead VM with ON_BAILOUT before constructing any Neander
845 // objects.  To remind you about this there is no HandleScope in the
846 // NeanderObject constructor.  When you add one to the site calling the
847 // constructor you should check that you ensured the VM was not dead first.
848 NeanderObject::NeanderObject(v8::internal::Isolate* isolate, int size) {
849   ENTER_V8(isolate);
850   value_ = isolate->factory()->NewNeanderObject();
851   i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
852   value_->set_elements(*elements);
853 }
854
855
856 int NeanderObject::size() {
857   return i::FixedArray::cast(value_->elements())->length();
858 }
859
860
861 NeanderArray::NeanderArray(v8::internal::Isolate* isolate) : obj_(isolate, 2) {
862   obj_.set(0, i::Smi::FromInt(0));
863 }
864
865
866 int NeanderArray::length() {
867   return i::Smi::cast(obj_.get(0))->value();
868 }
869
870
871 i::Object* NeanderArray::get(int offset) {
872   DCHECK(0 <= offset);
873   DCHECK(offset < length());
874   return obj_.get(offset + 1);
875 }
876
877
878 // This method cannot easily return an error value, therefore it is necessary
879 // to check for a dead VM with ON_BAILOUT before calling it.  To remind you
880 // about this there is no HandleScope in this method.  When you add one to the
881 // site calling this method you should check that you ensured the VM was not
882 // dead first.
883 void NeanderArray::add(i::Isolate* isolate, i::Handle<i::Object> value) {
884   int length = this->length();
885   int size = obj_.size();
886   if (length == size - 1) {
887     i::Factory* factory = isolate->factory();
888     i::Handle<i::FixedArray> new_elms = factory->NewFixedArray(2 * size);
889     for (int i = 0; i < length; i++)
890       new_elms->set(i + 1, get(i));
891     obj_.value()->set_elements(*new_elms);
892   }
893   obj_.set(length + 1, *value);
894   obj_.set(0, i::Smi::FromInt(length + 1));
895 }
896
897
898 void NeanderArray::set(int index, i::Object* value) {
899   if (index < 0 || index >= this->length()) return;
900   obj_.set(index + 1, value);
901 }
902
903
904 // --- T e m p l a t e ---
905
906
907 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
908   that->set_number_of_properties(0);
909   that->set_tag(i::Smi::FromInt(type));
910 }
911
912
913 void Template::Set(v8::Local<Name> name, v8::Local<Data> value,
914                    v8::PropertyAttribute attribute) {
915   auto templ = Utils::OpenHandle(this);
916   i::Isolate* isolate = templ->GetIsolate();
917   ENTER_V8(isolate);
918   i::HandleScope scope(isolate);
919   // TODO(dcarney): split api to allow values of v8::Value or v8::TemplateInfo.
920   i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
921                                  Utils::OpenHandle(*value),
922                                  static_cast<PropertyAttributes>(attribute));
923 }
924
925
926 void Template::SetAccessorProperty(
927     v8::Local<v8::Name> name,
928     v8::Local<FunctionTemplate> getter,
929     v8::Local<FunctionTemplate> setter,
930     v8::PropertyAttribute attribute,
931     v8::AccessControl access_control) {
932   // TODO(verwaest): Remove |access_control|.
933   DCHECK_EQ(v8::DEFAULT, access_control);
934   auto templ = Utils::OpenHandle(this);
935   auto isolate = templ->GetIsolate();
936   ENTER_V8(isolate);
937   DCHECK(!name.IsEmpty());
938   DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
939   i::HandleScope scope(isolate);
940   i::ApiNatives::AddAccessorProperty(
941       isolate, templ, Utils::OpenHandle(*name),
942       Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true),
943       static_cast<PropertyAttributes>(attribute));
944 }
945
946
947 // --- F u n c t i o n   T e m p l a t e ---
948 static void InitializeFunctionTemplate(
949     i::Handle<i::FunctionTemplateInfo> info) {
950   InitializeTemplate(info, Consts::FUNCTION_TEMPLATE);
951   info->set_flag(0);
952 }
953
954
955 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
956   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
957   ENTER_V8(i_isolate);
958   i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(),
959                               i_isolate);
960   if (result->IsUndefined()) {
961     v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(i_isolate);
962     result = Utils::OpenHandle(*ObjectTemplate::New(isolate));
963     Utils::OpenHandle(this)->set_prototype_template(*result);
964   }
965   return ToApiHandle<ObjectTemplate>(result);
966 }
967
968
969 static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info,
970                                   const char* func) {
971   Utils::ApiCheck(!info->instantiated(), func,
972                   "FunctionTemplate already instantiated");
973 }
974
975
976 void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) {
977   auto info = Utils::OpenHandle(this);
978   EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit");
979   i::Isolate* isolate = info->GetIsolate();
980   ENTER_V8(isolate);
981   info->set_parent_template(*Utils::OpenHandle(*value));
982 }
983
984
985 static Local<FunctionTemplate> FunctionTemplateNew(
986     i::Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
987     v8::Local<Signature> signature, int length, bool do_not_cache) {
988   i::Handle<i::Struct> struct_obj =
989       isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
990   i::Handle<i::FunctionTemplateInfo> obj =
991       i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
992   InitializeFunctionTemplate(obj);
993   obj->set_do_not_cache(do_not_cache);
994   int next_serial_number = 0;
995   if (!do_not_cache) {
996     next_serial_number = isolate->next_serial_number() + 1;
997     isolate->set_next_serial_number(next_serial_number);
998   }
999   obj->set_serial_number(i::Smi::FromInt(next_serial_number));
1000   if (callback != 0) {
1001     if (data.IsEmpty()) {
1002       data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1003     }
1004     Utils::ToLocal(obj)->SetCallHandler(callback, data);
1005   }
1006   obj->set_length(length);
1007   obj->set_undetectable(false);
1008   obj->set_needs_access_check(false);
1009   obj->set_accept_any_receiver(true);
1010   if (!signature.IsEmpty())
1011     obj->set_signature(*Utils::OpenHandle(*signature));
1012   return Utils::ToLocal(obj);
1013 }
1014
1015 Local<FunctionTemplate> FunctionTemplate::New(Isolate* isolate,
1016                                               FunctionCallback callback,
1017                                               v8::Local<Value> data,
1018                                               v8::Local<Signature> signature,
1019                                               int length) {
1020   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1021   // Changes to the environment cannot be captured in the snapshot. Expect no
1022   // function templates when the isolate is created for serialization.
1023   DCHECK(!i_isolate->serializer_enabled());
1024   LOG_API(i_isolate, "FunctionTemplate::New");
1025   ENTER_V8(i_isolate);
1026   return FunctionTemplateNew(
1027       i_isolate, callback, data, signature, length, false);
1028 }
1029
1030
1031 Local<Signature> Signature::New(Isolate* isolate,
1032                                 Local<FunctionTemplate> receiver) {
1033   return Utils::SignatureToLocal(Utils::OpenHandle(*receiver));
1034 }
1035
1036
1037 Local<AccessorSignature> AccessorSignature::New(
1038     Isolate* isolate, Local<FunctionTemplate> receiver) {
1039   return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
1040 }
1041
1042
1043 Local<TypeSwitch> TypeSwitch::New(Local<FunctionTemplate> type) {
1044   Local<FunctionTemplate> types[1] = {type};
1045   return TypeSwitch::New(1, types);
1046 }
1047
1048
1049 Local<TypeSwitch> TypeSwitch::New(int argc, Local<FunctionTemplate> types[]) {
1050   i::Isolate* isolate = i::Isolate::Current();
1051   LOG_API(isolate, "TypeSwitch::New");
1052   ENTER_V8(isolate);
1053   i::Handle<i::FixedArray> vector = isolate->factory()->NewFixedArray(argc);
1054   for (int i = 0; i < argc; i++)
1055     vector->set(i, *Utils::OpenHandle(*types[i]));
1056   i::Handle<i::Struct> struct_obj =
1057       isolate->factory()->NewStruct(i::TYPE_SWITCH_INFO_TYPE);
1058   i::Handle<i::TypeSwitchInfo> obj =
1059       i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
1060   obj->set_types(*vector);
1061   return Utils::ToLocal(obj);
1062 }
1063
1064
1065 int TypeSwitch::match(v8::Local<Value> value) {
1066   i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
1067   LOG_API(info->GetIsolate(), "TypeSwitch::match");
1068   i::Handle<i::Object> obj = Utils::OpenHandle(*value);
1069   i::FixedArray* types = i::FixedArray::cast(info->types());
1070   for (int i = 0; i < types->length(); i++) {
1071     if (i::FunctionTemplateInfo::cast(types->get(i))->IsTemplateFor(*obj))
1072       return i + 1;
1073   }
1074   return 0;
1075 }
1076
1077
1078 #define SET_FIELD_WRAPPED(obj, setter, cdata) do {                      \
1079     i::Handle<i::Object> foreign = FromCData(obj->GetIsolate(), cdata); \
1080     (obj)->setter(*foreign);                                            \
1081   } while (false)
1082
1083
1084 void FunctionTemplate::SetCallHandler(FunctionCallback callback,
1085                                       v8::Local<Value> data) {
1086   auto info = Utils::OpenHandle(this);
1087   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler");
1088   i::Isolate* isolate = info->GetIsolate();
1089   ENTER_V8(isolate);
1090   i::HandleScope scope(isolate);
1091   i::Handle<i::Struct> struct_obj =
1092       isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1093   i::Handle<i::CallHandlerInfo> obj =
1094       i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1095   SET_FIELD_WRAPPED(obj, set_callback, callback);
1096   if (data.IsEmpty()) {
1097     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1098   }
1099   obj->set_data(*Utils::OpenHandle(*data));
1100   info->set_call_code(*obj);
1101 }
1102
1103
1104 static i::Handle<i::AccessorInfo> SetAccessorInfoProperties(
1105     i::Handle<i::AccessorInfo> obj, v8::Local<Name> name,
1106     v8::AccessControl settings, v8::PropertyAttribute attributes,
1107     v8::Local<AccessorSignature> signature) {
1108   obj->set_name(*Utils::OpenHandle(*name));
1109   if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
1110   if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
1111   obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
1112   if (!signature.IsEmpty()) {
1113     obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
1114   }
1115   return obj;
1116 }
1117
1118
1119 template <typename Getter, typename Setter>
1120 static i::Handle<i::AccessorInfo> MakeAccessorInfo(
1121     v8::Local<Name> name, Getter getter, Setter setter, v8::Local<Value> data,
1122     v8::AccessControl settings, v8::PropertyAttribute attributes,
1123     v8::Local<AccessorSignature> signature) {
1124   i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate();
1125   i::Handle<i::ExecutableAccessorInfo> obj =
1126       isolate->factory()->NewExecutableAccessorInfo();
1127   SET_FIELD_WRAPPED(obj, set_getter, getter);
1128   SET_FIELD_WRAPPED(obj, set_setter, setter);
1129   if (data.IsEmpty()) {
1130     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1131   }
1132   obj->set_data(*Utils::OpenHandle(*data));
1133   return SetAccessorInfoProperties(obj, name, settings, attributes, signature);
1134 }
1135
1136
1137 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
1138   i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
1139   if (!Utils::ApiCheck(!handle.is_null(),
1140                        "v8::FunctionTemplate::InstanceTemplate()",
1141                        "Reading from empty handle")) {
1142     return Local<ObjectTemplate>();
1143   }
1144   i::Isolate* isolate = handle->GetIsolate();
1145   ENTER_V8(isolate);
1146   if (handle->instance_template()->IsUndefined()) {
1147     Local<ObjectTemplate> templ =
1148         ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
1149     handle->set_instance_template(*Utils::OpenHandle(*templ));
1150   }
1151   i::Handle<i::ObjectTemplateInfo> result(
1152       i::ObjectTemplateInfo::cast(handle->instance_template()));
1153   return Utils::ToLocal(result);
1154 }
1155
1156
1157 void FunctionTemplate::SetLength(int length) {
1158   auto info = Utils::OpenHandle(this);
1159   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength");
1160   auto isolate = info->GetIsolate();
1161   ENTER_V8(isolate);
1162   info->set_length(length);
1163 }
1164
1165
1166 void FunctionTemplate::SetClassName(Local<String> name) {
1167   auto info = Utils::OpenHandle(this);
1168   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName");
1169   auto isolate = info->GetIsolate();
1170   ENTER_V8(isolate);
1171   info->set_class_name(*Utils::OpenHandle(*name));
1172 }
1173
1174
1175 void FunctionTemplate::SetAcceptAnyReceiver(bool value) {
1176   auto info = Utils::OpenHandle(this);
1177   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
1178   auto isolate = info->GetIsolate();
1179   ENTER_V8(isolate);
1180   info->set_accept_any_receiver(value);
1181 }
1182
1183
1184 void FunctionTemplate::SetHiddenPrototype(bool value) {
1185   auto info = Utils::OpenHandle(this);
1186   EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype");
1187   auto isolate = info->GetIsolate();
1188   ENTER_V8(isolate);
1189   info->set_hidden_prototype(value);
1190 }
1191
1192
1193 void FunctionTemplate::ReadOnlyPrototype() {
1194   auto info = Utils::OpenHandle(this);
1195   EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype");
1196   auto isolate = info->GetIsolate();
1197   ENTER_V8(isolate);
1198   info->set_read_only_prototype(true);
1199 }
1200
1201
1202 void FunctionTemplate::RemovePrototype() {
1203   auto info = Utils::OpenHandle(this);
1204   EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype");
1205   auto isolate = info->GetIsolate();
1206   ENTER_V8(isolate);
1207   info->set_remove_prototype(true);
1208 }
1209
1210
1211 // --- O b j e c t T e m p l a t e ---
1212
1213
1214 Local<ObjectTemplate> ObjectTemplate::New(
1215     Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1216   return New(reinterpret_cast<i::Isolate*>(isolate), constructor);
1217 }
1218
1219
1220 Local<ObjectTemplate> ObjectTemplate::New() {
1221   return New(i::Isolate::Current(), Local<FunctionTemplate>());
1222 }
1223
1224
1225 Local<ObjectTemplate> ObjectTemplate::New(
1226     i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1227   // Changes to the environment cannot be captured in the snapshot. Expect no
1228   // object templates when the isolate is created for serialization.
1229   DCHECK(!isolate->serializer_enabled());
1230   LOG_API(isolate, "ObjectTemplate::New");
1231   ENTER_V8(isolate);
1232   i::Handle<i::Struct> struct_obj =
1233       isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
1234   i::Handle<i::ObjectTemplateInfo> obj =
1235       i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
1236   InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
1237   if (!constructor.IsEmpty())
1238     obj->set_constructor(*Utils::OpenHandle(*constructor));
1239   obj->set_internal_field_count(i::Smi::FromInt(0));
1240   return Utils::ToLocal(obj);
1241 }
1242
1243
1244 // Ensure that the object template has a constructor.  If no
1245 // constructor is available we create one.
1246 static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
1247     i::Isolate* isolate,
1248     ObjectTemplate* object_template) {
1249   i::Object* obj = Utils::OpenHandle(object_template)->constructor();
1250   if (!obj ->IsUndefined()) {
1251     i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj);
1252     return i::Handle<i::FunctionTemplateInfo>(info, isolate);
1253   }
1254   Local<FunctionTemplate> templ =
1255       FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
1256   i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
1257   constructor->set_instance_template(*Utils::OpenHandle(object_template));
1258   Utils::OpenHandle(object_template)->set_constructor(*constructor);
1259   return constructor;
1260 }
1261
1262
1263 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1264     i::Isolate* isolate,
1265     Template* template_obj) {
1266   return Utils::OpenHandle(template_obj);
1267 }
1268
1269
1270 // TODO(dcarney): remove this with ObjectTemplate::SetAccessor
1271 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1272     i::Isolate* isolate,
1273     ObjectTemplate* object_template) {
1274   EnsureConstructor(isolate, object_template);
1275   return Utils::OpenHandle(object_template);
1276 }
1277
1278
1279 template<typename Getter, typename Setter, typename Data, typename Template>
1280 static bool TemplateSetAccessor(
1281     Template* template_obj,
1282     v8::Local<Name> name,
1283     Getter getter,
1284     Setter setter,
1285     Data data,
1286     AccessControl settings,
1287     PropertyAttribute attribute,
1288     v8::Local<AccessorSignature> signature) {
1289   auto isolate = Utils::OpenHandle(template_obj)->GetIsolate();
1290   ENTER_V8(isolate);
1291   i::HandleScope scope(isolate);
1292   auto obj = MakeAccessorInfo(name, getter, setter, data, settings, attribute,
1293                               signature);
1294   if (obj.is_null()) return false;
1295   auto info = GetTemplateInfo(isolate, template_obj);
1296   i::ApiNatives::AddNativeDataProperty(isolate, info, obj);
1297   return true;
1298 }
1299
1300
1301 void Template::SetNativeDataProperty(v8::Local<String> name,
1302                                      AccessorGetterCallback getter,
1303                                      AccessorSetterCallback setter,
1304                                      v8::Local<Value> data,
1305                                      PropertyAttribute attribute,
1306                                      v8::Local<AccessorSignature> signature,
1307                                      AccessControl settings) {
1308   TemplateSetAccessor(
1309       this, name, getter, setter, data, settings, attribute, signature);
1310 }
1311
1312
1313 void Template::SetNativeDataProperty(v8::Local<Name> name,
1314                                      AccessorNameGetterCallback getter,
1315                                      AccessorNameSetterCallback setter,
1316                                      v8::Local<Value> data,
1317                                      PropertyAttribute attribute,
1318                                      v8::Local<AccessorSignature> signature,
1319                                      AccessControl settings) {
1320   TemplateSetAccessor(
1321       this, name, getter, setter, data, settings, attribute, signature);
1322 }
1323
1324
1325 void ObjectTemplate::SetAccessor(v8::Local<String> name,
1326                                  AccessorGetterCallback getter,
1327                                  AccessorSetterCallback setter,
1328                                  v8::Local<Value> data, AccessControl settings,
1329                                  PropertyAttribute attribute,
1330                                  v8::Local<AccessorSignature> signature) {
1331   TemplateSetAccessor(
1332       this, name, getter, setter, data, settings, attribute, signature);
1333 }
1334
1335
1336 void ObjectTemplate::SetAccessor(v8::Local<Name> name,
1337                                  AccessorNameGetterCallback getter,
1338                                  AccessorNameSetterCallback setter,
1339                                  v8::Local<Value> data, AccessControl settings,
1340                                  PropertyAttribute attribute,
1341                                  v8::Local<AccessorSignature> signature) {
1342   TemplateSetAccessor(
1343       this, name, getter, setter, data, settings, attribute, signature);
1344 }
1345
1346
1347 template <typename Getter, typename Setter, typename Query, typename Deleter,
1348           typename Enumerator>
1349 static void ObjectTemplateSetNamedPropertyHandler(ObjectTemplate* templ,
1350                                                   Getter getter, Setter setter,
1351                                                   Query query, Deleter remover,
1352                                                   Enumerator enumerator,
1353                                                   Local<Value> data,
1354                                                   PropertyHandlerFlags flags) {
1355   i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate();
1356   ENTER_V8(isolate);
1357   i::HandleScope scope(isolate);
1358   auto cons = EnsureConstructor(isolate, templ);
1359   EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler");
1360   auto obj = i::Handle<i::InterceptorInfo>::cast(
1361       isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1362
1363   if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1364   if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1365   if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1366   if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1367   if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1368   obj->set_flags(0);
1369   obj->set_can_intercept_symbols(
1370       !(static_cast<int>(flags) &
1371         static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings)));
1372   obj->set_all_can_read(static_cast<int>(flags) &
1373                         static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1374   obj->set_non_masking(static_cast<int>(flags) &
1375                        static_cast<int>(PropertyHandlerFlags::kNonMasking));
1376
1377   if (data.IsEmpty()) {
1378     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1379   }
1380   obj->set_data(*Utils::OpenHandle(*data));
1381   cons->set_named_property_handler(*obj);
1382 }
1383
1384
1385 void ObjectTemplate::SetNamedPropertyHandler(
1386     NamedPropertyGetterCallback getter, NamedPropertySetterCallback setter,
1387     NamedPropertyQueryCallback query, NamedPropertyDeleterCallback remover,
1388     NamedPropertyEnumeratorCallback enumerator, Local<Value> data) {
1389   ObjectTemplateSetNamedPropertyHandler(
1390       this, getter, setter, query, remover, enumerator, data,
1391       PropertyHandlerFlags::kOnlyInterceptStrings);
1392 }
1393
1394
1395 void ObjectTemplate::SetHandler(
1396     const NamedPropertyHandlerConfiguration& config) {
1397   ObjectTemplateSetNamedPropertyHandler(
1398       this, config.getter, config.setter, config.query, config.deleter,
1399       config.enumerator, config.data, config.flags);
1400 }
1401
1402
1403 void ObjectTemplate::MarkAsUndetectable() {
1404   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1405   ENTER_V8(isolate);
1406   i::HandleScope scope(isolate);
1407   auto cons = EnsureConstructor(isolate, this);
1408   EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable");
1409   cons->set_undetectable(true);
1410 }
1411
1412
1413 void ObjectTemplate::SetAccessCheckCallbacks(
1414     NamedSecurityCallback named_callback,
1415     IndexedSecurityCallback indexed_callback, Local<Value> data) {
1416   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1417   ENTER_V8(isolate);
1418   i::HandleScope scope(isolate);
1419   auto cons = EnsureConstructor(isolate, this);
1420   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallbacks");
1421
1422   i::Handle<i::Struct> struct_info =
1423       isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE);
1424   i::Handle<i::AccessCheckInfo> info =
1425       i::Handle<i::AccessCheckInfo>::cast(struct_info);
1426
1427   SET_FIELD_WRAPPED(info, set_named_callback, named_callback);
1428   SET_FIELD_WRAPPED(info, set_indexed_callback, indexed_callback);
1429
1430   if (data.IsEmpty()) {
1431     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1432   }
1433   info->set_data(*Utils::OpenHandle(*data));
1434
1435   cons->set_access_check_info(*info);
1436   cons->set_needs_access_check(true);
1437 }
1438
1439
1440 void ObjectTemplate::SetHandler(
1441     const IndexedPropertyHandlerConfiguration& config) {
1442   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1443   ENTER_V8(isolate);
1444   i::HandleScope scope(isolate);
1445   auto cons = EnsureConstructor(isolate, this);
1446   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler");
1447   auto obj = i::Handle<i::InterceptorInfo>::cast(
1448       isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1449
1450   if (config.getter != 0) SET_FIELD_WRAPPED(obj, set_getter, config.getter);
1451   if (config.setter != 0) SET_FIELD_WRAPPED(obj, set_setter, config.setter);
1452   if (config.query != 0) SET_FIELD_WRAPPED(obj, set_query, config.query);
1453   if (config.deleter != 0) SET_FIELD_WRAPPED(obj, set_deleter, config.deleter);
1454   if (config.enumerator != 0) {
1455     SET_FIELD_WRAPPED(obj, set_enumerator, config.enumerator);
1456   }
1457   obj->set_flags(0);
1458   obj->set_all_can_read(static_cast<int>(config.flags) &
1459                         static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1460
1461   v8::Local<v8::Value> data = config.data;
1462   if (data.IsEmpty()) {
1463     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1464   }
1465   obj->set_data(*Utils::OpenHandle(*data));
1466   cons->set_indexed_property_handler(*obj);
1467 }
1468
1469
1470 void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
1471                                               Local<Value> data) {
1472   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1473   ENTER_V8(isolate);
1474   i::HandleScope scope(isolate);
1475   auto cons = EnsureConstructor(isolate, this);
1476   EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
1477   i::Handle<i::Struct> struct_obj =
1478       isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1479   i::Handle<i::CallHandlerInfo> obj =
1480       i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1481   SET_FIELD_WRAPPED(obj, set_callback, callback);
1482   if (data.IsEmpty()) {
1483     data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1484   }
1485   obj->set_data(*Utils::OpenHandle(*data));
1486   cons->set_instance_call_handler(*obj);
1487 }
1488
1489
1490 int ObjectTemplate::InternalFieldCount() {
1491   return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
1492 }
1493
1494
1495 void ObjectTemplate::SetInternalFieldCount(int value) {
1496   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1497   if (!Utils::ApiCheck(i::Smi::IsValid(value),
1498                        "v8::ObjectTemplate::SetInternalFieldCount()",
1499                        "Invalid internal field count")) {
1500     return;
1501   }
1502   ENTER_V8(isolate);
1503   if (value > 0) {
1504     // The internal field count is set by the constructor function's
1505     // construct code, so we ensure that there is a constructor
1506     // function to do the setting.
1507     EnsureConstructor(isolate, this);
1508   }
1509   Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
1510 }
1511
1512
1513 // --- S c r i p t s ---
1514
1515
1516 // Internally, UnboundScript is a SharedFunctionInfo, and Script is a
1517 // JSFunction.
1518
1519 ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
1520                                        BufferPolicy buffer_policy_)
1521     : data(data_),
1522       length(length_),
1523       rejected(false),
1524       buffer_policy(buffer_policy_) {}
1525
1526
1527 ScriptCompiler::CachedData::~CachedData() {
1528   if (buffer_policy == BufferOwned) {
1529     delete[] data;
1530   }
1531 }
1532
1533
1534 bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; }
1535
1536
1537 void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); }
1538
1539
1540 ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
1541                                                Encoding encoding)
1542     : impl_(new i::StreamedSource(stream, encoding)) {}
1543
1544
1545 ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; }
1546
1547
1548 const ScriptCompiler::CachedData*
1549 ScriptCompiler::StreamedSource::GetCachedData() const {
1550   return impl_->cached_data.get();
1551 }
1552
1553
1554 Local<Script> UnboundScript::BindToCurrentContext() {
1555   i::Handle<i::HeapObject> obj =
1556       i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1557   i::Handle<i::SharedFunctionInfo>
1558       function_info(i::SharedFunctionInfo::cast(*obj), obj->GetIsolate());
1559   i::Isolate* isolate = obj->GetIsolate();
1560
1561   i::ScopeInfo* scope_info = function_info->scope_info();
1562   i::Handle<i::JSReceiver> global(isolate->native_context()->global_object());
1563   for (int i = 0; i < scope_info->StrongModeFreeVariableCount(); ++i) {
1564     i::Handle<i::String> name_string(scope_info->StrongModeFreeVariableName(i));
1565     i::ScriptContextTable::LookupResult result;
1566     i::Handle<i::ScriptContextTable> script_context_table(
1567         isolate->native_context()->script_context_table());
1568     if (!i::ScriptContextTable::Lookup(script_context_table, name_string,
1569                                        &result)) {
1570       i::Handle<i::Name> name(scope_info->StrongModeFreeVariableName(i));
1571       Maybe<bool> has = i::JSReceiver::HasProperty(global, name);
1572       if (has.IsJust() && !has.FromJust()) {
1573         i::PendingCompilationErrorHandler pending_error_handler_;
1574         pending_error_handler_.ReportMessageAt(
1575             scope_info->StrongModeFreeVariableStartPosition(i),
1576             scope_info->StrongModeFreeVariableEndPosition(i),
1577             i::MessageTemplate::kStrongUnboundGlobal, name_string,
1578             i::kReferenceError);
1579         i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1580         pending_error_handler_.ThrowPendingError(isolate, script);
1581         isolate->ReportPendingMessages();
1582         isolate->OptionalRescheduleException(true);
1583         return Local<Script>();
1584       }
1585     }
1586   }
1587   i::Handle<i::JSFunction> function =
1588       obj->GetIsolate()->factory()->NewFunctionFromSharedFunctionInfo(
1589           function_info, isolate->native_context());
1590   return ToApiHandle<Script>(function);
1591 }
1592
1593
1594 int UnboundScript::GetId() {
1595   i::Handle<i::HeapObject> obj =
1596       i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1597   i::Isolate* isolate = obj->GetIsolate();
1598   LOG_API(isolate, "v8::UnboundScript::GetId");
1599   i::HandleScope scope(isolate);
1600   i::Handle<i::SharedFunctionInfo> function_info(
1601       i::SharedFunctionInfo::cast(*obj));
1602   i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1603   return script->id()->value();
1604 }
1605
1606
1607 int UnboundScript::GetLineNumber(int code_pos) {
1608   i::Handle<i::SharedFunctionInfo> obj =
1609       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1610   i::Isolate* isolate = obj->GetIsolate();
1611   LOG_API(isolate, "UnboundScript::GetLineNumber");
1612   if (obj->script()->IsScript()) {
1613     i::Handle<i::Script> script(i::Script::cast(obj->script()));
1614     return i::Script::GetLineNumber(script, code_pos);
1615   } else {
1616     return -1;
1617   }
1618 }
1619
1620
1621 Local<Value> UnboundScript::GetScriptName() {
1622   i::Handle<i::SharedFunctionInfo> obj =
1623       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1624   i::Isolate* isolate = obj->GetIsolate();
1625   LOG_API(isolate, "UnboundScript::GetName");
1626   if (obj->script()->IsScript()) {
1627     i::Object* name = i::Script::cast(obj->script())->name();
1628     return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
1629   } else {
1630     return Local<String>();
1631   }
1632 }
1633
1634
1635 Local<Value> UnboundScript::GetSourceURL() {
1636   i::Handle<i::SharedFunctionInfo> obj =
1637       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1638   i::Isolate* isolate = obj->GetIsolate();
1639   LOG_API(isolate, "UnboundScript::GetSourceURL");
1640   if (obj->script()->IsScript()) {
1641     i::Object* url = i::Script::cast(obj->script())->source_url();
1642     return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1643   } else {
1644     return Local<String>();
1645   }
1646 }
1647
1648
1649 Local<Value> UnboundScript::GetSourceMappingURL() {
1650   i::Handle<i::SharedFunctionInfo> obj =
1651       i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1652   i::Isolate* isolate = obj->GetIsolate();
1653   LOG_API(isolate, "UnboundScript::GetSourceMappingURL");
1654   if (obj->script()->IsScript()) {
1655     i::Object* url = i::Script::cast(obj->script())->source_mapping_url();
1656     return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1657   } else {
1658     return Local<String>();
1659   }
1660 }
1661
1662
1663 MaybeLocal<Value> Script::Run(Local<Context> context) {
1664   PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Script::Run()", Value)
1665   i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
1666   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
1667   auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this));
1668   i::Handle<i::Object> receiver(isolate->global_proxy(), isolate);
1669   Local<Value> result;
1670   has_pending_exception =
1671       !ToLocal<Value>(i::Execution::Call(isolate, fun, receiver, 0, NULL),
1672                       &result);
1673   RETURN_ON_FAILED_EXECUTION(Value);
1674   RETURN_ESCAPED(result);
1675 }
1676
1677
1678 Local<Value> Script::Run() {
1679   auto self = Utils::OpenHandle(this, true);
1680   // If execution is terminating, Compile(..)->Run() requires this
1681   // check.
1682   if (self.is_null()) return Local<Value>();
1683   auto context = ContextFromHeapObject(self);
1684   RETURN_TO_LOCAL_UNCHECKED(Run(context), Value);
1685 }
1686
1687
1688 Local<UnboundScript> Script::GetUnboundScript() {
1689   i::Handle<i::Object> obj = Utils::OpenHandle(this);
1690   return ToApiHandle<UnboundScript>(
1691       i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared()));
1692 }
1693
1694
1695 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal(
1696     Isolate* v8_isolate, Source* source, CompileOptions options,
1697     bool is_module) {
1698   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1699   PREPARE_FOR_EXECUTION_WITH_ISOLATE(
1700       isolate, "v8::ScriptCompiler::CompileUnbound()", UnboundScript);
1701
1702   // Don't try to produce any kind of cache when the debugger is loaded.
1703   if (isolate->debug()->is_loaded() &&
1704       (options == kProduceParserCache || options == kProduceCodeCache)) {
1705     options = kNoCompileOptions;
1706   }
1707
1708   i::ScriptData* script_data = NULL;
1709   if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1710     DCHECK(source->cached_data);
1711     // ScriptData takes care of pointer-aligning the data.
1712     script_data = new i::ScriptData(source->cached_data->data,
1713                                     source->cached_data->length);
1714   }
1715
1716   i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
1717   i::Handle<i::SharedFunctionInfo> result;
1718   {
1719     i::HistogramTimerScope total(isolate->counters()->compile_script(), true);
1720     i::Handle<i::Object> name_obj;
1721     i::Handle<i::Object> source_map_url;
1722     int line_offset = 0;
1723     int column_offset = 0;
1724     if (!source->resource_name.IsEmpty()) {
1725       name_obj = Utils::OpenHandle(*(source->resource_name));
1726     }
1727     if (!source->resource_line_offset.IsEmpty()) {
1728       line_offset = static_cast<int>(source->resource_line_offset->Value());
1729     }
1730     if (!source->resource_column_offset.IsEmpty()) {
1731       column_offset =
1732           static_cast<int>(source->resource_column_offset->Value());
1733     }
1734     if (!source->source_map_url.IsEmpty()) {
1735       source_map_url = Utils::OpenHandle(*(source->source_map_url));
1736     }
1737     result = i::Compiler::CompileScript(
1738         str, name_obj, line_offset, column_offset, source->resource_options,
1739         source_map_url, isolate->native_context(), NULL, &script_data, options,
1740         i::NOT_NATIVES_CODE, is_module);
1741     has_pending_exception = result.is_null();
1742     if (has_pending_exception && script_data != NULL) {
1743       // This case won't happen during normal operation; we have compiled
1744       // successfully and produced cached data, and but the second compilation
1745       // of the same source code fails.
1746       delete script_data;
1747       script_data = NULL;
1748     }
1749     RETURN_ON_FAILED_EXECUTION(UnboundScript);
1750
1751     if ((options == kProduceParserCache || options == kProduceCodeCache) &&
1752         script_data != NULL) {
1753       // script_data now contains the data that was generated. source will
1754       // take the ownership.
1755       source->cached_data = new CachedData(
1756           script_data->data(), script_data->length(), CachedData::BufferOwned);
1757       script_data->ReleaseDataOwnership();
1758     } else if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1759       source->cached_data->rejected = script_data->rejected();
1760     }
1761     delete script_data;
1762   }
1763   RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
1764 }
1765
1766
1767 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript(
1768     Isolate* v8_isolate, Source* source, CompileOptions options) {
1769   return CompileUnboundInternal(v8_isolate, source, options, false);
1770 }
1771
1772
1773 Local<UnboundScript> ScriptCompiler::CompileUnbound(Isolate* v8_isolate,
1774                                                     Source* source,
1775                                                     CompileOptions options) {
1776   RETURN_TO_LOCAL_UNCHECKED(
1777       CompileUnboundInternal(v8_isolate, source, options, false),
1778       UnboundScript);
1779 }
1780
1781
1782 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1783                                            Source* source,
1784                                            CompileOptions options) {
1785   auto isolate = context->GetIsolate();
1786   auto maybe = CompileUnboundInternal(isolate, source, options, false);
1787   Local<UnboundScript> result;
1788   if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
1789   v8::Context::Scope scope(context);
1790   return result->BindToCurrentContext();
1791 }
1792
1793
1794 Local<Script> ScriptCompiler::Compile(
1795     Isolate* v8_isolate,
1796     Source* source,
1797     CompileOptions options) {
1798   auto context = v8_isolate->GetCurrentContext();
1799   RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, options), Script);
1800 }
1801
1802
1803 MaybeLocal<Script> ScriptCompiler::CompileModule(Local<Context> context,
1804                                                  Source* source,
1805                                                  CompileOptions options) {
1806   CHECK(i::FLAG_harmony_modules);
1807   auto isolate = context->GetIsolate();
1808   auto maybe = CompileUnboundInternal(isolate, source, options, true);
1809   Local<UnboundScript> generic;
1810   if (!maybe.ToLocal(&generic)) return MaybeLocal<Script>();
1811   v8::Context::Scope scope(context);
1812   return generic->BindToCurrentContext();
1813 }
1814
1815
1816 Local<Script> ScriptCompiler::CompileModule(Isolate* v8_isolate, Source* source,
1817                                             CompileOptions options) {
1818   auto context = v8_isolate->GetCurrentContext();
1819   RETURN_TO_LOCAL_UNCHECKED(CompileModule(context, source, options), Script);
1820 }
1821
1822
1823 class IsIdentifierHelper {
1824  public:
1825   IsIdentifierHelper() : is_identifier_(false), first_char_(true) {}
1826
1827   bool Check(i::String* string) {
1828     i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
1829     if (cons_string == NULL) return is_identifier_;
1830     // We don't support cons strings here.
1831     return false;
1832   }
1833   void VisitOneByteString(const uint8_t* chars, int length) {
1834     for (int i = 0; i < length; ++i) {
1835       if (first_char_) {
1836         first_char_ = false;
1837         is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1838       } else {
1839         is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1840       }
1841     }
1842   }
1843   void VisitTwoByteString(const uint16_t* chars, int length) {
1844     for (int i = 0; i < length; ++i) {
1845       if (first_char_) {
1846         first_char_ = false;
1847         is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1848       } else {
1849         is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1850       }
1851     }
1852   }
1853
1854  private:
1855   bool is_identifier_;
1856   bool first_char_;
1857   i::UnicodeCache unicode_cache_;
1858   DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper);
1859 };
1860
1861
1862 MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext(
1863     Local<Context> v8_context, Source* source, size_t arguments_count,
1864     Local<String> arguments[], size_t context_extension_count,
1865     Local<Object> context_extensions[]) {
1866   PREPARE_FOR_EXECUTION(
1867       v8_context, "v8::ScriptCompiler::CompileFunctionInContext()", Function);
1868   i::Handle<i::String> source_string;
1869   auto factory = isolate->factory();
1870   if (arguments_count) {
1871     source_string = factory->NewStringFromStaticChars("(function(");
1872     for (size_t i = 0; i < arguments_count; ++i) {
1873       IsIdentifierHelper helper;
1874       if (!helper.Check(*Utils::OpenHandle(*arguments[i]))) {
1875         return Local<Function>();
1876       }
1877       has_pending_exception =
1878           !factory->NewConsString(source_string,
1879                                   Utils::OpenHandle(*arguments[i]))
1880                .ToHandle(&source_string);
1881       RETURN_ON_FAILED_EXECUTION(Function);
1882       if (i + 1 == arguments_count) continue;
1883       has_pending_exception =
1884           !factory->NewConsString(source_string,
1885                                   factory->LookupSingleCharacterStringFromCode(
1886                                       ',')).ToHandle(&source_string);
1887       RETURN_ON_FAILED_EXECUTION(Function);
1888     }
1889     auto brackets = factory->NewStringFromStaticChars("){");
1890     has_pending_exception = !factory->NewConsString(source_string, brackets)
1891                                  .ToHandle(&source_string);
1892     RETURN_ON_FAILED_EXECUTION(Function);
1893   } else {
1894     source_string = factory->NewStringFromStaticChars("(function(){");
1895   }
1896
1897   int scope_position = source_string->length();
1898   has_pending_exception =
1899       !factory->NewConsString(source_string,
1900                               Utils::OpenHandle(*source->source_string))
1901            .ToHandle(&source_string);
1902   RETURN_ON_FAILED_EXECUTION(Function);
1903   // Include \n in case the source contains a line end comment.
1904   auto brackets = factory->NewStringFromStaticChars("\n})");
1905   has_pending_exception =
1906       !factory->NewConsString(source_string, brackets).ToHandle(&source_string);
1907   RETURN_ON_FAILED_EXECUTION(Function);
1908
1909   i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
1910   i::Handle<i::SharedFunctionInfo> outer_info(context->closure()->shared(),
1911                                               isolate);
1912   for (size_t i = 0; i < context_extension_count; ++i) {
1913     i::Handle<i::JSObject> extension =
1914         Utils::OpenHandle(*context_extensions[i]);
1915     i::Handle<i::JSFunction> closure(context->closure(), isolate);
1916     context = factory->NewWithContext(closure, context, extension);
1917   }
1918
1919   i::Handle<i::JSFunction> fun;
1920   has_pending_exception =
1921       !i::Compiler::GetFunctionFromEval(
1922            source_string, outer_info, context, i::SLOPPY,
1923            i::ONLY_SINGLE_FUNCTION_LITERAL, scope_position).ToHandle(&fun);
1924   RETURN_ON_FAILED_EXECUTION(Function);
1925
1926   i::Handle<i::Object> result;
1927   has_pending_exception =
1928       !i::Execution::Call(isolate, fun,
1929                           Utils::OpenHandle(*v8_context->Global()), 0,
1930                           nullptr).ToHandle(&result);
1931   RETURN_ON_FAILED_EXECUTION(Function);
1932   RETURN_ESCAPED(Utils::ToLocal(i::Handle<i::JSFunction>::cast(result)));
1933 }
1934
1935
1936 Local<Function> ScriptCompiler::CompileFunctionInContext(
1937     Isolate* v8_isolate, Source* source, Local<Context> v8_context,
1938     size_t arguments_count, Local<String> arguments[],
1939     size_t context_extension_count, Local<Object> context_extensions[]) {
1940   RETURN_TO_LOCAL_UNCHECKED(
1941       CompileFunctionInContext(v8_context, source, arguments_count, arguments,
1942                                context_extension_count, context_extensions),
1943       Function);
1944 }
1945
1946
1947 ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript(
1948     Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
1949   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1950   return new i::BackgroundParsingTask(source->impl(), options,
1951                                       i::FLAG_stack_size, isolate);
1952 }
1953
1954
1955 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1956                                            StreamedSource* v8_source,
1957                                            Local<String> full_source_string,
1958                                            const ScriptOrigin& origin) {
1959   PREPARE_FOR_EXECUTION(context, "v8::ScriptCompiler::Compile()", Script);
1960   i::StreamedSource* source = v8_source->impl();
1961   i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
1962   i::Handle<i::Script> script = isolate->factory()->NewScript(str);
1963   if (!origin.ResourceName().IsEmpty()) {
1964     script->set_name(*Utils::OpenHandle(*(origin.ResourceName())));
1965   }
1966   if (!origin.ResourceLineOffset().IsEmpty()) {
1967     script->set_line_offset(i::Smi::FromInt(
1968         static_cast<int>(origin.ResourceLineOffset()->Value())));
1969   }
1970   if (!origin.ResourceColumnOffset().IsEmpty()) {
1971     script->set_column_offset(i::Smi::FromInt(
1972         static_cast<int>(origin.ResourceColumnOffset()->Value())));
1973   }
1974   script->set_origin_options(origin.Options());
1975   if (!origin.SourceMapUrl().IsEmpty()) {
1976     script->set_source_mapping_url(
1977         *Utils::OpenHandle(*(origin.SourceMapUrl())));
1978   }
1979
1980   source->info->set_script(script);
1981   source->info->set_context(isolate->native_context());
1982
1983   // Do the parsing tasks which need to be done on the main thread. This will
1984   // also handle parse errors.
1985   source->parser->Internalize(isolate, script,
1986                               source->info->function() == nullptr);
1987   source->parser->HandleSourceURLComments(isolate, script);
1988
1989   i::Handle<i::SharedFunctionInfo> result;
1990   if (source->info->function() != nullptr) {
1991     // Parsing has succeeded.
1992     result = i::Compiler::CompileStreamedScript(script, source->info.get(),
1993                                                 str->length());
1994   }
1995   has_pending_exception = result.is_null();
1996   if (has_pending_exception) isolate->ReportPendingMessages();
1997   RETURN_ON_FAILED_EXECUTION(Script);
1998
1999   source->info->clear_script();  // because script goes out of scope.
2000
2001   Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
2002   if (generic.IsEmpty()) return Local<Script>();
2003   Local<Script> bound = generic->BindToCurrentContext();
2004   if (bound.IsEmpty()) return Local<Script>();
2005   RETURN_ESCAPED(bound);
2006 }
2007
2008
2009 Local<Script> ScriptCompiler::Compile(Isolate* v8_isolate,
2010                                       StreamedSource* v8_source,
2011                                       Local<String> full_source_string,
2012                                       const ScriptOrigin& origin) {
2013   auto context = v8_isolate->GetCurrentContext();
2014   RETURN_TO_LOCAL_UNCHECKED(
2015       Compile(context, v8_source, full_source_string, origin), Script);
2016 }
2017
2018
2019 uint32_t ScriptCompiler::CachedDataVersionTag() {
2020   return static_cast<uint32_t>(base::hash_combine(
2021       internal::Version::Hash(), internal::FlagList::Hash(),
2022       static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures())));
2023 }
2024
2025
2026 MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source,
2027                                    ScriptOrigin* origin) {
2028   if (origin) {
2029     ScriptCompiler::Source script_source(source, *origin);
2030     return ScriptCompiler::Compile(context, &script_source);
2031   }
2032   ScriptCompiler::Source script_source(source);
2033   return ScriptCompiler::Compile(context, &script_source);
2034 }
2035
2036
2037 Local<Script> Script::Compile(v8::Local<String> source,
2038                               v8::ScriptOrigin* origin) {
2039   auto str = Utils::OpenHandle(*source);
2040   auto context = ContextFromHeapObject(str);
2041   RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, origin), Script);
2042 }
2043
2044
2045 Local<Script> Script::Compile(v8::Local<String> source,
2046                               v8::Local<String> file_name) {
2047   auto str = Utils::OpenHandle(*source);
2048   auto context = ContextFromHeapObject(str);
2049   ScriptOrigin origin(file_name);
2050   return Compile(context, source, &origin).FromMaybe(Local<Script>());
2051 }
2052
2053
2054 // --- E x c e p t i o n s ---
2055
2056
2057 v8::TryCatch::TryCatch()
2058     : isolate_(i::Isolate::Current()),
2059       next_(isolate_->try_catch_handler()),
2060       is_verbose_(false),
2061       can_continue_(true),
2062       capture_message_(true),
2063       rethrow_(false),
2064       has_terminated_(false) {
2065   ResetInternal();
2066   // Special handling for simulators which have a separate JS stack.
2067   js_stack_comparable_address_ =
2068       reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2069           v8::internal::GetCurrentStackPosition()));
2070   isolate_->RegisterTryCatchHandler(this);
2071 }
2072
2073
2074 v8::TryCatch::TryCatch(v8::Isolate* isolate)
2075     : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
2076       next_(isolate_->try_catch_handler()),
2077       is_verbose_(false),
2078       can_continue_(true),
2079       capture_message_(true),
2080       rethrow_(false),
2081       has_terminated_(false) {
2082   ResetInternal();
2083   // Special handling for simulators which have a separate JS stack.
2084   js_stack_comparable_address_ =
2085       reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2086           v8::internal::GetCurrentStackPosition()));
2087   isolate_->RegisterTryCatchHandler(this);
2088 }
2089
2090
2091 v8::TryCatch::~TryCatch() {
2092   if (rethrow_) {
2093     v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
2094     v8::HandleScope scope(isolate);
2095     v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
2096     if (HasCaught() && capture_message_) {
2097       // If an exception was caught and rethrow_ is indicated, the saved
2098       // message, script, and location need to be restored to Isolate TLS
2099       // for reuse.  capture_message_ needs to be disabled so that Throw()
2100       // does not create a new message.
2101       isolate_->thread_local_top()->rethrowing_message_ = true;
2102       isolate_->RestorePendingMessageFromTryCatch(this);
2103     }
2104     isolate_->UnregisterTryCatchHandler(this);
2105     v8::internal::SimulatorStack::UnregisterCTryCatch();
2106     reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
2107     DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
2108   } else {
2109     if (HasCaught() && isolate_->has_scheduled_exception()) {
2110       // If an exception was caught but is still scheduled because no API call
2111       // promoted it, then it is canceled to prevent it from being propagated.
2112       // Note that this will not cancel termination exceptions.
2113       isolate_->CancelScheduledExceptionFromTryCatch(this);
2114     }
2115     isolate_->UnregisterTryCatchHandler(this);
2116     v8::internal::SimulatorStack::UnregisterCTryCatch();
2117   }
2118 }
2119
2120
2121 bool v8::TryCatch::HasCaught() const {
2122   return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
2123 }
2124
2125
2126 bool v8::TryCatch::CanContinue() const {
2127   return can_continue_;
2128 }
2129
2130
2131 bool v8::TryCatch::HasTerminated() const {
2132   return has_terminated_;
2133 }
2134
2135
2136 v8::Local<v8::Value> v8::TryCatch::ReThrow() {
2137   if (!HasCaught()) return v8::Local<v8::Value>();
2138   rethrow_ = true;
2139   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
2140 }
2141
2142
2143 v8::Local<Value> v8::TryCatch::Exception() const {
2144   if (HasCaught()) {
2145     // Check for out of memory exception.
2146     i::Object* exception = reinterpret_cast<i::Object*>(exception_);
2147     return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
2148   } else {
2149     return v8::Local<Value>();
2150   }
2151 }
2152
2153
2154 MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const {
2155   if (!HasCaught()) return v8::Local<Value>();
2156   i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
2157   if (!raw_obj->IsJSObject()) return v8::Local<Value>();
2158   PREPARE_FOR_EXECUTION(context, "v8::TryCatch::StackTrace", Value);
2159   i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
2160   i::Handle<i::String> name = isolate->factory()->stack_string();
2161   Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
2162   has_pending_exception = !maybe.IsJust();
2163   RETURN_ON_FAILED_EXECUTION(Value);
2164   if (!maybe.FromJust()) return v8::Local<Value>();
2165   Local<Value> result;
2166   has_pending_exception =
2167       !ToLocal<Value>(i::Object::GetProperty(obj, name), &result);
2168   RETURN_ON_FAILED_EXECUTION(Value);
2169   RETURN_ESCAPED(result);
2170 }
2171
2172
2173 v8::Local<Value> v8::TryCatch::StackTrace() const {
2174   auto context = reinterpret_cast<v8::Isolate*>(isolate_)->GetCurrentContext();
2175   RETURN_TO_LOCAL_UNCHECKED(StackTrace(context), Value);
2176 }
2177
2178
2179 v8::Local<v8::Message> v8::TryCatch::Message() const {
2180   i::Object* message = reinterpret_cast<i::Object*>(message_obj_);
2181   DCHECK(message->IsJSMessageObject() || message->IsTheHole());
2182   if (HasCaught() && !message->IsTheHole()) {
2183     return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
2184   } else {
2185     return v8::Local<v8::Message>();
2186   }
2187 }
2188
2189
2190 void v8::TryCatch::Reset() {
2191   if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
2192     // If an exception was caught but is still scheduled because no API call
2193     // promoted it, then it is canceled to prevent it from being propagated.
2194     // Note that this will not cancel termination exceptions.
2195     isolate_->CancelScheduledExceptionFromTryCatch(this);
2196   }
2197   ResetInternal();
2198 }
2199
2200
2201 void v8::TryCatch::ResetInternal() {
2202   i::Object* the_hole = isolate_->heap()->the_hole_value();
2203   exception_ = the_hole;
2204   message_obj_ = the_hole;
2205 }
2206
2207
2208 void v8::TryCatch::SetVerbose(bool value) {
2209   is_verbose_ = value;
2210 }
2211
2212
2213 void v8::TryCatch::SetCaptureMessage(bool value) {
2214   capture_message_ = value;
2215 }
2216
2217
2218 // --- M e s s a g e ---
2219
2220
2221 Local<String> Message::Get() const {
2222   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2223   ENTER_V8(isolate);
2224   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2225   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2226   i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
2227   Local<String> result = Utils::ToLocal(raw_result);
2228   return scope.Escape(result);
2229 }
2230
2231
2232 ScriptOrigin Message::GetScriptOrigin() const {
2233   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2234   auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2235   auto script_wraper = i::Handle<i::Object>(message->script(), isolate);
2236   auto script_value = i::Handle<i::JSValue>::cast(script_wraper);
2237   i::Handle<i::Script> script(i::Script::cast(script_value->value()));
2238   return GetScriptOriginForScript(isolate, script);
2239 }
2240
2241
2242 v8::Local<Value> Message::GetScriptResourceName() const {
2243   return GetScriptOrigin().ResourceName();
2244 }
2245
2246
2247 v8::Local<v8::StackTrace> Message::GetStackTrace() const {
2248   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2249   ENTER_V8(isolate);
2250   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2251   auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2252   i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
2253   if (!stackFramesObj->IsJSArray()) return v8::Local<v8::StackTrace>();
2254   auto stackTrace = i::Handle<i::JSArray>::cast(stackFramesObj);
2255   return scope.Escape(Utils::StackTraceToLocal(stackTrace));
2256 }
2257
2258
2259 MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
2260     i::Isolate* isolate, const char* name, i::Handle<i::Object> recv, int argc,
2261     i::Handle<i::Object> argv[]) {
2262   i::Handle<i::Object> object_fun =
2263       i::Object::GetProperty(
2264           isolate, isolate->js_builtins_object(), name).ToHandleChecked();
2265   i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(object_fun);
2266   return i::Execution::Call(isolate, fun, recv, argc, argv);
2267 }
2268
2269
2270 MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
2271     i::Isolate* isolate, const char* name, i::Handle<i::Object> data) {
2272   i::Handle<i::Object> argv[] = { data };
2273   return CallV8HeapFunction(isolate, name, isolate->js_builtins_object(),
2274                             arraysize(argv), argv);
2275 }
2276
2277
2278 Maybe<int> Message::GetLineNumber(Local<Context> context) const {
2279   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetLineNumber()", int);
2280   i::Handle<i::Object> result;
2281   has_pending_exception =
2282       !CallV8HeapFunction(isolate, "$messageGetLineNumber",
2283                           Utils::OpenHandle(this)).ToHandle(&result);
2284   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2285   return Just(static_cast<int>(result->Number()));
2286 }
2287
2288
2289 int Message::GetLineNumber() const {
2290   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2291   return GetLineNumber(context).FromMaybe(0);
2292 }
2293
2294
2295 int Message::GetStartPosition() const {
2296   auto self = Utils::OpenHandle(this);
2297   return self->start_position();
2298 }
2299
2300
2301 int Message::GetEndPosition() const {
2302   auto self = Utils::OpenHandle(this);
2303   return self->end_position();
2304 }
2305
2306
2307 Maybe<int> Message::GetStartColumn(Local<Context> context) const {
2308   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetStartColumn()",
2309                                   int);
2310   auto self = Utils::OpenHandle(this);
2311   i::Handle<i::Object> start_col_obj;
2312   has_pending_exception =
2313       !CallV8HeapFunction(isolate, "$messageGetPositionInLine", self)
2314            .ToHandle(&start_col_obj);
2315   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2316   return Just(static_cast<int>(start_col_obj->Number()));
2317 }
2318
2319
2320 int Message::GetStartColumn() const {
2321   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2322   const int default_value = kNoColumnInfo;
2323   return GetStartColumn(context).FromMaybe(default_value);
2324 }
2325
2326
2327 Maybe<int> Message::GetEndColumn(Local<Context> context) const {
2328   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetEndColumn()", int);
2329   auto self = Utils::OpenHandle(this);
2330   i::Handle<i::Object> start_col_obj;
2331   has_pending_exception =
2332       !CallV8HeapFunction(isolate, "$messageGetPositionInLine", self)
2333            .ToHandle(&start_col_obj);
2334   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2335   int start = self->start_position();
2336   int end = self->end_position();
2337   return Just(static_cast<int>(start_col_obj->Number()) + (end - start));
2338 }
2339
2340
2341 int Message::GetEndColumn() const {
2342   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2343   const int default_value = kNoColumnInfo;
2344   return GetEndColumn(context).FromMaybe(default_value);
2345 }
2346
2347
2348 bool Message::IsSharedCrossOrigin() const {
2349   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2350   ENTER_V8(isolate);
2351   auto self = Utils::OpenHandle(this);
2352   auto script = i::Handle<i::JSValue>::cast(
2353       i::Handle<i::Object>(self->script(), isolate));
2354   return i::Script::cast(script->value())
2355       ->origin_options()
2356       .IsSharedCrossOrigin();
2357 }
2358
2359 bool Message::IsOpaque() const {
2360   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2361   ENTER_V8(isolate);
2362   auto self = Utils::OpenHandle(this);
2363   auto script = i::Handle<i::JSValue>::cast(
2364       i::Handle<i::Object>(self->script(), isolate));
2365   return i::Script::cast(script->value())->origin_options().IsOpaque();
2366 }
2367
2368
2369 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
2370   PREPARE_FOR_EXECUTION(context, "v8::Message::GetSourceLine()", String);
2371   i::Handle<i::Object> result;
2372   has_pending_exception =
2373       !CallV8HeapFunction(isolate, "$messageGetSourceLine",
2374                           Utils::OpenHandle(this)).ToHandle(&result);
2375   RETURN_ON_FAILED_EXECUTION(String);
2376   Local<String> str;
2377   if (result->IsString()) {
2378     str = Utils::ToLocal(i::Handle<i::String>::cast(result));
2379   }
2380   RETURN_ESCAPED(str);
2381 }
2382
2383
2384 Local<String> Message::GetSourceLine() const {
2385   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2386   RETURN_TO_LOCAL_UNCHECKED(GetSourceLine(context), String)
2387 }
2388
2389
2390 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
2391   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2392   ENTER_V8(i_isolate);
2393   i_isolate->PrintCurrentStackTrace(out);
2394 }
2395
2396
2397 // --- S t a c k T r a c e ---
2398
2399 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
2400   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2401   ENTER_V8(isolate);
2402   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2403   auto self = Utils::OpenHandle(this);
2404   auto obj = i::Object::GetElement(isolate, self, index).ToHandleChecked();
2405   auto jsobj = i::Handle<i::JSObject>::cast(obj);
2406   return scope.Escape(Utils::StackFrameToLocal(jsobj));
2407 }
2408
2409
2410 int StackTrace::GetFrameCount() const {
2411   return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
2412 }
2413
2414
2415 Local<Array> StackTrace::AsArray() {
2416   return Utils::ToLocal(Utils::OpenHandle(this));
2417 }
2418
2419
2420 Local<StackTrace> StackTrace::CurrentStackTrace(
2421     Isolate* isolate,
2422     int frame_limit,
2423     StackTraceOptions options) {
2424   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2425   ENTER_V8(i_isolate);
2426   // TODO(dcarney): remove when ScriptDebugServer is fixed.
2427   options = static_cast<StackTraceOptions>(
2428       static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins);
2429   i::Handle<i::JSArray> stackTrace =
2430       i_isolate->CaptureCurrentStackTrace(frame_limit, options);
2431   return Utils::StackTraceToLocal(stackTrace);
2432 }
2433
2434
2435 // --- S t a c k F r a m e ---
2436
2437 static int getIntProperty(const StackFrame* f, const char* propertyName,
2438                           int defaultValue) {
2439   i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2440   ENTER_V8(isolate);
2441   i::HandleScope scope(isolate);
2442   i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2443   i::Handle<i::Object> obj =
2444       i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2445   return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue;
2446 }
2447
2448
2449 int StackFrame::GetLineNumber() const {
2450   return getIntProperty(this, "lineNumber", Message::kNoLineNumberInfo);
2451 }
2452
2453
2454 int StackFrame::GetColumn() const {
2455   return getIntProperty(this, "column", Message::kNoColumnInfo);
2456 }
2457
2458
2459 int StackFrame::GetScriptId() const {
2460   return getIntProperty(this, "scriptId", Message::kNoScriptIdInfo);
2461 }
2462
2463
2464 static Local<String> getStringProperty(const StackFrame* f,
2465                                        const char* propertyName) {
2466   i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2467   ENTER_V8(isolate);
2468   EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2469   i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2470   i::Handle<i::Object> obj =
2471       i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2472   return obj->IsString()
2473              ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2474              : Local<String>();
2475 }
2476
2477
2478 Local<String> StackFrame::GetScriptName() const {
2479   return getStringProperty(this, "scriptName");
2480 }
2481
2482
2483 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2484   return getStringProperty(this, "scriptNameOrSourceURL");
2485 }
2486
2487
2488 Local<String> StackFrame::GetFunctionName() const {
2489   return getStringProperty(this, "functionName");
2490 }
2491
2492
2493 static bool getBoolProperty(const StackFrame* f, const char* propertyName) {
2494   i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2495   ENTER_V8(isolate);
2496   i::HandleScope scope(isolate);
2497   i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2498   i::Handle<i::Object> obj =
2499       i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2500   return obj->IsTrue();
2501 }
2502
2503 bool StackFrame::IsEval() const { return getBoolProperty(this, "isEval"); }
2504
2505
2506 bool StackFrame::IsConstructor() const {
2507   return getBoolProperty(this, "isConstructor");
2508 }
2509
2510
2511 // --- N a t i v e W e a k M a p ---
2512
2513 Local<NativeWeakMap> NativeWeakMap::New(Isolate* v8_isolate) {
2514   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2515   ENTER_V8(isolate);
2516   i::Handle<i::JSWeakMap> weakmap = isolate->factory()->NewJSWeakMap();
2517   i::Runtime::WeakCollectionInitialize(isolate, weakmap);
2518   return Utils::NativeWeakMapToLocal(weakmap);
2519 }
2520
2521
2522 void NativeWeakMap::Set(Local<Value> v8_key, Local<Value> v8_value) {
2523   i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2524   i::Isolate* isolate = weak_collection->GetIsolate();
2525   ENTER_V8(isolate);
2526   i::HandleScope scope(isolate);
2527   i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2528   i::Handle<i::Object> value = Utils::OpenHandle(*v8_value);
2529   if (!key->IsJSReceiver() && !key->IsSymbol()) {
2530     DCHECK(false);
2531     return;
2532   }
2533   i::Handle<i::ObjectHashTable> table(
2534       i::ObjectHashTable::cast(weak_collection->table()));
2535   if (!table->IsKey(*key)) {
2536     DCHECK(false);
2537     return;
2538   }
2539   int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value();
2540   i::Runtime::WeakCollectionSet(weak_collection, key, value, hash);
2541 }
2542
2543
2544 Local<Value> NativeWeakMap::Get(Local<Value> v8_key) {
2545   i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2546   i::Isolate* isolate = weak_collection->GetIsolate();
2547   ENTER_V8(isolate);
2548   i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2549   if (!key->IsJSReceiver() && !key->IsSymbol()) {
2550     DCHECK(false);
2551     return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2552   }
2553   i::Handle<i::ObjectHashTable> table(
2554       i::ObjectHashTable::cast(weak_collection->table()));
2555   if (!table->IsKey(*key)) {
2556     DCHECK(false);
2557     return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2558   }
2559   i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2560   if (lookup->IsTheHole())
2561     return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2562   return Utils::ToLocal(lookup);
2563 }
2564
2565
2566 bool NativeWeakMap::Has(Local<Value> v8_key) {
2567   i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2568   i::Isolate* isolate = weak_collection->GetIsolate();
2569   ENTER_V8(isolate);
2570   i::HandleScope scope(isolate);
2571   i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2572   if (!key->IsJSReceiver() && !key->IsSymbol()) {
2573     DCHECK(false);
2574     return false;
2575   }
2576   i::Handle<i::ObjectHashTable> table(
2577       i::ObjectHashTable::cast(weak_collection->table()));
2578   if (!table->IsKey(*key)) {
2579     DCHECK(false);
2580     return false;
2581   }
2582   i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2583   return !lookup->IsTheHole();
2584 }
2585
2586
2587 bool NativeWeakMap::Delete(Local<Value> v8_key) {
2588   i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2589   i::Isolate* isolate = weak_collection->GetIsolate();
2590   ENTER_V8(isolate);
2591   i::HandleScope scope(isolate);
2592   i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2593   if (!key->IsJSReceiver() && !key->IsSymbol()) {
2594     DCHECK(false);
2595     return false;
2596   }
2597   i::Handle<i::ObjectHashTable> table(
2598       i::ObjectHashTable::cast(weak_collection->table()));
2599   if (!table->IsKey(*key)) {
2600     DCHECK(false);
2601     return false;
2602   }
2603   return i::Runtime::WeakCollectionDelete(weak_collection, key);
2604 }
2605
2606
2607 // --- J S O N ---
2608
2609 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) {
2610   auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2611   PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, "JSON::Parse", Value);
2612   i::Handle<i::String> string = Utils::OpenHandle(*json_string);
2613   i::Handle<i::String> source = i::String::Flatten(string);
2614   auto maybe = source->IsSeqOneByteString()
2615                    ? i::JsonParser<true>::Parse(source)
2616                    : i::JsonParser<false>::Parse(source);
2617   Local<Value> result;
2618   has_pending_exception = !ToLocal<Value>(maybe, &result);
2619   RETURN_ON_FAILED_EXECUTION(Value);
2620   RETURN_ESCAPED(result);
2621 }
2622
2623
2624 Local<Value> JSON::Parse(Local<String> json_string) {
2625   auto isolate = reinterpret_cast<v8::Isolate*>(
2626       Utils::OpenHandle(*json_string)->GetIsolate());
2627   RETURN_TO_LOCAL_UNCHECKED(Parse(isolate, json_string), Value);
2628 }
2629
2630
2631 // --- D a t a ---
2632
2633 bool Value::FullIsUndefined() const {
2634   bool result = Utils::OpenHandle(this)->IsUndefined();
2635   DCHECK_EQ(result, QuickIsUndefined());
2636   return result;
2637 }
2638
2639
2640 bool Value::FullIsNull() const {
2641   bool result = Utils::OpenHandle(this)->IsNull();
2642   DCHECK_EQ(result, QuickIsNull());
2643   return result;
2644 }
2645
2646
2647 bool Value::IsTrue() const {
2648   return Utils::OpenHandle(this)->IsTrue();
2649 }
2650
2651
2652 bool Value::IsFalse() const {
2653   return Utils::OpenHandle(this)->IsFalse();
2654 }
2655
2656
2657 bool Value::IsFunction() const {
2658   return Utils::OpenHandle(this)->IsJSFunction();
2659 }
2660
2661
2662 bool Value::IsName() const {
2663   return Utils::OpenHandle(this)->IsName();
2664 }
2665
2666
2667 bool Value::FullIsString() const {
2668   bool result = Utils::OpenHandle(this)->IsString();
2669   DCHECK_EQ(result, QuickIsString());
2670   return result;
2671 }
2672
2673
2674 bool Value::IsSymbol() const {
2675   return Utils::OpenHandle(this)->IsSymbol();
2676 }
2677
2678
2679 bool Value::IsArray() const {
2680   return Utils::OpenHandle(this)->IsJSArray();
2681 }
2682
2683
2684 bool Value::IsArrayBuffer() const {
2685   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2686   return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
2687 }
2688
2689
2690 bool Value::IsArrayBufferView() const {
2691   return Utils::OpenHandle(this)->IsJSArrayBufferView();
2692 }
2693
2694
2695 bool Value::IsTypedArray() const {
2696   return Utils::OpenHandle(this)->IsJSTypedArray();
2697 }
2698
2699
2700 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype, size)              \
2701   bool Value::Is##Type##Array() const {                                      \
2702     i::Handle<i::Object> obj = Utils::OpenHandle(this);                      \
2703     return obj->IsJSTypedArray() &&                                          \
2704            i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
2705   }
2706
2707
2708 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
2709
2710 #undef VALUE_IS_TYPED_ARRAY
2711
2712
2713 bool Value::IsDataView() const {
2714   return Utils::OpenHandle(this)->IsJSDataView();
2715 }
2716
2717
2718 bool Value::IsSharedArrayBuffer() const {
2719   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2720   return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
2721 }
2722
2723
2724 bool Value::IsObject() const {
2725   return Utils::OpenHandle(this)->IsJSObject();
2726 }
2727
2728
2729 bool Value::IsNumber() const {
2730   return Utils::OpenHandle(this)->IsNumber();
2731 }
2732
2733
2734 #define VALUE_IS_SPECIFIC_TYPE(Type, Class)                            \
2735   bool Value::Is##Type() const {                                       \
2736     i::Handle<i::Object> obj = Utils::OpenHandle(this);                \
2737     if (!obj->IsHeapObject()) return false;                            \
2738     i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();     \
2739     return obj->HasSpecificClassOf(isolate->heap()->Class##_string()); \
2740   }
2741
2742 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, Arguments)
2743 VALUE_IS_SPECIFIC_TYPE(BooleanObject, Boolean)
2744 VALUE_IS_SPECIFIC_TYPE(NumberObject, Number)
2745 VALUE_IS_SPECIFIC_TYPE(StringObject, String)
2746 VALUE_IS_SPECIFIC_TYPE(SymbolObject, Symbol)
2747 VALUE_IS_SPECIFIC_TYPE(Date, Date)
2748 VALUE_IS_SPECIFIC_TYPE(Map, Map)
2749 VALUE_IS_SPECIFIC_TYPE(Set, Set)
2750 VALUE_IS_SPECIFIC_TYPE(WeakMap, WeakMap)
2751 VALUE_IS_SPECIFIC_TYPE(WeakSet, WeakSet)
2752
2753 #undef VALUE_IS_SPECIFIC_TYPE
2754
2755
2756 bool Value::IsBoolean() const {
2757   return Utils::OpenHandle(this)->IsBoolean();
2758 }
2759
2760
2761 bool Value::IsExternal() const {
2762   return Utils::OpenHandle(this)->IsExternal();
2763 }
2764
2765
2766 bool Value::IsInt32() const {
2767   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2768   if (obj->IsSmi()) return true;
2769   if (obj->IsNumber()) {
2770     return i::IsInt32Double(obj->Number());
2771   }
2772   return false;
2773 }
2774
2775
2776 bool Value::IsUint32() const {
2777   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2778   if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2779   if (obj->IsNumber()) {
2780     double value = obj->Number();
2781     return !i::IsMinusZero(value) &&
2782         value >= 0 &&
2783         value <= i::kMaxUInt32 &&
2784         value == i::FastUI2D(i::FastD2UI(value));
2785   }
2786   return false;
2787 }
2788
2789
2790 static bool CheckConstructor(i::Isolate* isolate,
2791                              i::Handle<i::JSObject> obj,
2792                              const char* class_name) {
2793   i::Handle<i::Object> constr(obj->map()->GetConstructor(), isolate);
2794   if (!constr->IsJSFunction()) return false;
2795   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(constr);
2796   return func->shared()->native() && constr.is_identical_to(
2797       i::Object::GetProperty(isolate,
2798                              isolate->js_builtins_object(),
2799                              class_name).ToHandleChecked());
2800 }
2801
2802
2803 bool Value::IsNativeError() const {
2804   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2805   if (obj->IsJSObject()) {
2806     i::Handle<i::JSObject> js_obj(i::JSObject::cast(*obj));
2807     i::Isolate* isolate = js_obj->GetIsolate();
2808     return CheckConstructor(isolate, js_obj, "$Error") ||
2809         CheckConstructor(isolate, js_obj, "$EvalError") ||
2810         CheckConstructor(isolate, js_obj, "$RangeError") ||
2811         CheckConstructor(isolate, js_obj, "$ReferenceError") ||
2812         CheckConstructor(isolate, js_obj, "$SyntaxError") ||
2813         CheckConstructor(isolate, js_obj, "$TypeError") ||
2814         CheckConstructor(isolate, js_obj, "$URIError");
2815   } else {
2816     return false;
2817   }
2818 }
2819
2820
2821 bool Value::IsRegExp() const {
2822   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2823   return obj->IsJSRegExp();
2824 }
2825
2826
2827 bool Value::IsGeneratorFunction() const {
2828   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2829   if (!obj->IsJSFunction()) return false;
2830   i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
2831   return func->shared()->is_generator();
2832 }
2833
2834
2835 bool Value::IsGeneratorObject() const {
2836   return Utils::OpenHandle(this)->IsJSGeneratorObject();
2837 }
2838
2839
2840 bool Value::IsMapIterator() const {
2841   return Utils::OpenHandle(this)->IsJSMapIterator();
2842 }
2843
2844
2845 bool Value::IsSetIterator() const {
2846   return Utils::OpenHandle(this)->IsJSSetIterator();
2847 }
2848
2849
2850 MaybeLocal<String> Value::ToString(Local<Context> context) const {
2851   auto obj = Utils::OpenHandle(this);
2852   if (obj->IsString()) return ToApiHandle<String>(obj);
2853   PREPARE_FOR_EXECUTION(context, "ToString", String);
2854   Local<String> result;
2855   has_pending_exception =
2856       !ToLocal<String>(i::Execution::ToString(isolate, obj), &result);
2857   RETURN_ON_FAILED_EXECUTION(String);
2858   RETURN_ESCAPED(result);
2859 }
2860
2861
2862 Local<String> Value::ToString(Isolate* isolate) const {
2863   RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
2864 }
2865
2866
2867 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
2868   auto obj = Utils::OpenHandle(this);
2869   if (obj->IsString()) return ToApiHandle<String>(obj);
2870   PREPARE_FOR_EXECUTION(context, "ToDetailString", String);
2871   Local<String> result;
2872   has_pending_exception =
2873       !ToLocal<String>(i::Execution::ToDetailString(isolate, obj), &result);
2874   RETURN_ON_FAILED_EXECUTION(String);
2875   RETURN_ESCAPED(result);
2876 }
2877
2878
2879 Local<String> Value::ToDetailString(Isolate* isolate) const {
2880   RETURN_TO_LOCAL_UNCHECKED(ToDetailString(isolate->GetCurrentContext()),
2881                             String);
2882 }
2883
2884
2885 MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
2886   auto obj = Utils::OpenHandle(this);
2887   if (obj->IsJSObject()) return ToApiHandle<Object>(obj);
2888   PREPARE_FOR_EXECUTION(context, "ToObject", Object);
2889   Local<Object> result;
2890   has_pending_exception =
2891       !ToLocal<Object>(i::Execution::ToObject(isolate, obj), &result);
2892   RETURN_ON_FAILED_EXECUTION(Object);
2893   RETURN_ESCAPED(result);
2894 }
2895
2896
2897 Local<v8::Object> Value::ToObject(Isolate* isolate) const {
2898   RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
2899 }
2900
2901
2902 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
2903   auto obj = Utils::OpenHandle(this);
2904   if (obj->IsBoolean()) return ToApiHandle<Boolean>(obj);
2905   auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2906   auto val = isolate->factory()->ToBoolean(obj->BooleanValue());
2907   return ToApiHandle<Boolean>(val);
2908 }
2909
2910
2911 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
2912   return ToBoolean(v8_isolate->GetCurrentContext()).ToLocalChecked();
2913 }
2914
2915
2916 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
2917   auto obj = Utils::OpenHandle(this);
2918   if (obj->IsNumber()) return ToApiHandle<Number>(obj);
2919   PREPARE_FOR_EXECUTION(context, "ToNumber", Number);
2920   Local<Number> result;
2921   has_pending_exception =
2922       !ToLocal<Number>(i::Execution::ToNumber(isolate, obj), &result);
2923   RETURN_ON_FAILED_EXECUTION(Number);
2924   RETURN_ESCAPED(result);
2925 }
2926
2927
2928 Local<Number> Value::ToNumber(Isolate* isolate) const {
2929   RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
2930 }
2931
2932
2933 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
2934   auto obj = Utils::OpenHandle(this);
2935   if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
2936   PREPARE_FOR_EXECUTION(context, "ToInteger", Integer);
2937   Local<Integer> result;
2938   has_pending_exception =
2939       !ToLocal<Integer>(i::Execution::ToInteger(isolate, obj), &result);
2940   RETURN_ON_FAILED_EXECUTION(Integer);
2941   RETURN_ESCAPED(result);
2942 }
2943
2944
2945 Local<Integer> Value::ToInteger(Isolate* isolate) const {
2946   RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
2947 }
2948
2949
2950 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
2951   auto obj = Utils::OpenHandle(this);
2952   if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
2953   Local<Int32> result;
2954   PREPARE_FOR_EXECUTION(context, "ToInt32", Int32);
2955   has_pending_exception =
2956       !ToLocal<Int32>(i::Execution::ToInt32(isolate, obj), &result);
2957   RETURN_ON_FAILED_EXECUTION(Int32);
2958   RETURN_ESCAPED(result);
2959 }
2960
2961
2962 Local<Int32> Value::ToInt32(Isolate* isolate) const {
2963   RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
2964 }
2965
2966
2967 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
2968   auto obj = Utils::OpenHandle(this);
2969   if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
2970   Local<Uint32> result;
2971   PREPARE_FOR_EXECUTION(context, "ToUInt32", Uint32);
2972   has_pending_exception =
2973       !ToLocal<Uint32>(i::Execution::ToUint32(isolate, obj), &result);
2974   RETURN_ON_FAILED_EXECUTION(Uint32);
2975   RETURN_ESCAPED(result);
2976 }
2977
2978
2979 Local<Uint32> Value::ToUint32(Isolate* isolate) const {
2980   RETURN_TO_LOCAL_UNCHECKED(ToUint32(isolate->GetCurrentContext()), Uint32);
2981 }
2982
2983
2984 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
2985   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
2986   Utils::ApiCheck(isolate != NULL &&
2987                   !isolate->IsDead(),
2988                   "v8::internal::Internals::CheckInitialized()",
2989                   "Isolate is not initialized or V8 has died");
2990 }
2991
2992
2993 void External::CheckCast(v8::Value* that) {
2994   Utils::ApiCheck(Utils::OpenHandle(that)->IsExternal(),
2995                   "v8::External::Cast()",
2996                   "Could not convert to external");
2997 }
2998
2999
3000 void v8::Object::CheckCast(Value* that) {
3001   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3002   Utils::ApiCheck(obj->IsJSObject(),
3003                   "v8::Object::Cast()",
3004                   "Could not convert to object");
3005 }
3006
3007
3008 void v8::Function::CheckCast(Value* that) {
3009   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3010   Utils::ApiCheck(obj->IsJSFunction(),
3011                   "v8::Function::Cast()",
3012                   "Could not convert to function");
3013 }
3014
3015
3016 void v8::Boolean::CheckCast(v8::Value* that) {
3017   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3018   Utils::ApiCheck(obj->IsBoolean(),
3019                   "v8::Boolean::Cast()",
3020                   "Could not convert to boolean");
3021 }
3022
3023
3024 void v8::Name::CheckCast(v8::Value* that) {
3025   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3026   Utils::ApiCheck(obj->IsName(),
3027                   "v8::Name::Cast()",
3028                   "Could not convert to name");
3029 }
3030
3031
3032 void v8::String::CheckCast(v8::Value* that) {
3033   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3034   Utils::ApiCheck(obj->IsString(),
3035                   "v8::String::Cast()",
3036                   "Could not convert to string");
3037 }
3038
3039
3040 void v8::Symbol::CheckCast(v8::Value* that) {
3041   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3042   Utils::ApiCheck(obj->IsSymbol(),
3043                   "v8::Symbol::Cast()",
3044                   "Could not convert to symbol");
3045 }
3046
3047
3048 void v8::Number::CheckCast(v8::Value* that) {
3049   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3050   Utils::ApiCheck(obj->IsNumber(),
3051                   "v8::Number::Cast()",
3052                   "Could not convert to number");
3053 }
3054
3055
3056 void v8::Integer::CheckCast(v8::Value* that) {
3057   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3058   Utils::ApiCheck(obj->IsNumber(),
3059                   "v8::Integer::Cast()",
3060                   "Could not convert to number");
3061 }
3062
3063
3064 void v8::Int32::CheckCast(v8::Value* that) {
3065   Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast()",
3066                   "Could not convert to 32-bit signed integer");
3067 }
3068
3069
3070 void v8::Uint32::CheckCast(v8::Value* that) {
3071   Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast()",
3072                   "Could not convert to 32-bit unsigned integer");
3073 }
3074
3075
3076 void v8::Array::CheckCast(Value* that) {
3077   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3078   Utils::ApiCheck(obj->IsJSArray(),
3079                   "v8::Array::Cast()",
3080                   "Could not convert to array");
3081 }
3082
3083
3084 void v8::Map::CheckCast(Value* that) {
3085   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3086   Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast()",
3087                   "Could not convert to Map");
3088 }
3089
3090
3091 void v8::Set::CheckCast(Value* that) {
3092   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3093   Utils::ApiCheck(obj->IsJSSet(), "v8::Set::Cast()",
3094                   "Could not convert to Set");
3095 }
3096
3097
3098 void v8::Promise::CheckCast(Value* that) {
3099   Utils::ApiCheck(that->IsPromise(),
3100                   "v8::Promise::Cast()",
3101                   "Could not convert to promise");
3102 }
3103
3104
3105 void v8::Promise::Resolver::CheckCast(Value* that) {
3106   Utils::ApiCheck(that->IsPromise(),
3107                   "v8::Promise::Resolver::Cast()",
3108                   "Could not convert to promise resolver");
3109 }
3110
3111
3112 void v8::ArrayBuffer::CheckCast(Value* that) {
3113   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3114   Utils::ApiCheck(
3115       obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
3116       "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
3117 }
3118
3119
3120 void v8::ArrayBufferView::CheckCast(Value* that) {
3121   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3122   Utils::ApiCheck(obj->IsJSArrayBufferView(),
3123                   "v8::ArrayBufferView::Cast()",
3124                   "Could not convert to ArrayBufferView");
3125 }
3126
3127
3128 void v8::TypedArray::CheckCast(Value* that) {
3129   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3130   Utils::ApiCheck(obj->IsJSTypedArray(),
3131                   "v8::TypedArray::Cast()",
3132                   "Could not convert to TypedArray");
3133 }
3134
3135
3136 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype, size)             \
3137   void v8::Type##Array::CheckCast(Value* that) {                              \
3138     i::Handle<i::Object> obj = Utils::OpenHandle(that);                       \
3139     Utils::ApiCheck(                                                          \
3140         obj->IsJSTypedArray() &&                                              \
3141             i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
3142         "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
3143   }
3144
3145
3146 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
3147
3148 #undef CHECK_TYPED_ARRAY_CAST
3149
3150
3151 void v8::DataView::CheckCast(Value* that) {
3152   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3153   Utils::ApiCheck(obj->IsJSDataView(),
3154                   "v8::DataView::Cast()",
3155                   "Could not convert to DataView");
3156 }
3157
3158
3159 void v8::SharedArrayBuffer::CheckCast(Value* that) {
3160   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3161   Utils::ApiCheck(
3162       obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
3163       "v8::SharedArrayBuffer::Cast()",
3164       "Could not convert to SharedArrayBuffer");
3165 }
3166
3167
3168 void v8::Date::CheckCast(v8::Value* that) {
3169   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3170   i::Isolate* isolate = NULL;
3171   if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3172   Utils::ApiCheck(isolate != NULL &&
3173                   obj->HasSpecificClassOf(isolate->heap()->Date_string()),
3174                   "v8::Date::Cast()",
3175                   "Could not convert to date");
3176 }
3177
3178
3179 void v8::StringObject::CheckCast(v8::Value* that) {
3180   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3181   i::Isolate* isolate = NULL;
3182   if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3183   Utils::ApiCheck(isolate != NULL &&
3184                   obj->HasSpecificClassOf(isolate->heap()->String_string()),
3185                   "v8::StringObject::Cast()",
3186                   "Could not convert to StringObject");
3187 }
3188
3189
3190 void v8::SymbolObject::CheckCast(v8::Value* that) {
3191   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3192   i::Isolate* isolate = NULL;
3193   if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3194   Utils::ApiCheck(isolate != NULL &&
3195                   obj->HasSpecificClassOf(isolate->heap()->Symbol_string()),
3196                   "v8::SymbolObject::Cast()",
3197                   "Could not convert to SymbolObject");
3198 }
3199
3200
3201 void v8::NumberObject::CheckCast(v8::Value* that) {
3202   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3203   i::Isolate* isolate = NULL;
3204   if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3205   Utils::ApiCheck(isolate != NULL &&
3206                   obj->HasSpecificClassOf(isolate->heap()->Number_string()),
3207                   "v8::NumberObject::Cast()",
3208                   "Could not convert to NumberObject");
3209 }
3210
3211
3212 void v8::BooleanObject::CheckCast(v8::Value* that) {
3213   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3214   i::Isolate* isolate = NULL;
3215   if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3216   Utils::ApiCheck(isolate != NULL &&
3217                   obj->HasSpecificClassOf(isolate->heap()->Boolean_string()),
3218                   "v8::BooleanObject::Cast()",
3219                   "Could not convert to BooleanObject");
3220 }
3221
3222
3223 void v8::RegExp::CheckCast(v8::Value* that) {
3224   i::Handle<i::Object> obj = Utils::OpenHandle(that);
3225   Utils::ApiCheck(obj->IsJSRegExp(),
3226                   "v8::RegExp::Cast()",
3227                   "Could not convert to regular expression");
3228 }
3229
3230
3231 Maybe<bool> Value::BooleanValue(Local<Context> context) const {
3232   return Just(Utils::OpenHandle(this)->BooleanValue());
3233 }
3234
3235
3236 bool Value::BooleanValue() const {
3237   return Utils::OpenHandle(this)->BooleanValue();
3238 }
3239
3240
3241 Maybe<double> Value::NumberValue(Local<Context> context) const {
3242   auto obj = Utils::OpenHandle(this);
3243   if (obj->IsNumber()) return Just(obj->Number());
3244   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "NumberValue", double);
3245   i::Handle<i::Object> num;
3246   has_pending_exception = !i::Execution::ToNumber(isolate, obj).ToHandle(&num);
3247   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
3248   return Just(num->Number());
3249 }
3250
3251
3252 double Value::NumberValue() const {
3253   auto obj = Utils::OpenHandle(this);
3254   if (obj->IsNumber()) return obj->Number();
3255   return NumberValue(ContextFromHeapObject(obj))
3256       .FromMaybe(std::numeric_limits<double>::quiet_NaN());
3257 }
3258
3259
3260 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
3261   auto obj = Utils::OpenHandle(this);
3262   i::Handle<i::Object> num;
3263   if (obj->IsNumber()) {
3264     num = obj;
3265   } else {
3266     PREPARE_FOR_EXECUTION_PRIMITIVE(context, "IntegerValue", int64_t);
3267     has_pending_exception =
3268         !i::Execution::ToInteger(isolate, obj).ToHandle(&num);
3269     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
3270   }
3271   return Just(num->IsSmi() ? static_cast<int64_t>(i::Smi::cast(*num)->value())
3272                            : static_cast<int64_t>(num->Number()));
3273 }
3274
3275
3276 int64_t Value::IntegerValue() const {
3277   auto obj = Utils::OpenHandle(this);
3278   if (obj->IsNumber()) {
3279     if (obj->IsSmi()) {
3280       return i::Smi::cast(*obj)->value();
3281     } else {
3282       return static_cast<int64_t>(obj->Number());
3283     }
3284   }
3285   return IntegerValue(ContextFromHeapObject(obj)).FromMaybe(0);
3286 }
3287
3288
3289 Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
3290   auto obj = Utils::OpenHandle(this);
3291   if (obj->IsNumber()) return Just(NumberToInt32(*obj));
3292   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Int32Value", int32_t);
3293   i::Handle<i::Object> num;
3294   has_pending_exception = !i::Execution::ToInt32(isolate, obj).ToHandle(&num);
3295   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
3296   return Just(num->IsSmi() ? i::Smi::cast(*num)->value()
3297                            : static_cast<int32_t>(num->Number()));
3298 }
3299
3300
3301 int32_t Value::Int32Value() const {
3302   auto obj = Utils::OpenHandle(this);
3303   if (obj->IsNumber()) return NumberToInt32(*obj);
3304   return Int32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3305 }
3306
3307
3308 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
3309   auto obj = Utils::OpenHandle(this);
3310   if (obj->IsNumber()) return Just(NumberToUint32(*obj));
3311   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Uint32Value", uint32_t);
3312   i::Handle<i::Object> num;
3313   has_pending_exception = !i::Execution::ToUint32(isolate, obj).ToHandle(&num);
3314   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
3315   return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::cast(*num)->value())
3316                            : static_cast<uint32_t>(num->Number()));
3317 }
3318
3319
3320 uint32_t Value::Uint32Value() const {
3321   auto obj = Utils::OpenHandle(this);
3322   if (obj->IsNumber()) return NumberToUint32(*obj);
3323   return Uint32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3324 }
3325
3326
3327 MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const {
3328   auto self = Utils::OpenHandle(this);
3329   if (self->IsSmi()) {
3330     if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3331     return Local<Uint32>();
3332   }
3333   PREPARE_FOR_EXECUTION(context, "ToArrayIndex", Uint32);
3334   i::Handle<i::Object> string_obj;
3335   has_pending_exception =
3336       !i::Execution::ToString(isolate, self).ToHandle(&string_obj);
3337   RETURN_ON_FAILED_EXECUTION(Uint32);
3338   i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
3339   uint32_t index;
3340   if (str->AsArrayIndex(&index)) {
3341     i::Handle<i::Object> value;
3342     if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
3343       value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
3344     } else {
3345       value = isolate->factory()->NewNumber(index);
3346     }
3347     RETURN_ESCAPED(Utils::Uint32ToLocal(value));
3348   }
3349   return Local<Uint32>();
3350 }
3351
3352
3353 Local<Uint32> Value::ToArrayIndex() const {
3354   auto self = Utils::OpenHandle(this);
3355   if (self->IsSmi()) {
3356     if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3357     return Local<Uint32>();
3358   }
3359   auto context = ContextFromHeapObject(self);
3360   RETURN_TO_LOCAL_UNCHECKED(ToArrayIndex(context), Uint32);
3361 }
3362
3363
3364 Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const {
3365   auto self = Utils::OpenHandle(this);
3366   auto other = Utils::OpenHandle(*that);
3367   if (self->IsSmi() && other->IsSmi()) {
3368     return Just(self->Number() == other->Number());
3369   }
3370   if (self->IsJSObject() && other->IsJSObject()) {
3371     return Just(*self == *other);
3372   }
3373   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Value::Equals()", bool);
3374   i::Handle<i::Object> args[] = { other };
3375   i::Handle<i::Object> result;
3376   has_pending_exception =
3377       !CallV8HeapFunction(isolate, "EQUALS", self, arraysize(args), args)
3378            .ToHandle(&result);
3379   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3380   return Just(*result == i::Smi::FromInt(i::EQUAL));
3381 }
3382
3383
3384 bool Value::Equals(Local<Value> that) const {
3385   auto self = Utils::OpenHandle(this);
3386   auto other = Utils::OpenHandle(*that);
3387   if (self->IsSmi() && other->IsSmi()) {
3388     return self->Number() == other->Number();
3389   }
3390   if (self->IsJSObject() && other->IsJSObject()) {
3391     return *self == *other;
3392   }
3393   auto heap_object = self->IsSmi() ? other : self;
3394   auto context = ContextFromHeapObject(heap_object);
3395   return Equals(context, that).FromMaybe(false);
3396 }
3397
3398
3399 bool Value::StrictEquals(Local<Value> that) const {
3400   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3401   i::Handle<i::Object> other = Utils::OpenHandle(*that);
3402   if (obj->IsSmi()) {
3403     return other->IsNumber() && obj->Number() == other->Number();
3404   }
3405   i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
3406   LOG_API(isolate, "StrictEquals");
3407   // Must check HeapNumber first, since NaN !== NaN.
3408   if (obj->IsHeapNumber()) {
3409     if (!other->IsNumber()) return false;
3410     double x = obj->Number();
3411     double y = other->Number();
3412     // Must check explicitly for NaN:s on Windows, but -0 works fine.
3413     return x == y && !std::isnan(x) && !std::isnan(y);
3414   } else if (*obj == *other) {  // Also covers Booleans.
3415     return true;
3416   } else if (obj->IsSmi()) {
3417     return other->IsNumber() && obj->Number() == other->Number();
3418   } else if (obj->IsString()) {
3419     return other->IsString() &&
3420         i::String::Equals(i::Handle<i::String>::cast(obj),
3421                           i::Handle<i::String>::cast(other));
3422   } else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
3423     return other->IsUndefined() || other->IsUndetectableObject();
3424   } else {
3425     return false;
3426   }
3427 }
3428
3429
3430 bool Value::SameValue(Local<Value> that) const {
3431   auto self = Utils::OpenHandle(this);
3432   auto other = Utils::OpenHandle(*that);
3433   return self->SameValue(*other);
3434 }
3435
3436
3437 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
3438                             v8::Local<Value> key, v8::Local<Value> value) {
3439   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3440   auto self = Utils::OpenHandle(this);
3441   auto key_obj = Utils::OpenHandle(*key);
3442   auto value_obj = Utils::OpenHandle(*value);
3443   has_pending_exception =
3444       i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
3445                                     i::SLOPPY).is_null();
3446   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3447   return Just(true);
3448 }
3449
3450
3451 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
3452   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3453   return Set(context, key, value).FromMaybe(false);
3454 }
3455
3456
3457 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
3458                             v8::Local<Value> value) {
3459   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3460   auto self = Utils::OpenHandle(this);
3461   auto value_obj = Utils::OpenHandle(*value);
3462   has_pending_exception =
3463       i::JSReceiver::SetElement(self, index, value_obj, i::SLOPPY).is_null();
3464   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3465   return Just(true);
3466 }
3467
3468
3469 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
3470   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3471   return Set(context, index, value).FromMaybe(false);
3472 }
3473
3474
3475 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3476                                            v8::Local<Name> key,
3477                                            v8::Local<Value> value) {
3478   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3479                                   bool);
3480   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3481   i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
3482   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3483
3484   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
3485       isolate, self, key_obj, i::LookupIterator::OWN);
3486   Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3487   has_pending_exception = result.IsNothing();
3488   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3489   return result;
3490 }
3491
3492
3493 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3494                                            uint32_t index,
3495                                            v8::Local<Value> value) {
3496   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3497                                   bool);
3498   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3499   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3500
3501   i::LookupIterator it(isolate, self, index, i::LookupIterator::OWN);
3502   Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3503   has_pending_exception = result.IsNothing();
3504   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3505   return result;
3506 }
3507
3508
3509 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
3510                                           v8::Local<Name> key,
3511                                           v8::Local<Value> value,
3512                                           v8::PropertyAttribute attributes) {
3513   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DefineOwnProperty()",
3514                                   bool);
3515   auto self = Utils::OpenHandle(this);
3516   auto key_obj = Utils::OpenHandle(*key);
3517   auto value_obj = Utils::OpenHandle(*value);
3518
3519   if (self->IsAccessCheckNeeded() && !isolate->MayAccess(self)) {
3520     isolate->ReportFailedAccessCheck(self);
3521     return Nothing<bool>();
3522   }
3523
3524   i::Handle<i::FixedArray> desc = isolate->factory()->NewFixedArray(3);
3525   desc->set(0, isolate->heap()->ToBoolean(!(attributes & v8::ReadOnly)));
3526   desc->set(1, isolate->heap()->ToBoolean(!(attributes & v8::DontEnum)));
3527   desc->set(2, isolate->heap()->ToBoolean(!(attributes & v8::DontDelete)));
3528   i::Handle<i::JSArray> desc_array =
3529       isolate->factory()->NewJSArrayWithElements(desc, i::FAST_ELEMENTS, 3);
3530   i::Handle<i::Object> args[] = {self, key_obj, value_obj, desc_array};
3531   i::Handle<i::Object> result;
3532   has_pending_exception =
3533       !CallV8HeapFunction(isolate, "$objectDefineOwnProperty",
3534                           isolate->factory()->undefined_value(),
3535                           arraysize(args), args).ToHandle(&result);
3536   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3537   return Just(result->BooleanValue());
3538 }
3539
3540
3541 MUST_USE_RESULT
3542 static i::MaybeHandle<i::Object> DefineObjectProperty(
3543     i::Handle<i::JSObject> js_object, i::Handle<i::Object> key,
3544     i::Handle<i::Object> value, PropertyAttributes attrs) {
3545   i::Isolate* isolate = js_object->GetIsolate();
3546   // Check if the given key is an array index.
3547   uint32_t index = 0;
3548   if (key->ToArrayIndex(&index)) {
3549     return i::JSObject::SetOwnElementIgnoreAttributes(js_object, index, value,
3550                                                       attrs);
3551   }
3552
3553   i::Handle<i::Name> name;
3554   ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
3555                                    i::Runtime::ToName(isolate, key),
3556                                    i::MaybeHandle<i::Object>());
3557
3558   return i::JSObject::DefinePropertyOrElementIgnoreAttributes(js_object, name,
3559                                                               value, attrs);
3560 }
3561
3562
3563 Maybe<bool> v8::Object::ForceSet(v8::Local<v8::Context> context,
3564                                  v8::Local<Value> key, v8::Local<Value> value,
3565                                  v8::PropertyAttribute attribs) {
3566   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3567   auto self = Utils::OpenHandle(this);
3568   auto key_obj = Utils::OpenHandle(*key);
3569   auto value_obj = Utils::OpenHandle(*value);
3570   has_pending_exception =
3571       DefineObjectProperty(self, key_obj, value_obj,
3572                            static_cast<PropertyAttributes>(attribs)).is_null();
3573   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3574   return Just(true);
3575 }
3576
3577
3578 bool v8::Object::ForceSet(v8::Local<Value> key, v8::Local<Value> value,
3579                           v8::PropertyAttribute attribs) {
3580   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3581   PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(),
3582                                 "v8::Object::ForceSet", false, i::HandleScope,
3583                                 false);
3584   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3585   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
3586   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3587   has_pending_exception =
3588       DefineObjectProperty(self, key_obj, value_obj,
3589                            static_cast<PropertyAttributes>(attribs)).is_null();
3590   EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, false);
3591   return true;
3592 }
3593
3594
3595 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
3596                                   Local<Value> key) {
3597   PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3598   auto self = Utils::OpenHandle(this);
3599   auto key_obj = Utils::OpenHandle(*key);
3600   i::Handle<i::Object> result;
3601   has_pending_exception =
3602       !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
3603   RETURN_ON_FAILED_EXECUTION(Value);
3604   RETURN_ESCAPED(Utils::ToLocal(result));
3605 }
3606
3607
3608 Local<Value> v8::Object::Get(v8::Local<Value> key) {
3609   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3610   RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
3611 }
3612
3613
3614 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
3615   PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3616   auto self = Utils::OpenHandle(this);
3617   i::Handle<i::Object> result;
3618   has_pending_exception =
3619       !i::Object::GetElement(isolate, self, index).ToHandle(&result);
3620   RETURN_ON_FAILED_EXECUTION(Value);
3621   RETURN_ESCAPED(Utils::ToLocal(result));
3622 }
3623
3624
3625 Local<Value> v8::Object::Get(uint32_t index) {
3626   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3627   RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
3628 }
3629
3630
3631 Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes(
3632     Local<Context> context, Local<Value> key) {
3633   PREPARE_FOR_EXECUTION_PRIMITIVE(
3634       context, "v8::Object::GetPropertyAttributes()", PropertyAttribute);
3635   auto self = Utils::OpenHandle(this);
3636   auto key_obj = Utils::OpenHandle(*key);
3637   if (!key_obj->IsName()) {
3638     has_pending_exception = !i::Execution::ToString(
3639         isolate, key_obj).ToHandle(&key_obj);
3640     RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3641   }
3642   auto key_name = i::Handle<i::Name>::cast(key_obj);
3643   auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
3644   has_pending_exception = result.IsNothing();
3645   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3646   if (result.FromJust() == ABSENT) {
3647     return Just(static_cast<PropertyAttribute>(NONE));
3648   }
3649   return Just(static_cast<PropertyAttribute>(result.FromJust()));
3650 }
3651
3652
3653 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Local<Value> key) {
3654   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3655   return GetPropertyAttributes(context, key)
3656       .FromMaybe(static_cast<PropertyAttribute>(NONE));
3657 }
3658
3659
3660 MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context,
3661                                                        Local<String> key) {
3662   PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyDescriptor()",
3663                         Value);
3664   auto obj = Utils::OpenHandle(this);
3665   auto key_name = Utils::OpenHandle(*key);
3666   i::Handle<i::Object> args[] = { obj, key_name };
3667   i::Handle<i::Object> result;
3668   has_pending_exception =
3669       !CallV8HeapFunction(isolate, "$objectGetOwnPropertyDescriptor",
3670                           isolate->factory()->undefined_value(),
3671                           arraysize(args), args).ToHandle(&result);
3672   RETURN_ON_FAILED_EXECUTION(Value);
3673   RETURN_ESCAPED(Utils::ToLocal(result));
3674 }
3675
3676
3677 Local<Value> v8::Object::GetOwnPropertyDescriptor(Local<String> key) {
3678   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3679   RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyDescriptor(context, key), Value);
3680 }
3681
3682
3683 Local<Value> v8::Object::GetPrototype() {
3684   auto isolate = Utils::OpenHandle(this)->GetIsolate();
3685   auto self = Utils::OpenHandle(this);
3686   i::PrototypeIterator iter(isolate, self);
3687   return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
3688 }
3689
3690
3691 Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
3692                                      Local<Value> value) {
3693   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetPrototype()", bool);
3694   auto self = Utils::OpenHandle(this);
3695   auto value_obj = Utils::OpenHandle(*value);
3696   // We do not allow exceptions thrown while setting the prototype
3697   // to propagate outside.
3698   TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
3699   auto result = i::JSObject::SetPrototype(self, value_obj, false);
3700   has_pending_exception = result.is_null();
3701   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3702   return Just(true);
3703 }
3704
3705
3706 bool v8::Object::SetPrototype(Local<Value> value) {
3707   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3708   return SetPrototype(context, value).FromMaybe(false);
3709 }
3710
3711
3712 Local<Object> v8::Object::FindInstanceInPrototypeChain(
3713     v8::Local<FunctionTemplate> tmpl) {
3714   auto isolate = Utils::OpenHandle(this)->GetIsolate();
3715   i::PrototypeIterator iter(isolate, *Utils::OpenHandle(this),
3716                             i::PrototypeIterator::START_AT_RECEIVER);
3717   auto tmpl_info = *Utils::OpenHandle(*tmpl);
3718   while (!tmpl_info->IsTemplateFor(iter.GetCurrent())) {
3719     iter.Advance();
3720     if (iter.IsAtEnd()) {
3721       return Local<Object>();
3722     }
3723   }
3724   return Utils::ToLocal(
3725       i::handle(i::JSObject::cast(iter.GetCurrent()), isolate));
3726 }
3727
3728
3729 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
3730   PREPARE_FOR_EXECUTION(context, "v8::Object::GetPropertyNames()", Array);
3731   auto self = Utils::OpenHandle(this);
3732   i::Handle<i::FixedArray> value;
3733   has_pending_exception = !i::JSReceiver::GetKeys(
3734       self, i::JSReceiver::INCLUDE_PROTOS).ToHandle(&value);
3735   RETURN_ON_FAILED_EXECUTION(Array);
3736   // Because we use caching to speed up enumeration it is important
3737   // to never change the result of the basic enumeration function so
3738   // we clone the result.
3739   auto elms = isolate->factory()->CopyFixedArray(value);
3740   auto result = isolate->factory()->NewJSArrayWithElements(elms);
3741   RETURN_ESCAPED(Utils::ToLocal(result));
3742 }
3743
3744
3745 Local<Array> v8::Object::GetPropertyNames() {
3746   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3747   RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array);
3748 }
3749
3750
3751 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
3752   PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyNames()", Array);
3753   auto self = Utils::OpenHandle(this);
3754   i::Handle<i::FixedArray> value;
3755   has_pending_exception = !i::JSReceiver::GetKeys(
3756       self, i::JSReceiver::OWN_ONLY).ToHandle(&value);
3757   RETURN_ON_FAILED_EXECUTION(Array);
3758   // Because we use caching to speed up enumeration it is important
3759   // to never change the result of the basic enumeration function so
3760   // we clone the result.
3761   auto elms = isolate->factory()->CopyFixedArray(value);
3762   auto result = isolate->factory()->NewJSArrayWithElements(elms);
3763   RETURN_ESCAPED(Utils::ToLocal(result));
3764 }
3765
3766
3767 Local<Array> v8::Object::GetOwnPropertyNames() {
3768   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3769   RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array);
3770 }
3771
3772
3773 MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) {
3774   auto self = Utils::OpenHandle(this);
3775   auto isolate = self->GetIsolate();
3776   auto v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
3777   i::Handle<i::Object> name(self->class_name(), isolate);
3778   i::Handle<i::Object> tag;
3779
3780   // Native implementation of Object.prototype.toString (v8natives.js):
3781   //   var c = %_ClassOf(this);
3782   //   if (c === 'Arguments') c  = 'Object';
3783   //   return "[object " + c + "]";
3784
3785   if (!name->IsString()) {
3786     return v8::String::NewFromUtf8(v8_isolate, "[object ]",
3787                                    NewStringType::kNormal);
3788   }
3789   auto class_name = i::Handle<i::String>::cast(name);
3790   if (i::String::Equals(class_name, isolate->factory()->Arguments_string())) {
3791     return v8::String::NewFromUtf8(v8_isolate, "[object Object]",
3792                                    NewStringType::kNormal);
3793   }
3794   if (internal::FLAG_harmony_tostring) {
3795     PREPARE_FOR_EXECUTION(context, "v8::Object::ObjectProtoToString()", String);
3796     auto toStringTag = isolate->factory()->to_string_tag_symbol();
3797     has_pending_exception = !i::Runtime::GetObjectProperty(
3798                                  isolate, self, toStringTag).ToHandle(&tag);
3799     RETURN_ON_FAILED_EXECUTION(String);
3800     if (tag->IsString()) {
3801       class_name = i::Handle<i::String>::cast(tag).EscapeFrom(&handle_scope);
3802     }
3803   }
3804   const char* prefix = "[object ";
3805   Local<String> str = Utils::ToLocal(class_name);
3806   const char* postfix = "]";
3807
3808   int prefix_len = i::StrLength(prefix);
3809   int str_len = str->Utf8Length();
3810   int postfix_len = i::StrLength(postfix);
3811
3812   int buf_len = prefix_len + str_len + postfix_len;
3813   i::ScopedVector<char> buf(buf_len);
3814
3815   // Write prefix.
3816   char* ptr = buf.start();
3817   i::MemCopy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3818   ptr += prefix_len;
3819
3820   // Write real content.
3821   str->WriteUtf8(ptr, str_len);
3822   ptr += str_len;
3823
3824   // Write postfix.
3825   i::MemCopy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3826
3827   // Copy the buffer into a heap-allocated string and return it.
3828   return v8::String::NewFromUtf8(v8_isolate, buf.start(),
3829                                  NewStringType::kNormal, buf_len);
3830 }
3831
3832
3833 Local<String> v8::Object::ObjectProtoToString() {
3834   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3835   RETURN_TO_LOCAL_UNCHECKED(ObjectProtoToString(context), String);
3836 }
3837
3838
3839 Local<String> v8::Object::GetConstructorName() {
3840   auto self = Utils::OpenHandle(this);
3841   i::Handle<i::String> name(self->constructor_name());
3842   return Utils::ToLocal(name);
3843 }
3844
3845
3846 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
3847   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Delete()", bool);
3848   auto self = Utils::OpenHandle(this);
3849   auto key_obj = Utils::OpenHandle(*key);
3850   i::Handle<i::Object> obj;
3851   has_pending_exception =
3852       !i::Runtime::DeleteObjectProperty(isolate, self, key_obj, i::SLOPPY)
3853            .ToHandle(&obj);
3854   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3855   return Just(obj->IsTrue());
3856 }
3857
3858
3859 bool v8::Object::Delete(v8::Local<Value> key) {
3860   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3861   return Delete(context, key).FromMaybe(false);
3862 }
3863
3864
3865 Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) {
3866   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3867   auto self = Utils::OpenHandle(this);
3868   auto key_obj = Utils::OpenHandle(*key);
3869   Maybe<bool> maybe = Nothing<bool>();
3870   // Check if the given key is an array index.
3871   uint32_t index = 0;
3872   if (key_obj->ToArrayIndex(&index)) {
3873     maybe = i::JSReceiver::HasElement(self, index);
3874   } else {
3875     // Convert the key to a name - possibly by calling back into JavaScript.
3876     i::Handle<i::Name> name;
3877     if (i::Runtime::ToName(isolate, key_obj).ToHandle(&name)) {
3878       maybe = i::JSReceiver::HasProperty(self, name);
3879     }
3880   }
3881   has_pending_exception = maybe.IsNothing();
3882   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3883   return maybe;
3884 }
3885
3886
3887 bool v8::Object::Has(v8::Local<Value> key) {
3888   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3889   return Has(context, key).FromMaybe(false);
3890 }
3891
3892
3893 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
3894   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DeleteProperty()",
3895                                   bool);
3896   auto self = Utils::OpenHandle(this);
3897   i::Handle<i::Object> obj;
3898   has_pending_exception =
3899       !i::JSReceiver::DeleteElement(self, index).ToHandle(&obj);
3900   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3901   return Just(obj->IsTrue());
3902 }
3903
3904
3905 bool v8::Object::Delete(uint32_t index) {
3906   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3907   return Delete(context, index).FromMaybe(false);
3908 }
3909
3910
3911 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
3912   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3913   auto self = Utils::OpenHandle(this);
3914   auto maybe = i::JSReceiver::HasElement(self, index);
3915   has_pending_exception = maybe.IsNothing();
3916   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3917   return maybe;
3918 }
3919
3920
3921 bool v8::Object::Has(uint32_t index) {
3922   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3923   return Has(context, index).FromMaybe(false);
3924 }
3925
3926
3927 template <typename Getter, typename Setter, typename Data>
3928 static Maybe<bool> ObjectSetAccessor(Local<Context> context, Object* obj,
3929                                      Local<Name> name, Getter getter,
3930                                      Setter setter, Data data,
3931                                      AccessControl settings,
3932                                      PropertyAttribute attributes) {
3933   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetAccessor()", bool);
3934   v8::Local<AccessorSignature> signature;
3935   auto info = MakeAccessorInfo(name, getter, setter, data, settings, attributes,
3936                                signature);
3937   if (info.is_null()) return Nothing<bool>();
3938   bool fast = Utils::OpenHandle(obj)->HasFastProperties();
3939   i::Handle<i::Object> result;
3940   has_pending_exception =
3941       !i::JSObject::SetAccessor(Utils::OpenHandle(obj), info).ToHandle(&result);
3942   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3943   if (result->IsUndefined()) return Nothing<bool>();
3944   if (fast) {
3945     i::JSObject::MigrateSlowToFast(Utils::OpenHandle(obj), 0, "APISetAccessor");
3946   }
3947   return Just(true);
3948 }
3949
3950
3951 Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name,
3952                                 AccessorNameGetterCallback getter,
3953                                 AccessorNameSetterCallback setter,
3954                                 MaybeLocal<Value> data, AccessControl settings,
3955                                 PropertyAttribute attribute) {
3956   return ObjectSetAccessor(context, this, name, getter, setter,
3957                            data.FromMaybe(Local<Value>()), settings, attribute);
3958 }
3959
3960
3961 bool Object::SetAccessor(Local<String> name, AccessorGetterCallback getter,
3962                          AccessorSetterCallback setter, v8::Local<Value> data,
3963                          AccessControl settings, PropertyAttribute attributes) {
3964   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3965   return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3966                            attributes).FromMaybe(false);
3967 }
3968
3969
3970 bool Object::SetAccessor(Local<Name> name, AccessorNameGetterCallback getter,
3971                          AccessorNameSetterCallback setter,
3972                          v8::Local<Value> data, AccessControl settings,
3973                          PropertyAttribute attributes) {
3974   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3975   return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3976                            attributes).FromMaybe(false);
3977 }
3978
3979
3980 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
3981                                  Local<Function> setter,
3982                                  PropertyAttribute attribute,
3983                                  AccessControl settings) {
3984   // TODO(verwaest): Remove |settings|.
3985   DCHECK_EQ(v8::DEFAULT, settings);
3986   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3987   ENTER_V8(isolate);
3988   i::HandleScope scope(isolate);
3989   i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
3990   i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
3991   if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
3992   i::JSObject::DefineAccessor(v8::Utils::OpenHandle(this),
3993                               v8::Utils::OpenHandle(*name),
3994                               getter_i,
3995                               setter_i,
3996                               static_cast<PropertyAttributes>(attribute));
3997 }
3998
3999
4000 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
4001                                        Local<Name> key) {
4002   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasOwnProperty()",
4003                                   bool);
4004   auto self = Utils::OpenHandle(this);
4005   auto key_val = Utils::OpenHandle(*key);
4006   auto result = i::JSReceiver::HasOwnProperty(self, key_val);
4007   has_pending_exception = result.IsNothing();
4008   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4009   return result;
4010 }
4011
4012
4013 bool v8::Object::HasOwnProperty(Local<String> key) {
4014   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4015   return HasOwnProperty(context, key).FromMaybe(false);
4016 }
4017
4018
4019 Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context,
4020                                              Local<Name> key) {
4021   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasRealNamedProperty()",
4022                                   bool);
4023   auto self = Utils::OpenHandle(this);
4024   auto key_val = Utils::OpenHandle(*key);
4025   auto result = i::JSObject::HasRealNamedProperty(self, key_val);
4026   has_pending_exception = result.IsNothing();
4027   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4028   return result;
4029 }
4030
4031
4032 bool v8::Object::HasRealNamedProperty(Local<String> key) {
4033   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4034   return HasRealNamedProperty(context, key).FromMaybe(false);
4035 }
4036
4037
4038 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
4039                                                uint32_t index) {
4040   PREPARE_FOR_EXECUTION_PRIMITIVE(context,
4041                                   "v8::Object::HasRealIndexedProperty()", bool);
4042   auto self = Utils::OpenHandle(this);
4043   auto result = i::JSObject::HasRealElementProperty(self, index);
4044   has_pending_exception = result.IsNothing();
4045   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4046   return result;
4047 }
4048
4049
4050 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
4051   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4052   return HasRealIndexedProperty(context, index).FromMaybe(false);
4053 }
4054
4055
4056 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
4057                                                      Local<Name> key) {
4058   PREPARE_FOR_EXECUTION_PRIMITIVE(
4059       context, "v8::Object::HasRealNamedCallbackProperty()", bool);
4060   auto self = Utils::OpenHandle(this);
4061   auto key_val = Utils::OpenHandle(*key);
4062   auto result = i::JSObject::HasRealNamedCallbackProperty(self, key_val);
4063   has_pending_exception = result.IsNothing();
4064   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4065   return result;
4066 }
4067
4068
4069 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) {
4070   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4071   return HasRealNamedCallbackProperty(context, key).FromMaybe(false);
4072 }
4073
4074
4075 bool v8::Object::HasNamedLookupInterceptor() {
4076   auto self = Utils::OpenHandle(this);
4077   return self->HasNamedInterceptor();
4078 }
4079
4080
4081 bool v8::Object::HasIndexedLookupInterceptor() {
4082   auto self = Utils::OpenHandle(this);
4083   return self->HasIndexedInterceptor();
4084 }
4085
4086
4087 MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4088     Local<Context> context, Local<Name> key) {
4089   PREPARE_FOR_EXECUTION(
4090       context, "v8::Object::GetRealNamedPropertyInPrototypeChain()", Value);
4091   auto self = Utils::OpenHandle(this);
4092   auto key_obj = Utils::OpenHandle(*key);
4093   i::PrototypeIterator iter(isolate, self);
4094   if (iter.IsAtEnd()) return MaybeLocal<Value>();
4095   auto proto = i::PrototypeIterator::GetCurrent(iter);
4096   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4097       isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4098       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4099   Local<Value> result;
4100   has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4101   RETURN_ON_FAILED_EXECUTION(Value);
4102   if (!it.IsFound()) return MaybeLocal<Value>();
4103   RETURN_ESCAPED(result);
4104 }
4105
4106
4107 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4108     Local<String> key) {
4109   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4110   RETURN_TO_LOCAL_UNCHECKED(GetRealNamedPropertyInPrototypeChain(context, key),
4111                             Value);
4112 }
4113
4114
4115 Maybe<PropertyAttribute>
4116 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(
4117     Local<Context> context, Local<Name> key) {
4118   PREPARE_FOR_EXECUTION_PRIMITIVE(
4119       context, "v8::Object::GetRealNamedPropertyAttributesInPrototypeChain()",
4120       PropertyAttribute);
4121   auto self = Utils::OpenHandle(this);
4122   auto key_obj = Utils::OpenHandle(*key);
4123   i::PrototypeIterator iter(isolate, self);
4124   if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
4125   auto proto = i::PrototypeIterator::GetCurrent(iter);
4126   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4127       isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4128       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4129   auto result = i::JSReceiver::GetPropertyAttributes(&it);
4130   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4131   if (!it.IsFound()) return Nothing<PropertyAttribute>();
4132   if (result.FromJust() == ABSENT) {
4133     return Just(static_cast<PropertyAttribute>(NONE));
4134   }
4135   return Just<PropertyAttribute>(
4136       static_cast<PropertyAttribute>(result.FromJust()));
4137 }
4138
4139
4140 Maybe<PropertyAttribute>
4141 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(Local<String> key) {
4142   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4143   return GetRealNamedPropertyAttributesInPrototypeChain(context, key);
4144 }
4145
4146
4147 MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context,
4148                                                    Local<Name> key) {
4149   PREPARE_FOR_EXECUTION(context, "v8::Object::GetRealNamedProperty()", Value);
4150   auto self = Utils::OpenHandle(this);
4151   auto key_obj = Utils::OpenHandle(*key);
4152   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4153       isolate, self, key_obj,
4154       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4155   Local<Value> result;
4156   has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4157   RETURN_ON_FAILED_EXECUTION(Value);
4158   if (!it.IsFound()) return MaybeLocal<Value>();
4159   RETURN_ESCAPED(result);
4160 }
4161
4162
4163 Local<Value> v8::Object::GetRealNamedProperty(Local<String> key) {
4164   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4165   RETURN_TO_LOCAL_UNCHECKED(GetRealNamedProperty(context, key), Value);
4166 }
4167
4168
4169 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4170     Local<Context> context, Local<Name> key) {
4171   PREPARE_FOR_EXECUTION_PRIMITIVE(
4172       context, "v8::Object::GetRealNamedPropertyAttributes()",
4173       PropertyAttribute);
4174   auto self = Utils::OpenHandle(this);
4175   auto key_obj = Utils::OpenHandle(*key);
4176   i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4177       isolate, self, key_obj,
4178       i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4179   auto result = i::JSReceiver::GetPropertyAttributes(&it);
4180   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4181   if (!it.IsFound()) return Nothing<PropertyAttribute>();
4182   if (result.FromJust() == ABSENT) {
4183     return Just(static_cast<PropertyAttribute>(NONE));
4184   }
4185   return Just<PropertyAttribute>(
4186       static_cast<PropertyAttribute>(result.FromJust()));
4187 }
4188
4189
4190 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4191     Local<String> key) {
4192   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4193   return GetRealNamedPropertyAttributes(context, key);
4194 }
4195
4196
4197 Local<v8::Object> v8::Object::Clone() {
4198   auto self = Utils::OpenHandle(this);
4199   auto isolate = self->GetIsolate();
4200   ENTER_V8(isolate);
4201   auto result = isolate->factory()->CopyJSObject(self);
4202   CHECK(!result.is_null());
4203   return Utils::ToLocal(result);
4204 }
4205
4206
4207 Local<v8::Context> v8::Object::CreationContext() {
4208   auto self = Utils::OpenHandle(this);
4209   auto context = handle(self->GetCreationContext());
4210   return Utils::ToLocal(context);
4211 }
4212
4213
4214 int v8::Object::GetIdentityHash() {
4215   auto isolate = Utils::OpenHandle(this)->GetIsolate();
4216   i::HandleScope scope(isolate);
4217   auto self = Utils::OpenHandle(this);
4218   return i::JSReceiver::GetOrCreateIdentityHash(self)->value();
4219 }
4220
4221
4222 bool v8::Object::SetHiddenValue(v8::Local<v8::String> key,
4223                                 v8::Local<v8::Value> value) {
4224   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4225   if (value.IsEmpty()) return DeleteHiddenValue(key);
4226   ENTER_V8(isolate);
4227   i::HandleScope scope(isolate);
4228   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4229   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4230   i::Handle<i::String> key_string =
4231       isolate->factory()->InternalizeString(key_obj);
4232   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4233   i::Handle<i::Object> result =
4234       i::JSObject::SetHiddenProperty(self, key_string, value_obj);
4235   return *result == *self;
4236 }
4237
4238
4239 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Local<v8::String> key) {
4240   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4241   ENTER_V8(isolate);
4242   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4243   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4244   i::Handle<i::String> key_string =
4245       isolate->factory()->InternalizeString(key_obj);
4246   i::Handle<i::Object> result(self->GetHiddenProperty(key_string), isolate);
4247   if (result->IsTheHole()) return v8::Local<v8::Value>();
4248   return Utils::ToLocal(result);
4249 }
4250
4251
4252 bool v8::Object::DeleteHiddenValue(v8::Local<v8::String> key) {
4253   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4254   ENTER_V8(isolate);
4255   i::HandleScope scope(isolate);
4256   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4257   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4258   i::Handle<i::String> key_string =
4259       isolate->factory()->InternalizeString(key_obj);
4260   i::JSObject::DeleteHiddenProperty(self, key_string);
4261   return true;
4262 }
4263
4264
4265 bool v8::Object::IsCallable() {
4266   auto self = Utils::OpenHandle(this);
4267   return self->IsCallable();
4268 }
4269
4270
4271 MaybeLocal<Value> Object::CallAsFunction(Local<Context> context,
4272                                          Local<Value> recv, int argc,
4273                                          Local<Value> argv[]) {
4274   PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Object::CallAsFunction()",
4275                                       Value);
4276   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4277   auto self = Utils::OpenHandle(this);
4278   auto recv_obj = Utils::OpenHandle(*recv);
4279   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4280   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4281   i::Handle<i::JSFunction> fun;
4282   if (self->IsJSFunction()) {
4283     fun = i::Handle<i::JSFunction>::cast(self);
4284   } else {
4285     i::Handle<i::Object> delegate;
4286     has_pending_exception = !i::Execution::TryGetFunctionDelegate(isolate, self)
4287                                  .ToHandle(&delegate);
4288     RETURN_ON_FAILED_EXECUTION(Value);
4289     fun = i::Handle<i::JSFunction>::cast(delegate);
4290     recv_obj = self;
4291   }
4292   Local<Value> result;
4293   has_pending_exception =
4294       !ToLocal<Value>(
4295           i::Execution::Call(isolate, fun, recv_obj, argc, args, true),
4296           &result);
4297   RETURN_ON_FAILED_EXECUTION(Value);
4298   RETURN_ESCAPED(result);
4299 }
4300
4301
4302 Local<v8::Value> Object::CallAsFunction(v8::Local<v8::Value> recv, int argc,
4303                                         v8::Local<v8::Value> argv[]) {
4304   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4305   Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4306   RETURN_TO_LOCAL_UNCHECKED(CallAsFunction(context, recv, argc, argv_cast),
4307                             Value);
4308 }
4309
4310
4311 MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc,
4312                                             Local<Value> argv[]) {
4313   PREPARE_FOR_EXECUTION_WITH_CALLBACK(context,
4314                                       "v8::Object::CallAsConstructor()", Value);
4315   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4316   auto self = Utils::OpenHandle(this);
4317   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4318   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4319   if (self->IsJSFunction()) {
4320     auto fun = i::Handle<i::JSFunction>::cast(self);
4321     Local<Value> result;
4322     has_pending_exception =
4323         !ToLocal<Value>(i::Execution::New(fun, argc, args), &result);
4324     RETURN_ON_FAILED_EXECUTION(Value);
4325     RETURN_ESCAPED(result);
4326   }
4327   i::Handle<i::Object> delegate;
4328   has_pending_exception = !i::Execution::TryGetConstructorDelegate(
4329                                isolate, self).ToHandle(&delegate);
4330   RETURN_ON_FAILED_EXECUTION(Value);
4331   if (!delegate->IsUndefined()) {
4332     auto fun = i::Handle<i::JSFunction>::cast(delegate);
4333     Local<Value> result;
4334     has_pending_exception =
4335         !ToLocal<Value>(i::Execution::Call(isolate, fun, self, argc, args),
4336                         &result);
4337     RETURN_ON_FAILED_EXECUTION(Value);
4338     DCHECK(!delegate->IsUndefined());
4339     RETURN_ESCAPED(result);
4340   }
4341   return MaybeLocal<Value>();
4342 }
4343
4344
4345 Local<v8::Value> Object::CallAsConstructor(int argc,
4346                                            v8::Local<v8::Value> argv[]) {
4347   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4348   Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4349   RETURN_TO_LOCAL_UNCHECKED(CallAsConstructor(context, argc, argv_cast), Value);
4350 }
4351
4352
4353 MaybeLocal<Function> Function::New(Local<Context> context,
4354                                    FunctionCallback callback, Local<Value> data,
4355                                    int length) {
4356   i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
4357   LOG_API(isolate, "Function::New");
4358   ENTER_V8(isolate);
4359   return FunctionTemplateNew(isolate, callback, data, Local<Signature>(),
4360                              length, true)->GetFunction(context);
4361 }
4362
4363
4364 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback,
4365                               Local<Value> data, int length) {
4366   return Function::New(v8_isolate->GetCurrentContext(), callback, data, length)
4367       .FromMaybe(Local<Function>());
4368 }
4369
4370
4371 Local<v8::Object> Function::NewInstance() const {
4372   return NewInstance(Isolate::GetCurrent()->GetCurrentContext(), 0, NULL)
4373       .FromMaybe(Local<Object>());
4374 }
4375
4376
4377 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
4378                                          v8::Local<v8::Value> argv[]) const {
4379   PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::NewInstance()",
4380                                       Object);
4381   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4382   auto self = Utils::OpenHandle(this);
4383   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4384   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4385   Local<Object> result;
4386   has_pending_exception =
4387       !ToLocal<Object>(i::Execution::New(self, argc, args), &result);
4388   RETURN_ON_FAILED_EXECUTION(Object);
4389   RETURN_ESCAPED(result);
4390 }
4391
4392
4393 Local<v8::Object> Function::NewInstance(int argc,
4394                                         v8::Local<v8::Value> argv[]) const {
4395   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4396   RETURN_TO_LOCAL_UNCHECKED(NewInstance(context, argc, argv), Object);
4397 }
4398
4399
4400 MaybeLocal<v8::Value> Function::Call(Local<Context> context,
4401                                      v8::Local<v8::Value> recv, int argc,
4402                                      v8::Local<v8::Value> argv[]) {
4403   PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::Call()", Value);
4404   i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4405   auto self = Utils::OpenHandle(this);
4406   i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
4407   STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4408   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4409   Local<Value> result;
4410   has_pending_exception =
4411       !ToLocal<Value>(
4412           i::Execution::Call(isolate, self, recv_obj, argc, args, true),
4413           &result);
4414   RETURN_ON_FAILED_EXECUTION(Value);
4415   RETURN_ESCAPED(result);
4416 }
4417
4418
4419 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc,
4420                                 v8::Local<v8::Value> argv[]) {
4421   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4422   RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value);
4423 }
4424
4425
4426 void Function::SetName(v8::Local<v8::String> name) {
4427   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4428   func->shared()->set_name(*Utils::OpenHandle(*name));
4429 }
4430
4431
4432 Local<Value> Function::GetName() const {
4433   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4434   return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name(),
4435                                              func->GetIsolate()));
4436 }
4437
4438
4439 Local<Value> Function::GetInferredName() const {
4440   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4441   return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
4442                                              func->GetIsolate()));
4443 }
4444
4445
4446 Local<Value> Function::GetDisplayName() const {
4447   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4448   ENTER_V8(isolate);
4449   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4450   i::Handle<i::String> property_name =
4451       isolate->factory()->NewStringFromStaticChars("displayName");
4452   i::Handle<i::Object> value =
4453       i::JSReceiver::GetDataProperty(func, property_name);
4454   if (value->IsString()) {
4455     i::Handle<i::String> name = i::Handle<i::String>::cast(value);
4456     if (name->length() > 0) return Utils::ToLocal(name);
4457   }
4458   return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
4459 }
4460
4461
4462 ScriptOrigin Function::GetScriptOrigin() const {
4463   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4464   if (func->shared()->script()->IsScript()) {
4465     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4466     return GetScriptOriginForScript(func->GetIsolate(), script);
4467   }
4468   return v8::ScriptOrigin(Local<Value>());
4469 }
4470
4471
4472 const int Function::kLineOffsetNotFound = -1;
4473
4474
4475 int Function::GetScriptLineNumber() const {
4476   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4477   if (func->shared()->script()->IsScript()) {
4478     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4479     return i::Script::GetLineNumber(script, func->shared()->start_position());
4480   }
4481   return kLineOffsetNotFound;
4482 }
4483
4484
4485 int Function::GetScriptColumnNumber() const {
4486   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4487   if (func->shared()->script()->IsScript()) {
4488     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4489     return i::Script::GetColumnNumber(script, func->shared()->start_position());
4490   }
4491   return kLineOffsetNotFound;
4492 }
4493
4494
4495 bool Function::IsBuiltin() const {
4496   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4497   return func->IsBuiltin();
4498 }
4499
4500
4501 int Function::ScriptId() const {
4502   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4503   if (!func->shared()->script()->IsScript()) {
4504     return v8::UnboundScript::kNoScriptId;
4505   }
4506   i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4507   return script->id()->value();
4508 }
4509
4510
4511 Local<v8::Value> Function::GetBoundFunction() const {
4512   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4513   if (!func->shared()->bound()) {
4514     return v8::Undefined(reinterpret_cast<v8::Isolate*>(func->GetIsolate()));
4515   }
4516   i::Handle<i::FixedArray> bound_args = i::Handle<i::FixedArray>(
4517       i::FixedArray::cast(func->function_bindings()));
4518   i::Handle<i::Object> original(
4519       bound_args->get(i::JSFunction::kBoundFunctionIndex),
4520       func->GetIsolate());
4521   return Utils::ToLocal(i::Handle<i::JSFunction>::cast(original));
4522 }
4523
4524
4525 int Name::GetIdentityHash() {
4526   auto self = Utils::OpenHandle(this);
4527   return static_cast<int>(self->Hash());
4528 }
4529
4530
4531 int String::Length() const {
4532   i::Handle<i::String> str = Utils::OpenHandle(this);
4533   return str->length();
4534 }
4535
4536
4537 bool String::IsOneByte() const {
4538   i::Handle<i::String> str = Utils::OpenHandle(this);
4539   return str->HasOnlyOneByteChars();
4540 }
4541
4542
4543 // Helpers for ContainsOnlyOneByteHelper
4544 template<size_t size> struct OneByteMask;
4545 template<> struct OneByteMask<4> {
4546   static const uint32_t value = 0xFF00FF00;
4547 };
4548 template<> struct OneByteMask<8> {
4549   static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
4550 };
4551 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
4552 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
4553 static inline bool Unaligned(const uint16_t* chars) {
4554   return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
4555 }
4556
4557
4558 static inline const uint16_t* Align(const uint16_t* chars) {
4559   return reinterpret_cast<uint16_t*>(
4560       reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
4561 }
4562
4563 class ContainsOnlyOneByteHelper {
4564  public:
4565   ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
4566   bool Check(i::String* string) {
4567     i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
4568     if (cons_string == NULL) return is_one_byte_;
4569     return CheckCons(cons_string);
4570   }
4571   void VisitOneByteString(const uint8_t* chars, int length) {
4572     // Nothing to do.
4573   }
4574   void VisitTwoByteString(const uint16_t* chars, int length) {
4575     // Accumulated bits.
4576     uintptr_t acc = 0;
4577     // Align to uintptr_t.
4578     const uint16_t* end = chars + length;
4579     while (Unaligned(chars) && chars != end) {
4580       acc |= *chars++;
4581     }
4582     // Read word aligned in blocks,
4583     // checking the return value at the end of each block.
4584     const uint16_t* aligned_end = Align(end);
4585     const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
4586     const int inner_loops = 16;
4587     while (chars + inner_loops*increment < aligned_end) {
4588       for (int i = 0; i < inner_loops; i++) {
4589         acc |= *reinterpret_cast<const uintptr_t*>(chars);
4590         chars += increment;
4591       }
4592       // Check for early return.
4593       if ((acc & kOneByteMask) != 0) {
4594         is_one_byte_ = false;
4595         return;
4596       }
4597     }
4598     // Read the rest.
4599     while (chars != end) {
4600       acc |= *chars++;
4601     }
4602     // Check result.
4603     if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
4604   }
4605
4606  private:
4607   bool CheckCons(i::ConsString* cons_string) {
4608     while (true) {
4609       // Check left side if flat.
4610       i::String* left = cons_string->first();
4611       i::ConsString* left_as_cons =
4612           i::String::VisitFlat(this, left, 0);
4613       if (!is_one_byte_) return false;
4614       // Check right side if flat.
4615       i::String* right = cons_string->second();
4616       i::ConsString* right_as_cons =
4617           i::String::VisitFlat(this, right, 0);
4618       if (!is_one_byte_) return false;
4619       // Standard recurse/iterate trick.
4620       if (left_as_cons != NULL && right_as_cons != NULL) {
4621         if (left->length() < right->length()) {
4622           CheckCons(left_as_cons);
4623           cons_string = right_as_cons;
4624         } else {
4625           CheckCons(right_as_cons);
4626           cons_string = left_as_cons;
4627         }
4628         // Check fast return.
4629         if (!is_one_byte_) return false;
4630         continue;
4631       }
4632       // Descend left in place.
4633       if (left_as_cons != NULL) {
4634         cons_string = left_as_cons;
4635         continue;
4636       }
4637       // Descend right in place.
4638       if (right_as_cons != NULL) {
4639         cons_string = right_as_cons;
4640         continue;
4641       }
4642       // Terminate.
4643       break;
4644     }
4645     return is_one_byte_;
4646   }
4647   bool is_one_byte_;
4648   DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
4649 };
4650
4651
4652 bool String::ContainsOnlyOneByte() const {
4653   i::Handle<i::String> str = Utils::OpenHandle(this);
4654   if (str->HasOnlyOneByteChars()) return true;
4655   ContainsOnlyOneByteHelper helper;
4656   return helper.Check(*str);
4657 }
4658
4659
4660 class Utf8LengthHelper : public i::AllStatic {
4661  public:
4662   enum State {
4663     kEndsWithLeadingSurrogate = 1 << 0,
4664     kStartsWithTrailingSurrogate = 1 << 1,
4665     kLeftmostEdgeIsCalculated = 1 << 2,
4666     kRightmostEdgeIsCalculated = 1 << 3,
4667     kLeftmostEdgeIsSurrogate = 1 << 4,
4668     kRightmostEdgeIsSurrogate = 1 << 5
4669   };
4670
4671   static const uint8_t kInitialState = 0;
4672
4673   static inline bool EndsWithSurrogate(uint8_t state) {
4674     return state & kEndsWithLeadingSurrogate;
4675   }
4676
4677   static inline bool StartsWithSurrogate(uint8_t state) {
4678     return state & kStartsWithTrailingSurrogate;
4679   }
4680
4681   class Visitor {
4682    public:
4683     Visitor() : utf8_length_(0), state_(kInitialState) {}
4684
4685     void VisitOneByteString(const uint8_t* chars, int length) {
4686       int utf8_length = 0;
4687       // Add in length 1 for each non-Latin1 character.
4688       for (int i = 0; i < length; i++) {
4689         utf8_length += *chars++ >> 7;
4690       }
4691       // Add in length 1 for each character.
4692       utf8_length_ = utf8_length + length;
4693       state_ = kInitialState;
4694     }
4695
4696     void VisitTwoByteString(const uint16_t* chars, int length) {
4697       int utf8_length = 0;
4698       int last_character = unibrow::Utf16::kNoPreviousCharacter;
4699       for (int i = 0; i < length; i++) {
4700         uint16_t c = chars[i];
4701         utf8_length += unibrow::Utf8::Length(c, last_character);
4702         last_character = c;
4703       }
4704       utf8_length_ = utf8_length;
4705       uint8_t state = 0;
4706       if (unibrow::Utf16::IsTrailSurrogate(chars[0])) {
4707         state |= kStartsWithTrailingSurrogate;
4708       }
4709       if (unibrow::Utf16::IsLeadSurrogate(chars[length-1])) {
4710         state |= kEndsWithLeadingSurrogate;
4711       }
4712       state_ = state;
4713     }
4714
4715     static i::ConsString* VisitFlat(i::String* string,
4716                                     int* length,
4717                                     uint8_t* state) {
4718       Visitor visitor;
4719       i::ConsString* cons_string = i::String::VisitFlat(&visitor, string);
4720       *length = visitor.utf8_length_;
4721       *state = visitor.state_;
4722       return cons_string;
4723     }
4724
4725    private:
4726     int utf8_length_;
4727     uint8_t state_;
4728     DISALLOW_COPY_AND_ASSIGN(Visitor);
4729   };
4730
4731   static inline void MergeLeafLeft(int* length,
4732                                    uint8_t* state,
4733                                    uint8_t leaf_state) {
4734     bool edge_surrogate = StartsWithSurrogate(leaf_state);
4735     if (!(*state & kLeftmostEdgeIsCalculated)) {
4736       DCHECK(!(*state & kLeftmostEdgeIsSurrogate));
4737       *state |= kLeftmostEdgeIsCalculated
4738           | (edge_surrogate ? kLeftmostEdgeIsSurrogate : 0);
4739     } else if (EndsWithSurrogate(*state) && edge_surrogate) {
4740       *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4741     }
4742     if (EndsWithSurrogate(leaf_state)) {
4743       *state |= kEndsWithLeadingSurrogate;
4744     } else {
4745       *state &= ~kEndsWithLeadingSurrogate;
4746     }
4747   }
4748
4749   static inline void MergeLeafRight(int* length,
4750                                     uint8_t* state,
4751                                     uint8_t leaf_state) {
4752     bool edge_surrogate = EndsWithSurrogate(leaf_state);
4753     if (!(*state & kRightmostEdgeIsCalculated)) {
4754       DCHECK(!(*state & kRightmostEdgeIsSurrogate));
4755       *state |= (kRightmostEdgeIsCalculated
4756                  | (edge_surrogate ? kRightmostEdgeIsSurrogate : 0));
4757     } else if (edge_surrogate && StartsWithSurrogate(*state)) {
4758       *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4759     }
4760     if (StartsWithSurrogate(leaf_state)) {
4761       *state |= kStartsWithTrailingSurrogate;
4762     } else {
4763       *state &= ~kStartsWithTrailingSurrogate;
4764     }
4765   }
4766
4767   static inline void MergeTerminal(int* length,
4768                                    uint8_t state,
4769                                    uint8_t* state_out) {
4770     DCHECK((state & kLeftmostEdgeIsCalculated) &&
4771            (state & kRightmostEdgeIsCalculated));
4772     if (EndsWithSurrogate(state) && StartsWithSurrogate(state)) {
4773       *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4774     }
4775     *state_out = kInitialState |
4776         (state & kLeftmostEdgeIsSurrogate ? kStartsWithTrailingSurrogate : 0) |
4777         (state & kRightmostEdgeIsSurrogate ? kEndsWithLeadingSurrogate : 0);
4778   }
4779
4780   static int Calculate(i::ConsString* current, uint8_t* state_out) {
4781     using namespace internal;
4782     int total_length = 0;
4783     uint8_t state = kInitialState;
4784     while (true) {
4785       i::String* left = current->first();
4786       i::String* right = current->second();
4787       uint8_t right_leaf_state;
4788       uint8_t left_leaf_state;
4789       int leaf_length;
4790       ConsString* left_as_cons =
4791           Visitor::VisitFlat(left, &leaf_length, &left_leaf_state);
4792       if (left_as_cons == NULL) {
4793         total_length += leaf_length;
4794         MergeLeafLeft(&total_length, &state, left_leaf_state);
4795       }
4796       ConsString* right_as_cons =
4797           Visitor::VisitFlat(right, &leaf_length, &right_leaf_state);
4798       if (right_as_cons == NULL) {
4799         total_length += leaf_length;
4800         MergeLeafRight(&total_length, &state, right_leaf_state);
4801         if (left_as_cons != NULL) {
4802           // 1 Leaf node. Descend in place.
4803           current = left_as_cons;
4804           continue;
4805         } else {
4806           // Terminal node.
4807           MergeTerminal(&total_length, state, state_out);
4808           return total_length;
4809         }
4810       } else if (left_as_cons == NULL) {
4811         // 1 Leaf node. Descend in place.
4812         current = right_as_cons;
4813         continue;
4814       }
4815       // Both strings are ConsStrings.
4816       // Recurse on smallest.
4817       if (left->length() < right->length()) {
4818         total_length += Calculate(left_as_cons, &left_leaf_state);
4819         MergeLeafLeft(&total_length, &state, left_leaf_state);
4820         current = right_as_cons;
4821       } else {
4822         total_length += Calculate(right_as_cons, &right_leaf_state);
4823         MergeLeafRight(&total_length, &state, right_leaf_state);
4824         current = left_as_cons;
4825       }
4826     }
4827     UNREACHABLE();
4828     return 0;
4829   }
4830
4831   static inline int Calculate(i::ConsString* current) {
4832     uint8_t state = kInitialState;
4833     return Calculate(current, &state);
4834   }
4835
4836  private:
4837   DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8LengthHelper);
4838 };
4839
4840
4841 static int Utf8Length(i::String* str, i::Isolate* isolate) {
4842   int length = str->length();
4843   if (length == 0) return 0;
4844   uint8_t state;
4845   i::ConsString* cons_string =
4846       Utf8LengthHelper::Visitor::VisitFlat(str, &length, &state);
4847   if (cons_string == NULL) return length;
4848   return Utf8LengthHelper::Calculate(cons_string);
4849 }
4850
4851
4852 int String::Utf8Length() const {
4853   i::Handle<i::String> str = Utils::OpenHandle(this);
4854   i::Isolate* isolate = str->GetIsolate();
4855   return v8::Utf8Length(*str, isolate);
4856 }
4857
4858
4859 class Utf8WriterVisitor {
4860  public:
4861   Utf8WriterVisitor(
4862       char* buffer,
4863       int capacity,
4864       bool skip_capacity_check,
4865       bool replace_invalid_utf8)
4866     : early_termination_(false),
4867       last_character_(unibrow::Utf16::kNoPreviousCharacter),
4868       buffer_(buffer),
4869       start_(buffer),
4870       capacity_(capacity),
4871       skip_capacity_check_(capacity == -1 || skip_capacity_check),
4872       replace_invalid_utf8_(replace_invalid_utf8),
4873       utf16_chars_read_(0) {
4874   }
4875
4876   static int WriteEndCharacter(uint16_t character,
4877                                int last_character,
4878                                int remaining,
4879                                char* const buffer,
4880                                bool replace_invalid_utf8) {
4881     using namespace unibrow;
4882     DCHECK(remaining > 0);
4883     // We can't use a local buffer here because Encode needs to modify
4884     // previous characters in the stream.  We know, however, that
4885     // exactly one character will be advanced.
4886     if (Utf16::IsSurrogatePair(last_character, character)) {
4887       int written = Utf8::Encode(buffer,
4888                                  character,
4889                                  last_character,
4890                                  replace_invalid_utf8);
4891       DCHECK(written == 1);
4892       return written;
4893     }
4894     // Use a scratch buffer to check the required characters.
4895     char temp_buffer[Utf8::kMaxEncodedSize];
4896     // Can't encode using last_character as gcc has array bounds issues.
4897     int written = Utf8::Encode(temp_buffer,
4898                                character,
4899                                Utf16::kNoPreviousCharacter,
4900                                replace_invalid_utf8);
4901     // Won't fit.
4902     if (written > remaining) return 0;
4903     // Copy over the character from temp_buffer.
4904     for (int j = 0; j < written; j++) {
4905       buffer[j] = temp_buffer[j];
4906     }
4907     return written;
4908   }
4909
4910   // Visit writes out a group of code units (chars) of a v8::String to the
4911   // internal buffer_. This is done in two phases. The first phase calculates a
4912   // pesimistic estimate (writable_length) on how many code units can be safely
4913   // written without exceeding the buffer capacity and without writing the last
4914   // code unit (it could be a lead surrogate). The estimated number of code
4915   // units is then written out in one go, and the reported byte usage is used
4916   // to correct the estimate. This is repeated until the estimate becomes <= 0
4917   // or all code units have been written out. The second phase writes out code
4918   // units until the buffer capacity is reached, would be exceeded by the next
4919   // unit, or all units have been written out.
4920   template<typename Char>
4921   void Visit(const Char* chars, const int length) {
4922     using namespace unibrow;
4923     DCHECK(!early_termination_);
4924     if (length == 0) return;
4925     // Copy state to stack.
4926     char* buffer = buffer_;
4927     int last_character =
4928         sizeof(Char) == 1 ? Utf16::kNoPreviousCharacter : last_character_;
4929     int i = 0;
4930     // Do a fast loop where there is no exit capacity check.
4931     while (true) {
4932       int fast_length;
4933       if (skip_capacity_check_) {
4934         fast_length = length;
4935       } else {
4936         int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4937         // Need enough space to write everything but one character.
4938         STATIC_ASSERT(Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 3);
4939         int max_size_per_char =  sizeof(Char) == 1 ? 2 : 3;
4940         int writable_length =
4941             (remaining_capacity - max_size_per_char)/max_size_per_char;
4942         // Need to drop into slow loop.
4943         if (writable_length <= 0) break;
4944         fast_length = i + writable_length;
4945         if (fast_length > length) fast_length = length;
4946       }
4947       // Write the characters to the stream.
4948       if (sizeof(Char) == 1) {
4949         for (; i < fast_length; i++) {
4950           buffer +=
4951               Utf8::EncodeOneByte(buffer, static_cast<uint8_t>(*chars++));
4952           DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4953         }
4954       } else {
4955         for (; i < fast_length; i++) {
4956           uint16_t character = *chars++;
4957           buffer += Utf8::Encode(buffer,
4958                                  character,
4959                                  last_character,
4960                                  replace_invalid_utf8_);
4961           last_character = character;
4962           DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4963         }
4964       }
4965       // Array is fully written. Exit.
4966       if (fast_length == length) {
4967         // Write state back out to object.
4968         last_character_ = last_character;
4969         buffer_ = buffer;
4970         utf16_chars_read_ += length;
4971         return;
4972       }
4973     }
4974     DCHECK(!skip_capacity_check_);
4975     // Slow loop. Must check capacity on each iteration.
4976     int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4977     DCHECK(remaining_capacity >= 0);
4978     for (; i < length && remaining_capacity > 0; i++) {
4979       uint16_t character = *chars++;
4980       // remaining_capacity is <= 3 bytes at this point, so we do not write out
4981       // an umatched lead surrogate.
4982       if (replace_invalid_utf8_ && Utf16::IsLeadSurrogate(character)) {
4983         early_termination_ = true;
4984         break;
4985       }
4986       int written = WriteEndCharacter(character,
4987                                       last_character,
4988                                       remaining_capacity,
4989                                       buffer,
4990                                       replace_invalid_utf8_);
4991       if (written == 0) {
4992         early_termination_ = true;
4993         break;
4994       }
4995       buffer += written;
4996       remaining_capacity -= written;
4997       last_character = character;
4998     }
4999     // Write state back out to object.
5000     last_character_ = last_character;
5001     buffer_ = buffer;
5002     utf16_chars_read_ += i;
5003   }
5004
5005   inline bool IsDone() {
5006     return early_termination_;
5007   }
5008
5009   inline void VisitOneByteString(const uint8_t* chars, int length) {
5010     Visit(chars, length);
5011   }
5012
5013   inline void VisitTwoByteString(const uint16_t* chars, int length) {
5014     Visit(chars, length);
5015   }
5016
5017   int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
5018     // Write out number of utf16 characters written to the stream.
5019     if (utf16_chars_read_out != NULL) {
5020       *utf16_chars_read_out = utf16_chars_read_;
5021     }
5022     // Only null terminate if all of the string was written and there's space.
5023     if (write_null &&
5024         !early_termination_ &&
5025         (capacity_ == -1 || (buffer_ - start_) < capacity_)) {
5026       *buffer_++ = '\0';
5027     }
5028     return static_cast<int>(buffer_ - start_);
5029   }
5030
5031  private:
5032   bool early_termination_;
5033   int last_character_;
5034   char* buffer_;
5035   char* const start_;
5036   int capacity_;
5037   bool const skip_capacity_check_;
5038   bool const replace_invalid_utf8_;
5039   int utf16_chars_read_;
5040   DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
5041 };
5042
5043
5044 static bool RecursivelySerializeToUtf8(i::String* current,
5045                                        Utf8WriterVisitor* writer,
5046                                        int recursion_budget) {
5047   while (!writer->IsDone()) {
5048     i::ConsString* cons_string = i::String::VisitFlat(writer, current);
5049     if (cons_string == NULL) return true;  // Leaf node.
5050     if (recursion_budget <= 0) return false;
5051     // Must write the left branch first.
5052     i::String* first = cons_string->first();
5053     bool success = RecursivelySerializeToUtf8(first,
5054                                               writer,
5055                                               recursion_budget - 1);
5056     if (!success) return false;
5057     // Inline tail recurse for right branch.
5058     current = cons_string->second();
5059   }
5060   return true;
5061 }
5062
5063
5064 int String::WriteUtf8(char* buffer,
5065                       int capacity,
5066                       int* nchars_ref,
5067                       int options) const {
5068   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
5069   LOG_API(isolate, "String::WriteUtf8");
5070   ENTER_V8(isolate);
5071   i::Handle<i::String> str = Utils::OpenHandle(this);
5072   if (options & HINT_MANY_WRITES_EXPECTED) {
5073     str = i::String::Flatten(str);  // Flatten the string for efficiency.
5074   }
5075   const int string_length = str->length();
5076   bool write_null = !(options & NO_NULL_TERMINATION);
5077   bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
5078   int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
5079   // First check if we can just write the string without checking capacity.
5080   if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
5081     Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
5082     const int kMaxRecursion = 100;
5083     bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
5084     if (success) return writer.CompleteWrite(write_null, nchars_ref);
5085   } else if (capacity >= string_length) {
5086     // First check that the buffer is large enough.
5087     int utf8_bytes = v8::Utf8Length(*str, str->GetIsolate());
5088     if (utf8_bytes <= capacity) {
5089       // one-byte fast path.
5090       if (utf8_bytes == string_length) {
5091         WriteOneByte(reinterpret_cast<uint8_t*>(buffer), 0, capacity, options);
5092         if (nchars_ref != NULL) *nchars_ref = string_length;
5093         if (write_null && (utf8_bytes+1 <= capacity)) {
5094           return string_length + 1;
5095         }
5096         return string_length;
5097       }
5098       if (write_null && (utf8_bytes+1 > capacity)) {
5099         options |= NO_NULL_TERMINATION;
5100       }
5101       // Recurse once without a capacity limit.
5102       // This will get into the first branch above.
5103       // TODO(dcarney) Check max left rec. in Utf8Length and fall through.
5104       return WriteUtf8(buffer, -1, nchars_ref, options);
5105     }
5106   }
5107   // Recursive slow path can potentially be unreasonable slow. Flatten.
5108   str = i::String::Flatten(str);
5109   Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
5110   i::String::VisitFlat(&writer, *str);
5111   return writer.CompleteWrite(write_null, nchars_ref);
5112 }
5113
5114
5115 template<typename CharType>
5116 static inline int WriteHelper(const String* string,
5117                               CharType* buffer,
5118                               int start,
5119                               int length,
5120                               int options) {
5121   i::Isolate* isolate = Utils::OpenHandle(string)->GetIsolate();
5122   LOG_API(isolate, "String::Write");
5123   ENTER_V8(isolate);
5124   DCHECK(start >= 0 && length >= -1);
5125   i::Handle<i::String> str = Utils::OpenHandle(string);
5126   isolate->string_tracker()->RecordWrite(str);
5127   if (options & String::HINT_MANY_WRITES_EXPECTED) {
5128     // Flatten the string for efficiency.  This applies whether we are
5129     // using StringCharacterStream or Get(i) to access the characters.
5130     str = i::String::Flatten(str);
5131   }
5132   int end = start + length;
5133   if ((length == -1) || (length > str->length() - start) )
5134     end = str->length();
5135   if (end < 0) return 0;
5136   i::String::WriteToFlat(*str, buffer, start, end);
5137   if (!(options & String::NO_NULL_TERMINATION) &&
5138       (length == -1 || end - start < length)) {
5139     buffer[end - start] = '\0';
5140   }
5141   return end - start;
5142 }
5143
5144
5145 int String::WriteOneByte(uint8_t* buffer,
5146                          int start,
5147                          int length,
5148                          int options) const {
5149   return WriteHelper(this, buffer, start, length, options);
5150 }
5151
5152
5153 int String::Write(uint16_t* buffer,
5154                   int start,
5155                   int length,
5156                   int options) const {
5157   return WriteHelper(this, buffer, start, length, options);
5158 }
5159
5160
5161 bool v8::String::IsExternal() const {
5162   i::Handle<i::String> str = Utils::OpenHandle(this);
5163   return i::StringShape(*str).IsExternalTwoByte();
5164 }
5165
5166
5167 bool v8::String::IsExternalOneByte() const {
5168   i::Handle<i::String> str = Utils::OpenHandle(this);
5169   return i::StringShape(*str).IsExternalOneByte();
5170 }
5171
5172
5173 void v8::String::VerifyExternalStringResource(
5174     v8::String::ExternalStringResource* value) const {
5175   i::Handle<i::String> str = Utils::OpenHandle(this);
5176   const v8::String::ExternalStringResource* expected;
5177   if (i::StringShape(*str).IsExternalTwoByte()) {
5178     const void* resource =
5179         i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5180     expected = reinterpret_cast<const ExternalStringResource*>(resource);
5181   } else {
5182     expected = NULL;
5183   }
5184   CHECK_EQ(expected, value);
5185 }
5186
5187 void v8::String::VerifyExternalStringResourceBase(
5188     v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
5189   i::Handle<i::String> str = Utils::OpenHandle(this);
5190   const v8::String::ExternalStringResourceBase* expected;
5191   Encoding expectedEncoding;
5192   if (i::StringShape(*str).IsExternalOneByte()) {
5193     const void* resource =
5194         i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5195     expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5196     expectedEncoding = ONE_BYTE_ENCODING;
5197   } else if (i::StringShape(*str).IsExternalTwoByte()) {
5198     const void* resource =
5199         i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5200     expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5201     expectedEncoding = TWO_BYTE_ENCODING;
5202   } else {
5203     expected = NULL;
5204     expectedEncoding =
5205         str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
5206   }
5207   CHECK_EQ(expected, value);
5208   CHECK_EQ(expectedEncoding, encoding);
5209 }
5210
5211 const v8::String::ExternalOneByteStringResource*
5212 v8::String::GetExternalOneByteStringResource() const {
5213   i::Handle<i::String> str = Utils::OpenHandle(this);
5214   if (i::StringShape(*str).IsExternalOneByte()) {
5215     const void* resource =
5216         i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5217     return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
5218   } else {
5219     return NULL;
5220   }
5221 }
5222
5223
5224 Local<Value> Symbol::Name() const {
5225   i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
5226   i::Handle<i::Object> name(sym->name(), sym->GetIsolate());
5227   return Utils::ToLocal(name);
5228 }
5229
5230
5231 double Number::Value() const {
5232   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5233   return obj->Number();
5234 }
5235
5236
5237 bool Boolean::Value() const {
5238   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5239   return obj->IsTrue();
5240 }
5241
5242
5243 int64_t Integer::Value() const {
5244   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5245   if (obj->IsSmi()) {
5246     return i::Smi::cast(*obj)->value();
5247   } else {
5248     return static_cast<int64_t>(obj->Number());
5249   }
5250 }
5251
5252
5253 int32_t Int32::Value() const {
5254   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5255   if (obj->IsSmi()) {
5256     return i::Smi::cast(*obj)->value();
5257   } else {
5258     return static_cast<int32_t>(obj->Number());
5259   }
5260 }
5261
5262
5263 uint32_t Uint32::Value() const {
5264   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5265   if (obj->IsSmi()) {
5266     return i::Smi::cast(*obj)->value();
5267   } else {
5268     return static_cast<uint32_t>(obj->Number());
5269   }
5270 }
5271
5272
5273 int v8::Object::InternalFieldCount() {
5274   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5275   return obj->GetInternalFieldCount();
5276 }
5277
5278
5279 static bool InternalFieldOK(i::Handle<i::JSObject> obj,
5280                             int index,
5281                             const char* location) {
5282   return Utils::ApiCheck(index < obj->GetInternalFieldCount(),
5283                          location,
5284                          "Internal field out of bounds");
5285 }
5286
5287
5288 Local<Value> v8::Object::SlowGetInternalField(int index) {
5289   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5290   const char* location = "v8::Object::GetInternalField()";
5291   if (!InternalFieldOK(obj, index, location)) return Local<Value>();
5292   i::Handle<i::Object> value(obj->GetInternalField(index), obj->GetIsolate());
5293   return Utils::ToLocal(value);
5294 }
5295
5296
5297 void v8::Object::SetInternalField(int index, v8::Local<Value> value) {
5298   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5299   const char* location = "v8::Object::SetInternalField()";
5300   if (!InternalFieldOK(obj, index, location)) return;
5301   i::Handle<i::Object> val = Utils::OpenHandle(*value);
5302   obj->SetInternalField(index, *val);
5303 }
5304
5305
5306 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
5307   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5308   const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
5309   if (!InternalFieldOK(obj, index, location)) return NULL;
5310   return DecodeSmiToAligned(obj->GetInternalField(index), location);
5311 }
5312
5313
5314 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
5315   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5316   const char* location = "v8::Object::SetAlignedPointerInInternalField()";
5317   if (!InternalFieldOK(obj, index, location)) return;
5318   obj->SetInternalField(index, EncodeAlignedAsSmi(value, location));
5319   DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
5320 }
5321
5322
5323 static void* ExternalValue(i::Object* obj) {
5324   // Obscure semantics for undefined, but somehow checked in our unit tests...
5325   if (obj->IsUndefined()) return NULL;
5326   i::Object* foreign = i::JSObject::cast(obj)->GetInternalField(0);
5327   return i::Foreign::cast(foreign)->foreign_address();
5328 }
5329
5330
5331 // --- E n v i r o n m e n t ---
5332
5333
5334 void v8::V8::InitializePlatform(Platform* platform) {
5335   i::V8::InitializePlatform(platform);
5336 }
5337
5338
5339 void v8::V8::ShutdownPlatform() {
5340   i::V8::ShutdownPlatform();
5341 }
5342
5343
5344 bool v8::V8::Initialize() {
5345   i::V8::Initialize();
5346 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5347   i::ReadNatives();
5348 #endif
5349   return true;
5350 }
5351
5352
5353 void v8::V8::SetEntropySource(EntropySource entropy_source) {
5354   base::RandomNumberGenerator::SetEntropySource(entropy_source);
5355 }
5356
5357
5358 void v8::V8::SetReturnAddressLocationResolver(
5359     ReturnAddressLocationResolver return_address_resolver) {
5360   i::V8::SetReturnAddressLocationResolver(return_address_resolver);
5361 }
5362
5363 void v8::V8::SetArrayBufferAllocator(
5364     ArrayBuffer::Allocator* allocator) {
5365   if (!Utils::ApiCheck(i::V8::ArrayBufferAllocator() == NULL,
5366                        "v8::V8::SetArrayBufferAllocator",
5367                        "ArrayBufferAllocator might only be set once"))
5368     return;
5369   i::V8::SetArrayBufferAllocator(allocator);
5370 }
5371
5372
5373 bool v8::V8::Dispose() {
5374   i::V8::TearDown();
5375 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5376   i::DisposeNatives();
5377 #endif
5378   return true;
5379 }
5380
5381
5382 HeapStatistics::HeapStatistics(): total_heap_size_(0),
5383                                   total_heap_size_executable_(0),
5384                                   total_physical_size_(0),
5385                                   used_heap_size_(0),
5386                                   heap_size_limit_(0) { }
5387
5388
5389 HeapSpaceStatistics::HeapSpaceStatistics(): space_name_(0),
5390                                             space_size_(0),
5391                                             space_used_size_(0),
5392                                             space_available_size_(0),
5393                                             physical_space_size_(0) { }
5394
5395
5396 HeapObjectStatistics::HeapObjectStatistics()
5397     : object_type_(nullptr),
5398       object_sub_type_(nullptr),
5399       object_count_(0),
5400       object_size_(0) {}
5401
5402
5403 bool v8::V8::InitializeICU(const char* icu_data_file) {
5404   return i::InitializeICU(icu_data_file);
5405 }
5406
5407
5408 void v8::V8::InitializeExternalStartupData(const char* directory_path) {
5409   i::InitializeExternalStartupData(directory_path);
5410 }
5411
5412
5413 void v8::V8::InitializeExternalStartupData(const char* natives_blob,
5414                                            const char* snapshot_blob) {
5415   i::InitializeExternalStartupData(natives_blob, snapshot_blob);
5416 }
5417
5418
5419 const char* v8::V8::GetVersion() {
5420   return i::Version::GetVersion();
5421 }
5422
5423
5424 static i::Handle<i::Context> CreateEnvironment(
5425     i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
5426     v8::Local<ObjectTemplate> global_template,
5427     v8::Local<Value> maybe_global_proxy) {
5428   i::Handle<i::Context> env;
5429
5430   // Enter V8 via an ENTER_V8 scope.
5431   {
5432     ENTER_V8(isolate);
5433     v8::Local<ObjectTemplate> proxy_template = global_template;
5434     i::Handle<i::FunctionTemplateInfo> proxy_constructor;
5435     i::Handle<i::FunctionTemplateInfo> global_constructor;
5436
5437     if (!global_template.IsEmpty()) {
5438       // Make sure that the global_template has a constructor.
5439       global_constructor = EnsureConstructor(isolate, *global_template);
5440
5441       // Create a fresh template for the global proxy object.
5442       proxy_template = ObjectTemplate::New(
5443           reinterpret_cast<v8::Isolate*>(isolate));
5444       proxy_constructor = EnsureConstructor(isolate, *proxy_template);
5445
5446       // Set the global template to be the prototype template of
5447       // global proxy template.
5448       proxy_constructor->set_prototype_template(
5449           *Utils::OpenHandle(*global_template));
5450
5451       // Migrate security handlers from global_template to
5452       // proxy_template.  Temporarily removing access check
5453       // information from the global template.
5454       if (!global_constructor->access_check_info()->IsUndefined()) {
5455         proxy_constructor->set_access_check_info(
5456             global_constructor->access_check_info());
5457         proxy_constructor->set_needs_access_check(
5458             global_constructor->needs_access_check());
5459         global_constructor->set_needs_access_check(false);
5460         global_constructor->set_access_check_info(
5461             isolate->heap()->undefined_value());
5462       }
5463     }
5464
5465     i::Handle<i::Object> proxy = Utils::OpenHandle(*maybe_global_proxy, true);
5466     i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
5467     if (!proxy.is_null()) {
5468       maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(proxy);
5469     }
5470     // Create the environment.
5471     env = isolate->bootstrapper()->CreateEnvironment(
5472         maybe_proxy, proxy_template, extensions);
5473
5474     // Restore the access check info on the global template.
5475     if (!global_template.IsEmpty()) {
5476       DCHECK(!global_constructor.is_null());
5477       DCHECK(!proxy_constructor.is_null());
5478       global_constructor->set_access_check_info(
5479           proxy_constructor->access_check_info());
5480       global_constructor->set_needs_access_check(
5481           proxy_constructor->needs_access_check());
5482     }
5483   }
5484   // Leave V8.
5485
5486   return env;
5487 }
5488
5489 Local<Context> v8::Context::New(v8::Isolate* external_isolate,
5490                                 v8::ExtensionConfiguration* extensions,
5491                                 v8::Local<ObjectTemplate> global_template,
5492                                 v8::Local<Value> global_object) {
5493   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
5494   LOG_API(isolate, "Context::New");
5495   i::HandleScope scope(isolate);
5496   ExtensionConfiguration no_extensions;
5497   if (extensions == NULL) extensions = &no_extensions;
5498   i::Handle<i::Context> env =
5499       CreateEnvironment(isolate, extensions, global_template, global_object);
5500   if (env.is_null()) {
5501     if (isolate->has_pending_exception()) {
5502       isolate->OptionalRescheduleException(true);
5503     }
5504     return Local<Context>();
5505   }
5506   return Utils::ToLocal(scope.CloseAndEscape(env));
5507 }
5508
5509
5510 void v8::Context::SetSecurityToken(Local<Value> token) {
5511   i::Handle<i::Context> env = Utils::OpenHandle(this);
5512   i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
5513   env->set_security_token(*token_handle);
5514 }
5515
5516
5517 void v8::Context::UseDefaultSecurityToken() {
5518   i::Handle<i::Context> env = Utils::OpenHandle(this);
5519   env->set_security_token(env->global_object());
5520 }
5521
5522
5523 Local<Value> v8::Context::GetSecurityToken() {
5524   i::Handle<i::Context> env = Utils::OpenHandle(this);
5525   i::Isolate* isolate = env->GetIsolate();
5526   i::Object* security_token = env->security_token();
5527   i::Handle<i::Object> token_handle(security_token, isolate);
5528   return Utils::ToLocal(token_handle);
5529 }
5530
5531
5532 v8::Isolate* Context::GetIsolate() {
5533   i::Handle<i::Context> env = Utils::OpenHandle(this);
5534   return reinterpret_cast<Isolate*>(env->GetIsolate());
5535 }
5536
5537
5538 v8::Local<v8::Object> Context::Global() {
5539   i::Handle<i::Context> context = Utils::OpenHandle(this);
5540   i::Isolate* isolate = context->GetIsolate();
5541   i::Handle<i::Object> global(context->global_proxy(), isolate);
5542   // TODO(dcarney): This should always return the global proxy
5543   // but can't presently as calls to GetProtoype will return the wrong result.
5544   if (i::Handle<i::JSGlobalProxy>::cast(
5545           global)->IsDetachedFrom(context->global_object())) {
5546     global = i::Handle<i::Object>(context->global_object(), isolate);
5547   }
5548   return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
5549 }
5550
5551
5552 void Context::DetachGlobal() {
5553   i::Handle<i::Context> context = Utils::OpenHandle(this);
5554   i::Isolate* isolate = context->GetIsolate();
5555   ENTER_V8(isolate);
5556   isolate->bootstrapper()->DetachGlobal(context);
5557 }
5558
5559
5560 Local<v8::Object> Context::GetExtrasExportsObject() {
5561   i::Handle<i::Context> context = Utils::OpenHandle(this);
5562   i::Isolate* isolate = context->GetIsolate();
5563   i::Handle<i::JSObject> exports(context->extras_exports_object(), isolate);
5564   return Utils::ToLocal(exports);
5565 }
5566
5567
5568 void Context::AllowCodeGenerationFromStrings(bool allow) {
5569   i::Handle<i::Context> context = Utils::OpenHandle(this);
5570   i::Isolate* isolate = context->GetIsolate();
5571   ENTER_V8(isolate);
5572   context->set_allow_code_gen_from_strings(
5573       allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
5574 }
5575
5576
5577 bool Context::IsCodeGenerationFromStringsAllowed() {
5578   i::Handle<i::Context> context = Utils::OpenHandle(this);
5579   return !context->allow_code_gen_from_strings()->IsFalse();
5580 }
5581
5582
5583 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
5584   i::Handle<i::Context> context = Utils::OpenHandle(this);
5585   i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
5586   context->set_error_message_for_code_gen_from_strings(*error_handle);
5587 }
5588
5589
5590 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
5591   PREPARE_FOR_EXECUTION(context, "v8::ObjectTemplate::NewInstance()", Object);
5592   auto self = Utils::OpenHandle(this);
5593   Local<Object> result;
5594   has_pending_exception =
5595       !ToLocal<Object>(i::ApiNatives::InstantiateObject(self), &result);
5596   RETURN_ON_FAILED_EXECUTION(Object);
5597   RETURN_ESCAPED(result);
5598 }
5599
5600
5601 Local<v8::Object> ObjectTemplate::NewInstance() {
5602   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5603   RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object);
5604 }
5605
5606
5607 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
5608   PREPARE_FOR_EXECUTION(context, "v8::FunctionTemplate::GetFunction()",
5609                         Function);
5610   auto self = Utils::OpenHandle(this);
5611   Local<Function> result;
5612   has_pending_exception =
5613       !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
5614   RETURN_ON_FAILED_EXECUTION(Function);
5615   RETURN_ESCAPED(result);
5616 }
5617
5618
5619 Local<v8::Function> FunctionTemplate::GetFunction() {
5620   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5621   RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function);
5622 }
5623
5624
5625 bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) {
5626   auto self = Utils::OpenHandle(this);
5627   auto obj = Utils::OpenHandle(*value);
5628   return self->IsTemplateFor(*obj);
5629 }
5630
5631
5632 Local<External> v8::External::New(Isolate* isolate, void* value) {
5633   STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
5634   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5635   LOG_API(i_isolate, "External::New");
5636   ENTER_V8(i_isolate);
5637   i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
5638   return Utils::ExternalToLocal(external);
5639 }
5640
5641
5642 void* External::Value() const {
5643   return ExternalValue(*Utils::OpenHandle(this));
5644 }
5645
5646
5647 // anonymous namespace for string creation helper functions
5648 namespace {
5649
5650 inline int StringLength(const char* string) {
5651   return i::StrLength(string);
5652 }
5653
5654
5655 inline int StringLength(const uint8_t* string) {
5656   return i::StrLength(reinterpret_cast<const char*>(string));
5657 }
5658
5659
5660 inline int StringLength(const uint16_t* string) {
5661   int length = 0;
5662   while (string[length] != '\0')
5663     length++;
5664   return length;
5665 }
5666
5667
5668 MUST_USE_RESULT
5669 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5670                                            v8::NewStringType type,
5671                                            i::Vector<const char> string) {
5672   if (type == v8::NewStringType::kInternalized) {
5673     return factory->InternalizeUtf8String(string);
5674   }
5675   return factory->NewStringFromUtf8(string);
5676 }
5677
5678
5679 MUST_USE_RESULT
5680 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5681                                            v8::NewStringType type,
5682                                            i::Vector<const uint8_t> string) {
5683   if (type == v8::NewStringType::kInternalized) {
5684     return factory->InternalizeOneByteString(string);
5685   }
5686   return factory->NewStringFromOneByte(string);
5687 }
5688
5689
5690 MUST_USE_RESULT
5691 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5692                                            v8::NewStringType type,
5693                                            i::Vector<const uint16_t> string) {
5694   if (type == v8::NewStringType::kInternalized) {
5695     return factory->InternalizeTwoByteString(string);
5696   }
5697   return factory->NewStringFromTwoByte(string);
5698 }
5699
5700
5701 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
5702
5703
5704 template <typename Char>
5705 inline MaybeLocal<String> NewString(Isolate* v8_isolate, const char* location,
5706                                     const char* env, const Char* data,
5707                                     v8::NewStringType type, int length) {
5708   i::Isolate* isolate = reinterpret_cast<internal::Isolate*>(v8_isolate);
5709   if (length == 0) return String::Empty(v8_isolate);
5710   // TODO(dcarney): throw a context free exception.
5711   if (length > i::String::kMaxLength) return MaybeLocal<String>();
5712   ENTER_V8(isolate);
5713   LOG_API(isolate, env);
5714   if (length < 0) length = StringLength(data);
5715   i::Handle<i::String> result =
5716       NewString(isolate->factory(), type, i::Vector<const Char>(data, length))
5717           .ToHandleChecked();
5718   return Utils::ToLocal(result);
5719 }
5720
5721 }  // anonymous namespace
5722
5723
5724 Local<String> String::NewFromUtf8(Isolate* isolate,
5725                                   const char* data,
5726                                   NewStringType type,
5727                                   int length) {
5728   RETURN_TO_LOCAL_UNCHECKED(
5729       NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5730                 data, static_cast<v8::NewStringType>(type), length),
5731       String);
5732 }
5733
5734
5735 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
5736                                        v8::NewStringType type, int length) {
5737   return NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5738                    data, type, length);
5739 }
5740
5741
5742 Local<String> String::NewFromOneByte(Isolate* isolate,
5743                                      const uint8_t* data,
5744                                      NewStringType type,
5745                                      int length) {
5746   RETURN_TO_LOCAL_UNCHECKED(
5747       NewString(isolate, "v8::String::NewFromOneByte()",
5748                 "String::NewFromOneByte", data,
5749                 static_cast<v8::NewStringType>(type), length),
5750       String);
5751 }
5752
5753
5754 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
5755                                           v8::NewStringType type, int length) {
5756   return NewString(isolate, "v8::String::NewFromOneByte()",
5757                    "String::NewFromOneByte", data, type, length);
5758 }
5759
5760
5761 Local<String> String::NewFromTwoByte(Isolate* isolate,
5762                                      const uint16_t* data,
5763                                      NewStringType type,
5764                                      int length) {
5765   RETURN_TO_LOCAL_UNCHECKED(
5766       NewString(isolate, "v8::String::NewFromTwoByte()",
5767                 "String::NewFromTwoByte", data,
5768                 static_cast<v8::NewStringType>(type), length),
5769       String);
5770 }
5771
5772
5773 MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate,
5774                                           const uint16_t* data,
5775                                           v8::NewStringType type, int length) {
5776   return NewString(isolate, "v8::String::NewFromTwoByte()",
5777                    "String::NewFromTwoByte", data, type, length);
5778 }
5779
5780
5781 Local<String> v8::String::Concat(Local<String> left, Local<String> right) {
5782   i::Handle<i::String> left_string = Utils::OpenHandle(*left);
5783   i::Isolate* isolate = left_string->GetIsolate();
5784   ENTER_V8(isolate);
5785   LOG_API(isolate, "v8::String::Concat");
5786   i::Handle<i::String> right_string = Utils::OpenHandle(*right);
5787   // If we are steering towards a range error, do not wait for the error to be
5788   // thrown, and return the null handle instead.
5789   if (left_string->length() + right_string->length() > i::String::kMaxLength) {
5790     return Local<String>();
5791   }
5792   i::Handle<i::String> result = isolate->factory()->NewConsString(
5793       left_string, right_string).ToHandleChecked();
5794   return Utils::ToLocal(result);
5795 }
5796
5797
5798 MaybeLocal<String> v8::String::NewExternalTwoByte(
5799     Isolate* isolate, v8::String::ExternalStringResource* resource) {
5800   CHECK(resource && resource->data());
5801   // TODO(dcarney): throw a context free exception.
5802   if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5803     return MaybeLocal<String>();
5804   }
5805   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5806   ENTER_V8(i_isolate);
5807   LOG_API(i_isolate, "String::NewExternalTwoByte");
5808   i::Handle<i::String> string = i_isolate->factory()
5809                                     ->NewExternalStringFromTwoByte(resource)
5810                                     .ToHandleChecked();
5811   i_isolate->heap()->external_string_table()->AddString(*string);
5812   return Utils::ToLocal(string);
5813 }
5814
5815
5816 Local<String> v8::String::NewExternal(
5817     Isolate* isolate, v8::String::ExternalStringResource* resource) {
5818   RETURN_TO_LOCAL_UNCHECKED(NewExternalTwoByte(isolate, resource), String);
5819 }
5820
5821
5822 MaybeLocal<String> v8::String::NewExternalOneByte(
5823     Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5824   CHECK(resource && resource->data());
5825   // TODO(dcarney): throw a context free exception.
5826   if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5827     return MaybeLocal<String>();
5828   }
5829   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5830   ENTER_V8(i_isolate);
5831   LOG_API(i_isolate, "String::NewExternalOneByte");
5832   i::Handle<i::String> string = i_isolate->factory()
5833                                     ->NewExternalStringFromOneByte(resource)
5834                                     .ToHandleChecked();
5835   i_isolate->heap()->external_string_table()->AddString(*string);
5836   return Utils::ToLocal(string);
5837 }
5838
5839
5840 Local<String> v8::String::NewExternal(
5841     Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5842   RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
5843 }
5844
5845
5846 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
5847   i::Handle<i::String> obj = Utils::OpenHandle(this);
5848   i::Isolate* isolate = obj->GetIsolate();
5849   if (i::StringShape(*obj).IsExternal()) {
5850     return false;  // Already an external string.
5851   }
5852   ENTER_V8(isolate);
5853   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
5854     return false;
5855   }
5856   if (isolate->heap()->IsInGCPostProcessing()) {
5857     return false;
5858   }
5859   CHECK(resource && resource->data());
5860
5861   bool result = obj->MakeExternal(resource);
5862   // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5863   DCHECK(!CanMakeExternal() || result);
5864   if (result) {
5865     DCHECK(obj->IsExternalString());
5866     isolate->heap()->external_string_table()->AddString(*obj);
5867   }
5868   return result;
5869 }
5870
5871
5872 bool v8::String::MakeExternal(
5873     v8::String::ExternalOneByteStringResource* resource) {
5874   i::Handle<i::String> obj = Utils::OpenHandle(this);
5875   i::Isolate* isolate = obj->GetIsolate();
5876   if (i::StringShape(*obj).IsExternal()) {
5877     return false;  // Already an external string.
5878   }
5879   ENTER_V8(isolate);
5880   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
5881     return false;
5882   }
5883   if (isolate->heap()->IsInGCPostProcessing()) {
5884     return false;
5885   }
5886   CHECK(resource && resource->data());
5887
5888   bool result = obj->MakeExternal(resource);
5889   // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5890   DCHECK(!CanMakeExternal() || result);
5891   if (result) {
5892     DCHECK(obj->IsExternalString());
5893     isolate->heap()->external_string_table()->AddString(*obj);
5894   }
5895   return result;
5896 }
5897
5898
5899 bool v8::String::CanMakeExternal() {
5900   i::Handle<i::String> obj = Utils::OpenHandle(this);
5901   i::Isolate* isolate = obj->GetIsolate();
5902
5903   if (isolate->string_tracker()->IsFreshUnusedString(obj)) return false;
5904   int size = obj->Size();  // Byte size of the original string.
5905   if (size < i::ExternalString::kShortSize) return false;
5906   i::StringShape shape(*obj);
5907   return !shape.IsExternal();
5908 }
5909
5910
5911 Isolate* v8::Object::GetIsolate() {
5912   i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
5913   return reinterpret_cast<Isolate*>(i_isolate);
5914 }
5915
5916
5917 Local<v8::Object> v8::Object::New(Isolate* isolate) {
5918   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5919   LOG_API(i_isolate, "Object::New");
5920   ENTER_V8(i_isolate);
5921   i::Handle<i::JSObject> obj =
5922       i_isolate->factory()->NewJSObject(i_isolate->object_function());
5923   return Utils::ToLocal(obj);
5924 }
5925
5926
5927 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
5928   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5929   LOG_API(i_isolate, "NumberObject::New");
5930   ENTER_V8(i_isolate);
5931   i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
5932   i::Handle<i::Object> obj =
5933       i::Object::ToObject(i_isolate, number).ToHandleChecked();
5934   return Utils::ToLocal(obj);
5935 }
5936
5937
5938 double v8::NumberObject::ValueOf() const {
5939   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5940   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5941   i::Isolate* isolate = jsvalue->GetIsolate();
5942   LOG_API(isolate, "NumberObject::NumberValue");
5943   return jsvalue->value()->Number();
5944 }
5945
5946
5947 Local<v8::Value> v8::BooleanObject::New(bool value) {
5948   i::Isolate* isolate = i::Isolate::Current();
5949   LOG_API(isolate, "BooleanObject::New");
5950   ENTER_V8(isolate);
5951   i::Handle<i::Object> boolean(value
5952                                ? isolate->heap()->true_value()
5953                                : isolate->heap()->false_value(),
5954                                isolate);
5955   i::Handle<i::Object> obj =
5956       i::Object::ToObject(isolate, boolean).ToHandleChecked();
5957   return Utils::ToLocal(obj);
5958 }
5959
5960
5961 bool v8::BooleanObject::ValueOf() const {
5962   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5963   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5964   i::Isolate* isolate = jsvalue->GetIsolate();
5965   LOG_API(isolate, "BooleanObject::BooleanValue");
5966   return jsvalue->value()->IsTrue();
5967 }
5968
5969
5970 Local<v8::Value> v8::StringObject::New(Local<String> value) {
5971   i::Handle<i::String> string = Utils::OpenHandle(*value);
5972   i::Isolate* isolate = string->GetIsolate();
5973   LOG_API(isolate, "StringObject::New");
5974   ENTER_V8(isolate);
5975   i::Handle<i::Object> obj =
5976       i::Object::ToObject(isolate, string).ToHandleChecked();
5977   return Utils::ToLocal(obj);
5978 }
5979
5980
5981 Local<v8::String> v8::StringObject::ValueOf() const {
5982   i::Handle<i::Object> obj = Utils::OpenHandle(this);
5983   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5984   i::Isolate* isolate = jsvalue->GetIsolate();
5985   LOG_API(isolate, "StringObject::StringValue");
5986   return Utils::ToLocal(
5987       i::Handle<i::String>(i::String::cast(jsvalue->value())));
5988 }
5989
5990
5991 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
5992   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5993   LOG_API(i_isolate, "SymbolObject::New");
5994   ENTER_V8(i_isolate);
5995   i::Handle<i::Object> obj = i::Object::ToObject(
5996       i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
5997   return Utils::ToLocal(obj);
5998 }
5999
6000
6001 Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
6002   i::Handle<i::Object> obj = Utils::OpenHandle(this);
6003   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
6004   i::Isolate* isolate = jsvalue->GetIsolate();
6005   LOG_API(isolate, "SymbolObject::SymbolValue");
6006   return Utils::ToLocal(
6007       i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value())));
6008 }
6009
6010
6011 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
6012   if (std::isnan(time)) {
6013     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6014     time = std::numeric_limits<double>::quiet_NaN();
6015   }
6016   PREPARE_FOR_EXECUTION(context, "Date::New", Value);
6017   Local<Value> result;
6018   has_pending_exception =
6019       !ToLocal<Value>(i::Execution::NewDate(isolate, time), &result);
6020   RETURN_ON_FAILED_EXECUTION(Value);
6021   RETURN_ESCAPED(result);
6022 }
6023
6024
6025 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
6026   auto context = isolate->GetCurrentContext();
6027   RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value);
6028 }
6029
6030
6031 double v8::Date::ValueOf() const {
6032   i::Handle<i::Object> obj = Utils::OpenHandle(this);
6033   i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
6034   i::Isolate* isolate = jsdate->GetIsolate();
6035   LOG_API(isolate, "Date::NumberValue");
6036   return jsdate->value()->Number();
6037 }
6038
6039
6040 void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) {
6041   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6042   LOG_API(i_isolate, "Date::DateTimeConfigurationChangeNotification");
6043   ENTER_V8(i_isolate);
6044   i_isolate->date_cache()->ResetDateCache();
6045   if (!i_isolate->eternal_handles()->Exists(
6046           i::EternalHandles::DATE_CACHE_VERSION)) {
6047     return;
6048   }
6049   i::Handle<i::FixedArray> date_cache_version =
6050       i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton(
6051           i::EternalHandles::DATE_CACHE_VERSION));
6052   DCHECK_EQ(1, date_cache_version->length());
6053   CHECK(date_cache_version->get(0)->IsSmi());
6054   date_cache_version->set(
6055       0,
6056       i::Smi::FromInt(i::Smi::cast(date_cache_version->get(0))->value() + 1));
6057 }
6058
6059
6060 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
6061   i::Isolate* isolate = i::Isolate::Current();
6062   uint8_t flags_buf[3];
6063   int num_flags = 0;
6064   if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
6065   if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
6066   if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
6067   DCHECK(num_flags <= static_cast<int>(arraysize(flags_buf)));
6068   return isolate->factory()->InternalizeOneByteString(
6069       i::Vector<const uint8_t>(flags_buf, num_flags));
6070 }
6071
6072
6073 MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context,
6074                                        Local<String> pattern, Flags flags) {
6075   PREPARE_FOR_EXECUTION(context, "RegExp::New", RegExp);
6076   Local<v8::RegExp> result;
6077   has_pending_exception =
6078       !ToLocal<RegExp>(i::Execution::NewJSRegExp(Utils::OpenHandle(*pattern),
6079                                                  RegExpFlagsToString(flags)),
6080                        &result);
6081   RETURN_ON_FAILED_EXECUTION(RegExp);
6082   RETURN_ESCAPED(result);
6083 }
6084
6085
6086 Local<v8::RegExp> v8::RegExp::New(Local<String> pattern, Flags flags) {
6087   auto isolate =
6088       reinterpret_cast<Isolate*>(Utils::OpenHandle(*pattern)->GetIsolate());
6089   auto context = isolate->GetCurrentContext();
6090   RETURN_TO_LOCAL_UNCHECKED(New(context, pattern, flags), RegExp);
6091 }
6092
6093
6094 Local<v8::String> v8::RegExp::GetSource() const {
6095   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6096   return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
6097 }
6098
6099
6100 // Assert that the static flags cast in GetFlags is valid.
6101 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag)          \
6102   STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) ==       \
6103                 static_cast<int>(i::JSRegExp::internal_flag))
6104 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
6105 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
6106 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
6107 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
6108 #undef REGEXP_FLAG_ASSERT_EQ
6109
6110 v8::RegExp::Flags v8::RegExp::GetFlags() const {
6111   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6112   return static_cast<RegExp::Flags>(obj->GetFlags().value());
6113 }
6114
6115
6116 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
6117   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6118   LOG_API(i_isolate, "Array::New");
6119   ENTER_V8(i_isolate);
6120   int real_length = length > 0 ? length : 0;
6121   i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
6122   i::Handle<i::Object> length_obj =
6123       i_isolate->factory()->NewNumberFromInt(real_length);
6124   obj->set_length(*length_obj);
6125   return Utils::ToLocal(obj);
6126 }
6127
6128
6129 uint32_t v8::Array::Length() const {
6130   i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
6131   i::Object* length = obj->length();
6132   if (length->IsSmi()) {
6133     return i::Smi::cast(length)->value();
6134   } else {
6135     return static_cast<uint32_t>(length->Number());
6136   }
6137 }
6138
6139
6140 MaybeLocal<Object> Array::CloneElementAt(Local<Context> context,
6141                                          uint32_t index) {
6142   PREPARE_FOR_EXECUTION(context, "v8::Array::CloneElementAt()", Object);
6143   auto self = Utils::OpenHandle(this);
6144   if (!self->HasFastObjectElements()) return Local<Object>();
6145   i::FixedArray* elms = i::FixedArray::cast(self->elements());
6146   i::Object* paragon = elms->get(index);
6147   if (!paragon->IsJSObject()) return Local<Object>();
6148   i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
6149   Local<Object> result;
6150   has_pending_exception =
6151       !ToLocal<Object>(isolate->factory()->CopyJSObject(paragon_handle),
6152                        &result);
6153   RETURN_ON_FAILED_EXECUTION(Object);
6154   RETURN_ESCAPED(result);
6155 }
6156
6157
6158 Local<Object> Array::CloneElementAt(uint32_t index) {
6159   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6160   RETURN_TO_LOCAL_UNCHECKED(CloneElementAt(context, index), Object);
6161 }
6162
6163
6164 Local<v8::Map> v8::Map::New(Isolate* isolate) {
6165   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6166   LOG_API(i_isolate, "Map::New");
6167   ENTER_V8(i_isolate);
6168   i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
6169   return Utils::ToLocal(obj);
6170 }
6171
6172
6173 size_t v8::Map::Size() const {
6174   i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6175   return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
6176 }
6177
6178
6179 void Map::Clear() {
6180   auto self = Utils::OpenHandle(this);
6181   i::Isolate* isolate = self->GetIsolate();
6182   LOG_API(isolate, "Map::Clear");
6183   ENTER_V8(isolate);
6184   i::Runtime::JSMapClear(isolate, self);
6185 }
6186
6187
6188 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
6189   PREPARE_FOR_EXECUTION(context, "Map::Get", Value);
6190   auto self = Utils::OpenHandle(this);
6191   Local<Value> result;
6192   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6193   has_pending_exception =
6194       !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
6195                                          arraysize(argv), argv, false),
6196                       &result);
6197   RETURN_ON_FAILED_EXECUTION(Value);
6198   RETURN_ESCAPED(result);
6199 }
6200
6201
6202 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
6203                          Local<Value> value) {
6204   PREPARE_FOR_EXECUTION(context, "Map::Set", Map);
6205   auto self = Utils::OpenHandle(this);
6206   i::Handle<i::Object> result;
6207   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
6208                                  Utils::OpenHandle(*value)};
6209   has_pending_exception =
6210       !i::Execution::Call(isolate, isolate->map_set(), self, arraysize(argv),
6211                           argv, false).ToHandle(&result);
6212   RETURN_ON_FAILED_EXECUTION(Map);
6213   RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6214 }
6215
6216
6217 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
6218   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Has", bool);
6219   auto self = Utils::OpenHandle(this);
6220   i::Handle<i::Object> result;
6221   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6222   has_pending_exception =
6223       !i::Execution::Call(isolate, isolate->map_has(), self, arraysize(argv),
6224                           argv, false).ToHandle(&result);
6225   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6226   return Just(result->IsTrue());
6227 }
6228
6229
6230 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
6231   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Delete", bool);
6232   auto self = Utils::OpenHandle(this);
6233   i::Handle<i::Object> result;
6234   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6235   has_pending_exception =
6236       !i::Execution::Call(isolate, isolate->map_delete(), self, arraysize(argv),
6237                           argv, false).ToHandle(&result);
6238   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6239   return Just(result->IsTrue());
6240 }
6241
6242
6243 Local<Array> Map::AsArray() const {
6244   i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6245   i::Isolate* isolate = obj->GetIsolate();
6246   i::Factory* factory = isolate->factory();
6247   LOG_API(isolate, "Map::AsArray");
6248   ENTER_V8(isolate);
6249   i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(obj->table()));
6250   int size = table->NumberOfElements();
6251   int length = size * 2;
6252   i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6253   for (int i = 0; i < size; ++i) {
6254     if (table->KeyAt(i)->IsTheHole()) continue;
6255     result->set(i * 2, table->KeyAt(i));
6256     result->set(i * 2 + 1, table->ValueAt(i));
6257   }
6258   i::Handle<i::JSArray> result_array =
6259       factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6260   return Utils::ToLocal(result_array);
6261 }
6262
6263
6264 MaybeLocal<Map> Map::FromArray(Local<Context> context, Local<Array> array) {
6265   PREPARE_FOR_EXECUTION(context, "Map::FromArray", Map);
6266   if (array->Length() % 2 != 0) {
6267     return MaybeLocal<Map>();
6268   }
6269   i::Handle<i::Object> result;
6270   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6271   has_pending_exception =
6272       !i::Execution::Call(isolate, isolate->map_from_array(),
6273                           isolate->factory()->undefined_value(),
6274                           arraysize(argv), argv, false).ToHandle(&result);
6275   RETURN_ON_FAILED_EXECUTION(Map);
6276   RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6277 }
6278
6279
6280 Local<v8::Set> v8::Set::New(Isolate* isolate) {
6281   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6282   LOG_API(i_isolate, "Set::New");
6283   ENTER_V8(i_isolate);
6284   i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
6285   return Utils::ToLocal(obj);
6286 }
6287
6288
6289 size_t v8::Set::Size() const {
6290   i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6291   return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
6292 }
6293
6294
6295 void Set::Clear() {
6296   auto self = Utils::OpenHandle(this);
6297   i::Isolate* isolate = self->GetIsolate();
6298   LOG_API(isolate, "Set::Clear");
6299   ENTER_V8(isolate);
6300   i::Runtime::JSSetClear(isolate, self);
6301 }
6302
6303
6304 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
6305   PREPARE_FOR_EXECUTION(context, "Set::Add", Set);
6306   auto self = Utils::OpenHandle(this);
6307   i::Handle<i::Object> result;
6308   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6309   has_pending_exception =
6310       !i::Execution::Call(isolate, isolate->set_add(), self, arraysize(argv),
6311                           argv, false).ToHandle(&result);
6312   RETURN_ON_FAILED_EXECUTION(Set);
6313   RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6314 }
6315
6316
6317 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
6318   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Has", bool);
6319   auto self = Utils::OpenHandle(this);
6320   i::Handle<i::Object> result;
6321   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6322   has_pending_exception =
6323       !i::Execution::Call(isolate, isolate->set_has(), self, arraysize(argv),
6324                           argv, false).ToHandle(&result);
6325   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6326   return Just(result->IsTrue());
6327 }
6328
6329
6330 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
6331   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Delete", bool);
6332   auto self = Utils::OpenHandle(this);
6333   i::Handle<i::Object> result;
6334   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6335   has_pending_exception =
6336       !i::Execution::Call(isolate, isolate->set_delete(), self, arraysize(argv),
6337                           argv, false).ToHandle(&result);
6338   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6339   return Just(result->IsTrue());
6340 }
6341
6342
6343 Local<Array> Set::AsArray() const {
6344   i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6345   i::Isolate* isolate = obj->GetIsolate();
6346   i::Factory* factory = isolate->factory();
6347   LOG_API(isolate, "Set::AsArray");
6348   ENTER_V8(isolate);
6349   i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(obj->table()));
6350   int length = table->NumberOfElements();
6351   i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6352   for (int i = 0; i < length; ++i) {
6353     i::Object* key = table->KeyAt(i);
6354     if (!key->IsTheHole()) {
6355       result->set(i, key);
6356     }
6357   }
6358   i::Handle<i::JSArray> result_array =
6359       factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6360   return Utils::ToLocal(result_array);
6361 }
6362
6363
6364 MaybeLocal<Set> Set::FromArray(Local<Context> context, Local<Array> array) {
6365   PREPARE_FOR_EXECUTION(context, "Set::FromArray", Set);
6366   i::Handle<i::Object> result;
6367   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6368   has_pending_exception =
6369       !i::Execution::Call(isolate, isolate->set_from_array(),
6370                           isolate->factory()->undefined_value(),
6371                           arraysize(argv), argv, false).ToHandle(&result);
6372   RETURN_ON_FAILED_EXECUTION(Set);
6373   RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6374 }
6375
6376
6377 bool Value::IsPromise() const {
6378   auto self = Utils::OpenHandle(this);
6379   return i::Object::IsPromise(self);
6380 }
6381
6382
6383 MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) {
6384   PREPARE_FOR_EXECUTION(context, "Promise::Resolver::New", Resolver);
6385   i::Handle<i::Object> result;
6386   has_pending_exception = !i::Execution::Call(
6387       isolate,
6388       isolate->promise_create(),
6389       isolate->factory()->undefined_value(),
6390       0, NULL,
6391       false).ToHandle(&result);
6392   RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
6393   RETURN_ESCAPED(Local<Promise::Resolver>::Cast(Utils::ToLocal(result)));
6394 }
6395
6396
6397 Local<Promise::Resolver> Promise::Resolver::New(Isolate* isolate) {
6398   RETURN_TO_LOCAL_UNCHECKED(New(isolate->GetCurrentContext()),
6399                             Promise::Resolver);
6400 }
6401
6402
6403 Local<Promise> Promise::Resolver::GetPromise() {
6404   i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6405   return Local<Promise>::Cast(Utils::ToLocal(promise));
6406 }
6407
6408
6409 Maybe<bool> Promise::Resolver::Resolve(Local<Context> context,
6410                                        Local<Value> value) {
6411   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6412   auto self = Utils::OpenHandle(this);
6413   i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6414   has_pending_exception = i::Execution::Call(
6415       isolate,
6416       isolate->promise_resolve(),
6417       isolate->factory()->undefined_value(),
6418       arraysize(argv), argv,
6419       false).is_null();
6420   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6421   return Just(true);
6422 }
6423
6424
6425 void Promise::Resolver::Resolve(Local<Value> value) {
6426   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6427   USE(Resolve(context, value));
6428 }
6429
6430
6431 Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
6432                                       Local<Value> value) {
6433   PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6434   auto self = Utils::OpenHandle(this);
6435   i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6436   has_pending_exception = i::Execution::Call(
6437       isolate,
6438       isolate->promise_reject(),
6439       isolate->factory()->undefined_value(),
6440       arraysize(argv), argv,
6441       false).is_null();
6442   RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6443   return Just(true);
6444 }
6445
6446
6447 void Promise::Resolver::Reject(Local<Value> value) {
6448   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6449   USE(Reject(context, value));
6450 }
6451
6452
6453 MaybeLocal<Promise> Promise::Chain(Local<Context> context,
6454                                    Local<Function> handler) {
6455   PREPARE_FOR_EXECUTION(context, "Promise::Chain", Promise);
6456   auto self = Utils::OpenHandle(this);
6457   i::Handle<i::Object> argv[] = {Utils::OpenHandle(*handler)};
6458   i::Handle<i::Object> result;
6459   has_pending_exception =
6460       !i::Execution::Call(isolate, isolate->promise_chain(), self,
6461                           arraysize(argv), argv, false).ToHandle(&result);
6462   RETURN_ON_FAILED_EXECUTION(Promise);
6463   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6464 }
6465
6466
6467 Local<Promise> Promise::Chain(Local<Function> handler) {
6468   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6469   RETURN_TO_LOCAL_UNCHECKED(Chain(context, handler), Promise);
6470 }
6471
6472
6473 MaybeLocal<Promise> Promise::Catch(Local<Context> context,
6474                                    Local<Function> handler) {
6475   PREPARE_FOR_EXECUTION(context, "Promise::Catch", Promise);
6476   auto self = Utils::OpenHandle(this);
6477   i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6478   i::Handle<i::Object> result;
6479   has_pending_exception =
6480       !i::Execution::Call(isolate, isolate->promise_catch(), self,
6481                           arraysize(argv), argv, false).ToHandle(&result);
6482   RETURN_ON_FAILED_EXECUTION(Promise);
6483   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6484 }
6485
6486
6487 Local<Promise> Promise::Catch(Local<Function> handler) {
6488   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6489   RETURN_TO_LOCAL_UNCHECKED(Catch(context, handler), Promise);
6490 }
6491
6492
6493 MaybeLocal<Promise> Promise::Then(Local<Context> context,
6494                                   Local<Function> handler) {
6495   PREPARE_FOR_EXECUTION(context, "Promise::Then", Promise);
6496   auto self = Utils::OpenHandle(this);
6497   i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6498   i::Handle<i::Object> result;
6499   has_pending_exception =
6500       !i::Execution::Call(isolate, isolate->promise_then(), self,
6501                           arraysize(argv), argv, false).ToHandle(&result);
6502   RETURN_ON_FAILED_EXECUTION(Promise);
6503   RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6504 }
6505
6506
6507 Local<Promise> Promise::Then(Local<Function> handler) {
6508   auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6509   RETURN_TO_LOCAL_UNCHECKED(Then(context, handler), Promise);
6510 }
6511
6512
6513 bool Promise::HasHandler() {
6514   i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6515   i::Isolate* isolate = promise->GetIsolate();
6516   LOG_API(isolate, "Promise::HasRejectHandler");
6517   ENTER_V8(isolate);
6518   i::Handle<i::Symbol> key = isolate->factory()->promise_has_handler_symbol();
6519   return i::JSReceiver::GetDataProperty(promise, key)->IsTrue();
6520 }
6521
6522
6523 bool v8::ArrayBuffer::IsExternal() const {
6524   return Utils::OpenHandle(this)->is_external();
6525 }
6526
6527
6528 bool v8::ArrayBuffer::IsNeuterable() const {
6529   return Utils::OpenHandle(this)->is_neuterable();
6530 }
6531
6532
6533 v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
6534   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6535   i::Isolate* isolate = self->GetIsolate();
6536   Utils::ApiCheck(!self->is_external(), "v8::ArrayBuffer::Externalize",
6537                   "ArrayBuffer already externalized");
6538   self->set_is_external(true);
6539   isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6540                                          self->backing_store());
6541
6542   return GetContents();
6543 }
6544
6545
6546 v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() {
6547   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6548   size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6549   Contents contents;
6550   contents.data_ = self->backing_store();
6551   contents.byte_length_ = byte_length;
6552   return contents;
6553 }
6554
6555
6556 void v8::ArrayBuffer::Neuter() {
6557   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6558   i::Isolate* isolate = obj->GetIsolate();
6559   Utils::ApiCheck(obj->is_external(),
6560                   "v8::ArrayBuffer::Neuter",
6561                   "Only externalized ArrayBuffers can be neutered");
6562   Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter",
6563                   "Only neuterable ArrayBuffers can be neutered");
6564   LOG_API(obj->GetIsolate(), "v8::ArrayBuffer::Neuter()");
6565   ENTER_V8(isolate);
6566   i::Runtime::NeuterArrayBuffer(obj);
6567 }
6568
6569
6570 size_t v8::ArrayBuffer::ByteLength() const {
6571   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6572   return static_cast<size_t>(obj->byte_length()->Number());
6573 }
6574
6575
6576 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
6577   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6578   LOG_API(i_isolate, "v8::ArrayBuffer::New(size_t)");
6579   ENTER_V8(i_isolate);
6580   i::Handle<i::JSArrayBuffer> obj =
6581       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6582   i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length);
6583   return Utils::ToLocal(obj);
6584 }
6585
6586
6587 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
6588                                         size_t byte_length,
6589                                         ArrayBufferCreationMode mode) {
6590   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6591   LOG_API(i_isolate, "v8::ArrayBuffer::New(void*, size_t)");
6592   ENTER_V8(i_isolate);
6593   i::Handle<i::JSArrayBuffer> obj =
6594       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6595   i::Runtime::SetupArrayBuffer(i_isolate, obj,
6596                                mode == ArrayBufferCreationMode::kExternalized,
6597                                data, byte_length);
6598   return Utils::ToLocal(obj);
6599 }
6600
6601
6602 Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
6603   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6604   i::Handle<i::JSArrayBuffer> buffer;
6605   if (obj->IsJSDataView()) {
6606     i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj));
6607     DCHECK(data_view->buffer()->IsJSArrayBuffer());
6608     buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()));
6609   } else {
6610     DCHECK(obj->IsJSTypedArray());
6611     buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
6612   }
6613   return Utils::ToLocal(buffer);
6614 }
6615
6616
6617 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
6618   i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6619   i::Isolate* isolate = self->GetIsolate();
6620   size_t byte_offset = i::NumberToSize(isolate, self->byte_offset());
6621   size_t bytes_to_copy =
6622       i::Min(byte_length, i::NumberToSize(isolate, self->byte_length()));
6623   if (bytes_to_copy) {
6624     i::DisallowHeapAllocation no_gc;
6625     i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6626     const char* source = reinterpret_cast<char*>(buffer->backing_store());
6627     if (source == nullptr) {
6628       DCHECK(self->IsJSTypedArray());
6629       i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self));
6630       i::Handle<i::FixedTypedArrayBase> fixed_array(
6631           i::FixedTypedArrayBase::cast(typed_array->elements()));
6632       source = reinterpret_cast<char*>(fixed_array->DataPtr());
6633     }
6634     memcpy(dest, source + byte_offset, bytes_to_copy);
6635   }
6636   return bytes_to_copy;
6637 }
6638
6639
6640 bool v8::ArrayBufferView::HasBuffer() const {
6641   i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6642   i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6643   return buffer->backing_store() != nullptr;
6644 }
6645
6646
6647 size_t v8::ArrayBufferView::ByteOffset() {
6648   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6649   return static_cast<size_t>(obj->byte_offset()->Number());
6650 }
6651
6652
6653 size_t v8::ArrayBufferView::ByteLength() {
6654   i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6655   return static_cast<size_t>(obj->byte_length()->Number());
6656 }
6657
6658
6659 size_t v8::TypedArray::Length() {
6660   i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
6661   return static_cast<size_t>(obj->length_value());
6662 }
6663
6664
6665 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype, size)                        \
6666   Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer,        \
6667                                       size_t byte_offset, size_t length) {    \
6668     i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate();     \
6669     LOG_API(isolate,                                                          \
6670             "v8::" #Type "Array::New(Local<ArrayBuffer>, size_t, size_t)");   \
6671     ENTER_V8(isolate);                                                        \
6672     if (!Utils::ApiCheck(length <= static_cast<size_t>(i::Smi::kMaxValue),    \
6673                          "v8::" #Type                                         \
6674                          "Array::New(Local<ArrayBuffer>, size_t, size_t)",    \
6675                          "length exceeds max allowed value")) {               \
6676       return Local<Type##Array>();                                            \
6677     }                                                                         \
6678     i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);    \
6679     i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray(     \
6680         i::kExternal##Type##Array, buffer, byte_offset, length);              \
6681     return Utils::ToLocal##Type##Array(obj);                                  \
6682   }                                                                           \
6683   Local<Type##Array> Type##Array::New(                                        \
6684       Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,       \
6685       size_t length) {                                                        \
6686     CHECK(i::FLAG_harmony_sharedarraybuffer);                                 \
6687     i::Isolate* isolate =                                                     \
6688         Utils::OpenHandle(*shared_array_buffer)->GetIsolate();                \
6689     LOG_API(isolate, "v8::" #Type                                             \
6690                      "Array::New(Local<SharedArrayBuffer>, size_t, size_t)"); \
6691     ENTER_V8(isolate);                                                        \
6692     if (!Utils::ApiCheck(                                                     \
6693             length <= static_cast<size_t>(i::Smi::kMaxValue),                 \
6694             "v8::" #Type                                                      \
6695             "Array::New(Local<SharedArrayBuffer>, size_t, size_t)",           \
6696             "length exceeds max allowed value")) {                            \
6697       return Local<Type##Array>();                                            \
6698     }                                                                         \
6699     i::Handle<i::JSArrayBuffer> buffer =                                      \
6700         Utils::OpenHandle(*shared_array_buffer);                              \
6701     i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray(     \
6702         i::kExternal##Type##Array, buffer, byte_offset, length);              \
6703     return Utils::ToLocal##Type##Array(obj);                                  \
6704   }
6705
6706
6707 TYPED_ARRAYS(TYPED_ARRAY_NEW)
6708 #undef TYPED_ARRAY_NEW
6709
6710 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
6711                               size_t byte_offset, size_t byte_length) {
6712   i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
6713   i::Isolate* isolate = buffer->GetIsolate();
6714   LOG_API(isolate, "v8::DataView::New(Local<ArrayBuffer>, size_t, size_t)");
6715   ENTER_V8(isolate);
6716   i::Handle<i::JSDataView> obj =
6717       isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6718   return Utils::ToLocal(obj);
6719 }
6720
6721
6722 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
6723                               size_t byte_offset, size_t byte_length) {
6724   CHECK(i::FLAG_harmony_sharedarraybuffer);
6725   i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
6726   i::Isolate* isolate = buffer->GetIsolate();
6727   LOG_API(isolate,
6728           "v8::DataView::New(Local<SharedArrayBuffer>, size_t, size_t)");
6729   ENTER_V8(isolate);
6730   i::Handle<i::JSDataView> obj =
6731       isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6732   return Utils::ToLocal(obj);
6733 }
6734
6735
6736 bool v8::SharedArrayBuffer::IsExternal() const {
6737   return Utils::OpenHandle(this)->is_external();
6738 }
6739
6740
6741 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
6742   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6743   i::Isolate* isolate = self->GetIsolate();
6744   Utils::ApiCheck(!self->is_external(), "v8::SharedArrayBuffer::Externalize",
6745                   "SharedArrayBuffer already externalized");
6746   self->set_is_external(true);
6747   isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6748                                          self->backing_store());
6749   return GetContents();
6750 }
6751
6752
6753 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
6754   i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6755   size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6756   Contents contents;
6757   contents.data_ = self->backing_store();
6758   contents.byte_length_ = byte_length;
6759   return contents;
6760 }
6761
6762
6763 size_t v8::SharedArrayBuffer::ByteLength() const {
6764   i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6765   return static_cast<size_t>(obj->byte_length()->Number());
6766 }
6767
6768
6769 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate,
6770                                                     size_t byte_length) {
6771   CHECK(i::FLAG_harmony_sharedarraybuffer);
6772   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6773   LOG_API(i_isolate, "v8::SharedArrayBuffer::New(size_t)");
6774   ENTER_V8(i_isolate);
6775   i::Handle<i::JSArrayBuffer> obj =
6776       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6777   i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length, true,
6778                                              i::SharedFlag::kShared);
6779   return Utils::ToLocalShared(obj);
6780 }
6781
6782
6783 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
6784     Isolate* isolate, void* data, size_t byte_length,
6785     ArrayBufferCreationMode mode) {
6786   CHECK(i::FLAG_harmony_sharedarraybuffer);
6787   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6788   LOG_API(i_isolate, "v8::SharedArrayBuffer::New(void*, size_t)");
6789   ENTER_V8(i_isolate);
6790   i::Handle<i::JSArrayBuffer> obj =
6791       i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6792   i::Runtime::SetupArrayBuffer(i_isolate, obj,
6793                                mode == ArrayBufferCreationMode::kExternalized,
6794                                data, byte_length, i::SharedFlag::kShared);
6795   return Utils::ToLocalShared(obj);
6796 }
6797
6798
6799 Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
6800   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6801   LOG_API(i_isolate, "Symbol::New()");
6802   ENTER_V8(i_isolate);
6803   i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
6804   if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
6805   return Utils::ToLocal(result);
6806 }
6807
6808
6809 static i::Handle<i::Symbol> SymbolFor(i::Isolate* isolate,
6810                                       i::Handle<i::String> name,
6811                                       i::Handle<i::String> part) {
6812   i::Handle<i::JSObject> registry = isolate->GetSymbolRegistry();
6813   i::Handle<i::JSObject> symbols =
6814       i::Handle<i::JSObject>::cast(
6815           i::Object::GetPropertyOrElement(registry, part).ToHandleChecked());
6816   i::Handle<i::Object> symbol =
6817       i::Object::GetPropertyOrElement(symbols, name).ToHandleChecked();
6818   if (!symbol->IsSymbol()) {
6819     DCHECK(symbol->IsUndefined());
6820     symbol = isolate->factory()->NewSymbol();
6821     i::Handle<i::Symbol>::cast(symbol)->set_name(*name);
6822     i::JSObject::SetProperty(symbols, name, symbol, i::STRICT).Assert();
6823   }
6824   return i::Handle<i::Symbol>::cast(symbol);
6825 }
6826
6827
6828 Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
6829   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6830   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6831   i::Handle<i::String> part = i_isolate->factory()->for_string();
6832   return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6833 }
6834
6835
6836 Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
6837   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6838   i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6839   i::Handle<i::String> part = i_isolate->factory()->for_api_string();
6840   return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6841 }
6842
6843
6844 Local<Symbol> v8::Symbol::GetIterator(Isolate* isolate) {
6845   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6846   return Utils::ToLocal(i_isolate->factory()->iterator_symbol());
6847 }
6848
6849
6850 Local<Symbol> v8::Symbol::GetUnscopables(Isolate* isolate) {
6851   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6852   return Utils::ToLocal(i_isolate->factory()->unscopables_symbol());
6853 }
6854
6855
6856 Local<Symbol> v8::Symbol::GetToStringTag(Isolate* isolate) {
6857   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6858   return Utils::ToLocal(i_isolate->factory()->to_string_tag_symbol());
6859 }
6860
6861
6862 Local<Number> v8::Number::New(Isolate* isolate, double value) {
6863   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6864   if (std::isnan(value)) {
6865     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6866     value = std::numeric_limits<double>::quiet_NaN();
6867   }
6868   ENTER_V8(internal_isolate);
6869   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6870   return Utils::NumberToLocal(result);
6871 }
6872
6873
6874 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
6875   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6876   if (i::Smi::IsValid(value)) {
6877     return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
6878                                                       internal_isolate));
6879   }
6880   ENTER_V8(internal_isolate);
6881   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6882   return Utils::IntegerToLocal(result);
6883 }
6884
6885
6886 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
6887   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6888   bool fits_into_int32_t = (value & (1 << 31)) == 0;
6889   if (fits_into_int32_t) {
6890     return Integer::New(isolate, static_cast<int32_t>(value));
6891   }
6892   ENTER_V8(internal_isolate);
6893   i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6894   return Utils::IntegerToLocal(result);
6895 }
6896
6897
6898 void Isolate::CollectAllGarbage(const char* gc_reason) {
6899   reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
6900       i::Heap::kNoGCFlags, gc_reason);
6901 }
6902
6903
6904 HeapProfiler* Isolate::GetHeapProfiler() {
6905   i::HeapProfiler* heap_profiler =
6906       reinterpret_cast<i::Isolate*>(this)->heap_profiler();
6907   return reinterpret_cast<HeapProfiler*>(heap_profiler);
6908 }
6909
6910
6911 CpuProfiler* Isolate::GetCpuProfiler() {
6912   i::CpuProfiler* cpu_profiler =
6913       reinterpret_cast<i::Isolate*>(this)->cpu_profiler();
6914   return reinterpret_cast<CpuProfiler*>(cpu_profiler);
6915 }
6916
6917
6918 bool Isolate::InContext() {
6919   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6920   return isolate->context() != NULL;
6921 }
6922
6923
6924 v8::Local<v8::Context> Isolate::GetCurrentContext() {
6925   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6926   i::Context* context = isolate->context();
6927   if (context == NULL) return Local<Context>();
6928   i::Context* native_context = context->native_context();
6929   if (native_context == NULL) return Local<Context>();
6930   return Utils::ToLocal(i::Handle<i::Context>(native_context));
6931 }
6932
6933
6934 v8::Local<v8::Context> Isolate::GetCallingContext() {
6935   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6936   i::Handle<i::Object> calling = isolate->GetCallingNativeContext();
6937   if (calling.is_null()) return Local<Context>();
6938   return Utils::ToLocal(i::Handle<i::Context>::cast(calling));
6939 }
6940
6941
6942 v8::Local<v8::Context> Isolate::GetEnteredContext() {
6943   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6944   i::Handle<i::Object> last =
6945       isolate->handle_scope_implementer()->LastEnteredContext();
6946   if (last.is_null()) return Local<Context>();
6947   return Utils::ToLocal(i::Handle<i::Context>::cast(last));
6948 }
6949
6950
6951 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
6952   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6953   ENTER_V8(isolate);
6954   // If we're passed an empty handle, we throw an undefined exception
6955   // to deal more gracefully with out of memory situations.
6956   if (value.IsEmpty()) {
6957     isolate->ScheduleThrow(isolate->heap()->undefined_value());
6958   } else {
6959     isolate->ScheduleThrow(*Utils::OpenHandle(*value));
6960   }
6961   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
6962 }
6963
6964
6965 void Isolate::SetObjectGroupId(internal::Object** object, UniqueId id) {
6966   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6967   internal_isolate->global_handles()->SetObjectGroupId(
6968       v8::internal::Handle<v8::internal::Object>(object).location(),
6969       id);
6970 }
6971
6972
6973 void Isolate::SetReferenceFromGroup(UniqueId id, internal::Object** object) {
6974   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6975   internal_isolate->global_handles()->SetReferenceFromGroup(
6976       id,
6977       v8::internal::Handle<v8::internal::Object>(object).location());
6978 }
6979
6980
6981 void Isolate::SetReference(internal::Object** parent,
6982                            internal::Object** child) {
6983   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6984   i::Object** parent_location =
6985       v8::internal::Handle<v8::internal::Object>(parent).location();
6986   internal_isolate->global_handles()->SetReference(
6987       reinterpret_cast<i::HeapObject**>(parent_location),
6988       v8::internal::Handle<v8::internal::Object>(child).location());
6989 }
6990
6991
6992 void Isolate::AddGCPrologueCallback(GCPrologueCallback callback,
6993                                     GCType gc_type) {
6994   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6995   isolate->heap()->AddGCPrologueCallback(callback, gc_type);
6996 }
6997
6998
6999 void Isolate::RemoveGCPrologueCallback(GCPrologueCallback callback) {
7000   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7001   isolate->heap()->RemoveGCPrologueCallback(callback);
7002 }
7003
7004
7005 void Isolate::AddGCEpilogueCallback(GCEpilogueCallback callback,
7006                                     GCType gc_type) {
7007   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7008   isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
7009 }
7010
7011
7012 void Isolate::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
7013   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7014   isolate->heap()->RemoveGCEpilogueCallback(callback);
7015 }
7016
7017
7018 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
7019   i::Isolate* isolate = i::Isolate::Current();
7020   isolate->heap()->AddGCPrologueCallback(
7021       reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback),
7022       gc_type,
7023       false);
7024 }
7025
7026
7027 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
7028   i::Isolate* isolate = i::Isolate::Current();
7029   isolate->heap()->AddGCEpilogueCallback(
7030       reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback),
7031       gc_type,
7032       false);
7033 }
7034
7035
7036 void Isolate::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
7037                                           ObjectSpace space,
7038                                           AllocationAction action) {
7039   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7040   isolate->memory_allocator()->AddMemoryAllocationCallback(
7041       callback, space, action);
7042 }
7043
7044
7045 void Isolate::RemoveMemoryAllocationCallback(
7046     MemoryAllocationCallback callback) {
7047   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7048   isolate->memory_allocator()->RemoveMemoryAllocationCallback(
7049       callback);
7050 }
7051
7052
7053 void Isolate::TerminateExecution() {
7054   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7055   isolate->stack_guard()->RequestTerminateExecution();
7056 }
7057
7058
7059 bool Isolate::IsExecutionTerminating() {
7060   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7061   return IsExecutionTerminatingCheck(isolate);
7062 }
7063
7064
7065 void Isolate::CancelTerminateExecution() {
7066   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7067   isolate->stack_guard()->ClearTerminateExecution();
7068   isolate->CancelTerminateExecution();
7069 }
7070
7071
7072 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
7073   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7074   isolate->RequestInterrupt(callback, data);
7075 }
7076
7077
7078 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
7079   CHECK(i::FLAG_expose_gc);
7080   if (type == kMinorGarbageCollection) {
7081     reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
7082         i::NEW_SPACE, "Isolate::RequestGarbageCollection",
7083         kGCCallbackFlagForced);
7084   } else {
7085     DCHECK_EQ(kFullGarbageCollection, type);
7086     reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
7087         i::Heap::kAbortIncrementalMarkingMask,
7088         "Isolate::RequestGarbageCollection", kGCCallbackFlagForced);
7089   }
7090 }
7091
7092
7093 Isolate* Isolate::GetCurrent() {
7094   i::Isolate* isolate = i::Isolate::Current();
7095   return reinterpret_cast<Isolate*>(isolate);
7096 }
7097
7098
7099 Isolate* Isolate::New() {
7100   Isolate::CreateParams create_params;
7101   return New(create_params);
7102 }
7103
7104
7105 Isolate* Isolate::New(const Isolate::CreateParams& params) {
7106   i::Isolate* isolate = new i::Isolate(false);
7107   Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7108   if (params.array_buffer_allocator != NULL) {
7109     isolate->set_array_buffer_allocator(params.array_buffer_allocator);
7110   } else {
7111     isolate->set_array_buffer_allocator(i::V8::ArrayBufferAllocator());
7112   }
7113   if (params.snapshot_blob != NULL) {
7114     isolate->set_snapshot_blob(params.snapshot_blob);
7115   } else {
7116     isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
7117   }
7118   if (params.entry_hook) {
7119     isolate->set_function_entry_hook(params.entry_hook);
7120   }
7121   if (params.code_event_handler) {
7122     isolate->InitializeLoggingAndCounters();
7123     isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
7124                                            params.code_event_handler);
7125   }
7126   if (params.counter_lookup_callback) {
7127     v8_isolate->SetCounterFunction(params.counter_lookup_callback);
7128   }
7129
7130   if (params.create_histogram_callback) {
7131     v8_isolate->SetCreateHistogramFunction(params.create_histogram_callback);
7132   }
7133
7134   if (params.add_histogram_sample_callback) {
7135     v8_isolate->SetAddHistogramSampleFunction(
7136         params.add_histogram_sample_callback);
7137   }
7138   SetResourceConstraints(isolate, params.constraints);
7139   // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
7140   Isolate::Scope isolate_scope(v8_isolate);
7141   if (params.entry_hook || !i::Snapshot::Initialize(isolate)) {
7142     // If the isolate has a function entry hook, it needs to re-build all its
7143     // code stubs with entry hooks embedded, so don't deserialize a snapshot.
7144     if (i::Snapshot::EmbedsScript(isolate)) {
7145       // If the snapshot embeds a script, we cannot initialize the isolate
7146       // without the snapshot as a fallback. This is unlikely to happen though.
7147       V8_Fatal(__FILE__, __LINE__,
7148                "Initializing isolate from custom startup snapshot failed");
7149     }
7150     isolate->Init(NULL);
7151   }
7152   return v8_isolate;
7153 }
7154
7155
7156 void Isolate::Dispose() {
7157   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7158   if (!Utils::ApiCheck(!isolate->IsInUse(),
7159                        "v8::Isolate::Dispose()",
7160                        "Disposing the isolate that is entered by a thread.")) {
7161     return;
7162   }
7163   isolate->TearDown();
7164 }
7165
7166
7167 void Isolate::Enter() {
7168   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7169   isolate->Enter();
7170 }
7171
7172
7173 void Isolate::Exit() {
7174   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7175   isolate->Exit();
7176 }
7177
7178
7179 void Isolate::SetAbortOnUncaughtExceptionCallback(
7180     AbortOnUncaughtExceptionCallback callback) {
7181   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7182   isolate->SetAbortOnUncaughtExceptionCallback(callback);
7183 }
7184
7185
7186 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
7187     Isolate* isolate,
7188     Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
7189     : on_failure_(on_failure) {
7190   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7191   if (on_failure_ == CRASH_ON_FAILURE) {
7192     internal_ = reinterpret_cast<void*>(
7193         new i::DisallowJavascriptExecution(i_isolate));
7194   } else {
7195     DCHECK_EQ(THROW_ON_FAILURE, on_failure);
7196     internal_ = reinterpret_cast<void*>(
7197         new i::ThrowOnJavascriptExecution(i_isolate));
7198   }
7199 }
7200
7201
7202 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
7203   if (on_failure_ == CRASH_ON_FAILURE) {
7204     delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
7205   } else {
7206     delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
7207   }
7208 }
7209
7210
7211 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
7212     Isolate* isolate) {
7213   i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7214   internal_assert_ = reinterpret_cast<void*>(
7215       new i::AllowJavascriptExecution(i_isolate));
7216   internal_throws_ = reinterpret_cast<void*>(
7217       new i::NoThrowOnJavascriptExecution(i_isolate));
7218 }
7219
7220
7221 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
7222   delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
7223   delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
7224 }
7225
7226
7227 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
7228     Isolate* isolate)
7229     : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
7230   isolate_->handle_scope_implementer()->IncrementCallDepth();
7231 }
7232
7233
7234 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
7235   isolate_->handle_scope_implementer()->DecrementCallDepth();
7236 }
7237
7238
7239 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
7240   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7241   i::Heap* heap = isolate->heap();
7242   heap_statistics->total_heap_size_ = heap->CommittedMemory();
7243   heap_statistics->total_heap_size_executable_ =
7244       heap->CommittedMemoryExecutable();
7245   heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
7246   heap_statistics->total_available_size_ = heap->Available();
7247   heap_statistics->used_heap_size_ = heap->SizeOfObjects();
7248   heap_statistics->heap_size_limit_ = heap->MaxReserved();
7249 }
7250
7251
7252 size_t Isolate::NumberOfHeapSpaces() {
7253   return i::LAST_SPACE - i::FIRST_SPACE + 1;
7254 }
7255
7256
7257 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7258                                      size_t index) {
7259   if (!space_statistics) return false;
7260   if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
7261     return false;
7262
7263   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7264   i::Heap* heap = isolate->heap();
7265   i::Space* space = heap->space(static_cast<int>(index));
7266
7267   space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
7268   space_statistics->space_size_ = space->CommittedMemory();
7269   space_statistics->space_used_size_ = space->SizeOfObjects();
7270   space_statistics->space_available_size_ = space->Available();
7271   space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
7272   return true;
7273 }
7274
7275
7276 size_t Isolate::NumberOfTrackedHeapObjectTypes() {
7277   return i::Heap::OBJECT_STATS_COUNT;
7278 }
7279
7280
7281 bool Isolate::GetHeapObjectStatisticsAtLastGC(
7282     HeapObjectStatistics* object_statistics, size_t type_index) {
7283   if (!object_statistics) return false;
7284   if (type_index >= i::Heap::OBJECT_STATS_COUNT) return false;
7285   if (!i::FLAG_track_gc_object_stats) return false;
7286
7287   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7288   i::Heap* heap = isolate->heap();
7289   const char* object_type;
7290   const char* object_sub_type;
7291   size_t object_count = heap->object_count_last_gc(type_index);
7292   size_t object_size = heap->object_size_last_gc(type_index);
7293   if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
7294     // There should be no objects counted when the type is unknown.
7295     DCHECK_EQ(object_count, 0U);
7296     DCHECK_EQ(object_size, 0U);
7297     return false;
7298   }
7299
7300   object_statistics->object_type_ = object_type;
7301   object_statistics->object_sub_type_ = object_sub_type;
7302   object_statistics->object_count_ = object_count;
7303   object_statistics->object_size_ = object_size;
7304   return true;
7305 }
7306
7307
7308 void Isolate::GetStackSample(const RegisterState& state, void** frames,
7309                              size_t frames_limit, SampleInfo* sample_info) {
7310   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7311   i::TickSample::GetStackSample(isolate, state, i::TickSample::kSkipCEntryFrame,
7312                                 frames, frames_limit, sample_info);
7313 }
7314
7315
7316 void Isolate::SetEventLogger(LogEventCallback that) {
7317   // Do not overwrite the event logger if we want to log explicitly.
7318   if (i::FLAG_log_internal_timer_events) return;
7319   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7320   isolate->set_event_logger(that);
7321 }
7322
7323
7324 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
7325   if (callback == NULL) return;
7326   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7327   isolate->AddCallCompletedCallback(callback);
7328 }
7329
7330
7331 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
7332   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7333   isolate->RemoveCallCompletedCallback(callback);
7334 }
7335
7336
7337 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
7338   if (callback == NULL) return;
7339   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7340   isolate->SetPromiseRejectCallback(callback);
7341 }
7342
7343
7344 void Isolate::RunMicrotasks() {
7345   reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
7346 }
7347
7348
7349 void Isolate::EnqueueMicrotask(Local<Function> microtask) {
7350   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7351   isolate->EnqueueMicrotask(Utils::OpenHandle(*microtask));
7352 }
7353
7354
7355 void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) {
7356   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7357   i::HandleScope scope(isolate);
7358   i::Handle<i::CallHandlerInfo> callback_info =
7359       i::Handle<i::CallHandlerInfo>::cast(
7360           isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE));
7361   SET_FIELD_WRAPPED(callback_info, set_callback, microtask);
7362   SET_FIELD_WRAPPED(callback_info, set_data, data);
7363   isolate->EnqueueMicrotask(callback_info);
7364 }
7365
7366
7367 void Isolate::SetAutorunMicrotasks(bool autorun) {
7368   reinterpret_cast<i::Isolate*>(this)->set_autorun_microtasks(autorun);
7369 }
7370
7371
7372 bool Isolate::WillAutorunMicrotasks() const {
7373   return reinterpret_cast<const i::Isolate*>(this)->autorun_microtasks();
7374 }
7375
7376
7377 void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
7378   reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
7379 }
7380
7381
7382 void Isolate::SetCounterFunction(CounterLookupCallback callback) {
7383   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7384   isolate->stats_table()->SetCounterFunction(callback);
7385   isolate->InitializeLoggingAndCounters();
7386   isolate->counters()->ResetCounters();
7387 }
7388
7389
7390 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
7391   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7392   isolate->stats_table()->SetCreateHistogramFunction(callback);
7393   isolate->InitializeLoggingAndCounters();
7394   isolate->counters()->ResetHistograms();
7395 }
7396
7397
7398 void Isolate::SetAddHistogramSampleFunction(
7399     AddHistogramSampleCallback callback) {
7400   reinterpret_cast<i::Isolate*>(this)
7401       ->stats_table()
7402       ->SetAddHistogramSampleFunction(callback);
7403 }
7404
7405
7406 bool Isolate::IdleNotification(int idle_time_in_ms) {
7407   // Returning true tells the caller that it need not
7408   // continue to call IdleNotification.
7409   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7410   if (!i::FLAG_use_idle_notification) return true;
7411   return isolate->heap()->IdleNotification(idle_time_in_ms);
7412 }
7413
7414
7415 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
7416   // Returning true tells the caller that it need not
7417   // continue to call IdleNotification.
7418   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7419   if (!i::FLAG_use_idle_notification) return true;
7420   return isolate->heap()->IdleNotification(deadline_in_seconds);
7421 }
7422
7423
7424 void Isolate::LowMemoryNotification() {
7425   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7426   {
7427     i::HistogramTimerScope idle_notification_scope(
7428         isolate->counters()->gc_low_memory_notification());
7429     isolate->heap()->CollectAllAvailableGarbage("low memory notification");
7430   }
7431 }
7432
7433
7434 int Isolate::ContextDisposedNotification(bool dependant_context) {
7435   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7436   return isolate->heap()->NotifyContextDisposed(dependant_context);
7437 }
7438
7439
7440 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
7441                                      JitCodeEventHandler event_handler) {
7442   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7443   // Ensure that logging is initialized for our isolate.
7444   isolate->InitializeLoggingAndCounters();
7445   isolate->logger()->SetCodeEventHandler(options, event_handler);
7446 }
7447
7448
7449 void Isolate::SetStackLimit(uintptr_t stack_limit) {
7450   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7451   CHECK(stack_limit);
7452   isolate->stack_guard()->SetStackLimit(stack_limit);
7453 }
7454
7455
7456 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
7457   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7458   if (isolate->code_range()->valid()) {
7459     *start = isolate->code_range()->start();
7460     *length_in_bytes = isolate->code_range()->size();
7461   } else {
7462     *start = NULL;
7463     *length_in_bytes = 0;
7464   }
7465 }
7466
7467
7468 void Isolate::SetFatalErrorHandler(FatalErrorCallback that) {
7469   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7470   isolate->set_exception_behavior(that);
7471 }
7472
7473
7474 void Isolate::SetAllowCodeGenerationFromStringsCallback(
7475     AllowCodeGenerationFromStringsCallback callback) {
7476   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7477   isolate->set_allow_code_gen_callback(callback);
7478 }
7479
7480
7481 bool Isolate::IsDead() {
7482   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7483   return isolate->IsDead();
7484 }
7485
7486
7487 bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
7488   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7489   ENTER_V8(isolate);
7490   i::HandleScope scope(isolate);
7491   NeanderArray listeners(isolate->factory()->message_listeners());
7492   NeanderObject obj(isolate, 2);
7493   obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
7494   obj.set(1, data.IsEmpty() ? isolate->heap()->undefined_value()
7495                             : *Utils::OpenHandle(*data));
7496   listeners.add(isolate, obj.value());
7497   return true;
7498 }
7499
7500
7501 void Isolate::RemoveMessageListeners(MessageCallback that) {
7502   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7503   ENTER_V8(isolate);
7504   i::HandleScope scope(isolate);
7505   NeanderArray listeners(isolate->factory()->message_listeners());
7506   for (int i = 0; i < listeners.length(); i++) {
7507     if (listeners.get(i)->IsUndefined()) continue;  // skip deleted ones
7508
7509     NeanderObject listener(i::JSObject::cast(listeners.get(i)));
7510     i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
7511     if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
7512       listeners.set(i, isolate->heap()->undefined_value());
7513     }
7514   }
7515 }
7516
7517
7518 void Isolate::SetFailedAccessCheckCallbackFunction(
7519     FailedAccessCheckCallback callback) {
7520   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7521   isolate->SetFailedAccessCheckCallback(callback);
7522 }
7523
7524
7525 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
7526     bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7527   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7528   isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7529                                                      options);
7530 }
7531
7532
7533 void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) {
7534   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7535   isolate->heap()->VisitExternalResources(visitor);
7536 }
7537
7538
7539 class VisitorAdapter : public i::ObjectVisitor {
7540  public:
7541   explicit VisitorAdapter(PersistentHandleVisitor* visitor)
7542       : visitor_(visitor) {}
7543   virtual void VisitPointers(i::Object** start, i::Object** end) {
7544     UNREACHABLE();
7545   }
7546   virtual void VisitEmbedderReference(i::Object** p, uint16_t class_id) {
7547     Value* value = ToApi<Value>(i::Handle<i::Object>(p));
7548     visitor_->VisitPersistentHandle(
7549         reinterpret_cast<Persistent<Value>*>(&value), class_id);
7550   }
7551
7552  private:
7553   PersistentHandleVisitor* visitor_;
7554 };
7555
7556
7557 void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
7558   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7559   i::DisallowHeapAllocation no_allocation;
7560   VisitorAdapter visitor_adapter(visitor);
7561   isolate->global_handles()->IterateAllRootsWithClassIds(&visitor_adapter);
7562 }
7563
7564
7565 void Isolate::VisitHandlesForPartialDependence(
7566     PersistentHandleVisitor* visitor) {
7567   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7568   i::DisallowHeapAllocation no_allocation;
7569   VisitorAdapter visitor_adapter(visitor);
7570   isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds(
7571       &visitor_adapter);
7572 }
7573
7574
7575 String::Utf8Value::Utf8Value(v8::Local<v8::Value> obj)
7576     : str_(NULL), length_(0) {
7577   if (obj.IsEmpty()) return;
7578   i::Isolate* isolate = i::Isolate::Current();
7579   Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7580   ENTER_V8(isolate);
7581   i::HandleScope scope(isolate);
7582   Local<Context> context = v8_isolate->GetCurrentContext();
7583   TryCatch try_catch(v8_isolate);
7584   Local<String> str;
7585   if (!obj->ToString(context).ToLocal(&str)) return;
7586   i::Handle<i::String> i_str = Utils::OpenHandle(*str);
7587   length_ = v8::Utf8Length(*i_str, isolate);
7588   str_ = i::NewArray<char>(length_ + 1);
7589   str->WriteUtf8(str_);
7590 }
7591
7592
7593 String::Utf8Value::~Utf8Value() {
7594   i::DeleteArray(str_);
7595 }
7596
7597
7598 String::Value::Value(v8::Local<v8::Value> obj) : str_(NULL), length_(0) {
7599   if (obj.IsEmpty()) return;
7600   i::Isolate* isolate = i::Isolate::Current();
7601   Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7602   ENTER_V8(isolate);
7603   i::HandleScope scope(isolate);
7604   Local<Context> context = v8_isolate->GetCurrentContext();
7605   TryCatch try_catch(v8_isolate);
7606   Local<String> str;
7607   if (!obj->ToString(context).ToLocal(&str)) return;
7608   length_ = str->Length();
7609   str_ = i::NewArray<uint16_t>(length_ + 1);
7610   str->Write(str_);
7611 }
7612
7613
7614 String::Value::~Value() {
7615   i::DeleteArray(str_);
7616 }
7617
7618
7619 #define DEFINE_ERROR(NAME)                                            \
7620   Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) {   \
7621     i::Isolate* isolate = i::Isolate::Current();                      \
7622     LOG_API(isolate, #NAME);                                          \
7623     ENTER_V8(isolate);                                                \
7624     i::Object* error;                                                 \
7625     {                                                                 \
7626       i::HandleScope scope(isolate);                                  \
7627       i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \
7628       error = *isolate->factory()->NewError("$" #NAME, message);      \
7629     }                                                                 \
7630     i::Handle<i::Object> result(error, isolate);                      \
7631     return Utils::ToLocal(result);                                    \
7632   }
7633
7634 DEFINE_ERROR(RangeError)
7635 DEFINE_ERROR(ReferenceError)
7636 DEFINE_ERROR(SyntaxError)
7637 DEFINE_ERROR(TypeError)
7638 DEFINE_ERROR(Error)
7639
7640 #undef DEFINE_ERROR
7641
7642
7643 Local<Message> Exception::CreateMessage(Local<Value> exception) {
7644   i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7645   if (!obj->IsHeapObject()) return Local<Message>();
7646   i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
7647   ENTER_V8(isolate);
7648   i::HandleScope scope(isolate);
7649   return Utils::MessageToLocal(
7650       scope.CloseAndEscape(isolate->CreateMessage(obj, NULL)));
7651 }
7652
7653
7654 Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) {
7655   i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7656   if (!obj->IsJSObject()) return Local<StackTrace>();
7657   i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
7658   i::Isolate* isolate = js_obj->GetIsolate();
7659   ENTER_V8(isolate);
7660   return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj));
7661 }
7662
7663
7664 // --- D e b u g   S u p p o r t ---
7665
7666 bool Debug::SetDebugEventListener(EventCallback that, Local<Value> data) {
7667   i::Isolate* isolate = i::Isolate::Current();
7668   ENTER_V8(isolate);
7669   i::HandleScope scope(isolate);
7670   i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
7671   if (that != NULL) {
7672     foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
7673   }
7674   isolate->debug()->SetEventListener(foreign,
7675                                      Utils::OpenHandle(*data, true));
7676   return true;
7677 }
7678
7679
7680 void Debug::DebugBreak(Isolate* isolate) {
7681   reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->RequestDebugBreak();
7682 }
7683
7684
7685 void Debug::CancelDebugBreak(Isolate* isolate) {
7686   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7687   internal_isolate->stack_guard()->ClearDebugBreak();
7688 }
7689
7690
7691 bool Debug::CheckDebugBreak(Isolate* isolate) {
7692   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7693   return internal_isolate->stack_guard()->CheckDebugBreak();
7694 }
7695
7696
7697 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
7698   i::Isolate* isolate = i::Isolate::Current();
7699   ENTER_V8(isolate);
7700   isolate->debug()->SetMessageHandler(handler);
7701 }
7702
7703
7704 void Debug::SendCommand(Isolate* isolate,
7705                         const uint16_t* command,
7706                         int length,
7707                         ClientData* client_data) {
7708   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7709   internal_isolate->debug()->EnqueueCommandMessage(
7710       i::Vector<const uint16_t>(command, length), client_data);
7711 }
7712
7713
7714 MaybeLocal<Value> Debug::Call(Local<Context> context,
7715                               v8::Local<v8::Function> fun,
7716                               v8::Local<v8::Value> data) {
7717   PREPARE_FOR_EXECUTION(context, "v8::Debug::Call()", Value);
7718   i::Handle<i::Object> data_obj;
7719   if (data.IsEmpty()) {
7720     data_obj = isolate->factory()->undefined_value();
7721   } else {
7722     data_obj = Utils::OpenHandle(*data);
7723   }
7724   Local<Value> result;
7725   has_pending_exception =
7726       !ToLocal<Value>(isolate->debug()->Call(Utils::OpenHandle(*fun), data_obj),
7727                       &result);
7728   RETURN_ON_FAILED_EXECUTION(Value);
7729   RETURN_ESCAPED(result);
7730 }
7731
7732
7733 Local<Value> Debug::Call(v8::Local<v8::Function> fun,
7734                          v8::Local<v8::Value> data) {
7735   auto context = ContextFromHeapObject(Utils::OpenHandle(*fun));
7736   RETURN_TO_LOCAL_UNCHECKED(Call(context, fun, data), Value);
7737 }
7738
7739
7740 MaybeLocal<Value> Debug::GetMirror(Local<Context> context,
7741                                    v8::Local<v8::Value> obj) {
7742   PREPARE_FOR_EXECUTION(context, "v8::Debug::GetMirror()", Value);
7743   i::Debug* isolate_debug = isolate->debug();
7744   has_pending_exception = !isolate_debug->Load();
7745   RETURN_ON_FAILED_EXECUTION(Value);
7746   i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global_object());
7747   auto name = isolate->factory()->NewStringFromStaticChars("MakeMirror");
7748   auto fun_obj = i::Object::GetProperty(debug, name).ToHandleChecked();
7749   auto v8_fun = Utils::ToLocal(i::Handle<i::JSFunction>::cast(fun_obj));
7750   const int kArgc = 1;
7751   v8::Local<v8::Value> argv[kArgc] = {obj};
7752   Local<Value> result;
7753   has_pending_exception = !v8_fun->Call(context, Utils::ToLocal(debug), kArgc,
7754                                         argv).ToLocal(&result);
7755   RETURN_ON_FAILED_EXECUTION(Value);
7756   RETURN_ESCAPED(result);
7757 }
7758
7759
7760 Local<Value> Debug::GetMirror(v8::Local<v8::Value> obj) {
7761   RETURN_TO_LOCAL_UNCHECKED(GetMirror(Local<Context>(), obj), Value);
7762 }
7763
7764
7765 void Debug::ProcessDebugMessages() {
7766   i::Isolate::Current()->debug()->ProcessDebugMessages(true);
7767 }
7768
7769
7770 Local<Context> Debug::GetDebugContext() {
7771   i::Isolate* isolate = i::Isolate::Current();
7772   ENTER_V8(isolate);
7773   return Utils::ToLocal(isolate->debug()->GetDebugContext());
7774 }
7775
7776
7777 void Debug::SetLiveEditEnabled(Isolate* isolate, bool enable) {
7778   i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7779   internal_isolate->debug()->set_live_edit_enabled(enable);
7780 }
7781
7782
7783 MaybeLocal<Array> Debug::GetInternalProperties(Isolate* v8_isolate,
7784                                                Local<Value> value) {
7785   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7786   ENTER_V8(isolate);
7787   i::Handle<i::Object> val = Utils::OpenHandle(*value);
7788   i::Handle<i::JSArray> result;
7789   if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
7790     return MaybeLocal<Array>();
7791   return Utils::ToLocal(result);
7792 }
7793
7794
7795 Local<String> CpuProfileNode::GetFunctionName() const {
7796   i::Isolate* isolate = i::Isolate::Current();
7797   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7798   const i::CodeEntry* entry = node->entry();
7799   i::Handle<i::String> name =
7800       isolate->factory()->InternalizeUtf8String(entry->name());
7801   if (!entry->has_name_prefix()) {
7802     return ToApiHandle<String>(name);
7803   } else {
7804     // We do not expect this to fail. Change this if it does.
7805     i::Handle<i::String> cons = isolate->factory()->NewConsString(
7806         isolate->factory()->InternalizeUtf8String(entry->name_prefix()),
7807         name).ToHandleChecked();
7808     return ToApiHandle<String>(cons);
7809   }
7810 }
7811
7812
7813 int CpuProfileNode::GetScriptId() const {
7814   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7815   const i::CodeEntry* entry = node->entry();
7816   return entry->script_id();
7817 }
7818
7819
7820 Local<String> CpuProfileNode::GetScriptResourceName() const {
7821   i::Isolate* isolate = i::Isolate::Current();
7822   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7823   return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7824       node->entry()->resource_name()));
7825 }
7826
7827
7828 int CpuProfileNode::GetLineNumber() const {
7829   return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
7830 }
7831
7832
7833 int CpuProfileNode::GetColumnNumber() const {
7834   return reinterpret_cast<const i::ProfileNode*>(this)->
7835       entry()->column_number();
7836 }
7837
7838
7839 unsigned int CpuProfileNode::GetHitLineCount() const {
7840   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7841   return node->GetHitLineCount();
7842 }
7843
7844
7845 bool CpuProfileNode::GetLineTicks(LineTick* entries,
7846                                   unsigned int length) const {
7847   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7848   return node->GetLineTicks(entries, length);
7849 }
7850
7851
7852 const char* CpuProfileNode::GetBailoutReason() const {
7853   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7854   return node->entry()->bailout_reason();
7855 }
7856
7857
7858 unsigned CpuProfileNode::GetHitCount() const {
7859   return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
7860 }
7861
7862
7863 unsigned CpuProfileNode::GetCallUid() const {
7864   return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
7865 }
7866
7867
7868 unsigned CpuProfileNode::GetNodeId() const {
7869   return reinterpret_cast<const i::ProfileNode*>(this)->id();
7870 }
7871
7872
7873 int CpuProfileNode::GetChildrenCount() const {
7874   return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
7875 }
7876
7877
7878 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
7879   const i::ProfileNode* child =
7880       reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
7881   return reinterpret_cast<const CpuProfileNode*>(child);
7882 }
7883
7884
7885 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
7886   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7887   return node->deopt_infos();
7888 }
7889
7890
7891 void CpuProfile::Delete() {
7892   i::Isolate* isolate = i::Isolate::Current();
7893   i::CpuProfiler* profiler = isolate->cpu_profiler();
7894   DCHECK(profiler != NULL);
7895   profiler->DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
7896 }
7897
7898
7899 Local<String> CpuProfile::GetTitle() const {
7900   i::Isolate* isolate = i::Isolate::Current();
7901   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7902   return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7903       profile->title()));
7904 }
7905
7906
7907 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
7908   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7909   return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
7910 }
7911
7912
7913 const CpuProfileNode* CpuProfile::GetSample(int index) const {
7914   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7915   return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
7916 }
7917
7918
7919 int64_t CpuProfile::GetSampleTimestamp(int index) const {
7920   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7921   return (profile->sample_timestamp(index) - base::TimeTicks())
7922       .InMicroseconds();
7923 }
7924
7925
7926 int64_t CpuProfile::GetStartTime() const {
7927   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7928   return (profile->start_time() - base::TimeTicks()).InMicroseconds();
7929 }
7930
7931
7932 int64_t CpuProfile::GetEndTime() const {
7933   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7934   return (profile->end_time() - base::TimeTicks()).InMicroseconds();
7935 }
7936
7937
7938 int CpuProfile::GetSamplesCount() const {
7939   return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
7940 }
7941
7942
7943 void CpuProfiler::SetSamplingInterval(int us) {
7944   DCHECK(us >= 0);
7945   return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
7946       base::TimeDelta::FromMicroseconds(us));
7947 }
7948
7949
7950 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
7951   reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
7952       *Utils::OpenHandle(*title), record_samples);
7953 }
7954
7955
7956 CpuProfile* CpuProfiler::StopProfiling(Local<String> title) {
7957   return reinterpret_cast<CpuProfile*>(
7958       reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
7959           *Utils::OpenHandle(*title)));
7960 }
7961
7962
7963 void CpuProfiler::SetIdle(bool is_idle) {
7964   i::Isolate* isolate = reinterpret_cast<i::CpuProfiler*>(this)->isolate();
7965   v8::StateTag state = isolate->current_vm_state();
7966   DCHECK(state == v8::EXTERNAL || state == v8::IDLE);
7967   if (isolate->js_entry_sp() != NULL) return;
7968   if (is_idle) {
7969     isolate->set_current_vm_state(v8::IDLE);
7970   } else if (state == v8::IDLE) {
7971     isolate->set_current_vm_state(v8::EXTERNAL);
7972   }
7973 }
7974
7975
7976 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
7977   return const_cast<i::HeapGraphEdge*>(
7978       reinterpret_cast<const i::HeapGraphEdge*>(edge));
7979 }
7980
7981
7982 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
7983   return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
7984 }
7985
7986
7987 Local<Value> HeapGraphEdge::GetName() const {
7988   i::Isolate* isolate = i::Isolate::Current();
7989   i::HeapGraphEdge* edge = ToInternal(this);
7990   switch (edge->type()) {
7991     case i::HeapGraphEdge::kContextVariable:
7992     case i::HeapGraphEdge::kInternal:
7993     case i::HeapGraphEdge::kProperty:
7994     case i::HeapGraphEdge::kShortcut:
7995     case i::HeapGraphEdge::kWeak:
7996       return ToApiHandle<String>(
7997           isolate->factory()->InternalizeUtf8String(edge->name()));
7998     case i::HeapGraphEdge::kElement:
7999     case i::HeapGraphEdge::kHidden:
8000       return ToApiHandle<Number>(
8001           isolate->factory()->NewNumberFromInt(edge->index()));
8002     default: UNREACHABLE();
8003   }
8004   return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
8005 }
8006
8007
8008 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
8009   const i::HeapEntry* from = ToInternal(this)->from();
8010   return reinterpret_cast<const HeapGraphNode*>(from);
8011 }
8012
8013
8014 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
8015   const i::HeapEntry* to = ToInternal(this)->to();
8016   return reinterpret_cast<const HeapGraphNode*>(to);
8017 }
8018
8019
8020 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
8021   return const_cast<i::HeapEntry*>(
8022       reinterpret_cast<const i::HeapEntry*>(entry));
8023 }
8024
8025
8026 HeapGraphNode::Type HeapGraphNode::GetType() const {
8027   return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
8028 }
8029
8030
8031 Local<String> HeapGraphNode::GetName() const {
8032   i::Isolate* isolate = i::Isolate::Current();
8033   return ToApiHandle<String>(
8034       isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
8035 }
8036
8037
8038 SnapshotObjectId HeapGraphNode::GetId() const {
8039   return ToInternal(this)->id();
8040 }
8041
8042
8043 size_t HeapGraphNode::GetShallowSize() const {
8044   return ToInternal(this)->self_size();
8045 }
8046
8047
8048 int HeapGraphNode::GetChildrenCount() const {
8049   return ToInternal(this)->children().length();
8050 }
8051
8052
8053 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
8054   return reinterpret_cast<const HeapGraphEdge*>(
8055       ToInternal(this)->children()[index]);
8056 }
8057
8058
8059 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
8060   return const_cast<i::HeapSnapshot*>(
8061       reinterpret_cast<const i::HeapSnapshot*>(snapshot));
8062 }
8063
8064
8065 void HeapSnapshot::Delete() {
8066   i::Isolate* isolate = i::Isolate::Current();
8067   if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
8068     ToInternal(this)->Delete();
8069   } else {
8070     // If this is the last snapshot, clean up all accessory data as well.
8071     isolate->heap_profiler()->DeleteAllSnapshots();
8072   }
8073 }
8074
8075
8076 const HeapGraphNode* HeapSnapshot::GetRoot() const {
8077   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
8078 }
8079
8080
8081 const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
8082   return reinterpret_cast<const HeapGraphNode*>(
8083       ToInternal(this)->GetEntryById(id));
8084 }
8085
8086
8087 int HeapSnapshot::GetNodesCount() const {
8088   return ToInternal(this)->entries().length();
8089 }
8090
8091
8092 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
8093   return reinterpret_cast<const HeapGraphNode*>(
8094       &ToInternal(this)->entries().at(index));
8095 }
8096
8097
8098 SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
8099   return ToInternal(this)->max_snapshot_js_object_id();
8100 }
8101
8102
8103 void HeapSnapshot::Serialize(OutputStream* stream,
8104                              HeapSnapshot::SerializationFormat format) const {
8105   Utils::ApiCheck(format == kJSON,
8106                   "v8::HeapSnapshot::Serialize",
8107                   "Unknown serialization format");
8108   Utils::ApiCheck(stream->GetChunkSize() > 0,
8109                   "v8::HeapSnapshot::Serialize",
8110                   "Invalid stream chunk size");
8111   i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
8112   serializer.Serialize(stream);
8113 }
8114
8115
8116 // static
8117 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
8118     HeapProfiler::kUnknownObjectId;
8119
8120
8121 int HeapProfiler::GetSnapshotCount() {
8122   return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
8123 }
8124
8125
8126 const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
8127   return reinterpret_cast<const HeapSnapshot*>(
8128       reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
8129 }
8130
8131
8132 SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) {
8133   i::Handle<i::Object> obj = Utils::OpenHandle(*value);
8134   return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
8135 }
8136
8137
8138 Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
8139   i::Handle<i::Object> obj =
8140       reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
8141   if (obj.is_null()) return Local<Value>();
8142   return Utils::ToLocal(obj);
8143 }
8144
8145
8146 void HeapProfiler::ClearObjectIds() {
8147   reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
8148 }
8149
8150
8151 const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
8152     ActivityControl* control, ObjectNameResolver* resolver) {
8153   return reinterpret_cast<const HeapSnapshot*>(
8154       reinterpret_cast<i::HeapProfiler*>(this)
8155           ->TakeSnapshot(control, resolver));
8156 }
8157
8158
8159 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
8160   reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
8161       track_allocations);
8162 }
8163
8164
8165 void HeapProfiler::StopTrackingHeapObjects() {
8166   reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
8167 }
8168
8169
8170 SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream,
8171                                             int64_t* timestamp_us) {
8172   i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
8173   return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
8174 }
8175
8176
8177 void HeapProfiler::DeleteAllHeapSnapshots() {
8178   reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
8179 }
8180
8181
8182 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
8183                                                WrapperInfoCallback callback) {
8184   reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
8185                                                                callback);
8186 }
8187
8188
8189 size_t HeapProfiler::GetProfilerMemorySize() {
8190   return reinterpret_cast<i::HeapProfiler*>(this)->
8191       GetMemorySizeUsedByProfiler();
8192 }
8193
8194
8195 void HeapProfiler::SetRetainedObjectInfo(UniqueId id,
8196                                          RetainedObjectInfo* info) {
8197   reinterpret_cast<i::HeapProfiler*>(this)->SetRetainedObjectInfo(id, info);
8198 }
8199
8200
8201 v8::Testing::StressType internal::Testing::stress_type_ =
8202     v8::Testing::kStressTypeOpt;
8203
8204
8205 void Testing::SetStressRunType(Testing::StressType type) {
8206   internal::Testing::set_stress_type(type);
8207 }
8208
8209
8210 int Testing::GetStressRuns() {
8211   if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
8212 #ifdef DEBUG
8213   // In debug mode the code runs much slower so stressing will only make two
8214   // runs.
8215   return 2;
8216 #else
8217   return 5;
8218 #endif
8219 }
8220
8221
8222 static void SetFlagsFromString(const char* flags) {
8223   V8::SetFlagsFromString(flags, i::StrLength(flags));
8224 }
8225
8226
8227 void Testing::PrepareStressRun(int run) {
8228   static const char* kLazyOptimizations =
8229       "--prepare-always-opt "
8230       "--max-inlined-source-size=999999 "
8231       "--max-inlined-nodes=999999 "
8232       "--max-inlined-nodes-cumulative=999999 "
8233       "--noalways-opt";
8234   static const char* kForcedOptimizations = "--always-opt";
8235
8236   // If deoptimization stressed turn on frequent deoptimization. If no value
8237   // is spefified through --deopt-every-n-times use a default default value.
8238   static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
8239   if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
8240       internal::FLAG_deopt_every_n_times == 0) {
8241     SetFlagsFromString(kDeoptEvery13Times);
8242   }
8243
8244 #ifdef DEBUG
8245   // As stressing in debug mode only make two runs skip the deopt stressing
8246   // here.
8247   if (run == GetStressRuns() - 1) {
8248     SetFlagsFromString(kForcedOptimizations);
8249   } else {
8250     SetFlagsFromString(kLazyOptimizations);
8251   }
8252 #else
8253   if (run == GetStressRuns() - 1) {
8254     SetFlagsFromString(kForcedOptimizations);
8255   } else if (run != GetStressRuns() - 2) {
8256     SetFlagsFromString(kLazyOptimizations);
8257   }
8258 #endif
8259 }
8260
8261
8262 // TODO(svenpanne) Deprecate this.
8263 void Testing::DeoptimizeAll() {
8264   i::Isolate* isolate = i::Isolate::Current();
8265   i::HandleScope scope(isolate);
8266   internal::Deoptimizer::DeoptimizeAll(isolate);
8267 }
8268
8269
8270 namespace internal {
8271
8272
8273 void HandleScopeImplementer::FreeThreadResources() {
8274   Free();
8275 }
8276
8277
8278 char* HandleScopeImplementer::ArchiveThread(char* storage) {
8279   HandleScopeData* current = isolate_->handle_scope_data();
8280   handle_scope_data_ = *current;
8281   MemCopy(storage, this, sizeof(*this));
8282
8283   ResetAfterArchive();
8284   current->Initialize();
8285
8286   return storage + ArchiveSpacePerThread();
8287 }
8288
8289
8290 int HandleScopeImplementer::ArchiveSpacePerThread() {
8291   return sizeof(HandleScopeImplementer);
8292 }
8293
8294
8295 char* HandleScopeImplementer::RestoreThread(char* storage) {
8296   MemCopy(this, storage, sizeof(*this));
8297   *isolate_->handle_scope_data() = handle_scope_data_;
8298   return storage + ArchiveSpacePerThread();
8299 }
8300
8301
8302 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
8303 #ifdef DEBUG
8304   bool found_block_before_deferred = false;
8305 #endif
8306   // Iterate over all handles in the blocks except for the last.
8307   for (int i = blocks()->length() - 2; i >= 0; --i) {
8308     Object** block = blocks()->at(i);
8309     if (last_handle_before_deferred_block_ != NULL &&
8310         (last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) &&
8311         (last_handle_before_deferred_block_ >= block)) {
8312       v->VisitPointers(block, last_handle_before_deferred_block_);
8313       DCHECK(!found_block_before_deferred);
8314 #ifdef DEBUG
8315       found_block_before_deferred = true;
8316 #endif
8317     } else {
8318       v->VisitPointers(block, &block[kHandleBlockSize]);
8319     }
8320   }
8321
8322   DCHECK(last_handle_before_deferred_block_ == NULL ||
8323          found_block_before_deferred);
8324
8325   // Iterate over live handles in the last block (if any).
8326   if (!blocks()->is_empty()) {
8327     v->VisitPointers(blocks()->last(), handle_scope_data_.next);
8328   }
8329
8330   List<Context*>* context_lists[2] = { &saved_contexts_, &entered_contexts_};
8331   for (unsigned i = 0; i < arraysize(context_lists); i++) {
8332     if (context_lists[i]->is_empty()) continue;
8333     Object** start = reinterpret_cast<Object**>(&context_lists[i]->first());
8334     v->VisitPointers(start, start + context_lists[i]->length());
8335   }
8336 }
8337
8338
8339 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
8340   HandleScopeData* current = isolate_->handle_scope_data();
8341   handle_scope_data_ = *current;
8342   IterateThis(v);
8343 }
8344
8345
8346 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
8347   HandleScopeImplementer* scope_implementer =
8348       reinterpret_cast<HandleScopeImplementer*>(storage);
8349   scope_implementer->IterateThis(v);
8350   return storage + ArchiveSpacePerThread();
8351 }
8352
8353
8354 DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) {
8355   DeferredHandles* deferred =
8356       new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
8357
8358   while (!blocks_.is_empty()) {
8359     Object** block_start = blocks_.last();
8360     Object** block_limit = &block_start[kHandleBlockSize];
8361     // We should not need to check for SealHandleScope here. Assert this.
8362     DCHECK(prev_limit == block_limit ||
8363            !(block_start <= prev_limit && prev_limit <= block_limit));
8364     if (prev_limit == block_limit) break;
8365     deferred->blocks_.Add(blocks_.last());
8366     blocks_.RemoveLast();
8367   }
8368
8369   // deferred->blocks_ now contains the blocks installed on the
8370   // HandleScope stack since BeginDeferredScope was called, but in
8371   // reverse order.
8372
8373   DCHECK(prev_limit == NULL || !blocks_.is_empty());
8374
8375   DCHECK(!blocks_.is_empty() && prev_limit != NULL);
8376   DCHECK(last_handle_before_deferred_block_ != NULL);
8377   last_handle_before_deferred_block_ = NULL;
8378   return deferred;
8379 }
8380
8381
8382 void HandleScopeImplementer::BeginDeferredScope() {
8383   DCHECK(last_handle_before_deferred_block_ == NULL);
8384   last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
8385 }
8386
8387
8388 DeferredHandles::~DeferredHandles() {
8389   isolate_->UnlinkDeferredHandles(this);
8390
8391   for (int i = 0; i < blocks_.length(); i++) {
8392 #ifdef ENABLE_HANDLE_ZAPPING
8393     HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
8394 #endif
8395     isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
8396   }
8397 }
8398
8399
8400 void DeferredHandles::Iterate(ObjectVisitor* v) {
8401   DCHECK(!blocks_.is_empty());
8402
8403   DCHECK((first_block_limit_ >= blocks_.first()) &&
8404          (first_block_limit_ <= &(blocks_.first())[kHandleBlockSize]));
8405
8406   v->VisitPointers(blocks_.first(), first_block_limit_);
8407
8408   for (int i = 1; i < blocks_.length(); i++) {
8409     v->VisitPointers(blocks_[i], &blocks_[i][kHandleBlockSize]);
8410   }
8411 }
8412
8413
8414 void InvokeAccessorGetterCallback(
8415     v8::Local<v8::Name> property,
8416     const v8::PropertyCallbackInfo<v8::Value>& info,
8417     v8::AccessorNameGetterCallback getter) {
8418   // Leaving JavaScript.
8419   Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8420   Address getter_address = reinterpret_cast<Address>(reinterpret_cast<intptr_t>(
8421       getter));
8422   VMState<EXTERNAL> state(isolate);
8423   ExternalCallbackScope call_scope(isolate, getter_address);
8424   getter(property, info);
8425 }
8426
8427
8428 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
8429                             v8::FunctionCallback callback) {
8430   Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8431   Address callback_address =
8432       reinterpret_cast<Address>(reinterpret_cast<intptr_t>(callback));
8433   VMState<EXTERNAL> state(isolate);
8434   ExternalCallbackScope call_scope(isolate, callback_address);
8435   callback(info);
8436 }
8437
8438
8439 }  // namespace internal
8440 }  // namespace v8