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.
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/char-predicates-inl.h"
24 #include "src/code-stubs.h"
25 #include "src/compiler.h"
26 #include "src/context-measure.h"
27 #include "src/contexts.h"
28 #include "src/conversions-inl.h"
29 #include "src/counters.h"
30 #include "src/cpu-profiler.h"
31 #include "src/debug/debug.h"
32 #include "src/deoptimizer.h"
33 #include "src/execution.h"
34 #include "src/global-handles.h"
35 #include "src/heap-profiler.h"
36 #include "src/heap-snapshot-generator-inl.h"
37 #include "src/icu_util.h"
38 #include "src/json-parser.h"
39 #include "src/messages.h"
40 #include "src/parser.h"
41 #include "src/pending-compilation-error-handler.h"
42 #include "src/profile-generator-inl.h"
43 #include "src/property.h"
44 #include "src/property-details.h"
45 #include "src/prototype.h"
46 #include "src/runtime/runtime.h"
47 #include "src/runtime-profiler.h"
48 #include "src/sampler.h"
49 #include "src/scanner-character-streams.h"
50 #include "src/simulator.h"
51 #include "src/snapshot/natives.h"
52 #include "src/snapshot/snapshot.h"
53 #include "src/startup-data-util.h"
54 #include "src/unicode-inl.h"
56 #include "src/v8threads.h"
57 #include "src/version.h"
58 #include "src/vm-state-inl.h"
63 #define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
66 #define ENTER_V8(isolate) i::VMState<v8::OTHER> __state__((isolate))
69 #define PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name, \
70 bailout_value, HandleScopeClass, \
72 if (IsExecutionTerminatingCheck(isolate)) { \
73 return bailout_value; \
75 HandleScopeClass handle_scope(isolate); \
76 CallDepthScope call_depth_scope(isolate, context, do_callback); \
77 LOG_API(isolate, function_name); \
79 bool has_pending_exception = false
82 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT( \
83 context, function_name, bailout_value, HandleScopeClass, do_callback) \
84 auto isolate = context.IsEmpty() \
85 ? i::Isolate::Current() \
86 : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \
87 PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name, \
88 bailout_value, HandleScopeClass, do_callback);
91 #define PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, function_name, T) \
92 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(), function_name, \
93 MaybeLocal<T>(), InternalEscapableScope, \
97 #define PREPARE_FOR_EXECUTION(context, function_name, T) \
98 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
99 InternalEscapableScope, false)
102 #define PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, function_name, T) \
103 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
104 InternalEscapableScope, true)
107 #define PREPARE_FOR_EXECUTION_PRIMITIVE(context, function_name, T) \
108 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, Nothing<T>(), \
109 i::HandleScope, false)
112 #define EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, value) \
114 if (has_pending_exception) { \
115 call_depth_scope.Escape(); \
121 #define RETURN_ON_FAILED_EXECUTION(T) \
122 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, MaybeLocal<T>())
125 #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \
126 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, Nothing<T>())
129 #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \
130 return maybe_local.FromMaybe(Local<T>());
133 #define RETURN_ESCAPED(value) return handle_scope.Escape(value);
138 Local<Context> ContextFromHeapObject(i::Handle<i::Object> obj) {
139 return reinterpret_cast<v8::Isolate*>(i::HeapObject::cast(*obj)->GetIsolate())
140 ->GetCurrentContext();
143 class InternalEscapableScope : public v8::EscapableHandleScope {
145 explicit inline InternalEscapableScope(i::Isolate* isolate)
146 : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {}
150 class CallDepthScope {
152 explicit CallDepthScope(i::Isolate* isolate, Local<Context> context,
157 do_callback_(do_callback) {
158 // TODO(dcarney): remove this when blink stops crashing.
159 DCHECK(!isolate_->external_caught_exception());
160 isolate_->handle_scope_implementer()->IncrementCallDepth();
161 if (!context_.IsEmpty()) context_->Enter();
164 if (!context_.IsEmpty()) context_->Exit();
165 if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth();
166 if (do_callback_) isolate_->FireCallCompletedCallback();
172 auto handle_scope_implementer = isolate_->handle_scope_implementer();
173 handle_scope_implementer->DecrementCallDepth();
174 bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero();
175 isolate_->OptionalRescheduleException(call_depth_is_zero);
179 i::Isolate* const isolate_;
180 Local<Context> context_;
188 static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate,
189 i::Handle<i::Script> script) {
190 i::Handle<i::Object> scriptName(i::Script::GetNameOrSourceURL(script));
191 i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate);
192 v8::Isolate* v8_isolate =
193 reinterpret_cast<v8::Isolate*>(script->GetIsolate());
194 ScriptOriginOptions options(script->origin_options());
195 v8::ScriptOrigin origin(
196 Utils::ToLocal(scriptName),
197 v8::Integer::New(v8_isolate, script->line_offset()->value()),
198 v8::Integer::New(v8_isolate, script->column_offset()->value()),
199 v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()),
200 v8::Integer::New(v8_isolate, script->id()->value()),
201 v8::Boolean::New(v8_isolate, options.IsEmbedderDebugScript()),
202 Utils::ToLocal(source_map_url),
203 v8::Boolean::New(v8_isolate, options.IsOpaque()));
208 // --- E x c e p t i o n B e h a v i o r ---
211 void i::FatalProcessOutOfMemory(const char* location) {
212 i::V8::FatalProcessOutOfMemory(location, false);
216 // When V8 cannot allocated memory FatalProcessOutOfMemory is called.
217 // The default fatal error handler is called and execution is stopped.
218 void i::V8::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
219 i::Isolate* isolate = i::Isolate::Current();
220 char last_few_messages[Heap::kTraceRingBufferSize + 1];
221 char js_stacktrace[Heap::kStacktraceBufferSize + 1];
222 memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
223 memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1);
225 i::HeapStats heap_stats;
227 heap_stats.start_marker = &start_marker;
229 heap_stats.new_space_size = &new_space_size;
230 int new_space_capacity;
231 heap_stats.new_space_capacity = &new_space_capacity;
232 intptr_t old_space_size;
233 heap_stats.old_space_size = &old_space_size;
234 intptr_t old_space_capacity;
235 heap_stats.old_space_capacity = &old_space_capacity;
236 intptr_t code_space_size;
237 heap_stats.code_space_size = &code_space_size;
238 intptr_t code_space_capacity;
239 heap_stats.code_space_capacity = &code_space_capacity;
240 intptr_t map_space_size;
241 heap_stats.map_space_size = &map_space_size;
242 intptr_t map_space_capacity;
243 heap_stats.map_space_capacity = &map_space_capacity;
244 intptr_t lo_space_size;
245 heap_stats.lo_space_size = &lo_space_size;
246 int global_handle_count;
247 heap_stats.global_handle_count = &global_handle_count;
248 int weak_global_handle_count;
249 heap_stats.weak_global_handle_count = &weak_global_handle_count;
250 int pending_global_handle_count;
251 heap_stats.pending_global_handle_count = &pending_global_handle_count;
252 int near_death_global_handle_count;
253 heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
254 int free_global_handle_count;
255 heap_stats.free_global_handle_count = &free_global_handle_count;
256 intptr_t memory_allocator_size;
257 heap_stats.memory_allocator_size = &memory_allocator_size;
258 intptr_t memory_allocator_capacity;
259 heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
260 int objects_per_type[LAST_TYPE + 1] = {0};
261 heap_stats.objects_per_type = objects_per_type;
262 int size_per_type[LAST_TYPE + 1] = {0};
263 heap_stats.size_per_type = size_per_type;
265 heap_stats.os_error = &os_error;
266 heap_stats.last_few_messages = last_few_messages;
267 heap_stats.js_stacktrace = js_stacktrace;
269 heap_stats.end_marker = &end_marker;
270 if (isolate->heap()->HasBeenSetUp()) {
271 // BUG(1718): Don't use the take_snapshot since we don't support
272 // HeapIterator here without doing a special GC.
273 isolate->heap()->RecordStats(&heap_stats, false);
274 char* first_newline = strchr(last_few_messages, '\n');
275 if (first_newline == NULL || first_newline[1] == '\0')
276 first_newline = last_few_messages;
277 PrintF("\n<--- Last few GCs --->\n%s\n", first_newline);
278 PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace);
280 Utils::ApiCheck(false, location, "Allocation failed - process out of memory");
281 // If the fatal error handler returns, we stop execution.
282 FATAL("API fatal error handler returned after process out of memory");
286 void Utils::ReportApiFailure(const char* location, const char* message) {
287 i::Isolate* isolate = i::Isolate::Current();
288 FatalErrorCallback callback = isolate->exception_behavior();
289 if (callback == NULL) {
290 base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
294 callback(location, message);
296 isolate->SignalFatalError();
300 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
301 if (isolate->has_scheduled_exception()) {
302 return isolate->scheduled_exception() ==
303 isolate->heap()->termination_exception();
309 void V8::SetNativesDataBlob(StartupData* natives_blob) {
310 i::V8::SetNativesBlob(natives_blob);
314 void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
315 i::V8::SetSnapshotBlob(snapshot_blob);
319 bool RunExtraCode(Isolate* isolate, Local<Context> context,
320 const char* utf8_source) {
321 // Run custom script if provided.
322 base::ElapsedTimer timer;
324 TryCatch try_catch(isolate);
325 Local<String> source_string;
326 if (!String::NewFromUtf8(isolate, utf8_source, NewStringType::kNormal)
327 .ToLocal(&source_string)) {
330 Local<String> resource_name =
331 String::NewFromUtf8(isolate, "<embedded script>", NewStringType::kNormal)
333 ScriptOrigin origin(resource_name);
334 ScriptCompiler::Source source(source_string, origin);
335 Local<Script> script;
336 if (!ScriptCompiler::Compile(context, &source).ToLocal(&script)) return false;
337 if (script->Run(context).IsEmpty()) return false;
338 if (i::FLAG_profile_deserialization) {
339 i::PrintF("Executing custom snapshot script took %0.3f ms\n",
340 timer.Elapsed().InMillisecondsF());
343 CHECK(!try_catch.HasCaught());
350 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
352 virtual void* Allocate(size_t length) {
353 void* data = AllocateUninitialized(length);
354 return data == NULL ? data : memset(data, 0, length);
356 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
357 virtual void Free(void* data, size_t) { free(data); }
363 StartupData V8::CreateSnapshotDataBlob(const char* custom_source) {
364 i::Isolate* internal_isolate = new i::Isolate(true);
365 ArrayBufferAllocator allocator;
366 internal_isolate->set_array_buffer_allocator(&allocator);
367 Isolate* isolate = reinterpret_cast<Isolate*>(internal_isolate);
368 StartupData result = {NULL, 0};
370 base::ElapsedTimer timer;
372 Isolate::Scope isolate_scope(isolate);
373 internal_isolate->Init(NULL);
374 Persistent<Context> context;
375 i::Snapshot::Metadata metadata;
377 HandleScope handle_scope(isolate);
378 Local<Context> new_context = Context::New(isolate);
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();
386 if (!context.IsEmpty()) {
387 // If we don't do this then we end up with a stray root pointing at the
388 // context even after we have disposed of the context.
389 internal_isolate->heap()->CollectAllAvailableGarbage("mksnapshot");
391 // GC may have cleared weak cells, so compact any WeakFixedArrays
392 // found on the heap.
393 i::HeapIterator iterator(internal_isolate->heap(),
394 i::HeapIterator::kFilterUnreachable);
395 for (i::HeapObject* o = iterator.next(); o != NULL; o = iterator.next()) {
396 if (o->IsPrototypeInfo()) {
397 i::Object* prototype_users =
398 i::PrototypeInfo::cast(o)->prototype_users();
399 if (prototype_users->IsWeakFixedArray()) {
400 i::WeakFixedArray* array = i::WeakFixedArray::cast(prototype_users);
401 array->Compact<i::JSObject::PrototypeRegistryCompactionCallback>();
403 } else if (o->IsScript()) {
404 i::Object* shared_list = i::Script::cast(o)->shared_function_infos();
405 if (shared_list->IsWeakFixedArray()) {
406 i::WeakFixedArray* array = i::WeakFixedArray::cast(shared_list);
407 array->Compact<i::WeakFixedArray::NullCallback>();
412 i::Object* raw_context = *v8::Utils::OpenPersistent(context);
415 i::SnapshotByteSink snapshot_sink;
416 i::StartupSerializer ser(internal_isolate, &snapshot_sink);
417 ser.SerializeStrongReferences();
419 i::SnapshotByteSink context_sink;
420 i::PartialSerializer context_ser(internal_isolate, &ser, &context_sink);
421 context_ser.Serialize(&raw_context);
422 ser.SerializeWeakReferencesAndDeferred();
424 result = i::Snapshot::CreateSnapshotBlob(ser, context_ser, metadata);
426 if (i::FLAG_profile_deserialization) {
427 i::PrintF("Creating snapshot took %0.3f ms\n",
428 timer.Elapsed().InMillisecondsF());
437 void V8::SetFlagsFromString(const char* str, int length) {
438 i::FlagList::SetFlagsFromString(str, length);
442 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
443 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
447 RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
450 RegisteredExtension::RegisteredExtension(Extension* extension)
451 : extension_(extension) { }
454 void RegisteredExtension::Register(RegisteredExtension* that) {
455 that->next_ = first_extension_;
456 first_extension_ = that;
460 void RegisteredExtension::UnregisterAll() {
461 RegisteredExtension* re = first_extension_;
463 RegisteredExtension* next = re->next();
467 first_extension_ = NULL;
471 void RegisterExtension(Extension* that) {
472 RegisteredExtension* extension = new RegisteredExtension(that);
473 RegisteredExtension::Register(extension);
477 Extension::Extension(const char* name,
483 source_length_(source_length >= 0 ?
485 (source ? static_cast<int>(strlen(source)) : 0)),
486 source_(source, source_length_),
487 dep_count_(dep_count),
489 auto_enable_(false) {
490 CHECK(source != NULL || source_length_ == 0);
494 ResourceConstraints::ResourceConstraints()
495 : max_semi_space_size_(0),
496 max_old_space_size_(0),
497 max_executable_size_(0),
499 code_range_size_(0) { }
501 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
502 uint64_t virtual_memory_limit) {
504 // Android has higher physical memory requirements before raising the maximum
505 // heap size limits since it has no swap space.
506 const uint64_t low_limit = 512ul * i::MB;
507 const uint64_t medium_limit = 1ul * i::GB;
508 const uint64_t high_limit = 2ul * i::GB;
510 const uint64_t low_limit = 512ul * i::MB;
511 const uint64_t medium_limit = 768ul * i::MB;
512 const uint64_t high_limit = 1ul * i::GB;
515 if (physical_memory <= low_limit) {
516 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeLowMemoryDevice);
517 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeLowMemoryDevice);
518 set_max_executable_size(i::Heap::kMaxExecutableSizeLowMemoryDevice);
519 } else if (physical_memory <= medium_limit) {
520 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeMediumMemoryDevice);
521 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeMediumMemoryDevice);
522 set_max_executable_size(i::Heap::kMaxExecutableSizeMediumMemoryDevice);
523 } else if (physical_memory <= high_limit) {
524 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHighMemoryDevice);
525 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHighMemoryDevice);
526 set_max_executable_size(i::Heap::kMaxExecutableSizeHighMemoryDevice);
528 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHugeMemoryDevice);
529 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHugeMemoryDevice);
530 set_max_executable_size(i::Heap::kMaxExecutableSizeHugeMemoryDevice);
533 if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
534 // Reserve no more than 1/8 of the memory for the code range, but at most
535 // kMaximalCodeRangeSize.
537 i::Min(i::kMaximalCodeRangeSize / i::MB,
538 static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
543 void SetResourceConstraints(i::Isolate* isolate,
544 const ResourceConstraints& constraints) {
545 int semi_space_size = constraints.max_semi_space_size();
546 int old_space_size = constraints.max_old_space_size();
547 int max_executable_size = constraints.max_executable_size();
548 size_t code_range_size = constraints.code_range_size();
549 if (semi_space_size != 0 || old_space_size != 0 ||
550 max_executable_size != 0 || code_range_size != 0) {
551 isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
552 max_executable_size, code_range_size);
554 if (constraints.stack_limit() != NULL) {
555 uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
556 isolate->stack_guard()->SetStackLimit(limit);
561 i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** obj) {
562 LOG_API(isolate, "Persistent::New");
563 i::Handle<i::Object> result = isolate->global_handles()->Create(*obj);
565 if (i::FLAG_verify_heap) {
566 (*obj)->ObjectVerify();
568 #endif // VERIFY_HEAP
569 return result.location();
573 i::Object** V8::CopyPersistent(i::Object** obj) {
574 i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj);
576 if (i::FLAG_verify_heap) {
577 (*obj)->ObjectVerify();
579 #endif // VERIFY_HEAP
580 return result.location();
584 void V8::MakeWeak(i::Object** object, void* parameter,
585 WeakCallback weak_callback) {
586 i::GlobalHandles::MakeWeak(object, parameter, weak_callback);
590 void V8::MakeWeak(i::Object** object, void* parameter,
591 int internal_field_index1, int internal_field_index2,
592 WeakCallbackInfo<void>::Callback weak_callback) {
593 WeakCallbackType type = WeakCallbackType::kParameter;
594 if (internal_field_index1 == 0) {
595 if (internal_field_index2 == 1) {
596 type = WeakCallbackType::kInternalFields;
598 DCHECK_EQ(internal_field_index2, -1);
599 type = WeakCallbackType::kInternalFields;
602 DCHECK_EQ(internal_field_index1, -1);
603 DCHECK_EQ(internal_field_index2, -1);
605 i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
609 void V8::MakeWeak(i::Object** object, void* parameter,
610 WeakCallbackInfo<void>::Callback weak_callback,
611 WeakCallbackType type) {
612 i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
616 void* V8::ClearWeak(i::Object** obj) {
617 return i::GlobalHandles::ClearWeakness(obj);
621 void V8::DisposeGlobal(i::Object** obj) {
622 i::GlobalHandles::Destroy(obj);
626 void V8::Eternalize(Isolate* v8_isolate, Value* value, int* index) {
627 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
628 i::Object* object = *Utils::OpenHandle(value);
629 isolate->eternal_handles()->Create(isolate, object, index);
633 Local<Value> V8::GetEternal(Isolate* v8_isolate, int index) {
634 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
635 return Utils::ToLocal(isolate->eternal_handles()->Get(index));
639 void V8::FromJustIsNothing() {
640 Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing.");
644 void V8::ToLocalEmpty() {
645 Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal.");
649 void V8::InternalFieldOutOfBounds(int index) {
650 Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback,
651 "WeakCallbackInfo::GetInternalField",
652 "Internal field out of bounds.");
656 // --- H a n d l e s ---
659 HandleScope::HandleScope(Isolate* isolate) {
664 void HandleScope::Initialize(Isolate* isolate) {
665 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
666 // We do not want to check the correct usage of the Locker class all over the
667 // place, so we do it only here: Without a HandleScope, an embedder can do
668 // almost nothing, so it is enough to check in this central place.
669 // We make an exception if the serializer is enabled, which means that the
670 // Isolate is exclusively used to create a snapshot.
672 !v8::Locker::IsActive() ||
673 internal_isolate->thread_manager()->IsLockedByCurrentThread() ||
674 internal_isolate->serializer_enabled(),
675 "HandleScope::HandleScope",
676 "Entering the V8 API without proper locking in place");
677 i::HandleScopeData* current = internal_isolate->handle_scope_data();
678 isolate_ = internal_isolate;
679 prev_next_ = current->next;
680 prev_limit_ = current->limit;
685 HandleScope::~HandleScope() {
686 i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
690 int HandleScope::NumberOfHandles(Isolate* isolate) {
691 return i::HandleScope::NumberOfHandles(
692 reinterpret_cast<i::Isolate*>(isolate));
696 i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) {
697 return i::HandleScope::CreateHandle(isolate, value);
701 i::Object** HandleScope::CreateHandle(i::HeapObject* heap_object,
703 DCHECK(heap_object->IsHeapObject());
704 return i::HandleScope::CreateHandle(heap_object->GetIsolate(), value);
708 EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
709 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
710 escape_slot_ = CreateHandle(isolate, isolate->heap()->the_hole_value());
711 Initialize(v8_isolate);
715 i::Object** EscapableHandleScope::Escape(i::Object** escape_value) {
716 i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
717 Utils::ApiCheck(*escape_slot_ == heap->the_hole_value(),
718 "EscapeableHandleScope::Escape",
719 "Escape value set twice");
720 if (escape_value == NULL) {
721 *escape_slot_ = heap->undefined_value();
724 *escape_slot_ = *escape_value;
729 SealHandleScope::SealHandleScope(Isolate* isolate) {
730 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
732 isolate_ = internal_isolate;
733 i::HandleScopeData* current = internal_isolate->handle_scope_data();
734 prev_limit_ = current->limit;
735 current->limit = current->next;
736 prev_level_ = current->level;
741 SealHandleScope::~SealHandleScope() {
742 i::HandleScopeData* current = isolate_->handle_scope_data();
743 DCHECK_EQ(0, current->level);
744 current->level = prev_level_;
745 DCHECK_EQ(current->next, current->limit);
746 current->limit = prev_limit_;
750 void Context::Enter() {
751 i::Handle<i::Context> env = Utils::OpenHandle(this);
752 i::Isolate* isolate = env->GetIsolate();
754 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
755 impl->EnterContext(env);
756 impl->SaveContext(isolate->context());
757 isolate->set_context(*env);
761 void Context::Exit() {
762 i::Handle<i::Context> env = Utils::OpenHandle(this);
763 i::Isolate* isolate = env->GetIsolate();
765 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
766 if (!Utils::ApiCheck(impl->LastEnteredContextWas(env),
767 "v8::Context::Exit()",
768 "Cannot exit non-entered context")) {
771 impl->LeaveContext();
772 isolate->set_context(impl->RestoreContext());
776 static void* DecodeSmiToAligned(i::Object* value, const char* location) {
777 Utils::ApiCheck(value->IsSmi(), location, "Not a Smi");
778 return reinterpret_cast<void*>(value);
782 static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) {
783 i::Smi* smi = reinterpret_cast<i::Smi*>(value);
784 Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned");
789 static i::Handle<i::FixedArray> EmbedderDataFor(Context* context,
792 const char* location) {
793 i::Handle<i::Context> env = Utils::OpenHandle(context);
794 i::Isolate* isolate = env->GetIsolate();
796 Utils::ApiCheck(env->IsNativeContext(),
798 "Not a native context") &&
799 Utils::ApiCheck(index >= 0, location, "Negative index");
800 if (!ok) return i::Handle<i::FixedArray>();
801 i::Handle<i::FixedArray> data(env->embedder_data());
802 if (index < data->length()) return data;
803 if (!Utils::ApiCheck(can_grow, location, "Index too large")) {
804 return i::Handle<i::FixedArray>();
806 int new_size = i::Max(index, data->length() << 1) + 1;
807 int grow_by = new_size - data->length();
808 data = isolate->factory()->CopyFixedArrayAndGrow(data, grow_by);
809 env->set_embedder_data(*data);
814 v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
815 const char* location = "v8::Context::GetEmbedderData()";
816 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
817 if (data.is_null()) return Local<Value>();
818 i::Handle<i::Object> result(data->get(index), data->GetIsolate());
819 return Utils::ToLocal(result);
823 void Context::SetEmbedderData(int index, v8::Local<Value> value) {
824 const char* location = "v8::Context::SetEmbedderData()";
825 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
826 if (data.is_null()) return;
827 i::Handle<i::Object> val = Utils::OpenHandle(*value);
828 data->set(index, *val);
829 DCHECK_EQ(*Utils::OpenHandle(*value),
830 *Utils::OpenHandle(*GetEmbedderData(index)));
834 void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
835 const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
836 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
837 if (data.is_null()) return NULL;
838 return DecodeSmiToAligned(data->get(index), location);
842 void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
843 const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
844 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
845 data->set(index, EncodeAlignedAsSmi(value, location));
846 DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
850 // --- N e a n d e r ---
853 // A constructor cannot easily return an error value, therefore it is necessary
854 // to check for a dead VM with ON_BAILOUT before constructing any Neander
855 // objects. To remind you about this there is no HandleScope in the
856 // NeanderObject constructor. When you add one to the site calling the
857 // constructor you should check that you ensured the VM was not dead first.
858 NeanderObject::NeanderObject(v8::internal::Isolate* isolate, int size) {
860 value_ = isolate->factory()->NewNeanderObject();
861 i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
862 value_->set_elements(*elements);
866 int NeanderObject::size() {
867 return i::FixedArray::cast(value_->elements())->length();
871 NeanderArray::NeanderArray(v8::internal::Isolate* isolate) : obj_(isolate, 2) {
872 obj_.set(0, i::Smi::FromInt(0));
876 int NeanderArray::length() {
877 return i::Smi::cast(obj_.get(0))->value();
881 i::Object* NeanderArray::get(int offset) {
883 DCHECK(offset < length());
884 return obj_.get(offset + 1);
888 // This method cannot easily return an error value, therefore it is necessary
889 // to check for a dead VM with ON_BAILOUT before calling it. To remind you
890 // about this there is no HandleScope in this method. When you add one to the
891 // site calling this method you should check that you ensured the VM was not
893 void NeanderArray::add(i::Isolate* isolate, i::Handle<i::Object> value) {
894 int length = this->length();
895 int size = obj_.size();
896 if (length == size - 1) {
897 i::Factory* factory = isolate->factory();
898 i::Handle<i::FixedArray> new_elms = factory->NewFixedArray(2 * size);
899 for (int i = 0; i < length; i++)
900 new_elms->set(i + 1, get(i));
901 obj_.value()->set_elements(*new_elms);
903 obj_.set(length + 1, *value);
904 obj_.set(0, i::Smi::FromInt(length + 1));
908 void NeanderArray::set(int index, i::Object* value) {
909 if (index < 0 || index >= this->length()) return;
910 obj_.set(index + 1, value);
914 // --- T e m p l a t e ---
917 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
918 that->set_number_of_properties(0);
919 that->set_tag(i::Smi::FromInt(type));
923 void Template::Set(v8::Local<Name> name, v8::Local<Data> value,
924 v8::PropertyAttribute attribute) {
925 auto templ = Utils::OpenHandle(this);
926 i::Isolate* isolate = templ->GetIsolate();
928 i::HandleScope scope(isolate);
929 // TODO(dcarney): split api to allow values of v8::Value or v8::TemplateInfo.
930 i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
931 Utils::OpenHandle(*value),
932 static_cast<PropertyAttributes>(attribute));
936 void Template::SetAccessorProperty(
937 v8::Local<v8::Name> name,
938 v8::Local<FunctionTemplate> getter,
939 v8::Local<FunctionTemplate> setter,
940 v8::PropertyAttribute attribute,
941 v8::AccessControl access_control) {
942 // TODO(verwaest): Remove |access_control|.
943 DCHECK_EQ(v8::DEFAULT, access_control);
944 auto templ = Utils::OpenHandle(this);
945 auto isolate = templ->GetIsolate();
947 DCHECK(!name.IsEmpty());
948 DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
949 i::HandleScope scope(isolate);
950 i::ApiNatives::AddAccessorProperty(
951 isolate, templ, Utils::OpenHandle(*name),
952 Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true),
953 static_cast<PropertyAttributes>(attribute));
957 // --- F u n c t i o n T e m p l a t e ---
958 static void InitializeFunctionTemplate(
959 i::Handle<i::FunctionTemplateInfo> info) {
960 InitializeTemplate(info, Consts::FUNCTION_TEMPLATE);
965 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
966 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
968 i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(),
970 if (result->IsUndefined()) {
971 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(i_isolate);
972 result = Utils::OpenHandle(*ObjectTemplate::New(isolate));
973 Utils::OpenHandle(this)->set_prototype_template(*result);
975 return ToApiHandle<ObjectTemplate>(result);
979 static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info,
981 Utils::ApiCheck(!info->instantiated(), func,
982 "FunctionTemplate already instantiated");
986 void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) {
987 auto info = Utils::OpenHandle(this);
988 EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit");
989 i::Isolate* isolate = info->GetIsolate();
991 info->set_parent_template(*Utils::OpenHandle(*value));
995 static Local<FunctionTemplate> FunctionTemplateNew(
996 i::Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
997 v8::Local<Signature> signature, int length, bool do_not_cache) {
998 i::Handle<i::Struct> struct_obj =
999 isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
1000 i::Handle<i::FunctionTemplateInfo> obj =
1001 i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
1002 InitializeFunctionTemplate(obj);
1003 obj->set_do_not_cache(do_not_cache);
1004 int next_serial_number = 0;
1005 if (!do_not_cache) {
1006 next_serial_number = isolate->next_serial_number() + 1;
1007 isolate->set_next_serial_number(next_serial_number);
1009 obj->set_serial_number(i::Smi::FromInt(next_serial_number));
1010 if (callback != 0) {
1011 if (data.IsEmpty()) {
1012 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1014 Utils::ToLocal(obj)->SetCallHandler(callback, data);
1016 obj->set_length(length);
1017 obj->set_undetectable(false);
1018 obj->set_needs_access_check(false);
1019 obj->set_accept_any_receiver(true);
1020 if (!signature.IsEmpty())
1021 obj->set_signature(*Utils::OpenHandle(*signature));
1022 return Utils::ToLocal(obj);
1025 Local<FunctionTemplate> FunctionTemplate::New(Isolate* isolate,
1026 FunctionCallback callback,
1027 v8::Local<Value> data,
1028 v8::Local<Signature> signature,
1030 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1031 // Changes to the environment cannot be captured in the snapshot. Expect no
1032 // function templates when the isolate is created for serialization.
1033 DCHECK(!i_isolate->serializer_enabled());
1034 LOG_API(i_isolate, "FunctionTemplate::New");
1035 ENTER_V8(i_isolate);
1036 return FunctionTemplateNew(
1037 i_isolate, callback, data, signature, length, false);
1041 Local<Signature> Signature::New(Isolate* isolate,
1042 Local<FunctionTemplate> receiver) {
1043 return Utils::SignatureToLocal(Utils::OpenHandle(*receiver));
1047 Local<AccessorSignature> AccessorSignature::New(
1048 Isolate* isolate, Local<FunctionTemplate> receiver) {
1049 return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
1053 Local<TypeSwitch> TypeSwitch::New(Local<FunctionTemplate> type) {
1054 Local<FunctionTemplate> types[1] = {type};
1055 return TypeSwitch::New(1, types);
1059 Local<TypeSwitch> TypeSwitch::New(int argc, Local<FunctionTemplate> types[]) {
1060 i::Isolate* isolate = i::Isolate::Current();
1061 LOG_API(isolate, "TypeSwitch::New");
1063 i::Handle<i::FixedArray> vector = isolate->factory()->NewFixedArray(argc);
1064 for (int i = 0; i < argc; i++)
1065 vector->set(i, *Utils::OpenHandle(*types[i]));
1066 i::Handle<i::Struct> struct_obj =
1067 isolate->factory()->NewStruct(i::TYPE_SWITCH_INFO_TYPE);
1068 i::Handle<i::TypeSwitchInfo> obj =
1069 i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
1070 obj->set_types(*vector);
1071 return Utils::ToLocal(obj);
1075 int TypeSwitch::match(v8::Local<Value> value) {
1076 i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
1077 LOG_API(info->GetIsolate(), "TypeSwitch::match");
1078 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
1079 i::FixedArray* types = i::FixedArray::cast(info->types());
1080 for (int i = 0; i < types->length(); i++) {
1081 if (i::FunctionTemplateInfo::cast(types->get(i))->IsTemplateFor(*obj))
1088 #define SET_FIELD_WRAPPED(obj, setter, cdata) do { \
1089 i::Handle<i::Object> foreign = FromCData(obj->GetIsolate(), cdata); \
1090 (obj)->setter(*foreign); \
1094 void FunctionTemplate::SetCallHandler(FunctionCallback callback,
1095 v8::Local<Value> data) {
1096 auto info = Utils::OpenHandle(this);
1097 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler");
1098 i::Isolate* isolate = info->GetIsolate();
1100 i::HandleScope scope(isolate);
1101 i::Handle<i::Struct> struct_obj =
1102 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1103 i::Handle<i::CallHandlerInfo> obj =
1104 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1105 SET_FIELD_WRAPPED(obj, set_callback, callback);
1106 if (data.IsEmpty()) {
1107 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1109 obj->set_data(*Utils::OpenHandle(*data));
1110 info->set_call_code(*obj);
1114 static i::Handle<i::AccessorInfo> SetAccessorInfoProperties(
1115 i::Handle<i::AccessorInfo> obj, v8::Local<Name> name,
1116 v8::AccessControl settings, v8::PropertyAttribute attributes,
1117 v8::Local<AccessorSignature> signature) {
1118 obj->set_name(*Utils::OpenHandle(*name));
1119 if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
1120 if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
1121 obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
1122 if (!signature.IsEmpty()) {
1123 obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
1129 template <typename Getter, typename Setter>
1130 static i::Handle<i::AccessorInfo> MakeAccessorInfo(
1131 v8::Local<Name> name, Getter getter, Setter setter, v8::Local<Value> data,
1132 v8::AccessControl settings, v8::PropertyAttribute attributes,
1133 v8::Local<AccessorSignature> signature) {
1134 i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate();
1135 i::Handle<i::ExecutableAccessorInfo> obj =
1136 isolate->factory()->NewExecutableAccessorInfo();
1137 SET_FIELD_WRAPPED(obj, set_getter, getter);
1138 SET_FIELD_WRAPPED(obj, set_setter, setter);
1139 if (data.IsEmpty()) {
1140 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1142 obj->set_data(*Utils::OpenHandle(*data));
1143 return SetAccessorInfoProperties(obj, name, settings, attributes, signature);
1147 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
1148 i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
1149 if (!Utils::ApiCheck(!handle.is_null(),
1150 "v8::FunctionTemplate::InstanceTemplate()",
1151 "Reading from empty handle")) {
1152 return Local<ObjectTemplate>();
1154 i::Isolate* isolate = handle->GetIsolate();
1156 if (handle->instance_template()->IsUndefined()) {
1157 Local<ObjectTemplate> templ =
1158 ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
1159 handle->set_instance_template(*Utils::OpenHandle(*templ));
1161 i::Handle<i::ObjectTemplateInfo> result(
1162 i::ObjectTemplateInfo::cast(handle->instance_template()));
1163 return Utils::ToLocal(result);
1167 void FunctionTemplate::SetLength(int length) {
1168 auto info = Utils::OpenHandle(this);
1169 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength");
1170 auto isolate = info->GetIsolate();
1172 info->set_length(length);
1176 void FunctionTemplate::SetClassName(Local<String> name) {
1177 auto info = Utils::OpenHandle(this);
1178 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName");
1179 auto isolate = info->GetIsolate();
1181 info->set_class_name(*Utils::OpenHandle(*name));
1185 void FunctionTemplate::SetAcceptAnyReceiver(bool value) {
1186 auto info = Utils::OpenHandle(this);
1187 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
1188 auto isolate = info->GetIsolate();
1190 info->set_accept_any_receiver(value);
1194 void FunctionTemplate::SetHiddenPrototype(bool value) {
1195 auto info = Utils::OpenHandle(this);
1196 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype");
1197 auto isolate = info->GetIsolate();
1199 info->set_hidden_prototype(value);
1203 void FunctionTemplate::ReadOnlyPrototype() {
1204 auto info = Utils::OpenHandle(this);
1205 EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype");
1206 auto isolate = info->GetIsolate();
1208 info->set_read_only_prototype(true);
1212 void FunctionTemplate::RemovePrototype() {
1213 auto info = Utils::OpenHandle(this);
1214 EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype");
1215 auto isolate = info->GetIsolate();
1217 info->set_remove_prototype(true);
1221 // --- O b j e c t T e m p l a t e ---
1224 Local<ObjectTemplate> ObjectTemplate::New(
1225 Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1226 return New(reinterpret_cast<i::Isolate*>(isolate), constructor);
1230 Local<ObjectTemplate> ObjectTemplate::New() {
1231 return New(i::Isolate::Current(), Local<FunctionTemplate>());
1235 Local<ObjectTemplate> ObjectTemplate::New(
1236 i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1237 // Changes to the environment cannot be captured in the snapshot. Expect no
1238 // object templates when the isolate is created for serialization.
1239 DCHECK(!isolate->serializer_enabled());
1240 LOG_API(isolate, "ObjectTemplate::New");
1242 i::Handle<i::Struct> struct_obj =
1243 isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
1244 i::Handle<i::ObjectTemplateInfo> obj =
1245 i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
1246 InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
1247 if (!constructor.IsEmpty())
1248 obj->set_constructor(*Utils::OpenHandle(*constructor));
1249 obj->set_internal_field_count(i::Smi::FromInt(0));
1250 return Utils::ToLocal(obj);
1254 // Ensure that the object template has a constructor. If no
1255 // constructor is available we create one.
1256 static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
1257 i::Isolate* isolate,
1258 ObjectTemplate* object_template) {
1259 i::Object* obj = Utils::OpenHandle(object_template)->constructor();
1260 if (!obj ->IsUndefined()) {
1261 i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj);
1262 return i::Handle<i::FunctionTemplateInfo>(info, isolate);
1264 Local<FunctionTemplate> templ =
1265 FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
1266 i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
1267 constructor->set_instance_template(*Utils::OpenHandle(object_template));
1268 Utils::OpenHandle(object_template)->set_constructor(*constructor);
1273 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1274 i::Isolate* isolate,
1275 Template* template_obj) {
1276 return Utils::OpenHandle(template_obj);
1280 // TODO(dcarney): remove this with ObjectTemplate::SetAccessor
1281 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1282 i::Isolate* isolate,
1283 ObjectTemplate* object_template) {
1284 EnsureConstructor(isolate, object_template);
1285 return Utils::OpenHandle(object_template);
1289 template<typename Getter, typename Setter, typename Data, typename Template>
1290 static bool TemplateSetAccessor(
1291 Template* template_obj,
1292 v8::Local<Name> name,
1296 AccessControl settings,
1297 PropertyAttribute attribute,
1298 v8::Local<AccessorSignature> signature) {
1299 auto isolate = Utils::OpenHandle(template_obj)->GetIsolate();
1301 i::HandleScope scope(isolate);
1302 auto obj = MakeAccessorInfo(name, getter, setter, data, settings, attribute,
1304 if (obj.is_null()) return false;
1305 auto info = GetTemplateInfo(isolate, template_obj);
1306 i::ApiNatives::AddNativeDataProperty(isolate, info, obj);
1311 void Template::SetNativeDataProperty(v8::Local<String> name,
1312 AccessorGetterCallback getter,
1313 AccessorSetterCallback setter,
1314 v8::Local<Value> data,
1315 PropertyAttribute attribute,
1316 v8::Local<AccessorSignature> signature,
1317 AccessControl settings) {
1318 TemplateSetAccessor(
1319 this, name, getter, setter, data, settings, attribute, signature);
1323 void Template::SetNativeDataProperty(v8::Local<Name> name,
1324 AccessorNameGetterCallback getter,
1325 AccessorNameSetterCallback setter,
1326 v8::Local<Value> data,
1327 PropertyAttribute attribute,
1328 v8::Local<AccessorSignature> signature,
1329 AccessControl settings) {
1330 TemplateSetAccessor(
1331 this, name, getter, setter, data, settings, attribute, signature);
1335 void ObjectTemplate::SetAccessor(v8::Local<String> name,
1336 AccessorGetterCallback getter,
1337 AccessorSetterCallback setter,
1338 v8::Local<Value> data, AccessControl settings,
1339 PropertyAttribute attribute,
1340 v8::Local<AccessorSignature> signature) {
1341 TemplateSetAccessor(
1342 this, name, getter, setter, data, settings, attribute, signature);
1346 void ObjectTemplate::SetAccessor(v8::Local<Name> name,
1347 AccessorNameGetterCallback getter,
1348 AccessorNameSetterCallback setter,
1349 v8::Local<Value> data, AccessControl settings,
1350 PropertyAttribute attribute,
1351 v8::Local<AccessorSignature> signature) {
1352 TemplateSetAccessor(
1353 this, name, getter, setter, data, settings, attribute, signature);
1357 template <typename Getter, typename Setter, typename Query, typename Deleter,
1358 typename Enumerator>
1359 static void ObjectTemplateSetNamedPropertyHandler(ObjectTemplate* templ,
1360 Getter getter, Setter setter,
1361 Query query, Deleter remover,
1362 Enumerator enumerator,
1364 PropertyHandlerFlags flags) {
1365 i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate();
1367 i::HandleScope scope(isolate);
1368 auto cons = EnsureConstructor(isolate, templ);
1369 EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler");
1370 auto obj = i::Handle<i::InterceptorInfo>::cast(
1371 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1373 if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1374 if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1375 if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1376 if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1377 if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1379 obj->set_can_intercept_symbols(
1380 !(static_cast<int>(flags) &
1381 static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings)));
1382 obj->set_all_can_read(static_cast<int>(flags) &
1383 static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1384 obj->set_non_masking(static_cast<int>(flags) &
1385 static_cast<int>(PropertyHandlerFlags::kNonMasking));
1387 if (data.IsEmpty()) {
1388 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1390 obj->set_data(*Utils::OpenHandle(*data));
1391 cons->set_named_property_handler(*obj);
1395 void ObjectTemplate::SetNamedPropertyHandler(
1396 NamedPropertyGetterCallback getter, NamedPropertySetterCallback setter,
1397 NamedPropertyQueryCallback query, NamedPropertyDeleterCallback remover,
1398 NamedPropertyEnumeratorCallback enumerator, Local<Value> data) {
1399 ObjectTemplateSetNamedPropertyHandler(
1400 this, getter, setter, query, remover, enumerator, data,
1401 PropertyHandlerFlags::kOnlyInterceptStrings);
1405 void ObjectTemplate::SetHandler(
1406 const NamedPropertyHandlerConfiguration& config) {
1407 ObjectTemplateSetNamedPropertyHandler(
1408 this, config.getter, config.setter, config.query, config.deleter,
1409 config.enumerator, config.data, config.flags);
1413 void ObjectTemplate::MarkAsUndetectable() {
1414 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1416 i::HandleScope scope(isolate);
1417 auto cons = EnsureConstructor(isolate, this);
1418 EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable");
1419 cons->set_undetectable(true);
1423 void ObjectTemplate::SetAccessCheckCallbacks(
1424 NamedSecurityCallback named_callback,
1425 IndexedSecurityCallback indexed_callback, Local<Value> data) {
1426 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1428 i::HandleScope scope(isolate);
1429 auto cons = EnsureConstructor(isolate, this);
1430 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallbacks");
1432 i::Handle<i::Struct> struct_info =
1433 isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE);
1434 i::Handle<i::AccessCheckInfo> info =
1435 i::Handle<i::AccessCheckInfo>::cast(struct_info);
1437 SET_FIELD_WRAPPED(info, set_named_callback, named_callback);
1438 SET_FIELD_WRAPPED(info, set_indexed_callback, indexed_callback);
1440 if (data.IsEmpty()) {
1441 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1443 info->set_data(*Utils::OpenHandle(*data));
1445 cons->set_access_check_info(*info);
1446 cons->set_needs_access_check(true);
1450 void ObjectTemplate::SetHandler(
1451 const IndexedPropertyHandlerConfiguration& config) {
1452 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1454 i::HandleScope scope(isolate);
1455 auto cons = EnsureConstructor(isolate, this);
1456 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler");
1457 auto obj = i::Handle<i::InterceptorInfo>::cast(
1458 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1460 if (config.getter != 0) SET_FIELD_WRAPPED(obj, set_getter, config.getter);
1461 if (config.setter != 0) SET_FIELD_WRAPPED(obj, set_setter, config.setter);
1462 if (config.query != 0) SET_FIELD_WRAPPED(obj, set_query, config.query);
1463 if (config.deleter != 0) SET_FIELD_WRAPPED(obj, set_deleter, config.deleter);
1464 if (config.enumerator != 0) {
1465 SET_FIELD_WRAPPED(obj, set_enumerator, config.enumerator);
1468 obj->set_all_can_read(static_cast<int>(config.flags) &
1469 static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1471 v8::Local<v8::Value> data = config.data;
1472 if (data.IsEmpty()) {
1473 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1475 obj->set_data(*Utils::OpenHandle(*data));
1476 cons->set_indexed_property_handler(*obj);
1480 void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
1481 Local<Value> data) {
1482 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1484 i::HandleScope scope(isolate);
1485 auto cons = EnsureConstructor(isolate, this);
1486 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
1487 i::Handle<i::Struct> struct_obj =
1488 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1489 i::Handle<i::CallHandlerInfo> obj =
1490 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1491 SET_FIELD_WRAPPED(obj, set_callback, callback);
1492 if (data.IsEmpty()) {
1493 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1495 obj->set_data(*Utils::OpenHandle(*data));
1496 cons->set_instance_call_handler(*obj);
1500 int ObjectTemplate::InternalFieldCount() {
1501 return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
1505 void ObjectTemplate::SetInternalFieldCount(int value) {
1506 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1507 if (!Utils::ApiCheck(i::Smi::IsValid(value),
1508 "v8::ObjectTemplate::SetInternalFieldCount()",
1509 "Invalid internal field count")) {
1514 // The internal field count is set by the constructor function's
1515 // construct code, so we ensure that there is a constructor
1516 // function to do the setting.
1517 EnsureConstructor(isolate, this);
1519 Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
1523 // --- S c r i p t s ---
1526 // Internally, UnboundScript is a SharedFunctionInfo, and Script is a
1529 ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
1530 BufferPolicy buffer_policy_)
1534 buffer_policy(buffer_policy_) {}
1537 ScriptCompiler::CachedData::~CachedData() {
1538 if (buffer_policy == BufferOwned) {
1544 bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; }
1547 void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); }
1550 ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
1552 : impl_(new i::StreamedSource(stream, encoding)) {}
1555 ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; }
1558 const ScriptCompiler::CachedData*
1559 ScriptCompiler::StreamedSource::GetCachedData() const {
1560 return impl_->cached_data.get();
1564 Local<Script> UnboundScript::BindToCurrentContext() {
1565 i::Handle<i::HeapObject> obj =
1566 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1567 i::Handle<i::SharedFunctionInfo>
1568 function_info(i::SharedFunctionInfo::cast(*obj), obj->GetIsolate());
1569 i::Isolate* isolate = obj->GetIsolate();
1571 i::ScopeInfo* scope_info = function_info->scope_info();
1572 i::Handle<i::JSReceiver> global(isolate->native_context()->global_object());
1573 for (int i = 0; i < scope_info->StrongModeFreeVariableCount(); ++i) {
1574 i::Handle<i::String> name_string(scope_info->StrongModeFreeVariableName(i));
1575 i::ScriptContextTable::LookupResult result;
1576 i::Handle<i::ScriptContextTable> script_context_table(
1577 isolate->native_context()->script_context_table());
1578 if (!i::ScriptContextTable::Lookup(script_context_table, name_string,
1580 i::Handle<i::Name> name(scope_info->StrongModeFreeVariableName(i));
1581 Maybe<bool> has = i::JSReceiver::HasProperty(global, name);
1582 if (has.IsJust() && !has.FromJust()) {
1583 i::PendingCompilationErrorHandler pending_error_handler_;
1584 pending_error_handler_.ReportMessageAt(
1585 scope_info->StrongModeFreeVariableStartPosition(i),
1586 scope_info->StrongModeFreeVariableEndPosition(i),
1587 i::MessageTemplate::kStrongUnboundGlobal, name_string,
1588 i::kReferenceError);
1589 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1590 pending_error_handler_.ThrowPendingError(isolate, script);
1591 isolate->ReportPendingMessages();
1592 isolate->OptionalRescheduleException(true);
1593 return Local<Script>();
1597 i::Handle<i::JSFunction> function =
1598 obj->GetIsolate()->factory()->NewFunctionFromSharedFunctionInfo(
1599 function_info, isolate->native_context());
1600 return ToApiHandle<Script>(function);
1604 int UnboundScript::GetId() {
1605 i::Handle<i::HeapObject> obj =
1606 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1607 i::Isolate* isolate = obj->GetIsolate();
1608 LOG_API(isolate, "v8::UnboundScript::GetId");
1609 i::HandleScope scope(isolate);
1610 i::Handle<i::SharedFunctionInfo> function_info(
1611 i::SharedFunctionInfo::cast(*obj));
1612 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1613 return script->id()->value();
1617 int UnboundScript::GetLineNumber(int code_pos) {
1618 i::Handle<i::SharedFunctionInfo> obj =
1619 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1620 i::Isolate* isolate = obj->GetIsolate();
1621 LOG_API(isolate, "UnboundScript::GetLineNumber");
1622 if (obj->script()->IsScript()) {
1623 i::Handle<i::Script> script(i::Script::cast(obj->script()));
1624 return i::Script::GetLineNumber(script, code_pos);
1631 Local<Value> UnboundScript::GetScriptName() {
1632 i::Handle<i::SharedFunctionInfo> obj =
1633 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1634 i::Isolate* isolate = obj->GetIsolate();
1635 LOG_API(isolate, "UnboundScript::GetName");
1636 if (obj->script()->IsScript()) {
1637 i::Object* name = i::Script::cast(obj->script())->name();
1638 return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
1640 return Local<String>();
1645 Local<Value> UnboundScript::GetSourceURL() {
1646 i::Handle<i::SharedFunctionInfo> obj =
1647 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1648 i::Isolate* isolate = obj->GetIsolate();
1649 LOG_API(isolate, "UnboundScript::GetSourceURL");
1650 if (obj->script()->IsScript()) {
1651 i::Object* url = i::Script::cast(obj->script())->source_url();
1652 return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1654 return Local<String>();
1659 Local<Value> UnboundScript::GetSourceMappingURL() {
1660 i::Handle<i::SharedFunctionInfo> obj =
1661 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1662 i::Isolate* isolate = obj->GetIsolate();
1663 LOG_API(isolate, "UnboundScript::GetSourceMappingURL");
1664 if (obj->script()->IsScript()) {
1665 i::Object* url = i::Script::cast(obj->script())->source_mapping_url();
1666 return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1668 return Local<String>();
1673 MaybeLocal<Value> Script::Run(Local<Context> context) {
1674 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Script::Run()", Value)
1675 i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
1676 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
1677 auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this));
1678 i::Handle<i::Object> receiver(isolate->global_proxy(), isolate);
1679 Local<Value> result;
1680 has_pending_exception =
1681 !ToLocal<Value>(i::Execution::Call(isolate, fun, receiver, 0, NULL),
1683 RETURN_ON_FAILED_EXECUTION(Value);
1684 RETURN_ESCAPED(result);
1688 Local<Value> Script::Run() {
1689 auto self = Utils::OpenHandle(this, true);
1690 // If execution is terminating, Compile(..)->Run() requires this
1692 if (self.is_null()) return Local<Value>();
1693 auto context = ContextFromHeapObject(self);
1694 RETURN_TO_LOCAL_UNCHECKED(Run(context), Value);
1698 Local<UnboundScript> Script::GetUnboundScript() {
1699 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1700 return ToApiHandle<UnboundScript>(
1701 i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared()));
1705 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal(
1706 Isolate* v8_isolate, Source* source, CompileOptions options,
1708 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1709 PREPARE_FOR_EXECUTION_WITH_ISOLATE(
1710 isolate, "v8::ScriptCompiler::CompileUnbound()", UnboundScript);
1712 // Don't try to produce any kind of cache when the debugger is loaded.
1713 if (isolate->debug()->is_loaded() &&
1714 (options == kProduceParserCache || options == kProduceCodeCache)) {
1715 options = kNoCompileOptions;
1718 i::ScriptData* script_data = NULL;
1719 if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1720 DCHECK(source->cached_data);
1721 // ScriptData takes care of pointer-aligning the data.
1722 script_data = new i::ScriptData(source->cached_data->data,
1723 source->cached_data->length);
1726 i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
1727 i::Handle<i::SharedFunctionInfo> result;
1729 i::HistogramTimerScope total(isolate->counters()->compile_script(), true);
1730 i::Handle<i::Object> name_obj;
1731 i::Handle<i::Object> source_map_url;
1732 int line_offset = 0;
1733 int column_offset = 0;
1734 if (!source->resource_name.IsEmpty()) {
1735 name_obj = Utils::OpenHandle(*(source->resource_name));
1737 if (!source->resource_line_offset.IsEmpty()) {
1738 line_offset = static_cast<int>(source->resource_line_offset->Value());
1740 if (!source->resource_column_offset.IsEmpty()) {
1742 static_cast<int>(source->resource_column_offset->Value());
1744 if (!source->source_map_url.IsEmpty()) {
1745 source_map_url = Utils::OpenHandle(*(source->source_map_url));
1747 result = i::Compiler::CompileScript(
1748 str, name_obj, line_offset, column_offset, source->resource_options,
1749 source_map_url, isolate->native_context(), NULL, &script_data, options,
1750 i::NOT_NATIVES_CODE, is_module);
1751 has_pending_exception = result.is_null();
1752 if (has_pending_exception && script_data != NULL) {
1753 // This case won't happen during normal operation; we have compiled
1754 // successfully and produced cached data, and but the second compilation
1755 // of the same source code fails.
1759 RETURN_ON_FAILED_EXECUTION(UnboundScript);
1761 if ((options == kProduceParserCache || options == kProduceCodeCache) &&
1762 script_data != NULL) {
1763 // script_data now contains the data that was generated. source will
1764 // take the ownership.
1765 source->cached_data = new CachedData(
1766 script_data->data(), script_data->length(), CachedData::BufferOwned);
1767 script_data->ReleaseDataOwnership();
1768 } else if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1769 source->cached_data->rejected = script_data->rejected();
1773 RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
1777 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript(
1778 Isolate* v8_isolate, Source* source, CompileOptions options) {
1779 return CompileUnboundInternal(v8_isolate, source, options, false);
1783 Local<UnboundScript> ScriptCompiler::CompileUnbound(Isolate* v8_isolate,
1785 CompileOptions options) {
1786 RETURN_TO_LOCAL_UNCHECKED(
1787 CompileUnboundInternal(v8_isolate, source, options, false),
1792 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1794 CompileOptions options) {
1795 auto isolate = context->GetIsolate();
1796 auto maybe = CompileUnboundInternal(isolate, source, options, false);
1797 Local<UnboundScript> result;
1798 if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
1799 v8::Context::Scope scope(context);
1800 return result->BindToCurrentContext();
1804 Local<Script> ScriptCompiler::Compile(
1805 Isolate* v8_isolate,
1807 CompileOptions options) {
1808 auto context = v8_isolate->GetCurrentContext();
1809 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, options), Script);
1813 MaybeLocal<Script> ScriptCompiler::CompileModule(Local<Context> context,
1815 CompileOptions options) {
1816 CHECK(i::FLAG_harmony_modules);
1817 auto isolate = context->GetIsolate();
1818 auto maybe = CompileUnboundInternal(isolate, source, options, true);
1819 Local<UnboundScript> generic;
1820 if (!maybe.ToLocal(&generic)) return MaybeLocal<Script>();
1821 v8::Context::Scope scope(context);
1822 return generic->BindToCurrentContext();
1826 class IsIdentifierHelper {
1828 IsIdentifierHelper() : is_identifier_(false), first_char_(true) {}
1830 bool Check(i::String* string) {
1831 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
1832 if (cons_string == NULL) return is_identifier_;
1833 // We don't support cons strings here.
1836 void VisitOneByteString(const uint8_t* chars, int length) {
1837 for (int i = 0; i < length; ++i) {
1839 first_char_ = false;
1840 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1842 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1846 void VisitTwoByteString(const uint16_t* chars, int length) {
1847 for (int i = 0; i < length; ++i) {
1849 first_char_ = false;
1850 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1852 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1858 bool is_identifier_;
1860 i::UnicodeCache unicode_cache_;
1861 DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper);
1865 MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext(
1866 Local<Context> v8_context, Source* source, size_t arguments_count,
1867 Local<String> arguments[], size_t context_extension_count,
1868 Local<Object> context_extensions[]) {
1869 PREPARE_FOR_EXECUTION(
1870 v8_context, "v8::ScriptCompiler::CompileFunctionInContext()", Function);
1871 i::Handle<i::String> source_string;
1872 auto factory = isolate->factory();
1873 if (arguments_count) {
1874 source_string = factory->NewStringFromStaticChars("(function(");
1875 for (size_t i = 0; i < arguments_count; ++i) {
1876 IsIdentifierHelper helper;
1877 if (!helper.Check(*Utils::OpenHandle(*arguments[i]))) {
1878 return Local<Function>();
1880 has_pending_exception =
1881 !factory->NewConsString(source_string,
1882 Utils::OpenHandle(*arguments[i]))
1883 .ToHandle(&source_string);
1884 RETURN_ON_FAILED_EXECUTION(Function);
1885 if (i + 1 == arguments_count) continue;
1886 has_pending_exception =
1887 !factory->NewConsString(source_string,
1888 factory->LookupSingleCharacterStringFromCode(
1889 ',')).ToHandle(&source_string);
1890 RETURN_ON_FAILED_EXECUTION(Function);
1892 auto brackets = factory->NewStringFromStaticChars("){");
1893 has_pending_exception = !factory->NewConsString(source_string, brackets)
1894 .ToHandle(&source_string);
1895 RETURN_ON_FAILED_EXECUTION(Function);
1897 source_string = factory->NewStringFromStaticChars("(function(){");
1900 int scope_position = source_string->length();
1901 has_pending_exception =
1902 !factory->NewConsString(source_string,
1903 Utils::OpenHandle(*source->source_string))
1904 .ToHandle(&source_string);
1905 RETURN_ON_FAILED_EXECUTION(Function);
1906 // Include \n in case the source contains a line end comment.
1907 auto brackets = factory->NewStringFromStaticChars("\n})");
1908 has_pending_exception =
1909 !factory->NewConsString(source_string, brackets).ToHandle(&source_string);
1910 RETURN_ON_FAILED_EXECUTION(Function);
1912 i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
1913 i::Handle<i::SharedFunctionInfo> outer_info(context->closure()->shared(),
1915 for (size_t i = 0; i < context_extension_count; ++i) {
1916 i::Handle<i::JSObject> extension =
1917 Utils::OpenHandle(*context_extensions[i]);
1918 i::Handle<i::JSFunction> closure(context->closure(), isolate);
1919 context = factory->NewWithContext(closure, context, extension);
1922 i::Handle<i::Object> name_obj;
1923 int line_offset = 0;
1924 int column_offset = 0;
1925 if (!source->resource_name.IsEmpty()) {
1926 name_obj = Utils::OpenHandle(*(source->resource_name));
1928 if (!source->resource_line_offset.IsEmpty()) {
1929 line_offset = static_cast<int>(source->resource_line_offset->Value());
1931 if (!source->resource_column_offset.IsEmpty()) {
1932 column_offset = static_cast<int>(source->resource_column_offset->Value());
1934 i::Handle<i::JSFunction> fun;
1935 has_pending_exception = !i::Compiler::GetFunctionFromEval(
1936 source_string, outer_info, context, i::SLOPPY,
1937 i::ONLY_SINGLE_FUNCTION_LITERAL, line_offset,
1938 column_offset - scope_position, name_obj,
1939 source->resource_options).ToHandle(&fun);
1940 if (has_pending_exception) {
1941 isolate->ReportPendingMessages();
1943 RETURN_ON_FAILED_EXECUTION(Function);
1945 i::Handle<i::Object> result;
1946 has_pending_exception =
1947 !i::Execution::Call(isolate, fun,
1948 Utils::OpenHandle(*v8_context->Global()), 0,
1949 nullptr).ToHandle(&result);
1950 RETURN_ON_FAILED_EXECUTION(Function);
1951 RETURN_ESCAPED(Utils::ToLocal(i::Handle<i::JSFunction>::cast(result)));
1955 Local<Function> ScriptCompiler::CompileFunctionInContext(
1956 Isolate* v8_isolate, Source* source, Local<Context> v8_context,
1957 size_t arguments_count, Local<String> arguments[],
1958 size_t context_extension_count, Local<Object> context_extensions[]) {
1959 RETURN_TO_LOCAL_UNCHECKED(
1960 CompileFunctionInContext(v8_context, source, arguments_count, arguments,
1961 context_extension_count, context_extensions),
1966 ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript(
1967 Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
1968 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1969 return new i::BackgroundParsingTask(source->impl(), options,
1970 i::FLAG_stack_size, isolate);
1974 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1975 StreamedSource* v8_source,
1976 Local<String> full_source_string,
1977 const ScriptOrigin& origin) {
1978 PREPARE_FOR_EXECUTION(context, "v8::ScriptCompiler::Compile()", Script);
1979 i::StreamedSource* source = v8_source->impl();
1980 i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
1981 i::Handle<i::Script> script = isolate->factory()->NewScript(str);
1982 if (!origin.ResourceName().IsEmpty()) {
1983 script->set_name(*Utils::OpenHandle(*(origin.ResourceName())));
1985 if (!origin.ResourceLineOffset().IsEmpty()) {
1986 script->set_line_offset(i::Smi::FromInt(
1987 static_cast<int>(origin.ResourceLineOffset()->Value())));
1989 if (!origin.ResourceColumnOffset().IsEmpty()) {
1990 script->set_column_offset(i::Smi::FromInt(
1991 static_cast<int>(origin.ResourceColumnOffset()->Value())));
1993 script->set_origin_options(origin.Options());
1994 if (!origin.SourceMapUrl().IsEmpty()) {
1995 script->set_source_mapping_url(
1996 *Utils::OpenHandle(*(origin.SourceMapUrl())));
1999 source->info->set_script(script);
2000 source->info->set_context(isolate->native_context());
2002 // Do the parsing tasks which need to be done on the main thread. This will
2003 // also handle parse errors.
2004 source->parser->Internalize(isolate, script,
2005 source->info->function() == nullptr);
2006 source->parser->HandleSourceURLComments(isolate, script);
2008 i::Handle<i::SharedFunctionInfo> result;
2009 if (source->info->function() != nullptr) {
2010 // Parsing has succeeded.
2011 result = i::Compiler::CompileStreamedScript(script, source->info.get(),
2014 has_pending_exception = result.is_null();
2015 if (has_pending_exception) isolate->ReportPendingMessages();
2016 RETURN_ON_FAILED_EXECUTION(Script);
2018 source->info->clear_script(); // because script goes out of scope.
2020 Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
2021 if (generic.IsEmpty()) return Local<Script>();
2022 Local<Script> bound = generic->BindToCurrentContext();
2023 if (bound.IsEmpty()) return Local<Script>();
2024 RETURN_ESCAPED(bound);
2028 Local<Script> ScriptCompiler::Compile(Isolate* v8_isolate,
2029 StreamedSource* v8_source,
2030 Local<String> full_source_string,
2031 const ScriptOrigin& origin) {
2032 auto context = v8_isolate->GetCurrentContext();
2033 RETURN_TO_LOCAL_UNCHECKED(
2034 Compile(context, v8_source, full_source_string, origin), Script);
2038 uint32_t ScriptCompiler::CachedDataVersionTag() {
2039 return static_cast<uint32_t>(base::hash_combine(
2040 internal::Version::Hash(), internal::FlagList::Hash(),
2041 static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures())));
2045 MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source,
2046 ScriptOrigin* origin) {
2048 ScriptCompiler::Source script_source(source, *origin);
2049 return ScriptCompiler::Compile(context, &script_source);
2051 ScriptCompiler::Source script_source(source);
2052 return ScriptCompiler::Compile(context, &script_source);
2056 Local<Script> Script::Compile(v8::Local<String> source,
2057 v8::ScriptOrigin* origin) {
2058 auto str = Utils::OpenHandle(*source);
2059 auto context = ContextFromHeapObject(str);
2060 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, origin), Script);
2064 Local<Script> Script::Compile(v8::Local<String> source,
2065 v8::Local<String> file_name) {
2066 auto str = Utils::OpenHandle(*source);
2067 auto context = ContextFromHeapObject(str);
2068 ScriptOrigin origin(file_name);
2069 return Compile(context, source, &origin).FromMaybe(Local<Script>());
2073 // --- E x c e p t i o n s ---
2076 v8::TryCatch::TryCatch()
2077 : isolate_(i::Isolate::Current()),
2078 next_(isolate_->try_catch_handler()),
2080 can_continue_(true),
2081 capture_message_(true),
2083 has_terminated_(false) {
2085 // Special handling for simulators which have a separate JS stack.
2086 js_stack_comparable_address_ =
2087 reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2088 v8::internal::GetCurrentStackPosition()));
2089 isolate_->RegisterTryCatchHandler(this);
2093 v8::TryCatch::TryCatch(v8::Isolate* isolate)
2094 : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
2095 next_(isolate_->try_catch_handler()),
2097 can_continue_(true),
2098 capture_message_(true),
2100 has_terminated_(false) {
2102 // Special handling for simulators which have a separate JS stack.
2103 js_stack_comparable_address_ =
2104 reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2105 v8::internal::GetCurrentStackPosition()));
2106 isolate_->RegisterTryCatchHandler(this);
2110 v8::TryCatch::~TryCatch() {
2112 v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
2113 v8::HandleScope scope(isolate);
2114 v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
2115 if (HasCaught() && capture_message_) {
2116 // If an exception was caught and rethrow_ is indicated, the saved
2117 // message, script, and location need to be restored to Isolate TLS
2118 // for reuse. capture_message_ needs to be disabled so that Throw()
2119 // does not create a new message.
2120 isolate_->thread_local_top()->rethrowing_message_ = true;
2121 isolate_->RestorePendingMessageFromTryCatch(this);
2123 isolate_->UnregisterTryCatchHandler(this);
2124 v8::internal::SimulatorStack::UnregisterCTryCatch();
2125 reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
2126 DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
2128 if (HasCaught() && isolate_->has_scheduled_exception()) {
2129 // If an exception was caught but is still scheduled because no API call
2130 // promoted it, then it is canceled to prevent it from being propagated.
2131 // Note that this will not cancel termination exceptions.
2132 isolate_->CancelScheduledExceptionFromTryCatch(this);
2134 isolate_->UnregisterTryCatchHandler(this);
2135 v8::internal::SimulatorStack::UnregisterCTryCatch();
2140 bool v8::TryCatch::HasCaught() const {
2141 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
2145 bool v8::TryCatch::CanContinue() const {
2146 return can_continue_;
2150 bool v8::TryCatch::HasTerminated() const {
2151 return has_terminated_;
2155 v8::Local<v8::Value> v8::TryCatch::ReThrow() {
2156 if (!HasCaught()) return v8::Local<v8::Value>();
2158 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
2162 v8::Local<Value> v8::TryCatch::Exception() const {
2164 // Check for out of memory exception.
2165 i::Object* exception = reinterpret_cast<i::Object*>(exception_);
2166 return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
2168 return v8::Local<Value>();
2173 MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const {
2174 if (!HasCaught()) return v8::Local<Value>();
2175 i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
2176 if (!raw_obj->IsJSObject()) return v8::Local<Value>();
2177 PREPARE_FOR_EXECUTION(context, "v8::TryCatch::StackTrace", Value);
2178 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
2179 i::Handle<i::String> name = isolate->factory()->stack_string();
2180 Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
2181 has_pending_exception = !maybe.IsJust();
2182 RETURN_ON_FAILED_EXECUTION(Value);
2183 if (!maybe.FromJust()) return v8::Local<Value>();
2184 Local<Value> result;
2185 has_pending_exception =
2186 !ToLocal<Value>(i::Object::GetProperty(obj, name), &result);
2187 RETURN_ON_FAILED_EXECUTION(Value);
2188 RETURN_ESCAPED(result);
2192 v8::Local<Value> v8::TryCatch::StackTrace() const {
2193 auto context = reinterpret_cast<v8::Isolate*>(isolate_)->GetCurrentContext();
2194 RETURN_TO_LOCAL_UNCHECKED(StackTrace(context), Value);
2198 v8::Local<v8::Message> v8::TryCatch::Message() const {
2199 i::Object* message = reinterpret_cast<i::Object*>(message_obj_);
2200 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
2201 if (HasCaught() && !message->IsTheHole()) {
2202 return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
2204 return v8::Local<v8::Message>();
2209 void v8::TryCatch::Reset() {
2210 if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
2211 // If an exception was caught but is still scheduled because no API call
2212 // promoted it, then it is canceled to prevent it from being propagated.
2213 // Note that this will not cancel termination exceptions.
2214 isolate_->CancelScheduledExceptionFromTryCatch(this);
2220 void v8::TryCatch::ResetInternal() {
2221 i::Object* the_hole = isolate_->heap()->the_hole_value();
2222 exception_ = the_hole;
2223 message_obj_ = the_hole;
2227 void v8::TryCatch::SetVerbose(bool value) {
2228 is_verbose_ = value;
2232 void v8::TryCatch::SetCaptureMessage(bool value) {
2233 capture_message_ = value;
2237 // --- M e s s a g e ---
2240 Local<String> Message::Get() const {
2241 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2243 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2244 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2245 i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
2246 Local<String> result = Utils::ToLocal(raw_result);
2247 return scope.Escape(result);
2251 ScriptOrigin Message::GetScriptOrigin() const {
2252 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2253 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2254 auto script_wraper = i::Handle<i::Object>(message->script(), isolate);
2255 auto script_value = i::Handle<i::JSValue>::cast(script_wraper);
2256 i::Handle<i::Script> script(i::Script::cast(script_value->value()));
2257 return GetScriptOriginForScript(isolate, script);
2261 v8::Local<Value> Message::GetScriptResourceName() const {
2262 return GetScriptOrigin().ResourceName();
2266 v8::Local<v8::StackTrace> Message::GetStackTrace() const {
2267 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2269 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2270 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2271 i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
2272 if (!stackFramesObj->IsJSArray()) return v8::Local<v8::StackTrace>();
2273 auto stackTrace = i::Handle<i::JSArray>::cast(stackFramesObj);
2274 return scope.Escape(Utils::StackTraceToLocal(stackTrace));
2278 MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
2279 i::Isolate* isolate, const char* name, i::Handle<i::Object> recv, int argc,
2280 i::Handle<i::Object> argv[]) {
2281 i::Handle<i::Object> object_fun =
2282 i::Object::GetProperty(
2283 isolate, isolate->js_builtins_object(), name).ToHandleChecked();
2284 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(object_fun);
2285 return i::Execution::Call(isolate, fun, recv, argc, argv);
2289 MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
2290 i::Isolate* isolate, const char* name, i::Handle<i::Object> data) {
2291 i::Handle<i::Object> argv[] = { data };
2292 return CallV8HeapFunction(isolate, name, isolate->js_builtins_object(),
2293 arraysize(argv), argv);
2297 Maybe<int> Message::GetLineNumber(Local<Context> context) const {
2298 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetLineNumber()", int);
2299 i::Handle<i::Object> result;
2300 has_pending_exception =
2301 !CallV8HeapFunction(isolate, "$messageGetLineNumber",
2302 Utils::OpenHandle(this)).ToHandle(&result);
2303 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2304 return Just(static_cast<int>(result->Number()));
2308 int Message::GetLineNumber() const {
2309 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2310 return GetLineNumber(context).FromMaybe(0);
2314 int Message::GetStartPosition() const {
2315 auto self = Utils::OpenHandle(this);
2316 return self->start_position();
2320 int Message::GetEndPosition() const {
2321 auto self = Utils::OpenHandle(this);
2322 return self->end_position();
2326 Maybe<int> Message::GetStartColumn(Local<Context> context) const {
2327 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetStartColumn()",
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 return Just(static_cast<int>(start_col_obj->Number()));
2339 int Message::GetStartColumn() const {
2340 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2341 const int default_value = kNoColumnInfo;
2342 return GetStartColumn(context).FromMaybe(default_value);
2346 Maybe<int> Message::GetEndColumn(Local<Context> context) const {
2347 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetEndColumn()", int);
2348 auto self = Utils::OpenHandle(this);
2349 i::Handle<i::Object> start_col_obj;
2350 has_pending_exception =
2351 !CallV8HeapFunction(isolate, "$messageGetPositionInLine", self)
2352 .ToHandle(&start_col_obj);
2353 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2354 int start = self->start_position();
2355 int end = self->end_position();
2356 return Just(static_cast<int>(start_col_obj->Number()) + (end - start));
2360 int Message::GetEndColumn() const {
2361 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2362 const int default_value = kNoColumnInfo;
2363 return GetEndColumn(context).FromMaybe(default_value);
2367 bool Message::IsSharedCrossOrigin() const {
2368 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2370 auto self = Utils::OpenHandle(this);
2371 auto script = i::Handle<i::JSValue>::cast(
2372 i::Handle<i::Object>(self->script(), isolate));
2373 return i::Script::cast(script->value())
2375 .IsSharedCrossOrigin();
2378 bool Message::IsOpaque() const {
2379 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2381 auto self = Utils::OpenHandle(this);
2382 auto script = i::Handle<i::JSValue>::cast(
2383 i::Handle<i::Object>(self->script(), isolate));
2384 return i::Script::cast(script->value())->origin_options().IsOpaque();
2388 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
2389 PREPARE_FOR_EXECUTION(context, "v8::Message::GetSourceLine()", String);
2390 i::Handle<i::Object> result;
2391 has_pending_exception =
2392 !CallV8HeapFunction(isolate, "$messageGetSourceLine",
2393 Utils::OpenHandle(this)).ToHandle(&result);
2394 RETURN_ON_FAILED_EXECUTION(String);
2396 if (result->IsString()) {
2397 str = Utils::ToLocal(i::Handle<i::String>::cast(result));
2399 RETURN_ESCAPED(str);
2403 Local<String> Message::GetSourceLine() const {
2404 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2405 RETURN_TO_LOCAL_UNCHECKED(GetSourceLine(context), String)
2409 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
2410 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2411 ENTER_V8(i_isolate);
2412 i_isolate->PrintCurrentStackTrace(out);
2416 // --- S t a c k T r a c e ---
2418 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
2419 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2421 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2422 auto self = Utils::OpenHandle(this);
2423 auto obj = i::Object::GetElement(isolate, self, index).ToHandleChecked();
2424 auto jsobj = i::Handle<i::JSObject>::cast(obj);
2425 return scope.Escape(Utils::StackFrameToLocal(jsobj));
2429 int StackTrace::GetFrameCount() const {
2430 return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
2434 Local<Array> StackTrace::AsArray() {
2435 return Utils::ToLocal(Utils::OpenHandle(this));
2439 Local<StackTrace> StackTrace::CurrentStackTrace(
2442 StackTraceOptions options) {
2443 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2444 ENTER_V8(i_isolate);
2445 // TODO(dcarney): remove when ScriptDebugServer is fixed.
2446 options = static_cast<StackTraceOptions>(
2447 static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins);
2448 i::Handle<i::JSArray> stackTrace =
2449 i_isolate->CaptureCurrentStackTrace(frame_limit, options);
2450 return Utils::StackTraceToLocal(stackTrace);
2454 // --- S t a c k F r a m e ---
2456 static int getIntProperty(const StackFrame* f, const char* propertyName,
2458 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2460 i::HandleScope scope(isolate);
2461 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2462 i::Handle<i::Object> obj =
2463 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2464 return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue;
2468 int StackFrame::GetLineNumber() const {
2469 return getIntProperty(this, "lineNumber", Message::kNoLineNumberInfo);
2473 int StackFrame::GetColumn() const {
2474 return getIntProperty(this, "column", Message::kNoColumnInfo);
2478 int StackFrame::GetScriptId() const {
2479 return getIntProperty(this, "scriptId", Message::kNoScriptIdInfo);
2483 static Local<String> getStringProperty(const StackFrame* f,
2484 const char* propertyName) {
2485 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2487 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2488 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2489 i::Handle<i::Object> obj =
2490 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2491 return obj->IsString()
2492 ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2497 Local<String> StackFrame::GetScriptName() const {
2498 return getStringProperty(this, "scriptName");
2502 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2503 return getStringProperty(this, "scriptNameOrSourceURL");
2507 Local<String> StackFrame::GetFunctionName() const {
2508 return getStringProperty(this, "functionName");
2512 static bool getBoolProperty(const StackFrame* f, const char* propertyName) {
2513 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2515 i::HandleScope scope(isolate);
2516 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2517 i::Handle<i::Object> obj =
2518 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2519 return obj->IsTrue();
2522 bool StackFrame::IsEval() const { return getBoolProperty(this, "isEval"); }
2525 bool StackFrame::IsConstructor() const {
2526 return getBoolProperty(this, "isConstructor");
2530 // --- N a t i v e W e a k M a p ---
2532 Local<NativeWeakMap> NativeWeakMap::New(Isolate* v8_isolate) {
2533 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2535 i::Handle<i::JSWeakMap> weakmap = isolate->factory()->NewJSWeakMap();
2536 i::Runtime::WeakCollectionInitialize(isolate, weakmap);
2537 return Utils::NativeWeakMapToLocal(weakmap);
2541 void NativeWeakMap::Set(Local<Value> v8_key, Local<Value> v8_value) {
2542 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2543 i::Isolate* isolate = weak_collection->GetIsolate();
2545 i::HandleScope scope(isolate);
2546 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2547 i::Handle<i::Object> value = Utils::OpenHandle(*v8_value);
2548 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2552 i::Handle<i::ObjectHashTable> table(
2553 i::ObjectHashTable::cast(weak_collection->table()));
2554 if (!table->IsKey(*key)) {
2558 int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value();
2559 i::Runtime::WeakCollectionSet(weak_collection, key, value, hash);
2563 Local<Value> NativeWeakMap::Get(Local<Value> v8_key) {
2564 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2565 i::Isolate* isolate = weak_collection->GetIsolate();
2567 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2568 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2570 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2572 i::Handle<i::ObjectHashTable> table(
2573 i::ObjectHashTable::cast(weak_collection->table()));
2574 if (!table->IsKey(*key)) {
2576 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2578 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2579 if (lookup->IsTheHole())
2580 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2581 return Utils::ToLocal(lookup);
2585 bool NativeWeakMap::Has(Local<Value> v8_key) {
2586 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2587 i::Isolate* isolate = weak_collection->GetIsolate();
2589 i::HandleScope scope(isolate);
2590 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2591 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2595 i::Handle<i::ObjectHashTable> table(
2596 i::ObjectHashTable::cast(weak_collection->table()));
2597 if (!table->IsKey(*key)) {
2601 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2602 return !lookup->IsTheHole();
2606 bool NativeWeakMap::Delete(Local<Value> v8_key) {
2607 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2608 i::Isolate* isolate = weak_collection->GetIsolate();
2610 i::HandleScope scope(isolate);
2611 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2612 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2616 i::Handle<i::ObjectHashTable> table(
2617 i::ObjectHashTable::cast(weak_collection->table()));
2618 if (!table->IsKey(*key)) {
2622 return i::Runtime::WeakCollectionDelete(weak_collection, key);
2628 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) {
2629 auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2630 PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, "JSON::Parse", Value);
2631 i::Handle<i::String> string = Utils::OpenHandle(*json_string);
2632 i::Handle<i::String> source = i::String::Flatten(string);
2633 auto maybe = source->IsSeqOneByteString()
2634 ? i::JsonParser<true>::Parse(source)
2635 : i::JsonParser<false>::Parse(source);
2636 Local<Value> result;
2637 has_pending_exception = !ToLocal<Value>(maybe, &result);
2638 RETURN_ON_FAILED_EXECUTION(Value);
2639 RETURN_ESCAPED(result);
2643 Local<Value> JSON::Parse(Local<String> json_string) {
2644 auto isolate = reinterpret_cast<v8::Isolate*>(
2645 Utils::OpenHandle(*json_string)->GetIsolate());
2646 RETURN_TO_LOCAL_UNCHECKED(Parse(isolate, json_string), Value);
2652 bool Value::FullIsUndefined() const {
2653 bool result = Utils::OpenHandle(this)->IsUndefined();
2654 DCHECK_EQ(result, QuickIsUndefined());
2659 bool Value::FullIsNull() const {
2660 bool result = Utils::OpenHandle(this)->IsNull();
2661 DCHECK_EQ(result, QuickIsNull());
2666 bool Value::IsTrue() const {
2667 return Utils::OpenHandle(this)->IsTrue();
2671 bool Value::IsFalse() const {
2672 return Utils::OpenHandle(this)->IsFalse();
2676 bool Value::IsFunction() const {
2677 return Utils::OpenHandle(this)->IsJSFunction();
2681 bool Value::IsName() const {
2682 return Utils::OpenHandle(this)->IsName();
2686 bool Value::FullIsString() const {
2687 bool result = Utils::OpenHandle(this)->IsString();
2688 DCHECK_EQ(result, QuickIsString());
2693 bool Value::IsSymbol() const {
2694 return Utils::OpenHandle(this)->IsSymbol();
2698 bool Value::IsArray() const {
2699 return Utils::OpenHandle(this)->IsJSArray();
2703 bool Value::IsArrayBuffer() const {
2704 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2705 return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
2709 bool Value::IsArrayBufferView() const {
2710 return Utils::OpenHandle(this)->IsJSArrayBufferView();
2714 bool Value::IsTypedArray() const {
2715 return Utils::OpenHandle(this)->IsJSTypedArray();
2719 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype, size) \
2720 bool Value::Is##Type##Array() const { \
2721 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2722 return obj->IsJSTypedArray() && \
2723 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
2727 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
2729 #undef VALUE_IS_TYPED_ARRAY
2732 bool Value::IsDataView() const {
2733 return Utils::OpenHandle(this)->IsJSDataView();
2737 bool Value::IsSharedArrayBuffer() const {
2738 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2739 return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
2743 bool Value::IsObject() const {
2744 return Utils::OpenHandle(this)->IsJSObject();
2748 bool Value::IsNumber() const {
2749 return Utils::OpenHandle(this)->IsNumber();
2753 #define VALUE_IS_SPECIFIC_TYPE(Type, Class) \
2754 bool Value::Is##Type() const { \
2755 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2756 if (!obj->IsHeapObject()) return false; \
2757 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate(); \
2758 return obj->HasSpecificClassOf(isolate->heap()->Class##_string()); \
2761 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, Arguments)
2762 VALUE_IS_SPECIFIC_TYPE(BooleanObject, Boolean)
2763 VALUE_IS_SPECIFIC_TYPE(NumberObject, Number)
2764 VALUE_IS_SPECIFIC_TYPE(StringObject, String)
2765 VALUE_IS_SPECIFIC_TYPE(SymbolObject, Symbol)
2766 VALUE_IS_SPECIFIC_TYPE(Date, Date)
2767 VALUE_IS_SPECIFIC_TYPE(Map, Map)
2768 VALUE_IS_SPECIFIC_TYPE(Set, Set)
2769 VALUE_IS_SPECIFIC_TYPE(WeakMap, WeakMap)
2770 VALUE_IS_SPECIFIC_TYPE(WeakSet, WeakSet)
2772 #undef VALUE_IS_SPECIFIC_TYPE
2775 bool Value::IsBoolean() const {
2776 return Utils::OpenHandle(this)->IsBoolean();
2780 bool Value::IsExternal() const {
2781 return Utils::OpenHandle(this)->IsExternal();
2785 bool Value::IsInt32() const {
2786 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2787 if (obj->IsSmi()) return true;
2788 if (obj->IsNumber()) {
2789 return i::IsInt32Double(obj->Number());
2795 bool Value::IsUint32() const {
2796 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2797 if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2798 if (obj->IsNumber()) {
2799 double value = obj->Number();
2800 return !i::IsMinusZero(value) &&
2802 value <= i::kMaxUInt32 &&
2803 value == i::FastUI2D(i::FastD2UI(value));
2809 bool Value::IsNativeError() const {
2810 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2811 if (!obj->IsJSObject()) return false;
2812 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
2813 i::Isolate* isolate = js_obj->GetIsolate();
2814 i::Handle<i::Object> constructor(js_obj->map()->GetConstructor(), isolate);
2815 if (!constructor->IsJSFunction()) return false;
2816 i::Handle<i::JSFunction> function =
2817 i::Handle<i::JSFunction>::cast(constructor);
2818 if (!function->shared()->native()) return false;
2819 return function.is_identical_to(isolate->error_function()) ||
2820 function.is_identical_to(isolate->eval_error_function()) ||
2821 function.is_identical_to(isolate->range_error_function()) ||
2822 function.is_identical_to(isolate->reference_error_function()) ||
2823 function.is_identical_to(isolate->syntax_error_function()) ||
2824 function.is_identical_to(isolate->type_error_function()) ||
2825 function.is_identical_to(isolate->uri_error_function());
2829 bool Value::IsRegExp() const {
2830 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2831 return obj->IsJSRegExp();
2835 bool Value::IsGeneratorFunction() const {
2836 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2837 if (!obj->IsJSFunction()) return false;
2838 i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
2839 return func->shared()->is_generator();
2843 bool Value::IsGeneratorObject() const {
2844 return Utils::OpenHandle(this)->IsJSGeneratorObject();
2848 bool Value::IsMapIterator() const {
2849 return Utils::OpenHandle(this)->IsJSMapIterator();
2853 bool Value::IsSetIterator() const {
2854 return Utils::OpenHandle(this)->IsJSSetIterator();
2858 MaybeLocal<String> Value::ToString(Local<Context> context) const {
2859 auto obj = Utils::OpenHandle(this);
2860 if (obj->IsString()) return ToApiHandle<String>(obj);
2861 PREPARE_FOR_EXECUTION(context, "ToString", String);
2862 Local<String> result;
2863 has_pending_exception =
2864 !ToLocal<String>(i::Execution::ToString(isolate, obj), &result);
2865 RETURN_ON_FAILED_EXECUTION(String);
2866 RETURN_ESCAPED(result);
2870 Local<String> Value::ToString(Isolate* isolate) const {
2871 RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
2875 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
2876 auto obj = Utils::OpenHandle(this);
2877 if (obj->IsString()) return ToApiHandle<String>(obj);
2878 PREPARE_FOR_EXECUTION(context, "ToDetailString", String);
2879 Local<String> result;
2880 has_pending_exception =
2881 !ToLocal<String>(i::Execution::ToDetailString(isolate, obj), &result);
2882 RETURN_ON_FAILED_EXECUTION(String);
2883 RETURN_ESCAPED(result);
2887 Local<String> Value::ToDetailString(Isolate* isolate) const {
2888 RETURN_TO_LOCAL_UNCHECKED(ToDetailString(isolate->GetCurrentContext()),
2893 MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
2894 auto obj = Utils::OpenHandle(this);
2895 if (obj->IsJSObject()) return ToApiHandle<Object>(obj);
2896 PREPARE_FOR_EXECUTION(context, "ToObject", Object);
2897 Local<Object> result;
2898 has_pending_exception =
2899 !ToLocal<Object>(i::Execution::ToObject(isolate, obj), &result);
2900 RETURN_ON_FAILED_EXECUTION(Object);
2901 RETURN_ESCAPED(result);
2905 Local<v8::Object> Value::ToObject(Isolate* isolate) const {
2906 RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
2910 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
2911 auto obj = Utils::OpenHandle(this);
2912 if (obj->IsBoolean()) return ToApiHandle<Boolean>(obj);
2913 auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2914 auto val = isolate->factory()->ToBoolean(obj->BooleanValue());
2915 return ToApiHandle<Boolean>(val);
2919 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
2920 return ToBoolean(v8_isolate->GetCurrentContext()).ToLocalChecked();
2924 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
2925 auto obj = Utils::OpenHandle(this);
2926 if (obj->IsNumber()) return ToApiHandle<Number>(obj);
2927 PREPARE_FOR_EXECUTION(context, "ToNumber", Number);
2928 Local<Number> result;
2929 has_pending_exception =
2930 !ToLocal<Number>(i::Execution::ToNumber(isolate, obj), &result);
2931 RETURN_ON_FAILED_EXECUTION(Number);
2932 RETURN_ESCAPED(result);
2936 Local<Number> Value::ToNumber(Isolate* isolate) const {
2937 RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
2941 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
2942 auto obj = Utils::OpenHandle(this);
2943 if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
2944 PREPARE_FOR_EXECUTION(context, "ToInteger", Integer);
2945 Local<Integer> result;
2946 has_pending_exception =
2947 !ToLocal<Integer>(i::Execution::ToInteger(isolate, obj), &result);
2948 RETURN_ON_FAILED_EXECUTION(Integer);
2949 RETURN_ESCAPED(result);
2953 Local<Integer> Value::ToInteger(Isolate* isolate) const {
2954 RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
2958 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
2959 auto obj = Utils::OpenHandle(this);
2960 if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
2961 Local<Int32> result;
2962 PREPARE_FOR_EXECUTION(context, "ToInt32", Int32);
2963 has_pending_exception =
2964 !ToLocal<Int32>(i::Execution::ToInt32(isolate, obj), &result);
2965 RETURN_ON_FAILED_EXECUTION(Int32);
2966 RETURN_ESCAPED(result);
2970 Local<Int32> Value::ToInt32(Isolate* isolate) const {
2971 RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
2975 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
2976 auto obj = Utils::OpenHandle(this);
2977 if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
2978 Local<Uint32> result;
2979 PREPARE_FOR_EXECUTION(context, "ToUInt32", Uint32);
2980 has_pending_exception =
2981 !ToLocal<Uint32>(i::Execution::ToUint32(isolate, obj), &result);
2982 RETURN_ON_FAILED_EXECUTION(Uint32);
2983 RETURN_ESCAPED(result);
2987 Local<Uint32> Value::ToUint32(Isolate* isolate) const {
2988 RETURN_TO_LOCAL_UNCHECKED(ToUint32(isolate->GetCurrentContext()), Uint32);
2992 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
2993 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
2994 Utils::ApiCheck(isolate != NULL &&
2996 "v8::internal::Internals::CheckInitialized()",
2997 "Isolate is not initialized or V8 has died");
3001 void External::CheckCast(v8::Value* that) {
3002 Utils::ApiCheck(Utils::OpenHandle(that)->IsExternal(),
3003 "v8::External::Cast()",
3004 "Could not convert to external");
3008 void v8::Object::CheckCast(Value* that) {
3009 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3010 Utils::ApiCheck(obj->IsJSObject(),
3011 "v8::Object::Cast()",
3012 "Could not convert to object");
3016 void v8::Function::CheckCast(Value* that) {
3017 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3018 Utils::ApiCheck(obj->IsJSFunction(),
3019 "v8::Function::Cast()",
3020 "Could not convert to function");
3024 void v8::Boolean::CheckCast(v8::Value* that) {
3025 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3026 Utils::ApiCheck(obj->IsBoolean(),
3027 "v8::Boolean::Cast()",
3028 "Could not convert to boolean");
3032 void v8::Name::CheckCast(v8::Value* that) {
3033 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3034 Utils::ApiCheck(obj->IsName(),
3036 "Could not convert to name");
3040 void v8::String::CheckCast(v8::Value* that) {
3041 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3042 Utils::ApiCheck(obj->IsString(),
3043 "v8::String::Cast()",
3044 "Could not convert to string");
3048 void v8::Symbol::CheckCast(v8::Value* that) {
3049 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3050 Utils::ApiCheck(obj->IsSymbol(),
3051 "v8::Symbol::Cast()",
3052 "Could not convert to symbol");
3056 void v8::Number::CheckCast(v8::Value* that) {
3057 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3058 Utils::ApiCheck(obj->IsNumber(),
3059 "v8::Number::Cast()",
3060 "Could not convert to number");
3064 void v8::Integer::CheckCast(v8::Value* that) {
3065 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3066 Utils::ApiCheck(obj->IsNumber(),
3067 "v8::Integer::Cast()",
3068 "Could not convert to number");
3072 void v8::Int32::CheckCast(v8::Value* that) {
3073 Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast()",
3074 "Could not convert to 32-bit signed integer");
3078 void v8::Uint32::CheckCast(v8::Value* that) {
3079 Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast()",
3080 "Could not convert to 32-bit unsigned integer");
3084 void v8::Array::CheckCast(Value* that) {
3085 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3086 Utils::ApiCheck(obj->IsJSArray(),
3087 "v8::Array::Cast()",
3088 "Could not convert to array");
3092 void v8::Map::CheckCast(Value* that) {
3093 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3094 Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast()",
3095 "Could not convert to Map");
3099 void v8::Set::CheckCast(Value* that) {
3100 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3101 Utils::ApiCheck(obj->IsJSSet(), "v8::Set::Cast()",
3102 "Could not convert to Set");
3106 void v8::Promise::CheckCast(Value* that) {
3107 Utils::ApiCheck(that->IsPromise(),
3108 "v8::Promise::Cast()",
3109 "Could not convert to promise");
3113 void v8::Promise::Resolver::CheckCast(Value* that) {
3114 Utils::ApiCheck(that->IsPromise(),
3115 "v8::Promise::Resolver::Cast()",
3116 "Could not convert to promise resolver");
3120 void v8::ArrayBuffer::CheckCast(Value* that) {
3121 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3123 obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
3124 "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
3128 void v8::ArrayBufferView::CheckCast(Value* that) {
3129 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3130 Utils::ApiCheck(obj->IsJSArrayBufferView(),
3131 "v8::ArrayBufferView::Cast()",
3132 "Could not convert to ArrayBufferView");
3136 void v8::TypedArray::CheckCast(Value* that) {
3137 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3138 Utils::ApiCheck(obj->IsJSTypedArray(),
3139 "v8::TypedArray::Cast()",
3140 "Could not convert to TypedArray");
3144 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype, size) \
3145 void v8::Type##Array::CheckCast(Value* that) { \
3146 i::Handle<i::Object> obj = Utils::OpenHandle(that); \
3148 obj->IsJSTypedArray() && \
3149 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
3150 "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
3154 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
3156 #undef CHECK_TYPED_ARRAY_CAST
3159 void v8::DataView::CheckCast(Value* that) {
3160 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3161 Utils::ApiCheck(obj->IsJSDataView(),
3162 "v8::DataView::Cast()",
3163 "Could not convert to DataView");
3167 void v8::SharedArrayBuffer::CheckCast(Value* that) {
3168 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3170 obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
3171 "v8::SharedArrayBuffer::Cast()",
3172 "Could not convert to SharedArrayBuffer");
3176 void v8::Date::CheckCast(v8::Value* that) {
3177 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3178 i::Isolate* isolate = NULL;
3179 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3180 Utils::ApiCheck(isolate != NULL &&
3181 obj->HasSpecificClassOf(isolate->heap()->Date_string()),
3183 "Could not convert to date");
3187 void v8::StringObject::CheckCast(v8::Value* that) {
3188 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3189 i::Isolate* isolate = NULL;
3190 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3191 Utils::ApiCheck(isolate != NULL &&
3192 obj->HasSpecificClassOf(isolate->heap()->String_string()),
3193 "v8::StringObject::Cast()",
3194 "Could not convert to StringObject");
3198 void v8::SymbolObject::CheckCast(v8::Value* that) {
3199 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3200 i::Isolate* isolate = NULL;
3201 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3202 Utils::ApiCheck(isolate != NULL &&
3203 obj->HasSpecificClassOf(isolate->heap()->Symbol_string()),
3204 "v8::SymbolObject::Cast()",
3205 "Could not convert to SymbolObject");
3209 void v8::NumberObject::CheckCast(v8::Value* that) {
3210 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3211 i::Isolate* isolate = NULL;
3212 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3213 Utils::ApiCheck(isolate != NULL &&
3214 obj->HasSpecificClassOf(isolate->heap()->Number_string()),
3215 "v8::NumberObject::Cast()",
3216 "Could not convert to NumberObject");
3220 void v8::BooleanObject::CheckCast(v8::Value* that) {
3221 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3222 i::Isolate* isolate = NULL;
3223 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3224 Utils::ApiCheck(isolate != NULL &&
3225 obj->HasSpecificClassOf(isolate->heap()->Boolean_string()),
3226 "v8::BooleanObject::Cast()",
3227 "Could not convert to BooleanObject");
3231 void v8::RegExp::CheckCast(v8::Value* that) {
3232 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3233 Utils::ApiCheck(obj->IsJSRegExp(),
3234 "v8::RegExp::Cast()",
3235 "Could not convert to regular expression");
3239 Maybe<bool> Value::BooleanValue(Local<Context> context) const {
3240 return Just(Utils::OpenHandle(this)->BooleanValue());
3244 bool Value::BooleanValue() const {
3245 return Utils::OpenHandle(this)->BooleanValue();
3249 Maybe<double> Value::NumberValue(Local<Context> context) const {
3250 auto obj = Utils::OpenHandle(this);
3251 if (obj->IsNumber()) return Just(obj->Number());
3252 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "NumberValue", double);
3253 i::Handle<i::Object> num;
3254 has_pending_exception = !i::Execution::ToNumber(isolate, obj).ToHandle(&num);
3255 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
3256 return Just(num->Number());
3260 double Value::NumberValue() const {
3261 auto obj = Utils::OpenHandle(this);
3262 if (obj->IsNumber()) return obj->Number();
3263 return NumberValue(ContextFromHeapObject(obj))
3264 .FromMaybe(std::numeric_limits<double>::quiet_NaN());
3268 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
3269 auto obj = Utils::OpenHandle(this);
3270 i::Handle<i::Object> num;
3271 if (obj->IsNumber()) {
3274 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "IntegerValue", int64_t);
3275 has_pending_exception =
3276 !i::Execution::ToInteger(isolate, obj).ToHandle(&num);
3277 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
3279 return Just(num->IsSmi() ? static_cast<int64_t>(i::Smi::cast(*num)->value())
3280 : static_cast<int64_t>(num->Number()));
3284 int64_t Value::IntegerValue() const {
3285 auto obj = Utils::OpenHandle(this);
3286 if (obj->IsNumber()) {
3288 return i::Smi::cast(*obj)->value();
3290 return static_cast<int64_t>(obj->Number());
3293 return IntegerValue(ContextFromHeapObject(obj)).FromMaybe(0);
3297 Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
3298 auto obj = Utils::OpenHandle(this);
3299 if (obj->IsNumber()) return Just(NumberToInt32(*obj));
3300 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Int32Value", int32_t);
3301 i::Handle<i::Object> num;
3302 has_pending_exception = !i::Execution::ToInt32(isolate, obj).ToHandle(&num);
3303 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
3304 return Just(num->IsSmi() ? i::Smi::cast(*num)->value()
3305 : static_cast<int32_t>(num->Number()));
3309 int32_t Value::Int32Value() const {
3310 auto obj = Utils::OpenHandle(this);
3311 if (obj->IsNumber()) return NumberToInt32(*obj);
3312 return Int32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3316 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
3317 auto obj = Utils::OpenHandle(this);
3318 if (obj->IsNumber()) return Just(NumberToUint32(*obj));
3319 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Uint32Value", uint32_t);
3320 i::Handle<i::Object> num;
3321 has_pending_exception = !i::Execution::ToUint32(isolate, obj).ToHandle(&num);
3322 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
3323 return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::cast(*num)->value())
3324 : static_cast<uint32_t>(num->Number()));
3328 uint32_t Value::Uint32Value() const {
3329 auto obj = Utils::OpenHandle(this);
3330 if (obj->IsNumber()) return NumberToUint32(*obj);
3331 return Uint32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3335 MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const {
3336 auto self = Utils::OpenHandle(this);
3337 if (self->IsSmi()) {
3338 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3339 return Local<Uint32>();
3341 PREPARE_FOR_EXECUTION(context, "ToArrayIndex", Uint32);
3342 i::Handle<i::Object> string_obj;
3343 has_pending_exception =
3344 !i::Execution::ToString(isolate, self).ToHandle(&string_obj);
3345 RETURN_ON_FAILED_EXECUTION(Uint32);
3346 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
3348 if (str->AsArrayIndex(&index)) {
3349 i::Handle<i::Object> value;
3350 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
3351 value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
3353 value = isolate->factory()->NewNumber(index);
3355 RETURN_ESCAPED(Utils::Uint32ToLocal(value));
3357 return Local<Uint32>();
3361 Local<Uint32> Value::ToArrayIndex() const {
3362 auto self = Utils::OpenHandle(this);
3363 if (self->IsSmi()) {
3364 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3365 return Local<Uint32>();
3367 auto context = ContextFromHeapObject(self);
3368 RETURN_TO_LOCAL_UNCHECKED(ToArrayIndex(context), Uint32);
3372 Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const {
3373 auto self = Utils::OpenHandle(this);
3374 auto other = Utils::OpenHandle(*that);
3375 if (self->IsSmi() && other->IsSmi()) {
3376 return Just(self->Number() == other->Number());
3378 if (self->IsJSObject() && other->IsJSObject()) {
3379 return Just(*self == *other);
3381 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Value::Equals()", bool);
3382 i::Handle<i::Object> args[] = { other };
3383 i::Handle<i::Object> result;
3384 has_pending_exception =
3385 !CallV8HeapFunction(isolate, "EQUALS", self, arraysize(args), args)
3387 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3388 return Just(*result == i::Smi::FromInt(i::EQUAL));
3392 bool Value::Equals(Local<Value> that) const {
3393 auto self = Utils::OpenHandle(this);
3394 auto other = Utils::OpenHandle(*that);
3395 if (self->IsSmi() && other->IsSmi()) {
3396 return self->Number() == other->Number();
3398 if (self->IsJSObject() && other->IsJSObject()) {
3399 return *self == *other;
3401 auto heap_object = self->IsSmi() ? other : self;
3402 auto context = ContextFromHeapObject(heap_object);
3403 return Equals(context, that).FromMaybe(false);
3407 bool Value::StrictEquals(Local<Value> that) const {
3408 auto self = Utils::OpenHandle(this);
3409 auto other = Utils::OpenHandle(*that);
3410 return self->StrictEquals(*other);
3414 bool Value::SameValue(Local<Value> that) const {
3415 auto self = Utils::OpenHandle(this);
3416 auto other = Utils::OpenHandle(*that);
3417 return self->SameValue(*other);
3421 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
3422 v8::Local<Value> key, v8::Local<Value> value) {
3423 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3424 auto self = Utils::OpenHandle(this);
3425 auto key_obj = Utils::OpenHandle(*key);
3426 auto value_obj = Utils::OpenHandle(*value);
3427 has_pending_exception =
3428 i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
3429 i::SLOPPY).is_null();
3430 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3435 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
3436 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3437 return Set(context, key, value).FromMaybe(false);
3441 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
3442 v8::Local<Value> value) {
3443 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3444 auto self = Utils::OpenHandle(this);
3445 auto value_obj = Utils::OpenHandle(*value);
3446 has_pending_exception = i::Object::SetElement(isolate, self, index, value_obj,
3447 i::SLOPPY).is_null();
3448 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3453 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
3454 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3455 return Set(context, index, value).FromMaybe(false);
3459 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3460 v8::Local<Name> key,
3461 v8::Local<Value> value) {
3462 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3464 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3465 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
3466 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3468 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
3469 isolate, self, key_obj, i::LookupIterator::OWN);
3470 Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3471 has_pending_exception = result.IsNothing();
3472 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3477 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3479 v8::Local<Value> value) {
3480 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3482 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3483 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3485 i::LookupIterator it(isolate, self, index, 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);
3493 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
3494 v8::Local<Name> key,
3495 v8::Local<Value> value,
3496 v8::PropertyAttribute attributes) {
3497 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DefineOwnProperty()",
3499 auto self = Utils::OpenHandle(this);
3500 auto key_obj = Utils::OpenHandle(*key);
3501 auto value_obj = Utils::OpenHandle(*value);
3503 if (self->IsAccessCheckNeeded() && !isolate->MayAccess(self)) {
3504 isolate->ReportFailedAccessCheck(self);
3505 return Nothing<bool>();
3508 i::Handle<i::FixedArray> desc = isolate->factory()->NewFixedArray(3);
3509 desc->set(0, isolate->heap()->ToBoolean(!(attributes & v8::ReadOnly)));
3510 desc->set(1, isolate->heap()->ToBoolean(!(attributes & v8::DontEnum)));
3511 desc->set(2, isolate->heap()->ToBoolean(!(attributes & v8::DontDelete)));
3512 i::Handle<i::JSArray> desc_array =
3513 isolate->factory()->NewJSArrayWithElements(desc, i::FAST_ELEMENTS, 3);
3514 i::Handle<i::Object> args[] = {self, key_obj, value_obj, desc_array};
3515 i::Handle<i::Object> result;
3516 has_pending_exception =
3517 !CallV8HeapFunction(isolate, "$objectDefineOwnProperty",
3518 isolate->factory()->undefined_value(),
3519 arraysize(args), args).ToHandle(&result);
3520 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3521 return Just(result->BooleanValue());
3526 static i::MaybeHandle<i::Object> DefineObjectProperty(
3527 i::Handle<i::JSObject> js_object, i::Handle<i::Object> key,
3528 i::Handle<i::Object> value, PropertyAttributes attrs) {
3529 i::Isolate* isolate = js_object->GetIsolate();
3530 // Check if the given key is an array index.
3532 if (key->ToArrayIndex(&index)) {
3533 return i::JSObject::SetOwnElementIgnoreAttributes(js_object, index, value,
3537 i::Handle<i::Name> name;
3538 ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
3539 i::Runtime::ToName(isolate, key),
3540 i::MaybeHandle<i::Object>());
3542 return i::JSObject::DefinePropertyOrElementIgnoreAttributes(js_object, name,
3547 Maybe<bool> v8::Object::ForceSet(v8::Local<v8::Context> context,
3548 v8::Local<Value> key, v8::Local<Value> value,
3549 v8::PropertyAttribute attribs) {
3550 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3551 auto self = Utils::OpenHandle(this);
3552 auto key_obj = Utils::OpenHandle(*key);
3553 auto value_obj = Utils::OpenHandle(*value);
3554 has_pending_exception =
3555 DefineObjectProperty(self, key_obj, value_obj,
3556 static_cast<PropertyAttributes>(attribs)).is_null();
3557 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3562 bool v8::Object::ForceSet(v8::Local<Value> key, v8::Local<Value> value,
3563 v8::PropertyAttribute attribs) {
3564 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3565 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(),
3566 "v8::Object::ForceSet", false, i::HandleScope,
3568 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3569 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
3570 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3571 has_pending_exception =
3572 DefineObjectProperty(self, key_obj, value_obj,
3573 static_cast<PropertyAttributes>(attribs)).is_null();
3574 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, false);
3579 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
3581 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3582 auto self = Utils::OpenHandle(this);
3583 auto key_obj = Utils::OpenHandle(*key);
3584 i::Handle<i::Object> result;
3585 has_pending_exception =
3586 !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
3587 RETURN_ON_FAILED_EXECUTION(Value);
3588 RETURN_ESCAPED(Utils::ToLocal(result));
3592 Local<Value> v8::Object::Get(v8::Local<Value> key) {
3593 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3594 RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
3598 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
3599 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3600 auto self = Utils::OpenHandle(this);
3601 i::Handle<i::Object> result;
3602 has_pending_exception =
3603 !i::Object::GetElement(isolate, self, index).ToHandle(&result);
3604 RETURN_ON_FAILED_EXECUTION(Value);
3605 RETURN_ESCAPED(Utils::ToLocal(result));
3609 Local<Value> v8::Object::Get(uint32_t index) {
3610 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3611 RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
3615 Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes(
3616 Local<Context> context, Local<Value> key) {
3617 PREPARE_FOR_EXECUTION_PRIMITIVE(
3618 context, "v8::Object::GetPropertyAttributes()", PropertyAttribute);
3619 auto self = Utils::OpenHandle(this);
3620 auto key_obj = Utils::OpenHandle(*key);
3621 if (!key_obj->IsName()) {
3622 has_pending_exception = !i::Execution::ToString(
3623 isolate, key_obj).ToHandle(&key_obj);
3624 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3626 auto key_name = i::Handle<i::Name>::cast(key_obj);
3627 auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
3628 has_pending_exception = result.IsNothing();
3629 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3630 if (result.FromJust() == ABSENT) {
3631 return Just(static_cast<PropertyAttribute>(NONE));
3633 return Just(static_cast<PropertyAttribute>(result.FromJust()));
3637 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Local<Value> key) {
3638 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3639 return GetPropertyAttributes(context, key)
3640 .FromMaybe(static_cast<PropertyAttribute>(NONE));
3644 MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context,
3645 Local<String> key) {
3646 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyDescriptor()",
3648 auto obj = Utils::OpenHandle(this);
3649 auto key_name = Utils::OpenHandle(*key);
3650 i::Handle<i::Object> args[] = { obj, key_name };
3651 i::Handle<i::Object> result;
3652 has_pending_exception =
3653 !CallV8HeapFunction(isolate, "$objectGetOwnPropertyDescriptor",
3654 isolate->factory()->undefined_value(),
3655 arraysize(args), args).ToHandle(&result);
3656 RETURN_ON_FAILED_EXECUTION(Value);
3657 RETURN_ESCAPED(Utils::ToLocal(result));
3661 Local<Value> v8::Object::GetOwnPropertyDescriptor(Local<String> key) {
3662 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3663 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyDescriptor(context, key), Value);
3667 Local<Value> v8::Object::GetPrototype() {
3668 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3669 auto self = Utils::OpenHandle(this);
3670 i::PrototypeIterator iter(isolate, self);
3671 return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
3675 Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
3676 Local<Value> value) {
3677 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetPrototype()", bool);
3678 auto self = Utils::OpenHandle(this);
3679 auto value_obj = Utils::OpenHandle(*value);
3680 // We do not allow exceptions thrown while setting the prototype
3681 // to propagate outside.
3682 TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
3683 auto result = i::JSObject::SetPrototype(self, value_obj, false);
3684 has_pending_exception = result.is_null();
3685 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3690 bool v8::Object::SetPrototype(Local<Value> value) {
3691 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3692 return SetPrototype(context, value).FromMaybe(false);
3696 Local<Object> v8::Object::FindInstanceInPrototypeChain(
3697 v8::Local<FunctionTemplate> tmpl) {
3698 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3699 i::PrototypeIterator iter(isolate, *Utils::OpenHandle(this),
3700 i::PrototypeIterator::START_AT_RECEIVER);
3701 auto tmpl_info = *Utils::OpenHandle(*tmpl);
3702 while (!tmpl_info->IsTemplateFor(iter.GetCurrent())) {
3704 if (iter.IsAtEnd()) {
3705 return Local<Object>();
3708 return Utils::ToLocal(
3709 i::handle(i::JSObject::cast(iter.GetCurrent()), isolate));
3713 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
3714 PREPARE_FOR_EXECUTION(context, "v8::Object::GetPropertyNames()", Array);
3715 auto self = Utils::OpenHandle(this);
3716 i::Handle<i::FixedArray> value;
3717 has_pending_exception = !i::JSReceiver::GetKeys(
3718 self, i::JSReceiver::INCLUDE_PROTOS).ToHandle(&value);
3719 RETURN_ON_FAILED_EXECUTION(Array);
3720 // Because we use caching to speed up enumeration it is important
3721 // to never change the result of the basic enumeration function so
3722 // we clone the result.
3723 auto elms = isolate->factory()->CopyFixedArray(value);
3724 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3725 RETURN_ESCAPED(Utils::ToLocal(result));
3729 Local<Array> v8::Object::GetPropertyNames() {
3730 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3731 RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array);
3735 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
3736 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyNames()", Array);
3737 auto self = Utils::OpenHandle(this);
3738 i::Handle<i::FixedArray> value;
3739 has_pending_exception = !i::JSReceiver::GetKeys(
3740 self, i::JSReceiver::OWN_ONLY).ToHandle(&value);
3741 RETURN_ON_FAILED_EXECUTION(Array);
3742 // Because we use caching to speed up enumeration it is important
3743 // to never change the result of the basic enumeration function so
3744 // we clone the result.
3745 auto elms = isolate->factory()->CopyFixedArray(value);
3746 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3747 RETURN_ESCAPED(Utils::ToLocal(result));
3751 Local<Array> v8::Object::GetOwnPropertyNames() {
3752 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3753 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array);
3757 MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) {
3758 auto self = Utils::OpenHandle(this);
3759 auto isolate = self->GetIsolate();
3760 auto v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
3761 i::Handle<i::Object> name(self->class_name(), isolate);
3762 i::Handle<i::Object> tag;
3764 // Native implementation of Object.prototype.toString (v8natives.js):
3765 // var c = %_ClassOf(this);
3766 // if (c === 'Arguments') c = 'Object';
3767 // return "[object " + c + "]";
3769 if (!name->IsString()) {
3770 return v8::String::NewFromUtf8(v8_isolate, "[object ]",
3771 NewStringType::kNormal);
3773 auto class_name = i::Handle<i::String>::cast(name);
3774 if (i::String::Equals(class_name, isolate->factory()->Arguments_string())) {
3775 return v8::String::NewFromUtf8(v8_isolate, "[object Object]",
3776 NewStringType::kNormal);
3778 if (internal::FLAG_harmony_tostring) {
3779 PREPARE_FOR_EXECUTION(context, "v8::Object::ObjectProtoToString()", String);
3780 auto toStringTag = isolate->factory()->to_string_tag_symbol();
3781 has_pending_exception = !i::Runtime::GetObjectProperty(
3782 isolate, self, toStringTag).ToHandle(&tag);
3783 RETURN_ON_FAILED_EXECUTION(String);
3784 if (tag->IsString()) {
3785 class_name = Utils::OpenHandle(*handle_scope.Escape(
3786 Utils::ToLocal(i::Handle<i::String>::cast(tag))));
3789 const char* prefix = "[object ";
3790 Local<String> str = Utils::ToLocal(class_name);
3791 const char* postfix = "]";
3793 int prefix_len = i::StrLength(prefix);
3794 int str_len = str->Utf8Length();
3795 int postfix_len = i::StrLength(postfix);
3797 int buf_len = prefix_len + str_len + postfix_len;
3798 i::ScopedVector<char> buf(buf_len);
3801 char* ptr = buf.start();
3802 i::MemCopy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3805 // Write real content.
3806 str->WriteUtf8(ptr, str_len);
3810 i::MemCopy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3812 // Copy the buffer into a heap-allocated string and return it.
3813 return v8::String::NewFromUtf8(v8_isolate, buf.start(),
3814 NewStringType::kNormal, buf_len);
3818 Local<String> v8::Object::ObjectProtoToString() {
3819 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3820 RETURN_TO_LOCAL_UNCHECKED(ObjectProtoToString(context), String);
3824 Local<String> v8::Object::GetConstructorName() {
3825 auto self = Utils::OpenHandle(this);
3826 i::Handle<i::String> name(self->constructor_name());
3827 return Utils::ToLocal(name);
3831 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
3832 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Delete()", bool);
3833 auto self = Utils::OpenHandle(this);
3834 auto key_obj = Utils::OpenHandle(*key);
3835 i::Handle<i::Object> obj;
3836 has_pending_exception =
3837 !i::Runtime::DeleteObjectProperty(isolate, self, key_obj, i::SLOPPY)
3839 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3840 return Just(obj->IsTrue());
3844 bool v8::Object::Delete(v8::Local<Value> key) {
3845 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3846 return Delete(context, key).FromMaybe(false);
3850 Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) {
3851 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3852 auto self = Utils::OpenHandle(this);
3853 auto key_obj = Utils::OpenHandle(*key);
3854 Maybe<bool> maybe = Nothing<bool>();
3855 // Check if the given key is an array index.
3857 if (key_obj->ToArrayIndex(&index)) {
3858 maybe = i::JSReceiver::HasElement(self, index);
3860 // Convert the key to a name - possibly by calling back into JavaScript.
3861 i::Handle<i::Name> name;
3862 if (i::Runtime::ToName(isolate, key_obj).ToHandle(&name)) {
3863 maybe = i::JSReceiver::HasProperty(self, name);
3866 has_pending_exception = maybe.IsNothing();
3867 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3872 bool v8::Object::Has(v8::Local<Value> key) {
3873 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3874 return Has(context, key).FromMaybe(false);
3878 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
3879 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DeleteProperty()",
3881 auto self = Utils::OpenHandle(this);
3882 i::Handle<i::Object> obj;
3883 has_pending_exception =
3884 !i::JSReceiver::DeleteElement(self, index).ToHandle(&obj);
3885 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3886 return Just(obj->IsTrue());
3890 bool v8::Object::Delete(uint32_t index) {
3891 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3892 return Delete(context, index).FromMaybe(false);
3896 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
3897 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3898 auto self = Utils::OpenHandle(this);
3899 auto maybe = i::JSReceiver::HasElement(self, index);
3900 has_pending_exception = maybe.IsNothing();
3901 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3906 bool v8::Object::Has(uint32_t index) {
3907 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3908 return Has(context, index).FromMaybe(false);
3912 template <typename Getter, typename Setter, typename Data>
3913 static Maybe<bool> ObjectSetAccessor(Local<Context> context, Object* obj,
3914 Local<Name> name, Getter getter,
3915 Setter setter, Data data,
3916 AccessControl settings,
3917 PropertyAttribute attributes) {
3918 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetAccessor()", bool);
3919 v8::Local<AccessorSignature> signature;
3920 auto info = MakeAccessorInfo(name, getter, setter, data, settings, attributes,
3922 if (info.is_null()) return Nothing<bool>();
3923 bool fast = Utils::OpenHandle(obj)->HasFastProperties();
3924 i::Handle<i::Object> result;
3925 has_pending_exception =
3926 !i::JSObject::SetAccessor(Utils::OpenHandle(obj), info).ToHandle(&result);
3927 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3928 if (result->IsUndefined()) return Nothing<bool>();
3930 i::JSObject::MigrateSlowToFast(Utils::OpenHandle(obj), 0, "APISetAccessor");
3936 Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name,
3937 AccessorNameGetterCallback getter,
3938 AccessorNameSetterCallback setter,
3939 MaybeLocal<Value> data, AccessControl settings,
3940 PropertyAttribute attribute) {
3941 return ObjectSetAccessor(context, this, name, getter, setter,
3942 data.FromMaybe(Local<Value>()), settings, attribute);
3946 bool Object::SetAccessor(Local<String> name, AccessorGetterCallback getter,
3947 AccessorSetterCallback setter, v8::Local<Value> data,
3948 AccessControl settings, PropertyAttribute attributes) {
3949 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3950 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3951 attributes).FromMaybe(false);
3955 bool Object::SetAccessor(Local<Name> name, AccessorNameGetterCallback getter,
3956 AccessorNameSetterCallback setter,
3957 v8::Local<Value> data, AccessControl settings,
3958 PropertyAttribute attributes) {
3959 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3960 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3961 attributes).FromMaybe(false);
3965 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
3966 Local<Function> setter,
3967 PropertyAttribute attribute,
3968 AccessControl settings) {
3969 // TODO(verwaest): Remove |settings|.
3970 DCHECK_EQ(v8::DEFAULT, settings);
3971 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3973 i::HandleScope scope(isolate);
3974 i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
3975 i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
3976 if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
3977 i::JSObject::DefineAccessor(v8::Utils::OpenHandle(this),
3978 v8::Utils::OpenHandle(*name),
3981 static_cast<PropertyAttributes>(attribute));
3985 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
3987 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasOwnProperty()",
3989 auto self = Utils::OpenHandle(this);
3990 auto key_val = Utils::OpenHandle(*key);
3991 auto result = i::JSReceiver::HasOwnProperty(self, key_val);
3992 has_pending_exception = result.IsNothing();
3993 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3998 bool v8::Object::HasOwnProperty(Local<String> key) {
3999 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4000 return HasOwnProperty(context, key).FromMaybe(false);
4004 Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context,
4006 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasRealNamedProperty()",
4008 auto self = Utils::OpenHandle(this);
4009 auto key_val = Utils::OpenHandle(*key);
4010 auto result = i::JSObject::HasRealNamedProperty(self, key_val);
4011 has_pending_exception = result.IsNothing();
4012 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4017 bool v8::Object::HasRealNamedProperty(Local<String> key) {
4018 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4019 return HasRealNamedProperty(context, key).FromMaybe(false);
4023 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
4025 PREPARE_FOR_EXECUTION_PRIMITIVE(context,
4026 "v8::Object::HasRealIndexedProperty()", bool);
4027 auto self = Utils::OpenHandle(this);
4028 auto result = i::JSObject::HasRealElementProperty(self, index);
4029 has_pending_exception = result.IsNothing();
4030 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4035 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
4036 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4037 return HasRealIndexedProperty(context, index).FromMaybe(false);
4041 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
4043 PREPARE_FOR_EXECUTION_PRIMITIVE(
4044 context, "v8::Object::HasRealNamedCallbackProperty()", bool);
4045 auto self = Utils::OpenHandle(this);
4046 auto key_val = Utils::OpenHandle(*key);
4047 auto result = i::JSObject::HasRealNamedCallbackProperty(self, key_val);
4048 has_pending_exception = result.IsNothing();
4049 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4054 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) {
4055 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4056 return HasRealNamedCallbackProperty(context, key).FromMaybe(false);
4060 bool v8::Object::HasNamedLookupInterceptor() {
4061 auto self = Utils::OpenHandle(this);
4062 return self->HasNamedInterceptor();
4066 bool v8::Object::HasIndexedLookupInterceptor() {
4067 auto self = Utils::OpenHandle(this);
4068 return self->HasIndexedInterceptor();
4072 MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4073 Local<Context> context, Local<Name> key) {
4074 PREPARE_FOR_EXECUTION(
4075 context, "v8::Object::GetRealNamedPropertyInPrototypeChain()", Value);
4076 auto self = Utils::OpenHandle(this);
4077 auto key_obj = Utils::OpenHandle(*key);
4078 i::PrototypeIterator iter(isolate, self);
4079 if (iter.IsAtEnd()) return MaybeLocal<Value>();
4080 auto proto = i::PrototypeIterator::GetCurrent(iter);
4081 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4082 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4083 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4084 Local<Value> result;
4085 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4086 RETURN_ON_FAILED_EXECUTION(Value);
4087 if (!it.IsFound()) return MaybeLocal<Value>();
4088 RETURN_ESCAPED(result);
4092 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4093 Local<String> key) {
4094 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4095 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedPropertyInPrototypeChain(context, key),
4100 Maybe<PropertyAttribute>
4101 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(
4102 Local<Context> context, Local<Name> key) {
4103 PREPARE_FOR_EXECUTION_PRIMITIVE(
4104 context, "v8::Object::GetRealNamedPropertyAttributesInPrototypeChain()",
4106 auto self = Utils::OpenHandle(this);
4107 auto key_obj = Utils::OpenHandle(*key);
4108 i::PrototypeIterator iter(isolate, self);
4109 if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
4110 auto proto = i::PrototypeIterator::GetCurrent(iter);
4111 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4112 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4113 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4114 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4115 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4116 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4117 if (result.FromJust() == ABSENT) {
4118 return Just(static_cast<PropertyAttribute>(NONE));
4120 return Just<PropertyAttribute>(
4121 static_cast<PropertyAttribute>(result.FromJust()));
4125 Maybe<PropertyAttribute>
4126 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(Local<String> key) {
4127 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4128 return GetRealNamedPropertyAttributesInPrototypeChain(context, key);
4132 MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context,
4134 PREPARE_FOR_EXECUTION(context, "v8::Object::GetRealNamedProperty()", Value);
4135 auto self = Utils::OpenHandle(this);
4136 auto key_obj = Utils::OpenHandle(*key);
4137 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4138 isolate, self, key_obj,
4139 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4140 Local<Value> result;
4141 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4142 RETURN_ON_FAILED_EXECUTION(Value);
4143 if (!it.IsFound()) return MaybeLocal<Value>();
4144 RETURN_ESCAPED(result);
4148 Local<Value> v8::Object::GetRealNamedProperty(Local<String> key) {
4149 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4150 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedProperty(context, key), Value);
4154 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4155 Local<Context> context, Local<Name> key) {
4156 PREPARE_FOR_EXECUTION_PRIMITIVE(
4157 context, "v8::Object::GetRealNamedPropertyAttributes()",
4159 auto self = Utils::OpenHandle(this);
4160 auto key_obj = Utils::OpenHandle(*key);
4161 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4162 isolate, self, key_obj,
4163 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4164 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4165 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4166 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4167 if (result.FromJust() == ABSENT) {
4168 return Just(static_cast<PropertyAttribute>(NONE));
4170 return Just<PropertyAttribute>(
4171 static_cast<PropertyAttribute>(result.FromJust()));
4175 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4176 Local<String> key) {
4177 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4178 return GetRealNamedPropertyAttributes(context, key);
4182 Local<v8::Object> v8::Object::Clone() {
4183 auto self = Utils::OpenHandle(this);
4184 auto isolate = self->GetIsolate();
4186 auto result = isolate->factory()->CopyJSObject(self);
4187 CHECK(!result.is_null());
4188 return Utils::ToLocal(result);
4192 Local<v8::Context> v8::Object::CreationContext() {
4193 auto self = Utils::OpenHandle(this);
4194 auto context = handle(self->GetCreationContext());
4195 return Utils::ToLocal(context);
4199 int v8::Object::GetIdentityHash() {
4200 auto isolate = Utils::OpenHandle(this)->GetIsolate();
4201 i::HandleScope scope(isolate);
4202 auto self = Utils::OpenHandle(this);
4203 return i::JSReceiver::GetOrCreateIdentityHash(self)->value();
4207 bool v8::Object::SetHiddenValue(v8::Local<v8::String> key,
4208 v8::Local<v8::Value> value) {
4209 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4210 if (value.IsEmpty()) return DeleteHiddenValue(key);
4212 i::HandleScope scope(isolate);
4213 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4214 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4215 i::Handle<i::String> key_string =
4216 isolate->factory()->InternalizeString(key_obj);
4217 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4218 i::Handle<i::Object> result =
4219 i::JSObject::SetHiddenProperty(self, key_string, value_obj);
4220 return *result == *self;
4224 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Local<v8::String> key) {
4225 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4227 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4228 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4229 i::Handle<i::String> key_string =
4230 isolate->factory()->InternalizeString(key_obj);
4231 i::Handle<i::Object> result(self->GetHiddenProperty(key_string), isolate);
4232 if (result->IsTheHole()) return v8::Local<v8::Value>();
4233 return Utils::ToLocal(result);
4237 bool v8::Object::DeleteHiddenValue(v8::Local<v8::String> key) {
4238 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4240 i::HandleScope scope(isolate);
4241 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4242 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4243 i::Handle<i::String> key_string =
4244 isolate->factory()->InternalizeString(key_obj);
4245 i::JSObject::DeleteHiddenProperty(self, key_string);
4250 bool v8::Object::IsCallable() {
4251 auto self = Utils::OpenHandle(this);
4252 return self->IsCallable();
4256 MaybeLocal<Value> Object::CallAsFunction(Local<Context> context,
4257 Local<Value> recv, int argc,
4258 Local<Value> argv[]) {
4259 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Object::CallAsFunction()",
4261 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4262 auto self = Utils::OpenHandle(this);
4263 auto recv_obj = Utils::OpenHandle(*recv);
4264 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4265 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4266 i::Handle<i::JSFunction> fun;
4267 if (self->IsJSFunction()) {
4268 fun = i::Handle<i::JSFunction>::cast(self);
4270 i::Handle<i::Object> delegate;
4271 has_pending_exception = !i::Execution::TryGetFunctionDelegate(isolate, self)
4272 .ToHandle(&delegate);
4273 RETURN_ON_FAILED_EXECUTION(Value);
4274 fun = i::Handle<i::JSFunction>::cast(delegate);
4277 Local<Value> result;
4278 has_pending_exception =
4280 i::Execution::Call(isolate, fun, recv_obj, argc, args, true),
4282 RETURN_ON_FAILED_EXECUTION(Value);
4283 RETURN_ESCAPED(result);
4287 Local<v8::Value> Object::CallAsFunction(v8::Local<v8::Value> recv, int argc,
4288 v8::Local<v8::Value> argv[]) {
4289 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4290 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4291 RETURN_TO_LOCAL_UNCHECKED(CallAsFunction(context, recv, argc, argv_cast),
4296 MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc,
4297 Local<Value> argv[]) {
4298 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context,
4299 "v8::Object::CallAsConstructor()", Value);
4300 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4301 auto self = Utils::OpenHandle(this);
4302 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4303 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4304 if (self->IsJSFunction()) {
4305 auto fun = i::Handle<i::JSFunction>::cast(self);
4306 Local<Value> result;
4307 has_pending_exception =
4308 !ToLocal<Value>(i::Execution::New(fun, argc, args), &result);
4309 RETURN_ON_FAILED_EXECUTION(Value);
4310 RETURN_ESCAPED(result);
4312 i::Handle<i::Object> delegate;
4313 has_pending_exception = !i::Execution::TryGetConstructorDelegate(
4314 isolate, self).ToHandle(&delegate);
4315 RETURN_ON_FAILED_EXECUTION(Value);
4316 if (!delegate->IsUndefined()) {
4317 auto fun = i::Handle<i::JSFunction>::cast(delegate);
4318 Local<Value> result;
4319 has_pending_exception =
4320 !ToLocal<Value>(i::Execution::Call(isolate, fun, self, argc, args),
4322 RETURN_ON_FAILED_EXECUTION(Value);
4323 DCHECK(!delegate->IsUndefined());
4324 RETURN_ESCAPED(result);
4326 return MaybeLocal<Value>();
4330 Local<v8::Value> Object::CallAsConstructor(int argc,
4331 v8::Local<v8::Value> argv[]) {
4332 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4333 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4334 RETURN_TO_LOCAL_UNCHECKED(CallAsConstructor(context, argc, argv_cast), Value);
4338 MaybeLocal<Function> Function::New(Local<Context> context,
4339 FunctionCallback callback, Local<Value> data,
4341 i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
4342 LOG_API(isolate, "Function::New");
4344 return FunctionTemplateNew(isolate, callback, data, Local<Signature>(),
4345 length, true)->GetFunction(context);
4349 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback,
4350 Local<Value> data, int length) {
4351 return Function::New(v8_isolate->GetCurrentContext(), callback, data, length)
4352 .FromMaybe(Local<Function>());
4356 Local<v8::Object> Function::NewInstance() const {
4357 return NewInstance(Isolate::GetCurrent()->GetCurrentContext(), 0, NULL)
4358 .FromMaybe(Local<Object>());
4362 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
4363 v8::Local<v8::Value> argv[]) const {
4364 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::NewInstance()",
4366 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4367 auto self = Utils::OpenHandle(this);
4368 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4369 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4370 Local<Object> result;
4371 has_pending_exception =
4372 !ToLocal<Object>(i::Execution::New(self, argc, args), &result);
4373 RETURN_ON_FAILED_EXECUTION(Object);
4374 RETURN_ESCAPED(result);
4378 Local<v8::Object> Function::NewInstance(int argc,
4379 v8::Local<v8::Value> argv[]) const {
4380 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4381 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context, argc, argv), Object);
4385 MaybeLocal<v8::Value> Function::Call(Local<Context> context,
4386 v8::Local<v8::Value> recv, int argc,
4387 v8::Local<v8::Value> argv[]) {
4388 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::Call()", Value);
4389 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4390 auto self = Utils::OpenHandle(this);
4391 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
4392 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4393 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4394 Local<Value> result;
4395 has_pending_exception =
4397 i::Execution::Call(isolate, self, recv_obj, argc, args, true),
4399 RETURN_ON_FAILED_EXECUTION(Value);
4400 RETURN_ESCAPED(result);
4404 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc,
4405 v8::Local<v8::Value> argv[]) {
4406 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4407 RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value);
4411 void Function::SetName(v8::Local<v8::String> name) {
4412 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4413 func->shared()->set_name(*Utils::OpenHandle(*name));
4417 Local<Value> Function::GetName() const {
4418 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4419 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name(),
4420 func->GetIsolate()));
4424 Local<Value> Function::GetInferredName() const {
4425 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4426 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
4427 func->GetIsolate()));
4431 Local<Value> Function::GetDisplayName() const {
4432 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4434 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4435 i::Handle<i::String> property_name =
4436 isolate->factory()->NewStringFromStaticChars("displayName");
4437 i::Handle<i::Object> value =
4438 i::JSReceiver::GetDataProperty(func, property_name);
4439 if (value->IsString()) {
4440 i::Handle<i::String> name = i::Handle<i::String>::cast(value);
4441 if (name->length() > 0) return Utils::ToLocal(name);
4443 return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
4447 ScriptOrigin Function::GetScriptOrigin() const {
4448 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4449 if (func->shared()->script()->IsScript()) {
4450 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4451 return GetScriptOriginForScript(func->GetIsolate(), script);
4453 return v8::ScriptOrigin(Local<Value>());
4457 const int Function::kLineOffsetNotFound = -1;
4460 int Function::GetScriptLineNumber() const {
4461 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4462 if (func->shared()->script()->IsScript()) {
4463 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4464 return i::Script::GetLineNumber(script, func->shared()->start_position());
4466 return kLineOffsetNotFound;
4470 int Function::GetScriptColumnNumber() const {
4471 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4472 if (func->shared()->script()->IsScript()) {
4473 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4474 return i::Script::GetColumnNumber(script, func->shared()->start_position());
4476 return kLineOffsetNotFound;
4480 bool Function::IsBuiltin() const {
4481 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4482 return func->IsBuiltin();
4486 int Function::ScriptId() const {
4487 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4488 if (!func->shared()->script()->IsScript()) {
4489 return v8::UnboundScript::kNoScriptId;
4491 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4492 return script->id()->value();
4496 Local<v8::Value> Function::GetBoundFunction() const {
4497 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4498 if (!func->shared()->bound()) {
4499 return v8::Undefined(reinterpret_cast<v8::Isolate*>(func->GetIsolate()));
4501 i::Handle<i::FixedArray> bound_args = i::Handle<i::FixedArray>(
4502 i::FixedArray::cast(func->function_bindings()));
4503 i::Handle<i::Object> original(
4504 bound_args->get(i::JSFunction::kBoundFunctionIndex),
4505 func->GetIsolate());
4506 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(original));
4510 int Name::GetIdentityHash() {
4511 auto self = Utils::OpenHandle(this);
4512 return static_cast<int>(self->Hash());
4516 int String::Length() const {
4517 i::Handle<i::String> str = Utils::OpenHandle(this);
4518 return str->length();
4522 bool String::IsOneByte() const {
4523 i::Handle<i::String> str = Utils::OpenHandle(this);
4524 return str->HasOnlyOneByteChars();
4528 // Helpers for ContainsOnlyOneByteHelper
4529 template<size_t size> struct OneByteMask;
4530 template<> struct OneByteMask<4> {
4531 static const uint32_t value = 0xFF00FF00;
4533 template<> struct OneByteMask<8> {
4534 static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
4536 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
4537 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
4538 static inline bool Unaligned(const uint16_t* chars) {
4539 return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
4543 static inline const uint16_t* Align(const uint16_t* chars) {
4544 return reinterpret_cast<uint16_t*>(
4545 reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
4548 class ContainsOnlyOneByteHelper {
4550 ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
4551 bool Check(i::String* string) {
4552 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
4553 if (cons_string == NULL) return is_one_byte_;
4554 return CheckCons(cons_string);
4556 void VisitOneByteString(const uint8_t* chars, int length) {
4559 void VisitTwoByteString(const uint16_t* chars, int length) {
4560 // Accumulated bits.
4562 // Align to uintptr_t.
4563 const uint16_t* end = chars + length;
4564 while (Unaligned(chars) && chars != end) {
4567 // Read word aligned in blocks,
4568 // checking the return value at the end of each block.
4569 const uint16_t* aligned_end = Align(end);
4570 const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
4571 const int inner_loops = 16;
4572 while (chars + inner_loops*increment < aligned_end) {
4573 for (int i = 0; i < inner_loops; i++) {
4574 acc |= *reinterpret_cast<const uintptr_t*>(chars);
4577 // Check for early return.
4578 if ((acc & kOneByteMask) != 0) {
4579 is_one_byte_ = false;
4584 while (chars != end) {
4588 if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
4592 bool CheckCons(i::ConsString* cons_string) {
4594 // Check left side if flat.
4595 i::String* left = cons_string->first();
4596 i::ConsString* left_as_cons =
4597 i::String::VisitFlat(this, left, 0);
4598 if (!is_one_byte_) return false;
4599 // Check right side if flat.
4600 i::String* right = cons_string->second();
4601 i::ConsString* right_as_cons =
4602 i::String::VisitFlat(this, right, 0);
4603 if (!is_one_byte_) return false;
4604 // Standard recurse/iterate trick.
4605 if (left_as_cons != NULL && right_as_cons != NULL) {
4606 if (left->length() < right->length()) {
4607 CheckCons(left_as_cons);
4608 cons_string = right_as_cons;
4610 CheckCons(right_as_cons);
4611 cons_string = left_as_cons;
4613 // Check fast return.
4614 if (!is_one_byte_) return false;
4617 // Descend left in place.
4618 if (left_as_cons != NULL) {
4619 cons_string = left_as_cons;
4622 // Descend right in place.
4623 if (right_as_cons != NULL) {
4624 cons_string = right_as_cons;
4630 return is_one_byte_;
4633 DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
4637 bool String::ContainsOnlyOneByte() const {
4638 i::Handle<i::String> str = Utils::OpenHandle(this);
4639 if (str->HasOnlyOneByteChars()) return true;
4640 ContainsOnlyOneByteHelper helper;
4641 return helper.Check(*str);
4645 class Utf8LengthHelper : public i::AllStatic {
4648 kEndsWithLeadingSurrogate = 1 << 0,
4649 kStartsWithTrailingSurrogate = 1 << 1,
4650 kLeftmostEdgeIsCalculated = 1 << 2,
4651 kRightmostEdgeIsCalculated = 1 << 3,
4652 kLeftmostEdgeIsSurrogate = 1 << 4,
4653 kRightmostEdgeIsSurrogate = 1 << 5
4656 static const uint8_t kInitialState = 0;
4658 static inline bool EndsWithSurrogate(uint8_t state) {
4659 return state & kEndsWithLeadingSurrogate;
4662 static inline bool StartsWithSurrogate(uint8_t state) {
4663 return state & kStartsWithTrailingSurrogate;
4668 Visitor() : utf8_length_(0), state_(kInitialState) {}
4670 void VisitOneByteString(const uint8_t* chars, int length) {
4671 int utf8_length = 0;
4672 // Add in length 1 for each non-Latin1 character.
4673 for (int i = 0; i < length; i++) {
4674 utf8_length += *chars++ >> 7;
4676 // Add in length 1 for each character.
4677 utf8_length_ = utf8_length + length;
4678 state_ = kInitialState;
4681 void VisitTwoByteString(const uint16_t* chars, int length) {
4682 int utf8_length = 0;
4683 int last_character = unibrow::Utf16::kNoPreviousCharacter;
4684 for (int i = 0; i < length; i++) {
4685 uint16_t c = chars[i];
4686 utf8_length += unibrow::Utf8::Length(c, last_character);
4689 utf8_length_ = utf8_length;
4691 if (unibrow::Utf16::IsTrailSurrogate(chars[0])) {
4692 state |= kStartsWithTrailingSurrogate;
4694 if (unibrow::Utf16::IsLeadSurrogate(chars[length-1])) {
4695 state |= kEndsWithLeadingSurrogate;
4700 static i::ConsString* VisitFlat(i::String* string,
4704 i::ConsString* cons_string = i::String::VisitFlat(&visitor, string);
4705 *length = visitor.utf8_length_;
4706 *state = visitor.state_;
4713 DISALLOW_COPY_AND_ASSIGN(Visitor);
4716 static inline void MergeLeafLeft(int* length,
4718 uint8_t leaf_state) {
4719 bool edge_surrogate = StartsWithSurrogate(leaf_state);
4720 if (!(*state & kLeftmostEdgeIsCalculated)) {
4721 DCHECK(!(*state & kLeftmostEdgeIsSurrogate));
4722 *state |= kLeftmostEdgeIsCalculated
4723 | (edge_surrogate ? kLeftmostEdgeIsSurrogate : 0);
4724 } else if (EndsWithSurrogate(*state) && edge_surrogate) {
4725 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4727 if (EndsWithSurrogate(leaf_state)) {
4728 *state |= kEndsWithLeadingSurrogate;
4730 *state &= ~kEndsWithLeadingSurrogate;
4734 static inline void MergeLeafRight(int* length,
4736 uint8_t leaf_state) {
4737 bool edge_surrogate = EndsWithSurrogate(leaf_state);
4738 if (!(*state & kRightmostEdgeIsCalculated)) {
4739 DCHECK(!(*state & kRightmostEdgeIsSurrogate));
4740 *state |= (kRightmostEdgeIsCalculated
4741 | (edge_surrogate ? kRightmostEdgeIsSurrogate : 0));
4742 } else if (edge_surrogate && StartsWithSurrogate(*state)) {
4743 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4745 if (StartsWithSurrogate(leaf_state)) {
4746 *state |= kStartsWithTrailingSurrogate;
4748 *state &= ~kStartsWithTrailingSurrogate;
4752 static inline void MergeTerminal(int* length,
4754 uint8_t* state_out) {
4755 DCHECK((state & kLeftmostEdgeIsCalculated) &&
4756 (state & kRightmostEdgeIsCalculated));
4757 if (EndsWithSurrogate(state) && StartsWithSurrogate(state)) {
4758 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4760 *state_out = kInitialState |
4761 (state & kLeftmostEdgeIsSurrogate ? kStartsWithTrailingSurrogate : 0) |
4762 (state & kRightmostEdgeIsSurrogate ? kEndsWithLeadingSurrogate : 0);
4765 static int Calculate(i::ConsString* current, uint8_t* state_out) {
4766 using namespace internal;
4767 int total_length = 0;
4768 uint8_t state = kInitialState;
4770 i::String* left = current->first();
4771 i::String* right = current->second();
4772 uint8_t right_leaf_state;
4773 uint8_t left_leaf_state;
4775 ConsString* left_as_cons =
4776 Visitor::VisitFlat(left, &leaf_length, &left_leaf_state);
4777 if (left_as_cons == NULL) {
4778 total_length += leaf_length;
4779 MergeLeafLeft(&total_length, &state, left_leaf_state);
4781 ConsString* right_as_cons =
4782 Visitor::VisitFlat(right, &leaf_length, &right_leaf_state);
4783 if (right_as_cons == NULL) {
4784 total_length += leaf_length;
4785 MergeLeafRight(&total_length, &state, right_leaf_state);
4786 if (left_as_cons != NULL) {
4787 // 1 Leaf node. Descend in place.
4788 current = left_as_cons;
4792 MergeTerminal(&total_length, state, state_out);
4793 return total_length;
4795 } else if (left_as_cons == NULL) {
4796 // 1 Leaf node. Descend in place.
4797 current = right_as_cons;
4800 // Both strings are ConsStrings.
4801 // Recurse on smallest.
4802 if (left->length() < right->length()) {
4803 total_length += Calculate(left_as_cons, &left_leaf_state);
4804 MergeLeafLeft(&total_length, &state, left_leaf_state);
4805 current = right_as_cons;
4807 total_length += Calculate(right_as_cons, &right_leaf_state);
4808 MergeLeafRight(&total_length, &state, right_leaf_state);
4809 current = left_as_cons;
4816 static inline int Calculate(i::ConsString* current) {
4817 uint8_t state = kInitialState;
4818 return Calculate(current, &state);
4822 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8LengthHelper);
4826 static int Utf8Length(i::String* str, i::Isolate* isolate) {
4827 int length = str->length();
4828 if (length == 0) return 0;
4830 i::ConsString* cons_string =
4831 Utf8LengthHelper::Visitor::VisitFlat(str, &length, &state);
4832 if (cons_string == NULL) return length;
4833 return Utf8LengthHelper::Calculate(cons_string);
4837 int String::Utf8Length() const {
4838 i::Handle<i::String> str = Utils::OpenHandle(this);
4839 i::Isolate* isolate = str->GetIsolate();
4840 return v8::Utf8Length(*str, isolate);
4844 class Utf8WriterVisitor {
4849 bool skip_capacity_check,
4850 bool replace_invalid_utf8)
4851 : early_termination_(false),
4852 last_character_(unibrow::Utf16::kNoPreviousCharacter),
4855 capacity_(capacity),
4856 skip_capacity_check_(capacity == -1 || skip_capacity_check),
4857 replace_invalid_utf8_(replace_invalid_utf8),
4858 utf16_chars_read_(0) {
4861 static int WriteEndCharacter(uint16_t character,
4865 bool replace_invalid_utf8) {
4866 using namespace unibrow;
4867 DCHECK(remaining > 0);
4868 // We can't use a local buffer here because Encode needs to modify
4869 // previous characters in the stream. We know, however, that
4870 // exactly one character will be advanced.
4871 if (Utf16::IsSurrogatePair(last_character, character)) {
4872 int written = Utf8::Encode(buffer,
4875 replace_invalid_utf8);
4876 DCHECK(written == 1);
4879 // Use a scratch buffer to check the required characters.
4880 char temp_buffer[Utf8::kMaxEncodedSize];
4881 // Can't encode using last_character as gcc has array bounds issues.
4882 int written = Utf8::Encode(temp_buffer,
4884 Utf16::kNoPreviousCharacter,
4885 replace_invalid_utf8);
4887 if (written > remaining) return 0;
4888 // Copy over the character from temp_buffer.
4889 for (int j = 0; j < written; j++) {
4890 buffer[j] = temp_buffer[j];
4895 // Visit writes out a group of code units (chars) of a v8::String to the
4896 // internal buffer_. This is done in two phases. The first phase calculates a
4897 // pesimistic estimate (writable_length) on how many code units can be safely
4898 // written without exceeding the buffer capacity and without writing the last
4899 // code unit (it could be a lead surrogate). The estimated number of code
4900 // units is then written out in one go, and the reported byte usage is used
4901 // to correct the estimate. This is repeated until the estimate becomes <= 0
4902 // or all code units have been written out. The second phase writes out code
4903 // units until the buffer capacity is reached, would be exceeded by the next
4904 // unit, or all units have been written out.
4905 template<typename Char>
4906 void Visit(const Char* chars, const int length) {
4907 using namespace unibrow;
4908 DCHECK(!early_termination_);
4909 if (length == 0) return;
4910 // Copy state to stack.
4911 char* buffer = buffer_;
4912 int last_character =
4913 sizeof(Char) == 1 ? Utf16::kNoPreviousCharacter : last_character_;
4915 // Do a fast loop where there is no exit capacity check.
4918 if (skip_capacity_check_) {
4919 fast_length = length;
4921 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4922 // Need enough space to write everything but one character.
4923 STATIC_ASSERT(Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 3);
4924 int max_size_per_char = sizeof(Char) == 1 ? 2 : 3;
4925 int writable_length =
4926 (remaining_capacity - max_size_per_char)/max_size_per_char;
4927 // Need to drop into slow loop.
4928 if (writable_length <= 0) break;
4929 fast_length = i + writable_length;
4930 if (fast_length > length) fast_length = length;
4932 // Write the characters to the stream.
4933 if (sizeof(Char) == 1) {
4934 for (; i < fast_length; i++) {
4936 Utf8::EncodeOneByte(buffer, static_cast<uint8_t>(*chars++));
4937 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4940 for (; i < fast_length; i++) {
4941 uint16_t character = *chars++;
4942 buffer += Utf8::Encode(buffer,
4945 replace_invalid_utf8_);
4946 last_character = character;
4947 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4950 // Array is fully written. Exit.
4951 if (fast_length == length) {
4952 // Write state back out to object.
4953 last_character_ = last_character;
4955 utf16_chars_read_ += length;
4959 DCHECK(!skip_capacity_check_);
4960 // Slow loop. Must check capacity on each iteration.
4961 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4962 DCHECK(remaining_capacity >= 0);
4963 for (; i < length && remaining_capacity > 0; i++) {
4964 uint16_t character = *chars++;
4965 // remaining_capacity is <= 3 bytes at this point, so we do not write out
4966 // an umatched lead surrogate.
4967 if (replace_invalid_utf8_ && Utf16::IsLeadSurrogate(character)) {
4968 early_termination_ = true;
4971 int written = WriteEndCharacter(character,
4975 replace_invalid_utf8_);
4977 early_termination_ = true;
4981 remaining_capacity -= written;
4982 last_character = character;
4984 // Write state back out to object.
4985 last_character_ = last_character;
4987 utf16_chars_read_ += i;
4990 inline bool IsDone() {
4991 return early_termination_;
4994 inline void VisitOneByteString(const uint8_t* chars, int length) {
4995 Visit(chars, length);
4998 inline void VisitTwoByteString(const uint16_t* chars, int length) {
4999 Visit(chars, length);
5002 int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
5003 // Write out number of utf16 characters written to the stream.
5004 if (utf16_chars_read_out != NULL) {
5005 *utf16_chars_read_out = utf16_chars_read_;
5007 // Only null terminate if all of the string was written and there's space.
5009 !early_termination_ &&
5010 (capacity_ == -1 || (buffer_ - start_) < capacity_)) {
5013 return static_cast<int>(buffer_ - start_);
5017 bool early_termination_;
5018 int last_character_;
5022 bool const skip_capacity_check_;
5023 bool const replace_invalid_utf8_;
5024 int utf16_chars_read_;
5025 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
5029 static bool RecursivelySerializeToUtf8(i::String* current,
5030 Utf8WriterVisitor* writer,
5031 int recursion_budget) {
5032 while (!writer->IsDone()) {
5033 i::ConsString* cons_string = i::String::VisitFlat(writer, current);
5034 if (cons_string == NULL) return true; // Leaf node.
5035 if (recursion_budget <= 0) return false;
5036 // Must write the left branch first.
5037 i::String* first = cons_string->first();
5038 bool success = RecursivelySerializeToUtf8(first,
5040 recursion_budget - 1);
5041 if (!success) return false;
5042 // Inline tail recurse for right branch.
5043 current = cons_string->second();
5049 int String::WriteUtf8(char* buffer,
5052 int options) const {
5053 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
5054 LOG_API(isolate, "String::WriteUtf8");
5056 i::Handle<i::String> str = Utils::OpenHandle(this);
5057 if (options & HINT_MANY_WRITES_EXPECTED) {
5058 str = i::String::Flatten(str); // Flatten the string for efficiency.
5060 const int string_length = str->length();
5061 bool write_null = !(options & NO_NULL_TERMINATION);
5062 bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
5063 int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
5064 // First check if we can just write the string without checking capacity.
5065 if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
5066 Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
5067 const int kMaxRecursion = 100;
5068 bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
5069 if (success) return writer.CompleteWrite(write_null, nchars_ref);
5070 } else if (capacity >= string_length) {
5071 // First check that the buffer is large enough.
5072 int utf8_bytes = v8::Utf8Length(*str, str->GetIsolate());
5073 if (utf8_bytes <= capacity) {
5074 // one-byte fast path.
5075 if (utf8_bytes == string_length) {
5076 WriteOneByte(reinterpret_cast<uint8_t*>(buffer), 0, capacity, options);
5077 if (nchars_ref != NULL) *nchars_ref = string_length;
5078 if (write_null && (utf8_bytes+1 <= capacity)) {
5079 return string_length + 1;
5081 return string_length;
5083 if (write_null && (utf8_bytes+1 > capacity)) {
5084 options |= NO_NULL_TERMINATION;
5086 // Recurse once without a capacity limit.
5087 // This will get into the first branch above.
5088 // TODO(dcarney) Check max left rec. in Utf8Length and fall through.
5089 return WriteUtf8(buffer, -1, nchars_ref, options);
5092 // Recursive slow path can potentially be unreasonable slow. Flatten.
5093 str = i::String::Flatten(str);
5094 Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
5095 i::String::VisitFlat(&writer, *str);
5096 return writer.CompleteWrite(write_null, nchars_ref);
5100 template<typename CharType>
5101 static inline int WriteHelper(const String* string,
5106 i::Isolate* isolate = Utils::OpenHandle(string)->GetIsolate();
5107 LOG_API(isolate, "String::Write");
5109 DCHECK(start >= 0 && length >= -1);
5110 i::Handle<i::String> str = Utils::OpenHandle(string);
5111 if (options & String::HINT_MANY_WRITES_EXPECTED) {
5112 // Flatten the string for efficiency. This applies whether we are
5113 // using StringCharacterStream or Get(i) to access the characters.
5114 str = i::String::Flatten(str);
5116 int end = start + length;
5117 if ((length == -1) || (length > str->length() - start) )
5118 end = str->length();
5119 if (end < 0) return 0;
5120 i::String::WriteToFlat(*str, buffer, start, end);
5121 if (!(options & String::NO_NULL_TERMINATION) &&
5122 (length == -1 || end - start < length)) {
5123 buffer[end - start] = '\0';
5129 int String::WriteOneByte(uint8_t* buffer,
5132 int options) const {
5133 return WriteHelper(this, buffer, start, length, options);
5137 int String::Write(uint16_t* buffer,
5140 int options) const {
5141 return WriteHelper(this, buffer, start, length, options);
5145 bool v8::String::IsExternal() const {
5146 i::Handle<i::String> str = Utils::OpenHandle(this);
5147 return i::StringShape(*str).IsExternalTwoByte();
5151 bool v8::String::IsExternalOneByte() const {
5152 i::Handle<i::String> str = Utils::OpenHandle(this);
5153 return i::StringShape(*str).IsExternalOneByte();
5157 void v8::String::VerifyExternalStringResource(
5158 v8::String::ExternalStringResource* value) const {
5159 i::Handle<i::String> str = Utils::OpenHandle(this);
5160 const v8::String::ExternalStringResource* expected;
5161 if (i::StringShape(*str).IsExternalTwoByte()) {
5162 const void* resource =
5163 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5164 expected = reinterpret_cast<const ExternalStringResource*>(resource);
5168 CHECK_EQ(expected, value);
5171 void v8::String::VerifyExternalStringResourceBase(
5172 v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
5173 i::Handle<i::String> str = Utils::OpenHandle(this);
5174 const v8::String::ExternalStringResourceBase* expected;
5175 Encoding expectedEncoding;
5176 if (i::StringShape(*str).IsExternalOneByte()) {
5177 const void* resource =
5178 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5179 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5180 expectedEncoding = ONE_BYTE_ENCODING;
5181 } else if (i::StringShape(*str).IsExternalTwoByte()) {
5182 const void* resource =
5183 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5184 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5185 expectedEncoding = TWO_BYTE_ENCODING;
5189 str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
5191 CHECK_EQ(expected, value);
5192 CHECK_EQ(expectedEncoding, encoding);
5195 const v8::String::ExternalOneByteStringResource*
5196 v8::String::GetExternalOneByteStringResource() const {
5197 i::Handle<i::String> str = Utils::OpenHandle(this);
5198 if (i::StringShape(*str).IsExternalOneByte()) {
5199 const void* resource =
5200 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5201 return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
5208 Local<Value> Symbol::Name() const {
5209 i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
5210 i::Handle<i::Object> name(sym->name(), sym->GetIsolate());
5211 return Utils::ToLocal(name);
5215 double Number::Value() const {
5216 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5217 return obj->Number();
5221 bool Boolean::Value() const {
5222 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5223 return obj->IsTrue();
5227 int64_t Integer::Value() const {
5228 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5230 return i::Smi::cast(*obj)->value();
5232 return static_cast<int64_t>(obj->Number());
5237 int32_t Int32::Value() const {
5238 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5240 return i::Smi::cast(*obj)->value();
5242 return static_cast<int32_t>(obj->Number());
5247 uint32_t Uint32::Value() const {
5248 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5250 return i::Smi::cast(*obj)->value();
5252 return static_cast<uint32_t>(obj->Number());
5257 int v8::Object::InternalFieldCount() {
5258 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5259 return obj->GetInternalFieldCount();
5263 static bool InternalFieldOK(i::Handle<i::JSObject> obj,
5265 const char* location) {
5266 return Utils::ApiCheck(index < obj->GetInternalFieldCount(),
5268 "Internal field out of bounds");
5272 Local<Value> v8::Object::SlowGetInternalField(int index) {
5273 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5274 const char* location = "v8::Object::GetInternalField()";
5275 if (!InternalFieldOK(obj, index, location)) return Local<Value>();
5276 i::Handle<i::Object> value(obj->GetInternalField(index), obj->GetIsolate());
5277 return Utils::ToLocal(value);
5281 void v8::Object::SetInternalField(int index, v8::Local<Value> value) {
5282 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5283 const char* location = "v8::Object::SetInternalField()";
5284 if (!InternalFieldOK(obj, index, location)) return;
5285 i::Handle<i::Object> val = Utils::OpenHandle(*value);
5286 obj->SetInternalField(index, *val);
5290 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
5291 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5292 const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
5293 if (!InternalFieldOK(obj, index, location)) return NULL;
5294 return DecodeSmiToAligned(obj->GetInternalField(index), location);
5298 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
5299 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5300 const char* location = "v8::Object::SetAlignedPointerInInternalField()";
5301 if (!InternalFieldOK(obj, index, location)) return;
5302 obj->SetInternalField(index, EncodeAlignedAsSmi(value, location));
5303 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
5307 static void* ExternalValue(i::Object* obj) {
5308 // Obscure semantics for undefined, but somehow checked in our unit tests...
5309 if (obj->IsUndefined()) return NULL;
5310 i::Object* foreign = i::JSObject::cast(obj)->GetInternalField(0);
5311 return i::Foreign::cast(foreign)->foreign_address();
5315 // --- E n v i r o n m e n t ---
5318 void v8::V8::InitializePlatform(Platform* platform) {
5319 i::V8::InitializePlatform(platform);
5323 void v8::V8::ShutdownPlatform() {
5324 i::V8::ShutdownPlatform();
5328 bool v8::V8::Initialize() {
5329 i::V8::Initialize();
5330 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5337 void v8::V8::SetEntropySource(EntropySource entropy_source) {
5338 base::RandomNumberGenerator::SetEntropySource(entropy_source);
5342 void v8::V8::SetReturnAddressLocationResolver(
5343 ReturnAddressLocationResolver return_address_resolver) {
5344 i::V8::SetReturnAddressLocationResolver(return_address_resolver);
5348 bool v8::V8::Dispose() {
5350 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5351 i::DisposeNatives();
5357 HeapStatistics::HeapStatistics(): total_heap_size_(0),
5358 total_heap_size_executable_(0),
5359 total_physical_size_(0),
5361 heap_size_limit_(0) { }
5364 HeapSpaceStatistics::HeapSpaceStatistics(): space_name_(0),
5366 space_used_size_(0),
5367 space_available_size_(0),
5368 physical_space_size_(0) { }
5371 HeapObjectStatistics::HeapObjectStatistics()
5372 : object_type_(nullptr),
5373 object_sub_type_(nullptr),
5378 bool v8::V8::InitializeICU(const char* icu_data_file) {
5379 return i::InitializeICU(icu_data_file);
5383 void v8::V8::InitializeExternalStartupData(const char* directory_path) {
5384 i::InitializeExternalStartupData(directory_path);
5388 void v8::V8::InitializeExternalStartupData(const char* natives_blob,
5389 const char* snapshot_blob) {
5390 i::InitializeExternalStartupData(natives_blob, snapshot_blob);
5394 const char* v8::V8::GetVersion() {
5395 return i::Version::GetVersion();
5399 static i::Handle<i::Context> CreateEnvironment(
5400 i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
5401 v8::Local<ObjectTemplate> global_template,
5402 v8::Local<Value> maybe_global_proxy) {
5403 i::Handle<i::Context> env;
5405 // Enter V8 via an ENTER_V8 scope.
5408 v8::Local<ObjectTemplate> proxy_template = global_template;
5409 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
5410 i::Handle<i::FunctionTemplateInfo> global_constructor;
5412 if (!global_template.IsEmpty()) {
5413 // Make sure that the global_template has a constructor.
5414 global_constructor = EnsureConstructor(isolate, *global_template);
5416 // Create a fresh template for the global proxy object.
5417 proxy_template = ObjectTemplate::New(
5418 reinterpret_cast<v8::Isolate*>(isolate));
5419 proxy_constructor = EnsureConstructor(isolate, *proxy_template);
5421 // Set the global template to be the prototype template of
5422 // global proxy template.
5423 proxy_constructor->set_prototype_template(
5424 *Utils::OpenHandle(*global_template));
5426 // Migrate security handlers from global_template to
5427 // proxy_template. Temporarily removing access check
5428 // information from the global template.
5429 if (!global_constructor->access_check_info()->IsUndefined()) {
5430 proxy_constructor->set_access_check_info(
5431 global_constructor->access_check_info());
5432 proxy_constructor->set_needs_access_check(
5433 global_constructor->needs_access_check());
5434 global_constructor->set_needs_access_check(false);
5435 global_constructor->set_access_check_info(
5436 isolate->heap()->undefined_value());
5440 i::Handle<i::Object> proxy = Utils::OpenHandle(*maybe_global_proxy, true);
5441 i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
5442 if (!proxy.is_null()) {
5443 maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(proxy);
5445 // Create the environment.
5446 env = isolate->bootstrapper()->CreateEnvironment(
5447 maybe_proxy, proxy_template, extensions);
5449 // Restore the access check info on the global template.
5450 if (!global_template.IsEmpty()) {
5451 DCHECK(!global_constructor.is_null());
5452 DCHECK(!proxy_constructor.is_null());
5453 global_constructor->set_access_check_info(
5454 proxy_constructor->access_check_info());
5455 global_constructor->set_needs_access_check(
5456 proxy_constructor->needs_access_check());
5464 Local<Context> v8::Context::New(v8::Isolate* external_isolate,
5465 v8::ExtensionConfiguration* extensions,
5466 v8::Local<ObjectTemplate> global_template,
5467 v8::Local<Value> global_object) {
5468 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
5469 LOG_API(isolate, "Context::New");
5470 i::HandleScope scope(isolate);
5471 ExtensionConfiguration no_extensions;
5472 if (extensions == NULL) extensions = &no_extensions;
5473 i::Handle<i::Context> env =
5474 CreateEnvironment(isolate, extensions, global_template, global_object);
5475 if (env.is_null()) {
5476 if (isolate->has_pending_exception()) {
5477 isolate->OptionalRescheduleException(true);
5479 return Local<Context>();
5481 return Utils::ToLocal(scope.CloseAndEscape(env));
5485 void v8::Context::SetSecurityToken(Local<Value> token) {
5486 i::Handle<i::Context> env = Utils::OpenHandle(this);
5487 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
5488 env->set_security_token(*token_handle);
5492 void v8::Context::UseDefaultSecurityToken() {
5493 i::Handle<i::Context> env = Utils::OpenHandle(this);
5494 env->set_security_token(env->global_object());
5498 Local<Value> v8::Context::GetSecurityToken() {
5499 i::Handle<i::Context> env = Utils::OpenHandle(this);
5500 i::Isolate* isolate = env->GetIsolate();
5501 i::Object* security_token = env->security_token();
5502 i::Handle<i::Object> token_handle(security_token, isolate);
5503 return Utils::ToLocal(token_handle);
5507 v8::Isolate* Context::GetIsolate() {
5508 i::Handle<i::Context> env = Utils::OpenHandle(this);
5509 return reinterpret_cast<Isolate*>(env->GetIsolate());
5513 v8::Local<v8::Object> Context::Global() {
5514 i::Handle<i::Context> context = Utils::OpenHandle(this);
5515 i::Isolate* isolate = context->GetIsolate();
5516 i::Handle<i::Object> global(context->global_proxy(), isolate);
5517 // TODO(dcarney): This should always return the global proxy
5518 // but can't presently as calls to GetProtoype will return the wrong result.
5519 if (i::Handle<i::JSGlobalProxy>::cast(
5520 global)->IsDetachedFrom(context->global_object())) {
5521 global = i::Handle<i::Object>(context->global_object(), isolate);
5523 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
5527 void Context::DetachGlobal() {
5528 i::Handle<i::Context> context = Utils::OpenHandle(this);
5529 i::Isolate* isolate = context->GetIsolate();
5531 isolate->bootstrapper()->DetachGlobal(context);
5535 Local<v8::Object> Context::GetExtrasBindingObject() {
5536 i::Handle<i::Context> context = Utils::OpenHandle(this);
5537 i::Isolate* isolate = context->GetIsolate();
5538 i::Handle<i::JSObject> binding(context->extras_binding_object(), isolate);
5539 return Utils::ToLocal(binding);
5543 void Context::AllowCodeGenerationFromStrings(bool allow) {
5544 i::Handle<i::Context> context = Utils::OpenHandle(this);
5545 i::Isolate* isolate = context->GetIsolate();
5547 context->set_allow_code_gen_from_strings(
5548 allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
5552 bool Context::IsCodeGenerationFromStringsAllowed() {
5553 i::Handle<i::Context> context = Utils::OpenHandle(this);
5554 return !context->allow_code_gen_from_strings()->IsFalse();
5558 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
5559 i::Handle<i::Context> context = Utils::OpenHandle(this);
5560 i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
5561 context->set_error_message_for_code_gen_from_strings(*error_handle);
5565 size_t Context::EstimatedSize() {
5566 return static_cast<size_t>(
5567 i::ContextMeasure(*Utils::OpenHandle(this)).Size());
5571 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
5572 PREPARE_FOR_EXECUTION(context, "v8::ObjectTemplate::NewInstance()", Object);
5573 auto self = Utils::OpenHandle(this);
5574 Local<Object> result;
5575 has_pending_exception =
5576 !ToLocal<Object>(i::ApiNatives::InstantiateObject(self), &result);
5577 RETURN_ON_FAILED_EXECUTION(Object);
5578 RETURN_ESCAPED(result);
5582 Local<v8::Object> ObjectTemplate::NewInstance() {
5583 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5584 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object);
5588 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
5589 PREPARE_FOR_EXECUTION(context, "v8::FunctionTemplate::GetFunction()",
5591 auto self = Utils::OpenHandle(this);
5592 Local<Function> result;
5593 has_pending_exception =
5594 !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
5595 RETURN_ON_FAILED_EXECUTION(Function);
5596 RETURN_ESCAPED(result);
5600 Local<v8::Function> FunctionTemplate::GetFunction() {
5601 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5602 RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function);
5606 bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) {
5607 auto self = Utils::OpenHandle(this);
5608 auto obj = Utils::OpenHandle(*value);
5609 return self->IsTemplateFor(*obj);
5613 Local<External> v8::External::New(Isolate* isolate, void* value) {
5614 STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
5615 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5616 LOG_API(i_isolate, "External::New");
5617 ENTER_V8(i_isolate);
5618 i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
5619 return Utils::ExternalToLocal(external);
5623 void* External::Value() const {
5624 return ExternalValue(*Utils::OpenHandle(this));
5628 // anonymous namespace for string creation helper functions
5631 inline int StringLength(const char* string) {
5632 return i::StrLength(string);
5636 inline int StringLength(const uint8_t* string) {
5637 return i::StrLength(reinterpret_cast<const char*>(string));
5641 inline int StringLength(const uint16_t* string) {
5643 while (string[length] != '\0')
5650 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5651 v8::NewStringType type,
5652 i::Vector<const char> string) {
5653 if (type == v8::NewStringType::kInternalized) {
5654 return factory->InternalizeUtf8String(string);
5656 return factory->NewStringFromUtf8(string);
5661 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5662 v8::NewStringType type,
5663 i::Vector<const uint8_t> string) {
5664 if (type == v8::NewStringType::kInternalized) {
5665 return factory->InternalizeOneByteString(string);
5667 return factory->NewStringFromOneByte(string);
5672 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5673 v8::NewStringType type,
5674 i::Vector<const uint16_t> string) {
5675 if (type == v8::NewStringType::kInternalized) {
5676 return factory->InternalizeTwoByteString(string);
5678 return factory->NewStringFromTwoByte(string);
5682 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
5685 template <typename Char>
5686 inline MaybeLocal<String> NewString(Isolate* v8_isolate, const char* location,
5687 const char* env, const Char* data,
5688 v8::NewStringType type, int length) {
5689 i::Isolate* isolate = reinterpret_cast<internal::Isolate*>(v8_isolate);
5690 if (length == 0) return String::Empty(v8_isolate);
5691 // TODO(dcarney): throw a context free exception.
5692 if (length > i::String::kMaxLength) return MaybeLocal<String>();
5694 LOG_API(isolate, env);
5695 if (length < 0) length = StringLength(data);
5696 i::Handle<i::String> result =
5697 NewString(isolate->factory(), type, i::Vector<const Char>(data, length))
5699 return Utils::ToLocal(result);
5702 } // anonymous namespace
5705 Local<String> String::NewFromUtf8(Isolate* isolate,
5709 RETURN_TO_LOCAL_UNCHECKED(
5710 NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5711 data, static_cast<v8::NewStringType>(type), length),
5716 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
5717 v8::NewStringType type, int length) {
5718 return NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5719 data, type, length);
5723 Local<String> String::NewFromOneByte(Isolate* isolate,
5724 const uint8_t* data,
5727 RETURN_TO_LOCAL_UNCHECKED(
5728 NewString(isolate, "v8::String::NewFromOneByte()",
5729 "String::NewFromOneByte", data,
5730 static_cast<v8::NewStringType>(type), length),
5735 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
5736 v8::NewStringType type, int length) {
5737 return NewString(isolate, "v8::String::NewFromOneByte()",
5738 "String::NewFromOneByte", data, type, length);
5742 Local<String> String::NewFromTwoByte(Isolate* isolate,
5743 const uint16_t* data,
5746 RETURN_TO_LOCAL_UNCHECKED(
5747 NewString(isolate, "v8::String::NewFromTwoByte()",
5748 "String::NewFromTwoByte", data,
5749 static_cast<v8::NewStringType>(type), length),
5754 MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate,
5755 const uint16_t* data,
5756 v8::NewStringType type, int length) {
5757 return NewString(isolate, "v8::String::NewFromTwoByte()",
5758 "String::NewFromTwoByte", data, type, length);
5762 Local<String> v8::String::Concat(Local<String> left, Local<String> right) {
5763 i::Handle<i::String> left_string = Utils::OpenHandle(*left);
5764 i::Isolate* isolate = left_string->GetIsolate();
5766 LOG_API(isolate, "v8::String::Concat");
5767 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
5768 // If we are steering towards a range error, do not wait for the error to be
5769 // thrown, and return the null handle instead.
5770 if (left_string->length() + right_string->length() > i::String::kMaxLength) {
5771 return Local<String>();
5773 i::Handle<i::String> result = isolate->factory()->NewConsString(
5774 left_string, right_string).ToHandleChecked();
5775 return Utils::ToLocal(result);
5779 MaybeLocal<String> v8::String::NewExternalTwoByte(
5780 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5781 CHECK(resource && resource->data());
5782 // TODO(dcarney): throw a context free exception.
5783 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5784 return MaybeLocal<String>();
5786 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5787 ENTER_V8(i_isolate);
5788 LOG_API(i_isolate, "String::NewExternalTwoByte");
5789 i::Handle<i::String> string = i_isolate->factory()
5790 ->NewExternalStringFromTwoByte(resource)
5792 i_isolate->heap()->external_string_table()->AddString(*string);
5793 return Utils::ToLocal(string);
5797 Local<String> v8::String::NewExternal(
5798 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5799 RETURN_TO_LOCAL_UNCHECKED(NewExternalTwoByte(isolate, resource), String);
5803 MaybeLocal<String> v8::String::NewExternalOneByte(
5804 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5805 CHECK(resource && resource->data());
5806 // TODO(dcarney): throw a context free exception.
5807 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5808 return MaybeLocal<String>();
5810 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5811 ENTER_V8(i_isolate);
5812 LOG_API(i_isolate, "String::NewExternalOneByte");
5813 i::Handle<i::String> string = i_isolate->factory()
5814 ->NewExternalStringFromOneByte(resource)
5816 i_isolate->heap()->external_string_table()->AddString(*string);
5817 return Utils::ToLocal(string);
5821 Local<String> v8::String::NewExternal(
5822 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5823 RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
5827 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
5828 i::Handle<i::String> obj = Utils::OpenHandle(this);
5829 i::Isolate* isolate = obj->GetIsolate();
5830 if (i::StringShape(*obj).IsExternal()) {
5831 return false; // Already an external string.
5834 if (isolate->heap()->IsInGCPostProcessing()) {
5837 CHECK(resource && resource->data());
5839 bool result = obj->MakeExternal(resource);
5840 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5841 DCHECK(!CanMakeExternal() || result);
5843 DCHECK(obj->IsExternalString());
5844 isolate->heap()->external_string_table()->AddString(*obj);
5850 bool v8::String::MakeExternal(
5851 v8::String::ExternalOneByteStringResource* resource) {
5852 i::Handle<i::String> obj = Utils::OpenHandle(this);
5853 i::Isolate* isolate = obj->GetIsolate();
5854 if (i::StringShape(*obj).IsExternal()) {
5855 return false; // Already an external string.
5858 if (isolate->heap()->IsInGCPostProcessing()) {
5861 CHECK(resource && resource->data());
5863 bool result = obj->MakeExternal(resource);
5864 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5865 DCHECK(!CanMakeExternal() || result);
5867 DCHECK(obj->IsExternalString());
5868 isolate->heap()->external_string_table()->AddString(*obj);
5874 bool v8::String::CanMakeExternal() {
5875 i::Handle<i::String> obj = Utils::OpenHandle(this);
5876 i::Isolate* isolate = obj->GetIsolate();
5878 // Old space strings should be externalized.
5879 if (!isolate->heap()->new_space()->Contains(*obj)) return true;
5880 int size = obj->Size(); // Byte size of the original string.
5881 if (size <= i::ExternalString::kShortSize) return false;
5882 i::StringShape shape(*obj);
5883 return !shape.IsExternal();
5887 Isolate* v8::Object::GetIsolate() {
5888 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
5889 return reinterpret_cast<Isolate*>(i_isolate);
5893 Local<v8::Object> v8::Object::New(Isolate* isolate) {
5894 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5895 LOG_API(i_isolate, "Object::New");
5896 ENTER_V8(i_isolate);
5897 i::Handle<i::JSObject> obj =
5898 i_isolate->factory()->NewJSObject(i_isolate->object_function());
5899 return Utils::ToLocal(obj);
5903 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
5904 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5905 LOG_API(i_isolate, "NumberObject::New");
5906 ENTER_V8(i_isolate);
5907 i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
5908 i::Handle<i::Object> obj =
5909 i::Object::ToObject(i_isolate, number).ToHandleChecked();
5910 return Utils::ToLocal(obj);
5914 double v8::NumberObject::ValueOf() const {
5915 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5916 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5917 i::Isolate* isolate = jsvalue->GetIsolate();
5918 LOG_API(isolate, "NumberObject::NumberValue");
5919 return jsvalue->value()->Number();
5923 Local<v8::Value> v8::BooleanObject::New(bool value) {
5924 i::Isolate* isolate = i::Isolate::Current();
5925 LOG_API(isolate, "BooleanObject::New");
5927 i::Handle<i::Object> boolean(value
5928 ? isolate->heap()->true_value()
5929 : isolate->heap()->false_value(),
5931 i::Handle<i::Object> obj =
5932 i::Object::ToObject(isolate, boolean).ToHandleChecked();
5933 return Utils::ToLocal(obj);
5937 bool v8::BooleanObject::ValueOf() const {
5938 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5939 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5940 i::Isolate* isolate = jsvalue->GetIsolate();
5941 LOG_API(isolate, "BooleanObject::BooleanValue");
5942 return jsvalue->value()->IsTrue();
5946 Local<v8::Value> v8::StringObject::New(Local<String> value) {
5947 i::Handle<i::String> string = Utils::OpenHandle(*value);
5948 i::Isolate* isolate = string->GetIsolate();
5949 LOG_API(isolate, "StringObject::New");
5951 i::Handle<i::Object> obj =
5952 i::Object::ToObject(isolate, string).ToHandleChecked();
5953 return Utils::ToLocal(obj);
5957 Local<v8::String> v8::StringObject::ValueOf() const {
5958 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5959 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5960 i::Isolate* isolate = jsvalue->GetIsolate();
5961 LOG_API(isolate, "StringObject::StringValue");
5962 return Utils::ToLocal(
5963 i::Handle<i::String>(i::String::cast(jsvalue->value())));
5967 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
5968 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5969 LOG_API(i_isolate, "SymbolObject::New");
5970 ENTER_V8(i_isolate);
5971 i::Handle<i::Object> obj = i::Object::ToObject(
5972 i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
5973 return Utils::ToLocal(obj);
5977 Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
5978 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5979 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5980 i::Isolate* isolate = jsvalue->GetIsolate();
5981 LOG_API(isolate, "SymbolObject::SymbolValue");
5982 return Utils::ToLocal(
5983 i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value())));
5987 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
5988 if (std::isnan(time)) {
5989 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
5990 time = std::numeric_limits<double>::quiet_NaN();
5992 PREPARE_FOR_EXECUTION(context, "Date::New", Value);
5993 Local<Value> result;
5994 has_pending_exception =
5995 !ToLocal<Value>(i::Execution::NewDate(isolate, time), &result);
5996 RETURN_ON_FAILED_EXECUTION(Value);
5997 RETURN_ESCAPED(result);
6001 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
6002 auto context = isolate->GetCurrentContext();
6003 RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value);
6007 double v8::Date::ValueOf() const {
6008 i::Handle<i::Object> obj = Utils::OpenHandle(this);
6009 i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
6010 i::Isolate* isolate = jsdate->GetIsolate();
6011 LOG_API(isolate, "Date::NumberValue");
6012 return jsdate->value()->Number();
6016 void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) {
6017 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6018 LOG_API(i_isolate, "Date::DateTimeConfigurationChangeNotification");
6019 ENTER_V8(i_isolate);
6020 i_isolate->date_cache()->ResetDateCache();
6021 if (!i_isolate->eternal_handles()->Exists(
6022 i::EternalHandles::DATE_CACHE_VERSION)) {
6025 i::Handle<i::FixedArray> date_cache_version =
6026 i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton(
6027 i::EternalHandles::DATE_CACHE_VERSION));
6028 DCHECK_EQ(1, date_cache_version->length());
6029 CHECK(date_cache_version->get(0)->IsSmi());
6030 date_cache_version->set(
6032 i::Smi::FromInt(i::Smi::cast(date_cache_version->get(0))->value() + 1));
6036 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
6037 i::Isolate* isolate = i::Isolate::Current();
6038 uint8_t flags_buf[3];
6040 if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
6041 if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
6042 if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
6043 DCHECK(num_flags <= static_cast<int>(arraysize(flags_buf)));
6044 return isolate->factory()->InternalizeOneByteString(
6045 i::Vector<const uint8_t>(flags_buf, num_flags));
6049 MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context,
6050 Local<String> pattern, Flags flags) {
6051 PREPARE_FOR_EXECUTION(context, "RegExp::New", RegExp);
6052 Local<v8::RegExp> result;
6053 has_pending_exception =
6054 !ToLocal<RegExp>(i::Execution::NewJSRegExp(Utils::OpenHandle(*pattern),
6055 RegExpFlagsToString(flags)),
6057 RETURN_ON_FAILED_EXECUTION(RegExp);
6058 RETURN_ESCAPED(result);
6062 Local<v8::RegExp> v8::RegExp::New(Local<String> pattern, Flags flags) {
6064 reinterpret_cast<Isolate*>(Utils::OpenHandle(*pattern)->GetIsolate());
6065 auto context = isolate->GetCurrentContext();
6066 RETURN_TO_LOCAL_UNCHECKED(New(context, pattern, flags), RegExp);
6070 Local<v8::String> v8::RegExp::GetSource() const {
6071 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6072 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
6076 // Assert that the static flags cast in GetFlags is valid.
6077 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag) \
6078 STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) == \
6079 static_cast<int>(i::JSRegExp::internal_flag))
6080 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
6081 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
6082 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
6083 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
6084 #undef REGEXP_FLAG_ASSERT_EQ
6086 v8::RegExp::Flags v8::RegExp::GetFlags() const {
6087 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6088 return static_cast<RegExp::Flags>(obj->GetFlags().value());
6092 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
6093 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6094 LOG_API(i_isolate, "Array::New");
6095 ENTER_V8(i_isolate);
6096 int real_length = length > 0 ? length : 0;
6097 i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
6098 i::Handle<i::Object> length_obj =
6099 i_isolate->factory()->NewNumberFromInt(real_length);
6100 obj->set_length(*length_obj);
6101 return Utils::ToLocal(obj);
6105 uint32_t v8::Array::Length() const {
6106 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
6107 i::Object* length = obj->length();
6108 if (length->IsSmi()) {
6109 return i::Smi::cast(length)->value();
6111 return static_cast<uint32_t>(length->Number());
6116 MaybeLocal<Object> Array::CloneElementAt(Local<Context> context,
6118 PREPARE_FOR_EXECUTION(context, "v8::Array::CloneElementAt()", Object);
6119 auto self = Utils::OpenHandle(this);
6120 if (!self->HasFastObjectElements()) return Local<Object>();
6121 i::FixedArray* elms = i::FixedArray::cast(self->elements());
6122 i::Object* paragon = elms->get(index);
6123 if (!paragon->IsJSObject()) return Local<Object>();
6124 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
6125 Local<Object> result;
6126 has_pending_exception =
6127 !ToLocal<Object>(isolate->factory()->CopyJSObject(paragon_handle),
6129 RETURN_ON_FAILED_EXECUTION(Object);
6130 RETURN_ESCAPED(result);
6134 Local<Object> Array::CloneElementAt(uint32_t index) {
6135 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6136 RETURN_TO_LOCAL_UNCHECKED(CloneElementAt(context, index), Object);
6140 Local<v8::Map> v8::Map::New(Isolate* isolate) {
6141 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6142 LOG_API(i_isolate, "Map::New");
6143 ENTER_V8(i_isolate);
6144 i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
6145 return Utils::ToLocal(obj);
6149 size_t v8::Map::Size() const {
6150 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6151 return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
6156 auto self = Utils::OpenHandle(this);
6157 i::Isolate* isolate = self->GetIsolate();
6158 LOG_API(isolate, "Map::Clear");
6160 i::Runtime::JSMapClear(isolate, self);
6164 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
6165 PREPARE_FOR_EXECUTION(context, "Map::Get", Value);
6166 auto self = Utils::OpenHandle(this);
6167 Local<Value> result;
6168 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6169 has_pending_exception =
6170 !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
6171 arraysize(argv), argv, false),
6173 RETURN_ON_FAILED_EXECUTION(Value);
6174 RETURN_ESCAPED(result);
6178 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
6179 Local<Value> value) {
6180 PREPARE_FOR_EXECUTION(context, "Map::Set", Map);
6181 auto self = Utils::OpenHandle(this);
6182 i::Handle<i::Object> result;
6183 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
6184 Utils::OpenHandle(*value)};
6185 has_pending_exception =
6186 !i::Execution::Call(isolate, isolate->map_set(), self, arraysize(argv),
6187 argv, false).ToHandle(&result);
6188 RETURN_ON_FAILED_EXECUTION(Map);
6189 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6193 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
6194 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Has", bool);
6195 auto self = Utils::OpenHandle(this);
6196 i::Handle<i::Object> result;
6197 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6198 has_pending_exception =
6199 !i::Execution::Call(isolate, isolate->map_has(), self, arraysize(argv),
6200 argv, false).ToHandle(&result);
6201 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6202 return Just(result->IsTrue());
6206 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
6207 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Delete", bool);
6208 auto self = Utils::OpenHandle(this);
6209 i::Handle<i::Object> result;
6210 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6211 has_pending_exception =
6212 !i::Execution::Call(isolate, isolate->map_delete(), self, arraysize(argv),
6213 argv, false).ToHandle(&result);
6214 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6215 return Just(result->IsTrue());
6219 Local<Array> Map::AsArray() const {
6220 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6221 i::Isolate* isolate = obj->GetIsolate();
6222 i::Factory* factory = isolate->factory();
6223 LOG_API(isolate, "Map::AsArray");
6225 i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(obj->table()));
6226 int size = table->NumberOfElements();
6227 int length = size * 2;
6228 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6229 for (int i = 0; i < size; ++i) {
6230 if (table->KeyAt(i)->IsTheHole()) continue;
6231 result->set(i * 2, table->KeyAt(i));
6232 result->set(i * 2 + 1, table->ValueAt(i));
6234 i::Handle<i::JSArray> result_array =
6235 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6236 return Utils::ToLocal(result_array);
6240 MaybeLocal<Map> Map::FromArray(Local<Context> context, Local<Array> array) {
6241 PREPARE_FOR_EXECUTION(context, "Map::FromArray", Map);
6242 if (array->Length() % 2 != 0) {
6243 return MaybeLocal<Map>();
6245 i::Handle<i::Object> result;
6246 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6247 has_pending_exception =
6248 !i::Execution::Call(isolate, isolate->map_from_array(),
6249 isolate->factory()->undefined_value(),
6250 arraysize(argv), argv, false).ToHandle(&result);
6251 RETURN_ON_FAILED_EXECUTION(Map);
6252 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6256 Local<v8::Set> v8::Set::New(Isolate* isolate) {
6257 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6258 LOG_API(i_isolate, "Set::New");
6259 ENTER_V8(i_isolate);
6260 i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
6261 return Utils::ToLocal(obj);
6265 size_t v8::Set::Size() const {
6266 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6267 return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
6272 auto self = Utils::OpenHandle(this);
6273 i::Isolate* isolate = self->GetIsolate();
6274 LOG_API(isolate, "Set::Clear");
6276 i::Runtime::JSSetClear(isolate, self);
6280 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
6281 PREPARE_FOR_EXECUTION(context, "Set::Add", Set);
6282 auto self = Utils::OpenHandle(this);
6283 i::Handle<i::Object> result;
6284 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6285 has_pending_exception =
6286 !i::Execution::Call(isolate, isolate->set_add(), self, arraysize(argv),
6287 argv, false).ToHandle(&result);
6288 RETURN_ON_FAILED_EXECUTION(Set);
6289 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6293 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
6294 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Has", bool);
6295 auto self = Utils::OpenHandle(this);
6296 i::Handle<i::Object> result;
6297 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6298 has_pending_exception =
6299 !i::Execution::Call(isolate, isolate->set_has(), self, arraysize(argv),
6300 argv, false).ToHandle(&result);
6301 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6302 return Just(result->IsTrue());
6306 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
6307 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Delete", bool);
6308 auto self = Utils::OpenHandle(this);
6309 i::Handle<i::Object> result;
6310 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6311 has_pending_exception =
6312 !i::Execution::Call(isolate, isolate->set_delete(), self, arraysize(argv),
6313 argv, false).ToHandle(&result);
6314 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6315 return Just(result->IsTrue());
6319 Local<Array> Set::AsArray() const {
6320 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6321 i::Isolate* isolate = obj->GetIsolate();
6322 i::Factory* factory = isolate->factory();
6323 LOG_API(isolate, "Set::AsArray");
6325 i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(obj->table()));
6326 int length = table->NumberOfElements();
6327 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6328 for (int i = 0; i < length; ++i) {
6329 i::Object* key = table->KeyAt(i);
6330 if (!key->IsTheHole()) {
6331 result->set(i, key);
6334 i::Handle<i::JSArray> result_array =
6335 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6336 return Utils::ToLocal(result_array);
6340 MaybeLocal<Set> Set::FromArray(Local<Context> context, Local<Array> array) {
6341 PREPARE_FOR_EXECUTION(context, "Set::FromArray", Set);
6342 i::Handle<i::Object> result;
6343 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6344 has_pending_exception =
6345 !i::Execution::Call(isolate, isolate->set_from_array(),
6346 isolate->factory()->undefined_value(),
6347 arraysize(argv), argv, false).ToHandle(&result);
6348 RETURN_ON_FAILED_EXECUTION(Set);
6349 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6353 bool Value::IsPromise() const {
6354 auto self = Utils::OpenHandle(this);
6355 return i::Object::IsPromise(self);
6359 MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) {
6360 PREPARE_FOR_EXECUTION(context, "Promise::Resolver::New", Resolver);
6361 i::Handle<i::Object> result;
6362 has_pending_exception = !i::Execution::Call(
6364 isolate->promise_create(),
6365 isolate->factory()->undefined_value(),
6367 false).ToHandle(&result);
6368 RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
6369 RETURN_ESCAPED(Local<Promise::Resolver>::Cast(Utils::ToLocal(result)));
6373 Local<Promise::Resolver> Promise::Resolver::New(Isolate* isolate) {
6374 RETURN_TO_LOCAL_UNCHECKED(New(isolate->GetCurrentContext()),
6379 Local<Promise> Promise::Resolver::GetPromise() {
6380 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6381 return Local<Promise>::Cast(Utils::ToLocal(promise));
6385 Maybe<bool> Promise::Resolver::Resolve(Local<Context> context,
6386 Local<Value> value) {
6387 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6388 auto self = Utils::OpenHandle(this);
6389 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6390 has_pending_exception = i::Execution::Call(
6392 isolate->promise_resolve(),
6393 isolate->factory()->undefined_value(),
6394 arraysize(argv), argv,
6396 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6401 void Promise::Resolver::Resolve(Local<Value> value) {
6402 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6403 USE(Resolve(context, value));
6407 Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
6408 Local<Value> value) {
6409 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6410 auto self = Utils::OpenHandle(this);
6411 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6412 has_pending_exception = i::Execution::Call(
6414 isolate->promise_reject(),
6415 isolate->factory()->undefined_value(),
6416 arraysize(argv), argv,
6418 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6423 void Promise::Resolver::Reject(Local<Value> value) {
6424 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6425 USE(Reject(context, value));
6429 MaybeLocal<Promise> Promise::Chain(Local<Context> context,
6430 Local<Function> handler) {
6431 PREPARE_FOR_EXECUTION(context, "Promise::Chain", Promise);
6432 auto self = Utils::OpenHandle(this);
6433 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*handler)};
6434 i::Handle<i::Object> result;
6435 has_pending_exception =
6436 !i::Execution::Call(isolate, isolate->promise_chain(), self,
6437 arraysize(argv), argv, false).ToHandle(&result);
6438 RETURN_ON_FAILED_EXECUTION(Promise);
6439 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6443 Local<Promise> Promise::Chain(Local<Function> handler) {
6444 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6445 RETURN_TO_LOCAL_UNCHECKED(Chain(context, handler), Promise);
6449 MaybeLocal<Promise> Promise::Catch(Local<Context> context,
6450 Local<Function> handler) {
6451 PREPARE_FOR_EXECUTION(context, "Promise::Catch", Promise);
6452 auto self = Utils::OpenHandle(this);
6453 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6454 i::Handle<i::Object> result;
6455 has_pending_exception =
6456 !i::Execution::Call(isolate, isolate->promise_catch(), self,
6457 arraysize(argv), argv, false).ToHandle(&result);
6458 RETURN_ON_FAILED_EXECUTION(Promise);
6459 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6463 Local<Promise> Promise::Catch(Local<Function> handler) {
6464 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6465 RETURN_TO_LOCAL_UNCHECKED(Catch(context, handler), Promise);
6469 MaybeLocal<Promise> Promise::Then(Local<Context> context,
6470 Local<Function> handler) {
6471 PREPARE_FOR_EXECUTION(context, "Promise::Then", Promise);
6472 auto self = Utils::OpenHandle(this);
6473 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6474 i::Handle<i::Object> result;
6475 has_pending_exception =
6476 !i::Execution::Call(isolate, isolate->promise_then(), self,
6477 arraysize(argv), argv, false).ToHandle(&result);
6478 RETURN_ON_FAILED_EXECUTION(Promise);
6479 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6483 Local<Promise> Promise::Then(Local<Function> handler) {
6484 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6485 RETURN_TO_LOCAL_UNCHECKED(Then(context, handler), Promise);
6489 bool Promise::HasHandler() {
6490 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6491 i::Isolate* isolate = promise->GetIsolate();
6492 LOG_API(isolate, "Promise::HasRejectHandler");
6494 i::Handle<i::Symbol> key = isolate->factory()->promise_has_handler_symbol();
6495 return i::JSReceiver::GetDataProperty(promise, key)->IsTrue();
6499 bool v8::ArrayBuffer::IsExternal() const {
6500 return Utils::OpenHandle(this)->is_external();
6504 bool v8::ArrayBuffer::IsNeuterable() const {
6505 return Utils::OpenHandle(this)->is_neuterable();
6509 v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
6510 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6511 i::Isolate* isolate = self->GetIsolate();
6512 Utils::ApiCheck(!self->is_external(), "v8::ArrayBuffer::Externalize",
6513 "ArrayBuffer already externalized");
6514 self->set_is_external(true);
6515 isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6516 self->backing_store());
6518 return GetContents();
6522 v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() {
6523 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6524 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6526 contents.data_ = self->backing_store();
6527 contents.byte_length_ = byte_length;
6532 void v8::ArrayBuffer::Neuter() {
6533 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6534 i::Isolate* isolate = obj->GetIsolate();
6535 Utils::ApiCheck(obj->is_external(),
6536 "v8::ArrayBuffer::Neuter",
6537 "Only externalized ArrayBuffers can be neutered");
6538 Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter",
6539 "Only neuterable ArrayBuffers can be neutered");
6540 LOG_API(obj->GetIsolate(), "v8::ArrayBuffer::Neuter()");
6542 i::Runtime::NeuterArrayBuffer(obj);
6546 size_t v8::ArrayBuffer::ByteLength() const {
6547 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6548 return static_cast<size_t>(obj->byte_length()->Number());
6552 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
6553 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6554 LOG_API(i_isolate, "v8::ArrayBuffer::New(size_t)");
6555 ENTER_V8(i_isolate);
6556 i::Handle<i::JSArrayBuffer> obj =
6557 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6558 i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length);
6559 return Utils::ToLocal(obj);
6563 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
6565 ArrayBufferCreationMode mode) {
6566 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6567 LOG_API(i_isolate, "v8::ArrayBuffer::New(void*, size_t)");
6568 ENTER_V8(i_isolate);
6569 i::Handle<i::JSArrayBuffer> obj =
6570 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6571 i::Runtime::SetupArrayBuffer(i_isolate, obj,
6572 mode == ArrayBufferCreationMode::kExternalized,
6574 return Utils::ToLocal(obj);
6578 Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
6579 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6580 i::Handle<i::JSArrayBuffer> buffer;
6581 if (obj->IsJSDataView()) {
6582 i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj));
6583 DCHECK(data_view->buffer()->IsJSArrayBuffer());
6584 buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()));
6586 DCHECK(obj->IsJSTypedArray());
6587 buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
6589 return Utils::ToLocal(buffer);
6593 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
6594 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6595 i::Isolate* isolate = self->GetIsolate();
6596 size_t byte_offset = i::NumberToSize(isolate, self->byte_offset());
6597 size_t bytes_to_copy =
6598 i::Min(byte_length, i::NumberToSize(isolate, self->byte_length()));
6599 if (bytes_to_copy) {
6600 i::DisallowHeapAllocation no_gc;
6601 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6602 const char* source = reinterpret_cast<char*>(buffer->backing_store());
6603 if (source == nullptr) {
6604 DCHECK(self->IsJSTypedArray());
6605 i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self));
6606 i::Handle<i::FixedTypedArrayBase> fixed_array(
6607 i::FixedTypedArrayBase::cast(typed_array->elements()));
6608 source = reinterpret_cast<char*>(fixed_array->DataPtr());
6610 memcpy(dest, source + byte_offset, bytes_to_copy);
6612 return bytes_to_copy;
6616 bool v8::ArrayBufferView::HasBuffer() const {
6617 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6618 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6619 return buffer->backing_store() != nullptr;
6623 size_t v8::ArrayBufferView::ByteOffset() {
6624 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6625 return static_cast<size_t>(obj->byte_offset()->Number());
6629 size_t v8::ArrayBufferView::ByteLength() {
6630 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6631 return static_cast<size_t>(obj->byte_length()->Number());
6635 size_t v8::TypedArray::Length() {
6636 i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
6637 return static_cast<size_t>(obj->length_value());
6641 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype, size) \
6642 Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer, \
6643 size_t byte_offset, size_t length) { \
6644 i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate(); \
6646 "v8::" #Type "Array::New(Local<ArrayBuffer>, size_t, size_t)"); \
6647 ENTER_V8(isolate); \
6648 if (!Utils::ApiCheck(length <= static_cast<size_t>(i::Smi::kMaxValue), \
6650 "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
6651 "length exceeds max allowed value")) { \
6652 return Local<Type##Array>(); \
6654 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \
6655 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6656 i::kExternal##Type##Array, buffer, byte_offset, length); \
6657 return Utils::ToLocal##Type##Array(obj); \
6659 Local<Type##Array> Type##Array::New( \
6660 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, \
6662 CHECK(i::FLAG_harmony_sharedarraybuffer); \
6663 i::Isolate* isolate = \
6664 Utils::OpenHandle(*shared_array_buffer)->GetIsolate(); \
6665 LOG_API(isolate, "v8::" #Type \
6666 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)"); \
6667 ENTER_V8(isolate); \
6668 if (!Utils::ApiCheck( \
6669 length <= static_cast<size_t>(i::Smi::kMaxValue), \
6671 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)", \
6672 "length exceeds max allowed value")) { \
6673 return Local<Type##Array>(); \
6675 i::Handle<i::JSArrayBuffer> buffer = \
6676 Utils::OpenHandle(*shared_array_buffer); \
6677 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6678 i::kExternal##Type##Array, buffer, byte_offset, length); \
6679 return Utils::ToLocal##Type##Array(obj); \
6683 TYPED_ARRAYS(TYPED_ARRAY_NEW)
6684 #undef TYPED_ARRAY_NEW
6686 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
6687 size_t byte_offset, size_t byte_length) {
6688 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
6689 i::Isolate* isolate = buffer->GetIsolate();
6690 LOG_API(isolate, "v8::DataView::New(Local<ArrayBuffer>, size_t, size_t)");
6692 i::Handle<i::JSDataView> obj =
6693 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6694 return Utils::ToLocal(obj);
6698 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
6699 size_t byte_offset, size_t byte_length) {
6700 CHECK(i::FLAG_harmony_sharedarraybuffer);
6701 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
6702 i::Isolate* isolate = buffer->GetIsolate();
6704 "v8::DataView::New(Local<SharedArrayBuffer>, size_t, size_t)");
6706 i::Handle<i::JSDataView> obj =
6707 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6708 return Utils::ToLocal(obj);
6712 bool v8::SharedArrayBuffer::IsExternal() const {
6713 return Utils::OpenHandle(this)->is_external();
6717 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
6718 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6719 i::Isolate* isolate = self->GetIsolate();
6720 Utils::ApiCheck(!self->is_external(), "v8::SharedArrayBuffer::Externalize",
6721 "SharedArrayBuffer already externalized");
6722 self->set_is_external(true);
6723 isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6724 self->backing_store());
6725 return GetContents();
6729 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
6730 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6731 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6733 contents.data_ = self->backing_store();
6734 contents.byte_length_ = byte_length;
6739 size_t v8::SharedArrayBuffer::ByteLength() const {
6740 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6741 return static_cast<size_t>(obj->byte_length()->Number());
6745 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate,
6746 size_t byte_length) {
6747 CHECK(i::FLAG_harmony_sharedarraybuffer);
6748 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6749 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(size_t)");
6750 ENTER_V8(i_isolate);
6751 i::Handle<i::JSArrayBuffer> obj =
6752 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6753 i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length, true,
6754 i::SharedFlag::kShared);
6755 return Utils::ToLocalShared(obj);
6759 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
6760 Isolate* isolate, void* data, size_t byte_length,
6761 ArrayBufferCreationMode mode) {
6762 CHECK(i::FLAG_harmony_sharedarraybuffer);
6763 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6764 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(void*, size_t)");
6765 ENTER_V8(i_isolate);
6766 i::Handle<i::JSArrayBuffer> obj =
6767 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6768 i::Runtime::SetupArrayBuffer(i_isolate, obj,
6769 mode == ArrayBufferCreationMode::kExternalized,
6770 data, byte_length, i::SharedFlag::kShared);
6771 return Utils::ToLocalShared(obj);
6775 Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
6776 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6777 LOG_API(i_isolate, "Symbol::New()");
6778 ENTER_V8(i_isolate);
6779 i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
6780 if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
6781 return Utils::ToLocal(result);
6785 static i::Handle<i::Symbol> SymbolFor(i::Isolate* isolate,
6786 i::Handle<i::String> name,
6787 i::Handle<i::String> part) {
6788 i::Handle<i::JSObject> registry = isolate->GetSymbolRegistry();
6789 i::Handle<i::JSObject> symbols =
6790 i::Handle<i::JSObject>::cast(
6791 i::Object::GetPropertyOrElement(registry, part).ToHandleChecked());
6792 i::Handle<i::Object> symbol =
6793 i::Object::GetPropertyOrElement(symbols, name).ToHandleChecked();
6794 if (!symbol->IsSymbol()) {
6795 DCHECK(symbol->IsUndefined());
6796 symbol = isolate->factory()->NewSymbol();
6797 i::Handle<i::Symbol>::cast(symbol)->set_name(*name);
6798 i::JSObject::SetProperty(symbols, name, symbol, i::STRICT).Assert();
6800 return i::Handle<i::Symbol>::cast(symbol);
6804 Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
6805 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6806 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6807 i::Handle<i::String> part = i_isolate->factory()->for_string();
6808 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6812 Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
6813 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6814 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6815 i::Handle<i::String> part = i_isolate->factory()->for_api_string();
6816 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6820 Local<Symbol> v8::Symbol::GetIterator(Isolate* isolate) {
6821 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6822 return Utils::ToLocal(i_isolate->factory()->iterator_symbol());
6826 Local<Symbol> v8::Symbol::GetUnscopables(Isolate* isolate) {
6827 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6828 return Utils::ToLocal(i_isolate->factory()->unscopables_symbol());
6832 Local<Symbol> v8::Symbol::GetToStringTag(Isolate* isolate) {
6833 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6834 return Utils::ToLocal(i_isolate->factory()->to_string_tag_symbol());
6838 Local<Number> v8::Number::New(Isolate* isolate, double value) {
6839 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6840 if (std::isnan(value)) {
6841 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6842 value = std::numeric_limits<double>::quiet_NaN();
6844 ENTER_V8(internal_isolate);
6845 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6846 return Utils::NumberToLocal(result);
6850 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
6851 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6852 if (i::Smi::IsValid(value)) {
6853 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
6856 ENTER_V8(internal_isolate);
6857 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6858 return Utils::IntegerToLocal(result);
6862 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
6863 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6864 bool fits_into_int32_t = (value & (1 << 31)) == 0;
6865 if (fits_into_int32_t) {
6866 return Integer::New(isolate, static_cast<int32_t>(value));
6868 ENTER_V8(internal_isolate);
6869 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6870 return Utils::IntegerToLocal(result);
6874 void Isolate::CollectAllGarbage(const char* gc_reason) {
6875 i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
6876 if (heap->incremental_marking()->IsStopped()) {
6877 if (heap->incremental_marking()->CanBeActivated()) {
6878 heap->StartIncrementalMarking(
6879 i::Heap::kNoGCFlags,
6880 kGCCallbackFlagSynchronousPhantomCallbackProcessing, gc_reason);
6882 heap->CollectAllGarbage(
6883 i::Heap::kNoGCFlags, gc_reason,
6884 kGCCallbackFlagSynchronousPhantomCallbackProcessing);
6887 // Incremental marking is turned on an has already been started.
6889 // TODO(mlippautz): Compute the time slice for incremental marking based on
6891 double deadline = heap->MonotonicallyIncreasingTimeInMs() +
6892 i::FLAG_external_allocation_limit_incremental_time;
6893 heap->AdvanceIncrementalMarking(
6894 0, deadline, i::IncrementalMarking::StepActions(
6895 i::IncrementalMarking::GC_VIA_STACK_GUARD,
6896 i::IncrementalMarking::FORCE_MARKING,
6897 i::IncrementalMarking::FORCE_COMPLETION));
6902 HeapProfiler* Isolate::GetHeapProfiler() {
6903 i::HeapProfiler* heap_profiler =
6904 reinterpret_cast<i::Isolate*>(this)->heap_profiler();
6905 return reinterpret_cast<HeapProfiler*>(heap_profiler);
6909 CpuProfiler* Isolate::GetCpuProfiler() {
6910 i::CpuProfiler* cpu_profiler =
6911 reinterpret_cast<i::Isolate*>(this)->cpu_profiler();
6912 return reinterpret_cast<CpuProfiler*>(cpu_profiler);
6916 bool Isolate::InContext() {
6917 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6918 return isolate->context() != NULL;
6922 v8::Local<v8::Context> Isolate::GetCurrentContext() {
6923 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6924 i::Context* context = isolate->context();
6925 if (context == NULL) return Local<Context>();
6926 i::Context* native_context = context->native_context();
6927 if (native_context == NULL) return Local<Context>();
6928 return Utils::ToLocal(i::Handle<i::Context>(native_context));
6932 v8::Local<v8::Context> Isolate::GetCallingContext() {
6933 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6934 i::Handle<i::Object> calling = isolate->GetCallingNativeContext();
6935 if (calling.is_null()) return Local<Context>();
6936 return Utils::ToLocal(i::Handle<i::Context>::cast(calling));
6940 v8::Local<v8::Context> Isolate::GetEnteredContext() {
6941 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6942 i::Handle<i::Object> last =
6943 isolate->handle_scope_implementer()->LastEnteredContext();
6944 if (last.is_null()) return Local<Context>();
6945 return Utils::ToLocal(i::Handle<i::Context>::cast(last));
6949 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
6950 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6952 // If we're passed an empty handle, we throw an undefined exception
6953 // to deal more gracefully with out of memory situations.
6954 if (value.IsEmpty()) {
6955 isolate->ScheduleThrow(isolate->heap()->undefined_value());
6957 isolate->ScheduleThrow(*Utils::OpenHandle(*value));
6959 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
6963 void Isolate::SetObjectGroupId(internal::Object** object, UniqueId id) {
6964 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6965 internal_isolate->global_handles()->SetObjectGroupId(
6966 v8::internal::Handle<v8::internal::Object>(object).location(),
6971 void Isolate::SetReferenceFromGroup(UniqueId id, internal::Object** object) {
6972 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6973 internal_isolate->global_handles()->SetReferenceFromGroup(
6975 v8::internal::Handle<v8::internal::Object>(object).location());
6979 void Isolate::SetReference(internal::Object** parent,
6980 internal::Object** child) {
6981 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6982 i::Object** parent_location =
6983 v8::internal::Handle<v8::internal::Object>(parent).location();
6984 internal_isolate->global_handles()->SetReference(
6985 reinterpret_cast<i::HeapObject**>(parent_location),
6986 v8::internal::Handle<v8::internal::Object>(child).location());
6990 void Isolate::AddGCPrologueCallback(GCPrologueCallback callback,
6992 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6993 isolate->heap()->AddGCPrologueCallback(callback, gc_type);
6997 void Isolate::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6998 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6999 isolate->heap()->RemoveGCPrologueCallback(callback);
7003 void Isolate::AddGCEpilogueCallback(GCEpilogueCallback callback,
7005 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7006 isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
7010 void Isolate::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
7011 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7012 isolate->heap()->RemoveGCEpilogueCallback(callback);
7016 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
7017 i::Isolate* isolate = i::Isolate::Current();
7018 isolate->heap()->AddGCPrologueCallback(
7019 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback),
7025 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
7026 i::Isolate* isolate = i::Isolate::Current();
7027 isolate->heap()->AddGCEpilogueCallback(
7028 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback),
7034 void Isolate::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
7036 AllocationAction action) {
7037 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7038 isolate->memory_allocator()->AddMemoryAllocationCallback(
7039 callback, space, action);
7043 void Isolate::RemoveMemoryAllocationCallback(
7044 MemoryAllocationCallback callback) {
7045 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7046 isolate->memory_allocator()->RemoveMemoryAllocationCallback(
7051 void Isolate::TerminateExecution() {
7052 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7053 isolate->stack_guard()->RequestTerminateExecution();
7057 bool Isolate::IsExecutionTerminating() {
7058 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7059 return IsExecutionTerminatingCheck(isolate);
7063 void Isolate::CancelTerminateExecution() {
7064 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7065 isolate->stack_guard()->ClearTerminateExecution();
7066 isolate->CancelTerminateExecution();
7070 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
7071 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7072 isolate->RequestInterrupt(callback, data);
7076 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
7077 CHECK(i::FLAG_expose_gc);
7078 if (type == kMinorGarbageCollection) {
7079 reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
7080 i::NEW_SPACE, "Isolate::RequestGarbageCollection",
7081 kGCCallbackFlagForced);
7083 DCHECK_EQ(kFullGarbageCollection, type);
7084 reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
7085 i::Heap::kAbortIncrementalMarkingMask,
7086 "Isolate::RequestGarbageCollection", kGCCallbackFlagForced);
7091 Isolate* Isolate::GetCurrent() {
7092 i::Isolate* isolate = i::Isolate::Current();
7093 return reinterpret_cast<Isolate*>(isolate);
7097 Isolate* Isolate::New(const Isolate::CreateParams& params) {
7098 i::Isolate* isolate = new i::Isolate(false);
7099 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7100 CHECK(params.array_buffer_allocator != NULL);
7101 isolate->set_array_buffer_allocator(params.array_buffer_allocator);
7102 if (params.snapshot_blob != NULL) {
7103 isolate->set_snapshot_blob(params.snapshot_blob);
7105 isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
7107 if (params.entry_hook) {
7108 isolate->set_function_entry_hook(params.entry_hook);
7110 if (params.code_event_handler) {
7111 isolate->InitializeLoggingAndCounters();
7112 isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
7113 params.code_event_handler);
7115 if (params.counter_lookup_callback) {
7116 v8_isolate->SetCounterFunction(params.counter_lookup_callback);
7119 if (params.create_histogram_callback) {
7120 v8_isolate->SetCreateHistogramFunction(params.create_histogram_callback);
7123 if (params.add_histogram_sample_callback) {
7124 v8_isolate->SetAddHistogramSampleFunction(
7125 params.add_histogram_sample_callback);
7127 SetResourceConstraints(isolate, params.constraints);
7128 // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
7129 Isolate::Scope isolate_scope(v8_isolate);
7130 if (params.entry_hook || !i::Snapshot::Initialize(isolate)) {
7131 // If the isolate has a function entry hook, it needs to re-build all its
7132 // code stubs with entry hooks embedded, so don't deserialize a snapshot.
7133 if (i::Snapshot::EmbedsScript(isolate)) {
7134 // If the snapshot embeds a script, we cannot initialize the isolate
7135 // without the snapshot as a fallback. This is unlikely to happen though.
7136 V8_Fatal(__FILE__, __LINE__,
7137 "Initializing isolate from custom startup snapshot failed");
7139 isolate->Init(NULL);
7145 void Isolate::Dispose() {
7146 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7147 if (!Utils::ApiCheck(!isolate->IsInUse(),
7148 "v8::Isolate::Dispose()",
7149 "Disposing the isolate that is entered by a thread.")) {
7152 isolate->TearDown();
7156 void Isolate::Enter() {
7157 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7162 void Isolate::Exit() {
7163 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7168 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
7170 Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
7171 : on_failure_(on_failure) {
7172 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7173 if (on_failure_ == CRASH_ON_FAILURE) {
7174 internal_ = reinterpret_cast<void*>(
7175 new i::DisallowJavascriptExecution(i_isolate));
7177 DCHECK_EQ(THROW_ON_FAILURE, on_failure);
7178 internal_ = reinterpret_cast<void*>(
7179 new i::ThrowOnJavascriptExecution(i_isolate));
7184 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
7185 if (on_failure_ == CRASH_ON_FAILURE) {
7186 delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
7188 delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
7193 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
7195 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7196 internal_assert_ = reinterpret_cast<void*>(
7197 new i::AllowJavascriptExecution(i_isolate));
7198 internal_throws_ = reinterpret_cast<void*>(
7199 new i::NoThrowOnJavascriptExecution(i_isolate));
7203 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
7204 delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
7205 delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
7209 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
7211 : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
7212 isolate_->handle_scope_implementer()->IncrementCallDepth();
7216 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
7217 isolate_->handle_scope_implementer()->DecrementCallDepth();
7221 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
7222 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7223 i::Heap* heap = isolate->heap();
7224 heap_statistics->total_heap_size_ = heap->CommittedMemory();
7225 heap_statistics->total_heap_size_executable_ =
7226 heap->CommittedMemoryExecutable();
7227 heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
7228 heap_statistics->total_available_size_ = heap->Available();
7229 heap_statistics->used_heap_size_ = heap->SizeOfObjects();
7230 heap_statistics->heap_size_limit_ = heap->MaxReserved();
7234 size_t Isolate::NumberOfHeapSpaces() {
7235 return i::LAST_SPACE - i::FIRST_SPACE + 1;
7239 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7241 if (!space_statistics) return false;
7242 if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
7245 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7246 i::Heap* heap = isolate->heap();
7247 i::Space* space = heap->space(static_cast<int>(index));
7249 space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
7250 space_statistics->space_size_ = space->CommittedMemory();
7251 space_statistics->space_used_size_ = space->SizeOfObjects();
7252 space_statistics->space_available_size_ = space->Available();
7253 space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
7258 size_t Isolate::NumberOfTrackedHeapObjectTypes() {
7259 return i::Heap::OBJECT_STATS_COUNT;
7263 bool Isolate::GetHeapObjectStatisticsAtLastGC(
7264 HeapObjectStatistics* object_statistics, size_t type_index) {
7265 if (!object_statistics) return false;
7266 if (type_index >= i::Heap::OBJECT_STATS_COUNT) return false;
7267 if (!i::FLAG_track_gc_object_stats) return false;
7269 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7270 i::Heap* heap = isolate->heap();
7271 const char* object_type;
7272 const char* object_sub_type;
7273 size_t object_count = heap->object_count_last_gc(type_index);
7274 size_t object_size = heap->object_size_last_gc(type_index);
7275 if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
7276 // There should be no objects counted when the type is unknown.
7277 DCHECK_EQ(object_count, 0U);
7278 DCHECK_EQ(object_size, 0U);
7282 object_statistics->object_type_ = object_type;
7283 object_statistics->object_sub_type_ = object_sub_type;
7284 object_statistics->object_count_ = object_count;
7285 object_statistics->object_size_ = object_size;
7290 void Isolate::GetStackSample(const RegisterState& state, void** frames,
7291 size_t frames_limit, SampleInfo* sample_info) {
7292 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7293 i::TickSample::GetStackSample(isolate, state, i::TickSample::kSkipCEntryFrame,
7294 frames, frames_limit, sample_info);
7298 void Isolate::SetEventLogger(LogEventCallback that) {
7299 // Do not overwrite the event logger if we want to log explicitly.
7300 if (i::FLAG_log_internal_timer_events) return;
7301 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7302 isolate->set_event_logger(that);
7306 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
7307 if (callback == NULL) return;
7308 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7309 isolate->AddCallCompletedCallback(callback);
7313 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
7314 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7315 isolate->RemoveCallCompletedCallback(callback);
7319 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
7320 if (callback == NULL) return;
7321 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7322 isolate->SetPromiseRejectCallback(callback);
7326 void Isolate::RunMicrotasks() {
7327 reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
7331 void Isolate::EnqueueMicrotask(Local<Function> microtask) {
7332 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7333 isolate->EnqueueMicrotask(Utils::OpenHandle(*microtask));
7337 void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) {
7338 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7339 i::HandleScope scope(isolate);
7340 i::Handle<i::CallHandlerInfo> callback_info =
7341 i::Handle<i::CallHandlerInfo>::cast(
7342 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE));
7343 SET_FIELD_WRAPPED(callback_info, set_callback, microtask);
7344 SET_FIELD_WRAPPED(callback_info, set_data, data);
7345 isolate->EnqueueMicrotask(callback_info);
7349 void Isolate::SetAutorunMicrotasks(bool autorun) {
7350 reinterpret_cast<i::Isolate*>(this)->set_autorun_microtasks(autorun);
7354 bool Isolate::WillAutorunMicrotasks() const {
7355 return reinterpret_cast<const i::Isolate*>(this)->autorun_microtasks();
7359 void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
7360 reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
7364 void Isolate::SetCounterFunction(CounterLookupCallback callback) {
7365 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7366 isolate->stats_table()->SetCounterFunction(callback);
7367 isolate->InitializeLoggingAndCounters();
7368 isolate->counters()->ResetCounters();
7372 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
7373 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7374 isolate->stats_table()->SetCreateHistogramFunction(callback);
7375 isolate->InitializeLoggingAndCounters();
7376 isolate->counters()->ResetHistograms();
7380 void Isolate::SetAddHistogramSampleFunction(
7381 AddHistogramSampleCallback callback) {
7382 reinterpret_cast<i::Isolate*>(this)
7384 ->SetAddHistogramSampleFunction(callback);
7388 bool Isolate::IdleNotification(int idle_time_in_ms) {
7389 // Returning true tells the caller that it need not
7390 // continue to call IdleNotification.
7391 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7392 if (!i::FLAG_use_idle_notification) return true;
7393 return isolate->heap()->IdleNotification(idle_time_in_ms);
7397 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
7398 // Returning true tells the caller that it need not
7399 // continue to call IdleNotification.
7400 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7401 if (!i::FLAG_use_idle_notification) return true;
7402 return isolate->heap()->IdleNotification(deadline_in_seconds);
7406 void Isolate::LowMemoryNotification() {
7407 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7409 i::HistogramTimerScope idle_notification_scope(
7410 isolate->counters()->gc_low_memory_notification());
7411 isolate->heap()->CollectAllAvailableGarbage("low memory notification");
7416 int Isolate::ContextDisposedNotification(bool dependant_context) {
7417 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7418 return isolate->heap()->NotifyContextDisposed(dependant_context);
7422 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
7423 JitCodeEventHandler event_handler) {
7424 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7425 // Ensure that logging is initialized for our isolate.
7426 isolate->InitializeLoggingAndCounters();
7427 isolate->logger()->SetCodeEventHandler(options, event_handler);
7431 void Isolate::SetStackLimit(uintptr_t stack_limit) {
7432 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7434 isolate->stack_guard()->SetStackLimit(stack_limit);
7438 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
7439 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7440 if (isolate->code_range()->valid()) {
7441 *start = isolate->code_range()->start();
7442 *length_in_bytes = isolate->code_range()->size();
7445 *length_in_bytes = 0;
7450 void Isolate::SetFatalErrorHandler(FatalErrorCallback that) {
7451 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7452 isolate->set_exception_behavior(that);
7456 void Isolate::SetAllowCodeGenerationFromStringsCallback(
7457 AllowCodeGenerationFromStringsCallback callback) {
7458 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7459 isolate->set_allow_code_gen_callback(callback);
7463 bool Isolate::IsDead() {
7464 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7465 return isolate->IsDead();
7469 bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
7470 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7472 i::HandleScope scope(isolate);
7473 NeanderArray listeners(isolate->factory()->message_listeners());
7474 NeanderObject obj(isolate, 2);
7475 obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
7476 obj.set(1, data.IsEmpty() ? isolate->heap()->undefined_value()
7477 : *Utils::OpenHandle(*data));
7478 listeners.add(isolate, obj.value());
7483 void Isolate::RemoveMessageListeners(MessageCallback that) {
7484 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7486 i::HandleScope scope(isolate);
7487 NeanderArray listeners(isolate->factory()->message_listeners());
7488 for (int i = 0; i < listeners.length(); i++) {
7489 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
7491 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
7492 i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
7493 if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
7494 listeners.set(i, isolate->heap()->undefined_value());
7500 void Isolate::SetFailedAccessCheckCallbackFunction(
7501 FailedAccessCheckCallback callback) {
7502 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7503 isolate->SetFailedAccessCheckCallback(callback);
7507 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
7508 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7509 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7510 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7515 void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) {
7516 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7517 isolate->heap()->VisitExternalResources(visitor);
7521 class VisitorAdapter : public i::ObjectVisitor {
7523 explicit VisitorAdapter(PersistentHandleVisitor* visitor)
7524 : visitor_(visitor) {}
7525 virtual void VisitPointers(i::Object** start, i::Object** end) {
7528 virtual void VisitEmbedderReference(i::Object** p, uint16_t class_id) {
7529 Value* value = ToApi<Value>(i::Handle<i::Object>(p));
7530 visitor_->VisitPersistentHandle(
7531 reinterpret_cast<Persistent<Value>*>(&value), class_id);
7535 PersistentHandleVisitor* visitor_;
7539 void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
7540 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7541 i::DisallowHeapAllocation no_allocation;
7542 VisitorAdapter visitor_adapter(visitor);
7543 isolate->global_handles()->IterateAllRootsWithClassIds(&visitor_adapter);
7547 void Isolate::VisitHandlesForPartialDependence(
7548 PersistentHandleVisitor* visitor) {
7549 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7550 i::DisallowHeapAllocation no_allocation;
7551 VisitorAdapter visitor_adapter(visitor);
7552 isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds(
7557 String::Utf8Value::Utf8Value(v8::Local<v8::Value> obj)
7558 : str_(NULL), length_(0) {
7559 if (obj.IsEmpty()) return;
7560 i::Isolate* isolate = i::Isolate::Current();
7561 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7563 i::HandleScope scope(isolate);
7564 Local<Context> context = v8_isolate->GetCurrentContext();
7565 TryCatch try_catch(v8_isolate);
7567 if (!obj->ToString(context).ToLocal(&str)) return;
7568 i::Handle<i::String> i_str = Utils::OpenHandle(*str);
7569 length_ = v8::Utf8Length(*i_str, isolate);
7570 str_ = i::NewArray<char>(length_ + 1);
7571 str->WriteUtf8(str_);
7575 String::Utf8Value::~Utf8Value() {
7576 i::DeleteArray(str_);
7580 String::Value::Value(v8::Local<v8::Value> obj) : str_(NULL), length_(0) {
7581 if (obj.IsEmpty()) return;
7582 i::Isolate* isolate = i::Isolate::Current();
7583 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7585 i::HandleScope scope(isolate);
7586 Local<Context> context = v8_isolate->GetCurrentContext();
7587 TryCatch try_catch(v8_isolate);
7589 if (!obj->ToString(context).ToLocal(&str)) return;
7590 length_ = str->Length();
7591 str_ = i::NewArray<uint16_t>(length_ + 1);
7596 String::Value::~Value() {
7597 i::DeleteArray(str_);
7601 #define DEFINE_ERROR(NAME, name) \
7602 Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) { \
7603 i::Isolate* isolate = i::Isolate::Current(); \
7604 LOG_API(isolate, #NAME); \
7605 ENTER_V8(isolate); \
7608 i::HandleScope scope(isolate); \
7609 i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \
7610 i::Handle<i::JSFunction> constructor = isolate->name##_function(); \
7611 error = *isolate->factory()->NewError(constructor, message); \
7613 i::Handle<i::Object> result(error, isolate); \
7614 return Utils::ToLocal(result); \
7617 DEFINE_ERROR(RangeError, range_error)
7618 DEFINE_ERROR(ReferenceError, reference_error)
7619 DEFINE_ERROR(SyntaxError, syntax_error)
7620 DEFINE_ERROR(TypeError, type_error)
7621 DEFINE_ERROR(Error, error)
7626 Local<Message> Exception::CreateMessage(Local<Value> exception) {
7627 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7628 if (!obj->IsHeapObject()) return Local<Message>();
7629 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
7631 i::HandleScope scope(isolate);
7632 return Utils::MessageToLocal(
7633 scope.CloseAndEscape(isolate->CreateMessage(obj, NULL)));
7637 Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) {
7638 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7639 if (!obj->IsJSObject()) return Local<StackTrace>();
7640 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
7641 i::Isolate* isolate = js_obj->GetIsolate();
7643 return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj));
7647 // --- D e b u g S u p p o r t ---
7649 bool Debug::SetDebugEventListener(EventCallback that, Local<Value> data) {
7650 i::Isolate* isolate = i::Isolate::Current();
7652 i::HandleScope scope(isolate);
7653 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
7655 foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
7657 isolate->debug()->SetEventListener(foreign,
7658 Utils::OpenHandle(*data, true));
7663 void Debug::DebugBreak(Isolate* isolate) {
7664 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->RequestDebugBreak();
7668 void Debug::CancelDebugBreak(Isolate* isolate) {
7669 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7670 internal_isolate->stack_guard()->ClearDebugBreak();
7674 bool Debug::CheckDebugBreak(Isolate* isolate) {
7675 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7676 return internal_isolate->stack_guard()->CheckDebugBreak();
7680 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
7681 i::Isolate* isolate = i::Isolate::Current();
7683 isolate->debug()->SetMessageHandler(handler);
7687 void Debug::SendCommand(Isolate* isolate,
7688 const uint16_t* command,
7690 ClientData* client_data) {
7691 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7692 internal_isolate->debug()->EnqueueCommandMessage(
7693 i::Vector<const uint16_t>(command, length), client_data);
7697 MaybeLocal<Value> Debug::Call(Local<Context> context,
7698 v8::Local<v8::Function> fun,
7699 v8::Local<v8::Value> data) {
7700 PREPARE_FOR_EXECUTION(context, "v8::Debug::Call()", Value);
7701 i::Handle<i::Object> data_obj;
7702 if (data.IsEmpty()) {
7703 data_obj = isolate->factory()->undefined_value();
7705 data_obj = Utils::OpenHandle(*data);
7707 Local<Value> result;
7708 has_pending_exception =
7709 !ToLocal<Value>(isolate->debug()->Call(Utils::OpenHandle(*fun), data_obj),
7711 RETURN_ON_FAILED_EXECUTION(Value);
7712 RETURN_ESCAPED(result);
7716 Local<Value> Debug::Call(v8::Local<v8::Function> fun,
7717 v8::Local<v8::Value> data) {
7718 auto context = ContextFromHeapObject(Utils::OpenHandle(*fun));
7719 RETURN_TO_LOCAL_UNCHECKED(Call(context, fun, data), Value);
7723 MaybeLocal<Value> Debug::GetMirror(Local<Context> context,
7724 v8::Local<v8::Value> obj) {
7725 PREPARE_FOR_EXECUTION(context, "v8::Debug::GetMirror()", Value);
7726 i::Debug* isolate_debug = isolate->debug();
7727 has_pending_exception = !isolate_debug->Load();
7728 RETURN_ON_FAILED_EXECUTION(Value);
7729 i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global_object());
7730 auto name = isolate->factory()->NewStringFromStaticChars("MakeMirror");
7731 auto fun_obj = i::Object::GetProperty(debug, name).ToHandleChecked();
7732 auto v8_fun = Utils::ToLocal(i::Handle<i::JSFunction>::cast(fun_obj));
7733 const int kArgc = 1;
7734 v8::Local<v8::Value> argv[kArgc] = {obj};
7735 Local<Value> result;
7736 has_pending_exception = !v8_fun->Call(context, Utils::ToLocal(debug), kArgc,
7737 argv).ToLocal(&result);
7738 RETURN_ON_FAILED_EXECUTION(Value);
7739 RETURN_ESCAPED(result);
7743 Local<Value> Debug::GetMirror(v8::Local<v8::Value> obj) {
7744 RETURN_TO_LOCAL_UNCHECKED(GetMirror(Local<Context>(), obj), Value);
7748 void Debug::ProcessDebugMessages() {
7749 i::Isolate::Current()->debug()->ProcessDebugMessages(true);
7753 Local<Context> Debug::GetDebugContext() {
7754 i::Isolate* isolate = i::Isolate::Current();
7756 return Utils::ToLocal(isolate->debug()->GetDebugContext());
7760 void Debug::SetLiveEditEnabled(Isolate* isolate, bool enable) {
7761 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7762 internal_isolate->debug()->set_live_edit_enabled(enable);
7766 MaybeLocal<Array> Debug::GetInternalProperties(Isolate* v8_isolate,
7767 Local<Value> value) {
7768 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7770 i::Handle<i::Object> val = Utils::OpenHandle(*value);
7771 i::Handle<i::JSArray> result;
7772 if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
7773 return MaybeLocal<Array>();
7774 return Utils::ToLocal(result);
7778 Local<String> CpuProfileNode::GetFunctionName() const {
7779 i::Isolate* isolate = i::Isolate::Current();
7780 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7781 const i::CodeEntry* entry = node->entry();
7782 i::Handle<i::String> name =
7783 isolate->factory()->InternalizeUtf8String(entry->name());
7784 if (!entry->has_name_prefix()) {
7785 return ToApiHandle<String>(name);
7787 // We do not expect this to fail. Change this if it does.
7788 i::Handle<i::String> cons = isolate->factory()->NewConsString(
7789 isolate->factory()->InternalizeUtf8String(entry->name_prefix()),
7790 name).ToHandleChecked();
7791 return ToApiHandle<String>(cons);
7796 int CpuProfileNode::GetScriptId() const {
7797 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7798 const i::CodeEntry* entry = node->entry();
7799 return entry->script_id();
7803 Local<String> CpuProfileNode::GetScriptResourceName() const {
7804 i::Isolate* isolate = i::Isolate::Current();
7805 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7806 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7807 node->entry()->resource_name()));
7811 int CpuProfileNode::GetLineNumber() const {
7812 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
7816 int CpuProfileNode::GetColumnNumber() const {
7817 return reinterpret_cast<const i::ProfileNode*>(this)->
7818 entry()->column_number();
7822 unsigned int CpuProfileNode::GetHitLineCount() const {
7823 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7824 return node->GetHitLineCount();
7828 bool CpuProfileNode::GetLineTicks(LineTick* entries,
7829 unsigned int length) const {
7830 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7831 return node->GetLineTicks(entries, length);
7835 const char* CpuProfileNode::GetBailoutReason() const {
7836 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7837 return node->entry()->bailout_reason();
7841 unsigned CpuProfileNode::GetHitCount() const {
7842 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
7846 unsigned CpuProfileNode::GetCallUid() const {
7847 return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
7851 unsigned CpuProfileNode::GetNodeId() const {
7852 return reinterpret_cast<const i::ProfileNode*>(this)->id();
7856 int CpuProfileNode::GetChildrenCount() const {
7857 return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
7861 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
7862 const i::ProfileNode* child =
7863 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
7864 return reinterpret_cast<const CpuProfileNode*>(child);
7868 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
7869 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7870 return node->deopt_infos();
7874 void CpuProfile::Delete() {
7875 i::Isolate* isolate = i::Isolate::Current();
7876 i::CpuProfiler* profiler = isolate->cpu_profiler();
7877 DCHECK(profiler != NULL);
7878 profiler->DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
7882 Local<String> CpuProfile::GetTitle() const {
7883 i::Isolate* isolate = i::Isolate::Current();
7884 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7885 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7890 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
7891 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7892 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
7896 const CpuProfileNode* CpuProfile::GetSample(int index) const {
7897 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7898 return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
7902 int64_t CpuProfile::GetSampleTimestamp(int index) const {
7903 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7904 return (profile->sample_timestamp(index) - base::TimeTicks())
7909 int64_t CpuProfile::GetStartTime() const {
7910 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7911 return (profile->start_time() - base::TimeTicks()).InMicroseconds();
7915 int64_t CpuProfile::GetEndTime() const {
7916 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7917 return (profile->end_time() - base::TimeTicks()).InMicroseconds();
7921 int CpuProfile::GetSamplesCount() const {
7922 return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
7926 void CpuProfiler::SetSamplingInterval(int us) {
7928 return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
7929 base::TimeDelta::FromMicroseconds(us));
7933 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
7934 reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
7935 *Utils::OpenHandle(*title), record_samples);
7939 CpuProfile* CpuProfiler::StopProfiling(Local<String> title) {
7940 return reinterpret_cast<CpuProfile*>(
7941 reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
7942 *Utils::OpenHandle(*title)));
7946 void CpuProfiler::SetIdle(bool is_idle) {
7947 i::Isolate* isolate = reinterpret_cast<i::CpuProfiler*>(this)->isolate();
7948 v8::StateTag state = isolate->current_vm_state();
7949 DCHECK(state == v8::EXTERNAL || state == v8::IDLE);
7950 if (isolate->js_entry_sp() != NULL) return;
7952 isolate->set_current_vm_state(v8::IDLE);
7953 } else if (state == v8::IDLE) {
7954 isolate->set_current_vm_state(v8::EXTERNAL);
7959 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
7960 return const_cast<i::HeapGraphEdge*>(
7961 reinterpret_cast<const i::HeapGraphEdge*>(edge));
7965 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
7966 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
7970 Local<Value> HeapGraphEdge::GetName() const {
7971 i::Isolate* isolate = i::Isolate::Current();
7972 i::HeapGraphEdge* edge = ToInternal(this);
7973 switch (edge->type()) {
7974 case i::HeapGraphEdge::kContextVariable:
7975 case i::HeapGraphEdge::kInternal:
7976 case i::HeapGraphEdge::kProperty:
7977 case i::HeapGraphEdge::kShortcut:
7978 case i::HeapGraphEdge::kWeak:
7979 return ToApiHandle<String>(
7980 isolate->factory()->InternalizeUtf8String(edge->name()));
7981 case i::HeapGraphEdge::kElement:
7982 case i::HeapGraphEdge::kHidden:
7983 return ToApiHandle<Number>(
7984 isolate->factory()->NewNumberFromInt(edge->index()));
7985 default: UNREACHABLE();
7987 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
7991 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
7992 const i::HeapEntry* from = ToInternal(this)->from();
7993 return reinterpret_cast<const HeapGraphNode*>(from);
7997 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
7998 const i::HeapEntry* to = ToInternal(this)->to();
7999 return reinterpret_cast<const HeapGraphNode*>(to);
8003 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
8004 return const_cast<i::HeapEntry*>(
8005 reinterpret_cast<const i::HeapEntry*>(entry));
8009 HeapGraphNode::Type HeapGraphNode::GetType() const {
8010 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
8014 Local<String> HeapGraphNode::GetName() const {
8015 i::Isolate* isolate = i::Isolate::Current();
8016 return ToApiHandle<String>(
8017 isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
8021 SnapshotObjectId HeapGraphNode::GetId() const {
8022 return ToInternal(this)->id();
8026 size_t HeapGraphNode::GetShallowSize() const {
8027 return ToInternal(this)->self_size();
8031 int HeapGraphNode::GetChildrenCount() const {
8032 return ToInternal(this)->children().length();
8036 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
8037 return reinterpret_cast<const HeapGraphEdge*>(
8038 ToInternal(this)->children()[index]);
8042 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
8043 return const_cast<i::HeapSnapshot*>(
8044 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
8048 void HeapSnapshot::Delete() {
8049 i::Isolate* isolate = i::Isolate::Current();
8050 if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
8051 ToInternal(this)->Delete();
8053 // If this is the last snapshot, clean up all accessory data as well.
8054 isolate->heap_profiler()->DeleteAllSnapshots();
8059 const HeapGraphNode* HeapSnapshot::GetRoot() const {
8060 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
8064 const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
8065 return reinterpret_cast<const HeapGraphNode*>(
8066 ToInternal(this)->GetEntryById(id));
8070 int HeapSnapshot::GetNodesCount() const {
8071 return ToInternal(this)->entries().length();
8075 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
8076 return reinterpret_cast<const HeapGraphNode*>(
8077 &ToInternal(this)->entries().at(index));
8081 SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
8082 return ToInternal(this)->max_snapshot_js_object_id();
8086 void HeapSnapshot::Serialize(OutputStream* stream,
8087 HeapSnapshot::SerializationFormat format) const {
8088 Utils::ApiCheck(format == kJSON,
8089 "v8::HeapSnapshot::Serialize",
8090 "Unknown serialization format");
8091 Utils::ApiCheck(stream->GetChunkSize() > 0,
8092 "v8::HeapSnapshot::Serialize",
8093 "Invalid stream chunk size");
8094 i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
8095 serializer.Serialize(stream);
8100 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
8101 HeapProfiler::kUnknownObjectId;
8104 int HeapProfiler::GetSnapshotCount() {
8105 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
8109 const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
8110 return reinterpret_cast<const HeapSnapshot*>(
8111 reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
8115 SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) {
8116 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
8117 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
8121 Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
8122 i::Handle<i::Object> obj =
8123 reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
8124 if (obj.is_null()) return Local<Value>();
8125 return Utils::ToLocal(obj);
8129 void HeapProfiler::ClearObjectIds() {
8130 reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
8134 const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
8135 ActivityControl* control, ObjectNameResolver* resolver) {
8136 return reinterpret_cast<const HeapSnapshot*>(
8137 reinterpret_cast<i::HeapProfiler*>(this)
8138 ->TakeSnapshot(control, resolver));
8142 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
8143 reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
8148 void HeapProfiler::StopTrackingHeapObjects() {
8149 reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
8153 SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream,
8154 int64_t* timestamp_us) {
8155 i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
8156 return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
8160 void HeapProfiler::DeleteAllHeapSnapshots() {
8161 reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
8165 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
8166 WrapperInfoCallback callback) {
8167 reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
8172 size_t HeapProfiler::GetProfilerMemorySize() {
8173 return reinterpret_cast<i::HeapProfiler*>(this)->
8174 GetMemorySizeUsedByProfiler();
8178 void HeapProfiler::SetRetainedObjectInfo(UniqueId id,
8179 RetainedObjectInfo* info) {
8180 reinterpret_cast<i::HeapProfiler*>(this)->SetRetainedObjectInfo(id, info);
8184 v8::Testing::StressType internal::Testing::stress_type_ =
8185 v8::Testing::kStressTypeOpt;
8188 void Testing::SetStressRunType(Testing::StressType type) {
8189 internal::Testing::set_stress_type(type);
8193 int Testing::GetStressRuns() {
8194 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
8196 // In debug mode the code runs much slower so stressing will only make two
8205 static void SetFlagsFromString(const char* flags) {
8206 V8::SetFlagsFromString(flags, i::StrLength(flags));
8210 void Testing::PrepareStressRun(int run) {
8211 static const char* kLazyOptimizations =
8212 "--prepare-always-opt "
8213 "--max-inlined-source-size=999999 "
8214 "--max-inlined-nodes=999999 "
8215 "--max-inlined-nodes-cumulative=999999 "
8217 static const char* kForcedOptimizations = "--always-opt";
8219 // If deoptimization stressed turn on frequent deoptimization. If no value
8220 // is spefified through --deopt-every-n-times use a default default value.
8221 static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
8222 if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
8223 internal::FLAG_deopt_every_n_times == 0) {
8224 SetFlagsFromString(kDeoptEvery13Times);
8228 // As stressing in debug mode only make two runs skip the deopt stressing
8230 if (run == GetStressRuns() - 1) {
8231 SetFlagsFromString(kForcedOptimizations);
8233 SetFlagsFromString(kLazyOptimizations);
8236 if (run == GetStressRuns() - 1) {
8237 SetFlagsFromString(kForcedOptimizations);
8238 } else if (run != GetStressRuns() - 2) {
8239 SetFlagsFromString(kLazyOptimizations);
8245 // TODO(svenpanne) Deprecate this.
8246 void Testing::DeoptimizeAll() {
8247 i::Isolate* isolate = i::Isolate::Current();
8248 i::HandleScope scope(isolate);
8249 internal::Deoptimizer::DeoptimizeAll(isolate);
8253 namespace internal {
8256 void HandleScopeImplementer::FreeThreadResources() {
8261 char* HandleScopeImplementer::ArchiveThread(char* storage) {
8262 HandleScopeData* current = isolate_->handle_scope_data();
8263 handle_scope_data_ = *current;
8264 MemCopy(storage, this, sizeof(*this));
8266 ResetAfterArchive();
8267 current->Initialize();
8269 return storage + ArchiveSpacePerThread();
8273 int HandleScopeImplementer::ArchiveSpacePerThread() {
8274 return sizeof(HandleScopeImplementer);
8278 char* HandleScopeImplementer::RestoreThread(char* storage) {
8279 MemCopy(this, storage, sizeof(*this));
8280 *isolate_->handle_scope_data() = handle_scope_data_;
8281 return storage + ArchiveSpacePerThread();
8285 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
8287 bool found_block_before_deferred = false;
8289 // Iterate over all handles in the blocks except for the last.
8290 for (int i = blocks()->length() - 2; i >= 0; --i) {
8291 Object** block = blocks()->at(i);
8292 if (last_handle_before_deferred_block_ != NULL &&
8293 (last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) &&
8294 (last_handle_before_deferred_block_ >= block)) {
8295 v->VisitPointers(block, last_handle_before_deferred_block_);
8296 DCHECK(!found_block_before_deferred);
8298 found_block_before_deferred = true;
8301 v->VisitPointers(block, &block[kHandleBlockSize]);
8305 DCHECK(last_handle_before_deferred_block_ == NULL ||
8306 found_block_before_deferred);
8308 // Iterate over live handles in the last block (if any).
8309 if (!blocks()->is_empty()) {
8310 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
8313 List<Context*>* context_lists[2] = { &saved_contexts_, &entered_contexts_};
8314 for (unsigned i = 0; i < arraysize(context_lists); i++) {
8315 if (context_lists[i]->is_empty()) continue;
8316 Object** start = reinterpret_cast<Object**>(&context_lists[i]->first());
8317 v->VisitPointers(start, start + context_lists[i]->length());
8322 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
8323 HandleScopeData* current = isolate_->handle_scope_data();
8324 handle_scope_data_ = *current;
8329 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
8330 HandleScopeImplementer* scope_implementer =
8331 reinterpret_cast<HandleScopeImplementer*>(storage);
8332 scope_implementer->IterateThis(v);
8333 return storage + ArchiveSpacePerThread();
8337 DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) {
8338 DeferredHandles* deferred =
8339 new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
8341 while (!blocks_.is_empty()) {
8342 Object** block_start = blocks_.last();
8343 Object** block_limit = &block_start[kHandleBlockSize];
8344 // We should not need to check for SealHandleScope here. Assert this.
8345 DCHECK(prev_limit == block_limit ||
8346 !(block_start <= prev_limit && prev_limit <= block_limit));
8347 if (prev_limit == block_limit) break;
8348 deferred->blocks_.Add(blocks_.last());
8349 blocks_.RemoveLast();
8352 // deferred->blocks_ now contains the blocks installed on the
8353 // HandleScope stack since BeginDeferredScope was called, but in
8356 DCHECK(prev_limit == NULL || !blocks_.is_empty());
8358 DCHECK(!blocks_.is_empty() && prev_limit != NULL);
8359 DCHECK(last_handle_before_deferred_block_ != NULL);
8360 last_handle_before_deferred_block_ = NULL;
8365 void HandleScopeImplementer::BeginDeferredScope() {
8366 DCHECK(last_handle_before_deferred_block_ == NULL);
8367 last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
8371 DeferredHandles::~DeferredHandles() {
8372 isolate_->UnlinkDeferredHandles(this);
8374 for (int i = 0; i < blocks_.length(); i++) {
8375 #ifdef ENABLE_HANDLE_ZAPPING
8376 HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
8378 isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
8383 void DeferredHandles::Iterate(ObjectVisitor* v) {
8384 DCHECK(!blocks_.is_empty());
8386 DCHECK((first_block_limit_ >= blocks_.first()) &&
8387 (first_block_limit_ <= &(blocks_.first())[kHandleBlockSize]));
8389 v->VisitPointers(blocks_.first(), first_block_limit_);
8391 for (int i = 1; i < blocks_.length(); i++) {
8392 v->VisitPointers(blocks_[i], &blocks_[i][kHandleBlockSize]);
8397 void InvokeAccessorGetterCallback(
8398 v8::Local<v8::Name> property,
8399 const v8::PropertyCallbackInfo<v8::Value>& info,
8400 v8::AccessorNameGetterCallback getter) {
8401 // Leaving JavaScript.
8402 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8403 Address getter_address = reinterpret_cast<Address>(reinterpret_cast<intptr_t>(
8405 VMState<EXTERNAL> state(isolate);
8406 ExternalCallbackScope call_scope(isolate, getter_address);
8407 getter(property, info);
8411 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
8412 v8::FunctionCallback callback) {
8413 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8414 Address callback_address =
8415 reinterpret_cast<Address>(reinterpret_cast<intptr_t>(callback));
8416 VMState<EXTERNAL> state(isolate);
8417 ExternalCallbackScope call_scope(isolate, callback_address);
8422 } // namespace internal