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 Maybe<int> Message::GetLineNumber(Local<Context> context) const {
2279 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetLineNumber()", int);
2280 i::Handle<i::JSFunction> fun = isolate->message_get_line_number();
2281 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2282 i::Handle<i::Object> args[] = {Utils::OpenHandle(this)};
2283 i::Handle<i::Object> result;
2284 has_pending_exception =
2285 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2287 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2288 return Just(static_cast<int>(result->Number()));
2292 int Message::GetLineNumber() const {
2293 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2294 return GetLineNumber(context).FromMaybe(0);
2298 int Message::GetStartPosition() const {
2299 auto self = Utils::OpenHandle(this);
2300 return self->start_position();
2304 int Message::GetEndPosition() const {
2305 auto self = Utils::OpenHandle(this);
2306 return self->end_position();
2310 Maybe<int> Message::GetStartColumn(Local<Context> context) const {
2311 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetStartColumn()",
2313 i::Handle<i::JSFunction> fun = isolate->message_get_column_number();
2314 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2315 i::Handle<i::Object> args[] = {Utils::OpenHandle(this)};
2316 i::Handle<i::Object> result;
2317 has_pending_exception =
2318 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2320 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2321 return Just(static_cast<int>(result->Number()));
2325 int Message::GetStartColumn() const {
2326 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2327 const int default_value = kNoColumnInfo;
2328 return GetStartColumn(context).FromMaybe(default_value);
2332 Maybe<int> Message::GetEndColumn(Local<Context> context) const {
2333 auto self = Utils::OpenHandle(this);
2334 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetEndColumn()", int);
2335 i::Handle<i::JSFunction> fun = isolate->message_get_column_number();
2336 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2337 i::Handle<i::Object> args[] = {self};
2338 i::Handle<i::Object> result;
2339 has_pending_exception =
2340 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2342 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2343 int start = self->start_position();
2344 int end = self->end_position();
2345 return Just(static_cast<int>(result->Number()) + (end - start));
2349 int Message::GetEndColumn() const {
2350 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2351 const int default_value = kNoColumnInfo;
2352 return GetEndColumn(context).FromMaybe(default_value);
2356 bool Message::IsSharedCrossOrigin() const {
2357 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2359 auto self = Utils::OpenHandle(this);
2360 auto script = i::Handle<i::JSValue>::cast(
2361 i::Handle<i::Object>(self->script(), isolate));
2362 return i::Script::cast(script->value())
2364 .IsSharedCrossOrigin();
2367 bool Message::IsOpaque() 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())->origin_options().IsOpaque();
2377 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
2378 PREPARE_FOR_EXECUTION(context, "v8::Message::GetSourceLine()", String);
2379 i::Handle<i::JSFunction> fun = isolate->message_get_source_line();
2380 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2381 i::Handle<i::Object> args[] = {Utils::OpenHandle(this)};
2382 i::Handle<i::Object> result;
2383 has_pending_exception =
2384 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2386 RETURN_ON_FAILED_EXECUTION(String);
2388 if (result->IsString()) {
2389 str = Utils::ToLocal(i::Handle<i::String>::cast(result));
2391 RETURN_ESCAPED(str);
2395 Local<String> Message::GetSourceLine() const {
2396 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2397 RETURN_TO_LOCAL_UNCHECKED(GetSourceLine(context), String)
2401 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
2402 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2403 ENTER_V8(i_isolate);
2404 i_isolate->PrintCurrentStackTrace(out);
2408 // --- S t a c k T r a c e ---
2410 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
2411 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2413 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2414 auto self = Utils::OpenHandle(this);
2415 auto obj = i::Object::GetElement(isolate, self, index).ToHandleChecked();
2416 auto jsobj = i::Handle<i::JSObject>::cast(obj);
2417 return scope.Escape(Utils::StackFrameToLocal(jsobj));
2421 int StackTrace::GetFrameCount() const {
2422 return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
2426 Local<Array> StackTrace::AsArray() {
2427 return Utils::ToLocal(Utils::OpenHandle(this));
2431 Local<StackTrace> StackTrace::CurrentStackTrace(
2434 StackTraceOptions options) {
2435 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2436 ENTER_V8(i_isolate);
2437 // TODO(dcarney): remove when ScriptDebugServer is fixed.
2438 options = static_cast<StackTraceOptions>(
2439 static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins);
2440 i::Handle<i::JSArray> stackTrace =
2441 i_isolate->CaptureCurrentStackTrace(frame_limit, options);
2442 return Utils::StackTraceToLocal(stackTrace);
2446 // --- S t a c k F r a m e ---
2448 static int getIntProperty(const StackFrame* f, const char* propertyName,
2450 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2452 i::HandleScope scope(isolate);
2453 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2454 i::Handle<i::Object> obj =
2455 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2456 return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue;
2460 int StackFrame::GetLineNumber() const {
2461 return getIntProperty(this, "lineNumber", Message::kNoLineNumberInfo);
2465 int StackFrame::GetColumn() const {
2466 return getIntProperty(this, "column", Message::kNoColumnInfo);
2470 int StackFrame::GetScriptId() const {
2471 return getIntProperty(this, "scriptId", Message::kNoScriptIdInfo);
2475 static Local<String> getStringProperty(const StackFrame* f,
2476 const char* propertyName) {
2477 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2479 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2480 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2481 i::Handle<i::Object> obj =
2482 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2483 return obj->IsString()
2484 ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2489 Local<String> StackFrame::GetScriptName() const {
2490 return getStringProperty(this, "scriptName");
2494 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2495 return getStringProperty(this, "scriptNameOrSourceURL");
2499 Local<String> StackFrame::GetFunctionName() const {
2500 return getStringProperty(this, "functionName");
2504 static bool getBoolProperty(const StackFrame* f, const char* propertyName) {
2505 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2507 i::HandleScope scope(isolate);
2508 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2509 i::Handle<i::Object> obj =
2510 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2511 return obj->IsTrue();
2514 bool StackFrame::IsEval() const { return getBoolProperty(this, "isEval"); }
2517 bool StackFrame::IsConstructor() const {
2518 return getBoolProperty(this, "isConstructor");
2522 // --- N a t i v e W e a k M a p ---
2524 Local<NativeWeakMap> NativeWeakMap::New(Isolate* v8_isolate) {
2525 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2527 i::Handle<i::JSWeakMap> weakmap = isolate->factory()->NewJSWeakMap();
2528 i::Runtime::WeakCollectionInitialize(isolate, weakmap);
2529 return Utils::NativeWeakMapToLocal(weakmap);
2533 void NativeWeakMap::Set(Local<Value> v8_key, Local<Value> v8_value) {
2534 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2535 i::Isolate* isolate = weak_collection->GetIsolate();
2537 i::HandleScope scope(isolate);
2538 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2539 i::Handle<i::Object> value = Utils::OpenHandle(*v8_value);
2540 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2544 i::Handle<i::ObjectHashTable> table(
2545 i::ObjectHashTable::cast(weak_collection->table()));
2546 if (!table->IsKey(*key)) {
2550 int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value();
2551 i::Runtime::WeakCollectionSet(weak_collection, key, value, hash);
2555 Local<Value> NativeWeakMap::Get(Local<Value> v8_key) {
2556 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2557 i::Isolate* isolate = weak_collection->GetIsolate();
2559 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2560 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2562 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2564 i::Handle<i::ObjectHashTable> table(
2565 i::ObjectHashTable::cast(weak_collection->table()));
2566 if (!table->IsKey(*key)) {
2568 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2570 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2571 if (lookup->IsTheHole())
2572 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2573 return Utils::ToLocal(lookup);
2577 bool NativeWeakMap::Has(Local<Value> v8_key) {
2578 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2579 i::Isolate* isolate = weak_collection->GetIsolate();
2581 i::HandleScope scope(isolate);
2582 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2583 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2587 i::Handle<i::ObjectHashTable> table(
2588 i::ObjectHashTable::cast(weak_collection->table()));
2589 if (!table->IsKey(*key)) {
2593 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2594 return !lookup->IsTheHole();
2598 bool NativeWeakMap::Delete(Local<Value> v8_key) {
2599 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2600 i::Isolate* isolate = weak_collection->GetIsolate();
2602 i::HandleScope scope(isolate);
2603 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2604 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2608 i::Handle<i::ObjectHashTable> table(
2609 i::ObjectHashTable::cast(weak_collection->table()));
2610 if (!table->IsKey(*key)) {
2614 return i::Runtime::WeakCollectionDelete(weak_collection, key);
2620 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) {
2621 auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2622 PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, "JSON::Parse", Value);
2623 i::Handle<i::String> string = Utils::OpenHandle(*json_string);
2624 i::Handle<i::String> source = i::String::Flatten(string);
2625 auto maybe = source->IsSeqOneByteString()
2626 ? i::JsonParser<true>::Parse(source)
2627 : i::JsonParser<false>::Parse(source);
2628 Local<Value> result;
2629 has_pending_exception = !ToLocal<Value>(maybe, &result);
2630 RETURN_ON_FAILED_EXECUTION(Value);
2631 RETURN_ESCAPED(result);
2635 Local<Value> JSON::Parse(Local<String> json_string) {
2636 auto isolate = reinterpret_cast<v8::Isolate*>(
2637 Utils::OpenHandle(*json_string)->GetIsolate());
2638 RETURN_TO_LOCAL_UNCHECKED(Parse(isolate, json_string), Value);
2644 bool Value::FullIsUndefined() const {
2645 bool result = Utils::OpenHandle(this)->IsUndefined();
2646 DCHECK_EQ(result, QuickIsUndefined());
2651 bool Value::FullIsNull() const {
2652 bool result = Utils::OpenHandle(this)->IsNull();
2653 DCHECK_EQ(result, QuickIsNull());
2658 bool Value::IsTrue() const {
2659 return Utils::OpenHandle(this)->IsTrue();
2663 bool Value::IsFalse() const {
2664 return Utils::OpenHandle(this)->IsFalse();
2668 bool Value::IsFunction() const {
2669 return Utils::OpenHandle(this)->IsJSFunction();
2673 bool Value::IsName() const {
2674 return Utils::OpenHandle(this)->IsName();
2678 bool Value::FullIsString() const {
2679 bool result = Utils::OpenHandle(this)->IsString();
2680 DCHECK_EQ(result, QuickIsString());
2685 bool Value::IsSymbol() const {
2686 return Utils::OpenHandle(this)->IsSymbol();
2690 bool Value::IsArray() const {
2691 return Utils::OpenHandle(this)->IsJSArray();
2695 bool Value::IsArrayBuffer() const {
2696 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2697 return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
2701 bool Value::IsArrayBufferView() const {
2702 return Utils::OpenHandle(this)->IsJSArrayBufferView();
2706 bool Value::IsTypedArray() const {
2707 return Utils::OpenHandle(this)->IsJSTypedArray();
2711 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype, size) \
2712 bool Value::Is##Type##Array() const { \
2713 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2714 return obj->IsJSTypedArray() && \
2715 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
2719 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
2721 #undef VALUE_IS_TYPED_ARRAY
2724 bool Value::IsDataView() const {
2725 return Utils::OpenHandle(this)->IsJSDataView();
2729 bool Value::IsSharedArrayBuffer() const {
2730 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2731 return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
2735 bool Value::IsObject() const {
2736 return Utils::OpenHandle(this)->IsJSObject();
2740 bool Value::IsNumber() const {
2741 return Utils::OpenHandle(this)->IsNumber();
2745 #define VALUE_IS_SPECIFIC_TYPE(Type, Class) \
2746 bool Value::Is##Type() const { \
2747 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2748 if (!obj->IsHeapObject()) return false; \
2749 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate(); \
2750 return obj->HasSpecificClassOf(isolate->heap()->Class##_string()); \
2753 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, Arguments)
2754 VALUE_IS_SPECIFIC_TYPE(BooleanObject, Boolean)
2755 VALUE_IS_SPECIFIC_TYPE(NumberObject, Number)
2756 VALUE_IS_SPECIFIC_TYPE(StringObject, String)
2757 VALUE_IS_SPECIFIC_TYPE(SymbolObject, Symbol)
2758 VALUE_IS_SPECIFIC_TYPE(Date, Date)
2759 VALUE_IS_SPECIFIC_TYPE(Map, Map)
2760 VALUE_IS_SPECIFIC_TYPE(Set, Set)
2761 VALUE_IS_SPECIFIC_TYPE(WeakMap, WeakMap)
2762 VALUE_IS_SPECIFIC_TYPE(WeakSet, WeakSet)
2764 #undef VALUE_IS_SPECIFIC_TYPE
2767 bool Value::IsBoolean() const {
2768 return Utils::OpenHandle(this)->IsBoolean();
2772 bool Value::IsExternal() const {
2773 return Utils::OpenHandle(this)->IsExternal();
2777 bool Value::IsInt32() const {
2778 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2779 if (obj->IsSmi()) return true;
2780 if (obj->IsNumber()) {
2781 return i::IsInt32Double(obj->Number());
2787 bool Value::IsUint32() const {
2788 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2789 if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2790 if (obj->IsNumber()) {
2791 double value = obj->Number();
2792 return !i::IsMinusZero(value) &&
2794 value <= i::kMaxUInt32 &&
2795 value == i::FastUI2D(i::FastD2UI(value));
2801 bool Value::IsNativeError() const {
2802 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2803 if (!obj->IsJSObject()) return false;
2804 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
2805 i::Isolate* isolate = js_obj->GetIsolate();
2806 i::Handle<i::Object> constructor(js_obj->map()->GetConstructor(), isolate);
2807 if (!constructor->IsJSFunction()) return false;
2808 i::Handle<i::JSFunction> function =
2809 i::Handle<i::JSFunction>::cast(constructor);
2810 if (!function->shared()->native()) return false;
2811 return function.is_identical_to(isolate->error_function()) ||
2812 function.is_identical_to(isolate->eval_error_function()) ||
2813 function.is_identical_to(isolate->range_error_function()) ||
2814 function.is_identical_to(isolate->reference_error_function()) ||
2815 function.is_identical_to(isolate->syntax_error_function()) ||
2816 function.is_identical_to(isolate->type_error_function()) ||
2817 function.is_identical_to(isolate->uri_error_function());
2821 bool Value::IsRegExp() const {
2822 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2823 return obj->IsJSRegExp();
2827 bool Value::IsGeneratorFunction() const {
2828 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2829 if (!obj->IsJSFunction()) return false;
2830 i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
2831 return func->shared()->is_generator();
2835 bool Value::IsGeneratorObject() const {
2836 return Utils::OpenHandle(this)->IsJSGeneratorObject();
2840 bool Value::IsMapIterator() const {
2841 return Utils::OpenHandle(this)->IsJSMapIterator();
2845 bool Value::IsSetIterator() const {
2846 return Utils::OpenHandle(this)->IsJSSetIterator();
2850 MaybeLocal<String> Value::ToString(Local<Context> context) const {
2851 auto obj = Utils::OpenHandle(this);
2852 if (obj->IsString()) return ToApiHandle<String>(obj);
2853 PREPARE_FOR_EXECUTION(context, "ToString", String);
2854 Local<String> result;
2855 has_pending_exception =
2856 !ToLocal<String>(i::Execution::ToString(isolate, obj), &result);
2857 RETURN_ON_FAILED_EXECUTION(String);
2858 RETURN_ESCAPED(result);
2862 Local<String> Value::ToString(Isolate* isolate) const {
2863 RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
2867 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
2868 auto obj = Utils::OpenHandle(this);
2869 if (obj->IsString()) return ToApiHandle<String>(obj);
2870 PREPARE_FOR_EXECUTION(context, "ToDetailString", String);
2871 Local<String> result;
2872 has_pending_exception =
2873 !ToLocal<String>(i::Execution::ToDetailString(isolate, obj), &result);
2874 RETURN_ON_FAILED_EXECUTION(String);
2875 RETURN_ESCAPED(result);
2879 Local<String> Value::ToDetailString(Isolate* isolate) const {
2880 RETURN_TO_LOCAL_UNCHECKED(ToDetailString(isolate->GetCurrentContext()),
2885 MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
2886 auto obj = Utils::OpenHandle(this);
2887 if (obj->IsJSObject()) return ToApiHandle<Object>(obj);
2888 PREPARE_FOR_EXECUTION(context, "ToObject", Object);
2889 Local<Object> result;
2890 has_pending_exception =
2891 !ToLocal<Object>(i::Execution::ToObject(isolate, obj), &result);
2892 RETURN_ON_FAILED_EXECUTION(Object);
2893 RETURN_ESCAPED(result);
2897 Local<v8::Object> Value::ToObject(Isolate* isolate) const {
2898 RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
2902 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
2903 auto obj = Utils::OpenHandle(this);
2904 if (obj->IsBoolean()) return ToApiHandle<Boolean>(obj);
2905 auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2906 auto val = isolate->factory()->ToBoolean(obj->BooleanValue());
2907 return ToApiHandle<Boolean>(val);
2911 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
2912 return ToBoolean(v8_isolate->GetCurrentContext()).ToLocalChecked();
2916 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
2917 auto obj = Utils::OpenHandle(this);
2918 if (obj->IsNumber()) return ToApiHandle<Number>(obj);
2919 PREPARE_FOR_EXECUTION(context, "ToNumber", Number);
2920 Local<Number> result;
2921 has_pending_exception =
2922 !ToLocal<Number>(i::Execution::ToNumber(isolate, obj), &result);
2923 RETURN_ON_FAILED_EXECUTION(Number);
2924 RETURN_ESCAPED(result);
2928 Local<Number> Value::ToNumber(Isolate* isolate) const {
2929 RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
2933 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
2934 auto obj = Utils::OpenHandle(this);
2935 if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
2936 PREPARE_FOR_EXECUTION(context, "ToInteger", Integer);
2937 Local<Integer> result;
2938 has_pending_exception =
2939 !ToLocal<Integer>(i::Execution::ToInteger(isolate, obj), &result);
2940 RETURN_ON_FAILED_EXECUTION(Integer);
2941 RETURN_ESCAPED(result);
2945 Local<Integer> Value::ToInteger(Isolate* isolate) const {
2946 RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
2950 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
2951 auto obj = Utils::OpenHandle(this);
2952 if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
2953 Local<Int32> result;
2954 PREPARE_FOR_EXECUTION(context, "ToInt32", Int32);
2955 has_pending_exception =
2956 !ToLocal<Int32>(i::Execution::ToInt32(isolate, obj), &result);
2957 RETURN_ON_FAILED_EXECUTION(Int32);
2958 RETURN_ESCAPED(result);
2962 Local<Int32> Value::ToInt32(Isolate* isolate) const {
2963 RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
2967 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
2968 auto obj = Utils::OpenHandle(this);
2969 if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
2970 Local<Uint32> result;
2971 PREPARE_FOR_EXECUTION(context, "ToUInt32", Uint32);
2972 has_pending_exception =
2973 !ToLocal<Uint32>(i::Execution::ToUint32(isolate, obj), &result);
2974 RETURN_ON_FAILED_EXECUTION(Uint32);
2975 RETURN_ESCAPED(result);
2979 Local<Uint32> Value::ToUint32(Isolate* isolate) const {
2980 RETURN_TO_LOCAL_UNCHECKED(ToUint32(isolate->GetCurrentContext()), Uint32);
2984 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
2985 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
2986 Utils::ApiCheck(isolate != NULL &&
2988 "v8::internal::Internals::CheckInitialized()",
2989 "Isolate is not initialized or V8 has died");
2993 void External::CheckCast(v8::Value* that) {
2994 Utils::ApiCheck(Utils::OpenHandle(that)->IsExternal(),
2995 "v8::External::Cast()",
2996 "Could not convert to external");
3000 void v8::Object::CheckCast(Value* that) {
3001 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3002 Utils::ApiCheck(obj->IsJSObject(),
3003 "v8::Object::Cast()",
3004 "Could not convert to object");
3008 void v8::Function::CheckCast(Value* that) {
3009 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3010 Utils::ApiCheck(obj->IsJSFunction(),
3011 "v8::Function::Cast()",
3012 "Could not convert to function");
3016 void v8::Boolean::CheckCast(v8::Value* that) {
3017 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3018 Utils::ApiCheck(obj->IsBoolean(),
3019 "v8::Boolean::Cast()",
3020 "Could not convert to boolean");
3024 void v8::Name::CheckCast(v8::Value* that) {
3025 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3026 Utils::ApiCheck(obj->IsName(),
3028 "Could not convert to name");
3032 void v8::String::CheckCast(v8::Value* that) {
3033 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3034 Utils::ApiCheck(obj->IsString(),
3035 "v8::String::Cast()",
3036 "Could not convert to string");
3040 void v8::Symbol::CheckCast(v8::Value* that) {
3041 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3042 Utils::ApiCheck(obj->IsSymbol(),
3043 "v8::Symbol::Cast()",
3044 "Could not convert to symbol");
3048 void v8::Number::CheckCast(v8::Value* that) {
3049 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3050 Utils::ApiCheck(obj->IsNumber(),
3051 "v8::Number::Cast()",
3052 "Could not convert to number");
3056 void v8::Integer::CheckCast(v8::Value* that) {
3057 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3058 Utils::ApiCheck(obj->IsNumber(),
3059 "v8::Integer::Cast()",
3060 "Could not convert to number");
3064 void v8::Int32::CheckCast(v8::Value* that) {
3065 Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast()",
3066 "Could not convert to 32-bit signed integer");
3070 void v8::Uint32::CheckCast(v8::Value* that) {
3071 Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast()",
3072 "Could not convert to 32-bit unsigned integer");
3076 void v8::Array::CheckCast(Value* that) {
3077 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3078 Utils::ApiCheck(obj->IsJSArray(),
3079 "v8::Array::Cast()",
3080 "Could not convert to array");
3084 void v8::Map::CheckCast(Value* that) {
3085 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3086 Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast()",
3087 "Could not convert to Map");
3091 void v8::Set::CheckCast(Value* that) {
3092 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3093 Utils::ApiCheck(obj->IsJSSet(), "v8::Set::Cast()",
3094 "Could not convert to Set");
3098 void v8::Promise::CheckCast(Value* that) {
3099 Utils::ApiCheck(that->IsPromise(),
3100 "v8::Promise::Cast()",
3101 "Could not convert to promise");
3105 void v8::Promise::Resolver::CheckCast(Value* that) {
3106 Utils::ApiCheck(that->IsPromise(),
3107 "v8::Promise::Resolver::Cast()",
3108 "Could not convert to promise resolver");
3112 void v8::ArrayBuffer::CheckCast(Value* that) {
3113 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3115 obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
3116 "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
3120 void v8::ArrayBufferView::CheckCast(Value* that) {
3121 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3122 Utils::ApiCheck(obj->IsJSArrayBufferView(),
3123 "v8::ArrayBufferView::Cast()",
3124 "Could not convert to ArrayBufferView");
3128 void v8::TypedArray::CheckCast(Value* that) {
3129 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3130 Utils::ApiCheck(obj->IsJSTypedArray(),
3131 "v8::TypedArray::Cast()",
3132 "Could not convert to TypedArray");
3136 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype, size) \
3137 void v8::Type##Array::CheckCast(Value* that) { \
3138 i::Handle<i::Object> obj = Utils::OpenHandle(that); \
3140 obj->IsJSTypedArray() && \
3141 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
3142 "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
3146 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
3148 #undef CHECK_TYPED_ARRAY_CAST
3151 void v8::DataView::CheckCast(Value* that) {
3152 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3153 Utils::ApiCheck(obj->IsJSDataView(),
3154 "v8::DataView::Cast()",
3155 "Could not convert to DataView");
3159 void v8::SharedArrayBuffer::CheckCast(Value* that) {
3160 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3162 obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
3163 "v8::SharedArrayBuffer::Cast()",
3164 "Could not convert to SharedArrayBuffer");
3168 void v8::Date::CheckCast(v8::Value* that) {
3169 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3170 i::Isolate* isolate = NULL;
3171 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3172 Utils::ApiCheck(isolate != NULL &&
3173 obj->HasSpecificClassOf(isolate->heap()->Date_string()),
3175 "Could not convert to date");
3179 void v8::StringObject::CheckCast(v8::Value* that) {
3180 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3181 i::Isolate* isolate = NULL;
3182 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3183 Utils::ApiCheck(isolate != NULL &&
3184 obj->HasSpecificClassOf(isolate->heap()->String_string()),
3185 "v8::StringObject::Cast()",
3186 "Could not convert to StringObject");
3190 void v8::SymbolObject::CheckCast(v8::Value* that) {
3191 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3192 i::Isolate* isolate = NULL;
3193 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3194 Utils::ApiCheck(isolate != NULL &&
3195 obj->HasSpecificClassOf(isolate->heap()->Symbol_string()),
3196 "v8::SymbolObject::Cast()",
3197 "Could not convert to SymbolObject");
3201 void v8::NumberObject::CheckCast(v8::Value* that) {
3202 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3203 i::Isolate* isolate = NULL;
3204 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3205 Utils::ApiCheck(isolate != NULL &&
3206 obj->HasSpecificClassOf(isolate->heap()->Number_string()),
3207 "v8::NumberObject::Cast()",
3208 "Could not convert to NumberObject");
3212 void v8::BooleanObject::CheckCast(v8::Value* that) {
3213 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3214 i::Isolate* isolate = NULL;
3215 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3216 Utils::ApiCheck(isolate != NULL &&
3217 obj->HasSpecificClassOf(isolate->heap()->Boolean_string()),
3218 "v8::BooleanObject::Cast()",
3219 "Could not convert to BooleanObject");
3223 void v8::RegExp::CheckCast(v8::Value* that) {
3224 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3225 Utils::ApiCheck(obj->IsJSRegExp(),
3226 "v8::RegExp::Cast()",
3227 "Could not convert to regular expression");
3231 Maybe<bool> Value::BooleanValue(Local<Context> context) const {
3232 return Just(Utils::OpenHandle(this)->BooleanValue());
3236 bool Value::BooleanValue() const {
3237 return Utils::OpenHandle(this)->BooleanValue();
3241 Maybe<double> Value::NumberValue(Local<Context> context) const {
3242 auto obj = Utils::OpenHandle(this);
3243 if (obj->IsNumber()) return Just(obj->Number());
3244 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "NumberValue", double);
3245 i::Handle<i::Object> num;
3246 has_pending_exception = !i::Execution::ToNumber(isolate, obj).ToHandle(&num);
3247 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
3248 return Just(num->Number());
3252 double Value::NumberValue() const {
3253 auto obj = Utils::OpenHandle(this);
3254 if (obj->IsNumber()) return obj->Number();
3255 return NumberValue(ContextFromHeapObject(obj))
3256 .FromMaybe(std::numeric_limits<double>::quiet_NaN());
3260 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
3261 auto obj = Utils::OpenHandle(this);
3262 i::Handle<i::Object> num;
3263 if (obj->IsNumber()) {
3266 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "IntegerValue", int64_t);
3267 has_pending_exception =
3268 !i::Execution::ToInteger(isolate, obj).ToHandle(&num);
3269 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
3271 return Just(num->IsSmi() ? static_cast<int64_t>(i::Smi::cast(*num)->value())
3272 : static_cast<int64_t>(num->Number()));
3276 int64_t Value::IntegerValue() const {
3277 auto obj = Utils::OpenHandle(this);
3278 if (obj->IsNumber()) {
3280 return i::Smi::cast(*obj)->value();
3282 return static_cast<int64_t>(obj->Number());
3285 return IntegerValue(ContextFromHeapObject(obj)).FromMaybe(0);
3289 Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
3290 auto obj = Utils::OpenHandle(this);
3291 if (obj->IsNumber()) return Just(NumberToInt32(*obj));
3292 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Int32Value", int32_t);
3293 i::Handle<i::Object> num;
3294 has_pending_exception = !i::Execution::ToInt32(isolate, obj).ToHandle(&num);
3295 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
3296 return Just(num->IsSmi() ? i::Smi::cast(*num)->value()
3297 : static_cast<int32_t>(num->Number()));
3301 int32_t Value::Int32Value() const {
3302 auto obj = Utils::OpenHandle(this);
3303 if (obj->IsNumber()) return NumberToInt32(*obj);
3304 return Int32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3308 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
3309 auto obj = Utils::OpenHandle(this);
3310 if (obj->IsNumber()) return Just(NumberToUint32(*obj));
3311 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Uint32Value", uint32_t);
3312 i::Handle<i::Object> num;
3313 has_pending_exception = !i::Execution::ToUint32(isolate, obj).ToHandle(&num);
3314 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
3315 return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::cast(*num)->value())
3316 : static_cast<uint32_t>(num->Number()));
3320 uint32_t Value::Uint32Value() const {
3321 auto obj = Utils::OpenHandle(this);
3322 if (obj->IsNumber()) return NumberToUint32(*obj);
3323 return Uint32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3327 MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const {
3328 auto self = Utils::OpenHandle(this);
3329 if (self->IsSmi()) {
3330 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3331 return Local<Uint32>();
3333 PREPARE_FOR_EXECUTION(context, "ToArrayIndex", Uint32);
3334 i::Handle<i::Object> string_obj;
3335 has_pending_exception =
3336 !i::Execution::ToString(isolate, self).ToHandle(&string_obj);
3337 RETURN_ON_FAILED_EXECUTION(Uint32);
3338 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
3340 if (str->AsArrayIndex(&index)) {
3341 i::Handle<i::Object> value;
3342 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
3343 value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
3345 value = isolate->factory()->NewNumber(index);
3347 RETURN_ESCAPED(Utils::Uint32ToLocal(value));
3349 return Local<Uint32>();
3353 Local<Uint32> Value::ToArrayIndex() const {
3354 auto self = Utils::OpenHandle(this);
3355 if (self->IsSmi()) {
3356 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3357 return Local<Uint32>();
3359 auto context = ContextFromHeapObject(self);
3360 RETURN_TO_LOCAL_UNCHECKED(ToArrayIndex(context), Uint32);
3364 Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const {
3365 auto self = Utils::OpenHandle(this);
3366 auto other = Utils::OpenHandle(*that);
3367 if (self->IsSmi() && other->IsSmi()) {
3368 return Just(self->Number() == other->Number());
3370 if (self->IsJSObject() && other->IsJSObject()) {
3371 return Just(*self == *other);
3373 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Value::Equals()", bool);
3374 i::Handle<i::Object> args[] = { other };
3375 i::Handle<i::JSFunction> fun(i::JSFunction::cast(
3376 isolate->js_builtins_object()->javascript_builtin(i::Builtins::EQUALS)));
3377 i::Handle<i::Object> result;
3378 has_pending_exception =
3379 !i::Execution::Call(isolate, fun, self, arraysize(args), args)
3381 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3382 return Just(*result == i::Smi::FromInt(i::EQUAL));
3386 bool Value::Equals(Local<Value> that) const {
3387 auto self = Utils::OpenHandle(this);
3388 auto other = Utils::OpenHandle(*that);
3389 if (self->IsSmi() && other->IsSmi()) {
3390 return self->Number() == other->Number();
3392 if (self->IsJSObject() && other->IsJSObject()) {
3393 return *self == *other;
3395 auto heap_object = self->IsSmi() ? other : self;
3396 auto context = ContextFromHeapObject(heap_object);
3397 return Equals(context, that).FromMaybe(false);
3401 bool Value::StrictEquals(Local<Value> that) const {
3402 auto self = Utils::OpenHandle(this);
3403 auto other = Utils::OpenHandle(*that);
3404 return self->StrictEquals(*other);
3408 bool Value::SameValue(Local<Value> that) const {
3409 auto self = Utils::OpenHandle(this);
3410 auto other = Utils::OpenHandle(*that);
3411 return self->SameValue(*other);
3415 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
3416 v8::Local<Value> key, v8::Local<Value> value) {
3417 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3418 auto self = Utils::OpenHandle(this);
3419 auto key_obj = Utils::OpenHandle(*key);
3420 auto value_obj = Utils::OpenHandle(*value);
3421 has_pending_exception =
3422 i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
3423 i::SLOPPY).is_null();
3424 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3429 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
3430 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3431 return Set(context, key, value).FromMaybe(false);
3435 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
3436 v8::Local<Value> value) {
3437 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3438 auto self = Utils::OpenHandle(this);
3439 auto value_obj = Utils::OpenHandle(*value);
3440 has_pending_exception = i::Object::SetElement(isolate, self, index, value_obj,
3441 i::SLOPPY).is_null();
3442 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3447 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
3448 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3449 return Set(context, index, value).FromMaybe(false);
3453 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3454 v8::Local<Name> key,
3455 v8::Local<Value> value) {
3456 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3458 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3459 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
3460 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3462 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
3463 isolate, self, key_obj, i::LookupIterator::OWN);
3464 Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3465 has_pending_exception = result.IsNothing();
3466 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3471 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3473 v8::Local<Value> value) {
3474 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3476 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3477 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3479 i::LookupIterator it(isolate, self, index, i::LookupIterator::OWN);
3480 Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3481 has_pending_exception = result.IsNothing();
3482 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3487 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
3488 v8::Local<Name> key,
3489 v8::Local<Value> value,
3490 v8::PropertyAttribute attributes) {
3491 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DefineOwnProperty()",
3493 auto self = Utils::OpenHandle(this);
3494 auto key_obj = Utils::OpenHandle(*key);
3495 auto value_obj = Utils::OpenHandle(*value);
3497 if (self->IsAccessCheckNeeded() && !isolate->MayAccess(self)) {
3498 isolate->ReportFailedAccessCheck(self);
3499 return Nothing<bool>();
3502 i::Handle<i::FixedArray> desc = isolate->factory()->NewFixedArray(3);
3503 desc->set(0, isolate->heap()->ToBoolean(!(attributes & v8::ReadOnly)));
3504 desc->set(1, isolate->heap()->ToBoolean(!(attributes & v8::DontEnum)));
3505 desc->set(2, isolate->heap()->ToBoolean(!(attributes & v8::DontDelete)));
3506 i::Handle<i::JSArray> desc_array =
3507 isolate->factory()->NewJSArrayWithElements(desc, i::FAST_ELEMENTS, 3);
3508 i::Handle<i::Object> args[] = {self, key_obj, value_obj, desc_array};
3509 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
3510 i::Handle<i::JSFunction> fun = isolate->object_define_own_property();
3511 i::Handle<i::Object> result;
3512 has_pending_exception =
3513 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
3515 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3516 return Just(result->BooleanValue());
3521 static i::MaybeHandle<i::Object> DefineObjectProperty(
3522 i::Handle<i::JSObject> js_object, i::Handle<i::Object> key,
3523 i::Handle<i::Object> value, PropertyAttributes attrs) {
3524 i::Isolate* isolate = js_object->GetIsolate();
3525 // Check if the given key is an array index.
3527 if (key->ToArrayIndex(&index)) {
3528 return i::JSObject::SetOwnElementIgnoreAttributes(js_object, index, value,
3532 i::Handle<i::Name> name;
3533 ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
3534 i::Runtime::ToName(isolate, key),
3535 i::MaybeHandle<i::Object>());
3537 return i::JSObject::DefinePropertyOrElementIgnoreAttributes(js_object, name,
3542 Maybe<bool> v8::Object::ForceSet(v8::Local<v8::Context> context,
3543 v8::Local<Value> key, v8::Local<Value> value,
3544 v8::PropertyAttribute attribs) {
3545 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3546 auto self = Utils::OpenHandle(this);
3547 auto key_obj = Utils::OpenHandle(*key);
3548 auto value_obj = Utils::OpenHandle(*value);
3549 has_pending_exception =
3550 DefineObjectProperty(self, key_obj, value_obj,
3551 static_cast<PropertyAttributes>(attribs)).is_null();
3552 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3557 bool v8::Object::ForceSet(v8::Local<Value> key, v8::Local<Value> value,
3558 v8::PropertyAttribute attribs) {
3559 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3560 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(),
3561 "v8::Object::ForceSet", false, i::HandleScope,
3563 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3564 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
3565 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3566 has_pending_exception =
3567 DefineObjectProperty(self, key_obj, value_obj,
3568 static_cast<PropertyAttributes>(attribs)).is_null();
3569 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, false);
3574 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
3576 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3577 auto self = Utils::OpenHandle(this);
3578 auto key_obj = Utils::OpenHandle(*key);
3579 i::Handle<i::Object> result;
3580 has_pending_exception =
3581 !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
3582 RETURN_ON_FAILED_EXECUTION(Value);
3583 RETURN_ESCAPED(Utils::ToLocal(result));
3587 Local<Value> v8::Object::Get(v8::Local<Value> key) {
3588 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3589 RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
3593 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
3594 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3595 auto self = Utils::OpenHandle(this);
3596 i::Handle<i::Object> result;
3597 has_pending_exception =
3598 !i::Object::GetElement(isolate, self, index).ToHandle(&result);
3599 RETURN_ON_FAILED_EXECUTION(Value);
3600 RETURN_ESCAPED(Utils::ToLocal(result));
3604 Local<Value> v8::Object::Get(uint32_t index) {
3605 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3606 RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
3610 Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes(
3611 Local<Context> context, Local<Value> key) {
3612 PREPARE_FOR_EXECUTION_PRIMITIVE(
3613 context, "v8::Object::GetPropertyAttributes()", PropertyAttribute);
3614 auto self = Utils::OpenHandle(this);
3615 auto key_obj = Utils::OpenHandle(*key);
3616 if (!key_obj->IsName()) {
3617 has_pending_exception = !i::Execution::ToString(
3618 isolate, key_obj).ToHandle(&key_obj);
3619 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3621 auto key_name = i::Handle<i::Name>::cast(key_obj);
3622 auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
3623 has_pending_exception = result.IsNothing();
3624 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3625 if (result.FromJust() == ABSENT) {
3626 return Just(static_cast<PropertyAttribute>(NONE));
3628 return Just(static_cast<PropertyAttribute>(result.FromJust()));
3632 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Local<Value> key) {
3633 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3634 return GetPropertyAttributes(context, key)
3635 .FromMaybe(static_cast<PropertyAttribute>(NONE));
3639 MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context,
3640 Local<String> key) {
3641 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyDescriptor()",
3643 auto obj = Utils::OpenHandle(this);
3644 auto key_name = Utils::OpenHandle(*key);
3645 i::Handle<i::Object> args[] = { obj, key_name };
3646 i::Handle<i::JSFunction> fun = isolate->object_get_own_property_descriptor();
3647 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
3648 i::Handle<i::Object> result;
3649 has_pending_exception =
3650 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
3652 RETURN_ON_FAILED_EXECUTION(Value);
3653 RETURN_ESCAPED(Utils::ToLocal(result));
3657 Local<Value> v8::Object::GetOwnPropertyDescriptor(Local<String> key) {
3658 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3659 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyDescriptor(context, key), Value);
3663 Local<Value> v8::Object::GetPrototype() {
3664 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3665 auto self = Utils::OpenHandle(this);
3666 i::PrototypeIterator iter(isolate, self);
3667 return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
3671 Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
3672 Local<Value> value) {
3673 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetPrototype()", bool);
3674 auto self = Utils::OpenHandle(this);
3675 auto value_obj = Utils::OpenHandle(*value);
3676 // We do not allow exceptions thrown while setting the prototype
3677 // to propagate outside.
3678 TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
3679 auto result = i::JSObject::SetPrototype(self, value_obj, false);
3680 has_pending_exception = result.is_null();
3681 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3686 bool v8::Object::SetPrototype(Local<Value> value) {
3687 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3688 return SetPrototype(context, value).FromMaybe(false);
3692 Local<Object> v8::Object::FindInstanceInPrototypeChain(
3693 v8::Local<FunctionTemplate> tmpl) {
3694 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3695 i::PrototypeIterator iter(isolate, *Utils::OpenHandle(this),
3696 i::PrototypeIterator::START_AT_RECEIVER);
3697 auto tmpl_info = *Utils::OpenHandle(*tmpl);
3698 while (!tmpl_info->IsTemplateFor(iter.GetCurrent())) {
3700 if (iter.IsAtEnd()) {
3701 return Local<Object>();
3704 return Utils::ToLocal(
3705 i::handle(i::JSObject::cast(iter.GetCurrent()), isolate));
3709 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
3710 PREPARE_FOR_EXECUTION(context, "v8::Object::GetPropertyNames()", Array);
3711 auto self = Utils::OpenHandle(this);
3712 i::Handle<i::FixedArray> value;
3713 has_pending_exception = !i::JSReceiver::GetKeys(
3714 self, i::JSReceiver::INCLUDE_PROTOS).ToHandle(&value);
3715 RETURN_ON_FAILED_EXECUTION(Array);
3716 // Because we use caching to speed up enumeration it is important
3717 // to never change the result of the basic enumeration function so
3718 // we clone the result.
3719 auto elms = isolate->factory()->CopyFixedArray(value);
3720 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3721 RETURN_ESCAPED(Utils::ToLocal(result));
3725 Local<Array> v8::Object::GetPropertyNames() {
3726 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3727 RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array);
3731 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
3732 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyNames()", Array);
3733 auto self = Utils::OpenHandle(this);
3734 i::Handle<i::FixedArray> value;
3735 has_pending_exception = !i::JSReceiver::GetKeys(
3736 self, i::JSReceiver::OWN_ONLY).ToHandle(&value);
3737 RETURN_ON_FAILED_EXECUTION(Array);
3738 // Because we use caching to speed up enumeration it is important
3739 // to never change the result of the basic enumeration function so
3740 // we clone the result.
3741 auto elms = isolate->factory()->CopyFixedArray(value);
3742 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3743 RETURN_ESCAPED(Utils::ToLocal(result));
3747 Local<Array> v8::Object::GetOwnPropertyNames() {
3748 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3749 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array);
3753 MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) {
3754 auto self = Utils::OpenHandle(this);
3755 auto isolate = self->GetIsolate();
3756 auto v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
3757 i::Handle<i::Object> name(self->class_name(), isolate);
3758 i::Handle<i::Object> tag;
3760 // Native implementation of Object.prototype.toString (v8natives.js):
3761 // var c = %_ClassOf(this);
3762 // if (c === 'Arguments') c = 'Object';
3763 // return "[object " + c + "]";
3765 if (!name->IsString()) {
3766 return v8::String::NewFromUtf8(v8_isolate, "[object ]",
3767 NewStringType::kNormal);
3769 auto class_name = i::Handle<i::String>::cast(name);
3770 if (i::String::Equals(class_name, isolate->factory()->Arguments_string())) {
3771 return v8::String::NewFromUtf8(v8_isolate, "[object Object]",
3772 NewStringType::kNormal);
3774 if (internal::FLAG_harmony_tostring) {
3775 PREPARE_FOR_EXECUTION(context, "v8::Object::ObjectProtoToString()", String);
3776 auto toStringTag = isolate->factory()->to_string_tag_symbol();
3777 has_pending_exception = !i::Runtime::GetObjectProperty(
3778 isolate, self, toStringTag).ToHandle(&tag);
3779 RETURN_ON_FAILED_EXECUTION(String);
3780 if (tag->IsString()) {
3781 class_name = Utils::OpenHandle(*handle_scope.Escape(
3782 Utils::ToLocal(i::Handle<i::String>::cast(tag))));
3785 const char* prefix = "[object ";
3786 Local<String> str = Utils::ToLocal(class_name);
3787 const char* postfix = "]";
3789 int prefix_len = i::StrLength(prefix);
3790 int str_len = str->Utf8Length();
3791 int postfix_len = i::StrLength(postfix);
3793 int buf_len = prefix_len + str_len + postfix_len;
3794 i::ScopedVector<char> buf(buf_len);
3797 char* ptr = buf.start();
3798 i::MemCopy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3801 // Write real content.
3802 str->WriteUtf8(ptr, str_len);
3806 i::MemCopy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3808 // Copy the buffer into a heap-allocated string and return it.
3809 return v8::String::NewFromUtf8(v8_isolate, buf.start(),
3810 NewStringType::kNormal, buf_len);
3814 Local<String> v8::Object::ObjectProtoToString() {
3815 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3816 RETURN_TO_LOCAL_UNCHECKED(ObjectProtoToString(context), String);
3820 Local<String> v8::Object::GetConstructorName() {
3821 auto self = Utils::OpenHandle(this);
3822 i::Handle<i::String> name(self->constructor_name());
3823 return Utils::ToLocal(name);
3827 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
3828 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Delete()", bool);
3829 auto self = Utils::OpenHandle(this);
3830 auto key_obj = Utils::OpenHandle(*key);
3831 i::Handle<i::Object> obj;
3832 has_pending_exception =
3833 !i::Runtime::DeleteObjectProperty(isolate, self, key_obj, i::SLOPPY)
3835 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3836 return Just(obj->IsTrue());
3840 bool v8::Object::Delete(v8::Local<Value> key) {
3841 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3842 return Delete(context, key).FromMaybe(false);
3846 Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) {
3847 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3848 auto self = Utils::OpenHandle(this);
3849 auto key_obj = Utils::OpenHandle(*key);
3850 Maybe<bool> maybe = Nothing<bool>();
3851 // Check if the given key is an array index.
3853 if (key_obj->ToArrayIndex(&index)) {
3854 maybe = i::JSReceiver::HasElement(self, index);
3856 // Convert the key to a name - possibly by calling back into JavaScript.
3857 i::Handle<i::Name> name;
3858 if (i::Runtime::ToName(isolate, key_obj).ToHandle(&name)) {
3859 maybe = i::JSReceiver::HasProperty(self, name);
3862 has_pending_exception = maybe.IsNothing();
3863 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3868 bool v8::Object::Has(v8::Local<Value> key) {
3869 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3870 return Has(context, key).FromMaybe(false);
3874 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
3875 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DeleteProperty()",
3877 auto self = Utils::OpenHandle(this);
3878 i::Handle<i::Object> obj;
3879 has_pending_exception =
3880 !i::JSReceiver::DeleteElement(self, index).ToHandle(&obj);
3881 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3882 return Just(obj->IsTrue());
3886 bool v8::Object::Delete(uint32_t index) {
3887 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3888 return Delete(context, index).FromMaybe(false);
3892 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
3893 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3894 auto self = Utils::OpenHandle(this);
3895 auto maybe = i::JSReceiver::HasElement(self, index);
3896 has_pending_exception = maybe.IsNothing();
3897 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3902 bool v8::Object::Has(uint32_t index) {
3903 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3904 return Has(context, index).FromMaybe(false);
3908 template <typename Getter, typename Setter, typename Data>
3909 static Maybe<bool> ObjectSetAccessor(Local<Context> context, Object* obj,
3910 Local<Name> name, Getter getter,
3911 Setter setter, Data data,
3912 AccessControl settings,
3913 PropertyAttribute attributes) {
3914 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetAccessor()", bool);
3915 v8::Local<AccessorSignature> signature;
3916 auto info = MakeAccessorInfo(name, getter, setter, data, settings, attributes,
3918 if (info.is_null()) return Nothing<bool>();
3919 bool fast = Utils::OpenHandle(obj)->HasFastProperties();
3920 i::Handle<i::Object> result;
3921 has_pending_exception =
3922 !i::JSObject::SetAccessor(Utils::OpenHandle(obj), info).ToHandle(&result);
3923 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3924 if (result->IsUndefined()) return Nothing<bool>();
3926 i::JSObject::MigrateSlowToFast(Utils::OpenHandle(obj), 0, "APISetAccessor");
3932 Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name,
3933 AccessorNameGetterCallback getter,
3934 AccessorNameSetterCallback setter,
3935 MaybeLocal<Value> data, AccessControl settings,
3936 PropertyAttribute attribute) {
3937 return ObjectSetAccessor(context, this, name, getter, setter,
3938 data.FromMaybe(Local<Value>()), settings, attribute);
3942 bool Object::SetAccessor(Local<String> name, AccessorGetterCallback getter,
3943 AccessorSetterCallback setter, v8::Local<Value> data,
3944 AccessControl settings, PropertyAttribute attributes) {
3945 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3946 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3947 attributes).FromMaybe(false);
3951 bool Object::SetAccessor(Local<Name> name, AccessorNameGetterCallback getter,
3952 AccessorNameSetterCallback setter,
3953 v8::Local<Value> data, AccessControl settings,
3954 PropertyAttribute attributes) {
3955 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3956 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3957 attributes).FromMaybe(false);
3961 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
3962 Local<Function> setter,
3963 PropertyAttribute attribute,
3964 AccessControl settings) {
3965 // TODO(verwaest): Remove |settings|.
3966 DCHECK_EQ(v8::DEFAULT, settings);
3967 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3969 i::HandleScope scope(isolate);
3970 i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
3971 i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
3972 if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
3973 i::JSObject::DefineAccessor(v8::Utils::OpenHandle(this),
3974 v8::Utils::OpenHandle(*name),
3977 static_cast<PropertyAttributes>(attribute));
3981 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
3983 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasOwnProperty()",
3985 auto self = Utils::OpenHandle(this);
3986 auto key_val = Utils::OpenHandle(*key);
3987 auto result = i::JSReceiver::HasOwnProperty(self, key_val);
3988 has_pending_exception = result.IsNothing();
3989 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3994 bool v8::Object::HasOwnProperty(Local<String> key) {
3995 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3996 return HasOwnProperty(context, key).FromMaybe(false);
4000 Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context,
4002 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasRealNamedProperty()",
4004 auto self = Utils::OpenHandle(this);
4005 auto key_val = Utils::OpenHandle(*key);
4006 auto result = i::JSObject::HasRealNamedProperty(self, key_val);
4007 has_pending_exception = result.IsNothing();
4008 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4013 bool v8::Object::HasRealNamedProperty(Local<String> key) {
4014 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4015 return HasRealNamedProperty(context, key).FromMaybe(false);
4019 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
4021 PREPARE_FOR_EXECUTION_PRIMITIVE(context,
4022 "v8::Object::HasRealIndexedProperty()", bool);
4023 auto self = Utils::OpenHandle(this);
4024 auto result = i::JSObject::HasRealElementProperty(self, index);
4025 has_pending_exception = result.IsNothing();
4026 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4031 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
4032 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4033 return HasRealIndexedProperty(context, index).FromMaybe(false);
4037 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
4039 PREPARE_FOR_EXECUTION_PRIMITIVE(
4040 context, "v8::Object::HasRealNamedCallbackProperty()", bool);
4041 auto self = Utils::OpenHandle(this);
4042 auto key_val = Utils::OpenHandle(*key);
4043 auto result = i::JSObject::HasRealNamedCallbackProperty(self, key_val);
4044 has_pending_exception = result.IsNothing();
4045 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4050 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) {
4051 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4052 return HasRealNamedCallbackProperty(context, key).FromMaybe(false);
4056 bool v8::Object::HasNamedLookupInterceptor() {
4057 auto self = Utils::OpenHandle(this);
4058 return self->HasNamedInterceptor();
4062 bool v8::Object::HasIndexedLookupInterceptor() {
4063 auto self = Utils::OpenHandle(this);
4064 return self->HasIndexedInterceptor();
4068 MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4069 Local<Context> context, Local<Name> key) {
4070 PREPARE_FOR_EXECUTION(
4071 context, "v8::Object::GetRealNamedPropertyInPrototypeChain()", Value);
4072 auto self = Utils::OpenHandle(this);
4073 auto key_obj = Utils::OpenHandle(*key);
4074 i::PrototypeIterator iter(isolate, self);
4075 if (iter.IsAtEnd()) return MaybeLocal<Value>();
4076 auto proto = i::PrototypeIterator::GetCurrent(iter);
4077 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4078 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4079 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4080 Local<Value> result;
4081 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4082 RETURN_ON_FAILED_EXECUTION(Value);
4083 if (!it.IsFound()) return MaybeLocal<Value>();
4084 RETURN_ESCAPED(result);
4088 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4089 Local<String> key) {
4090 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4091 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedPropertyInPrototypeChain(context, key),
4096 Maybe<PropertyAttribute>
4097 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(
4098 Local<Context> context, Local<Name> key) {
4099 PREPARE_FOR_EXECUTION_PRIMITIVE(
4100 context, "v8::Object::GetRealNamedPropertyAttributesInPrototypeChain()",
4102 auto self = Utils::OpenHandle(this);
4103 auto key_obj = Utils::OpenHandle(*key);
4104 i::PrototypeIterator iter(isolate, self);
4105 if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
4106 auto proto = i::PrototypeIterator::GetCurrent(iter);
4107 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4108 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4109 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4110 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4111 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4112 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4113 if (result.FromJust() == ABSENT) {
4114 return Just(static_cast<PropertyAttribute>(NONE));
4116 return Just<PropertyAttribute>(
4117 static_cast<PropertyAttribute>(result.FromJust()));
4121 Maybe<PropertyAttribute>
4122 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(Local<String> key) {
4123 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4124 return GetRealNamedPropertyAttributesInPrototypeChain(context, key);
4128 MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context,
4130 PREPARE_FOR_EXECUTION(context, "v8::Object::GetRealNamedProperty()", Value);
4131 auto self = Utils::OpenHandle(this);
4132 auto key_obj = Utils::OpenHandle(*key);
4133 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4134 isolate, self, key_obj,
4135 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4136 Local<Value> result;
4137 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4138 RETURN_ON_FAILED_EXECUTION(Value);
4139 if (!it.IsFound()) return MaybeLocal<Value>();
4140 RETURN_ESCAPED(result);
4144 Local<Value> v8::Object::GetRealNamedProperty(Local<String> key) {
4145 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4146 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedProperty(context, key), Value);
4150 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4151 Local<Context> context, Local<Name> key) {
4152 PREPARE_FOR_EXECUTION_PRIMITIVE(
4153 context, "v8::Object::GetRealNamedPropertyAttributes()",
4155 auto self = Utils::OpenHandle(this);
4156 auto key_obj = Utils::OpenHandle(*key);
4157 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4158 isolate, self, key_obj,
4159 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4160 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4161 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4162 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4163 if (result.FromJust() == ABSENT) {
4164 return Just(static_cast<PropertyAttribute>(NONE));
4166 return Just<PropertyAttribute>(
4167 static_cast<PropertyAttribute>(result.FromJust()));
4171 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4172 Local<String> key) {
4173 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4174 return GetRealNamedPropertyAttributes(context, key);
4178 Local<v8::Object> v8::Object::Clone() {
4179 auto self = Utils::OpenHandle(this);
4180 auto isolate = self->GetIsolate();
4182 auto result = isolate->factory()->CopyJSObject(self);
4183 CHECK(!result.is_null());
4184 return Utils::ToLocal(result);
4188 Local<v8::Context> v8::Object::CreationContext() {
4189 auto self = Utils::OpenHandle(this);
4190 auto context = handle(self->GetCreationContext());
4191 return Utils::ToLocal(context);
4195 int v8::Object::GetIdentityHash() {
4196 auto isolate = Utils::OpenHandle(this)->GetIsolate();
4197 i::HandleScope scope(isolate);
4198 auto self = Utils::OpenHandle(this);
4199 return i::JSReceiver::GetOrCreateIdentityHash(self)->value();
4203 bool v8::Object::SetHiddenValue(v8::Local<v8::String> key,
4204 v8::Local<v8::Value> value) {
4205 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4206 if (value.IsEmpty()) return DeleteHiddenValue(key);
4208 i::HandleScope scope(isolate);
4209 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4210 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4211 i::Handle<i::String> key_string =
4212 isolate->factory()->InternalizeString(key_obj);
4213 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4214 i::Handle<i::Object> result =
4215 i::JSObject::SetHiddenProperty(self, key_string, value_obj);
4216 return *result == *self;
4220 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Local<v8::String> key) {
4221 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4223 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4224 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4225 i::Handle<i::String> key_string =
4226 isolate->factory()->InternalizeString(key_obj);
4227 i::Handle<i::Object> result(self->GetHiddenProperty(key_string), isolate);
4228 if (result->IsTheHole()) return v8::Local<v8::Value>();
4229 return Utils::ToLocal(result);
4233 bool v8::Object::DeleteHiddenValue(v8::Local<v8::String> key) {
4234 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4236 i::HandleScope scope(isolate);
4237 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4238 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4239 i::Handle<i::String> key_string =
4240 isolate->factory()->InternalizeString(key_obj);
4241 i::JSObject::DeleteHiddenProperty(self, key_string);
4246 bool v8::Object::IsCallable() {
4247 auto self = Utils::OpenHandle(this);
4248 return self->IsCallable();
4252 MaybeLocal<Value> Object::CallAsFunction(Local<Context> context,
4253 Local<Value> recv, int argc,
4254 Local<Value> argv[]) {
4255 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Object::CallAsFunction()",
4257 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4258 auto self = Utils::OpenHandle(this);
4259 auto recv_obj = Utils::OpenHandle(*recv);
4260 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4261 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4262 i::Handle<i::JSFunction> fun;
4263 if (self->IsJSFunction()) {
4264 fun = i::Handle<i::JSFunction>::cast(self);
4266 i::Handle<i::Object> delegate;
4267 has_pending_exception = !i::Execution::TryGetFunctionDelegate(isolate, self)
4268 .ToHandle(&delegate);
4269 RETURN_ON_FAILED_EXECUTION(Value);
4270 fun = i::Handle<i::JSFunction>::cast(delegate);
4273 Local<Value> result;
4274 has_pending_exception =
4276 i::Execution::Call(isolate, fun, recv_obj, argc, args, true),
4278 RETURN_ON_FAILED_EXECUTION(Value);
4279 RETURN_ESCAPED(result);
4283 Local<v8::Value> Object::CallAsFunction(v8::Local<v8::Value> recv, int argc,
4284 v8::Local<v8::Value> argv[]) {
4285 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4286 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4287 RETURN_TO_LOCAL_UNCHECKED(CallAsFunction(context, recv, argc, argv_cast),
4292 MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc,
4293 Local<Value> argv[]) {
4294 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context,
4295 "v8::Object::CallAsConstructor()", Value);
4296 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4297 auto self = Utils::OpenHandle(this);
4298 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4299 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4300 if (self->IsJSFunction()) {
4301 auto fun = i::Handle<i::JSFunction>::cast(self);
4302 Local<Value> result;
4303 has_pending_exception =
4304 !ToLocal<Value>(i::Execution::New(fun, argc, args), &result);
4305 RETURN_ON_FAILED_EXECUTION(Value);
4306 RETURN_ESCAPED(result);
4308 i::Handle<i::Object> delegate;
4309 has_pending_exception = !i::Execution::TryGetConstructorDelegate(
4310 isolate, self).ToHandle(&delegate);
4311 RETURN_ON_FAILED_EXECUTION(Value);
4312 if (!delegate->IsUndefined()) {
4313 auto fun = i::Handle<i::JSFunction>::cast(delegate);
4314 Local<Value> result;
4315 has_pending_exception =
4316 !ToLocal<Value>(i::Execution::Call(isolate, fun, self, argc, args),
4318 RETURN_ON_FAILED_EXECUTION(Value);
4319 DCHECK(!delegate->IsUndefined());
4320 RETURN_ESCAPED(result);
4322 return MaybeLocal<Value>();
4326 Local<v8::Value> Object::CallAsConstructor(int argc,
4327 v8::Local<v8::Value> argv[]) {
4328 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4329 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4330 RETURN_TO_LOCAL_UNCHECKED(CallAsConstructor(context, argc, argv_cast), Value);
4334 MaybeLocal<Function> Function::New(Local<Context> context,
4335 FunctionCallback callback, Local<Value> data,
4337 i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
4338 LOG_API(isolate, "Function::New");
4340 return FunctionTemplateNew(isolate, callback, data, Local<Signature>(),
4341 length, true)->GetFunction(context);
4345 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback,
4346 Local<Value> data, int length) {
4347 return Function::New(v8_isolate->GetCurrentContext(), callback, data, length)
4348 .FromMaybe(Local<Function>());
4352 Local<v8::Object> Function::NewInstance() const {
4353 return NewInstance(Isolate::GetCurrent()->GetCurrentContext(), 0, NULL)
4354 .FromMaybe(Local<Object>());
4358 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
4359 v8::Local<v8::Value> argv[]) const {
4360 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::NewInstance()",
4362 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4363 auto self = Utils::OpenHandle(this);
4364 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4365 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4366 Local<Object> result;
4367 has_pending_exception =
4368 !ToLocal<Object>(i::Execution::New(self, argc, args), &result);
4369 RETURN_ON_FAILED_EXECUTION(Object);
4370 RETURN_ESCAPED(result);
4374 Local<v8::Object> Function::NewInstance(int argc,
4375 v8::Local<v8::Value> argv[]) const {
4376 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4377 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context, argc, argv), Object);
4381 MaybeLocal<v8::Value> Function::Call(Local<Context> context,
4382 v8::Local<v8::Value> recv, int argc,
4383 v8::Local<v8::Value> argv[]) {
4384 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::Call()", Value);
4385 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4386 auto self = Utils::OpenHandle(this);
4387 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
4388 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4389 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4390 Local<Value> result;
4391 has_pending_exception =
4393 i::Execution::Call(isolate, self, recv_obj, argc, args, true),
4395 RETURN_ON_FAILED_EXECUTION(Value);
4396 RETURN_ESCAPED(result);
4400 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc,
4401 v8::Local<v8::Value> argv[]) {
4402 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4403 RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value);
4407 void Function::SetName(v8::Local<v8::String> name) {
4408 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4409 func->shared()->set_name(*Utils::OpenHandle(*name));
4413 Local<Value> Function::GetName() const {
4414 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4415 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name(),
4416 func->GetIsolate()));
4420 Local<Value> Function::GetInferredName() const {
4421 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4422 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
4423 func->GetIsolate()));
4427 Local<Value> Function::GetDisplayName() const {
4428 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4430 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4431 i::Handle<i::String> property_name =
4432 isolate->factory()->NewStringFromStaticChars("displayName");
4433 i::Handle<i::Object> value =
4434 i::JSReceiver::GetDataProperty(func, property_name);
4435 if (value->IsString()) {
4436 i::Handle<i::String> name = i::Handle<i::String>::cast(value);
4437 if (name->length() > 0) return Utils::ToLocal(name);
4439 return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
4443 ScriptOrigin Function::GetScriptOrigin() const {
4444 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4445 if (func->shared()->script()->IsScript()) {
4446 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4447 return GetScriptOriginForScript(func->GetIsolate(), script);
4449 return v8::ScriptOrigin(Local<Value>());
4453 const int Function::kLineOffsetNotFound = -1;
4456 int Function::GetScriptLineNumber() const {
4457 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4458 if (func->shared()->script()->IsScript()) {
4459 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4460 return i::Script::GetLineNumber(script, func->shared()->start_position());
4462 return kLineOffsetNotFound;
4466 int Function::GetScriptColumnNumber() const {
4467 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4468 if (func->shared()->script()->IsScript()) {
4469 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4470 return i::Script::GetColumnNumber(script, func->shared()->start_position());
4472 return kLineOffsetNotFound;
4476 bool Function::IsBuiltin() const {
4477 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4478 return func->IsBuiltin();
4482 int Function::ScriptId() const {
4483 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4484 if (!func->shared()->script()->IsScript()) {
4485 return v8::UnboundScript::kNoScriptId;
4487 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4488 return script->id()->value();
4492 Local<v8::Value> Function::GetBoundFunction() const {
4493 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4494 if (!func->shared()->bound()) {
4495 return v8::Undefined(reinterpret_cast<v8::Isolate*>(func->GetIsolate()));
4497 i::Handle<i::FixedArray> bound_args = i::Handle<i::FixedArray>(
4498 i::FixedArray::cast(func->function_bindings()));
4499 i::Handle<i::Object> original(
4500 bound_args->get(i::JSFunction::kBoundFunctionIndex),
4501 func->GetIsolate());
4502 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(original));
4506 int Name::GetIdentityHash() {
4507 auto self = Utils::OpenHandle(this);
4508 return static_cast<int>(self->Hash());
4512 int String::Length() const {
4513 i::Handle<i::String> str = Utils::OpenHandle(this);
4514 return str->length();
4518 bool String::IsOneByte() const {
4519 i::Handle<i::String> str = Utils::OpenHandle(this);
4520 return str->HasOnlyOneByteChars();
4524 // Helpers for ContainsOnlyOneByteHelper
4525 template<size_t size> struct OneByteMask;
4526 template<> struct OneByteMask<4> {
4527 static const uint32_t value = 0xFF00FF00;
4529 template<> struct OneByteMask<8> {
4530 static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
4532 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
4533 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
4534 static inline bool Unaligned(const uint16_t* chars) {
4535 return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
4539 static inline const uint16_t* Align(const uint16_t* chars) {
4540 return reinterpret_cast<uint16_t*>(
4541 reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
4544 class ContainsOnlyOneByteHelper {
4546 ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
4547 bool Check(i::String* string) {
4548 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
4549 if (cons_string == NULL) return is_one_byte_;
4550 return CheckCons(cons_string);
4552 void VisitOneByteString(const uint8_t* chars, int length) {
4555 void VisitTwoByteString(const uint16_t* chars, int length) {
4556 // Accumulated bits.
4558 // Align to uintptr_t.
4559 const uint16_t* end = chars + length;
4560 while (Unaligned(chars) && chars != end) {
4563 // Read word aligned in blocks,
4564 // checking the return value at the end of each block.
4565 const uint16_t* aligned_end = Align(end);
4566 const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
4567 const int inner_loops = 16;
4568 while (chars + inner_loops*increment < aligned_end) {
4569 for (int i = 0; i < inner_loops; i++) {
4570 acc |= *reinterpret_cast<const uintptr_t*>(chars);
4573 // Check for early return.
4574 if ((acc & kOneByteMask) != 0) {
4575 is_one_byte_ = false;
4580 while (chars != end) {
4584 if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
4588 bool CheckCons(i::ConsString* cons_string) {
4590 // Check left side if flat.
4591 i::String* left = cons_string->first();
4592 i::ConsString* left_as_cons =
4593 i::String::VisitFlat(this, left, 0);
4594 if (!is_one_byte_) return false;
4595 // Check right side if flat.
4596 i::String* right = cons_string->second();
4597 i::ConsString* right_as_cons =
4598 i::String::VisitFlat(this, right, 0);
4599 if (!is_one_byte_) return false;
4600 // Standard recurse/iterate trick.
4601 if (left_as_cons != NULL && right_as_cons != NULL) {
4602 if (left->length() < right->length()) {
4603 CheckCons(left_as_cons);
4604 cons_string = right_as_cons;
4606 CheckCons(right_as_cons);
4607 cons_string = left_as_cons;
4609 // Check fast return.
4610 if (!is_one_byte_) return false;
4613 // Descend left in place.
4614 if (left_as_cons != NULL) {
4615 cons_string = left_as_cons;
4618 // Descend right in place.
4619 if (right_as_cons != NULL) {
4620 cons_string = right_as_cons;
4626 return is_one_byte_;
4629 DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
4633 bool String::ContainsOnlyOneByte() const {
4634 i::Handle<i::String> str = Utils::OpenHandle(this);
4635 if (str->HasOnlyOneByteChars()) return true;
4636 ContainsOnlyOneByteHelper helper;
4637 return helper.Check(*str);
4641 class Utf8LengthHelper : public i::AllStatic {
4644 kEndsWithLeadingSurrogate = 1 << 0,
4645 kStartsWithTrailingSurrogate = 1 << 1,
4646 kLeftmostEdgeIsCalculated = 1 << 2,
4647 kRightmostEdgeIsCalculated = 1 << 3,
4648 kLeftmostEdgeIsSurrogate = 1 << 4,
4649 kRightmostEdgeIsSurrogate = 1 << 5
4652 static const uint8_t kInitialState = 0;
4654 static inline bool EndsWithSurrogate(uint8_t state) {
4655 return state & kEndsWithLeadingSurrogate;
4658 static inline bool StartsWithSurrogate(uint8_t state) {
4659 return state & kStartsWithTrailingSurrogate;
4664 Visitor() : utf8_length_(0), state_(kInitialState) {}
4666 void VisitOneByteString(const uint8_t* chars, int length) {
4667 int utf8_length = 0;
4668 // Add in length 1 for each non-Latin1 character.
4669 for (int i = 0; i < length; i++) {
4670 utf8_length += *chars++ >> 7;
4672 // Add in length 1 for each character.
4673 utf8_length_ = utf8_length + length;
4674 state_ = kInitialState;
4677 void VisitTwoByteString(const uint16_t* chars, int length) {
4678 int utf8_length = 0;
4679 int last_character = unibrow::Utf16::kNoPreviousCharacter;
4680 for (int i = 0; i < length; i++) {
4681 uint16_t c = chars[i];
4682 utf8_length += unibrow::Utf8::Length(c, last_character);
4685 utf8_length_ = utf8_length;
4687 if (unibrow::Utf16::IsTrailSurrogate(chars[0])) {
4688 state |= kStartsWithTrailingSurrogate;
4690 if (unibrow::Utf16::IsLeadSurrogate(chars[length-1])) {
4691 state |= kEndsWithLeadingSurrogate;
4696 static i::ConsString* VisitFlat(i::String* string,
4700 i::ConsString* cons_string = i::String::VisitFlat(&visitor, string);
4701 *length = visitor.utf8_length_;
4702 *state = visitor.state_;
4709 DISALLOW_COPY_AND_ASSIGN(Visitor);
4712 static inline void MergeLeafLeft(int* length,
4714 uint8_t leaf_state) {
4715 bool edge_surrogate = StartsWithSurrogate(leaf_state);
4716 if (!(*state & kLeftmostEdgeIsCalculated)) {
4717 DCHECK(!(*state & kLeftmostEdgeIsSurrogate));
4718 *state |= kLeftmostEdgeIsCalculated
4719 | (edge_surrogate ? kLeftmostEdgeIsSurrogate : 0);
4720 } else if (EndsWithSurrogate(*state) && edge_surrogate) {
4721 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4723 if (EndsWithSurrogate(leaf_state)) {
4724 *state |= kEndsWithLeadingSurrogate;
4726 *state &= ~kEndsWithLeadingSurrogate;
4730 static inline void MergeLeafRight(int* length,
4732 uint8_t leaf_state) {
4733 bool edge_surrogate = EndsWithSurrogate(leaf_state);
4734 if (!(*state & kRightmostEdgeIsCalculated)) {
4735 DCHECK(!(*state & kRightmostEdgeIsSurrogate));
4736 *state |= (kRightmostEdgeIsCalculated
4737 | (edge_surrogate ? kRightmostEdgeIsSurrogate : 0));
4738 } else if (edge_surrogate && StartsWithSurrogate(*state)) {
4739 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4741 if (StartsWithSurrogate(leaf_state)) {
4742 *state |= kStartsWithTrailingSurrogate;
4744 *state &= ~kStartsWithTrailingSurrogate;
4748 static inline void MergeTerminal(int* length,
4750 uint8_t* state_out) {
4751 DCHECK((state & kLeftmostEdgeIsCalculated) &&
4752 (state & kRightmostEdgeIsCalculated));
4753 if (EndsWithSurrogate(state) && StartsWithSurrogate(state)) {
4754 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4756 *state_out = kInitialState |
4757 (state & kLeftmostEdgeIsSurrogate ? kStartsWithTrailingSurrogate : 0) |
4758 (state & kRightmostEdgeIsSurrogate ? kEndsWithLeadingSurrogate : 0);
4761 static int Calculate(i::ConsString* current, uint8_t* state_out) {
4762 using namespace internal;
4763 int total_length = 0;
4764 uint8_t state = kInitialState;
4766 i::String* left = current->first();
4767 i::String* right = current->second();
4768 uint8_t right_leaf_state;
4769 uint8_t left_leaf_state;
4771 ConsString* left_as_cons =
4772 Visitor::VisitFlat(left, &leaf_length, &left_leaf_state);
4773 if (left_as_cons == NULL) {
4774 total_length += leaf_length;
4775 MergeLeafLeft(&total_length, &state, left_leaf_state);
4777 ConsString* right_as_cons =
4778 Visitor::VisitFlat(right, &leaf_length, &right_leaf_state);
4779 if (right_as_cons == NULL) {
4780 total_length += leaf_length;
4781 MergeLeafRight(&total_length, &state, right_leaf_state);
4782 if (left_as_cons != NULL) {
4783 // 1 Leaf node. Descend in place.
4784 current = left_as_cons;
4788 MergeTerminal(&total_length, state, state_out);
4789 return total_length;
4791 } else if (left_as_cons == NULL) {
4792 // 1 Leaf node. Descend in place.
4793 current = right_as_cons;
4796 // Both strings are ConsStrings.
4797 // Recurse on smallest.
4798 if (left->length() < right->length()) {
4799 total_length += Calculate(left_as_cons, &left_leaf_state);
4800 MergeLeafLeft(&total_length, &state, left_leaf_state);
4801 current = right_as_cons;
4803 total_length += Calculate(right_as_cons, &right_leaf_state);
4804 MergeLeafRight(&total_length, &state, right_leaf_state);
4805 current = left_as_cons;
4812 static inline int Calculate(i::ConsString* current) {
4813 uint8_t state = kInitialState;
4814 return Calculate(current, &state);
4818 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8LengthHelper);
4822 static int Utf8Length(i::String* str, i::Isolate* isolate) {
4823 int length = str->length();
4824 if (length == 0) return 0;
4826 i::ConsString* cons_string =
4827 Utf8LengthHelper::Visitor::VisitFlat(str, &length, &state);
4828 if (cons_string == NULL) return length;
4829 return Utf8LengthHelper::Calculate(cons_string);
4833 int String::Utf8Length() const {
4834 i::Handle<i::String> str = Utils::OpenHandle(this);
4835 i::Isolate* isolate = str->GetIsolate();
4836 return v8::Utf8Length(*str, isolate);
4840 class Utf8WriterVisitor {
4845 bool skip_capacity_check,
4846 bool replace_invalid_utf8)
4847 : early_termination_(false),
4848 last_character_(unibrow::Utf16::kNoPreviousCharacter),
4851 capacity_(capacity),
4852 skip_capacity_check_(capacity == -1 || skip_capacity_check),
4853 replace_invalid_utf8_(replace_invalid_utf8),
4854 utf16_chars_read_(0) {
4857 static int WriteEndCharacter(uint16_t character,
4861 bool replace_invalid_utf8) {
4862 using namespace unibrow;
4863 DCHECK(remaining > 0);
4864 // We can't use a local buffer here because Encode needs to modify
4865 // previous characters in the stream. We know, however, that
4866 // exactly one character will be advanced.
4867 if (Utf16::IsSurrogatePair(last_character, character)) {
4868 int written = Utf8::Encode(buffer,
4871 replace_invalid_utf8);
4872 DCHECK(written == 1);
4875 // Use a scratch buffer to check the required characters.
4876 char temp_buffer[Utf8::kMaxEncodedSize];
4877 // Can't encode using last_character as gcc has array bounds issues.
4878 int written = Utf8::Encode(temp_buffer,
4880 Utf16::kNoPreviousCharacter,
4881 replace_invalid_utf8);
4883 if (written > remaining) return 0;
4884 // Copy over the character from temp_buffer.
4885 for (int j = 0; j < written; j++) {
4886 buffer[j] = temp_buffer[j];
4891 // Visit writes out a group of code units (chars) of a v8::String to the
4892 // internal buffer_. This is done in two phases. The first phase calculates a
4893 // pesimistic estimate (writable_length) on how many code units can be safely
4894 // written without exceeding the buffer capacity and without writing the last
4895 // code unit (it could be a lead surrogate). The estimated number of code
4896 // units is then written out in one go, and the reported byte usage is used
4897 // to correct the estimate. This is repeated until the estimate becomes <= 0
4898 // or all code units have been written out. The second phase writes out code
4899 // units until the buffer capacity is reached, would be exceeded by the next
4900 // unit, or all units have been written out.
4901 template<typename Char>
4902 void Visit(const Char* chars, const int length) {
4903 using namespace unibrow;
4904 DCHECK(!early_termination_);
4905 if (length == 0) return;
4906 // Copy state to stack.
4907 char* buffer = buffer_;
4908 int last_character =
4909 sizeof(Char) == 1 ? Utf16::kNoPreviousCharacter : last_character_;
4911 // Do a fast loop where there is no exit capacity check.
4914 if (skip_capacity_check_) {
4915 fast_length = length;
4917 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4918 // Need enough space to write everything but one character.
4919 STATIC_ASSERT(Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 3);
4920 int max_size_per_char = sizeof(Char) == 1 ? 2 : 3;
4921 int writable_length =
4922 (remaining_capacity - max_size_per_char)/max_size_per_char;
4923 // Need to drop into slow loop.
4924 if (writable_length <= 0) break;
4925 fast_length = i + writable_length;
4926 if (fast_length > length) fast_length = length;
4928 // Write the characters to the stream.
4929 if (sizeof(Char) == 1) {
4930 for (; i < fast_length; i++) {
4932 Utf8::EncodeOneByte(buffer, static_cast<uint8_t>(*chars++));
4933 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4936 for (; i < fast_length; i++) {
4937 uint16_t character = *chars++;
4938 buffer += Utf8::Encode(buffer,
4941 replace_invalid_utf8_);
4942 last_character = character;
4943 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4946 // Array is fully written. Exit.
4947 if (fast_length == length) {
4948 // Write state back out to object.
4949 last_character_ = last_character;
4951 utf16_chars_read_ += length;
4955 DCHECK(!skip_capacity_check_);
4956 // Slow loop. Must check capacity on each iteration.
4957 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4958 DCHECK(remaining_capacity >= 0);
4959 for (; i < length && remaining_capacity > 0; i++) {
4960 uint16_t character = *chars++;
4961 // remaining_capacity is <= 3 bytes at this point, so we do not write out
4962 // an umatched lead surrogate.
4963 if (replace_invalid_utf8_ && Utf16::IsLeadSurrogate(character)) {
4964 early_termination_ = true;
4967 int written = WriteEndCharacter(character,
4971 replace_invalid_utf8_);
4973 early_termination_ = true;
4977 remaining_capacity -= written;
4978 last_character = character;
4980 // Write state back out to object.
4981 last_character_ = last_character;
4983 utf16_chars_read_ += i;
4986 inline bool IsDone() {
4987 return early_termination_;
4990 inline void VisitOneByteString(const uint8_t* chars, int length) {
4991 Visit(chars, length);
4994 inline void VisitTwoByteString(const uint16_t* chars, int length) {
4995 Visit(chars, length);
4998 int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
4999 // Write out number of utf16 characters written to the stream.
5000 if (utf16_chars_read_out != NULL) {
5001 *utf16_chars_read_out = utf16_chars_read_;
5003 // Only null terminate if all of the string was written and there's space.
5005 !early_termination_ &&
5006 (capacity_ == -1 || (buffer_ - start_) < capacity_)) {
5009 return static_cast<int>(buffer_ - start_);
5013 bool early_termination_;
5014 int last_character_;
5018 bool const skip_capacity_check_;
5019 bool const replace_invalid_utf8_;
5020 int utf16_chars_read_;
5021 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
5025 static bool RecursivelySerializeToUtf8(i::String* current,
5026 Utf8WriterVisitor* writer,
5027 int recursion_budget) {
5028 while (!writer->IsDone()) {
5029 i::ConsString* cons_string = i::String::VisitFlat(writer, current);
5030 if (cons_string == NULL) return true; // Leaf node.
5031 if (recursion_budget <= 0) return false;
5032 // Must write the left branch first.
5033 i::String* first = cons_string->first();
5034 bool success = RecursivelySerializeToUtf8(first,
5036 recursion_budget - 1);
5037 if (!success) return false;
5038 // Inline tail recurse for right branch.
5039 current = cons_string->second();
5045 int String::WriteUtf8(char* buffer,
5048 int options) const {
5049 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
5050 LOG_API(isolate, "String::WriteUtf8");
5052 i::Handle<i::String> str = Utils::OpenHandle(this);
5053 if (options & HINT_MANY_WRITES_EXPECTED) {
5054 str = i::String::Flatten(str); // Flatten the string for efficiency.
5056 const int string_length = str->length();
5057 bool write_null = !(options & NO_NULL_TERMINATION);
5058 bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
5059 int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
5060 // First check if we can just write the string without checking capacity.
5061 if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
5062 Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
5063 const int kMaxRecursion = 100;
5064 bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
5065 if (success) return writer.CompleteWrite(write_null, nchars_ref);
5066 } else if (capacity >= string_length) {
5067 // First check that the buffer is large enough.
5068 int utf8_bytes = v8::Utf8Length(*str, str->GetIsolate());
5069 if (utf8_bytes <= capacity) {
5070 // one-byte fast path.
5071 if (utf8_bytes == string_length) {
5072 WriteOneByte(reinterpret_cast<uint8_t*>(buffer), 0, capacity, options);
5073 if (nchars_ref != NULL) *nchars_ref = string_length;
5074 if (write_null && (utf8_bytes+1 <= capacity)) {
5075 return string_length + 1;
5077 return string_length;
5079 if (write_null && (utf8_bytes+1 > capacity)) {
5080 options |= NO_NULL_TERMINATION;
5082 // Recurse once without a capacity limit.
5083 // This will get into the first branch above.
5084 // TODO(dcarney) Check max left rec. in Utf8Length and fall through.
5085 return WriteUtf8(buffer, -1, nchars_ref, options);
5088 // Recursive slow path can potentially be unreasonable slow. Flatten.
5089 str = i::String::Flatten(str);
5090 Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
5091 i::String::VisitFlat(&writer, *str);
5092 return writer.CompleteWrite(write_null, nchars_ref);
5096 template<typename CharType>
5097 static inline int WriteHelper(const String* string,
5102 i::Isolate* isolate = Utils::OpenHandle(string)->GetIsolate();
5103 LOG_API(isolate, "String::Write");
5105 DCHECK(start >= 0 && length >= -1);
5106 i::Handle<i::String> str = Utils::OpenHandle(string);
5107 if (options & String::HINT_MANY_WRITES_EXPECTED) {
5108 // Flatten the string for efficiency. This applies whether we are
5109 // using StringCharacterStream or Get(i) to access the characters.
5110 str = i::String::Flatten(str);
5112 int end = start + length;
5113 if ((length == -1) || (length > str->length() - start) )
5114 end = str->length();
5115 if (end < 0) return 0;
5116 i::String::WriteToFlat(*str, buffer, start, end);
5117 if (!(options & String::NO_NULL_TERMINATION) &&
5118 (length == -1 || end - start < length)) {
5119 buffer[end - start] = '\0';
5125 int String::WriteOneByte(uint8_t* buffer,
5128 int options) const {
5129 return WriteHelper(this, buffer, start, length, options);
5133 int String::Write(uint16_t* buffer,
5136 int options) const {
5137 return WriteHelper(this, buffer, start, length, options);
5141 bool v8::String::IsExternal() const {
5142 i::Handle<i::String> str = Utils::OpenHandle(this);
5143 return i::StringShape(*str).IsExternalTwoByte();
5147 bool v8::String::IsExternalOneByte() const {
5148 i::Handle<i::String> str = Utils::OpenHandle(this);
5149 return i::StringShape(*str).IsExternalOneByte();
5153 void v8::String::VerifyExternalStringResource(
5154 v8::String::ExternalStringResource* value) const {
5155 i::Handle<i::String> str = Utils::OpenHandle(this);
5156 const v8::String::ExternalStringResource* expected;
5157 if (i::StringShape(*str).IsExternalTwoByte()) {
5158 const void* resource =
5159 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5160 expected = reinterpret_cast<const ExternalStringResource*>(resource);
5164 CHECK_EQ(expected, value);
5167 void v8::String::VerifyExternalStringResourceBase(
5168 v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
5169 i::Handle<i::String> str = Utils::OpenHandle(this);
5170 const v8::String::ExternalStringResourceBase* expected;
5171 Encoding expectedEncoding;
5172 if (i::StringShape(*str).IsExternalOneByte()) {
5173 const void* resource =
5174 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5175 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5176 expectedEncoding = ONE_BYTE_ENCODING;
5177 } else if (i::StringShape(*str).IsExternalTwoByte()) {
5178 const void* resource =
5179 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5180 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5181 expectedEncoding = TWO_BYTE_ENCODING;
5185 str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
5187 CHECK_EQ(expected, value);
5188 CHECK_EQ(expectedEncoding, encoding);
5191 const v8::String::ExternalOneByteStringResource*
5192 v8::String::GetExternalOneByteStringResource() const {
5193 i::Handle<i::String> str = Utils::OpenHandle(this);
5194 if (i::StringShape(*str).IsExternalOneByte()) {
5195 const void* resource =
5196 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5197 return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
5204 Local<Value> Symbol::Name() const {
5205 i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
5206 i::Handle<i::Object> name(sym->name(), sym->GetIsolate());
5207 return Utils::ToLocal(name);
5211 double Number::Value() const {
5212 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5213 return obj->Number();
5217 bool Boolean::Value() const {
5218 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5219 return obj->IsTrue();
5223 int64_t Integer::Value() const {
5224 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5226 return i::Smi::cast(*obj)->value();
5228 return static_cast<int64_t>(obj->Number());
5233 int32_t Int32::Value() const {
5234 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5236 return i::Smi::cast(*obj)->value();
5238 return static_cast<int32_t>(obj->Number());
5243 uint32_t Uint32::Value() const {
5244 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5246 return i::Smi::cast(*obj)->value();
5248 return static_cast<uint32_t>(obj->Number());
5253 int v8::Object::InternalFieldCount() {
5254 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5255 return obj->GetInternalFieldCount();
5259 static bool InternalFieldOK(i::Handle<i::JSObject> obj,
5261 const char* location) {
5262 return Utils::ApiCheck(index < obj->GetInternalFieldCount(),
5264 "Internal field out of bounds");
5268 Local<Value> v8::Object::SlowGetInternalField(int index) {
5269 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5270 const char* location = "v8::Object::GetInternalField()";
5271 if (!InternalFieldOK(obj, index, location)) return Local<Value>();
5272 i::Handle<i::Object> value(obj->GetInternalField(index), obj->GetIsolate());
5273 return Utils::ToLocal(value);
5277 void v8::Object::SetInternalField(int index, v8::Local<Value> value) {
5278 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5279 const char* location = "v8::Object::SetInternalField()";
5280 if (!InternalFieldOK(obj, index, location)) return;
5281 i::Handle<i::Object> val = Utils::OpenHandle(*value);
5282 obj->SetInternalField(index, *val);
5286 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
5287 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5288 const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
5289 if (!InternalFieldOK(obj, index, location)) return NULL;
5290 return DecodeSmiToAligned(obj->GetInternalField(index), location);
5294 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
5295 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5296 const char* location = "v8::Object::SetAlignedPointerInInternalField()";
5297 if (!InternalFieldOK(obj, index, location)) return;
5298 obj->SetInternalField(index, EncodeAlignedAsSmi(value, location));
5299 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
5303 static void* ExternalValue(i::Object* obj) {
5304 // Obscure semantics for undefined, but somehow checked in our unit tests...
5305 if (obj->IsUndefined()) return NULL;
5306 i::Object* foreign = i::JSObject::cast(obj)->GetInternalField(0);
5307 return i::Foreign::cast(foreign)->foreign_address();
5311 // --- E n v i r o n m e n t ---
5314 void v8::V8::InitializePlatform(Platform* platform) {
5315 i::V8::InitializePlatform(platform);
5319 void v8::V8::ShutdownPlatform() {
5320 i::V8::ShutdownPlatform();
5324 bool v8::V8::Initialize() {
5325 i::V8::Initialize();
5326 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5333 void v8::V8::SetEntropySource(EntropySource entropy_source) {
5334 base::RandomNumberGenerator::SetEntropySource(entropy_source);
5338 void v8::V8::SetReturnAddressLocationResolver(
5339 ReturnAddressLocationResolver return_address_resolver) {
5340 i::V8::SetReturnAddressLocationResolver(return_address_resolver);
5344 bool v8::V8::Dispose() {
5346 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5347 i::DisposeNatives();
5353 HeapStatistics::HeapStatistics(): total_heap_size_(0),
5354 total_heap_size_executable_(0),
5355 total_physical_size_(0),
5357 heap_size_limit_(0) { }
5360 HeapSpaceStatistics::HeapSpaceStatistics(): space_name_(0),
5362 space_used_size_(0),
5363 space_available_size_(0),
5364 physical_space_size_(0) { }
5367 HeapObjectStatistics::HeapObjectStatistics()
5368 : object_type_(nullptr),
5369 object_sub_type_(nullptr),
5374 bool v8::V8::InitializeICU(const char* icu_data_file) {
5375 return i::InitializeICU(icu_data_file);
5379 void v8::V8::InitializeExternalStartupData(const char* directory_path) {
5380 i::InitializeExternalStartupData(directory_path);
5384 void v8::V8::InitializeExternalStartupData(const char* natives_blob,
5385 const char* snapshot_blob) {
5386 i::InitializeExternalStartupData(natives_blob, snapshot_blob);
5390 const char* v8::V8::GetVersion() {
5391 return i::Version::GetVersion();
5395 static i::Handle<i::Context> CreateEnvironment(
5396 i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
5397 v8::Local<ObjectTemplate> global_template,
5398 v8::Local<Value> maybe_global_proxy) {
5399 i::Handle<i::Context> env;
5401 // Enter V8 via an ENTER_V8 scope.
5404 v8::Local<ObjectTemplate> proxy_template = global_template;
5405 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
5406 i::Handle<i::FunctionTemplateInfo> global_constructor;
5408 if (!global_template.IsEmpty()) {
5409 // Make sure that the global_template has a constructor.
5410 global_constructor = EnsureConstructor(isolate, *global_template);
5412 // Create a fresh template for the global proxy object.
5413 proxy_template = ObjectTemplate::New(
5414 reinterpret_cast<v8::Isolate*>(isolate));
5415 proxy_constructor = EnsureConstructor(isolate, *proxy_template);
5417 // Set the global template to be the prototype template of
5418 // global proxy template.
5419 proxy_constructor->set_prototype_template(
5420 *Utils::OpenHandle(*global_template));
5422 // Migrate security handlers from global_template to
5423 // proxy_template. Temporarily removing access check
5424 // information from the global template.
5425 if (!global_constructor->access_check_info()->IsUndefined()) {
5426 proxy_constructor->set_access_check_info(
5427 global_constructor->access_check_info());
5428 proxy_constructor->set_needs_access_check(
5429 global_constructor->needs_access_check());
5430 global_constructor->set_needs_access_check(false);
5431 global_constructor->set_access_check_info(
5432 isolate->heap()->undefined_value());
5436 i::Handle<i::Object> proxy = Utils::OpenHandle(*maybe_global_proxy, true);
5437 i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
5438 if (!proxy.is_null()) {
5439 maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(proxy);
5441 // Create the environment.
5442 env = isolate->bootstrapper()->CreateEnvironment(
5443 maybe_proxy, proxy_template, extensions);
5445 // Restore the access check info on the global template.
5446 if (!global_template.IsEmpty()) {
5447 DCHECK(!global_constructor.is_null());
5448 DCHECK(!proxy_constructor.is_null());
5449 global_constructor->set_access_check_info(
5450 proxy_constructor->access_check_info());
5451 global_constructor->set_needs_access_check(
5452 proxy_constructor->needs_access_check());
5460 Local<Context> v8::Context::New(v8::Isolate* external_isolate,
5461 v8::ExtensionConfiguration* extensions,
5462 v8::Local<ObjectTemplate> global_template,
5463 v8::Local<Value> global_object) {
5464 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
5465 LOG_API(isolate, "Context::New");
5466 i::HandleScope scope(isolate);
5467 ExtensionConfiguration no_extensions;
5468 if (extensions == NULL) extensions = &no_extensions;
5469 i::Handle<i::Context> env =
5470 CreateEnvironment(isolate, extensions, global_template, global_object);
5471 if (env.is_null()) {
5472 if (isolate->has_pending_exception()) {
5473 isolate->OptionalRescheduleException(true);
5475 return Local<Context>();
5477 return Utils::ToLocal(scope.CloseAndEscape(env));
5481 void v8::Context::SetSecurityToken(Local<Value> token) {
5482 i::Handle<i::Context> env = Utils::OpenHandle(this);
5483 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
5484 env->set_security_token(*token_handle);
5488 void v8::Context::UseDefaultSecurityToken() {
5489 i::Handle<i::Context> env = Utils::OpenHandle(this);
5490 env->set_security_token(env->global_object());
5494 Local<Value> v8::Context::GetSecurityToken() {
5495 i::Handle<i::Context> env = Utils::OpenHandle(this);
5496 i::Isolate* isolate = env->GetIsolate();
5497 i::Object* security_token = env->security_token();
5498 i::Handle<i::Object> token_handle(security_token, isolate);
5499 return Utils::ToLocal(token_handle);
5503 v8::Isolate* Context::GetIsolate() {
5504 i::Handle<i::Context> env = Utils::OpenHandle(this);
5505 return reinterpret_cast<Isolate*>(env->GetIsolate());
5509 v8::Local<v8::Object> Context::Global() {
5510 i::Handle<i::Context> context = Utils::OpenHandle(this);
5511 i::Isolate* isolate = context->GetIsolate();
5512 i::Handle<i::Object> global(context->global_proxy(), isolate);
5513 // TODO(dcarney): This should always return the global proxy
5514 // but can't presently as calls to GetProtoype will return the wrong result.
5515 if (i::Handle<i::JSGlobalProxy>::cast(
5516 global)->IsDetachedFrom(context->global_object())) {
5517 global = i::Handle<i::Object>(context->global_object(), isolate);
5519 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
5523 void Context::DetachGlobal() {
5524 i::Handle<i::Context> context = Utils::OpenHandle(this);
5525 i::Isolate* isolate = context->GetIsolate();
5527 isolate->bootstrapper()->DetachGlobal(context);
5531 Local<v8::Object> Context::GetExtrasBindingObject() {
5532 i::Handle<i::Context> context = Utils::OpenHandle(this);
5533 i::Isolate* isolate = context->GetIsolate();
5534 i::Handle<i::JSObject> binding(context->extras_binding_object(), isolate);
5535 return Utils::ToLocal(binding);
5539 void Context::AllowCodeGenerationFromStrings(bool allow) {
5540 i::Handle<i::Context> context = Utils::OpenHandle(this);
5541 i::Isolate* isolate = context->GetIsolate();
5543 context->set_allow_code_gen_from_strings(
5544 allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
5548 bool Context::IsCodeGenerationFromStringsAllowed() {
5549 i::Handle<i::Context> context = Utils::OpenHandle(this);
5550 return !context->allow_code_gen_from_strings()->IsFalse();
5554 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
5555 i::Handle<i::Context> context = Utils::OpenHandle(this);
5556 i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
5557 context->set_error_message_for_code_gen_from_strings(*error_handle);
5561 size_t Context::EstimatedSize() {
5562 return static_cast<size_t>(
5563 i::ContextMeasure(*Utils::OpenHandle(this)).Size());
5567 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
5568 PREPARE_FOR_EXECUTION(context, "v8::ObjectTemplate::NewInstance()", Object);
5569 auto self = Utils::OpenHandle(this);
5570 Local<Object> result;
5571 has_pending_exception =
5572 !ToLocal<Object>(i::ApiNatives::InstantiateObject(self), &result);
5573 RETURN_ON_FAILED_EXECUTION(Object);
5574 RETURN_ESCAPED(result);
5578 Local<v8::Object> ObjectTemplate::NewInstance() {
5579 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5580 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object);
5584 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
5585 PREPARE_FOR_EXECUTION(context, "v8::FunctionTemplate::GetFunction()",
5587 auto self = Utils::OpenHandle(this);
5588 Local<Function> result;
5589 has_pending_exception =
5590 !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
5591 RETURN_ON_FAILED_EXECUTION(Function);
5592 RETURN_ESCAPED(result);
5596 Local<v8::Function> FunctionTemplate::GetFunction() {
5597 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5598 RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function);
5602 bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) {
5603 auto self = Utils::OpenHandle(this);
5604 auto obj = Utils::OpenHandle(*value);
5605 return self->IsTemplateFor(*obj);
5609 Local<External> v8::External::New(Isolate* isolate, void* value) {
5610 STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
5611 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5612 LOG_API(i_isolate, "External::New");
5613 ENTER_V8(i_isolate);
5614 i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
5615 return Utils::ExternalToLocal(external);
5619 void* External::Value() const {
5620 return ExternalValue(*Utils::OpenHandle(this));
5624 // anonymous namespace for string creation helper functions
5627 inline int StringLength(const char* string) {
5628 return i::StrLength(string);
5632 inline int StringLength(const uint8_t* string) {
5633 return i::StrLength(reinterpret_cast<const char*>(string));
5637 inline int StringLength(const uint16_t* string) {
5639 while (string[length] != '\0')
5646 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5647 v8::NewStringType type,
5648 i::Vector<const char> string) {
5649 if (type == v8::NewStringType::kInternalized) {
5650 return factory->InternalizeUtf8String(string);
5652 return factory->NewStringFromUtf8(string);
5657 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5658 v8::NewStringType type,
5659 i::Vector<const uint8_t> string) {
5660 if (type == v8::NewStringType::kInternalized) {
5661 return factory->InternalizeOneByteString(string);
5663 return factory->NewStringFromOneByte(string);
5668 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5669 v8::NewStringType type,
5670 i::Vector<const uint16_t> string) {
5671 if (type == v8::NewStringType::kInternalized) {
5672 return factory->InternalizeTwoByteString(string);
5674 return factory->NewStringFromTwoByte(string);
5678 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
5681 template <typename Char>
5682 inline MaybeLocal<String> NewString(Isolate* v8_isolate, const char* location,
5683 const char* env, const Char* data,
5684 v8::NewStringType type, int length) {
5685 i::Isolate* isolate = reinterpret_cast<internal::Isolate*>(v8_isolate);
5686 if (length == 0) return String::Empty(v8_isolate);
5687 // TODO(dcarney): throw a context free exception.
5688 if (length > i::String::kMaxLength) return MaybeLocal<String>();
5690 LOG_API(isolate, env);
5691 if (length < 0) length = StringLength(data);
5692 i::Handle<i::String> result =
5693 NewString(isolate->factory(), type, i::Vector<const Char>(data, length))
5695 return Utils::ToLocal(result);
5698 } // anonymous namespace
5701 Local<String> String::NewFromUtf8(Isolate* isolate,
5705 RETURN_TO_LOCAL_UNCHECKED(
5706 NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5707 data, static_cast<v8::NewStringType>(type), length),
5712 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
5713 v8::NewStringType type, int length) {
5714 return NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5715 data, type, length);
5719 Local<String> String::NewFromOneByte(Isolate* isolate,
5720 const uint8_t* data,
5723 RETURN_TO_LOCAL_UNCHECKED(
5724 NewString(isolate, "v8::String::NewFromOneByte()",
5725 "String::NewFromOneByte", data,
5726 static_cast<v8::NewStringType>(type), length),
5731 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
5732 v8::NewStringType type, int length) {
5733 return NewString(isolate, "v8::String::NewFromOneByte()",
5734 "String::NewFromOneByte", data, type, length);
5738 Local<String> String::NewFromTwoByte(Isolate* isolate,
5739 const uint16_t* data,
5742 RETURN_TO_LOCAL_UNCHECKED(
5743 NewString(isolate, "v8::String::NewFromTwoByte()",
5744 "String::NewFromTwoByte", data,
5745 static_cast<v8::NewStringType>(type), length),
5750 MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate,
5751 const uint16_t* data,
5752 v8::NewStringType type, int length) {
5753 return NewString(isolate, "v8::String::NewFromTwoByte()",
5754 "String::NewFromTwoByte", data, type, length);
5758 Local<String> v8::String::Concat(Local<String> left, Local<String> right) {
5759 i::Handle<i::String> left_string = Utils::OpenHandle(*left);
5760 i::Isolate* isolate = left_string->GetIsolate();
5762 LOG_API(isolate, "v8::String::Concat");
5763 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
5764 // If we are steering towards a range error, do not wait for the error to be
5765 // thrown, and return the null handle instead.
5766 if (left_string->length() + right_string->length() > i::String::kMaxLength) {
5767 return Local<String>();
5769 i::Handle<i::String> result = isolate->factory()->NewConsString(
5770 left_string, right_string).ToHandleChecked();
5771 return Utils::ToLocal(result);
5775 MaybeLocal<String> v8::String::NewExternalTwoByte(
5776 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5777 CHECK(resource && resource->data());
5778 // TODO(dcarney): throw a context free exception.
5779 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5780 return MaybeLocal<String>();
5782 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5783 ENTER_V8(i_isolate);
5784 LOG_API(i_isolate, "String::NewExternalTwoByte");
5785 i::Handle<i::String> string = i_isolate->factory()
5786 ->NewExternalStringFromTwoByte(resource)
5788 i_isolate->heap()->external_string_table()->AddString(*string);
5789 return Utils::ToLocal(string);
5793 Local<String> v8::String::NewExternal(
5794 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5795 RETURN_TO_LOCAL_UNCHECKED(NewExternalTwoByte(isolate, resource), String);
5799 MaybeLocal<String> v8::String::NewExternalOneByte(
5800 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5801 CHECK(resource && resource->data());
5802 // TODO(dcarney): throw a context free exception.
5803 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5804 return MaybeLocal<String>();
5806 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5807 ENTER_V8(i_isolate);
5808 LOG_API(i_isolate, "String::NewExternalOneByte");
5809 i::Handle<i::String> string = i_isolate->factory()
5810 ->NewExternalStringFromOneByte(resource)
5812 i_isolate->heap()->external_string_table()->AddString(*string);
5813 return Utils::ToLocal(string);
5817 Local<String> v8::String::NewExternal(
5818 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5819 RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
5823 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
5824 i::Handle<i::String> obj = Utils::OpenHandle(this);
5825 i::Isolate* isolate = obj->GetIsolate();
5826 if (i::StringShape(*obj).IsExternal()) {
5827 return false; // Already an external string.
5830 if (isolate->heap()->IsInGCPostProcessing()) {
5833 CHECK(resource && resource->data());
5835 bool result = obj->MakeExternal(resource);
5836 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5837 DCHECK(!CanMakeExternal() || result);
5839 DCHECK(obj->IsExternalString());
5840 isolate->heap()->external_string_table()->AddString(*obj);
5846 bool v8::String::MakeExternal(
5847 v8::String::ExternalOneByteStringResource* resource) {
5848 i::Handle<i::String> obj = Utils::OpenHandle(this);
5849 i::Isolate* isolate = obj->GetIsolate();
5850 if (i::StringShape(*obj).IsExternal()) {
5851 return false; // Already an external string.
5854 if (isolate->heap()->IsInGCPostProcessing()) {
5857 CHECK(resource && resource->data());
5859 bool result = obj->MakeExternal(resource);
5860 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5861 DCHECK(!CanMakeExternal() || result);
5863 DCHECK(obj->IsExternalString());
5864 isolate->heap()->external_string_table()->AddString(*obj);
5870 bool v8::String::CanMakeExternal() {
5871 i::Handle<i::String> obj = Utils::OpenHandle(this);
5872 i::Isolate* isolate = obj->GetIsolate();
5874 // Old space strings should be externalized.
5875 if (!isolate->heap()->new_space()->Contains(*obj)) return true;
5876 int size = obj->Size(); // Byte size of the original string.
5877 if (size <= i::ExternalString::kShortSize) return false;
5878 i::StringShape shape(*obj);
5879 return !shape.IsExternal();
5883 Isolate* v8::Object::GetIsolate() {
5884 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
5885 return reinterpret_cast<Isolate*>(i_isolate);
5889 Local<v8::Object> v8::Object::New(Isolate* isolate) {
5890 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5891 LOG_API(i_isolate, "Object::New");
5892 ENTER_V8(i_isolate);
5893 i::Handle<i::JSObject> obj =
5894 i_isolate->factory()->NewJSObject(i_isolate->object_function());
5895 return Utils::ToLocal(obj);
5899 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
5900 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5901 LOG_API(i_isolate, "NumberObject::New");
5902 ENTER_V8(i_isolate);
5903 i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
5904 i::Handle<i::Object> obj =
5905 i::Object::ToObject(i_isolate, number).ToHandleChecked();
5906 return Utils::ToLocal(obj);
5910 double v8::NumberObject::ValueOf() const {
5911 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5912 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5913 i::Isolate* isolate = jsvalue->GetIsolate();
5914 LOG_API(isolate, "NumberObject::NumberValue");
5915 return jsvalue->value()->Number();
5919 Local<v8::Value> v8::BooleanObject::New(bool value) {
5920 i::Isolate* isolate = i::Isolate::Current();
5921 LOG_API(isolate, "BooleanObject::New");
5923 i::Handle<i::Object> boolean(value
5924 ? isolate->heap()->true_value()
5925 : isolate->heap()->false_value(),
5927 i::Handle<i::Object> obj =
5928 i::Object::ToObject(isolate, boolean).ToHandleChecked();
5929 return Utils::ToLocal(obj);
5933 bool v8::BooleanObject::ValueOf() const {
5934 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5935 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5936 i::Isolate* isolate = jsvalue->GetIsolate();
5937 LOG_API(isolate, "BooleanObject::BooleanValue");
5938 return jsvalue->value()->IsTrue();
5942 Local<v8::Value> v8::StringObject::New(Local<String> value) {
5943 i::Handle<i::String> string = Utils::OpenHandle(*value);
5944 i::Isolate* isolate = string->GetIsolate();
5945 LOG_API(isolate, "StringObject::New");
5947 i::Handle<i::Object> obj =
5948 i::Object::ToObject(isolate, string).ToHandleChecked();
5949 return Utils::ToLocal(obj);
5953 Local<v8::String> v8::StringObject::ValueOf() const {
5954 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5955 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5956 i::Isolate* isolate = jsvalue->GetIsolate();
5957 LOG_API(isolate, "StringObject::StringValue");
5958 return Utils::ToLocal(
5959 i::Handle<i::String>(i::String::cast(jsvalue->value())));
5963 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
5964 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5965 LOG_API(i_isolate, "SymbolObject::New");
5966 ENTER_V8(i_isolate);
5967 i::Handle<i::Object> obj = i::Object::ToObject(
5968 i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
5969 return Utils::ToLocal(obj);
5973 Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
5974 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5975 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5976 i::Isolate* isolate = jsvalue->GetIsolate();
5977 LOG_API(isolate, "SymbolObject::SymbolValue");
5978 return Utils::ToLocal(
5979 i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value())));
5983 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
5984 if (std::isnan(time)) {
5985 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
5986 time = std::numeric_limits<double>::quiet_NaN();
5988 PREPARE_FOR_EXECUTION(context, "Date::New", Value);
5989 Local<Value> result;
5990 has_pending_exception =
5991 !ToLocal<Value>(i::Execution::NewDate(isolate, time), &result);
5992 RETURN_ON_FAILED_EXECUTION(Value);
5993 RETURN_ESCAPED(result);
5997 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
5998 auto context = isolate->GetCurrentContext();
5999 RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value);
6003 double v8::Date::ValueOf() const {
6004 i::Handle<i::Object> obj = Utils::OpenHandle(this);
6005 i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
6006 i::Isolate* isolate = jsdate->GetIsolate();
6007 LOG_API(isolate, "Date::NumberValue");
6008 return jsdate->value()->Number();
6012 void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) {
6013 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6014 LOG_API(i_isolate, "Date::DateTimeConfigurationChangeNotification");
6015 ENTER_V8(i_isolate);
6016 i_isolate->date_cache()->ResetDateCache();
6017 if (!i_isolate->eternal_handles()->Exists(
6018 i::EternalHandles::DATE_CACHE_VERSION)) {
6021 i::Handle<i::FixedArray> date_cache_version =
6022 i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton(
6023 i::EternalHandles::DATE_CACHE_VERSION));
6024 DCHECK_EQ(1, date_cache_version->length());
6025 CHECK(date_cache_version->get(0)->IsSmi());
6026 date_cache_version->set(
6028 i::Smi::FromInt(i::Smi::cast(date_cache_version->get(0))->value() + 1));
6032 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
6033 i::Isolate* isolate = i::Isolate::Current();
6034 uint8_t flags_buf[3];
6036 if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
6037 if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
6038 if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
6039 DCHECK(num_flags <= static_cast<int>(arraysize(flags_buf)));
6040 return isolate->factory()->InternalizeOneByteString(
6041 i::Vector<const uint8_t>(flags_buf, num_flags));
6045 MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context,
6046 Local<String> pattern, Flags flags) {
6047 PREPARE_FOR_EXECUTION(context, "RegExp::New", RegExp);
6048 Local<v8::RegExp> result;
6049 has_pending_exception =
6050 !ToLocal<RegExp>(i::Execution::NewJSRegExp(Utils::OpenHandle(*pattern),
6051 RegExpFlagsToString(flags)),
6053 RETURN_ON_FAILED_EXECUTION(RegExp);
6054 RETURN_ESCAPED(result);
6058 Local<v8::RegExp> v8::RegExp::New(Local<String> pattern, Flags flags) {
6060 reinterpret_cast<Isolate*>(Utils::OpenHandle(*pattern)->GetIsolate());
6061 auto context = isolate->GetCurrentContext();
6062 RETURN_TO_LOCAL_UNCHECKED(New(context, pattern, flags), RegExp);
6066 Local<v8::String> v8::RegExp::GetSource() const {
6067 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6068 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
6072 // Assert that the static flags cast in GetFlags is valid.
6073 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag) \
6074 STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) == \
6075 static_cast<int>(i::JSRegExp::internal_flag))
6076 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
6077 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
6078 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
6079 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
6080 #undef REGEXP_FLAG_ASSERT_EQ
6082 v8::RegExp::Flags v8::RegExp::GetFlags() const {
6083 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6084 return static_cast<RegExp::Flags>(obj->GetFlags().value());
6088 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
6089 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6090 LOG_API(i_isolate, "Array::New");
6091 ENTER_V8(i_isolate);
6092 int real_length = length > 0 ? length : 0;
6093 i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
6094 i::Handle<i::Object> length_obj =
6095 i_isolate->factory()->NewNumberFromInt(real_length);
6096 obj->set_length(*length_obj);
6097 return Utils::ToLocal(obj);
6101 uint32_t v8::Array::Length() const {
6102 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
6103 i::Object* length = obj->length();
6104 if (length->IsSmi()) {
6105 return i::Smi::cast(length)->value();
6107 return static_cast<uint32_t>(length->Number());
6112 MaybeLocal<Object> Array::CloneElementAt(Local<Context> context,
6114 PREPARE_FOR_EXECUTION(context, "v8::Array::CloneElementAt()", Object);
6115 auto self = Utils::OpenHandle(this);
6116 if (!self->HasFastObjectElements()) return Local<Object>();
6117 i::FixedArray* elms = i::FixedArray::cast(self->elements());
6118 i::Object* paragon = elms->get(index);
6119 if (!paragon->IsJSObject()) return Local<Object>();
6120 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
6121 Local<Object> result;
6122 has_pending_exception =
6123 !ToLocal<Object>(isolate->factory()->CopyJSObject(paragon_handle),
6125 RETURN_ON_FAILED_EXECUTION(Object);
6126 RETURN_ESCAPED(result);
6130 Local<Object> Array::CloneElementAt(uint32_t index) {
6131 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6132 RETURN_TO_LOCAL_UNCHECKED(CloneElementAt(context, index), Object);
6136 Local<v8::Map> v8::Map::New(Isolate* isolate) {
6137 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6138 LOG_API(i_isolate, "Map::New");
6139 ENTER_V8(i_isolate);
6140 i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
6141 return Utils::ToLocal(obj);
6145 size_t v8::Map::Size() const {
6146 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6147 return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
6152 auto self = Utils::OpenHandle(this);
6153 i::Isolate* isolate = self->GetIsolate();
6154 LOG_API(isolate, "Map::Clear");
6156 i::Runtime::JSMapClear(isolate, self);
6160 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
6161 PREPARE_FOR_EXECUTION(context, "Map::Get", Value);
6162 auto self = Utils::OpenHandle(this);
6163 Local<Value> result;
6164 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6165 has_pending_exception =
6166 !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
6167 arraysize(argv), argv, false),
6169 RETURN_ON_FAILED_EXECUTION(Value);
6170 RETURN_ESCAPED(result);
6174 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
6175 Local<Value> value) {
6176 PREPARE_FOR_EXECUTION(context, "Map::Set", Map);
6177 auto self = Utils::OpenHandle(this);
6178 i::Handle<i::Object> result;
6179 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
6180 Utils::OpenHandle(*value)};
6181 has_pending_exception =
6182 !i::Execution::Call(isolate, isolate->map_set(), self, arraysize(argv),
6183 argv, false).ToHandle(&result);
6184 RETURN_ON_FAILED_EXECUTION(Map);
6185 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6189 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
6190 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Has", bool);
6191 auto self = Utils::OpenHandle(this);
6192 i::Handle<i::Object> result;
6193 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6194 has_pending_exception =
6195 !i::Execution::Call(isolate, isolate->map_has(), self, arraysize(argv),
6196 argv, false).ToHandle(&result);
6197 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6198 return Just(result->IsTrue());
6202 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
6203 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Delete", bool);
6204 auto self = Utils::OpenHandle(this);
6205 i::Handle<i::Object> result;
6206 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6207 has_pending_exception =
6208 !i::Execution::Call(isolate, isolate->map_delete(), self, arraysize(argv),
6209 argv, false).ToHandle(&result);
6210 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6211 return Just(result->IsTrue());
6215 Local<Array> Map::AsArray() const {
6216 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6217 i::Isolate* isolate = obj->GetIsolate();
6218 i::Factory* factory = isolate->factory();
6219 LOG_API(isolate, "Map::AsArray");
6221 i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(obj->table()));
6222 int size = table->NumberOfElements();
6223 int length = size * 2;
6224 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6225 for (int i = 0; i < size; ++i) {
6226 if (table->KeyAt(i)->IsTheHole()) continue;
6227 result->set(i * 2, table->KeyAt(i));
6228 result->set(i * 2 + 1, table->ValueAt(i));
6230 i::Handle<i::JSArray> result_array =
6231 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6232 return Utils::ToLocal(result_array);
6236 MaybeLocal<Map> Map::FromArray(Local<Context> context, Local<Array> array) {
6237 PREPARE_FOR_EXECUTION(context, "Map::FromArray", Map);
6238 if (array->Length() % 2 != 0) {
6239 return MaybeLocal<Map>();
6241 i::Handle<i::Object> result;
6242 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6243 has_pending_exception =
6244 !i::Execution::Call(isolate, isolate->map_from_array(),
6245 isolate->factory()->undefined_value(),
6246 arraysize(argv), argv, false).ToHandle(&result);
6247 RETURN_ON_FAILED_EXECUTION(Map);
6248 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6252 Local<v8::Set> v8::Set::New(Isolate* isolate) {
6253 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6254 LOG_API(i_isolate, "Set::New");
6255 ENTER_V8(i_isolate);
6256 i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
6257 return Utils::ToLocal(obj);
6261 size_t v8::Set::Size() const {
6262 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6263 return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
6268 auto self = Utils::OpenHandle(this);
6269 i::Isolate* isolate = self->GetIsolate();
6270 LOG_API(isolate, "Set::Clear");
6272 i::Runtime::JSSetClear(isolate, self);
6276 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
6277 PREPARE_FOR_EXECUTION(context, "Set::Add", Set);
6278 auto self = Utils::OpenHandle(this);
6279 i::Handle<i::Object> result;
6280 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6281 has_pending_exception =
6282 !i::Execution::Call(isolate, isolate->set_add(), self, arraysize(argv),
6283 argv, false).ToHandle(&result);
6284 RETURN_ON_FAILED_EXECUTION(Set);
6285 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6289 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
6290 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Has", bool);
6291 auto self = Utils::OpenHandle(this);
6292 i::Handle<i::Object> result;
6293 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6294 has_pending_exception =
6295 !i::Execution::Call(isolate, isolate->set_has(), self, arraysize(argv),
6296 argv, false).ToHandle(&result);
6297 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6298 return Just(result->IsTrue());
6302 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
6303 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Delete", bool);
6304 auto self = Utils::OpenHandle(this);
6305 i::Handle<i::Object> result;
6306 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6307 has_pending_exception =
6308 !i::Execution::Call(isolate, isolate->set_delete(), self, arraysize(argv),
6309 argv, false).ToHandle(&result);
6310 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6311 return Just(result->IsTrue());
6315 Local<Array> Set::AsArray() const {
6316 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6317 i::Isolate* isolate = obj->GetIsolate();
6318 i::Factory* factory = isolate->factory();
6319 LOG_API(isolate, "Set::AsArray");
6321 i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(obj->table()));
6322 int length = table->NumberOfElements();
6323 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6324 for (int i = 0; i < length; ++i) {
6325 i::Object* key = table->KeyAt(i);
6326 if (!key->IsTheHole()) {
6327 result->set(i, key);
6330 i::Handle<i::JSArray> result_array =
6331 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6332 return Utils::ToLocal(result_array);
6336 MaybeLocal<Set> Set::FromArray(Local<Context> context, Local<Array> array) {
6337 PREPARE_FOR_EXECUTION(context, "Set::FromArray", Set);
6338 i::Handle<i::Object> result;
6339 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6340 has_pending_exception =
6341 !i::Execution::Call(isolate, isolate->set_from_array(),
6342 isolate->factory()->undefined_value(),
6343 arraysize(argv), argv, false).ToHandle(&result);
6344 RETURN_ON_FAILED_EXECUTION(Set);
6345 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6349 bool Value::IsPromise() const {
6350 auto self = Utils::OpenHandle(this);
6351 return i::Object::IsPromise(self);
6355 MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) {
6356 PREPARE_FOR_EXECUTION(context, "Promise::Resolver::New", Resolver);
6357 i::Handle<i::Object> result;
6358 has_pending_exception = !i::Execution::Call(
6360 isolate->promise_create(),
6361 isolate->factory()->undefined_value(),
6363 false).ToHandle(&result);
6364 RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
6365 RETURN_ESCAPED(Local<Promise::Resolver>::Cast(Utils::ToLocal(result)));
6369 Local<Promise::Resolver> Promise::Resolver::New(Isolate* isolate) {
6370 RETURN_TO_LOCAL_UNCHECKED(New(isolate->GetCurrentContext()),
6375 Local<Promise> Promise::Resolver::GetPromise() {
6376 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6377 return Local<Promise>::Cast(Utils::ToLocal(promise));
6381 Maybe<bool> Promise::Resolver::Resolve(Local<Context> context,
6382 Local<Value> value) {
6383 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6384 auto self = Utils::OpenHandle(this);
6385 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6386 has_pending_exception = i::Execution::Call(
6388 isolate->promise_resolve(),
6389 isolate->factory()->undefined_value(),
6390 arraysize(argv), argv,
6392 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6397 void Promise::Resolver::Resolve(Local<Value> value) {
6398 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6399 USE(Resolve(context, value));
6403 Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
6404 Local<Value> value) {
6405 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6406 auto self = Utils::OpenHandle(this);
6407 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6408 has_pending_exception = i::Execution::Call(
6410 isolate->promise_reject(),
6411 isolate->factory()->undefined_value(),
6412 arraysize(argv), argv,
6414 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6419 void Promise::Resolver::Reject(Local<Value> value) {
6420 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6421 USE(Reject(context, value));
6425 MaybeLocal<Promise> Promise::Chain(Local<Context> context,
6426 Local<Function> handler) {
6427 PREPARE_FOR_EXECUTION(context, "Promise::Chain", Promise);
6428 auto self = Utils::OpenHandle(this);
6429 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*handler)};
6430 i::Handle<i::Object> result;
6431 has_pending_exception =
6432 !i::Execution::Call(isolate, isolate->promise_chain(), self,
6433 arraysize(argv), argv, false).ToHandle(&result);
6434 RETURN_ON_FAILED_EXECUTION(Promise);
6435 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6439 Local<Promise> Promise::Chain(Local<Function> handler) {
6440 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6441 RETURN_TO_LOCAL_UNCHECKED(Chain(context, handler), Promise);
6445 MaybeLocal<Promise> Promise::Catch(Local<Context> context,
6446 Local<Function> handler) {
6447 PREPARE_FOR_EXECUTION(context, "Promise::Catch", Promise);
6448 auto self = Utils::OpenHandle(this);
6449 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6450 i::Handle<i::Object> result;
6451 has_pending_exception =
6452 !i::Execution::Call(isolate, isolate->promise_catch(), self,
6453 arraysize(argv), argv, false).ToHandle(&result);
6454 RETURN_ON_FAILED_EXECUTION(Promise);
6455 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6459 Local<Promise> Promise::Catch(Local<Function> handler) {
6460 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6461 RETURN_TO_LOCAL_UNCHECKED(Catch(context, handler), Promise);
6465 MaybeLocal<Promise> Promise::Then(Local<Context> context,
6466 Local<Function> handler) {
6467 PREPARE_FOR_EXECUTION(context, "Promise::Then", Promise);
6468 auto self = Utils::OpenHandle(this);
6469 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6470 i::Handle<i::Object> result;
6471 has_pending_exception =
6472 !i::Execution::Call(isolate, isolate->promise_then(), self,
6473 arraysize(argv), argv, false).ToHandle(&result);
6474 RETURN_ON_FAILED_EXECUTION(Promise);
6475 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6479 Local<Promise> Promise::Then(Local<Function> handler) {
6480 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6481 RETURN_TO_LOCAL_UNCHECKED(Then(context, handler), Promise);
6485 bool Promise::HasHandler() {
6486 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6487 i::Isolate* isolate = promise->GetIsolate();
6488 LOG_API(isolate, "Promise::HasRejectHandler");
6490 i::Handle<i::Symbol> key = isolate->factory()->promise_has_handler_symbol();
6491 return i::JSReceiver::GetDataProperty(promise, key)->IsTrue();
6495 bool v8::ArrayBuffer::IsExternal() const {
6496 return Utils::OpenHandle(this)->is_external();
6500 bool v8::ArrayBuffer::IsNeuterable() const {
6501 return Utils::OpenHandle(this)->is_neuterable();
6505 v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
6506 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6507 i::Isolate* isolate = self->GetIsolate();
6508 Utils::ApiCheck(!self->is_external(), "v8::ArrayBuffer::Externalize",
6509 "ArrayBuffer already externalized");
6510 self->set_is_external(true);
6511 isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6512 self->backing_store());
6514 return GetContents();
6518 v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() {
6519 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6520 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6522 contents.data_ = self->backing_store();
6523 contents.byte_length_ = byte_length;
6528 void v8::ArrayBuffer::Neuter() {
6529 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6530 i::Isolate* isolate = obj->GetIsolate();
6531 Utils::ApiCheck(obj->is_external(),
6532 "v8::ArrayBuffer::Neuter",
6533 "Only externalized ArrayBuffers can be neutered");
6534 Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter",
6535 "Only neuterable ArrayBuffers can be neutered");
6536 LOG_API(obj->GetIsolate(), "v8::ArrayBuffer::Neuter()");
6538 i::Runtime::NeuterArrayBuffer(obj);
6542 size_t v8::ArrayBuffer::ByteLength() const {
6543 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6544 return static_cast<size_t>(obj->byte_length()->Number());
6548 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
6549 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6550 LOG_API(i_isolate, "v8::ArrayBuffer::New(size_t)");
6551 ENTER_V8(i_isolate);
6552 i::Handle<i::JSArrayBuffer> obj =
6553 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6554 i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length);
6555 return Utils::ToLocal(obj);
6559 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
6561 ArrayBufferCreationMode mode) {
6562 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6563 LOG_API(i_isolate, "v8::ArrayBuffer::New(void*, size_t)");
6564 ENTER_V8(i_isolate);
6565 i::Handle<i::JSArrayBuffer> obj =
6566 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6567 i::Runtime::SetupArrayBuffer(i_isolate, obj,
6568 mode == ArrayBufferCreationMode::kExternalized,
6570 return Utils::ToLocal(obj);
6574 Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
6575 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6576 i::Handle<i::JSArrayBuffer> buffer;
6577 if (obj->IsJSDataView()) {
6578 i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj));
6579 DCHECK(data_view->buffer()->IsJSArrayBuffer());
6580 buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()));
6582 DCHECK(obj->IsJSTypedArray());
6583 buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
6585 return Utils::ToLocal(buffer);
6589 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
6590 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6591 i::Isolate* isolate = self->GetIsolate();
6592 size_t byte_offset = i::NumberToSize(isolate, self->byte_offset());
6593 size_t bytes_to_copy =
6594 i::Min(byte_length, i::NumberToSize(isolate, self->byte_length()));
6595 if (bytes_to_copy) {
6596 i::DisallowHeapAllocation no_gc;
6597 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6598 const char* source = reinterpret_cast<char*>(buffer->backing_store());
6599 if (source == nullptr) {
6600 DCHECK(self->IsJSTypedArray());
6601 i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self));
6602 i::Handle<i::FixedTypedArrayBase> fixed_array(
6603 i::FixedTypedArrayBase::cast(typed_array->elements()));
6604 source = reinterpret_cast<char*>(fixed_array->DataPtr());
6606 memcpy(dest, source + byte_offset, bytes_to_copy);
6608 return bytes_to_copy;
6612 bool v8::ArrayBufferView::HasBuffer() const {
6613 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6614 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6615 return buffer->backing_store() != nullptr;
6619 size_t v8::ArrayBufferView::ByteOffset() {
6620 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6621 return static_cast<size_t>(obj->byte_offset()->Number());
6625 size_t v8::ArrayBufferView::ByteLength() {
6626 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6627 return static_cast<size_t>(obj->byte_length()->Number());
6631 size_t v8::TypedArray::Length() {
6632 i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
6633 return static_cast<size_t>(obj->length_value());
6637 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype, size) \
6638 Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer, \
6639 size_t byte_offset, size_t length) { \
6640 i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate(); \
6642 "v8::" #Type "Array::New(Local<ArrayBuffer>, size_t, size_t)"); \
6643 ENTER_V8(isolate); \
6644 if (!Utils::ApiCheck(length <= static_cast<size_t>(i::Smi::kMaxValue), \
6646 "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
6647 "length exceeds max allowed value")) { \
6648 return Local<Type##Array>(); \
6650 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \
6651 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6652 i::kExternal##Type##Array, buffer, byte_offset, length); \
6653 return Utils::ToLocal##Type##Array(obj); \
6655 Local<Type##Array> Type##Array::New( \
6656 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, \
6658 CHECK(i::FLAG_harmony_sharedarraybuffer); \
6659 i::Isolate* isolate = \
6660 Utils::OpenHandle(*shared_array_buffer)->GetIsolate(); \
6661 LOG_API(isolate, "v8::" #Type \
6662 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)"); \
6663 ENTER_V8(isolate); \
6664 if (!Utils::ApiCheck( \
6665 length <= static_cast<size_t>(i::Smi::kMaxValue), \
6667 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)", \
6668 "length exceeds max allowed value")) { \
6669 return Local<Type##Array>(); \
6671 i::Handle<i::JSArrayBuffer> buffer = \
6672 Utils::OpenHandle(*shared_array_buffer); \
6673 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6674 i::kExternal##Type##Array, buffer, byte_offset, length); \
6675 return Utils::ToLocal##Type##Array(obj); \
6679 TYPED_ARRAYS(TYPED_ARRAY_NEW)
6680 #undef TYPED_ARRAY_NEW
6682 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
6683 size_t byte_offset, size_t byte_length) {
6684 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
6685 i::Isolate* isolate = buffer->GetIsolate();
6686 LOG_API(isolate, "v8::DataView::New(Local<ArrayBuffer>, size_t, size_t)");
6688 i::Handle<i::JSDataView> obj =
6689 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6690 return Utils::ToLocal(obj);
6694 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
6695 size_t byte_offset, size_t byte_length) {
6696 CHECK(i::FLAG_harmony_sharedarraybuffer);
6697 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
6698 i::Isolate* isolate = buffer->GetIsolate();
6700 "v8::DataView::New(Local<SharedArrayBuffer>, size_t, size_t)");
6702 i::Handle<i::JSDataView> obj =
6703 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6704 return Utils::ToLocal(obj);
6708 bool v8::SharedArrayBuffer::IsExternal() const {
6709 return Utils::OpenHandle(this)->is_external();
6713 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
6714 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6715 i::Isolate* isolate = self->GetIsolate();
6716 Utils::ApiCheck(!self->is_external(), "v8::SharedArrayBuffer::Externalize",
6717 "SharedArrayBuffer already externalized");
6718 self->set_is_external(true);
6719 isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6720 self->backing_store());
6721 return GetContents();
6725 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
6726 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6727 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6729 contents.data_ = self->backing_store();
6730 contents.byte_length_ = byte_length;
6735 size_t v8::SharedArrayBuffer::ByteLength() const {
6736 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6737 return static_cast<size_t>(obj->byte_length()->Number());
6741 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate,
6742 size_t byte_length) {
6743 CHECK(i::FLAG_harmony_sharedarraybuffer);
6744 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6745 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(size_t)");
6746 ENTER_V8(i_isolate);
6747 i::Handle<i::JSArrayBuffer> obj =
6748 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6749 i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length, true,
6750 i::SharedFlag::kShared);
6751 return Utils::ToLocalShared(obj);
6755 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
6756 Isolate* isolate, void* data, size_t byte_length,
6757 ArrayBufferCreationMode mode) {
6758 CHECK(i::FLAG_harmony_sharedarraybuffer);
6759 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6760 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(void*, size_t)");
6761 ENTER_V8(i_isolate);
6762 i::Handle<i::JSArrayBuffer> obj =
6763 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6764 i::Runtime::SetupArrayBuffer(i_isolate, obj,
6765 mode == ArrayBufferCreationMode::kExternalized,
6766 data, byte_length, i::SharedFlag::kShared);
6767 return Utils::ToLocalShared(obj);
6771 Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
6772 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6773 LOG_API(i_isolate, "Symbol::New()");
6774 ENTER_V8(i_isolate);
6775 i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
6776 if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
6777 return Utils::ToLocal(result);
6781 static i::Handle<i::Symbol> SymbolFor(i::Isolate* isolate,
6782 i::Handle<i::String> name,
6783 i::Handle<i::String> part) {
6784 i::Handle<i::JSObject> registry = isolate->GetSymbolRegistry();
6785 i::Handle<i::JSObject> symbols =
6786 i::Handle<i::JSObject>::cast(
6787 i::Object::GetPropertyOrElement(registry, part).ToHandleChecked());
6788 i::Handle<i::Object> symbol =
6789 i::Object::GetPropertyOrElement(symbols, name).ToHandleChecked();
6790 if (!symbol->IsSymbol()) {
6791 DCHECK(symbol->IsUndefined());
6792 symbol = isolate->factory()->NewSymbol();
6793 i::Handle<i::Symbol>::cast(symbol)->set_name(*name);
6794 i::JSObject::SetProperty(symbols, name, symbol, i::STRICT).Assert();
6796 return i::Handle<i::Symbol>::cast(symbol);
6800 Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
6801 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6802 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6803 i::Handle<i::String> part = i_isolate->factory()->for_string();
6804 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6808 Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
6809 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6810 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6811 i::Handle<i::String> part = i_isolate->factory()->for_api_string();
6812 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6816 Local<Symbol> v8::Symbol::GetIterator(Isolate* isolate) {
6817 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6818 return Utils::ToLocal(i_isolate->factory()->iterator_symbol());
6822 Local<Symbol> v8::Symbol::GetUnscopables(Isolate* isolate) {
6823 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6824 return Utils::ToLocal(i_isolate->factory()->unscopables_symbol());
6828 Local<Symbol> v8::Symbol::GetToStringTag(Isolate* isolate) {
6829 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6830 return Utils::ToLocal(i_isolate->factory()->to_string_tag_symbol());
6834 Local<Number> v8::Number::New(Isolate* isolate, double value) {
6835 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6836 if (std::isnan(value)) {
6837 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6838 value = std::numeric_limits<double>::quiet_NaN();
6840 ENTER_V8(internal_isolate);
6841 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6842 return Utils::NumberToLocal(result);
6846 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
6847 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6848 if (i::Smi::IsValid(value)) {
6849 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
6852 ENTER_V8(internal_isolate);
6853 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6854 return Utils::IntegerToLocal(result);
6858 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
6859 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6860 bool fits_into_int32_t = (value & (1 << 31)) == 0;
6861 if (fits_into_int32_t) {
6862 return Integer::New(isolate, static_cast<int32_t>(value));
6864 ENTER_V8(internal_isolate);
6865 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6866 return Utils::IntegerToLocal(result);
6870 void Isolate::CollectAllGarbage(const char* gc_reason) {
6871 i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
6872 if (heap->incremental_marking()->IsStopped()) {
6873 if (heap->incremental_marking()->CanBeActivated()) {
6874 heap->StartIncrementalMarking(
6875 i::Heap::kNoGCFlags,
6876 kGCCallbackFlagSynchronousPhantomCallbackProcessing, gc_reason);
6878 heap->CollectAllGarbage(
6879 i::Heap::kNoGCFlags, gc_reason,
6880 kGCCallbackFlagSynchronousPhantomCallbackProcessing);
6883 // Incremental marking is turned on an has already been started.
6885 // TODO(mlippautz): Compute the time slice for incremental marking based on
6887 double deadline = heap->MonotonicallyIncreasingTimeInMs() +
6888 i::FLAG_external_allocation_limit_incremental_time;
6889 heap->AdvanceIncrementalMarking(
6890 0, deadline, i::IncrementalMarking::StepActions(
6891 i::IncrementalMarking::GC_VIA_STACK_GUARD,
6892 i::IncrementalMarking::FORCE_MARKING,
6893 i::IncrementalMarking::FORCE_COMPLETION));
6898 HeapProfiler* Isolate::GetHeapProfiler() {
6899 i::HeapProfiler* heap_profiler =
6900 reinterpret_cast<i::Isolate*>(this)->heap_profiler();
6901 return reinterpret_cast<HeapProfiler*>(heap_profiler);
6905 CpuProfiler* Isolate::GetCpuProfiler() {
6906 i::CpuProfiler* cpu_profiler =
6907 reinterpret_cast<i::Isolate*>(this)->cpu_profiler();
6908 return reinterpret_cast<CpuProfiler*>(cpu_profiler);
6912 bool Isolate::InContext() {
6913 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6914 return isolate->context() != NULL;
6918 v8::Local<v8::Context> Isolate::GetCurrentContext() {
6919 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6920 i::Context* context = isolate->context();
6921 if (context == NULL) return Local<Context>();
6922 i::Context* native_context = context->native_context();
6923 if (native_context == NULL) return Local<Context>();
6924 return Utils::ToLocal(i::Handle<i::Context>(native_context));
6928 v8::Local<v8::Context> Isolate::GetCallingContext() {
6929 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6930 i::Handle<i::Object> calling = isolate->GetCallingNativeContext();
6931 if (calling.is_null()) return Local<Context>();
6932 return Utils::ToLocal(i::Handle<i::Context>::cast(calling));
6936 v8::Local<v8::Context> Isolate::GetEnteredContext() {
6937 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6938 i::Handle<i::Object> last =
6939 isolate->handle_scope_implementer()->LastEnteredContext();
6940 if (last.is_null()) return Local<Context>();
6941 return Utils::ToLocal(i::Handle<i::Context>::cast(last));
6945 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
6946 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6948 // If we're passed an empty handle, we throw an undefined exception
6949 // to deal more gracefully with out of memory situations.
6950 if (value.IsEmpty()) {
6951 isolate->ScheduleThrow(isolate->heap()->undefined_value());
6953 isolate->ScheduleThrow(*Utils::OpenHandle(*value));
6955 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
6959 void Isolate::SetObjectGroupId(internal::Object** object, UniqueId id) {
6960 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6961 internal_isolate->global_handles()->SetObjectGroupId(
6962 v8::internal::Handle<v8::internal::Object>(object).location(),
6967 void Isolate::SetReferenceFromGroup(UniqueId id, internal::Object** object) {
6968 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6969 internal_isolate->global_handles()->SetReferenceFromGroup(
6971 v8::internal::Handle<v8::internal::Object>(object).location());
6975 void Isolate::SetReference(internal::Object** parent,
6976 internal::Object** child) {
6977 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6978 i::Object** parent_location =
6979 v8::internal::Handle<v8::internal::Object>(parent).location();
6980 internal_isolate->global_handles()->SetReference(
6981 reinterpret_cast<i::HeapObject**>(parent_location),
6982 v8::internal::Handle<v8::internal::Object>(child).location());
6986 void Isolate::AddGCPrologueCallback(GCPrologueCallback callback,
6988 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6989 isolate->heap()->AddGCPrologueCallback(callback, gc_type);
6993 void Isolate::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6994 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6995 isolate->heap()->RemoveGCPrologueCallback(callback);
6999 void Isolate::AddGCEpilogueCallback(GCEpilogueCallback callback,
7001 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7002 isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
7006 void Isolate::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
7007 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7008 isolate->heap()->RemoveGCEpilogueCallback(callback);
7012 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
7013 i::Isolate* isolate = i::Isolate::Current();
7014 isolate->heap()->AddGCPrologueCallback(
7015 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback),
7021 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
7022 i::Isolate* isolate = i::Isolate::Current();
7023 isolate->heap()->AddGCEpilogueCallback(
7024 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback),
7030 void Isolate::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
7032 AllocationAction action) {
7033 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7034 isolate->memory_allocator()->AddMemoryAllocationCallback(
7035 callback, space, action);
7039 void Isolate::RemoveMemoryAllocationCallback(
7040 MemoryAllocationCallback callback) {
7041 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7042 isolate->memory_allocator()->RemoveMemoryAllocationCallback(
7047 void Isolate::TerminateExecution() {
7048 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7049 isolate->stack_guard()->RequestTerminateExecution();
7053 bool Isolate::IsExecutionTerminating() {
7054 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7055 return IsExecutionTerminatingCheck(isolate);
7059 void Isolate::CancelTerminateExecution() {
7060 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7061 isolate->stack_guard()->ClearTerminateExecution();
7062 isolate->CancelTerminateExecution();
7066 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
7067 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7068 isolate->RequestInterrupt(callback, data);
7072 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
7073 CHECK(i::FLAG_expose_gc);
7074 if (type == kMinorGarbageCollection) {
7075 reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
7076 i::NEW_SPACE, "Isolate::RequestGarbageCollection",
7077 kGCCallbackFlagForced);
7079 DCHECK_EQ(kFullGarbageCollection, type);
7080 reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
7081 i::Heap::kAbortIncrementalMarkingMask,
7082 "Isolate::RequestGarbageCollection", kGCCallbackFlagForced);
7087 Isolate* Isolate::GetCurrent() {
7088 i::Isolate* isolate = i::Isolate::Current();
7089 return reinterpret_cast<Isolate*>(isolate);
7093 Isolate* Isolate::New(const Isolate::CreateParams& params) {
7094 i::Isolate* isolate = new i::Isolate(false);
7095 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7096 CHECK(params.array_buffer_allocator != NULL);
7097 isolate->set_array_buffer_allocator(params.array_buffer_allocator);
7098 if (params.snapshot_blob != NULL) {
7099 isolate->set_snapshot_blob(params.snapshot_blob);
7101 isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
7103 if (params.entry_hook) {
7104 isolate->set_function_entry_hook(params.entry_hook);
7106 if (params.code_event_handler) {
7107 isolate->InitializeLoggingAndCounters();
7108 isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
7109 params.code_event_handler);
7111 if (params.counter_lookup_callback) {
7112 v8_isolate->SetCounterFunction(params.counter_lookup_callback);
7115 if (params.create_histogram_callback) {
7116 v8_isolate->SetCreateHistogramFunction(params.create_histogram_callback);
7119 if (params.add_histogram_sample_callback) {
7120 v8_isolate->SetAddHistogramSampleFunction(
7121 params.add_histogram_sample_callback);
7123 SetResourceConstraints(isolate, params.constraints);
7124 // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
7125 Isolate::Scope isolate_scope(v8_isolate);
7126 if (params.entry_hook || !i::Snapshot::Initialize(isolate)) {
7127 // If the isolate has a function entry hook, it needs to re-build all its
7128 // code stubs with entry hooks embedded, so don't deserialize a snapshot.
7129 if (i::Snapshot::EmbedsScript(isolate)) {
7130 // If the snapshot embeds a script, we cannot initialize the isolate
7131 // without the snapshot as a fallback. This is unlikely to happen though.
7132 V8_Fatal(__FILE__, __LINE__,
7133 "Initializing isolate from custom startup snapshot failed");
7135 isolate->Init(NULL);
7141 void Isolate::Dispose() {
7142 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7143 if (!Utils::ApiCheck(!isolate->IsInUse(),
7144 "v8::Isolate::Dispose()",
7145 "Disposing the isolate that is entered by a thread.")) {
7148 isolate->TearDown();
7152 void Isolate::Enter() {
7153 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7158 void Isolate::Exit() {
7159 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7164 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
7166 Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
7167 : on_failure_(on_failure) {
7168 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7169 if (on_failure_ == CRASH_ON_FAILURE) {
7170 internal_ = reinterpret_cast<void*>(
7171 new i::DisallowJavascriptExecution(i_isolate));
7173 DCHECK_EQ(THROW_ON_FAILURE, on_failure);
7174 internal_ = reinterpret_cast<void*>(
7175 new i::ThrowOnJavascriptExecution(i_isolate));
7180 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
7181 if (on_failure_ == CRASH_ON_FAILURE) {
7182 delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
7184 delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
7189 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
7191 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7192 internal_assert_ = reinterpret_cast<void*>(
7193 new i::AllowJavascriptExecution(i_isolate));
7194 internal_throws_ = reinterpret_cast<void*>(
7195 new i::NoThrowOnJavascriptExecution(i_isolate));
7199 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
7200 delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
7201 delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
7205 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
7207 : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
7208 isolate_->handle_scope_implementer()->IncrementCallDepth();
7212 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
7213 isolate_->handle_scope_implementer()->DecrementCallDepth();
7217 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
7218 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7219 i::Heap* heap = isolate->heap();
7220 heap_statistics->total_heap_size_ = heap->CommittedMemory();
7221 heap_statistics->total_heap_size_executable_ =
7222 heap->CommittedMemoryExecutable();
7223 heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
7224 heap_statistics->total_available_size_ = heap->Available();
7225 heap_statistics->used_heap_size_ = heap->SizeOfObjects();
7226 heap_statistics->heap_size_limit_ = heap->MaxReserved();
7230 size_t Isolate::NumberOfHeapSpaces() {
7231 return i::LAST_SPACE - i::FIRST_SPACE + 1;
7235 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7237 if (!space_statistics) return false;
7238 if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
7241 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7242 i::Heap* heap = isolate->heap();
7243 i::Space* space = heap->space(static_cast<int>(index));
7245 space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
7246 space_statistics->space_size_ = space->CommittedMemory();
7247 space_statistics->space_used_size_ = space->SizeOfObjects();
7248 space_statistics->space_available_size_ = space->Available();
7249 space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
7254 size_t Isolate::NumberOfTrackedHeapObjectTypes() {
7255 return i::Heap::OBJECT_STATS_COUNT;
7259 bool Isolate::GetHeapObjectStatisticsAtLastGC(
7260 HeapObjectStatistics* object_statistics, size_t type_index) {
7261 if (!object_statistics) return false;
7262 if (type_index >= i::Heap::OBJECT_STATS_COUNT) return false;
7263 if (!i::FLAG_track_gc_object_stats) return false;
7265 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7266 i::Heap* heap = isolate->heap();
7267 const char* object_type;
7268 const char* object_sub_type;
7269 size_t object_count = heap->object_count_last_gc(type_index);
7270 size_t object_size = heap->object_size_last_gc(type_index);
7271 if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
7272 // There should be no objects counted when the type is unknown.
7273 DCHECK_EQ(object_count, 0U);
7274 DCHECK_EQ(object_size, 0U);
7278 object_statistics->object_type_ = object_type;
7279 object_statistics->object_sub_type_ = object_sub_type;
7280 object_statistics->object_count_ = object_count;
7281 object_statistics->object_size_ = object_size;
7286 void Isolate::GetStackSample(const RegisterState& state, void** frames,
7287 size_t frames_limit, SampleInfo* sample_info) {
7288 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7289 i::TickSample::GetStackSample(isolate, state, i::TickSample::kSkipCEntryFrame,
7290 frames, frames_limit, sample_info);
7294 void Isolate::SetEventLogger(LogEventCallback that) {
7295 // Do not overwrite the event logger if we want to log explicitly.
7296 if (i::FLAG_log_internal_timer_events) return;
7297 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7298 isolate->set_event_logger(that);
7302 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
7303 if (callback == NULL) return;
7304 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7305 isolate->AddCallCompletedCallback(callback);
7309 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
7310 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7311 isolate->RemoveCallCompletedCallback(callback);
7315 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
7316 if (callback == NULL) return;
7317 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7318 isolate->SetPromiseRejectCallback(callback);
7322 void Isolate::RunMicrotasks() {
7323 reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
7327 void Isolate::EnqueueMicrotask(Local<Function> microtask) {
7328 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7329 isolate->EnqueueMicrotask(Utils::OpenHandle(*microtask));
7333 void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) {
7334 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7335 i::HandleScope scope(isolate);
7336 i::Handle<i::CallHandlerInfo> callback_info =
7337 i::Handle<i::CallHandlerInfo>::cast(
7338 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE));
7339 SET_FIELD_WRAPPED(callback_info, set_callback, microtask);
7340 SET_FIELD_WRAPPED(callback_info, set_data, data);
7341 isolate->EnqueueMicrotask(callback_info);
7345 void Isolate::SetAutorunMicrotasks(bool autorun) {
7346 reinterpret_cast<i::Isolate*>(this)->set_autorun_microtasks(autorun);
7350 bool Isolate::WillAutorunMicrotasks() const {
7351 return reinterpret_cast<const i::Isolate*>(this)->autorun_microtasks();
7355 void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
7356 reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
7360 void Isolate::SetCounterFunction(CounterLookupCallback callback) {
7361 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7362 isolate->stats_table()->SetCounterFunction(callback);
7363 isolate->InitializeLoggingAndCounters();
7364 isolate->counters()->ResetCounters();
7368 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
7369 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7370 isolate->stats_table()->SetCreateHistogramFunction(callback);
7371 isolate->InitializeLoggingAndCounters();
7372 isolate->counters()->ResetHistograms();
7376 void Isolate::SetAddHistogramSampleFunction(
7377 AddHistogramSampleCallback callback) {
7378 reinterpret_cast<i::Isolate*>(this)
7380 ->SetAddHistogramSampleFunction(callback);
7384 bool Isolate::IdleNotification(int idle_time_in_ms) {
7385 // Returning true tells the caller that it need not
7386 // continue to call IdleNotification.
7387 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7388 if (!i::FLAG_use_idle_notification) return true;
7389 return isolate->heap()->IdleNotification(idle_time_in_ms);
7393 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
7394 // Returning true tells the caller that it need not
7395 // continue to call IdleNotification.
7396 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7397 if (!i::FLAG_use_idle_notification) return true;
7398 return isolate->heap()->IdleNotification(deadline_in_seconds);
7402 void Isolate::LowMemoryNotification() {
7403 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7405 i::HistogramTimerScope idle_notification_scope(
7406 isolate->counters()->gc_low_memory_notification());
7407 isolate->heap()->CollectAllAvailableGarbage("low memory notification");
7412 int Isolate::ContextDisposedNotification(bool dependant_context) {
7413 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7414 return isolate->heap()->NotifyContextDisposed(dependant_context);
7418 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
7419 JitCodeEventHandler event_handler) {
7420 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7421 // Ensure that logging is initialized for our isolate.
7422 isolate->InitializeLoggingAndCounters();
7423 isolate->logger()->SetCodeEventHandler(options, event_handler);
7427 void Isolate::SetStackLimit(uintptr_t stack_limit) {
7428 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7430 isolate->stack_guard()->SetStackLimit(stack_limit);
7434 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
7435 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7436 if (isolate->code_range()->valid()) {
7437 *start = isolate->code_range()->start();
7438 *length_in_bytes = isolate->code_range()->size();
7441 *length_in_bytes = 0;
7446 void Isolate::SetFatalErrorHandler(FatalErrorCallback that) {
7447 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7448 isolate->set_exception_behavior(that);
7452 void Isolate::SetAllowCodeGenerationFromStringsCallback(
7453 AllowCodeGenerationFromStringsCallback callback) {
7454 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7455 isolate->set_allow_code_gen_callback(callback);
7459 bool Isolate::IsDead() {
7460 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7461 return isolate->IsDead();
7465 bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
7466 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7468 i::HandleScope scope(isolate);
7469 NeanderArray listeners(isolate->factory()->message_listeners());
7470 NeanderObject obj(isolate, 2);
7471 obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
7472 obj.set(1, data.IsEmpty() ? isolate->heap()->undefined_value()
7473 : *Utils::OpenHandle(*data));
7474 listeners.add(isolate, obj.value());
7479 void Isolate::RemoveMessageListeners(MessageCallback that) {
7480 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7482 i::HandleScope scope(isolate);
7483 NeanderArray listeners(isolate->factory()->message_listeners());
7484 for (int i = 0; i < listeners.length(); i++) {
7485 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
7487 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
7488 i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
7489 if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
7490 listeners.set(i, isolate->heap()->undefined_value());
7496 void Isolate::SetFailedAccessCheckCallbackFunction(
7497 FailedAccessCheckCallback callback) {
7498 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7499 isolate->SetFailedAccessCheckCallback(callback);
7503 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
7504 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7505 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7506 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7511 void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) {
7512 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7513 isolate->heap()->VisitExternalResources(visitor);
7517 class VisitorAdapter : public i::ObjectVisitor {
7519 explicit VisitorAdapter(PersistentHandleVisitor* visitor)
7520 : visitor_(visitor) {}
7521 virtual void VisitPointers(i::Object** start, i::Object** end) {
7524 virtual void VisitEmbedderReference(i::Object** p, uint16_t class_id) {
7525 Value* value = ToApi<Value>(i::Handle<i::Object>(p));
7526 visitor_->VisitPersistentHandle(
7527 reinterpret_cast<Persistent<Value>*>(&value), class_id);
7531 PersistentHandleVisitor* visitor_;
7535 void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
7536 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7537 i::DisallowHeapAllocation no_allocation;
7538 VisitorAdapter visitor_adapter(visitor);
7539 isolate->global_handles()->IterateAllRootsWithClassIds(&visitor_adapter);
7543 void Isolate::VisitHandlesForPartialDependence(
7544 PersistentHandleVisitor* visitor) {
7545 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7546 i::DisallowHeapAllocation no_allocation;
7547 VisitorAdapter visitor_adapter(visitor);
7548 isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds(
7553 String::Utf8Value::Utf8Value(v8::Local<v8::Value> obj)
7554 : str_(NULL), length_(0) {
7555 if (obj.IsEmpty()) return;
7556 i::Isolate* isolate = i::Isolate::Current();
7557 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7559 i::HandleScope scope(isolate);
7560 Local<Context> context = v8_isolate->GetCurrentContext();
7561 TryCatch try_catch(v8_isolate);
7563 if (!obj->ToString(context).ToLocal(&str)) return;
7564 i::Handle<i::String> i_str = Utils::OpenHandle(*str);
7565 length_ = v8::Utf8Length(*i_str, isolate);
7566 str_ = i::NewArray<char>(length_ + 1);
7567 str->WriteUtf8(str_);
7571 String::Utf8Value::~Utf8Value() {
7572 i::DeleteArray(str_);
7576 String::Value::Value(v8::Local<v8::Value> obj) : str_(NULL), length_(0) {
7577 if (obj.IsEmpty()) return;
7578 i::Isolate* isolate = i::Isolate::Current();
7579 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7581 i::HandleScope scope(isolate);
7582 Local<Context> context = v8_isolate->GetCurrentContext();
7583 TryCatch try_catch(v8_isolate);
7585 if (!obj->ToString(context).ToLocal(&str)) return;
7586 length_ = str->Length();
7587 str_ = i::NewArray<uint16_t>(length_ + 1);
7592 String::Value::~Value() {
7593 i::DeleteArray(str_);
7597 #define DEFINE_ERROR(NAME, name) \
7598 Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) { \
7599 i::Isolate* isolate = i::Isolate::Current(); \
7600 LOG_API(isolate, #NAME); \
7601 ENTER_V8(isolate); \
7604 i::HandleScope scope(isolate); \
7605 i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \
7606 i::Handle<i::JSFunction> constructor = isolate->name##_function(); \
7607 error = *isolate->factory()->NewError(constructor, message); \
7609 i::Handle<i::Object> result(error, isolate); \
7610 return Utils::ToLocal(result); \
7613 DEFINE_ERROR(RangeError, range_error)
7614 DEFINE_ERROR(ReferenceError, reference_error)
7615 DEFINE_ERROR(SyntaxError, syntax_error)
7616 DEFINE_ERROR(TypeError, type_error)
7617 DEFINE_ERROR(Error, error)
7622 Local<Message> Exception::CreateMessage(Local<Value> exception) {
7623 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7624 if (!obj->IsHeapObject()) return Local<Message>();
7625 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
7627 i::HandleScope scope(isolate);
7628 return Utils::MessageToLocal(
7629 scope.CloseAndEscape(isolate->CreateMessage(obj, NULL)));
7633 Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) {
7634 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7635 if (!obj->IsJSObject()) return Local<StackTrace>();
7636 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
7637 i::Isolate* isolate = js_obj->GetIsolate();
7639 return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj));
7643 // --- D e b u g S u p p o r t ---
7645 bool Debug::SetDebugEventListener(EventCallback that, Local<Value> data) {
7646 i::Isolate* isolate = i::Isolate::Current();
7648 i::HandleScope scope(isolate);
7649 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
7651 foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
7653 isolate->debug()->SetEventListener(foreign,
7654 Utils::OpenHandle(*data, true));
7659 void Debug::DebugBreak(Isolate* isolate) {
7660 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->RequestDebugBreak();
7664 void Debug::CancelDebugBreak(Isolate* isolate) {
7665 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7666 internal_isolate->stack_guard()->ClearDebugBreak();
7670 bool Debug::CheckDebugBreak(Isolate* isolate) {
7671 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7672 return internal_isolate->stack_guard()->CheckDebugBreak();
7676 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
7677 i::Isolate* isolate = i::Isolate::Current();
7679 isolate->debug()->SetMessageHandler(handler);
7683 void Debug::SendCommand(Isolate* isolate,
7684 const uint16_t* command,
7686 ClientData* client_data) {
7687 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7688 internal_isolate->debug()->EnqueueCommandMessage(
7689 i::Vector<const uint16_t>(command, length), client_data);
7693 MaybeLocal<Value> Debug::Call(Local<Context> context,
7694 v8::Local<v8::Function> fun,
7695 v8::Local<v8::Value> data) {
7696 PREPARE_FOR_EXECUTION(context, "v8::Debug::Call()", Value);
7697 i::Handle<i::Object> data_obj;
7698 if (data.IsEmpty()) {
7699 data_obj = isolate->factory()->undefined_value();
7701 data_obj = Utils::OpenHandle(*data);
7703 Local<Value> result;
7704 has_pending_exception =
7705 !ToLocal<Value>(isolate->debug()->Call(Utils::OpenHandle(*fun), data_obj),
7707 RETURN_ON_FAILED_EXECUTION(Value);
7708 RETURN_ESCAPED(result);
7712 Local<Value> Debug::Call(v8::Local<v8::Function> fun,
7713 v8::Local<v8::Value> data) {
7714 auto context = ContextFromHeapObject(Utils::OpenHandle(*fun));
7715 RETURN_TO_LOCAL_UNCHECKED(Call(context, fun, data), Value);
7719 MaybeLocal<Value> Debug::GetMirror(Local<Context> context,
7720 v8::Local<v8::Value> obj) {
7721 PREPARE_FOR_EXECUTION(context, "v8::Debug::GetMirror()", Value);
7722 i::Debug* isolate_debug = isolate->debug();
7723 has_pending_exception = !isolate_debug->Load();
7724 RETURN_ON_FAILED_EXECUTION(Value);
7725 i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global_object());
7726 auto name = isolate->factory()->NewStringFromStaticChars("MakeMirror");
7727 auto fun_obj = i::Object::GetProperty(debug, name).ToHandleChecked();
7728 auto v8_fun = Utils::ToLocal(i::Handle<i::JSFunction>::cast(fun_obj));
7729 const int kArgc = 1;
7730 v8::Local<v8::Value> argv[kArgc] = {obj};
7731 Local<Value> result;
7732 has_pending_exception = !v8_fun->Call(context, Utils::ToLocal(debug), kArgc,
7733 argv).ToLocal(&result);
7734 RETURN_ON_FAILED_EXECUTION(Value);
7735 RETURN_ESCAPED(result);
7739 Local<Value> Debug::GetMirror(v8::Local<v8::Value> obj) {
7740 RETURN_TO_LOCAL_UNCHECKED(GetMirror(Local<Context>(), obj), Value);
7744 void Debug::ProcessDebugMessages() {
7745 i::Isolate::Current()->debug()->ProcessDebugMessages(true);
7749 Local<Context> Debug::GetDebugContext() {
7750 i::Isolate* isolate = i::Isolate::Current();
7752 return Utils::ToLocal(isolate->debug()->GetDebugContext());
7756 void Debug::SetLiveEditEnabled(Isolate* isolate, bool enable) {
7757 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7758 internal_isolate->debug()->set_live_edit_enabled(enable);
7762 MaybeLocal<Array> Debug::GetInternalProperties(Isolate* v8_isolate,
7763 Local<Value> value) {
7764 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7766 i::Handle<i::Object> val = Utils::OpenHandle(*value);
7767 i::Handle<i::JSArray> result;
7768 if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
7769 return MaybeLocal<Array>();
7770 return Utils::ToLocal(result);
7774 Local<String> CpuProfileNode::GetFunctionName() const {
7775 i::Isolate* isolate = i::Isolate::Current();
7776 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7777 const i::CodeEntry* entry = node->entry();
7778 i::Handle<i::String> name =
7779 isolate->factory()->InternalizeUtf8String(entry->name());
7780 if (!entry->has_name_prefix()) {
7781 return ToApiHandle<String>(name);
7783 // We do not expect this to fail. Change this if it does.
7784 i::Handle<i::String> cons = isolate->factory()->NewConsString(
7785 isolate->factory()->InternalizeUtf8String(entry->name_prefix()),
7786 name).ToHandleChecked();
7787 return ToApiHandle<String>(cons);
7792 int CpuProfileNode::GetScriptId() const {
7793 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7794 const i::CodeEntry* entry = node->entry();
7795 return entry->script_id();
7799 Local<String> CpuProfileNode::GetScriptResourceName() const {
7800 i::Isolate* isolate = i::Isolate::Current();
7801 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7802 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7803 node->entry()->resource_name()));
7807 int CpuProfileNode::GetLineNumber() const {
7808 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
7812 int CpuProfileNode::GetColumnNumber() const {
7813 return reinterpret_cast<const i::ProfileNode*>(this)->
7814 entry()->column_number();
7818 unsigned int CpuProfileNode::GetHitLineCount() const {
7819 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7820 return node->GetHitLineCount();
7824 bool CpuProfileNode::GetLineTicks(LineTick* entries,
7825 unsigned int length) const {
7826 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7827 return node->GetLineTicks(entries, length);
7831 const char* CpuProfileNode::GetBailoutReason() const {
7832 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7833 return node->entry()->bailout_reason();
7837 unsigned CpuProfileNode::GetHitCount() const {
7838 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
7842 unsigned CpuProfileNode::GetCallUid() const {
7843 return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
7847 unsigned CpuProfileNode::GetNodeId() const {
7848 return reinterpret_cast<const i::ProfileNode*>(this)->id();
7852 int CpuProfileNode::GetChildrenCount() const {
7853 return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
7857 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
7858 const i::ProfileNode* child =
7859 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
7860 return reinterpret_cast<const CpuProfileNode*>(child);
7864 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
7865 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7866 return node->deopt_infos();
7870 void CpuProfile::Delete() {
7871 i::Isolate* isolate = i::Isolate::Current();
7872 i::CpuProfiler* profiler = isolate->cpu_profiler();
7873 DCHECK(profiler != NULL);
7874 profiler->DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
7878 Local<String> CpuProfile::GetTitle() const {
7879 i::Isolate* isolate = i::Isolate::Current();
7880 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7881 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7886 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
7887 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7888 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
7892 const CpuProfileNode* CpuProfile::GetSample(int index) const {
7893 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7894 return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
7898 int64_t CpuProfile::GetSampleTimestamp(int index) const {
7899 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7900 return (profile->sample_timestamp(index) - base::TimeTicks())
7905 int64_t CpuProfile::GetStartTime() const {
7906 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7907 return (profile->start_time() - base::TimeTicks()).InMicroseconds();
7911 int64_t CpuProfile::GetEndTime() const {
7912 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7913 return (profile->end_time() - base::TimeTicks()).InMicroseconds();
7917 int CpuProfile::GetSamplesCount() const {
7918 return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
7922 void CpuProfiler::SetSamplingInterval(int us) {
7924 return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
7925 base::TimeDelta::FromMicroseconds(us));
7929 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
7930 reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
7931 *Utils::OpenHandle(*title), record_samples);
7935 CpuProfile* CpuProfiler::StopProfiling(Local<String> title) {
7936 return reinterpret_cast<CpuProfile*>(
7937 reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
7938 *Utils::OpenHandle(*title)));
7942 void CpuProfiler::SetIdle(bool is_idle) {
7943 i::Isolate* isolate = reinterpret_cast<i::CpuProfiler*>(this)->isolate();
7944 v8::StateTag state = isolate->current_vm_state();
7945 DCHECK(state == v8::EXTERNAL || state == v8::IDLE);
7946 if (isolate->js_entry_sp() != NULL) return;
7948 isolate->set_current_vm_state(v8::IDLE);
7949 } else if (state == v8::IDLE) {
7950 isolate->set_current_vm_state(v8::EXTERNAL);
7955 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
7956 return const_cast<i::HeapGraphEdge*>(
7957 reinterpret_cast<const i::HeapGraphEdge*>(edge));
7961 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
7962 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
7966 Local<Value> HeapGraphEdge::GetName() const {
7967 i::Isolate* isolate = i::Isolate::Current();
7968 i::HeapGraphEdge* edge = ToInternal(this);
7969 switch (edge->type()) {
7970 case i::HeapGraphEdge::kContextVariable:
7971 case i::HeapGraphEdge::kInternal:
7972 case i::HeapGraphEdge::kProperty:
7973 case i::HeapGraphEdge::kShortcut:
7974 case i::HeapGraphEdge::kWeak:
7975 return ToApiHandle<String>(
7976 isolate->factory()->InternalizeUtf8String(edge->name()));
7977 case i::HeapGraphEdge::kElement:
7978 case i::HeapGraphEdge::kHidden:
7979 return ToApiHandle<Number>(
7980 isolate->factory()->NewNumberFromInt(edge->index()));
7981 default: UNREACHABLE();
7983 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
7987 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
7988 const i::HeapEntry* from = ToInternal(this)->from();
7989 return reinterpret_cast<const HeapGraphNode*>(from);
7993 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
7994 const i::HeapEntry* to = ToInternal(this)->to();
7995 return reinterpret_cast<const HeapGraphNode*>(to);
7999 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
8000 return const_cast<i::HeapEntry*>(
8001 reinterpret_cast<const i::HeapEntry*>(entry));
8005 HeapGraphNode::Type HeapGraphNode::GetType() const {
8006 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
8010 Local<String> HeapGraphNode::GetName() const {
8011 i::Isolate* isolate = i::Isolate::Current();
8012 return ToApiHandle<String>(
8013 isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
8017 SnapshotObjectId HeapGraphNode::GetId() const {
8018 return ToInternal(this)->id();
8022 size_t HeapGraphNode::GetShallowSize() const {
8023 return ToInternal(this)->self_size();
8027 int HeapGraphNode::GetChildrenCount() const {
8028 return ToInternal(this)->children().length();
8032 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
8033 return reinterpret_cast<const HeapGraphEdge*>(
8034 ToInternal(this)->children()[index]);
8038 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
8039 return const_cast<i::HeapSnapshot*>(
8040 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
8044 void HeapSnapshot::Delete() {
8045 i::Isolate* isolate = i::Isolate::Current();
8046 if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
8047 ToInternal(this)->Delete();
8049 // If this is the last snapshot, clean up all accessory data as well.
8050 isolate->heap_profiler()->DeleteAllSnapshots();
8055 const HeapGraphNode* HeapSnapshot::GetRoot() const {
8056 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
8060 const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
8061 return reinterpret_cast<const HeapGraphNode*>(
8062 ToInternal(this)->GetEntryById(id));
8066 int HeapSnapshot::GetNodesCount() const {
8067 return ToInternal(this)->entries().length();
8071 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
8072 return reinterpret_cast<const HeapGraphNode*>(
8073 &ToInternal(this)->entries().at(index));
8077 SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
8078 return ToInternal(this)->max_snapshot_js_object_id();
8082 void HeapSnapshot::Serialize(OutputStream* stream,
8083 HeapSnapshot::SerializationFormat format) const {
8084 Utils::ApiCheck(format == kJSON,
8085 "v8::HeapSnapshot::Serialize",
8086 "Unknown serialization format");
8087 Utils::ApiCheck(stream->GetChunkSize() > 0,
8088 "v8::HeapSnapshot::Serialize",
8089 "Invalid stream chunk size");
8090 i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
8091 serializer.Serialize(stream);
8096 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
8097 HeapProfiler::kUnknownObjectId;
8100 int HeapProfiler::GetSnapshotCount() {
8101 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
8105 const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
8106 return reinterpret_cast<const HeapSnapshot*>(
8107 reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
8111 SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) {
8112 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
8113 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
8117 Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
8118 i::Handle<i::Object> obj =
8119 reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
8120 if (obj.is_null()) return Local<Value>();
8121 return Utils::ToLocal(obj);
8125 void HeapProfiler::ClearObjectIds() {
8126 reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
8130 const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
8131 ActivityControl* control, ObjectNameResolver* resolver) {
8132 return reinterpret_cast<const HeapSnapshot*>(
8133 reinterpret_cast<i::HeapProfiler*>(this)
8134 ->TakeSnapshot(control, resolver));
8138 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
8139 reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
8144 void HeapProfiler::StopTrackingHeapObjects() {
8145 reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
8149 SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream,
8150 int64_t* timestamp_us) {
8151 i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
8152 return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
8156 void HeapProfiler::DeleteAllHeapSnapshots() {
8157 reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
8161 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
8162 WrapperInfoCallback callback) {
8163 reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
8168 size_t HeapProfiler::GetProfilerMemorySize() {
8169 return reinterpret_cast<i::HeapProfiler*>(this)->
8170 GetMemorySizeUsedByProfiler();
8174 void HeapProfiler::SetRetainedObjectInfo(UniqueId id,
8175 RetainedObjectInfo* info) {
8176 reinterpret_cast<i::HeapProfiler*>(this)->SetRetainedObjectInfo(id, info);
8180 v8::Testing::StressType internal::Testing::stress_type_ =
8181 v8::Testing::kStressTypeOpt;
8184 void Testing::SetStressRunType(Testing::StressType type) {
8185 internal::Testing::set_stress_type(type);
8189 int Testing::GetStressRuns() {
8190 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
8192 // In debug mode the code runs much slower so stressing will only make two
8201 static void SetFlagsFromString(const char* flags) {
8202 V8::SetFlagsFromString(flags, i::StrLength(flags));
8206 void Testing::PrepareStressRun(int run) {
8207 static const char* kLazyOptimizations =
8208 "--prepare-always-opt "
8209 "--max-inlined-source-size=999999 "
8210 "--max-inlined-nodes=999999 "
8211 "--max-inlined-nodes-cumulative=999999 "
8213 static const char* kForcedOptimizations = "--always-opt";
8215 // If deoptimization stressed turn on frequent deoptimization. If no value
8216 // is spefified through --deopt-every-n-times use a default default value.
8217 static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
8218 if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
8219 internal::FLAG_deopt_every_n_times == 0) {
8220 SetFlagsFromString(kDeoptEvery13Times);
8224 // As stressing in debug mode only make two runs skip the deopt stressing
8226 if (run == GetStressRuns() - 1) {
8227 SetFlagsFromString(kForcedOptimizations);
8229 SetFlagsFromString(kLazyOptimizations);
8232 if (run == GetStressRuns() - 1) {
8233 SetFlagsFromString(kForcedOptimizations);
8234 } else if (run != GetStressRuns() - 2) {
8235 SetFlagsFromString(kLazyOptimizations);
8241 // TODO(svenpanne) Deprecate this.
8242 void Testing::DeoptimizeAll() {
8243 i::Isolate* isolate = i::Isolate::Current();
8244 i::HandleScope scope(isolate);
8245 internal::Deoptimizer::DeoptimizeAll(isolate);
8249 namespace internal {
8252 void HandleScopeImplementer::FreeThreadResources() {
8257 char* HandleScopeImplementer::ArchiveThread(char* storage) {
8258 HandleScopeData* current = isolate_->handle_scope_data();
8259 handle_scope_data_ = *current;
8260 MemCopy(storage, this, sizeof(*this));
8262 ResetAfterArchive();
8263 current->Initialize();
8265 return storage + ArchiveSpacePerThread();
8269 int HandleScopeImplementer::ArchiveSpacePerThread() {
8270 return sizeof(HandleScopeImplementer);
8274 char* HandleScopeImplementer::RestoreThread(char* storage) {
8275 MemCopy(this, storage, sizeof(*this));
8276 *isolate_->handle_scope_data() = handle_scope_data_;
8277 return storage + ArchiveSpacePerThread();
8281 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
8283 bool found_block_before_deferred = false;
8285 // Iterate over all handles in the blocks except for the last.
8286 for (int i = blocks()->length() - 2; i >= 0; --i) {
8287 Object** block = blocks()->at(i);
8288 if (last_handle_before_deferred_block_ != NULL &&
8289 (last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) &&
8290 (last_handle_before_deferred_block_ >= block)) {
8291 v->VisitPointers(block, last_handle_before_deferred_block_);
8292 DCHECK(!found_block_before_deferred);
8294 found_block_before_deferred = true;
8297 v->VisitPointers(block, &block[kHandleBlockSize]);
8301 DCHECK(last_handle_before_deferred_block_ == NULL ||
8302 found_block_before_deferred);
8304 // Iterate over live handles in the last block (if any).
8305 if (!blocks()->is_empty()) {
8306 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
8309 List<Context*>* context_lists[2] = { &saved_contexts_, &entered_contexts_};
8310 for (unsigned i = 0; i < arraysize(context_lists); i++) {
8311 if (context_lists[i]->is_empty()) continue;
8312 Object** start = reinterpret_cast<Object**>(&context_lists[i]->first());
8313 v->VisitPointers(start, start + context_lists[i]->length());
8318 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
8319 HandleScopeData* current = isolate_->handle_scope_data();
8320 handle_scope_data_ = *current;
8325 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
8326 HandleScopeImplementer* scope_implementer =
8327 reinterpret_cast<HandleScopeImplementer*>(storage);
8328 scope_implementer->IterateThis(v);
8329 return storage + ArchiveSpacePerThread();
8333 DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) {
8334 DeferredHandles* deferred =
8335 new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
8337 while (!blocks_.is_empty()) {
8338 Object** block_start = blocks_.last();
8339 Object** block_limit = &block_start[kHandleBlockSize];
8340 // We should not need to check for SealHandleScope here. Assert this.
8341 DCHECK(prev_limit == block_limit ||
8342 !(block_start <= prev_limit && prev_limit <= block_limit));
8343 if (prev_limit == block_limit) break;
8344 deferred->blocks_.Add(blocks_.last());
8345 blocks_.RemoveLast();
8348 // deferred->blocks_ now contains the blocks installed on the
8349 // HandleScope stack since BeginDeferredScope was called, but in
8352 DCHECK(prev_limit == NULL || !blocks_.is_empty());
8354 DCHECK(!blocks_.is_empty() && prev_limit != NULL);
8355 DCHECK(last_handle_before_deferred_block_ != NULL);
8356 last_handle_before_deferred_block_ = NULL;
8361 void HandleScopeImplementer::BeginDeferredScope() {
8362 DCHECK(last_handle_before_deferred_block_ == NULL);
8363 last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
8367 DeferredHandles::~DeferredHandles() {
8368 isolate_->UnlinkDeferredHandles(this);
8370 for (int i = 0; i < blocks_.length(); i++) {
8371 #ifdef ENABLE_HANDLE_ZAPPING
8372 HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
8374 isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
8379 void DeferredHandles::Iterate(ObjectVisitor* v) {
8380 DCHECK(!blocks_.is_empty());
8382 DCHECK((first_block_limit_ >= blocks_.first()) &&
8383 (first_block_limit_ <= &(blocks_.first())[kHandleBlockSize]));
8385 v->VisitPointers(blocks_.first(), first_block_limit_);
8387 for (int i = 1; i < blocks_.length(); i++) {
8388 v->VisitPointers(blocks_[i], &blocks_[i][kHandleBlockSize]);
8393 void InvokeAccessorGetterCallback(
8394 v8::Local<v8::Name> property,
8395 const v8::PropertyCallbackInfo<v8::Value>& info,
8396 v8::AccessorNameGetterCallback getter) {
8397 // Leaving JavaScript.
8398 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8399 Address getter_address = reinterpret_cast<Address>(reinterpret_cast<intptr_t>(
8401 VMState<EXTERNAL> state(isolate);
8402 ExternalCallbackScope call_scope(isolate, getter_address);
8403 getter(property, info);
8407 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
8408 v8::FunctionCallback callback) {
8409 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8410 Address callback_address =
8411 reinterpret_cast<Address>(reinterpret_cast<intptr_t>(callback));
8412 VMState<EXTERNAL> state(isolate);
8413 ExternalCallbackScope call_scope(isolate, callback_address);
8418 } // namespace internal