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/isolate-inl.h"
39 #include "src/json-parser.h"
40 #include "src/messages.h"
41 #include "src/parser.h"
42 #include "src/pending-compilation-error-handler.h"
43 #include "src/profile-generator-inl.h"
44 #include "src/property.h"
45 #include "src/property-details.h"
46 #include "src/prototype.h"
47 #include "src/runtime/runtime.h"
48 #include "src/runtime-profiler.h"
49 #include "src/sampler.h"
50 #include "src/scanner-character-streams.h"
51 #include "src/simulator.h"
52 #include "src/snapshot/natives.h"
53 #include "src/snapshot/snapshot.h"
54 #include "src/startup-data-util.h"
55 #include "src/unicode-inl.h"
57 #include "src/v8threads.h"
58 #include "src/version.h"
59 #include "src/vm-state-inl.h"
64 #define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
67 #define ENTER_V8(isolate) i::VMState<v8::OTHER> __state__((isolate))
70 #define PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name, \
71 bailout_value, HandleScopeClass, \
73 if (IsExecutionTerminatingCheck(isolate)) { \
74 return bailout_value; \
76 HandleScopeClass handle_scope(isolate); \
77 CallDepthScope call_depth_scope(isolate, context, do_callback); \
78 LOG_API(isolate, function_name); \
80 bool has_pending_exception = false
83 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT( \
84 context, function_name, bailout_value, HandleScopeClass, do_callback) \
85 auto isolate = context.IsEmpty() \
86 ? i::Isolate::Current() \
87 : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \
88 PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name, \
89 bailout_value, HandleScopeClass, do_callback);
92 #define PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, function_name, T) \
93 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(), function_name, \
94 MaybeLocal<T>(), InternalEscapableScope, \
98 #define PREPARE_FOR_EXECUTION(context, function_name, T) \
99 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
100 InternalEscapableScope, false)
103 #define PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, function_name, T) \
104 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
105 InternalEscapableScope, true)
108 #define PREPARE_FOR_EXECUTION_PRIMITIVE(context, function_name, T) \
109 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, Nothing<T>(), \
110 i::HandleScope, false)
113 #define EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, value) \
115 if (has_pending_exception) { \
116 call_depth_scope.Escape(); \
122 #define RETURN_ON_FAILED_EXECUTION(T) \
123 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, MaybeLocal<T>())
126 #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \
127 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, Nothing<T>())
130 #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \
131 return maybe_local.FromMaybe(Local<T>());
134 #define RETURN_ESCAPED(value) return handle_scope.Escape(value);
139 Local<Context> ContextFromHeapObject(i::Handle<i::Object> obj) {
140 return reinterpret_cast<v8::Isolate*>(i::HeapObject::cast(*obj)->GetIsolate())
141 ->GetCurrentContext();
144 class InternalEscapableScope : public v8::EscapableHandleScope {
146 explicit inline InternalEscapableScope(i::Isolate* isolate)
147 : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {}
151 class CallDepthScope {
153 explicit CallDepthScope(i::Isolate* isolate, Local<Context> context,
158 do_callback_(do_callback) {
159 // TODO(dcarney): remove this when blink stops crashing.
160 DCHECK(!isolate_->external_caught_exception());
161 isolate_->handle_scope_implementer()->IncrementCallDepth();
162 if (!context_.IsEmpty()) context_->Enter();
165 if (!context_.IsEmpty()) context_->Exit();
166 if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth();
167 if (do_callback_) isolate_->FireCallCompletedCallback();
173 auto handle_scope_implementer = isolate_->handle_scope_implementer();
174 handle_scope_implementer->DecrementCallDepth();
175 bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero();
176 isolate_->OptionalRescheduleException(call_depth_is_zero);
180 i::Isolate* const isolate_;
181 Local<Context> context_;
189 static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate,
190 i::Handle<i::Script> script) {
191 i::Handle<i::Object> scriptName(i::Script::GetNameOrSourceURL(script));
192 i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate);
193 v8::Isolate* v8_isolate =
194 reinterpret_cast<v8::Isolate*>(script->GetIsolate());
195 ScriptOriginOptions options(script->origin_options());
196 v8::ScriptOrigin origin(
197 Utils::ToLocal(scriptName),
198 v8::Integer::New(v8_isolate, script->line_offset()->value()),
199 v8::Integer::New(v8_isolate, script->column_offset()->value()),
200 v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()),
201 v8::Integer::New(v8_isolate, script->id()->value()),
202 v8::Boolean::New(v8_isolate, options.IsEmbedderDebugScript()),
203 Utils::ToLocal(source_map_url),
204 v8::Boolean::New(v8_isolate, options.IsOpaque()));
209 // --- E x c e p t i o n B e h a v i o r ---
212 void i::FatalProcessOutOfMemory(const char* location) {
213 i::V8::FatalProcessOutOfMemory(location, false);
217 // When V8 cannot allocated memory FatalProcessOutOfMemory is called.
218 // The default fatal error handler is called and execution is stopped.
219 void i::V8::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
220 i::Isolate* isolate = i::Isolate::Current();
221 char last_few_messages[Heap::kTraceRingBufferSize + 1];
222 char js_stacktrace[Heap::kStacktraceBufferSize + 1];
223 memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
224 memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1);
226 i::HeapStats heap_stats;
228 heap_stats.start_marker = &start_marker;
230 heap_stats.new_space_size = &new_space_size;
231 int new_space_capacity;
232 heap_stats.new_space_capacity = &new_space_capacity;
233 intptr_t old_space_size;
234 heap_stats.old_space_size = &old_space_size;
235 intptr_t old_space_capacity;
236 heap_stats.old_space_capacity = &old_space_capacity;
237 intptr_t code_space_size;
238 heap_stats.code_space_size = &code_space_size;
239 intptr_t code_space_capacity;
240 heap_stats.code_space_capacity = &code_space_capacity;
241 intptr_t map_space_size;
242 heap_stats.map_space_size = &map_space_size;
243 intptr_t map_space_capacity;
244 heap_stats.map_space_capacity = &map_space_capacity;
245 intptr_t lo_space_size;
246 heap_stats.lo_space_size = &lo_space_size;
247 int global_handle_count;
248 heap_stats.global_handle_count = &global_handle_count;
249 int weak_global_handle_count;
250 heap_stats.weak_global_handle_count = &weak_global_handle_count;
251 int pending_global_handle_count;
252 heap_stats.pending_global_handle_count = &pending_global_handle_count;
253 int near_death_global_handle_count;
254 heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
255 int free_global_handle_count;
256 heap_stats.free_global_handle_count = &free_global_handle_count;
257 intptr_t memory_allocator_size;
258 heap_stats.memory_allocator_size = &memory_allocator_size;
259 intptr_t memory_allocator_capacity;
260 heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
261 int objects_per_type[LAST_TYPE + 1] = {0};
262 heap_stats.objects_per_type = objects_per_type;
263 int size_per_type[LAST_TYPE + 1] = {0};
264 heap_stats.size_per_type = size_per_type;
266 heap_stats.os_error = &os_error;
267 heap_stats.last_few_messages = last_few_messages;
268 heap_stats.js_stacktrace = js_stacktrace;
270 heap_stats.end_marker = &end_marker;
271 if (isolate->heap()->HasBeenSetUp()) {
272 // BUG(1718): Don't use the take_snapshot since we don't support
273 // HeapIterator here without doing a special GC.
274 isolate->heap()->RecordStats(&heap_stats, false);
275 char* first_newline = strchr(last_few_messages, '\n');
276 if (first_newline == NULL || first_newline[1] == '\0')
277 first_newline = last_few_messages;
278 PrintF("\n<--- Last few GCs --->\n%s\n", first_newline);
279 PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace);
281 Utils::ApiCheck(false, location, "Allocation failed - process out of memory");
282 // If the fatal error handler returns, we stop execution.
283 FATAL("API fatal error handler returned after process out of memory");
287 void Utils::ReportApiFailure(const char* location, const char* message) {
288 i::Isolate* isolate = i::Isolate::Current();
289 FatalErrorCallback callback = isolate->exception_behavior();
290 if (callback == NULL) {
291 base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
295 callback(location, message);
297 isolate->SignalFatalError();
301 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
302 if (isolate->has_scheduled_exception()) {
303 return isolate->scheduled_exception() ==
304 isolate->heap()->termination_exception();
310 void V8::SetNativesDataBlob(StartupData* natives_blob) {
311 i::V8::SetNativesBlob(natives_blob);
315 void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
316 i::V8::SetSnapshotBlob(snapshot_blob);
320 bool RunExtraCode(Isolate* isolate, Local<Context> context,
321 const char* utf8_source) {
322 // Run custom script if provided.
323 base::ElapsedTimer timer;
325 TryCatch try_catch(isolate);
326 Local<String> source_string;
327 if (!String::NewFromUtf8(isolate, utf8_source, NewStringType::kNormal)
328 .ToLocal(&source_string)) {
331 Local<String> resource_name =
332 String::NewFromUtf8(isolate, "<embedded script>", NewStringType::kNormal)
334 ScriptOrigin origin(resource_name);
335 ScriptCompiler::Source source(source_string, origin);
336 Local<Script> script;
337 if (!ScriptCompiler::Compile(context, &source).ToLocal(&script)) return false;
338 if (script->Run(context).IsEmpty()) return false;
339 if (i::FLAG_profile_deserialization) {
340 i::PrintF("Executing custom snapshot script took %0.3f ms\n",
341 timer.Elapsed().InMillisecondsF());
344 CHECK(!try_catch.HasCaught());
351 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
353 virtual void* Allocate(size_t length) {
354 void* data = AllocateUninitialized(length);
355 return data == NULL ? data : memset(data, 0, length);
357 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
358 virtual void Free(void* data, size_t) { free(data); }
364 StartupData V8::CreateSnapshotDataBlob(const char* custom_source) {
365 i::Isolate* internal_isolate = new i::Isolate(true);
366 ArrayBufferAllocator allocator;
367 internal_isolate->set_array_buffer_allocator(&allocator);
368 Isolate* isolate = reinterpret_cast<Isolate*>(internal_isolate);
369 StartupData result = {NULL, 0};
371 base::ElapsedTimer timer;
373 Isolate::Scope isolate_scope(isolate);
374 internal_isolate->Init(NULL);
375 Persistent<Context> context;
376 i::Snapshot::Metadata metadata;
378 HandleScope handle_scope(isolate);
379 Local<Context> new_context = Context::New(isolate);
380 context.Reset(isolate, new_context);
381 if (custom_source != NULL) {
382 metadata.set_embeds_script(true);
383 Context::Scope context_scope(new_context);
384 if (!RunExtraCode(isolate, new_context, custom_source)) context.Reset();
387 if (!context.IsEmpty()) {
388 // If we don't do this then we end up with a stray root pointing at the
389 // context even after we have disposed of the context.
390 internal_isolate->heap()->CollectAllAvailableGarbage("mksnapshot");
392 // GC may have cleared weak cells, so compact any WeakFixedArrays
393 // found on the heap.
394 i::HeapIterator iterator(internal_isolate->heap(),
395 i::HeapIterator::kFilterUnreachable);
396 for (i::HeapObject* o = iterator.next(); o != NULL; o = iterator.next()) {
397 if (o->IsPrototypeInfo()) {
398 i::Object* prototype_users =
399 i::PrototypeInfo::cast(o)->prototype_users();
400 if (prototype_users->IsWeakFixedArray()) {
401 i::WeakFixedArray* array = i::WeakFixedArray::cast(prototype_users);
402 array->Compact<i::JSObject::PrototypeRegistryCompactionCallback>();
404 } else if (o->IsScript()) {
405 i::Object* shared_list = i::Script::cast(o)->shared_function_infos();
406 if (shared_list->IsWeakFixedArray()) {
407 i::WeakFixedArray* array = i::WeakFixedArray::cast(shared_list);
408 array->Compact<i::WeakFixedArray::NullCallback>();
413 i::Object* raw_context = *v8::Utils::OpenPersistent(context);
416 i::SnapshotByteSink snapshot_sink;
417 i::StartupSerializer ser(internal_isolate, &snapshot_sink);
418 ser.SerializeStrongReferences();
420 i::SnapshotByteSink context_sink;
421 i::PartialSerializer context_ser(internal_isolate, &ser, &context_sink);
422 context_ser.Serialize(&raw_context);
423 ser.SerializeWeakReferencesAndDeferred();
425 result = i::Snapshot::CreateSnapshotBlob(ser, context_ser, metadata);
427 if (i::FLAG_profile_deserialization) {
428 i::PrintF("Creating snapshot took %0.3f ms\n",
429 timer.Elapsed().InMillisecondsF());
438 void V8::SetFlagsFromString(const char* str, int length) {
439 i::FlagList::SetFlagsFromString(str, length);
443 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
444 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
448 RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
451 RegisteredExtension::RegisteredExtension(Extension* extension)
452 : extension_(extension) { }
455 void RegisteredExtension::Register(RegisteredExtension* that) {
456 that->next_ = first_extension_;
457 first_extension_ = that;
461 void RegisteredExtension::UnregisterAll() {
462 RegisteredExtension* re = first_extension_;
464 RegisteredExtension* next = re->next();
468 first_extension_ = NULL;
472 void RegisterExtension(Extension* that) {
473 RegisteredExtension* extension = new RegisteredExtension(that);
474 RegisteredExtension::Register(extension);
478 Extension::Extension(const char* name,
484 source_length_(source_length >= 0 ?
486 (source ? static_cast<int>(strlen(source)) : 0)),
487 source_(source, source_length_),
488 dep_count_(dep_count),
490 auto_enable_(false) {
491 CHECK(source != NULL || source_length_ == 0);
495 ResourceConstraints::ResourceConstraints()
496 : max_semi_space_size_(0),
497 max_old_space_size_(0),
498 max_executable_size_(0),
500 code_range_size_(0) { }
502 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
503 uint64_t virtual_memory_limit) {
505 // Android has higher physical memory requirements before raising the maximum
506 // heap size limits since it has no swap space.
507 const uint64_t low_limit = 512ul * i::MB;
508 const uint64_t medium_limit = 1ul * i::GB;
509 const uint64_t high_limit = 2ul * i::GB;
511 const uint64_t low_limit = 512ul * i::MB;
512 const uint64_t medium_limit = 768ul * i::MB;
513 const uint64_t high_limit = 1ul * i::GB;
516 if (physical_memory <= low_limit) {
517 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeLowMemoryDevice);
518 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeLowMemoryDevice);
519 set_max_executable_size(i::Heap::kMaxExecutableSizeLowMemoryDevice);
520 } else if (physical_memory <= medium_limit) {
521 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeMediumMemoryDevice);
522 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeMediumMemoryDevice);
523 set_max_executable_size(i::Heap::kMaxExecutableSizeMediumMemoryDevice);
524 } else if (physical_memory <= high_limit) {
525 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHighMemoryDevice);
526 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHighMemoryDevice);
527 set_max_executable_size(i::Heap::kMaxExecutableSizeHighMemoryDevice);
529 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHugeMemoryDevice);
530 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHugeMemoryDevice);
531 set_max_executable_size(i::Heap::kMaxExecutableSizeHugeMemoryDevice);
534 if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
535 // Reserve no more than 1/8 of the memory for the code range, but at most
536 // kMaximalCodeRangeSize.
538 i::Min(i::kMaximalCodeRangeSize / i::MB,
539 static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
544 void SetResourceConstraints(i::Isolate* isolate,
545 const ResourceConstraints& constraints) {
546 int semi_space_size = constraints.max_semi_space_size();
547 int old_space_size = constraints.max_old_space_size();
548 int max_executable_size = constraints.max_executable_size();
549 size_t code_range_size = constraints.code_range_size();
550 if (semi_space_size != 0 || old_space_size != 0 ||
551 max_executable_size != 0 || code_range_size != 0) {
552 isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
553 max_executable_size, code_range_size);
555 if (constraints.stack_limit() != NULL) {
556 uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
557 isolate->stack_guard()->SetStackLimit(limit);
562 i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** obj) {
563 LOG_API(isolate, "Persistent::New");
564 i::Handle<i::Object> result = isolate->global_handles()->Create(*obj);
566 if (i::FLAG_verify_heap) {
567 (*obj)->ObjectVerify();
569 #endif // VERIFY_HEAP
570 return result.location();
574 i::Object** V8::CopyPersistent(i::Object** obj) {
575 i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj);
577 if (i::FLAG_verify_heap) {
578 (*obj)->ObjectVerify();
580 #endif // VERIFY_HEAP
581 return result.location();
585 void V8::MakeWeak(i::Object** object, void* parameter,
586 WeakCallback weak_callback) {
587 i::GlobalHandles::MakeWeak(object, parameter, weak_callback);
591 void V8::MakeWeak(i::Object** object, void* parameter,
592 int internal_field_index1, int internal_field_index2,
593 WeakCallbackInfo<void>::Callback weak_callback) {
594 WeakCallbackType type = WeakCallbackType::kParameter;
595 if (internal_field_index1 == 0) {
596 if (internal_field_index2 == 1) {
597 type = WeakCallbackType::kInternalFields;
599 DCHECK_EQ(internal_field_index2, -1);
600 type = WeakCallbackType::kInternalFields;
603 DCHECK_EQ(internal_field_index1, -1);
604 DCHECK_EQ(internal_field_index2, -1);
606 i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
610 void V8::MakeWeak(i::Object** object, void* parameter,
611 WeakCallbackInfo<void>::Callback weak_callback,
612 WeakCallbackType type) {
613 i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
617 void* V8::ClearWeak(i::Object** obj) {
618 return i::GlobalHandles::ClearWeakness(obj);
622 void V8::DisposeGlobal(i::Object** obj) {
623 i::GlobalHandles::Destroy(obj);
627 void V8::Eternalize(Isolate* v8_isolate, Value* value, int* index) {
628 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
629 i::Object* object = *Utils::OpenHandle(value);
630 isolate->eternal_handles()->Create(isolate, object, index);
634 Local<Value> V8::GetEternal(Isolate* v8_isolate, int index) {
635 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
636 return Utils::ToLocal(isolate->eternal_handles()->Get(index));
640 void V8::FromJustIsNothing() {
641 Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing.");
645 void V8::ToLocalEmpty() {
646 Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal.");
650 void V8::InternalFieldOutOfBounds(int index) {
651 Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback,
652 "WeakCallbackInfo::GetInternalField",
653 "Internal field out of bounds.");
657 // --- H a n d l e s ---
660 HandleScope::HandleScope(Isolate* isolate) {
665 void HandleScope::Initialize(Isolate* isolate) {
666 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
667 // We do not want to check the correct usage of the Locker class all over the
668 // place, so we do it only here: Without a HandleScope, an embedder can do
669 // almost nothing, so it is enough to check in this central place.
670 // We make an exception if the serializer is enabled, which means that the
671 // Isolate is exclusively used to create a snapshot.
673 !v8::Locker::IsActive() ||
674 internal_isolate->thread_manager()->IsLockedByCurrentThread() ||
675 internal_isolate->serializer_enabled(),
676 "HandleScope::HandleScope",
677 "Entering the V8 API without proper locking in place");
678 i::HandleScopeData* current = internal_isolate->handle_scope_data();
679 isolate_ = internal_isolate;
680 prev_next_ = current->next;
681 prev_limit_ = current->limit;
686 HandleScope::~HandleScope() {
687 i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
691 int HandleScope::NumberOfHandles(Isolate* isolate) {
692 return i::HandleScope::NumberOfHandles(
693 reinterpret_cast<i::Isolate*>(isolate));
697 i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) {
698 return i::HandleScope::CreateHandle(isolate, value);
702 i::Object** HandleScope::CreateHandle(i::HeapObject* heap_object,
704 DCHECK(heap_object->IsHeapObject());
705 return i::HandleScope::CreateHandle(heap_object->GetIsolate(), value);
709 EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
710 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
711 escape_slot_ = CreateHandle(isolate, isolate->heap()->the_hole_value());
712 Initialize(v8_isolate);
716 i::Object** EscapableHandleScope::Escape(i::Object** escape_value) {
717 i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
718 Utils::ApiCheck(*escape_slot_ == heap->the_hole_value(),
719 "EscapeableHandleScope::Escape",
720 "Escape value set twice");
721 if (escape_value == NULL) {
722 *escape_slot_ = heap->undefined_value();
725 *escape_slot_ = *escape_value;
730 SealHandleScope::SealHandleScope(Isolate* isolate) {
731 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
733 isolate_ = internal_isolate;
734 i::HandleScopeData* current = internal_isolate->handle_scope_data();
735 prev_limit_ = current->limit;
736 current->limit = current->next;
737 prev_level_ = current->level;
742 SealHandleScope::~SealHandleScope() {
743 i::HandleScopeData* current = isolate_->handle_scope_data();
744 DCHECK_EQ(0, current->level);
745 current->level = prev_level_;
746 DCHECK_EQ(current->next, current->limit);
747 current->limit = prev_limit_;
751 void Context::Enter() {
752 i::Handle<i::Context> env = Utils::OpenHandle(this);
753 i::Isolate* isolate = env->GetIsolate();
755 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
756 impl->EnterContext(env);
757 impl->SaveContext(isolate->context());
758 isolate->set_context(*env);
762 void Context::Exit() {
763 i::Handle<i::Context> env = Utils::OpenHandle(this);
764 i::Isolate* isolate = env->GetIsolate();
766 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
767 if (!Utils::ApiCheck(impl->LastEnteredContextWas(env),
768 "v8::Context::Exit()",
769 "Cannot exit non-entered context")) {
772 impl->LeaveContext();
773 isolate->set_context(impl->RestoreContext());
777 static void* DecodeSmiToAligned(i::Object* value, const char* location) {
778 Utils::ApiCheck(value->IsSmi(), location, "Not a Smi");
779 return reinterpret_cast<void*>(value);
783 static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) {
784 i::Smi* smi = reinterpret_cast<i::Smi*>(value);
785 Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned");
790 static i::Handle<i::FixedArray> EmbedderDataFor(Context* context,
793 const char* location) {
794 i::Handle<i::Context> env = Utils::OpenHandle(context);
795 i::Isolate* isolate = env->GetIsolate();
797 Utils::ApiCheck(env->IsNativeContext(),
799 "Not a native context") &&
800 Utils::ApiCheck(index >= 0, location, "Negative index");
801 if (!ok) return i::Handle<i::FixedArray>();
802 i::Handle<i::FixedArray> data(env->embedder_data());
803 if (index < data->length()) return data;
804 if (!Utils::ApiCheck(can_grow, location, "Index too large")) {
805 return i::Handle<i::FixedArray>();
807 int new_size = i::Max(index, data->length() << 1) + 1;
808 int grow_by = new_size - data->length();
809 data = isolate->factory()->CopyFixedArrayAndGrow(data, grow_by);
810 env->set_embedder_data(*data);
815 v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
816 const char* location = "v8::Context::GetEmbedderData()";
817 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
818 if (data.is_null()) return Local<Value>();
819 i::Handle<i::Object> result(data->get(index), data->GetIsolate());
820 return Utils::ToLocal(result);
824 void Context::SetEmbedderData(int index, v8::Local<Value> value) {
825 const char* location = "v8::Context::SetEmbedderData()";
826 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
827 if (data.is_null()) return;
828 i::Handle<i::Object> val = Utils::OpenHandle(*value);
829 data->set(index, *val);
830 DCHECK_EQ(*Utils::OpenHandle(*value),
831 *Utils::OpenHandle(*GetEmbedderData(index)));
835 void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
836 const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
837 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
838 if (data.is_null()) return NULL;
839 return DecodeSmiToAligned(data->get(index), location);
843 void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
844 const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
845 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
846 data->set(index, EncodeAlignedAsSmi(value, location));
847 DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
851 // --- N e a n d e r ---
854 // A constructor cannot easily return an error value, therefore it is necessary
855 // to check for a dead VM with ON_BAILOUT before constructing any Neander
856 // objects. To remind you about this there is no HandleScope in the
857 // NeanderObject constructor. When you add one to the site calling the
858 // constructor you should check that you ensured the VM was not dead first.
859 NeanderObject::NeanderObject(v8::internal::Isolate* isolate, int size) {
861 value_ = isolate->factory()->NewNeanderObject();
862 i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
863 value_->set_elements(*elements);
867 int NeanderObject::size() {
868 return i::FixedArray::cast(value_->elements())->length();
872 NeanderArray::NeanderArray(v8::internal::Isolate* isolate) : obj_(isolate, 2) {
873 obj_.set(0, i::Smi::FromInt(0));
877 int NeanderArray::length() {
878 return i::Smi::cast(obj_.get(0))->value();
882 i::Object* NeanderArray::get(int offset) {
884 DCHECK(offset < length());
885 return obj_.get(offset + 1);
889 // This method cannot easily return an error value, therefore it is necessary
890 // to check for a dead VM with ON_BAILOUT before calling it. To remind you
891 // about this there is no HandleScope in this method. When you add one to the
892 // site calling this method you should check that you ensured the VM was not
894 void NeanderArray::add(i::Isolate* isolate, i::Handle<i::Object> value) {
895 int length = this->length();
896 int size = obj_.size();
897 if (length == size - 1) {
898 i::Factory* factory = isolate->factory();
899 i::Handle<i::FixedArray> new_elms = factory->NewFixedArray(2 * size);
900 for (int i = 0; i < length; i++)
901 new_elms->set(i + 1, get(i));
902 obj_.value()->set_elements(*new_elms);
904 obj_.set(length + 1, *value);
905 obj_.set(0, i::Smi::FromInt(length + 1));
909 void NeanderArray::set(int index, i::Object* value) {
910 if (index < 0 || index >= this->length()) return;
911 obj_.set(index + 1, value);
915 // --- T e m p l a t e ---
918 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
919 that->set_number_of_properties(0);
920 that->set_tag(i::Smi::FromInt(type));
924 void Template::Set(v8::Local<Name> name, v8::Local<Data> value,
925 v8::PropertyAttribute attribute) {
926 auto templ = Utils::OpenHandle(this);
927 i::Isolate* isolate = templ->GetIsolate();
929 i::HandleScope scope(isolate);
930 // TODO(dcarney): split api to allow values of v8::Value or v8::TemplateInfo.
931 i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
932 Utils::OpenHandle(*value),
933 static_cast<PropertyAttributes>(attribute));
937 void Template::SetAccessorProperty(
938 v8::Local<v8::Name> name,
939 v8::Local<FunctionTemplate> getter,
940 v8::Local<FunctionTemplate> setter,
941 v8::PropertyAttribute attribute,
942 v8::AccessControl access_control) {
943 // TODO(verwaest): Remove |access_control|.
944 DCHECK_EQ(v8::DEFAULT, access_control);
945 auto templ = Utils::OpenHandle(this);
946 auto isolate = templ->GetIsolate();
948 DCHECK(!name.IsEmpty());
949 DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
950 i::HandleScope scope(isolate);
951 i::ApiNatives::AddAccessorProperty(
952 isolate, templ, Utils::OpenHandle(*name),
953 Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true),
954 static_cast<PropertyAttributes>(attribute));
958 // --- F u n c t i o n T e m p l a t e ---
959 static void InitializeFunctionTemplate(
960 i::Handle<i::FunctionTemplateInfo> info) {
961 InitializeTemplate(info, Consts::FUNCTION_TEMPLATE);
966 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
967 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
969 i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(),
971 if (result->IsUndefined()) {
972 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(i_isolate);
973 result = Utils::OpenHandle(*ObjectTemplate::New(isolate));
974 Utils::OpenHandle(this)->set_prototype_template(*result);
976 return ToApiHandle<ObjectTemplate>(result);
980 static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info,
982 Utils::ApiCheck(!info->instantiated(), func,
983 "FunctionTemplate already instantiated");
987 void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) {
988 auto info = Utils::OpenHandle(this);
989 EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit");
990 i::Isolate* isolate = info->GetIsolate();
992 info->set_parent_template(*Utils::OpenHandle(*value));
996 static Local<FunctionTemplate> FunctionTemplateNew(
997 i::Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
998 v8::Local<Signature> signature, int length, bool do_not_cache) {
999 i::Handle<i::Struct> struct_obj =
1000 isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
1001 i::Handle<i::FunctionTemplateInfo> obj =
1002 i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
1003 InitializeFunctionTemplate(obj);
1004 obj->set_do_not_cache(do_not_cache);
1005 int next_serial_number = 0;
1006 if (!do_not_cache) {
1007 next_serial_number = isolate->next_serial_number() + 1;
1008 isolate->set_next_serial_number(next_serial_number);
1010 obj->set_serial_number(i::Smi::FromInt(next_serial_number));
1011 if (callback != 0) {
1012 if (data.IsEmpty()) {
1013 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1015 Utils::ToLocal(obj)->SetCallHandler(callback, data);
1017 obj->set_length(length);
1018 obj->set_undetectable(false);
1019 obj->set_needs_access_check(false);
1020 obj->set_accept_any_receiver(true);
1021 if (!signature.IsEmpty())
1022 obj->set_signature(*Utils::OpenHandle(*signature));
1023 return Utils::ToLocal(obj);
1026 Local<FunctionTemplate> FunctionTemplate::New(Isolate* isolate,
1027 FunctionCallback callback,
1028 v8::Local<Value> data,
1029 v8::Local<Signature> signature,
1031 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1032 // Changes to the environment cannot be captured in the snapshot. Expect no
1033 // function templates when the isolate is created for serialization.
1034 DCHECK(!i_isolate->serializer_enabled());
1035 LOG_API(i_isolate, "FunctionTemplate::New");
1036 ENTER_V8(i_isolate);
1037 return FunctionTemplateNew(
1038 i_isolate, callback, data, signature, length, false);
1042 Local<Signature> Signature::New(Isolate* isolate,
1043 Local<FunctionTemplate> receiver) {
1044 return Utils::SignatureToLocal(Utils::OpenHandle(*receiver));
1048 Local<AccessorSignature> AccessorSignature::New(
1049 Isolate* isolate, Local<FunctionTemplate> receiver) {
1050 return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
1054 Local<TypeSwitch> TypeSwitch::New(Local<FunctionTemplate> type) {
1055 Local<FunctionTemplate> types[1] = {type};
1056 return TypeSwitch::New(1, types);
1060 Local<TypeSwitch> TypeSwitch::New(int argc, Local<FunctionTemplate> types[]) {
1061 i::Isolate* isolate = i::Isolate::Current();
1062 LOG_API(isolate, "TypeSwitch::New");
1064 i::Handle<i::FixedArray> vector = isolate->factory()->NewFixedArray(argc);
1065 for (int i = 0; i < argc; i++)
1066 vector->set(i, *Utils::OpenHandle(*types[i]));
1067 i::Handle<i::Struct> struct_obj =
1068 isolate->factory()->NewStruct(i::TYPE_SWITCH_INFO_TYPE);
1069 i::Handle<i::TypeSwitchInfo> obj =
1070 i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
1071 obj->set_types(*vector);
1072 return Utils::ToLocal(obj);
1076 int TypeSwitch::match(v8::Local<Value> value) {
1077 i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
1078 LOG_API(info->GetIsolate(), "TypeSwitch::match");
1079 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
1080 i::FixedArray* types = i::FixedArray::cast(info->types());
1081 for (int i = 0; i < types->length(); i++) {
1082 if (i::FunctionTemplateInfo::cast(types->get(i))->IsTemplateFor(*obj))
1089 #define SET_FIELD_WRAPPED(obj, setter, cdata) do { \
1090 i::Handle<i::Object> foreign = FromCData(obj->GetIsolate(), cdata); \
1091 (obj)->setter(*foreign); \
1095 void FunctionTemplate::SetCallHandler(FunctionCallback callback,
1096 v8::Local<Value> data) {
1097 auto info = Utils::OpenHandle(this);
1098 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler");
1099 i::Isolate* isolate = info->GetIsolate();
1101 i::HandleScope scope(isolate);
1102 i::Handle<i::Struct> struct_obj =
1103 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1104 i::Handle<i::CallHandlerInfo> obj =
1105 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1106 SET_FIELD_WRAPPED(obj, set_callback, callback);
1107 if (data.IsEmpty()) {
1108 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1110 obj->set_data(*Utils::OpenHandle(*data));
1111 info->set_call_code(*obj);
1115 static i::Handle<i::AccessorInfo> SetAccessorInfoProperties(
1116 i::Handle<i::AccessorInfo> obj, v8::Local<Name> name,
1117 v8::AccessControl settings, v8::PropertyAttribute attributes,
1118 v8::Local<AccessorSignature> signature) {
1119 obj->set_name(*Utils::OpenHandle(*name));
1120 if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
1121 if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
1122 obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
1123 if (!signature.IsEmpty()) {
1124 obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
1130 template <typename Getter, typename Setter>
1131 static i::Handle<i::AccessorInfo> MakeAccessorInfo(
1132 v8::Local<Name> name, Getter getter, Setter setter, v8::Local<Value> data,
1133 v8::AccessControl settings, v8::PropertyAttribute attributes,
1134 v8::Local<AccessorSignature> signature) {
1135 i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate();
1136 i::Handle<i::ExecutableAccessorInfo> obj =
1137 isolate->factory()->NewExecutableAccessorInfo();
1138 SET_FIELD_WRAPPED(obj, set_getter, getter);
1139 SET_FIELD_WRAPPED(obj, set_setter, setter);
1140 if (data.IsEmpty()) {
1141 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1143 obj->set_data(*Utils::OpenHandle(*data));
1144 return SetAccessorInfoProperties(obj, name, settings, attributes, signature);
1148 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
1149 i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
1150 if (!Utils::ApiCheck(!handle.is_null(),
1151 "v8::FunctionTemplate::InstanceTemplate()",
1152 "Reading from empty handle")) {
1153 return Local<ObjectTemplate>();
1155 i::Isolate* isolate = handle->GetIsolate();
1157 if (handle->instance_template()->IsUndefined()) {
1158 Local<ObjectTemplate> templ =
1159 ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
1160 handle->set_instance_template(*Utils::OpenHandle(*templ));
1162 i::Handle<i::ObjectTemplateInfo> result(
1163 i::ObjectTemplateInfo::cast(handle->instance_template()));
1164 return Utils::ToLocal(result);
1168 void FunctionTemplate::SetLength(int length) {
1169 auto info = Utils::OpenHandle(this);
1170 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength");
1171 auto isolate = info->GetIsolate();
1173 info->set_length(length);
1177 void FunctionTemplate::SetClassName(Local<String> name) {
1178 auto info = Utils::OpenHandle(this);
1179 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName");
1180 auto isolate = info->GetIsolate();
1182 info->set_class_name(*Utils::OpenHandle(*name));
1186 void FunctionTemplate::SetAcceptAnyReceiver(bool value) {
1187 auto info = Utils::OpenHandle(this);
1188 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
1189 auto isolate = info->GetIsolate();
1191 info->set_accept_any_receiver(value);
1195 void FunctionTemplate::SetHiddenPrototype(bool value) {
1196 auto info = Utils::OpenHandle(this);
1197 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype");
1198 auto isolate = info->GetIsolate();
1200 info->set_hidden_prototype(value);
1204 void FunctionTemplate::ReadOnlyPrototype() {
1205 auto info = Utils::OpenHandle(this);
1206 EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype");
1207 auto isolate = info->GetIsolate();
1209 info->set_read_only_prototype(true);
1213 void FunctionTemplate::RemovePrototype() {
1214 auto info = Utils::OpenHandle(this);
1215 EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype");
1216 auto isolate = info->GetIsolate();
1218 info->set_remove_prototype(true);
1222 // --- O b j e c t T e m p l a t e ---
1225 Local<ObjectTemplate> ObjectTemplate::New(
1226 Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1227 return New(reinterpret_cast<i::Isolate*>(isolate), constructor);
1231 Local<ObjectTemplate> ObjectTemplate::New() {
1232 return New(i::Isolate::Current(), Local<FunctionTemplate>());
1236 Local<ObjectTemplate> ObjectTemplate::New(
1237 i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1238 // Changes to the environment cannot be captured in the snapshot. Expect no
1239 // object templates when the isolate is created for serialization.
1240 DCHECK(!isolate->serializer_enabled());
1241 LOG_API(isolate, "ObjectTemplate::New");
1243 i::Handle<i::Struct> struct_obj =
1244 isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
1245 i::Handle<i::ObjectTemplateInfo> obj =
1246 i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
1247 InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
1248 if (!constructor.IsEmpty())
1249 obj->set_constructor(*Utils::OpenHandle(*constructor));
1250 obj->set_internal_field_count(i::Smi::FromInt(0));
1251 return Utils::ToLocal(obj);
1255 // Ensure that the object template has a constructor. If no
1256 // constructor is available we create one.
1257 static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
1258 i::Isolate* isolate,
1259 ObjectTemplate* object_template) {
1260 i::Object* obj = Utils::OpenHandle(object_template)->constructor();
1261 if (!obj ->IsUndefined()) {
1262 i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj);
1263 return i::Handle<i::FunctionTemplateInfo>(info, isolate);
1265 Local<FunctionTemplate> templ =
1266 FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
1267 i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
1268 constructor->set_instance_template(*Utils::OpenHandle(object_template));
1269 Utils::OpenHandle(object_template)->set_constructor(*constructor);
1274 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1275 i::Isolate* isolate,
1276 Template* template_obj) {
1277 return Utils::OpenHandle(template_obj);
1281 // TODO(dcarney): remove this with ObjectTemplate::SetAccessor
1282 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1283 i::Isolate* isolate,
1284 ObjectTemplate* object_template) {
1285 EnsureConstructor(isolate, object_template);
1286 return Utils::OpenHandle(object_template);
1290 template<typename Getter, typename Setter, typename Data, typename Template>
1291 static bool TemplateSetAccessor(
1292 Template* template_obj,
1293 v8::Local<Name> name,
1297 AccessControl settings,
1298 PropertyAttribute attribute,
1299 v8::Local<AccessorSignature> signature) {
1300 auto isolate = Utils::OpenHandle(template_obj)->GetIsolate();
1302 i::HandleScope scope(isolate);
1303 auto obj = MakeAccessorInfo(name, getter, setter, data, settings, attribute,
1305 if (obj.is_null()) return false;
1306 auto info = GetTemplateInfo(isolate, template_obj);
1307 i::ApiNatives::AddNativeDataProperty(isolate, info, obj);
1312 void Template::SetNativeDataProperty(v8::Local<String> name,
1313 AccessorGetterCallback getter,
1314 AccessorSetterCallback setter,
1315 v8::Local<Value> data,
1316 PropertyAttribute attribute,
1317 v8::Local<AccessorSignature> signature,
1318 AccessControl settings) {
1319 TemplateSetAccessor(
1320 this, name, getter, setter, data, settings, attribute, signature);
1324 void Template::SetNativeDataProperty(v8::Local<Name> name,
1325 AccessorNameGetterCallback getter,
1326 AccessorNameSetterCallback setter,
1327 v8::Local<Value> data,
1328 PropertyAttribute attribute,
1329 v8::Local<AccessorSignature> signature,
1330 AccessControl settings) {
1331 TemplateSetAccessor(
1332 this, name, getter, setter, data, settings, attribute, signature);
1336 void ObjectTemplate::SetAccessor(v8::Local<String> name,
1337 AccessorGetterCallback getter,
1338 AccessorSetterCallback setter,
1339 v8::Local<Value> data, AccessControl settings,
1340 PropertyAttribute attribute,
1341 v8::Local<AccessorSignature> signature) {
1342 TemplateSetAccessor(
1343 this, name, getter, setter, data, settings, attribute, signature);
1347 void ObjectTemplate::SetAccessor(v8::Local<Name> name,
1348 AccessorNameGetterCallback getter,
1349 AccessorNameSetterCallback setter,
1350 v8::Local<Value> data, AccessControl settings,
1351 PropertyAttribute attribute,
1352 v8::Local<AccessorSignature> signature) {
1353 TemplateSetAccessor(
1354 this, name, getter, setter, data, settings, attribute, signature);
1358 template <typename Getter, typename Setter, typename Query, typename Deleter,
1359 typename Enumerator>
1360 static void ObjectTemplateSetNamedPropertyHandler(ObjectTemplate* templ,
1361 Getter getter, Setter setter,
1362 Query query, Deleter remover,
1363 Enumerator enumerator,
1365 PropertyHandlerFlags flags) {
1366 i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate();
1368 i::HandleScope scope(isolate);
1369 auto cons = EnsureConstructor(isolate, templ);
1370 EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler");
1371 auto obj = i::Handle<i::InterceptorInfo>::cast(
1372 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1374 if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1375 if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1376 if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1377 if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1378 if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1380 obj->set_can_intercept_symbols(
1381 !(static_cast<int>(flags) &
1382 static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings)));
1383 obj->set_all_can_read(static_cast<int>(flags) &
1384 static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1385 obj->set_non_masking(static_cast<int>(flags) &
1386 static_cast<int>(PropertyHandlerFlags::kNonMasking));
1388 if (data.IsEmpty()) {
1389 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1391 obj->set_data(*Utils::OpenHandle(*data));
1392 cons->set_named_property_handler(*obj);
1396 void ObjectTemplate::SetNamedPropertyHandler(
1397 NamedPropertyGetterCallback getter, NamedPropertySetterCallback setter,
1398 NamedPropertyQueryCallback query, NamedPropertyDeleterCallback remover,
1399 NamedPropertyEnumeratorCallback enumerator, Local<Value> data) {
1400 ObjectTemplateSetNamedPropertyHandler(
1401 this, getter, setter, query, remover, enumerator, data,
1402 PropertyHandlerFlags::kOnlyInterceptStrings);
1406 void ObjectTemplate::SetHandler(
1407 const NamedPropertyHandlerConfiguration& config) {
1408 ObjectTemplateSetNamedPropertyHandler(
1409 this, config.getter, config.setter, config.query, config.deleter,
1410 config.enumerator, config.data, config.flags);
1414 void ObjectTemplate::MarkAsUndetectable() {
1415 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1417 i::HandleScope scope(isolate);
1418 auto cons = EnsureConstructor(isolate, this);
1419 EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable");
1420 cons->set_undetectable(true);
1424 void ObjectTemplate::SetAccessCheckCallbacks(
1425 NamedSecurityCallback named_callback,
1426 IndexedSecurityCallback indexed_callback, Local<Value> data) {
1427 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1429 i::HandleScope scope(isolate);
1430 auto cons = EnsureConstructor(isolate, this);
1431 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallbacks");
1433 i::Handle<i::Struct> struct_info =
1434 isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE);
1435 i::Handle<i::AccessCheckInfo> info =
1436 i::Handle<i::AccessCheckInfo>::cast(struct_info);
1438 SET_FIELD_WRAPPED(info, set_named_callback, named_callback);
1439 SET_FIELD_WRAPPED(info, set_indexed_callback, indexed_callback);
1441 if (data.IsEmpty()) {
1442 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1444 info->set_data(*Utils::OpenHandle(*data));
1446 cons->set_access_check_info(*info);
1447 cons->set_needs_access_check(true);
1451 void ObjectTemplate::SetHandler(
1452 const IndexedPropertyHandlerConfiguration& config) {
1453 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1455 i::HandleScope scope(isolate);
1456 auto cons = EnsureConstructor(isolate, this);
1457 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler");
1458 auto obj = i::Handle<i::InterceptorInfo>::cast(
1459 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1461 if (config.getter != 0) SET_FIELD_WRAPPED(obj, set_getter, config.getter);
1462 if (config.setter != 0) SET_FIELD_WRAPPED(obj, set_setter, config.setter);
1463 if (config.query != 0) SET_FIELD_WRAPPED(obj, set_query, config.query);
1464 if (config.deleter != 0) SET_FIELD_WRAPPED(obj, set_deleter, config.deleter);
1465 if (config.enumerator != 0) {
1466 SET_FIELD_WRAPPED(obj, set_enumerator, config.enumerator);
1469 obj->set_all_can_read(static_cast<int>(config.flags) &
1470 static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1472 v8::Local<v8::Value> data = config.data;
1473 if (data.IsEmpty()) {
1474 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1476 obj->set_data(*Utils::OpenHandle(*data));
1477 cons->set_indexed_property_handler(*obj);
1481 void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
1482 Local<Value> data) {
1483 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1485 i::HandleScope scope(isolate);
1486 auto cons = EnsureConstructor(isolate, this);
1487 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
1488 i::Handle<i::Struct> struct_obj =
1489 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1490 i::Handle<i::CallHandlerInfo> obj =
1491 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1492 SET_FIELD_WRAPPED(obj, set_callback, callback);
1493 if (data.IsEmpty()) {
1494 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1496 obj->set_data(*Utils::OpenHandle(*data));
1497 cons->set_instance_call_handler(*obj);
1501 int ObjectTemplate::InternalFieldCount() {
1502 return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
1506 void ObjectTemplate::SetInternalFieldCount(int value) {
1507 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1508 if (!Utils::ApiCheck(i::Smi::IsValid(value),
1509 "v8::ObjectTemplate::SetInternalFieldCount()",
1510 "Invalid internal field count")) {
1515 // The internal field count is set by the constructor function's
1516 // construct code, so we ensure that there is a constructor
1517 // function to do the setting.
1518 EnsureConstructor(isolate, this);
1520 Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
1524 // --- S c r i p t s ---
1527 // Internally, UnboundScript is a SharedFunctionInfo, and Script is a
1530 ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
1531 BufferPolicy buffer_policy_)
1535 buffer_policy(buffer_policy_) {}
1538 ScriptCompiler::CachedData::~CachedData() {
1539 if (buffer_policy == BufferOwned) {
1545 bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; }
1548 void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); }
1551 ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
1553 : impl_(new i::StreamedSource(stream, encoding)) {}
1556 ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; }
1559 const ScriptCompiler::CachedData*
1560 ScriptCompiler::StreamedSource::GetCachedData() const {
1561 return impl_->cached_data.get();
1565 Local<Script> UnboundScript::BindToCurrentContext() {
1566 i::Handle<i::HeapObject> obj =
1567 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1568 i::Handle<i::SharedFunctionInfo>
1569 function_info(i::SharedFunctionInfo::cast(*obj), obj->GetIsolate());
1570 i::Isolate* isolate = obj->GetIsolate();
1572 i::ScopeInfo* scope_info = function_info->scope_info();
1573 i::Handle<i::JSReceiver> global(isolate->native_context()->global_object());
1574 for (int i = 0; i < scope_info->StrongModeFreeVariableCount(); ++i) {
1575 i::Handle<i::String> name_string(scope_info->StrongModeFreeVariableName(i));
1576 i::ScriptContextTable::LookupResult result;
1577 i::Handle<i::ScriptContextTable> script_context_table(
1578 isolate->native_context()->script_context_table());
1579 if (!i::ScriptContextTable::Lookup(script_context_table, name_string,
1581 i::Handle<i::Name> name(scope_info->StrongModeFreeVariableName(i));
1582 Maybe<bool> has = i::JSReceiver::HasProperty(global, name);
1583 if (has.IsJust() && !has.FromJust()) {
1584 i::PendingCompilationErrorHandler pending_error_handler_;
1585 pending_error_handler_.ReportMessageAt(
1586 scope_info->StrongModeFreeVariableStartPosition(i),
1587 scope_info->StrongModeFreeVariableEndPosition(i),
1588 i::MessageTemplate::kStrongUnboundGlobal, name_string,
1589 i::kReferenceError);
1590 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1591 pending_error_handler_.ThrowPendingError(isolate, script);
1592 isolate->ReportPendingMessages();
1593 isolate->OptionalRescheduleException(true);
1594 return Local<Script>();
1598 i::Handle<i::JSFunction> function =
1599 obj->GetIsolate()->factory()->NewFunctionFromSharedFunctionInfo(
1600 function_info, isolate->native_context());
1601 return ToApiHandle<Script>(function);
1605 int UnboundScript::GetId() {
1606 i::Handle<i::HeapObject> obj =
1607 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1608 i::Isolate* isolate = obj->GetIsolate();
1609 LOG_API(isolate, "v8::UnboundScript::GetId");
1610 i::HandleScope scope(isolate);
1611 i::Handle<i::SharedFunctionInfo> function_info(
1612 i::SharedFunctionInfo::cast(*obj));
1613 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1614 return script->id()->value();
1618 int UnboundScript::GetLineNumber(int code_pos) {
1619 i::Handle<i::SharedFunctionInfo> obj =
1620 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1621 i::Isolate* isolate = obj->GetIsolate();
1622 LOG_API(isolate, "UnboundScript::GetLineNumber");
1623 if (obj->script()->IsScript()) {
1624 i::Handle<i::Script> script(i::Script::cast(obj->script()));
1625 return i::Script::GetLineNumber(script, code_pos);
1632 Local<Value> UnboundScript::GetScriptName() {
1633 i::Handle<i::SharedFunctionInfo> obj =
1634 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1635 i::Isolate* isolate = obj->GetIsolate();
1636 LOG_API(isolate, "UnboundScript::GetName");
1637 if (obj->script()->IsScript()) {
1638 i::Object* name = i::Script::cast(obj->script())->name();
1639 return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
1641 return Local<String>();
1646 Local<Value> UnboundScript::GetSourceURL() {
1647 i::Handle<i::SharedFunctionInfo> obj =
1648 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1649 i::Isolate* isolate = obj->GetIsolate();
1650 LOG_API(isolate, "UnboundScript::GetSourceURL");
1651 if (obj->script()->IsScript()) {
1652 i::Object* url = i::Script::cast(obj->script())->source_url();
1653 return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1655 return Local<String>();
1660 Local<Value> UnboundScript::GetSourceMappingURL() {
1661 i::Handle<i::SharedFunctionInfo> obj =
1662 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1663 i::Isolate* isolate = obj->GetIsolate();
1664 LOG_API(isolate, "UnboundScript::GetSourceMappingURL");
1665 if (obj->script()->IsScript()) {
1666 i::Object* url = i::Script::cast(obj->script())->source_mapping_url();
1667 return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1669 return Local<String>();
1674 MaybeLocal<Value> Script::Run(Local<Context> context) {
1675 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Script::Run()", Value)
1676 i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
1677 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
1678 auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this));
1679 i::Handle<i::Object> receiver(isolate->global_proxy(), isolate);
1680 Local<Value> result;
1681 has_pending_exception =
1682 !ToLocal<Value>(i::Execution::Call(isolate, fun, receiver, 0, NULL),
1684 RETURN_ON_FAILED_EXECUTION(Value);
1685 RETURN_ESCAPED(result);
1689 Local<Value> Script::Run() {
1690 auto self = Utils::OpenHandle(this, true);
1691 // If execution is terminating, Compile(..)->Run() requires this
1693 if (self.is_null()) return Local<Value>();
1694 auto context = ContextFromHeapObject(self);
1695 RETURN_TO_LOCAL_UNCHECKED(Run(context), Value);
1699 Local<UnboundScript> Script::GetUnboundScript() {
1700 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1701 return ToApiHandle<UnboundScript>(
1702 i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared()));
1706 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal(
1707 Isolate* v8_isolate, Source* source, CompileOptions options,
1709 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1710 PREPARE_FOR_EXECUTION_WITH_ISOLATE(
1711 isolate, "v8::ScriptCompiler::CompileUnbound()", UnboundScript);
1713 // Don't try to produce any kind of cache when the debugger is loaded.
1714 if (isolate->debug()->is_loaded() &&
1715 (options == kProduceParserCache || options == kProduceCodeCache)) {
1716 options = kNoCompileOptions;
1719 i::ScriptData* script_data = NULL;
1720 if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1721 DCHECK(source->cached_data);
1722 // ScriptData takes care of pointer-aligning the data.
1723 script_data = new i::ScriptData(source->cached_data->data,
1724 source->cached_data->length);
1727 i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
1728 i::Handle<i::SharedFunctionInfo> result;
1730 i::HistogramTimerScope total(isolate->counters()->compile_script(), true);
1731 i::Handle<i::Object> name_obj;
1732 i::Handle<i::Object> source_map_url;
1733 int line_offset = 0;
1734 int column_offset = 0;
1735 if (!source->resource_name.IsEmpty()) {
1736 name_obj = Utils::OpenHandle(*(source->resource_name));
1738 if (!source->resource_line_offset.IsEmpty()) {
1739 line_offset = static_cast<int>(source->resource_line_offset->Value());
1741 if (!source->resource_column_offset.IsEmpty()) {
1743 static_cast<int>(source->resource_column_offset->Value());
1745 if (!source->source_map_url.IsEmpty()) {
1746 source_map_url = Utils::OpenHandle(*(source->source_map_url));
1748 result = i::Compiler::CompileScript(
1749 str, name_obj, line_offset, column_offset, source->resource_options,
1750 source_map_url, isolate->native_context(), NULL, &script_data, options,
1751 i::NOT_NATIVES_CODE, is_module);
1752 has_pending_exception = result.is_null();
1753 if (has_pending_exception && script_data != NULL) {
1754 // This case won't happen during normal operation; we have compiled
1755 // successfully and produced cached data, and but the second compilation
1756 // of the same source code fails.
1760 RETURN_ON_FAILED_EXECUTION(UnboundScript);
1762 if ((options == kProduceParserCache || options == kProduceCodeCache) &&
1763 script_data != NULL) {
1764 // script_data now contains the data that was generated. source will
1765 // take the ownership.
1766 source->cached_data = new CachedData(
1767 script_data->data(), script_data->length(), CachedData::BufferOwned);
1768 script_data->ReleaseDataOwnership();
1769 } else if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1770 source->cached_data->rejected = script_data->rejected();
1774 RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
1778 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript(
1779 Isolate* v8_isolate, Source* source, CompileOptions options) {
1780 return CompileUnboundInternal(v8_isolate, source, options, false);
1784 Local<UnboundScript> ScriptCompiler::CompileUnbound(Isolate* v8_isolate,
1786 CompileOptions options) {
1787 RETURN_TO_LOCAL_UNCHECKED(
1788 CompileUnboundInternal(v8_isolate, source, options, false),
1793 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1795 CompileOptions options) {
1796 auto isolate = context->GetIsolate();
1797 auto maybe = CompileUnboundInternal(isolate, source, options, false);
1798 Local<UnboundScript> result;
1799 if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
1800 v8::Context::Scope scope(context);
1801 return result->BindToCurrentContext();
1805 Local<Script> ScriptCompiler::Compile(
1806 Isolate* v8_isolate,
1808 CompileOptions options) {
1809 auto context = v8_isolate->GetCurrentContext();
1810 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, options), Script);
1814 MaybeLocal<Script> ScriptCompiler::CompileModule(Local<Context> context,
1816 CompileOptions options) {
1817 CHECK(i::FLAG_harmony_modules);
1818 auto isolate = context->GetIsolate();
1819 auto maybe = CompileUnboundInternal(isolate, source, options, true);
1820 Local<UnboundScript> generic;
1821 if (!maybe.ToLocal(&generic)) return MaybeLocal<Script>();
1822 v8::Context::Scope scope(context);
1823 return generic->BindToCurrentContext();
1827 class IsIdentifierHelper {
1829 IsIdentifierHelper() : is_identifier_(false), first_char_(true) {}
1831 bool Check(i::String* string) {
1832 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
1833 if (cons_string == NULL) return is_identifier_;
1834 // We don't support cons strings here.
1837 void VisitOneByteString(const uint8_t* chars, int length) {
1838 for (int i = 0; i < length; ++i) {
1840 first_char_ = false;
1841 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1843 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1847 void VisitTwoByteString(const uint16_t* chars, int length) {
1848 for (int i = 0; i < length; ++i) {
1850 first_char_ = false;
1851 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1853 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1859 bool is_identifier_;
1861 i::UnicodeCache unicode_cache_;
1862 DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper);
1866 MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext(
1867 Local<Context> v8_context, Source* source, size_t arguments_count,
1868 Local<String> arguments[], size_t context_extension_count,
1869 Local<Object> context_extensions[]) {
1870 PREPARE_FOR_EXECUTION(
1871 v8_context, "v8::ScriptCompiler::CompileFunctionInContext()", Function);
1872 i::Handle<i::String> source_string;
1873 auto factory = isolate->factory();
1874 if (arguments_count) {
1875 source_string = factory->NewStringFromStaticChars("(function(");
1876 for (size_t i = 0; i < arguments_count; ++i) {
1877 IsIdentifierHelper helper;
1878 if (!helper.Check(*Utils::OpenHandle(*arguments[i]))) {
1879 return Local<Function>();
1881 has_pending_exception =
1882 !factory->NewConsString(source_string,
1883 Utils::OpenHandle(*arguments[i]))
1884 .ToHandle(&source_string);
1885 RETURN_ON_FAILED_EXECUTION(Function);
1886 if (i + 1 == arguments_count) continue;
1887 has_pending_exception =
1888 !factory->NewConsString(source_string,
1889 factory->LookupSingleCharacterStringFromCode(
1890 ',')).ToHandle(&source_string);
1891 RETURN_ON_FAILED_EXECUTION(Function);
1893 auto brackets = factory->NewStringFromStaticChars("){");
1894 has_pending_exception = !factory->NewConsString(source_string, brackets)
1895 .ToHandle(&source_string);
1896 RETURN_ON_FAILED_EXECUTION(Function);
1898 source_string = factory->NewStringFromStaticChars("(function(){");
1901 int scope_position = source_string->length();
1902 has_pending_exception =
1903 !factory->NewConsString(source_string,
1904 Utils::OpenHandle(*source->source_string))
1905 .ToHandle(&source_string);
1906 RETURN_ON_FAILED_EXECUTION(Function);
1907 // Include \n in case the source contains a line end comment.
1908 auto brackets = factory->NewStringFromStaticChars("\n})");
1909 has_pending_exception =
1910 !factory->NewConsString(source_string, brackets).ToHandle(&source_string);
1911 RETURN_ON_FAILED_EXECUTION(Function);
1913 i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
1914 i::Handle<i::SharedFunctionInfo> outer_info(context->closure()->shared(),
1916 for (size_t i = 0; i < context_extension_count; ++i) {
1917 i::Handle<i::JSObject> extension =
1918 Utils::OpenHandle(*context_extensions[i]);
1919 i::Handle<i::JSFunction> closure(context->closure(), isolate);
1920 context = factory->NewWithContext(closure, context, extension);
1923 i::Handle<i::Object> name_obj;
1924 int line_offset = 0;
1925 int column_offset = 0;
1926 if (!source->resource_name.IsEmpty()) {
1927 name_obj = Utils::OpenHandle(*(source->resource_name));
1929 if (!source->resource_line_offset.IsEmpty()) {
1930 line_offset = static_cast<int>(source->resource_line_offset->Value());
1932 if (!source->resource_column_offset.IsEmpty()) {
1933 column_offset = static_cast<int>(source->resource_column_offset->Value());
1935 i::Handle<i::JSFunction> fun;
1936 has_pending_exception = !i::Compiler::GetFunctionFromEval(
1937 source_string, outer_info, context, i::SLOPPY,
1938 i::ONLY_SINGLE_FUNCTION_LITERAL, line_offset,
1939 column_offset - scope_position, name_obj,
1940 source->resource_options).ToHandle(&fun);
1941 if (has_pending_exception) {
1942 isolate->ReportPendingMessages();
1944 RETURN_ON_FAILED_EXECUTION(Function);
1946 i::Handle<i::Object> result;
1947 has_pending_exception =
1948 !i::Execution::Call(isolate, fun,
1949 Utils::OpenHandle(*v8_context->Global()), 0,
1950 nullptr).ToHandle(&result);
1951 RETURN_ON_FAILED_EXECUTION(Function);
1952 RETURN_ESCAPED(Utils::ToLocal(i::Handle<i::JSFunction>::cast(result)));
1956 Local<Function> ScriptCompiler::CompileFunctionInContext(
1957 Isolate* v8_isolate, Source* source, Local<Context> v8_context,
1958 size_t arguments_count, Local<String> arguments[],
1959 size_t context_extension_count, Local<Object> context_extensions[]) {
1960 RETURN_TO_LOCAL_UNCHECKED(
1961 CompileFunctionInContext(v8_context, source, arguments_count, arguments,
1962 context_extension_count, context_extensions),
1967 ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript(
1968 Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
1969 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1970 return new i::BackgroundParsingTask(source->impl(), options,
1971 i::FLAG_stack_size, isolate);
1975 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1976 StreamedSource* v8_source,
1977 Local<String> full_source_string,
1978 const ScriptOrigin& origin) {
1979 PREPARE_FOR_EXECUTION(context, "v8::ScriptCompiler::Compile()", Script);
1980 i::StreamedSource* source = v8_source->impl();
1981 i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
1982 i::Handle<i::Script> script = isolate->factory()->NewScript(str);
1983 if (!origin.ResourceName().IsEmpty()) {
1984 script->set_name(*Utils::OpenHandle(*(origin.ResourceName())));
1986 if (!origin.ResourceLineOffset().IsEmpty()) {
1987 script->set_line_offset(i::Smi::FromInt(
1988 static_cast<int>(origin.ResourceLineOffset()->Value())));
1990 if (!origin.ResourceColumnOffset().IsEmpty()) {
1991 script->set_column_offset(i::Smi::FromInt(
1992 static_cast<int>(origin.ResourceColumnOffset()->Value())));
1994 script->set_origin_options(origin.Options());
1995 if (!origin.SourceMapUrl().IsEmpty()) {
1996 script->set_source_mapping_url(
1997 *Utils::OpenHandle(*(origin.SourceMapUrl())));
2000 source->info->set_script(script);
2001 source->info->set_context(isolate->native_context());
2003 // Do the parsing tasks which need to be done on the main thread. This will
2004 // also handle parse errors.
2005 source->parser->Internalize(isolate, script,
2006 source->info->literal() == nullptr);
2007 source->parser->HandleSourceURLComments(isolate, script);
2009 i::Handle<i::SharedFunctionInfo> result;
2010 if (source->info->literal() != nullptr) {
2011 // Parsing has succeeded.
2012 result = i::Compiler::CompileStreamedScript(script, source->info.get(),
2015 has_pending_exception = result.is_null();
2016 if (has_pending_exception) isolate->ReportPendingMessages();
2017 RETURN_ON_FAILED_EXECUTION(Script);
2019 source->info->clear_script(); // because script goes out of scope.
2021 Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
2022 if (generic.IsEmpty()) return Local<Script>();
2023 Local<Script> bound = generic->BindToCurrentContext();
2024 if (bound.IsEmpty()) return Local<Script>();
2025 RETURN_ESCAPED(bound);
2029 Local<Script> ScriptCompiler::Compile(Isolate* v8_isolate,
2030 StreamedSource* v8_source,
2031 Local<String> full_source_string,
2032 const ScriptOrigin& origin) {
2033 auto context = v8_isolate->GetCurrentContext();
2034 RETURN_TO_LOCAL_UNCHECKED(
2035 Compile(context, v8_source, full_source_string, origin), Script);
2039 uint32_t ScriptCompiler::CachedDataVersionTag() {
2040 return static_cast<uint32_t>(base::hash_combine(
2041 internal::Version::Hash(), internal::FlagList::Hash(),
2042 static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures())));
2046 MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source,
2047 ScriptOrigin* origin) {
2049 ScriptCompiler::Source script_source(source, *origin);
2050 return ScriptCompiler::Compile(context, &script_source);
2052 ScriptCompiler::Source script_source(source);
2053 return ScriptCompiler::Compile(context, &script_source);
2057 Local<Script> Script::Compile(v8::Local<String> source,
2058 v8::ScriptOrigin* origin) {
2059 auto str = Utils::OpenHandle(*source);
2060 auto context = ContextFromHeapObject(str);
2061 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, origin), Script);
2065 Local<Script> Script::Compile(v8::Local<String> source,
2066 v8::Local<String> file_name) {
2067 auto str = Utils::OpenHandle(*source);
2068 auto context = ContextFromHeapObject(str);
2069 ScriptOrigin origin(file_name);
2070 return Compile(context, source, &origin).FromMaybe(Local<Script>());
2074 // --- E x c e p t i o n s ---
2077 v8::TryCatch::TryCatch()
2078 : isolate_(i::Isolate::Current()),
2079 next_(isolate_->try_catch_handler()),
2081 can_continue_(true),
2082 capture_message_(true),
2084 has_terminated_(false) {
2086 // Special handling for simulators which have a separate JS stack.
2087 js_stack_comparable_address_ =
2088 reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2089 v8::internal::GetCurrentStackPosition()));
2090 isolate_->RegisterTryCatchHandler(this);
2094 v8::TryCatch::TryCatch(v8::Isolate* isolate)
2095 : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
2096 next_(isolate_->try_catch_handler()),
2098 can_continue_(true),
2099 capture_message_(true),
2101 has_terminated_(false) {
2103 // Special handling for simulators which have a separate JS stack.
2104 js_stack_comparable_address_ =
2105 reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2106 v8::internal::GetCurrentStackPosition()));
2107 isolate_->RegisterTryCatchHandler(this);
2111 v8::TryCatch::~TryCatch() {
2113 v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
2114 v8::HandleScope scope(isolate);
2115 v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
2116 if (HasCaught() && capture_message_) {
2117 // If an exception was caught and rethrow_ is indicated, the saved
2118 // message, script, and location need to be restored to Isolate TLS
2119 // for reuse. capture_message_ needs to be disabled so that Throw()
2120 // does not create a new message.
2121 isolate_->thread_local_top()->rethrowing_message_ = true;
2122 isolate_->RestorePendingMessageFromTryCatch(this);
2124 isolate_->UnregisterTryCatchHandler(this);
2125 v8::internal::SimulatorStack::UnregisterCTryCatch();
2126 reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
2127 DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
2129 if (HasCaught() && isolate_->has_scheduled_exception()) {
2130 // If an exception was caught but is still scheduled because no API call
2131 // promoted it, then it is canceled to prevent it from being propagated.
2132 // Note that this will not cancel termination exceptions.
2133 isolate_->CancelScheduledExceptionFromTryCatch(this);
2135 isolate_->UnregisterTryCatchHandler(this);
2136 v8::internal::SimulatorStack::UnregisterCTryCatch();
2141 bool v8::TryCatch::HasCaught() const {
2142 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
2146 bool v8::TryCatch::CanContinue() const {
2147 return can_continue_;
2151 bool v8::TryCatch::HasTerminated() const {
2152 return has_terminated_;
2156 v8::Local<v8::Value> v8::TryCatch::ReThrow() {
2157 if (!HasCaught()) return v8::Local<v8::Value>();
2159 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
2163 v8::Local<Value> v8::TryCatch::Exception() const {
2165 // Check for out of memory exception.
2166 i::Object* exception = reinterpret_cast<i::Object*>(exception_);
2167 return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
2169 return v8::Local<Value>();
2174 MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const {
2175 if (!HasCaught()) return v8::Local<Value>();
2176 i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
2177 if (!raw_obj->IsJSObject()) return v8::Local<Value>();
2178 PREPARE_FOR_EXECUTION(context, "v8::TryCatch::StackTrace", Value);
2179 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
2180 i::Handle<i::String> name = isolate->factory()->stack_string();
2181 Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
2182 has_pending_exception = !maybe.IsJust();
2183 RETURN_ON_FAILED_EXECUTION(Value);
2184 if (!maybe.FromJust()) return v8::Local<Value>();
2185 Local<Value> result;
2186 has_pending_exception =
2187 !ToLocal<Value>(i::Object::GetProperty(obj, name), &result);
2188 RETURN_ON_FAILED_EXECUTION(Value);
2189 RETURN_ESCAPED(result);
2193 v8::Local<Value> v8::TryCatch::StackTrace() const {
2194 auto context = reinterpret_cast<v8::Isolate*>(isolate_)->GetCurrentContext();
2195 RETURN_TO_LOCAL_UNCHECKED(StackTrace(context), Value);
2199 v8::Local<v8::Message> v8::TryCatch::Message() const {
2200 i::Object* message = reinterpret_cast<i::Object*>(message_obj_);
2201 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
2202 if (HasCaught() && !message->IsTheHole()) {
2203 return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
2205 return v8::Local<v8::Message>();
2210 void v8::TryCatch::Reset() {
2211 if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
2212 // If an exception was caught but is still scheduled because no API call
2213 // promoted it, then it is canceled to prevent it from being propagated.
2214 // Note that this will not cancel termination exceptions.
2215 isolate_->CancelScheduledExceptionFromTryCatch(this);
2221 void v8::TryCatch::ResetInternal() {
2222 i::Object* the_hole = isolate_->heap()->the_hole_value();
2223 exception_ = the_hole;
2224 message_obj_ = the_hole;
2228 void v8::TryCatch::SetVerbose(bool value) {
2229 is_verbose_ = value;
2233 void v8::TryCatch::SetCaptureMessage(bool value) {
2234 capture_message_ = value;
2238 // --- M e s s a g e ---
2241 Local<String> Message::Get() const {
2242 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2244 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2245 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2246 i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
2247 Local<String> result = Utils::ToLocal(raw_result);
2248 return scope.Escape(result);
2252 ScriptOrigin Message::GetScriptOrigin() const {
2253 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2254 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2255 auto script_wraper = i::Handle<i::Object>(message->script(), isolate);
2256 auto script_value = i::Handle<i::JSValue>::cast(script_wraper);
2257 i::Handle<i::Script> script(i::Script::cast(script_value->value()));
2258 return GetScriptOriginForScript(isolate, script);
2262 v8::Local<Value> Message::GetScriptResourceName() const {
2263 return GetScriptOrigin().ResourceName();
2267 v8::Local<v8::StackTrace> Message::GetStackTrace() const {
2268 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2270 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2271 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2272 i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
2273 if (!stackFramesObj->IsJSArray()) return v8::Local<v8::StackTrace>();
2274 auto stackTrace = i::Handle<i::JSArray>::cast(stackFramesObj);
2275 return scope.Escape(Utils::StackTraceToLocal(stackTrace));
2279 Maybe<int> Message::GetLineNumber(Local<Context> context) const {
2280 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetLineNumber()", int);
2281 i::Handle<i::JSFunction> fun = isolate->message_get_line_number();
2282 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2283 i::Handle<i::Object> args[] = {Utils::OpenHandle(this)};
2284 i::Handle<i::Object> result;
2285 has_pending_exception =
2286 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2288 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2289 return Just(static_cast<int>(result->Number()));
2293 int Message::GetLineNumber() const {
2294 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2295 return GetLineNumber(context).FromMaybe(0);
2299 int Message::GetStartPosition() const {
2300 auto self = Utils::OpenHandle(this);
2301 return self->start_position();
2305 int Message::GetEndPosition() const {
2306 auto self = Utils::OpenHandle(this);
2307 return self->end_position();
2311 Maybe<int> Message::GetStartColumn(Local<Context> context) const {
2312 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetStartColumn()",
2314 i::Handle<i::JSFunction> fun = isolate->message_get_column_number();
2315 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2316 i::Handle<i::Object> args[] = {Utils::OpenHandle(this)};
2317 i::Handle<i::Object> result;
2318 has_pending_exception =
2319 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2321 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2322 return Just(static_cast<int>(result->Number()));
2326 int Message::GetStartColumn() const {
2327 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2328 const int default_value = kNoColumnInfo;
2329 return GetStartColumn(context).FromMaybe(default_value);
2333 Maybe<int> Message::GetEndColumn(Local<Context> context) const {
2334 auto self = Utils::OpenHandle(this);
2335 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetEndColumn()", int);
2336 i::Handle<i::JSFunction> fun = isolate->message_get_column_number();
2337 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2338 i::Handle<i::Object> args[] = {self};
2339 i::Handle<i::Object> result;
2340 has_pending_exception =
2341 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2343 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2344 int start = self->start_position();
2345 int end = self->end_position();
2346 return Just(static_cast<int>(result->Number()) + (end - start));
2350 int Message::GetEndColumn() const {
2351 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2352 const int default_value = kNoColumnInfo;
2353 return GetEndColumn(context).FromMaybe(default_value);
2357 bool Message::IsSharedCrossOrigin() const {
2358 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2360 auto self = Utils::OpenHandle(this);
2361 auto script = i::Handle<i::JSValue>::cast(
2362 i::Handle<i::Object>(self->script(), isolate));
2363 return i::Script::cast(script->value())
2365 .IsSharedCrossOrigin();
2368 bool Message::IsOpaque() const {
2369 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2371 auto self = Utils::OpenHandle(this);
2372 auto script = i::Handle<i::JSValue>::cast(
2373 i::Handle<i::Object>(self->script(), isolate));
2374 return i::Script::cast(script->value())->origin_options().IsOpaque();
2378 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
2379 PREPARE_FOR_EXECUTION(context, "v8::Message::GetSourceLine()", String);
2380 i::Handle<i::JSFunction> fun = isolate->message_get_source_line();
2381 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
2382 i::Handle<i::Object> args[] = {Utils::OpenHandle(this)};
2383 i::Handle<i::Object> result;
2384 has_pending_exception =
2385 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
2387 RETURN_ON_FAILED_EXECUTION(String);
2389 if (result->IsString()) {
2390 str = Utils::ToLocal(i::Handle<i::String>::cast(result));
2392 RETURN_ESCAPED(str);
2396 Local<String> Message::GetSourceLine() const {
2397 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2398 RETURN_TO_LOCAL_UNCHECKED(GetSourceLine(context), String)
2402 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
2403 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2404 ENTER_V8(i_isolate);
2405 i_isolate->PrintCurrentStackTrace(out);
2409 // --- S t a c k T r a c e ---
2411 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
2412 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2414 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2415 auto self = Utils::OpenHandle(this);
2416 auto obj = i::Object::GetElement(isolate, self, index).ToHandleChecked();
2417 auto jsobj = i::Handle<i::JSObject>::cast(obj);
2418 return scope.Escape(Utils::StackFrameToLocal(jsobj));
2422 int StackTrace::GetFrameCount() const {
2423 return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
2427 Local<Array> StackTrace::AsArray() {
2428 return Utils::ToLocal(Utils::OpenHandle(this));
2432 Local<StackTrace> StackTrace::CurrentStackTrace(
2435 StackTraceOptions options) {
2436 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2437 ENTER_V8(i_isolate);
2438 // TODO(dcarney): remove when ScriptDebugServer is fixed.
2439 options = static_cast<StackTraceOptions>(
2440 static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins);
2441 i::Handle<i::JSArray> stackTrace =
2442 i_isolate->CaptureCurrentStackTrace(frame_limit, options);
2443 return Utils::StackTraceToLocal(stackTrace);
2447 // --- S t a c k F r a m e ---
2449 static int getIntProperty(const StackFrame* f, const char* propertyName,
2451 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2453 i::HandleScope scope(isolate);
2454 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2455 i::Handle<i::Object> obj =
2456 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2457 return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue;
2461 int StackFrame::GetLineNumber() const {
2462 return getIntProperty(this, "lineNumber", Message::kNoLineNumberInfo);
2466 int StackFrame::GetColumn() const {
2467 return getIntProperty(this, "column", Message::kNoColumnInfo);
2471 int StackFrame::GetScriptId() const {
2472 return getIntProperty(this, "scriptId", Message::kNoScriptIdInfo);
2476 static Local<String> getStringProperty(const StackFrame* f,
2477 const char* propertyName) {
2478 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2480 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2481 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2482 i::Handle<i::Object> obj =
2483 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2484 return obj->IsString()
2485 ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2490 Local<String> StackFrame::GetScriptName() const {
2491 return getStringProperty(this, "scriptName");
2495 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2496 return getStringProperty(this, "scriptNameOrSourceURL");
2500 Local<String> StackFrame::GetFunctionName() const {
2501 return getStringProperty(this, "functionName");
2505 static bool getBoolProperty(const StackFrame* f, const char* propertyName) {
2506 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2508 i::HandleScope scope(isolate);
2509 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2510 i::Handle<i::Object> obj =
2511 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2512 return obj->IsTrue();
2515 bool StackFrame::IsEval() const { return getBoolProperty(this, "isEval"); }
2518 bool StackFrame::IsConstructor() const {
2519 return getBoolProperty(this, "isConstructor");
2523 // --- N a t i v e W e a k M a p ---
2525 Local<NativeWeakMap> NativeWeakMap::New(Isolate* v8_isolate) {
2526 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2528 i::Handle<i::JSWeakMap> weakmap = isolate->factory()->NewJSWeakMap();
2529 i::JSWeakCollection::Initialize(weakmap, isolate);
2530 return Utils::NativeWeakMapToLocal(weakmap);
2534 void NativeWeakMap::Set(Local<Value> v8_key, Local<Value> v8_value) {
2535 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2536 i::Isolate* isolate = weak_collection->GetIsolate();
2538 i::HandleScope scope(isolate);
2539 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2540 i::Handle<i::Object> value = Utils::OpenHandle(*v8_value);
2541 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2545 i::Handle<i::ObjectHashTable> table(
2546 i::ObjectHashTable::cast(weak_collection->table()));
2547 if (!table->IsKey(*key)) {
2551 int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value();
2552 i::JSWeakCollection::Set(weak_collection, key, value, hash);
2556 Local<Value> NativeWeakMap::Get(Local<Value> v8_key) {
2557 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2558 i::Isolate* isolate = weak_collection->GetIsolate();
2560 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2561 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2563 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2565 i::Handle<i::ObjectHashTable> table(
2566 i::ObjectHashTable::cast(weak_collection->table()));
2567 if (!table->IsKey(*key)) {
2569 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2571 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2572 if (lookup->IsTheHole())
2573 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2574 return Utils::ToLocal(lookup);
2578 bool NativeWeakMap::Has(Local<Value> v8_key) {
2579 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2580 i::Isolate* isolate = weak_collection->GetIsolate();
2582 i::HandleScope scope(isolate);
2583 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2584 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2588 i::Handle<i::ObjectHashTable> table(
2589 i::ObjectHashTable::cast(weak_collection->table()));
2590 if (!table->IsKey(*key)) {
2594 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2595 return !lookup->IsTheHole();
2599 bool NativeWeakMap::Delete(Local<Value> v8_key) {
2600 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2601 i::Isolate* isolate = weak_collection->GetIsolate();
2603 i::HandleScope scope(isolate);
2604 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2605 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2609 i::Handle<i::ObjectHashTable> table(
2610 i::ObjectHashTable::cast(weak_collection->table()));
2611 if (!table->IsKey(*key)) {
2615 int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value();
2616 return i::JSWeakCollection::Delete(weak_collection, key, hash);
2622 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) {
2623 auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2624 PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, "JSON::Parse", Value);
2625 i::Handle<i::String> string = Utils::OpenHandle(*json_string);
2626 i::Handle<i::String> source = i::String::Flatten(string);
2627 auto maybe = source->IsSeqOneByteString()
2628 ? i::JsonParser<true>::Parse(source)
2629 : i::JsonParser<false>::Parse(source);
2630 Local<Value> result;
2631 has_pending_exception = !ToLocal<Value>(maybe, &result);
2632 RETURN_ON_FAILED_EXECUTION(Value);
2633 RETURN_ESCAPED(result);
2637 Local<Value> JSON::Parse(Local<String> json_string) {
2638 auto isolate = reinterpret_cast<v8::Isolate*>(
2639 Utils::OpenHandle(*json_string)->GetIsolate());
2640 RETURN_TO_LOCAL_UNCHECKED(Parse(isolate, json_string), Value);
2646 bool Value::FullIsUndefined() const {
2647 bool result = Utils::OpenHandle(this)->IsUndefined();
2648 DCHECK_EQ(result, QuickIsUndefined());
2653 bool Value::FullIsNull() const {
2654 bool result = Utils::OpenHandle(this)->IsNull();
2655 DCHECK_EQ(result, QuickIsNull());
2660 bool Value::IsTrue() const {
2661 return Utils::OpenHandle(this)->IsTrue();
2665 bool Value::IsFalse() const {
2666 return Utils::OpenHandle(this)->IsFalse();
2670 bool Value::IsFunction() const {
2671 return Utils::OpenHandle(this)->IsJSFunction();
2675 bool Value::IsName() const {
2676 return Utils::OpenHandle(this)->IsName();
2680 bool Value::FullIsString() const {
2681 bool result = Utils::OpenHandle(this)->IsString();
2682 DCHECK_EQ(result, QuickIsString());
2687 bool Value::IsSymbol() const {
2688 return Utils::OpenHandle(this)->IsSymbol();
2692 bool Value::IsArray() const {
2693 return Utils::OpenHandle(this)->IsJSArray();
2697 bool Value::IsArrayBuffer() const {
2698 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2699 return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
2703 bool Value::IsArrayBufferView() const {
2704 return Utils::OpenHandle(this)->IsJSArrayBufferView();
2708 bool Value::IsTypedArray() const {
2709 return Utils::OpenHandle(this)->IsJSTypedArray();
2713 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype, size) \
2714 bool Value::Is##Type##Array() const { \
2715 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2716 return obj->IsJSTypedArray() && \
2717 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
2721 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
2723 #undef VALUE_IS_TYPED_ARRAY
2726 bool Value::IsDataView() const {
2727 return Utils::OpenHandle(this)->IsJSDataView();
2731 bool Value::IsSharedArrayBuffer() const {
2732 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2733 return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
2737 bool Value::IsObject() const {
2738 return Utils::OpenHandle(this)->IsJSObject();
2742 bool Value::IsNumber() const {
2743 return Utils::OpenHandle(this)->IsNumber();
2747 #define VALUE_IS_SPECIFIC_TYPE(Type, Class) \
2748 bool Value::Is##Type() const { \
2749 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2750 if (!obj->IsHeapObject()) return false; \
2751 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate(); \
2752 return obj->HasSpecificClassOf(isolate->heap()->Class##_string()); \
2755 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, Arguments)
2756 VALUE_IS_SPECIFIC_TYPE(BooleanObject, Boolean)
2757 VALUE_IS_SPECIFIC_TYPE(NumberObject, Number)
2758 VALUE_IS_SPECIFIC_TYPE(StringObject, String)
2759 VALUE_IS_SPECIFIC_TYPE(SymbolObject, Symbol)
2760 VALUE_IS_SPECIFIC_TYPE(Date, Date)
2761 VALUE_IS_SPECIFIC_TYPE(Map, Map)
2762 VALUE_IS_SPECIFIC_TYPE(Set, Set)
2763 VALUE_IS_SPECIFIC_TYPE(WeakMap, WeakMap)
2764 VALUE_IS_SPECIFIC_TYPE(WeakSet, WeakSet)
2766 #undef VALUE_IS_SPECIFIC_TYPE
2769 bool Value::IsBoolean() const {
2770 return Utils::OpenHandle(this)->IsBoolean();
2774 bool Value::IsExternal() const {
2775 return Utils::OpenHandle(this)->IsExternal();
2779 bool Value::IsInt32() const {
2780 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2781 if (obj->IsSmi()) return true;
2782 if (obj->IsNumber()) {
2783 return i::IsInt32Double(obj->Number());
2789 bool Value::IsUint32() const {
2790 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2791 if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2792 if (obj->IsNumber()) {
2793 double value = obj->Number();
2794 return !i::IsMinusZero(value) &&
2796 value <= i::kMaxUInt32 &&
2797 value == i::FastUI2D(i::FastD2UI(value));
2803 bool Value::IsNativeError() const {
2804 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2805 if (!obj->IsJSObject()) return false;
2806 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
2807 i::Isolate* isolate = js_obj->GetIsolate();
2808 i::Handle<i::Object> constructor(js_obj->map()->GetConstructor(), isolate);
2809 if (!constructor->IsJSFunction()) return false;
2810 i::Handle<i::JSFunction> function =
2811 i::Handle<i::JSFunction>::cast(constructor);
2812 if (!function->shared()->native()) return false;
2813 return function.is_identical_to(isolate->error_function()) ||
2814 function.is_identical_to(isolate->eval_error_function()) ||
2815 function.is_identical_to(isolate->range_error_function()) ||
2816 function.is_identical_to(isolate->reference_error_function()) ||
2817 function.is_identical_to(isolate->syntax_error_function()) ||
2818 function.is_identical_to(isolate->type_error_function()) ||
2819 function.is_identical_to(isolate->uri_error_function());
2823 bool Value::IsRegExp() const {
2824 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2825 return obj->IsJSRegExp();
2829 bool Value::IsGeneratorFunction() const {
2830 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2831 if (!obj->IsJSFunction()) return false;
2832 i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
2833 return func->shared()->is_generator();
2837 bool Value::IsGeneratorObject() const {
2838 return Utils::OpenHandle(this)->IsJSGeneratorObject();
2842 bool Value::IsMapIterator() const {
2843 return Utils::OpenHandle(this)->IsJSMapIterator();
2847 bool Value::IsSetIterator() const {
2848 return Utils::OpenHandle(this)->IsJSSetIterator();
2852 MaybeLocal<String> Value::ToString(Local<Context> context) const {
2853 auto obj = Utils::OpenHandle(this);
2854 if (obj->IsString()) return ToApiHandle<String>(obj);
2855 PREPARE_FOR_EXECUTION(context, "ToString", String);
2856 Local<String> result;
2857 has_pending_exception =
2858 !ToLocal<String>(i::Object::ToString(isolate, obj), &result);
2859 RETURN_ON_FAILED_EXECUTION(String);
2860 RETURN_ESCAPED(result);
2864 Local<String> Value::ToString(Isolate* isolate) const {
2865 RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
2869 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
2870 auto obj = Utils::OpenHandle(this);
2871 if (obj->IsString()) return ToApiHandle<String>(obj);
2872 PREPARE_FOR_EXECUTION(context, "ToDetailString", String);
2873 Local<String> result;
2874 has_pending_exception =
2875 !ToLocal<String>(i::Execution::ToDetailString(isolate, obj), &result);
2876 RETURN_ON_FAILED_EXECUTION(String);
2877 RETURN_ESCAPED(result);
2881 Local<String> Value::ToDetailString(Isolate* isolate) const {
2882 RETURN_TO_LOCAL_UNCHECKED(ToDetailString(isolate->GetCurrentContext()),
2887 MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
2888 auto obj = Utils::OpenHandle(this);
2889 if (obj->IsJSObject()) return ToApiHandle<Object>(obj);
2890 PREPARE_FOR_EXECUTION(context, "ToObject", Object);
2891 Local<Object> result;
2892 has_pending_exception =
2893 !ToLocal<Object>(i::Execution::ToObject(isolate, obj), &result);
2894 RETURN_ON_FAILED_EXECUTION(Object);
2895 RETURN_ESCAPED(result);
2899 Local<v8::Object> Value::ToObject(Isolate* isolate) const {
2900 RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
2904 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
2905 auto obj = Utils::OpenHandle(this);
2906 if (obj->IsBoolean()) return ToApiHandle<Boolean>(obj);
2907 auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2908 auto val = isolate->factory()->ToBoolean(obj->BooleanValue());
2909 return ToApiHandle<Boolean>(val);
2913 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
2914 return ToBoolean(v8_isolate->GetCurrentContext()).ToLocalChecked();
2918 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
2919 auto obj = Utils::OpenHandle(this);
2920 if (obj->IsNumber()) return ToApiHandle<Number>(obj);
2921 PREPARE_FOR_EXECUTION(context, "ToNumber", Number);
2922 Local<Number> result;
2923 has_pending_exception = !ToLocal<Number>(i::Object::ToNumber(obj), &result);
2924 RETURN_ON_FAILED_EXECUTION(Number);
2925 RETURN_ESCAPED(result);
2929 Local<Number> Value::ToNumber(Isolate* isolate) const {
2930 RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
2934 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
2935 auto obj = Utils::OpenHandle(this);
2936 if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
2937 PREPARE_FOR_EXECUTION(context, "ToInteger", Integer);
2938 Local<Integer> result;
2939 has_pending_exception =
2940 !ToLocal<Integer>(i::Execution::ToInteger(isolate, obj), &result);
2941 RETURN_ON_FAILED_EXECUTION(Integer);
2942 RETURN_ESCAPED(result);
2946 Local<Integer> Value::ToInteger(Isolate* isolate) const {
2947 RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
2951 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
2952 auto obj = Utils::OpenHandle(this);
2953 if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
2954 Local<Int32> result;
2955 PREPARE_FOR_EXECUTION(context, "ToInt32", Int32);
2956 has_pending_exception =
2957 !ToLocal<Int32>(i::Execution::ToInt32(isolate, obj), &result);
2958 RETURN_ON_FAILED_EXECUTION(Int32);
2959 RETURN_ESCAPED(result);
2963 Local<Int32> Value::ToInt32(Isolate* isolate) const {
2964 RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
2968 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
2969 auto obj = Utils::OpenHandle(this);
2970 if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
2971 Local<Uint32> result;
2972 PREPARE_FOR_EXECUTION(context, "ToUInt32", Uint32);
2973 has_pending_exception =
2974 !ToLocal<Uint32>(i::Execution::ToUint32(isolate, obj), &result);
2975 RETURN_ON_FAILED_EXECUTION(Uint32);
2976 RETURN_ESCAPED(result);
2980 Local<Uint32> Value::ToUint32(Isolate* isolate) const {
2981 RETURN_TO_LOCAL_UNCHECKED(ToUint32(isolate->GetCurrentContext()), Uint32);
2985 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
2986 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
2987 Utils::ApiCheck(isolate != NULL &&
2989 "v8::internal::Internals::CheckInitialized()",
2990 "Isolate is not initialized or V8 has died");
2994 void External::CheckCast(v8::Value* that) {
2995 Utils::ApiCheck(Utils::OpenHandle(that)->IsExternal(),
2996 "v8::External::Cast()",
2997 "Could not convert to external");
3001 void v8::Object::CheckCast(Value* that) {
3002 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3003 Utils::ApiCheck(obj->IsJSObject(),
3004 "v8::Object::Cast()",
3005 "Could not convert to object");
3009 void v8::Function::CheckCast(Value* that) {
3010 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3011 Utils::ApiCheck(obj->IsJSFunction(),
3012 "v8::Function::Cast()",
3013 "Could not convert to function");
3017 void v8::Boolean::CheckCast(v8::Value* that) {
3018 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3019 Utils::ApiCheck(obj->IsBoolean(),
3020 "v8::Boolean::Cast()",
3021 "Could not convert to boolean");
3025 void v8::Name::CheckCast(v8::Value* that) {
3026 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3027 Utils::ApiCheck(obj->IsName(),
3029 "Could not convert to name");
3033 void v8::String::CheckCast(v8::Value* that) {
3034 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3035 Utils::ApiCheck(obj->IsString(),
3036 "v8::String::Cast()",
3037 "Could not convert to string");
3041 void v8::Symbol::CheckCast(v8::Value* that) {
3042 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3043 Utils::ApiCheck(obj->IsSymbol(),
3044 "v8::Symbol::Cast()",
3045 "Could not convert to symbol");
3049 void v8::Number::CheckCast(v8::Value* that) {
3050 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3051 Utils::ApiCheck(obj->IsNumber(),
3052 "v8::Number::Cast()",
3053 "Could not convert to number");
3057 void v8::Integer::CheckCast(v8::Value* that) {
3058 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3059 Utils::ApiCheck(obj->IsNumber(),
3060 "v8::Integer::Cast()",
3061 "Could not convert to number");
3065 void v8::Int32::CheckCast(v8::Value* that) {
3066 Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast()",
3067 "Could not convert to 32-bit signed integer");
3071 void v8::Uint32::CheckCast(v8::Value* that) {
3072 Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast()",
3073 "Could not convert to 32-bit unsigned integer");
3077 void v8::Array::CheckCast(Value* that) {
3078 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3079 Utils::ApiCheck(obj->IsJSArray(),
3080 "v8::Array::Cast()",
3081 "Could not convert to array");
3085 void v8::Map::CheckCast(Value* that) {
3086 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3087 Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast()",
3088 "Could not convert to Map");
3092 void v8::Set::CheckCast(Value* that) {
3093 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3094 Utils::ApiCheck(obj->IsJSSet(), "v8::Set::Cast()",
3095 "Could not convert to Set");
3099 void v8::Promise::CheckCast(Value* that) {
3100 Utils::ApiCheck(that->IsPromise(),
3101 "v8::Promise::Cast()",
3102 "Could not convert to promise");
3106 void v8::Promise::Resolver::CheckCast(Value* that) {
3107 Utils::ApiCheck(that->IsPromise(),
3108 "v8::Promise::Resolver::Cast()",
3109 "Could not convert to promise resolver");
3113 void v8::ArrayBuffer::CheckCast(Value* that) {
3114 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3116 obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
3117 "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
3121 void v8::ArrayBufferView::CheckCast(Value* that) {
3122 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3123 Utils::ApiCheck(obj->IsJSArrayBufferView(),
3124 "v8::ArrayBufferView::Cast()",
3125 "Could not convert to ArrayBufferView");
3129 void v8::TypedArray::CheckCast(Value* that) {
3130 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3131 Utils::ApiCheck(obj->IsJSTypedArray(),
3132 "v8::TypedArray::Cast()",
3133 "Could not convert to TypedArray");
3137 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype, size) \
3138 void v8::Type##Array::CheckCast(Value* that) { \
3139 i::Handle<i::Object> obj = Utils::OpenHandle(that); \
3141 obj->IsJSTypedArray() && \
3142 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
3143 "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
3147 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
3149 #undef CHECK_TYPED_ARRAY_CAST
3152 void v8::DataView::CheckCast(Value* that) {
3153 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3154 Utils::ApiCheck(obj->IsJSDataView(),
3155 "v8::DataView::Cast()",
3156 "Could not convert to DataView");
3160 void v8::SharedArrayBuffer::CheckCast(Value* that) {
3161 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3163 obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
3164 "v8::SharedArrayBuffer::Cast()",
3165 "Could not convert to SharedArrayBuffer");
3169 void v8::Date::CheckCast(v8::Value* that) {
3170 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3171 i::Isolate* isolate = NULL;
3172 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3173 Utils::ApiCheck(isolate != NULL &&
3174 obj->HasSpecificClassOf(isolate->heap()->Date_string()),
3176 "Could not convert to date");
3180 void v8::StringObject::CheckCast(v8::Value* that) {
3181 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3182 i::Isolate* isolate = NULL;
3183 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3184 Utils::ApiCheck(isolate != NULL &&
3185 obj->HasSpecificClassOf(isolate->heap()->String_string()),
3186 "v8::StringObject::Cast()",
3187 "Could not convert to StringObject");
3191 void v8::SymbolObject::CheckCast(v8::Value* that) {
3192 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3193 i::Isolate* isolate = NULL;
3194 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3195 Utils::ApiCheck(isolate != NULL &&
3196 obj->HasSpecificClassOf(isolate->heap()->Symbol_string()),
3197 "v8::SymbolObject::Cast()",
3198 "Could not convert to SymbolObject");
3202 void v8::NumberObject::CheckCast(v8::Value* that) {
3203 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3204 i::Isolate* isolate = NULL;
3205 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3206 Utils::ApiCheck(isolate != NULL &&
3207 obj->HasSpecificClassOf(isolate->heap()->Number_string()),
3208 "v8::NumberObject::Cast()",
3209 "Could not convert to NumberObject");
3213 void v8::BooleanObject::CheckCast(v8::Value* that) {
3214 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3215 i::Isolate* isolate = NULL;
3216 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3217 Utils::ApiCheck(isolate != NULL &&
3218 obj->HasSpecificClassOf(isolate->heap()->Boolean_string()),
3219 "v8::BooleanObject::Cast()",
3220 "Could not convert to BooleanObject");
3224 void v8::RegExp::CheckCast(v8::Value* that) {
3225 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3226 Utils::ApiCheck(obj->IsJSRegExp(),
3227 "v8::RegExp::Cast()",
3228 "Could not convert to regular expression");
3232 Maybe<bool> Value::BooleanValue(Local<Context> context) const {
3233 return Just(Utils::OpenHandle(this)->BooleanValue());
3237 bool Value::BooleanValue() const {
3238 return Utils::OpenHandle(this)->BooleanValue();
3242 Maybe<double> Value::NumberValue(Local<Context> context) const {
3243 auto obj = Utils::OpenHandle(this);
3244 if (obj->IsNumber()) return Just(obj->Number());
3245 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "NumberValue", double);
3246 i::Handle<i::Object> num;
3247 has_pending_exception = !i::Object::ToNumber(obj).ToHandle(&num);
3248 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
3249 return Just(num->Number());
3253 double Value::NumberValue() const {
3254 auto obj = Utils::OpenHandle(this);
3255 if (obj->IsNumber()) return obj->Number();
3256 return NumberValue(ContextFromHeapObject(obj))
3257 .FromMaybe(std::numeric_limits<double>::quiet_NaN());
3261 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
3262 auto obj = Utils::OpenHandle(this);
3263 i::Handle<i::Object> num;
3264 if (obj->IsNumber()) {
3267 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "IntegerValue", int64_t);
3268 has_pending_exception =
3269 !i::Execution::ToInteger(isolate, obj).ToHandle(&num);
3270 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
3272 return Just(num->IsSmi() ? static_cast<int64_t>(i::Smi::cast(*num)->value())
3273 : static_cast<int64_t>(num->Number()));
3277 int64_t Value::IntegerValue() const {
3278 auto obj = Utils::OpenHandle(this);
3279 if (obj->IsNumber()) {
3281 return i::Smi::cast(*obj)->value();
3283 return static_cast<int64_t>(obj->Number());
3286 return IntegerValue(ContextFromHeapObject(obj)).FromMaybe(0);
3290 Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
3291 auto obj = Utils::OpenHandle(this);
3292 if (obj->IsNumber()) return Just(NumberToInt32(*obj));
3293 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Int32Value", int32_t);
3294 i::Handle<i::Object> num;
3295 has_pending_exception = !i::Execution::ToInt32(isolate, obj).ToHandle(&num);
3296 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
3297 return Just(num->IsSmi() ? i::Smi::cast(*num)->value()
3298 : static_cast<int32_t>(num->Number()));
3302 int32_t Value::Int32Value() const {
3303 auto obj = Utils::OpenHandle(this);
3304 if (obj->IsNumber()) return NumberToInt32(*obj);
3305 return Int32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3309 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
3310 auto obj = Utils::OpenHandle(this);
3311 if (obj->IsNumber()) return Just(NumberToUint32(*obj));
3312 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Uint32Value", uint32_t);
3313 i::Handle<i::Object> num;
3314 has_pending_exception = !i::Execution::ToUint32(isolate, obj).ToHandle(&num);
3315 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
3316 return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::cast(*num)->value())
3317 : static_cast<uint32_t>(num->Number()));
3321 uint32_t Value::Uint32Value() const {
3322 auto obj = Utils::OpenHandle(this);
3323 if (obj->IsNumber()) return NumberToUint32(*obj);
3324 return Uint32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3328 MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const {
3329 auto self = Utils::OpenHandle(this);
3330 if (self->IsSmi()) {
3331 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3332 return Local<Uint32>();
3334 PREPARE_FOR_EXECUTION(context, "ToArrayIndex", Uint32);
3335 i::Handle<i::Object> string_obj;
3336 has_pending_exception =
3337 !i::Object::ToString(isolate, self).ToHandle(&string_obj);
3338 RETURN_ON_FAILED_EXECUTION(Uint32);
3339 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
3341 if (str->AsArrayIndex(&index)) {
3342 i::Handle<i::Object> value;
3343 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
3344 value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
3346 value = isolate->factory()->NewNumber(index);
3348 RETURN_ESCAPED(Utils::Uint32ToLocal(value));
3350 return Local<Uint32>();
3354 Local<Uint32> Value::ToArrayIndex() const {
3355 auto self = Utils::OpenHandle(this);
3356 if (self->IsSmi()) {
3357 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3358 return Local<Uint32>();
3360 auto context = ContextFromHeapObject(self);
3361 RETURN_TO_LOCAL_UNCHECKED(ToArrayIndex(context), Uint32);
3365 Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const {
3366 auto self = Utils::OpenHandle(this);
3367 auto other = Utils::OpenHandle(*that);
3368 return i::Object::Equals(self, other);
3372 bool Value::Equals(Local<Value> that) const {
3373 auto self = Utils::OpenHandle(this);
3374 auto other = Utils::OpenHandle(*that);
3375 if (self->IsSmi() && other->IsSmi()) {
3376 return self->Number() == other->Number();
3378 if (self->IsJSObject() && other->IsJSObject()) {
3379 return *self == *other;
3381 auto heap_object = self->IsSmi() ? other : self;
3382 auto context = ContextFromHeapObject(heap_object);
3383 return Equals(context, that).FromMaybe(false);
3387 bool Value::StrictEquals(Local<Value> that) const {
3388 auto self = Utils::OpenHandle(this);
3389 auto other = Utils::OpenHandle(*that);
3390 return self->StrictEquals(*other);
3394 bool Value::SameValue(Local<Value> that) const {
3395 auto self = Utils::OpenHandle(this);
3396 auto other = Utils::OpenHandle(*that);
3397 return self->SameValue(*other);
3401 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
3402 v8::Local<Value> key, v8::Local<Value> value) {
3403 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3404 auto self = Utils::OpenHandle(this);
3405 auto key_obj = Utils::OpenHandle(*key);
3406 auto value_obj = Utils::OpenHandle(*value);
3407 has_pending_exception =
3408 i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
3409 i::SLOPPY).is_null();
3410 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3415 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
3416 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3417 return Set(context, key, value).FromMaybe(false);
3421 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
3422 v8::Local<Value> value) {
3423 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3424 auto self = Utils::OpenHandle(this);
3425 auto value_obj = Utils::OpenHandle(*value);
3426 has_pending_exception = i::Object::SetElement(isolate, self, index, value_obj,
3427 i::SLOPPY).is_null();
3428 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3433 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
3434 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3435 return Set(context, index, value).FromMaybe(false);
3439 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3440 v8::Local<Name> key,
3441 v8::Local<Value> value) {
3442 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3444 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3445 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
3446 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3448 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
3449 isolate, self, key_obj, i::LookupIterator::OWN);
3450 Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3451 has_pending_exception = result.IsNothing();
3452 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3457 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3459 v8::Local<Value> value) {
3460 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3462 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3463 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3465 i::LookupIterator it(isolate, self, index, i::LookupIterator::OWN);
3466 Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3467 has_pending_exception = result.IsNothing();
3468 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3473 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
3474 v8::Local<Name> key,
3475 v8::Local<Value> value,
3476 v8::PropertyAttribute attributes) {
3477 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DefineOwnProperty()",
3479 auto self = Utils::OpenHandle(this);
3480 auto key_obj = Utils::OpenHandle(*key);
3481 auto value_obj = Utils::OpenHandle(*value);
3483 if (self->IsAccessCheckNeeded() && !isolate->MayAccess(self)) {
3484 isolate->ReportFailedAccessCheck(self);
3485 return Nothing<bool>();
3488 i::Handle<i::FixedArray> desc = isolate->factory()->NewFixedArray(3);
3489 desc->set(0, isolate->heap()->ToBoolean(!(attributes & v8::ReadOnly)));
3490 desc->set(1, isolate->heap()->ToBoolean(!(attributes & v8::DontEnum)));
3491 desc->set(2, isolate->heap()->ToBoolean(!(attributes & v8::DontDelete)));
3492 i::Handle<i::JSArray> desc_array =
3493 isolate->factory()->NewJSArrayWithElements(desc, i::FAST_ELEMENTS, 3);
3494 i::Handle<i::Object> args[] = {self, key_obj, value_obj, desc_array};
3495 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
3496 i::Handle<i::JSFunction> fun = isolate->object_define_own_property();
3497 i::Handle<i::Object> result;
3498 has_pending_exception =
3499 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
3501 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3502 return Just(result->BooleanValue());
3507 static i::MaybeHandle<i::Object> DefineObjectProperty(
3508 i::Handle<i::JSObject> js_object, i::Handle<i::Object> key,
3509 i::Handle<i::Object> value, PropertyAttributes attrs) {
3510 i::Isolate* isolate = js_object->GetIsolate();
3511 // Check if the given key is an array index.
3513 if (key->ToArrayIndex(&index)) {
3514 return i::JSObject::SetOwnElementIgnoreAttributes(js_object, index, value,
3518 i::Handle<i::Name> name;
3519 ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
3520 i::Object::ToName(isolate, key),
3521 i::MaybeHandle<i::Object>());
3523 return i::JSObject::DefinePropertyOrElementIgnoreAttributes(js_object, name,
3528 Maybe<bool> v8::Object::ForceSet(v8::Local<v8::Context> context,
3529 v8::Local<Value> key, v8::Local<Value> value,
3530 v8::PropertyAttribute attribs) {
3531 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3532 auto self = Utils::OpenHandle(this);
3533 auto key_obj = Utils::OpenHandle(*key);
3534 auto value_obj = Utils::OpenHandle(*value);
3535 has_pending_exception =
3536 DefineObjectProperty(self, key_obj, value_obj,
3537 static_cast<PropertyAttributes>(attribs)).is_null();
3538 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3543 bool v8::Object::ForceSet(v8::Local<Value> key, v8::Local<Value> value,
3544 v8::PropertyAttribute attribs) {
3545 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3546 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(),
3547 "v8::Object::ForceSet", false, i::HandleScope,
3549 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3550 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
3551 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3552 has_pending_exception =
3553 DefineObjectProperty(self, key_obj, value_obj,
3554 static_cast<PropertyAttributes>(attribs)).is_null();
3555 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, false);
3560 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
3562 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3563 auto self = Utils::OpenHandle(this);
3564 auto key_obj = Utils::OpenHandle(*key);
3565 i::Handle<i::Object> result;
3566 has_pending_exception =
3567 !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
3568 RETURN_ON_FAILED_EXECUTION(Value);
3569 RETURN_ESCAPED(Utils::ToLocal(result));
3573 Local<Value> v8::Object::Get(v8::Local<Value> key) {
3574 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3575 RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
3579 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
3580 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3581 auto self = Utils::OpenHandle(this);
3582 i::Handle<i::Object> result;
3583 has_pending_exception =
3584 !i::Object::GetElement(isolate, self, index).ToHandle(&result);
3585 RETURN_ON_FAILED_EXECUTION(Value);
3586 RETURN_ESCAPED(Utils::ToLocal(result));
3590 Local<Value> v8::Object::Get(uint32_t index) {
3591 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3592 RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
3596 Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes(
3597 Local<Context> context, Local<Value> key) {
3598 PREPARE_FOR_EXECUTION_PRIMITIVE(
3599 context, "v8::Object::GetPropertyAttributes()", PropertyAttribute);
3600 auto self = Utils::OpenHandle(this);
3601 auto key_obj = Utils::OpenHandle(*key);
3602 if (!key_obj->IsName()) {
3603 has_pending_exception =
3604 !i::Object::ToString(isolate, key_obj).ToHandle(&key_obj);
3605 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3607 auto key_name = i::Handle<i::Name>::cast(key_obj);
3608 auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
3609 has_pending_exception = result.IsNothing();
3610 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3611 if (result.FromJust() == ABSENT) {
3612 return Just(static_cast<PropertyAttribute>(NONE));
3614 return Just(static_cast<PropertyAttribute>(result.FromJust()));
3618 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Local<Value> key) {
3619 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3620 return GetPropertyAttributes(context, key)
3621 .FromMaybe(static_cast<PropertyAttribute>(NONE));
3625 MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context,
3626 Local<String> key) {
3627 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyDescriptor()",
3629 auto obj = Utils::OpenHandle(this);
3630 auto key_name = Utils::OpenHandle(*key);
3631 i::Handle<i::Object> args[] = { obj, key_name };
3632 i::Handle<i::JSFunction> fun = isolate->object_get_own_property_descriptor();
3633 i::Handle<i::Object> undefined = isolate->factory()->undefined_value();
3634 i::Handle<i::Object> result;
3635 has_pending_exception =
3636 !i::Execution::Call(isolate, fun, undefined, arraysize(args), args)
3638 RETURN_ON_FAILED_EXECUTION(Value);
3639 RETURN_ESCAPED(Utils::ToLocal(result));
3643 Local<Value> v8::Object::GetOwnPropertyDescriptor(Local<String> key) {
3644 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3645 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyDescriptor(context, key), Value);
3649 Local<Value> v8::Object::GetPrototype() {
3650 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3651 auto self = Utils::OpenHandle(this);
3652 i::PrototypeIterator iter(isolate, self);
3653 return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
3657 Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
3658 Local<Value> value) {
3659 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetPrototype()", bool);
3660 auto self = Utils::OpenHandle(this);
3661 auto value_obj = Utils::OpenHandle(*value);
3662 // We do not allow exceptions thrown while setting the prototype
3663 // to propagate outside.
3664 TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
3665 auto result = i::JSObject::SetPrototype(self, value_obj, false);
3666 has_pending_exception = result.is_null();
3667 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3672 bool v8::Object::SetPrototype(Local<Value> value) {
3673 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3674 return SetPrototype(context, value).FromMaybe(false);
3678 Local<Object> v8::Object::FindInstanceInPrototypeChain(
3679 v8::Local<FunctionTemplate> tmpl) {
3680 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3681 i::PrototypeIterator iter(isolate, *Utils::OpenHandle(this),
3682 i::PrototypeIterator::START_AT_RECEIVER);
3683 auto tmpl_info = *Utils::OpenHandle(*tmpl);
3684 while (!tmpl_info->IsTemplateFor(iter.GetCurrent())) {
3686 if (iter.IsAtEnd()) {
3687 return Local<Object>();
3690 return Utils::ToLocal(i::handle(iter.GetCurrent<i::JSObject>(), isolate));
3694 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
3695 PREPARE_FOR_EXECUTION(context, "v8::Object::GetPropertyNames()", Array);
3696 auto self = Utils::OpenHandle(this);
3697 i::Handle<i::FixedArray> value;
3698 has_pending_exception = !i::JSReceiver::GetKeys(
3699 self, i::JSReceiver::INCLUDE_PROTOS).ToHandle(&value);
3700 RETURN_ON_FAILED_EXECUTION(Array);
3701 // Because we use caching to speed up enumeration it is important
3702 // to never change the result of the basic enumeration function so
3703 // we clone the result.
3704 auto elms = isolate->factory()->CopyFixedArray(value);
3705 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3706 RETURN_ESCAPED(Utils::ToLocal(result));
3710 Local<Array> v8::Object::GetPropertyNames() {
3711 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3712 RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array);
3716 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
3717 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyNames()", Array);
3718 auto self = Utils::OpenHandle(this);
3719 i::Handle<i::FixedArray> value;
3720 has_pending_exception = !i::JSReceiver::GetKeys(
3721 self, i::JSReceiver::OWN_ONLY).ToHandle(&value);
3722 RETURN_ON_FAILED_EXECUTION(Array);
3723 // Because we use caching to speed up enumeration it is important
3724 // to never change the result of the basic enumeration function so
3725 // we clone the result.
3726 auto elms = isolate->factory()->CopyFixedArray(value);
3727 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3728 RETURN_ESCAPED(Utils::ToLocal(result));
3732 Local<Array> v8::Object::GetOwnPropertyNames() {
3733 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3734 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array);
3738 MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) {
3739 auto self = Utils::OpenHandle(this);
3740 auto isolate = self->GetIsolate();
3741 auto v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
3742 i::Handle<i::Object> name(self->class_name(), isolate);
3743 i::Handle<i::Object> tag;
3745 // Native implementation of Object.prototype.toString (v8natives.js):
3746 // var c = %_ClassOf(this);
3747 // if (c === 'Arguments') c = 'Object';
3748 // return "[object " + c + "]";
3750 if (!name->IsString()) {
3751 return v8::String::NewFromUtf8(v8_isolate, "[object ]",
3752 NewStringType::kNormal);
3754 auto class_name = i::Handle<i::String>::cast(name);
3755 if (i::String::Equals(class_name, isolate->factory()->Arguments_string())) {
3756 return v8::String::NewFromUtf8(v8_isolate, "[object Object]",
3757 NewStringType::kNormal);
3759 if (internal::FLAG_harmony_tostring) {
3760 PREPARE_FOR_EXECUTION(context, "v8::Object::ObjectProtoToString()", String);
3761 auto toStringTag = isolate->factory()->to_string_tag_symbol();
3762 has_pending_exception = !i::Runtime::GetObjectProperty(
3763 isolate, self, toStringTag).ToHandle(&tag);
3764 RETURN_ON_FAILED_EXECUTION(String);
3765 if (tag->IsString()) {
3766 class_name = Utils::OpenHandle(*handle_scope.Escape(
3767 Utils::ToLocal(i::Handle<i::String>::cast(tag))));
3770 const char* prefix = "[object ";
3771 Local<String> str = Utils::ToLocal(class_name);
3772 const char* postfix = "]";
3774 int prefix_len = i::StrLength(prefix);
3775 int str_len = str->Utf8Length();
3776 int postfix_len = i::StrLength(postfix);
3778 int buf_len = prefix_len + str_len + postfix_len;
3779 i::ScopedVector<char> buf(buf_len);
3782 char* ptr = buf.start();
3783 i::MemCopy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3786 // Write real content.
3787 str->WriteUtf8(ptr, str_len);
3791 i::MemCopy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3793 // Copy the buffer into a heap-allocated string and return it.
3794 return v8::String::NewFromUtf8(v8_isolate, buf.start(),
3795 NewStringType::kNormal, buf_len);
3799 Local<String> v8::Object::ObjectProtoToString() {
3800 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3801 RETURN_TO_LOCAL_UNCHECKED(ObjectProtoToString(context), String);
3805 Local<String> v8::Object::GetConstructorName() {
3806 auto self = Utils::OpenHandle(this);
3807 i::Handle<i::String> name(self->constructor_name());
3808 return Utils::ToLocal(name);
3812 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
3813 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Delete()", bool);
3814 auto self = Utils::OpenHandle(this);
3815 auto key_obj = Utils::OpenHandle(*key);
3816 i::Handle<i::Object> obj;
3817 has_pending_exception =
3818 !i::Runtime::DeleteObjectProperty(isolate, self, key_obj, i::SLOPPY)
3820 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3821 return Just(obj->IsTrue());
3825 bool v8::Object::Delete(v8::Local<Value> key) {
3826 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3827 return Delete(context, key).FromMaybe(false);
3831 Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) {
3832 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3833 auto self = Utils::OpenHandle(this);
3834 auto key_obj = Utils::OpenHandle(*key);
3835 Maybe<bool> maybe = Nothing<bool>();
3836 // Check if the given key is an array index.
3838 if (key_obj->ToArrayIndex(&index)) {
3839 maybe = i::JSReceiver::HasElement(self, index);
3841 // Convert the key to a name - possibly by calling back into JavaScript.
3842 i::Handle<i::Name> name;
3843 if (i::Object::ToName(isolate, key_obj).ToHandle(&name)) {
3844 maybe = i::JSReceiver::HasProperty(self, name);
3847 has_pending_exception = maybe.IsNothing();
3848 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3853 bool v8::Object::Has(v8::Local<Value> key) {
3854 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3855 return Has(context, key).FromMaybe(false);
3859 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
3860 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DeleteProperty()",
3862 auto self = Utils::OpenHandle(this);
3863 i::Handle<i::Object> obj;
3864 has_pending_exception =
3865 !i::JSReceiver::DeleteElement(self, index).ToHandle(&obj);
3866 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3867 return Just(obj->IsTrue());
3871 bool v8::Object::Delete(uint32_t index) {
3872 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3873 return Delete(context, index).FromMaybe(false);
3877 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
3878 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3879 auto self = Utils::OpenHandle(this);
3880 auto maybe = i::JSReceiver::HasElement(self, index);
3881 has_pending_exception = maybe.IsNothing();
3882 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3887 bool v8::Object::Has(uint32_t index) {
3888 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3889 return Has(context, index).FromMaybe(false);
3893 template <typename Getter, typename Setter, typename Data>
3894 static Maybe<bool> ObjectSetAccessor(Local<Context> context, Object* obj,
3895 Local<Name> name, Getter getter,
3896 Setter setter, Data data,
3897 AccessControl settings,
3898 PropertyAttribute attributes) {
3899 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetAccessor()", bool);
3900 v8::Local<AccessorSignature> signature;
3901 auto info = MakeAccessorInfo(name, getter, setter, data, settings, attributes,
3903 if (info.is_null()) return Nothing<bool>();
3904 bool fast = Utils::OpenHandle(obj)->HasFastProperties();
3905 i::Handle<i::Object> result;
3906 has_pending_exception =
3907 !i::JSObject::SetAccessor(Utils::OpenHandle(obj), info).ToHandle(&result);
3908 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3909 if (result->IsUndefined()) return Nothing<bool>();
3911 i::JSObject::MigrateSlowToFast(Utils::OpenHandle(obj), 0, "APISetAccessor");
3917 Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name,
3918 AccessorNameGetterCallback getter,
3919 AccessorNameSetterCallback setter,
3920 MaybeLocal<Value> data, AccessControl settings,
3921 PropertyAttribute attribute) {
3922 return ObjectSetAccessor(context, this, name, getter, setter,
3923 data.FromMaybe(Local<Value>()), settings, attribute);
3927 bool Object::SetAccessor(Local<String> name, AccessorGetterCallback getter,
3928 AccessorSetterCallback setter, v8::Local<Value> data,
3929 AccessControl settings, PropertyAttribute attributes) {
3930 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3931 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3932 attributes).FromMaybe(false);
3936 bool Object::SetAccessor(Local<Name> name, AccessorNameGetterCallback getter,
3937 AccessorNameSetterCallback setter,
3938 v8::Local<Value> data, AccessControl settings,
3939 PropertyAttribute attributes) {
3940 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3941 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3942 attributes).FromMaybe(false);
3946 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
3947 Local<Function> setter,
3948 PropertyAttribute attribute,
3949 AccessControl settings) {
3950 // TODO(verwaest): Remove |settings|.
3951 DCHECK_EQ(v8::DEFAULT, settings);
3952 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3954 i::HandleScope scope(isolate);
3955 i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
3956 i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
3957 if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
3958 i::JSObject::DefineAccessor(v8::Utils::OpenHandle(this),
3959 v8::Utils::OpenHandle(*name),
3962 static_cast<PropertyAttributes>(attribute));
3966 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
3968 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasOwnProperty()",
3970 auto self = Utils::OpenHandle(this);
3971 auto key_val = Utils::OpenHandle(*key);
3972 auto result = i::JSReceiver::HasOwnProperty(self, key_val);
3973 has_pending_exception = result.IsNothing();
3974 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3979 bool v8::Object::HasOwnProperty(Local<String> key) {
3980 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3981 return HasOwnProperty(context, key).FromMaybe(false);
3985 Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context,
3987 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasRealNamedProperty()",
3989 auto self = Utils::OpenHandle(this);
3990 auto key_val = Utils::OpenHandle(*key);
3991 auto result = i::JSObject::HasRealNamedProperty(self, key_val);
3992 has_pending_exception = result.IsNothing();
3993 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3998 bool v8::Object::HasRealNamedProperty(Local<String> key) {
3999 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4000 return HasRealNamedProperty(context, key).FromMaybe(false);
4004 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
4006 PREPARE_FOR_EXECUTION_PRIMITIVE(context,
4007 "v8::Object::HasRealIndexedProperty()", bool);
4008 auto self = Utils::OpenHandle(this);
4009 auto result = i::JSObject::HasRealElementProperty(self, index);
4010 has_pending_exception = result.IsNothing();
4011 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4016 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
4017 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4018 return HasRealIndexedProperty(context, index).FromMaybe(false);
4022 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
4024 PREPARE_FOR_EXECUTION_PRIMITIVE(
4025 context, "v8::Object::HasRealNamedCallbackProperty()", bool);
4026 auto self = Utils::OpenHandle(this);
4027 auto key_val = Utils::OpenHandle(*key);
4028 auto result = i::JSObject::HasRealNamedCallbackProperty(self, key_val);
4029 has_pending_exception = result.IsNothing();
4030 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4035 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) {
4036 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4037 return HasRealNamedCallbackProperty(context, key).FromMaybe(false);
4041 bool v8::Object::HasNamedLookupInterceptor() {
4042 auto self = Utils::OpenHandle(this);
4043 return self->HasNamedInterceptor();
4047 bool v8::Object::HasIndexedLookupInterceptor() {
4048 auto self = Utils::OpenHandle(this);
4049 return self->HasIndexedInterceptor();
4053 MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4054 Local<Context> context, Local<Name> key) {
4055 PREPARE_FOR_EXECUTION(
4056 context, "v8::Object::GetRealNamedPropertyInPrototypeChain()", Value);
4057 auto self = Utils::OpenHandle(this);
4058 auto key_obj = Utils::OpenHandle(*key);
4059 i::PrototypeIterator iter(isolate, self);
4060 if (iter.IsAtEnd()) return MaybeLocal<Value>();
4061 auto proto = i::PrototypeIterator::GetCurrent(iter);
4062 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4063 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4064 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4065 Local<Value> result;
4066 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4067 RETURN_ON_FAILED_EXECUTION(Value);
4068 if (!it.IsFound()) return MaybeLocal<Value>();
4069 RETURN_ESCAPED(result);
4073 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4074 Local<String> key) {
4075 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4076 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedPropertyInPrototypeChain(context, key),
4081 Maybe<PropertyAttribute>
4082 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(
4083 Local<Context> context, Local<Name> key) {
4084 PREPARE_FOR_EXECUTION_PRIMITIVE(
4085 context, "v8::Object::GetRealNamedPropertyAttributesInPrototypeChain()",
4087 auto self = Utils::OpenHandle(this);
4088 auto key_obj = Utils::OpenHandle(*key);
4089 i::PrototypeIterator iter(isolate, self);
4090 if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
4091 auto proto = i::PrototypeIterator::GetCurrent(iter);
4092 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4093 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4094 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4095 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4096 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4097 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4098 if (result.FromJust() == ABSENT) {
4099 return Just(static_cast<PropertyAttribute>(NONE));
4101 return Just<PropertyAttribute>(
4102 static_cast<PropertyAttribute>(result.FromJust()));
4106 Maybe<PropertyAttribute>
4107 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(Local<String> key) {
4108 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4109 return GetRealNamedPropertyAttributesInPrototypeChain(context, key);
4113 MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context,
4115 PREPARE_FOR_EXECUTION(context, "v8::Object::GetRealNamedProperty()", Value);
4116 auto self = Utils::OpenHandle(this);
4117 auto key_obj = Utils::OpenHandle(*key);
4118 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4119 isolate, self, key_obj,
4120 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4121 Local<Value> result;
4122 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4123 RETURN_ON_FAILED_EXECUTION(Value);
4124 if (!it.IsFound()) return MaybeLocal<Value>();
4125 RETURN_ESCAPED(result);
4129 Local<Value> v8::Object::GetRealNamedProperty(Local<String> key) {
4130 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4131 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedProperty(context, key), Value);
4135 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4136 Local<Context> context, Local<Name> key) {
4137 PREPARE_FOR_EXECUTION_PRIMITIVE(
4138 context, "v8::Object::GetRealNamedPropertyAttributes()",
4140 auto self = Utils::OpenHandle(this);
4141 auto key_obj = Utils::OpenHandle(*key);
4142 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4143 isolate, self, key_obj,
4144 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4145 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4146 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4147 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4148 if (result.FromJust() == ABSENT) {
4149 return Just(static_cast<PropertyAttribute>(NONE));
4151 return Just<PropertyAttribute>(
4152 static_cast<PropertyAttribute>(result.FromJust()));
4156 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4157 Local<String> key) {
4158 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4159 return GetRealNamedPropertyAttributes(context, key);
4163 Local<v8::Object> v8::Object::Clone() {
4164 auto self = Utils::OpenHandle(this);
4165 auto isolate = self->GetIsolate();
4167 auto result = isolate->factory()->CopyJSObject(self);
4168 CHECK(!result.is_null());
4169 return Utils::ToLocal(result);
4173 Local<v8::Context> v8::Object::CreationContext() {
4174 auto self = Utils::OpenHandle(this);
4175 auto context = handle(self->GetCreationContext());
4176 return Utils::ToLocal(context);
4180 int v8::Object::GetIdentityHash() {
4181 auto isolate = Utils::OpenHandle(this)->GetIsolate();
4182 i::HandleScope scope(isolate);
4183 auto self = Utils::OpenHandle(this);
4184 return i::JSReceiver::GetOrCreateIdentityHash(self)->value();
4188 bool v8::Object::SetHiddenValue(v8::Local<v8::String> key,
4189 v8::Local<v8::Value> value) {
4190 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4191 if (value.IsEmpty()) return DeleteHiddenValue(key);
4193 i::HandleScope scope(isolate);
4194 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4195 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4196 i::Handle<i::String> key_string =
4197 isolate->factory()->InternalizeString(key_obj);
4198 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4199 i::Handle<i::Object> result =
4200 i::JSObject::SetHiddenProperty(self, key_string, value_obj);
4201 return *result == *self;
4205 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Local<v8::String> key) {
4206 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4208 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4209 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4210 i::Handle<i::String> key_string =
4211 isolate->factory()->InternalizeString(key_obj);
4212 i::Handle<i::Object> result(self->GetHiddenProperty(key_string), isolate);
4213 if (result->IsTheHole()) return v8::Local<v8::Value>();
4214 return Utils::ToLocal(result);
4218 bool v8::Object::DeleteHiddenValue(v8::Local<v8::String> key) {
4219 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4221 i::HandleScope scope(isolate);
4222 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4223 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4224 i::Handle<i::String> key_string =
4225 isolate->factory()->InternalizeString(key_obj);
4226 i::JSObject::DeleteHiddenProperty(self, key_string);
4231 bool v8::Object::IsCallable() {
4232 auto self = Utils::OpenHandle(this);
4233 return self->IsCallable();
4237 MaybeLocal<Value> Object::CallAsFunction(Local<Context> context,
4238 Local<Value> recv, int argc,
4239 Local<Value> argv[]) {
4240 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Object::CallAsFunction()",
4242 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4243 auto self = Utils::OpenHandle(this);
4244 auto recv_obj = Utils::OpenHandle(*recv);
4245 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4246 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4247 i::Handle<i::JSFunction> fun;
4248 if (self->IsJSFunction()) {
4249 fun = i::Handle<i::JSFunction>::cast(self);
4251 has_pending_exception =
4252 !i::Execution::GetFunctionDelegate(isolate, self).ToHandle(&fun);
4253 RETURN_ON_FAILED_EXECUTION(Value);
4256 Local<Value> result;
4257 has_pending_exception = !ToLocal<Value>(
4258 i::Execution::Call(isolate, fun, recv_obj, argc, args), &result);
4259 RETURN_ON_FAILED_EXECUTION(Value);
4260 RETURN_ESCAPED(result);
4264 Local<v8::Value> Object::CallAsFunction(v8::Local<v8::Value> recv, int argc,
4265 v8::Local<v8::Value> argv[]) {
4266 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4267 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4268 RETURN_TO_LOCAL_UNCHECKED(CallAsFunction(context, recv, argc, argv_cast),
4273 MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc,
4274 Local<Value> argv[]) {
4275 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context,
4276 "v8::Object::CallAsConstructor()", Value);
4277 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4278 auto self = Utils::OpenHandle(this);
4279 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4280 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4281 if (self->IsJSFunction()) {
4282 auto fun = i::Handle<i::JSFunction>::cast(self);
4283 Local<Value> result;
4284 has_pending_exception =
4285 !ToLocal<Value>(i::Execution::New(fun, argc, args), &result);
4286 RETURN_ON_FAILED_EXECUTION(Value);
4287 RETURN_ESCAPED(result);
4289 i::Handle<i::JSFunction> fun;
4290 has_pending_exception =
4291 !i::Execution::GetConstructorDelegate(isolate, self).ToHandle(&fun);
4292 RETURN_ON_FAILED_EXECUTION(Value);
4293 Local<Value> result;
4294 has_pending_exception = !ToLocal<Value>(
4295 i::Execution::Call(isolate, fun, self, argc, args), &result);
4296 RETURN_ON_FAILED_EXECUTION(Value);
4297 RETURN_ESCAPED(result);
4301 Local<v8::Value> Object::CallAsConstructor(int argc,
4302 v8::Local<v8::Value> argv[]) {
4303 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4304 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4305 RETURN_TO_LOCAL_UNCHECKED(CallAsConstructor(context, argc, argv_cast), Value);
4309 MaybeLocal<Function> Function::New(Local<Context> context,
4310 FunctionCallback callback, Local<Value> data,
4312 i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
4313 LOG_API(isolate, "Function::New");
4315 return FunctionTemplateNew(isolate, callback, data, Local<Signature>(),
4316 length, true)->GetFunction(context);
4320 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback,
4321 Local<Value> data, int length) {
4322 return Function::New(v8_isolate->GetCurrentContext(), callback, data, length)
4323 .FromMaybe(Local<Function>());
4327 Local<v8::Object> Function::NewInstance() const {
4328 return NewInstance(Isolate::GetCurrent()->GetCurrentContext(), 0, NULL)
4329 .FromMaybe(Local<Object>());
4333 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
4334 v8::Local<v8::Value> argv[]) const {
4335 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::NewInstance()",
4337 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4338 auto self = Utils::OpenHandle(this);
4339 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4340 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4341 Local<Object> result;
4342 has_pending_exception =
4343 !ToLocal<Object>(i::Execution::New(self, argc, args), &result);
4344 RETURN_ON_FAILED_EXECUTION(Object);
4345 RETURN_ESCAPED(result);
4349 Local<v8::Object> Function::NewInstance(int argc,
4350 v8::Local<v8::Value> argv[]) const {
4351 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4352 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context, argc, argv), Object);
4356 MaybeLocal<v8::Value> Function::Call(Local<Context> context,
4357 v8::Local<v8::Value> recv, int argc,
4358 v8::Local<v8::Value> argv[]) {
4359 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::Call()", Value);
4360 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4361 auto self = Utils::OpenHandle(this);
4362 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
4363 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4364 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4365 Local<Value> result;
4366 has_pending_exception = !ToLocal<Value>(
4367 i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
4368 RETURN_ON_FAILED_EXECUTION(Value);
4369 RETURN_ESCAPED(result);
4373 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc,
4374 v8::Local<v8::Value> argv[]) {
4375 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4376 RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value);
4380 void Function::SetName(v8::Local<v8::String> name) {
4381 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4382 func->shared()->set_name(*Utils::OpenHandle(*name));
4386 Local<Value> Function::GetName() const {
4387 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4388 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name(),
4389 func->GetIsolate()));
4393 Local<Value> Function::GetInferredName() const {
4394 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4395 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
4396 func->GetIsolate()));
4400 Local<Value> Function::GetDisplayName() const {
4401 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4403 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4404 i::Handle<i::String> property_name =
4405 isolate->factory()->NewStringFromStaticChars("displayName");
4406 i::Handle<i::Object> value =
4407 i::JSReceiver::GetDataProperty(func, property_name);
4408 if (value->IsString()) {
4409 i::Handle<i::String> name = i::Handle<i::String>::cast(value);
4410 if (name->length() > 0) return Utils::ToLocal(name);
4412 return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
4416 ScriptOrigin Function::GetScriptOrigin() const {
4417 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4418 if (func->shared()->script()->IsScript()) {
4419 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4420 return GetScriptOriginForScript(func->GetIsolate(), script);
4422 return v8::ScriptOrigin(Local<Value>());
4426 const int Function::kLineOffsetNotFound = -1;
4429 int Function::GetScriptLineNumber() const {
4430 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4431 if (func->shared()->script()->IsScript()) {
4432 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4433 return i::Script::GetLineNumber(script, func->shared()->start_position());
4435 return kLineOffsetNotFound;
4439 int Function::GetScriptColumnNumber() const {
4440 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4441 if (func->shared()->script()->IsScript()) {
4442 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4443 return i::Script::GetColumnNumber(script, func->shared()->start_position());
4445 return kLineOffsetNotFound;
4449 bool Function::IsBuiltin() const {
4450 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4451 return func->IsBuiltin();
4455 int Function::ScriptId() const {
4456 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4457 if (!func->shared()->script()->IsScript()) {
4458 return v8::UnboundScript::kNoScriptId;
4460 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4461 return script->id()->value();
4465 Local<v8::Value> Function::GetBoundFunction() const {
4466 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4467 if (!func->shared()->bound()) {
4468 return v8::Undefined(reinterpret_cast<v8::Isolate*>(func->GetIsolate()));
4470 i::Handle<i::FixedArray> bound_args = i::Handle<i::FixedArray>(
4471 i::FixedArray::cast(func->function_bindings()));
4472 i::Handle<i::Object> original(
4473 bound_args->get(i::JSFunction::kBoundFunctionIndex),
4474 func->GetIsolate());
4475 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(original));
4479 int Name::GetIdentityHash() {
4480 auto self = Utils::OpenHandle(this);
4481 return static_cast<int>(self->Hash());
4485 int String::Length() const {
4486 i::Handle<i::String> str = Utils::OpenHandle(this);
4487 return str->length();
4491 bool String::IsOneByte() const {
4492 i::Handle<i::String> str = Utils::OpenHandle(this);
4493 return str->HasOnlyOneByteChars();
4497 // Helpers for ContainsOnlyOneByteHelper
4498 template<size_t size> struct OneByteMask;
4499 template<> struct OneByteMask<4> {
4500 static const uint32_t value = 0xFF00FF00;
4502 template<> struct OneByteMask<8> {
4503 static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
4505 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
4506 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
4507 static inline bool Unaligned(const uint16_t* chars) {
4508 return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
4512 static inline const uint16_t* Align(const uint16_t* chars) {
4513 return reinterpret_cast<uint16_t*>(
4514 reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
4517 class ContainsOnlyOneByteHelper {
4519 ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
4520 bool Check(i::String* string) {
4521 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
4522 if (cons_string == NULL) return is_one_byte_;
4523 return CheckCons(cons_string);
4525 void VisitOneByteString(const uint8_t* chars, int length) {
4528 void VisitTwoByteString(const uint16_t* chars, int length) {
4529 // Accumulated bits.
4531 // Align to uintptr_t.
4532 const uint16_t* end = chars + length;
4533 while (Unaligned(chars) && chars != end) {
4536 // Read word aligned in blocks,
4537 // checking the return value at the end of each block.
4538 const uint16_t* aligned_end = Align(end);
4539 const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
4540 const int inner_loops = 16;
4541 while (chars + inner_loops*increment < aligned_end) {
4542 for (int i = 0; i < inner_loops; i++) {
4543 acc |= *reinterpret_cast<const uintptr_t*>(chars);
4546 // Check for early return.
4547 if ((acc & kOneByteMask) != 0) {
4548 is_one_byte_ = false;
4553 while (chars != end) {
4557 if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
4561 bool CheckCons(i::ConsString* cons_string) {
4563 // Check left side if flat.
4564 i::String* left = cons_string->first();
4565 i::ConsString* left_as_cons =
4566 i::String::VisitFlat(this, left, 0);
4567 if (!is_one_byte_) return false;
4568 // Check right side if flat.
4569 i::String* right = cons_string->second();
4570 i::ConsString* right_as_cons =
4571 i::String::VisitFlat(this, right, 0);
4572 if (!is_one_byte_) return false;
4573 // Standard recurse/iterate trick.
4574 if (left_as_cons != NULL && right_as_cons != NULL) {
4575 if (left->length() < right->length()) {
4576 CheckCons(left_as_cons);
4577 cons_string = right_as_cons;
4579 CheckCons(right_as_cons);
4580 cons_string = left_as_cons;
4582 // Check fast return.
4583 if (!is_one_byte_) return false;
4586 // Descend left in place.
4587 if (left_as_cons != NULL) {
4588 cons_string = left_as_cons;
4591 // Descend right in place.
4592 if (right_as_cons != NULL) {
4593 cons_string = right_as_cons;
4599 return is_one_byte_;
4602 DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
4606 bool String::ContainsOnlyOneByte() const {
4607 i::Handle<i::String> str = Utils::OpenHandle(this);
4608 if (str->HasOnlyOneByteChars()) return true;
4609 ContainsOnlyOneByteHelper helper;
4610 return helper.Check(*str);
4614 class Utf8LengthHelper : public i::AllStatic {
4617 kEndsWithLeadingSurrogate = 1 << 0,
4618 kStartsWithTrailingSurrogate = 1 << 1,
4619 kLeftmostEdgeIsCalculated = 1 << 2,
4620 kRightmostEdgeIsCalculated = 1 << 3,
4621 kLeftmostEdgeIsSurrogate = 1 << 4,
4622 kRightmostEdgeIsSurrogate = 1 << 5
4625 static const uint8_t kInitialState = 0;
4627 static inline bool EndsWithSurrogate(uint8_t state) {
4628 return state & kEndsWithLeadingSurrogate;
4631 static inline bool StartsWithSurrogate(uint8_t state) {
4632 return state & kStartsWithTrailingSurrogate;
4637 Visitor() : utf8_length_(0), state_(kInitialState) {}
4639 void VisitOneByteString(const uint8_t* chars, int length) {
4640 int utf8_length = 0;
4641 // Add in length 1 for each non-Latin1 character.
4642 for (int i = 0; i < length; i++) {
4643 utf8_length += *chars++ >> 7;
4645 // Add in length 1 for each character.
4646 utf8_length_ = utf8_length + length;
4647 state_ = kInitialState;
4650 void VisitTwoByteString(const uint16_t* chars, int length) {
4651 int utf8_length = 0;
4652 int last_character = unibrow::Utf16::kNoPreviousCharacter;
4653 for (int i = 0; i < length; i++) {
4654 uint16_t c = chars[i];
4655 utf8_length += unibrow::Utf8::Length(c, last_character);
4658 utf8_length_ = utf8_length;
4660 if (unibrow::Utf16::IsTrailSurrogate(chars[0])) {
4661 state |= kStartsWithTrailingSurrogate;
4663 if (unibrow::Utf16::IsLeadSurrogate(chars[length-1])) {
4664 state |= kEndsWithLeadingSurrogate;
4669 static i::ConsString* VisitFlat(i::String* string,
4673 i::ConsString* cons_string = i::String::VisitFlat(&visitor, string);
4674 *length = visitor.utf8_length_;
4675 *state = visitor.state_;
4682 DISALLOW_COPY_AND_ASSIGN(Visitor);
4685 static inline void MergeLeafLeft(int* length,
4687 uint8_t leaf_state) {
4688 bool edge_surrogate = StartsWithSurrogate(leaf_state);
4689 if (!(*state & kLeftmostEdgeIsCalculated)) {
4690 DCHECK(!(*state & kLeftmostEdgeIsSurrogate));
4691 *state |= kLeftmostEdgeIsCalculated
4692 | (edge_surrogate ? kLeftmostEdgeIsSurrogate : 0);
4693 } else if (EndsWithSurrogate(*state) && edge_surrogate) {
4694 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4696 if (EndsWithSurrogate(leaf_state)) {
4697 *state |= kEndsWithLeadingSurrogate;
4699 *state &= ~kEndsWithLeadingSurrogate;
4703 static inline void MergeLeafRight(int* length,
4705 uint8_t leaf_state) {
4706 bool edge_surrogate = EndsWithSurrogate(leaf_state);
4707 if (!(*state & kRightmostEdgeIsCalculated)) {
4708 DCHECK(!(*state & kRightmostEdgeIsSurrogate));
4709 *state |= (kRightmostEdgeIsCalculated
4710 | (edge_surrogate ? kRightmostEdgeIsSurrogate : 0));
4711 } else if (edge_surrogate && StartsWithSurrogate(*state)) {
4712 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4714 if (StartsWithSurrogate(leaf_state)) {
4715 *state |= kStartsWithTrailingSurrogate;
4717 *state &= ~kStartsWithTrailingSurrogate;
4721 static inline void MergeTerminal(int* length,
4723 uint8_t* state_out) {
4724 DCHECK((state & kLeftmostEdgeIsCalculated) &&
4725 (state & kRightmostEdgeIsCalculated));
4726 if (EndsWithSurrogate(state) && StartsWithSurrogate(state)) {
4727 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4729 *state_out = kInitialState |
4730 (state & kLeftmostEdgeIsSurrogate ? kStartsWithTrailingSurrogate : 0) |
4731 (state & kRightmostEdgeIsSurrogate ? kEndsWithLeadingSurrogate : 0);
4734 static int Calculate(i::ConsString* current, uint8_t* state_out) {
4735 using namespace internal;
4736 int total_length = 0;
4737 uint8_t state = kInitialState;
4739 i::String* left = current->first();
4740 i::String* right = current->second();
4741 uint8_t right_leaf_state;
4742 uint8_t left_leaf_state;
4744 ConsString* left_as_cons =
4745 Visitor::VisitFlat(left, &leaf_length, &left_leaf_state);
4746 if (left_as_cons == NULL) {
4747 total_length += leaf_length;
4748 MergeLeafLeft(&total_length, &state, left_leaf_state);
4750 ConsString* right_as_cons =
4751 Visitor::VisitFlat(right, &leaf_length, &right_leaf_state);
4752 if (right_as_cons == NULL) {
4753 total_length += leaf_length;
4754 MergeLeafRight(&total_length, &state, right_leaf_state);
4755 if (left_as_cons != NULL) {
4756 // 1 Leaf node. Descend in place.
4757 current = left_as_cons;
4761 MergeTerminal(&total_length, state, state_out);
4762 return total_length;
4764 } else if (left_as_cons == NULL) {
4765 // 1 Leaf node. Descend in place.
4766 current = right_as_cons;
4769 // Both strings are ConsStrings.
4770 // Recurse on smallest.
4771 if (left->length() < right->length()) {
4772 total_length += Calculate(left_as_cons, &left_leaf_state);
4773 MergeLeafLeft(&total_length, &state, left_leaf_state);
4774 current = right_as_cons;
4776 total_length += Calculate(right_as_cons, &right_leaf_state);
4777 MergeLeafRight(&total_length, &state, right_leaf_state);
4778 current = left_as_cons;
4785 static inline int Calculate(i::ConsString* current) {
4786 uint8_t state = kInitialState;
4787 return Calculate(current, &state);
4791 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8LengthHelper);
4795 static int Utf8Length(i::String* str, i::Isolate* isolate) {
4796 int length = str->length();
4797 if (length == 0) return 0;
4799 i::ConsString* cons_string =
4800 Utf8LengthHelper::Visitor::VisitFlat(str, &length, &state);
4801 if (cons_string == NULL) return length;
4802 return Utf8LengthHelper::Calculate(cons_string);
4806 int String::Utf8Length() const {
4807 i::Handle<i::String> str = Utils::OpenHandle(this);
4808 i::Isolate* isolate = str->GetIsolate();
4809 return v8::Utf8Length(*str, isolate);
4813 class Utf8WriterVisitor {
4818 bool skip_capacity_check,
4819 bool replace_invalid_utf8)
4820 : early_termination_(false),
4821 last_character_(unibrow::Utf16::kNoPreviousCharacter),
4824 capacity_(capacity),
4825 skip_capacity_check_(capacity == -1 || skip_capacity_check),
4826 replace_invalid_utf8_(replace_invalid_utf8),
4827 utf16_chars_read_(0) {
4830 static int WriteEndCharacter(uint16_t character,
4834 bool replace_invalid_utf8) {
4835 using namespace unibrow;
4836 DCHECK(remaining > 0);
4837 // We can't use a local buffer here because Encode needs to modify
4838 // previous characters in the stream. We know, however, that
4839 // exactly one character will be advanced.
4840 if (Utf16::IsSurrogatePair(last_character, character)) {
4841 int written = Utf8::Encode(buffer,
4844 replace_invalid_utf8);
4845 DCHECK(written == 1);
4848 // Use a scratch buffer to check the required characters.
4849 char temp_buffer[Utf8::kMaxEncodedSize];
4850 // Can't encode using last_character as gcc has array bounds issues.
4851 int written = Utf8::Encode(temp_buffer,
4853 Utf16::kNoPreviousCharacter,
4854 replace_invalid_utf8);
4856 if (written > remaining) return 0;
4857 // Copy over the character from temp_buffer.
4858 for (int j = 0; j < written; j++) {
4859 buffer[j] = temp_buffer[j];
4864 // Visit writes out a group of code units (chars) of a v8::String to the
4865 // internal buffer_. This is done in two phases. The first phase calculates a
4866 // pesimistic estimate (writable_length) on how many code units can be safely
4867 // written without exceeding the buffer capacity and without writing the last
4868 // code unit (it could be a lead surrogate). The estimated number of code
4869 // units is then written out in one go, and the reported byte usage is used
4870 // to correct the estimate. This is repeated until the estimate becomes <= 0
4871 // or all code units have been written out. The second phase writes out code
4872 // units until the buffer capacity is reached, would be exceeded by the next
4873 // unit, or all units have been written out.
4874 template<typename Char>
4875 void Visit(const Char* chars, const int length) {
4876 using namespace unibrow;
4877 DCHECK(!early_termination_);
4878 if (length == 0) return;
4879 // Copy state to stack.
4880 char* buffer = buffer_;
4881 int last_character =
4882 sizeof(Char) == 1 ? Utf16::kNoPreviousCharacter : last_character_;
4884 // Do a fast loop where there is no exit capacity check.
4887 if (skip_capacity_check_) {
4888 fast_length = length;
4890 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4891 // Need enough space to write everything but one character.
4892 STATIC_ASSERT(Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 3);
4893 int max_size_per_char = sizeof(Char) == 1 ? 2 : 3;
4894 int writable_length =
4895 (remaining_capacity - max_size_per_char)/max_size_per_char;
4896 // Need to drop into slow loop.
4897 if (writable_length <= 0) break;
4898 fast_length = i + writable_length;
4899 if (fast_length > length) fast_length = length;
4901 // Write the characters to the stream.
4902 if (sizeof(Char) == 1) {
4903 for (; i < fast_length; i++) {
4905 Utf8::EncodeOneByte(buffer, static_cast<uint8_t>(*chars++));
4906 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4909 for (; i < fast_length; i++) {
4910 uint16_t character = *chars++;
4911 buffer += Utf8::Encode(buffer,
4914 replace_invalid_utf8_);
4915 last_character = character;
4916 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4919 // Array is fully written. Exit.
4920 if (fast_length == length) {
4921 // Write state back out to object.
4922 last_character_ = last_character;
4924 utf16_chars_read_ += length;
4928 DCHECK(!skip_capacity_check_);
4929 // Slow loop. Must check capacity on each iteration.
4930 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4931 DCHECK(remaining_capacity >= 0);
4932 for (; i < length && remaining_capacity > 0; i++) {
4933 uint16_t character = *chars++;
4934 // remaining_capacity is <= 3 bytes at this point, so we do not write out
4935 // an umatched lead surrogate.
4936 if (replace_invalid_utf8_ && Utf16::IsLeadSurrogate(character)) {
4937 early_termination_ = true;
4940 int written = WriteEndCharacter(character,
4944 replace_invalid_utf8_);
4946 early_termination_ = true;
4950 remaining_capacity -= written;
4951 last_character = character;
4953 // Write state back out to object.
4954 last_character_ = last_character;
4956 utf16_chars_read_ += i;
4959 inline bool IsDone() {
4960 return early_termination_;
4963 inline void VisitOneByteString(const uint8_t* chars, int length) {
4964 Visit(chars, length);
4967 inline void VisitTwoByteString(const uint16_t* chars, int length) {
4968 Visit(chars, length);
4971 int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
4972 // Write out number of utf16 characters written to the stream.
4973 if (utf16_chars_read_out != NULL) {
4974 *utf16_chars_read_out = utf16_chars_read_;
4976 // Only null terminate if all of the string was written and there's space.
4978 !early_termination_ &&
4979 (capacity_ == -1 || (buffer_ - start_) < capacity_)) {
4982 return static_cast<int>(buffer_ - start_);
4986 bool early_termination_;
4987 int last_character_;
4991 bool const skip_capacity_check_;
4992 bool const replace_invalid_utf8_;
4993 int utf16_chars_read_;
4994 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
4998 static bool RecursivelySerializeToUtf8(i::String* current,
4999 Utf8WriterVisitor* writer,
5000 int recursion_budget) {
5001 while (!writer->IsDone()) {
5002 i::ConsString* cons_string = i::String::VisitFlat(writer, current);
5003 if (cons_string == NULL) return true; // Leaf node.
5004 if (recursion_budget <= 0) return false;
5005 // Must write the left branch first.
5006 i::String* first = cons_string->first();
5007 bool success = RecursivelySerializeToUtf8(first,
5009 recursion_budget - 1);
5010 if (!success) return false;
5011 // Inline tail recurse for right branch.
5012 current = cons_string->second();
5018 int String::WriteUtf8(char* buffer,
5021 int options) const {
5022 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
5023 LOG_API(isolate, "String::WriteUtf8");
5025 i::Handle<i::String> str = Utils::OpenHandle(this);
5026 if (options & HINT_MANY_WRITES_EXPECTED) {
5027 str = i::String::Flatten(str); // Flatten the string for efficiency.
5029 const int string_length = str->length();
5030 bool write_null = !(options & NO_NULL_TERMINATION);
5031 bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
5032 int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
5033 // First check if we can just write the string without checking capacity.
5034 if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
5035 Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
5036 const int kMaxRecursion = 100;
5037 bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
5038 if (success) return writer.CompleteWrite(write_null, nchars_ref);
5039 } else if (capacity >= string_length) {
5040 // First check that the buffer is large enough.
5041 int utf8_bytes = v8::Utf8Length(*str, str->GetIsolate());
5042 if (utf8_bytes <= capacity) {
5043 // one-byte fast path.
5044 if (utf8_bytes == string_length) {
5045 WriteOneByte(reinterpret_cast<uint8_t*>(buffer), 0, capacity, options);
5046 if (nchars_ref != NULL) *nchars_ref = string_length;
5047 if (write_null && (utf8_bytes+1 <= capacity)) {
5048 return string_length + 1;
5050 return string_length;
5052 if (write_null && (utf8_bytes+1 > capacity)) {
5053 options |= NO_NULL_TERMINATION;
5055 // Recurse once without a capacity limit.
5056 // This will get into the first branch above.
5057 // TODO(dcarney) Check max left rec. in Utf8Length and fall through.
5058 return WriteUtf8(buffer, -1, nchars_ref, options);
5061 // Recursive slow path can potentially be unreasonable slow. Flatten.
5062 str = i::String::Flatten(str);
5063 Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
5064 i::String::VisitFlat(&writer, *str);
5065 return writer.CompleteWrite(write_null, nchars_ref);
5069 template<typename CharType>
5070 static inline int WriteHelper(const String* string,
5075 i::Isolate* isolate = Utils::OpenHandle(string)->GetIsolate();
5076 LOG_API(isolate, "String::Write");
5078 DCHECK(start >= 0 && length >= -1);
5079 i::Handle<i::String> str = Utils::OpenHandle(string);
5080 if (options & String::HINT_MANY_WRITES_EXPECTED) {
5081 // Flatten the string for efficiency. This applies whether we are
5082 // using StringCharacterStream or Get(i) to access the characters.
5083 str = i::String::Flatten(str);
5085 int end = start + length;
5086 if ((length == -1) || (length > str->length() - start) )
5087 end = str->length();
5088 if (end < 0) return 0;
5089 i::String::WriteToFlat(*str, buffer, start, end);
5090 if (!(options & String::NO_NULL_TERMINATION) &&
5091 (length == -1 || end - start < length)) {
5092 buffer[end - start] = '\0';
5098 int String::WriteOneByte(uint8_t* buffer,
5101 int options) const {
5102 return WriteHelper(this, buffer, start, length, options);
5106 int String::Write(uint16_t* buffer,
5109 int options) const {
5110 return WriteHelper(this, buffer, start, length, options);
5114 bool v8::String::IsExternal() const {
5115 i::Handle<i::String> str = Utils::OpenHandle(this);
5116 return i::StringShape(*str).IsExternalTwoByte();
5120 bool v8::String::IsExternalOneByte() const {
5121 i::Handle<i::String> str = Utils::OpenHandle(this);
5122 return i::StringShape(*str).IsExternalOneByte();
5126 void v8::String::VerifyExternalStringResource(
5127 v8::String::ExternalStringResource* value) const {
5128 i::Handle<i::String> str = Utils::OpenHandle(this);
5129 const v8::String::ExternalStringResource* expected;
5130 if (i::StringShape(*str).IsExternalTwoByte()) {
5131 const void* resource =
5132 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5133 expected = reinterpret_cast<const ExternalStringResource*>(resource);
5137 CHECK_EQ(expected, value);
5140 void v8::String::VerifyExternalStringResourceBase(
5141 v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
5142 i::Handle<i::String> str = Utils::OpenHandle(this);
5143 const v8::String::ExternalStringResourceBase* expected;
5144 Encoding expectedEncoding;
5145 if (i::StringShape(*str).IsExternalOneByte()) {
5146 const void* resource =
5147 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5148 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5149 expectedEncoding = ONE_BYTE_ENCODING;
5150 } else if (i::StringShape(*str).IsExternalTwoByte()) {
5151 const void* resource =
5152 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5153 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5154 expectedEncoding = TWO_BYTE_ENCODING;
5158 str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
5160 CHECK_EQ(expected, value);
5161 CHECK_EQ(expectedEncoding, encoding);
5164 const v8::String::ExternalOneByteStringResource*
5165 v8::String::GetExternalOneByteStringResource() const {
5166 i::Handle<i::String> str = Utils::OpenHandle(this);
5167 if (i::StringShape(*str).IsExternalOneByte()) {
5168 const void* resource =
5169 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5170 return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
5177 Local<Value> Symbol::Name() const {
5178 i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
5179 i::Handle<i::Object> name(sym->name(), sym->GetIsolate());
5180 return Utils::ToLocal(name);
5184 double Number::Value() const {
5185 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5186 return obj->Number();
5190 bool Boolean::Value() const {
5191 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5192 return obj->IsTrue();
5196 int64_t Integer::Value() const {
5197 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5199 return i::Smi::cast(*obj)->value();
5201 return static_cast<int64_t>(obj->Number());
5206 int32_t Int32::Value() const {
5207 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5209 return i::Smi::cast(*obj)->value();
5211 return static_cast<int32_t>(obj->Number());
5216 uint32_t Uint32::Value() const {
5217 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5219 return i::Smi::cast(*obj)->value();
5221 return static_cast<uint32_t>(obj->Number());
5226 int v8::Object::InternalFieldCount() {
5227 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5228 return obj->GetInternalFieldCount();
5232 static bool InternalFieldOK(i::Handle<i::JSObject> obj,
5234 const char* location) {
5235 return Utils::ApiCheck(index < obj->GetInternalFieldCount(),
5237 "Internal field out of bounds");
5241 Local<Value> v8::Object::SlowGetInternalField(int index) {
5242 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5243 const char* location = "v8::Object::GetInternalField()";
5244 if (!InternalFieldOK(obj, index, location)) return Local<Value>();
5245 i::Handle<i::Object> value(obj->GetInternalField(index), obj->GetIsolate());
5246 return Utils::ToLocal(value);
5250 void v8::Object::SetInternalField(int index, v8::Local<Value> value) {
5251 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5252 const char* location = "v8::Object::SetInternalField()";
5253 if (!InternalFieldOK(obj, index, location)) return;
5254 i::Handle<i::Object> val = Utils::OpenHandle(*value);
5255 obj->SetInternalField(index, *val);
5259 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
5260 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5261 const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
5262 if (!InternalFieldOK(obj, index, location)) return NULL;
5263 return DecodeSmiToAligned(obj->GetInternalField(index), location);
5267 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
5268 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5269 const char* location = "v8::Object::SetAlignedPointerInInternalField()";
5270 if (!InternalFieldOK(obj, index, location)) return;
5271 obj->SetInternalField(index, EncodeAlignedAsSmi(value, location));
5272 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
5276 static void* ExternalValue(i::Object* obj) {
5277 // Obscure semantics for undefined, but somehow checked in our unit tests...
5278 if (obj->IsUndefined()) return NULL;
5279 i::Object* foreign = i::JSObject::cast(obj)->GetInternalField(0);
5280 return i::Foreign::cast(foreign)->foreign_address();
5284 // --- E n v i r o n m e n t ---
5287 void v8::V8::InitializePlatform(Platform* platform) {
5288 i::V8::InitializePlatform(platform);
5292 void v8::V8::ShutdownPlatform() {
5293 i::V8::ShutdownPlatform();
5297 bool v8::V8::Initialize() {
5298 i::V8::Initialize();
5299 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5306 void v8::V8::SetEntropySource(EntropySource entropy_source) {
5307 base::RandomNumberGenerator::SetEntropySource(entropy_source);
5311 void v8::V8::SetReturnAddressLocationResolver(
5312 ReturnAddressLocationResolver return_address_resolver) {
5313 i::StackFrame::SetReturnAddressLocationResolver(return_address_resolver);
5317 bool v8::V8::Dispose() {
5319 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5320 i::DisposeNatives();
5326 HeapStatistics::HeapStatistics(): total_heap_size_(0),
5327 total_heap_size_executable_(0),
5328 total_physical_size_(0),
5330 heap_size_limit_(0) { }
5333 HeapSpaceStatistics::HeapSpaceStatistics(): space_name_(0),
5335 space_used_size_(0),
5336 space_available_size_(0),
5337 physical_space_size_(0) { }
5340 HeapObjectStatistics::HeapObjectStatistics()
5341 : object_type_(nullptr),
5342 object_sub_type_(nullptr),
5347 bool v8::V8::InitializeICU(const char* icu_data_file) {
5348 return i::InitializeICU(icu_data_file);
5352 void v8::V8::InitializeExternalStartupData(const char* directory_path) {
5353 i::InitializeExternalStartupData(directory_path);
5357 void v8::V8::InitializeExternalStartupData(const char* natives_blob,
5358 const char* snapshot_blob) {
5359 i::InitializeExternalStartupData(natives_blob, snapshot_blob);
5363 const char* v8::V8::GetVersion() {
5364 return i::Version::GetVersion();
5368 static i::Handle<i::Context> CreateEnvironment(
5369 i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
5370 v8::Local<ObjectTemplate> global_template,
5371 v8::Local<Value> maybe_global_proxy) {
5372 i::Handle<i::Context> env;
5374 // Enter V8 via an ENTER_V8 scope.
5377 v8::Local<ObjectTemplate> proxy_template = global_template;
5378 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
5379 i::Handle<i::FunctionTemplateInfo> global_constructor;
5381 if (!global_template.IsEmpty()) {
5382 // Make sure that the global_template has a constructor.
5383 global_constructor = EnsureConstructor(isolate, *global_template);
5385 // Create a fresh template for the global proxy object.
5386 proxy_template = ObjectTemplate::New(
5387 reinterpret_cast<v8::Isolate*>(isolate));
5388 proxy_constructor = EnsureConstructor(isolate, *proxy_template);
5390 // Set the global template to be the prototype template of
5391 // global proxy template.
5392 proxy_constructor->set_prototype_template(
5393 *Utils::OpenHandle(*global_template));
5395 // Migrate security handlers from global_template to
5396 // proxy_template. Temporarily removing access check
5397 // information from the global template.
5398 if (!global_constructor->access_check_info()->IsUndefined()) {
5399 proxy_constructor->set_access_check_info(
5400 global_constructor->access_check_info());
5401 proxy_constructor->set_needs_access_check(
5402 global_constructor->needs_access_check());
5403 global_constructor->set_needs_access_check(false);
5404 global_constructor->set_access_check_info(
5405 isolate->heap()->undefined_value());
5409 i::Handle<i::Object> proxy = Utils::OpenHandle(*maybe_global_proxy, true);
5410 i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
5411 if (!proxy.is_null()) {
5412 maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(proxy);
5414 // Create the environment.
5415 env = isolate->bootstrapper()->CreateEnvironment(
5416 maybe_proxy, proxy_template, extensions);
5418 // Restore the access check info on the global template.
5419 if (!global_template.IsEmpty()) {
5420 DCHECK(!global_constructor.is_null());
5421 DCHECK(!proxy_constructor.is_null());
5422 global_constructor->set_access_check_info(
5423 proxy_constructor->access_check_info());
5424 global_constructor->set_needs_access_check(
5425 proxy_constructor->needs_access_check());
5433 Local<Context> v8::Context::New(v8::Isolate* external_isolate,
5434 v8::ExtensionConfiguration* extensions,
5435 v8::Local<ObjectTemplate> global_template,
5436 v8::Local<Value> global_object) {
5437 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
5438 LOG_API(isolate, "Context::New");
5439 i::HandleScope scope(isolate);
5440 ExtensionConfiguration no_extensions;
5441 if (extensions == NULL) extensions = &no_extensions;
5442 i::Handle<i::Context> env =
5443 CreateEnvironment(isolate, extensions, global_template, global_object);
5444 if (env.is_null()) {
5445 if (isolate->has_pending_exception()) {
5446 isolate->OptionalRescheduleException(true);
5448 return Local<Context>();
5450 return Utils::ToLocal(scope.CloseAndEscape(env));
5454 void v8::Context::SetSecurityToken(Local<Value> token) {
5455 i::Handle<i::Context> env = Utils::OpenHandle(this);
5456 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
5457 env->set_security_token(*token_handle);
5461 void v8::Context::UseDefaultSecurityToken() {
5462 i::Handle<i::Context> env = Utils::OpenHandle(this);
5463 env->set_security_token(env->global_object());
5467 Local<Value> v8::Context::GetSecurityToken() {
5468 i::Handle<i::Context> env = Utils::OpenHandle(this);
5469 i::Isolate* isolate = env->GetIsolate();
5470 i::Object* security_token = env->security_token();
5471 i::Handle<i::Object> token_handle(security_token, isolate);
5472 return Utils::ToLocal(token_handle);
5476 v8::Isolate* Context::GetIsolate() {
5477 i::Handle<i::Context> env = Utils::OpenHandle(this);
5478 return reinterpret_cast<Isolate*>(env->GetIsolate());
5482 v8::Local<v8::Object> Context::Global() {
5483 i::Handle<i::Context> context = Utils::OpenHandle(this);
5484 i::Isolate* isolate = context->GetIsolate();
5485 i::Handle<i::Object> global(context->global_proxy(), isolate);
5486 // TODO(dcarney): This should always return the global proxy
5487 // but can't presently as calls to GetProtoype will return the wrong result.
5488 if (i::Handle<i::JSGlobalProxy>::cast(
5489 global)->IsDetachedFrom(context->global_object())) {
5490 global = i::Handle<i::Object>(context->global_object(), isolate);
5492 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
5496 void Context::DetachGlobal() {
5497 i::Handle<i::Context> context = Utils::OpenHandle(this);
5498 i::Isolate* isolate = context->GetIsolate();
5500 isolate->bootstrapper()->DetachGlobal(context);
5504 Local<v8::Object> Context::GetExtrasBindingObject() {
5505 i::Handle<i::Context> context = Utils::OpenHandle(this);
5506 i::Isolate* isolate = context->GetIsolate();
5507 i::Handle<i::JSObject> binding(context->extras_binding_object(), isolate);
5508 return Utils::ToLocal(binding);
5512 void Context::AllowCodeGenerationFromStrings(bool allow) {
5513 i::Handle<i::Context> context = Utils::OpenHandle(this);
5514 i::Isolate* isolate = context->GetIsolate();
5516 context->set_allow_code_gen_from_strings(
5517 allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
5521 bool Context::IsCodeGenerationFromStringsAllowed() {
5522 i::Handle<i::Context> context = Utils::OpenHandle(this);
5523 return !context->allow_code_gen_from_strings()->IsFalse();
5527 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
5528 i::Handle<i::Context> context = Utils::OpenHandle(this);
5529 i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
5530 context->set_error_message_for_code_gen_from_strings(*error_handle);
5534 size_t Context::EstimatedSize() {
5535 return static_cast<size_t>(
5536 i::ContextMeasure(*Utils::OpenHandle(this)).Size());
5540 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
5541 PREPARE_FOR_EXECUTION(context, "v8::ObjectTemplate::NewInstance()", Object);
5542 auto self = Utils::OpenHandle(this);
5543 Local<Object> result;
5544 has_pending_exception =
5545 !ToLocal<Object>(i::ApiNatives::InstantiateObject(self), &result);
5546 RETURN_ON_FAILED_EXECUTION(Object);
5547 RETURN_ESCAPED(result);
5551 Local<v8::Object> ObjectTemplate::NewInstance() {
5552 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5553 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object);
5557 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
5558 PREPARE_FOR_EXECUTION(context, "v8::FunctionTemplate::GetFunction()",
5560 auto self = Utils::OpenHandle(this);
5561 Local<Function> result;
5562 has_pending_exception =
5563 !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
5564 RETURN_ON_FAILED_EXECUTION(Function);
5565 RETURN_ESCAPED(result);
5569 Local<v8::Function> FunctionTemplate::GetFunction() {
5570 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5571 RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function);
5575 bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) {
5576 auto self = Utils::OpenHandle(this);
5577 auto obj = Utils::OpenHandle(*value);
5578 return self->IsTemplateFor(*obj);
5582 Local<External> v8::External::New(Isolate* isolate, void* value) {
5583 STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
5584 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5585 LOG_API(i_isolate, "External::New");
5586 ENTER_V8(i_isolate);
5587 i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
5588 return Utils::ExternalToLocal(external);
5592 void* External::Value() const {
5593 return ExternalValue(*Utils::OpenHandle(this));
5597 // anonymous namespace for string creation helper functions
5600 inline int StringLength(const char* string) {
5601 return i::StrLength(string);
5605 inline int StringLength(const uint8_t* string) {
5606 return i::StrLength(reinterpret_cast<const char*>(string));
5610 inline int StringLength(const uint16_t* string) {
5612 while (string[length] != '\0')
5619 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5620 v8::NewStringType type,
5621 i::Vector<const char> string) {
5622 if (type == v8::NewStringType::kInternalized) {
5623 return factory->InternalizeUtf8String(string);
5625 return factory->NewStringFromUtf8(string);
5630 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5631 v8::NewStringType type,
5632 i::Vector<const uint8_t> string) {
5633 if (type == v8::NewStringType::kInternalized) {
5634 return factory->InternalizeOneByteString(string);
5636 return factory->NewStringFromOneByte(string);
5641 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5642 v8::NewStringType type,
5643 i::Vector<const uint16_t> string) {
5644 if (type == v8::NewStringType::kInternalized) {
5645 return factory->InternalizeTwoByteString(string);
5647 return factory->NewStringFromTwoByte(string);
5651 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
5654 template <typename Char>
5655 inline MaybeLocal<String> NewString(Isolate* v8_isolate, const char* location,
5656 const char* env, const Char* data,
5657 v8::NewStringType type, int length) {
5658 i::Isolate* isolate = reinterpret_cast<internal::Isolate*>(v8_isolate);
5659 if (length == 0) return String::Empty(v8_isolate);
5660 // TODO(dcarney): throw a context free exception.
5661 if (length > i::String::kMaxLength) return MaybeLocal<String>();
5663 LOG_API(isolate, env);
5664 if (length < 0) length = StringLength(data);
5665 i::Handle<i::String> result =
5666 NewString(isolate->factory(), type, i::Vector<const Char>(data, length))
5668 return Utils::ToLocal(result);
5671 } // anonymous namespace
5674 Local<String> String::NewFromUtf8(Isolate* isolate,
5678 RETURN_TO_LOCAL_UNCHECKED(
5679 NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5680 data, static_cast<v8::NewStringType>(type), length),
5685 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
5686 v8::NewStringType type, int length) {
5687 return NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5688 data, type, length);
5692 Local<String> String::NewFromOneByte(Isolate* isolate,
5693 const uint8_t* data,
5696 RETURN_TO_LOCAL_UNCHECKED(
5697 NewString(isolate, "v8::String::NewFromOneByte()",
5698 "String::NewFromOneByte", data,
5699 static_cast<v8::NewStringType>(type), length),
5704 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
5705 v8::NewStringType type, int length) {
5706 return NewString(isolate, "v8::String::NewFromOneByte()",
5707 "String::NewFromOneByte", data, type, length);
5711 Local<String> String::NewFromTwoByte(Isolate* isolate,
5712 const uint16_t* data,
5715 RETURN_TO_LOCAL_UNCHECKED(
5716 NewString(isolate, "v8::String::NewFromTwoByte()",
5717 "String::NewFromTwoByte", data,
5718 static_cast<v8::NewStringType>(type), length),
5723 MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate,
5724 const uint16_t* data,
5725 v8::NewStringType type, int length) {
5726 return NewString(isolate, "v8::String::NewFromTwoByte()",
5727 "String::NewFromTwoByte", data, type, length);
5731 Local<String> v8::String::Concat(Local<String> left, Local<String> right) {
5732 i::Handle<i::String> left_string = Utils::OpenHandle(*left);
5733 i::Isolate* isolate = left_string->GetIsolate();
5735 LOG_API(isolate, "v8::String::Concat");
5736 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
5737 // If we are steering towards a range error, do not wait for the error to be
5738 // thrown, and return the null handle instead.
5739 if (left_string->length() + right_string->length() > i::String::kMaxLength) {
5740 return Local<String>();
5742 i::Handle<i::String> result = isolate->factory()->NewConsString(
5743 left_string, right_string).ToHandleChecked();
5744 return Utils::ToLocal(result);
5748 MaybeLocal<String> v8::String::NewExternalTwoByte(
5749 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5750 CHECK(resource && resource->data());
5751 // TODO(dcarney): throw a context free exception.
5752 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5753 return MaybeLocal<String>();
5755 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5756 ENTER_V8(i_isolate);
5757 LOG_API(i_isolate, "String::NewExternalTwoByte");
5758 i::Handle<i::String> string = i_isolate->factory()
5759 ->NewExternalStringFromTwoByte(resource)
5761 i_isolate->heap()->RegisterExternalString(*string);
5762 return Utils::ToLocal(string);
5766 Local<String> v8::String::NewExternal(
5767 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5768 RETURN_TO_LOCAL_UNCHECKED(NewExternalTwoByte(isolate, resource), String);
5772 MaybeLocal<String> v8::String::NewExternalOneByte(
5773 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5774 CHECK(resource && resource->data());
5775 // TODO(dcarney): throw a context free exception.
5776 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5777 return MaybeLocal<String>();
5779 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5780 ENTER_V8(i_isolate);
5781 LOG_API(i_isolate, "String::NewExternalOneByte");
5782 i::Handle<i::String> string = i_isolate->factory()
5783 ->NewExternalStringFromOneByte(resource)
5785 i_isolate->heap()->RegisterExternalString(*string);
5786 return Utils::ToLocal(string);
5790 Local<String> v8::String::NewExternal(
5791 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5792 RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
5796 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
5797 i::Handle<i::String> obj = Utils::OpenHandle(this);
5798 i::Isolate* isolate = obj->GetIsolate();
5799 if (i::StringShape(*obj).IsExternal()) {
5800 return false; // Already an external string.
5803 if (isolate->heap()->IsInGCPostProcessing()) {
5806 CHECK(resource && resource->data());
5808 bool result = obj->MakeExternal(resource);
5809 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5810 DCHECK(!CanMakeExternal() || result);
5812 DCHECK(obj->IsExternalString());
5813 isolate->heap()->RegisterExternalString(*obj);
5819 bool v8::String::MakeExternal(
5820 v8::String::ExternalOneByteStringResource* resource) {
5821 i::Handle<i::String> obj = Utils::OpenHandle(this);
5822 i::Isolate* isolate = obj->GetIsolate();
5823 if (i::StringShape(*obj).IsExternal()) {
5824 return false; // Already an external string.
5827 if (isolate->heap()->IsInGCPostProcessing()) {
5830 CHECK(resource && resource->data());
5832 bool result = obj->MakeExternal(resource);
5833 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5834 DCHECK(!CanMakeExternal() || result);
5836 DCHECK(obj->IsExternalString());
5837 isolate->heap()->RegisterExternalString(*obj);
5843 bool v8::String::CanMakeExternal() {
5844 i::Handle<i::String> obj = Utils::OpenHandle(this);
5845 i::Isolate* isolate = obj->GetIsolate();
5847 // Old space strings should be externalized.
5848 if (!isolate->heap()->new_space()->Contains(*obj)) return true;
5849 int size = obj->Size(); // Byte size of the original string.
5850 if (size <= i::ExternalString::kShortSize) return false;
5851 i::StringShape shape(*obj);
5852 return !shape.IsExternal();
5856 Isolate* v8::Object::GetIsolate() {
5857 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
5858 return reinterpret_cast<Isolate*>(i_isolate);
5862 Local<v8::Object> v8::Object::New(Isolate* isolate) {
5863 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5864 LOG_API(i_isolate, "Object::New");
5865 ENTER_V8(i_isolate);
5866 i::Handle<i::JSObject> obj =
5867 i_isolate->factory()->NewJSObject(i_isolate->object_function());
5868 return Utils::ToLocal(obj);
5872 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
5873 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5874 LOG_API(i_isolate, "NumberObject::New");
5875 ENTER_V8(i_isolate);
5876 i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
5877 i::Handle<i::Object> obj =
5878 i::Object::ToObject(i_isolate, number).ToHandleChecked();
5879 return Utils::ToLocal(obj);
5883 double v8::NumberObject::ValueOf() const {
5884 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5885 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5886 i::Isolate* isolate = jsvalue->GetIsolate();
5887 LOG_API(isolate, "NumberObject::NumberValue");
5888 return jsvalue->value()->Number();
5892 Local<v8::Value> v8::BooleanObject::New(bool value) {
5893 i::Isolate* isolate = i::Isolate::Current();
5894 LOG_API(isolate, "BooleanObject::New");
5896 i::Handle<i::Object> boolean(value
5897 ? isolate->heap()->true_value()
5898 : isolate->heap()->false_value(),
5900 i::Handle<i::Object> obj =
5901 i::Object::ToObject(isolate, boolean).ToHandleChecked();
5902 return Utils::ToLocal(obj);
5906 bool v8::BooleanObject::ValueOf() const {
5907 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5908 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5909 i::Isolate* isolate = jsvalue->GetIsolate();
5910 LOG_API(isolate, "BooleanObject::BooleanValue");
5911 return jsvalue->value()->IsTrue();
5915 Local<v8::Value> v8::StringObject::New(Local<String> value) {
5916 i::Handle<i::String> string = Utils::OpenHandle(*value);
5917 i::Isolate* isolate = string->GetIsolate();
5918 LOG_API(isolate, "StringObject::New");
5920 i::Handle<i::Object> obj =
5921 i::Object::ToObject(isolate, string).ToHandleChecked();
5922 return Utils::ToLocal(obj);
5926 Local<v8::String> v8::StringObject::ValueOf() const {
5927 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5928 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5929 i::Isolate* isolate = jsvalue->GetIsolate();
5930 LOG_API(isolate, "StringObject::StringValue");
5931 return Utils::ToLocal(
5932 i::Handle<i::String>(i::String::cast(jsvalue->value())));
5936 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
5937 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5938 LOG_API(i_isolate, "SymbolObject::New");
5939 ENTER_V8(i_isolate);
5940 i::Handle<i::Object> obj = i::Object::ToObject(
5941 i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
5942 return Utils::ToLocal(obj);
5946 Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
5947 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5948 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5949 i::Isolate* isolate = jsvalue->GetIsolate();
5950 LOG_API(isolate, "SymbolObject::SymbolValue");
5951 return Utils::ToLocal(
5952 i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value())));
5956 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
5957 if (std::isnan(time)) {
5958 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
5959 time = std::numeric_limits<double>::quiet_NaN();
5961 PREPARE_FOR_EXECUTION(context, "Date::New", Value);
5962 Local<Value> result;
5963 has_pending_exception =
5964 !ToLocal<Value>(i::Execution::NewDate(isolate, time), &result);
5965 RETURN_ON_FAILED_EXECUTION(Value);
5966 RETURN_ESCAPED(result);
5970 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
5971 auto context = isolate->GetCurrentContext();
5972 RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value);
5976 double v8::Date::ValueOf() const {
5977 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5978 i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
5979 i::Isolate* isolate = jsdate->GetIsolate();
5980 LOG_API(isolate, "Date::NumberValue");
5981 return jsdate->value()->Number();
5985 void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) {
5986 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5987 LOG_API(i_isolate, "Date::DateTimeConfigurationChangeNotification");
5988 ENTER_V8(i_isolate);
5989 i_isolate->date_cache()->ResetDateCache();
5990 if (!i_isolate->eternal_handles()->Exists(
5991 i::EternalHandles::DATE_CACHE_VERSION)) {
5994 i::Handle<i::FixedArray> date_cache_version =
5995 i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton(
5996 i::EternalHandles::DATE_CACHE_VERSION));
5997 DCHECK_EQ(1, date_cache_version->length());
5998 CHECK(date_cache_version->get(0)->IsSmi());
5999 date_cache_version->set(
6001 i::Smi::FromInt(i::Smi::cast(date_cache_version->get(0))->value() + 1));
6005 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
6006 i::Isolate* isolate = i::Isolate::Current();
6007 uint8_t flags_buf[3];
6009 if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
6010 if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
6011 if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
6012 DCHECK(num_flags <= static_cast<int>(arraysize(flags_buf)));
6013 return isolate->factory()->InternalizeOneByteString(
6014 i::Vector<const uint8_t>(flags_buf, num_flags));
6018 MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context,
6019 Local<String> pattern, Flags flags) {
6020 PREPARE_FOR_EXECUTION(context, "RegExp::New", RegExp);
6021 Local<v8::RegExp> result;
6022 has_pending_exception =
6023 !ToLocal<RegExp>(i::Execution::NewJSRegExp(Utils::OpenHandle(*pattern),
6024 RegExpFlagsToString(flags)),
6026 RETURN_ON_FAILED_EXECUTION(RegExp);
6027 RETURN_ESCAPED(result);
6031 Local<v8::RegExp> v8::RegExp::New(Local<String> pattern, Flags flags) {
6033 reinterpret_cast<Isolate*>(Utils::OpenHandle(*pattern)->GetIsolate());
6034 auto context = isolate->GetCurrentContext();
6035 RETURN_TO_LOCAL_UNCHECKED(New(context, pattern, flags), RegExp);
6039 Local<v8::String> v8::RegExp::GetSource() const {
6040 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6041 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
6045 // Assert that the static flags cast in GetFlags is valid.
6046 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag) \
6047 STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) == \
6048 static_cast<int>(i::JSRegExp::internal_flag))
6049 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
6050 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
6051 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
6052 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
6053 #undef REGEXP_FLAG_ASSERT_EQ
6055 v8::RegExp::Flags v8::RegExp::GetFlags() const {
6056 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6057 return static_cast<RegExp::Flags>(obj->GetFlags().value());
6061 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
6062 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6063 LOG_API(i_isolate, "Array::New");
6064 ENTER_V8(i_isolate);
6065 int real_length = length > 0 ? length : 0;
6066 i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
6067 i::Handle<i::Object> length_obj =
6068 i_isolate->factory()->NewNumberFromInt(real_length);
6069 obj->set_length(*length_obj);
6070 return Utils::ToLocal(obj);
6074 uint32_t v8::Array::Length() const {
6075 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
6076 i::Object* length = obj->length();
6077 if (length->IsSmi()) {
6078 return i::Smi::cast(length)->value();
6080 return static_cast<uint32_t>(length->Number());
6085 MaybeLocal<Object> Array::CloneElementAt(Local<Context> context,
6087 PREPARE_FOR_EXECUTION(context, "v8::Array::CloneElementAt()", Object);
6088 auto self = Utils::OpenHandle(this);
6089 if (!self->HasFastObjectElements()) return Local<Object>();
6090 i::FixedArray* elms = i::FixedArray::cast(self->elements());
6091 i::Object* paragon = elms->get(index);
6092 if (!paragon->IsJSObject()) return Local<Object>();
6093 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
6094 Local<Object> result;
6095 has_pending_exception =
6096 !ToLocal<Object>(isolate->factory()->CopyJSObject(paragon_handle),
6098 RETURN_ON_FAILED_EXECUTION(Object);
6099 RETURN_ESCAPED(result);
6103 Local<Object> Array::CloneElementAt(uint32_t index) {
6104 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6105 RETURN_TO_LOCAL_UNCHECKED(CloneElementAt(context, index), Object);
6109 Local<v8::Map> v8::Map::New(Isolate* isolate) {
6110 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6111 LOG_API(i_isolate, "Map::New");
6112 ENTER_V8(i_isolate);
6113 i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
6114 return Utils::ToLocal(obj);
6118 size_t v8::Map::Size() const {
6119 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6120 return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
6125 auto self = Utils::OpenHandle(this);
6126 i::Isolate* isolate = self->GetIsolate();
6127 LOG_API(isolate, "Map::Clear");
6129 i::JSMap::Clear(self);
6133 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
6134 PREPARE_FOR_EXECUTION(context, "Map::Get", Value);
6135 auto self = Utils::OpenHandle(this);
6136 Local<Value> result;
6137 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6138 has_pending_exception =
6139 !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
6140 arraysize(argv), argv),
6142 RETURN_ON_FAILED_EXECUTION(Value);
6143 RETURN_ESCAPED(result);
6147 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
6148 Local<Value> value) {
6149 PREPARE_FOR_EXECUTION(context, "Map::Set", Map);
6150 auto self = Utils::OpenHandle(this);
6151 i::Handle<i::Object> result;
6152 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
6153 Utils::OpenHandle(*value)};
6154 has_pending_exception = !i::Execution::Call(isolate, isolate->map_set(), self,
6155 arraysize(argv), argv)
6157 RETURN_ON_FAILED_EXECUTION(Map);
6158 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6162 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
6163 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Has", bool);
6164 auto self = Utils::OpenHandle(this);
6165 i::Handle<i::Object> result;
6166 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6167 has_pending_exception = !i::Execution::Call(isolate, isolate->map_has(), self,
6168 arraysize(argv), argv)
6170 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6171 return Just(result->IsTrue());
6175 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
6176 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Delete", bool);
6177 auto self = Utils::OpenHandle(this);
6178 i::Handle<i::Object> result;
6179 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6180 has_pending_exception = !i::Execution::Call(isolate, isolate->map_delete(),
6181 self, arraysize(argv), argv)
6183 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6184 return Just(result->IsTrue());
6188 Local<Array> Map::AsArray() const {
6189 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6190 i::Isolate* isolate = obj->GetIsolate();
6191 i::Factory* factory = isolate->factory();
6192 LOG_API(isolate, "Map::AsArray");
6194 i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(obj->table()));
6195 int size = table->NumberOfElements();
6196 int length = size * 2;
6197 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6198 for (int i = 0; i < size; ++i) {
6199 if (table->KeyAt(i)->IsTheHole()) continue;
6200 result->set(i * 2, table->KeyAt(i));
6201 result->set(i * 2 + 1, table->ValueAt(i));
6203 i::Handle<i::JSArray> result_array =
6204 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6205 return Utils::ToLocal(result_array);
6209 MaybeLocal<Map> Map::FromArray(Local<Context> context, Local<Array> array) {
6210 PREPARE_FOR_EXECUTION(context, "Map::FromArray", Map);
6211 if (array->Length() % 2 != 0) {
6212 return MaybeLocal<Map>();
6214 i::Handle<i::Object> result;
6215 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6216 has_pending_exception =
6217 !i::Execution::Call(isolate, isolate->map_from_array(),
6218 isolate->factory()->undefined_value(),
6219 arraysize(argv), argv)
6221 RETURN_ON_FAILED_EXECUTION(Map);
6222 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6226 Local<v8::Set> v8::Set::New(Isolate* isolate) {
6227 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6228 LOG_API(i_isolate, "Set::New");
6229 ENTER_V8(i_isolate);
6230 i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
6231 return Utils::ToLocal(obj);
6235 size_t v8::Set::Size() const {
6236 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6237 return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
6242 auto self = Utils::OpenHandle(this);
6243 i::Isolate* isolate = self->GetIsolate();
6244 LOG_API(isolate, "Set::Clear");
6246 i::JSSet::Clear(self);
6250 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
6251 PREPARE_FOR_EXECUTION(context, "Set::Add", Set);
6252 auto self = Utils::OpenHandle(this);
6253 i::Handle<i::Object> result;
6254 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6255 has_pending_exception = !i::Execution::Call(isolate, isolate->set_add(), self,
6256 arraysize(argv), argv)
6258 RETURN_ON_FAILED_EXECUTION(Set);
6259 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6263 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
6264 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Has", bool);
6265 auto self = Utils::OpenHandle(this);
6266 i::Handle<i::Object> result;
6267 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6268 has_pending_exception = !i::Execution::Call(isolate, isolate->set_has(), self,
6269 arraysize(argv), argv)
6271 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6272 return Just(result->IsTrue());
6276 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
6277 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Delete", bool);
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 = !i::Execution::Call(isolate, isolate->set_delete(),
6282 self, arraysize(argv), argv)
6284 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6285 return Just(result->IsTrue());
6289 Local<Array> Set::AsArray() const {
6290 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6291 i::Isolate* isolate = obj->GetIsolate();
6292 i::Factory* factory = isolate->factory();
6293 LOG_API(isolate, "Set::AsArray");
6295 i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(obj->table()));
6296 int length = table->NumberOfElements();
6297 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6298 for (int i = 0; i < length; ++i) {
6299 i::Object* key = table->KeyAt(i);
6300 if (!key->IsTheHole()) {
6301 result->set(i, key);
6304 i::Handle<i::JSArray> result_array =
6305 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6306 return Utils::ToLocal(result_array);
6310 MaybeLocal<Set> Set::FromArray(Local<Context> context, Local<Array> array) {
6311 PREPARE_FOR_EXECUTION(context, "Set::FromArray", Set);
6312 i::Handle<i::Object> result;
6313 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6314 has_pending_exception =
6315 !i::Execution::Call(isolate, isolate->set_from_array(),
6316 isolate->factory()->undefined_value(),
6317 arraysize(argv), argv)
6319 RETURN_ON_FAILED_EXECUTION(Set);
6320 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6324 bool Value::IsPromise() const {
6325 auto self = Utils::OpenHandle(this);
6326 return i::Object::IsPromise(self);
6330 MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) {
6331 PREPARE_FOR_EXECUTION(context, "Promise::Resolver::New", Resolver);
6332 i::Handle<i::Object> result;
6333 has_pending_exception =
6334 !i::Execution::Call(isolate, isolate->promise_create(),
6335 isolate->factory()->undefined_value(), 0, NULL)
6337 RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
6338 RETURN_ESCAPED(Local<Promise::Resolver>::Cast(Utils::ToLocal(result)));
6342 Local<Promise::Resolver> Promise::Resolver::New(Isolate* isolate) {
6343 RETURN_TO_LOCAL_UNCHECKED(New(isolate->GetCurrentContext()),
6348 Local<Promise> Promise::Resolver::GetPromise() {
6349 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6350 return Local<Promise>::Cast(Utils::ToLocal(promise));
6354 Maybe<bool> Promise::Resolver::Resolve(Local<Context> context,
6355 Local<Value> value) {
6356 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6357 auto self = Utils::OpenHandle(this);
6358 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6359 has_pending_exception =
6360 i::Execution::Call(isolate, isolate->promise_resolve(),
6361 isolate->factory()->undefined_value(), arraysize(argv),
6364 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6369 void Promise::Resolver::Resolve(Local<Value> value) {
6370 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6371 USE(Resolve(context, value));
6375 Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
6376 Local<Value> value) {
6377 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6378 auto self = Utils::OpenHandle(this);
6379 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6380 has_pending_exception =
6381 i::Execution::Call(isolate, isolate->promise_reject(),
6382 isolate->factory()->undefined_value(), arraysize(argv),
6385 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6390 void Promise::Resolver::Reject(Local<Value> value) {
6391 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6392 USE(Reject(context, value));
6396 MaybeLocal<Promise> Promise::Chain(Local<Context> context,
6397 Local<Function> handler) {
6398 PREPARE_FOR_EXECUTION(context, "Promise::Chain", Promise);
6399 auto self = Utils::OpenHandle(this);
6400 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*handler)};
6401 i::Handle<i::Object> result;
6402 has_pending_exception = !i::Execution::Call(isolate, isolate->promise_chain(),
6403 self, arraysize(argv), argv)
6405 RETURN_ON_FAILED_EXECUTION(Promise);
6406 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6410 Local<Promise> Promise::Chain(Local<Function> handler) {
6411 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6412 RETURN_TO_LOCAL_UNCHECKED(Chain(context, handler), Promise);
6416 MaybeLocal<Promise> Promise::Catch(Local<Context> context,
6417 Local<Function> handler) {
6418 PREPARE_FOR_EXECUTION(context, "Promise::Catch", Promise);
6419 auto self = Utils::OpenHandle(this);
6420 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6421 i::Handle<i::Object> result;
6422 has_pending_exception = !i::Execution::Call(isolate, isolate->promise_catch(),
6423 self, arraysize(argv), argv)
6425 RETURN_ON_FAILED_EXECUTION(Promise);
6426 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6430 Local<Promise> Promise::Catch(Local<Function> handler) {
6431 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6432 RETURN_TO_LOCAL_UNCHECKED(Catch(context, handler), Promise);
6436 MaybeLocal<Promise> Promise::Then(Local<Context> context,
6437 Local<Function> handler) {
6438 PREPARE_FOR_EXECUTION(context, "Promise::Then", Promise);
6439 auto self = Utils::OpenHandle(this);
6440 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6441 i::Handle<i::Object> result;
6442 has_pending_exception = !i::Execution::Call(isolate, isolate->promise_then(),
6443 self, arraysize(argv), argv)
6445 RETURN_ON_FAILED_EXECUTION(Promise);
6446 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6450 Local<Promise> Promise::Then(Local<Function> handler) {
6451 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6452 RETURN_TO_LOCAL_UNCHECKED(Then(context, handler), Promise);
6456 bool Promise::HasHandler() {
6457 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6458 i::Isolate* isolate = promise->GetIsolate();
6459 LOG_API(isolate, "Promise::HasRejectHandler");
6461 i::Handle<i::Symbol> key = isolate->factory()->promise_has_handler_symbol();
6462 return i::JSReceiver::GetDataProperty(promise, key)->IsTrue();
6466 bool v8::ArrayBuffer::IsExternal() const {
6467 return Utils::OpenHandle(this)->is_external();
6471 bool v8::ArrayBuffer::IsNeuterable() const {
6472 return Utils::OpenHandle(this)->is_neuterable();
6476 v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
6477 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6478 i::Isolate* isolate = self->GetIsolate();
6479 Utils::ApiCheck(!self->is_external(), "v8::ArrayBuffer::Externalize",
6480 "ArrayBuffer already externalized");
6481 self->set_is_external(true);
6482 isolate->heap()->UnregisterArrayBuffer(*self);
6484 return GetContents();
6488 v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() {
6489 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6490 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6492 contents.data_ = self->backing_store();
6493 contents.byte_length_ = byte_length;
6498 void v8::ArrayBuffer::Neuter() {
6499 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6500 i::Isolate* isolate = obj->GetIsolate();
6501 Utils::ApiCheck(obj->is_external(),
6502 "v8::ArrayBuffer::Neuter",
6503 "Only externalized ArrayBuffers can be neutered");
6504 Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter",
6505 "Only neuterable ArrayBuffers can be neutered");
6506 LOG_API(obj->GetIsolate(), "v8::ArrayBuffer::Neuter()");
6512 size_t v8::ArrayBuffer::ByteLength() const {
6513 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6514 return static_cast<size_t>(obj->byte_length()->Number());
6518 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
6519 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6520 LOG_API(i_isolate, "v8::ArrayBuffer::New(size_t)");
6521 ENTER_V8(i_isolate);
6522 i::Handle<i::JSArrayBuffer> obj =
6523 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6524 i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length);
6525 return Utils::ToLocal(obj);
6529 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
6531 ArrayBufferCreationMode mode) {
6532 // Embedders must guarantee that the external backing store is valid.
6533 CHECK(byte_length == 0 || data != NULL);
6534 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6535 LOG_API(i_isolate, "v8::ArrayBuffer::New(void*, size_t)");
6536 ENTER_V8(i_isolate);
6537 i::Handle<i::JSArrayBuffer> obj =
6538 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6539 i::JSArrayBuffer::Setup(obj, i_isolate,
6540 mode == ArrayBufferCreationMode::kExternalized, data,
6542 return Utils::ToLocal(obj);
6546 Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
6547 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6548 i::Handle<i::JSArrayBuffer> buffer;
6549 if (obj->IsJSDataView()) {
6550 i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj));
6551 DCHECK(data_view->buffer()->IsJSArrayBuffer());
6552 buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()));
6554 DCHECK(obj->IsJSTypedArray());
6555 buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
6557 return Utils::ToLocal(buffer);
6561 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
6562 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6563 i::Isolate* isolate = self->GetIsolate();
6564 size_t byte_offset = i::NumberToSize(isolate, self->byte_offset());
6565 size_t bytes_to_copy =
6566 i::Min(byte_length, i::NumberToSize(isolate, self->byte_length()));
6567 if (bytes_to_copy) {
6568 i::DisallowHeapAllocation no_gc;
6569 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6570 const char* source = reinterpret_cast<char*>(buffer->backing_store());
6571 if (source == nullptr) {
6572 DCHECK(self->IsJSTypedArray());
6573 i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self));
6574 i::Handle<i::FixedTypedArrayBase> fixed_array(
6575 i::FixedTypedArrayBase::cast(typed_array->elements()));
6576 source = reinterpret_cast<char*>(fixed_array->DataPtr());
6578 memcpy(dest, source + byte_offset, bytes_to_copy);
6580 return bytes_to_copy;
6584 bool v8::ArrayBufferView::HasBuffer() const {
6585 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6586 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6587 return buffer->backing_store() != nullptr;
6591 size_t v8::ArrayBufferView::ByteOffset() {
6592 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6593 return static_cast<size_t>(obj->byte_offset()->Number());
6597 size_t v8::ArrayBufferView::ByteLength() {
6598 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6599 return static_cast<size_t>(obj->byte_length()->Number());
6603 size_t v8::TypedArray::Length() {
6604 i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
6605 return static_cast<size_t>(obj->length_value());
6609 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype, size) \
6610 Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer, \
6611 size_t byte_offset, size_t length) { \
6612 i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate(); \
6614 "v8::" #Type "Array::New(Local<ArrayBuffer>, size_t, size_t)"); \
6615 ENTER_V8(isolate); \
6616 if (!Utils::ApiCheck(length <= static_cast<size_t>(i::Smi::kMaxValue), \
6618 "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
6619 "length exceeds max allowed value")) { \
6620 return Local<Type##Array>(); \
6622 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \
6623 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6624 i::kExternal##Type##Array, buffer, byte_offset, length); \
6625 return Utils::ToLocal##Type##Array(obj); \
6627 Local<Type##Array> Type##Array::New( \
6628 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, \
6630 CHECK(i::FLAG_harmony_sharedarraybuffer); \
6631 i::Isolate* isolate = \
6632 Utils::OpenHandle(*shared_array_buffer)->GetIsolate(); \
6633 LOG_API(isolate, "v8::" #Type \
6634 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)"); \
6635 ENTER_V8(isolate); \
6636 if (!Utils::ApiCheck( \
6637 length <= static_cast<size_t>(i::Smi::kMaxValue), \
6639 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)", \
6640 "length exceeds max allowed value")) { \
6641 return Local<Type##Array>(); \
6643 i::Handle<i::JSArrayBuffer> buffer = \
6644 Utils::OpenHandle(*shared_array_buffer); \
6645 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6646 i::kExternal##Type##Array, buffer, byte_offset, length); \
6647 return Utils::ToLocal##Type##Array(obj); \
6651 TYPED_ARRAYS(TYPED_ARRAY_NEW)
6652 #undef TYPED_ARRAY_NEW
6654 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
6655 size_t byte_offset, size_t byte_length) {
6656 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
6657 i::Isolate* isolate = buffer->GetIsolate();
6658 LOG_API(isolate, "v8::DataView::New(Local<ArrayBuffer>, size_t, size_t)");
6660 i::Handle<i::JSDataView> obj =
6661 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6662 return Utils::ToLocal(obj);
6666 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
6667 size_t byte_offset, size_t byte_length) {
6668 CHECK(i::FLAG_harmony_sharedarraybuffer);
6669 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
6670 i::Isolate* isolate = buffer->GetIsolate();
6672 "v8::DataView::New(Local<SharedArrayBuffer>, size_t, size_t)");
6674 i::Handle<i::JSDataView> obj =
6675 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6676 return Utils::ToLocal(obj);
6680 bool v8::SharedArrayBuffer::IsExternal() const {
6681 return Utils::OpenHandle(this)->is_external();
6685 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
6686 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6687 i::Isolate* isolate = self->GetIsolate();
6688 Utils::ApiCheck(!self->is_external(), "v8::SharedArrayBuffer::Externalize",
6689 "SharedArrayBuffer already externalized");
6690 self->set_is_external(true);
6691 isolate->heap()->UnregisterArrayBuffer(*self);
6692 return GetContents();
6696 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
6697 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6698 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6700 contents.data_ = self->backing_store();
6701 contents.byte_length_ = byte_length;
6706 size_t v8::SharedArrayBuffer::ByteLength() const {
6707 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6708 return static_cast<size_t>(obj->byte_length()->Number());
6712 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate,
6713 size_t byte_length) {
6714 CHECK(i::FLAG_harmony_sharedarraybuffer);
6715 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6716 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(size_t)");
6717 ENTER_V8(i_isolate);
6718 i::Handle<i::JSArrayBuffer> obj =
6719 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6720 i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length, true,
6721 i::SharedFlag::kShared);
6722 return Utils::ToLocalShared(obj);
6726 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
6727 Isolate* isolate, void* data, size_t byte_length,
6728 ArrayBufferCreationMode mode) {
6729 CHECK(i::FLAG_harmony_sharedarraybuffer);
6730 // Embedders must guarantee that the external backing store is valid.
6731 CHECK(byte_length == 0 || data != NULL);
6732 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6733 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(void*, size_t)");
6734 ENTER_V8(i_isolate);
6735 i::Handle<i::JSArrayBuffer> obj =
6736 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6737 i::JSArrayBuffer::Setup(obj, i_isolate,
6738 mode == ArrayBufferCreationMode::kExternalized, data,
6739 byte_length, i::SharedFlag::kShared);
6740 return Utils::ToLocalShared(obj);
6744 Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
6745 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6746 LOG_API(i_isolate, "Symbol::New()");
6747 ENTER_V8(i_isolate);
6748 i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
6749 if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
6750 return Utils::ToLocal(result);
6754 static i::Handle<i::Symbol> SymbolFor(i::Isolate* isolate,
6755 i::Handle<i::String> name,
6756 i::Handle<i::String> part) {
6757 i::Handle<i::JSObject> registry = isolate->GetSymbolRegistry();
6758 i::Handle<i::JSObject> symbols =
6759 i::Handle<i::JSObject>::cast(
6760 i::Object::GetPropertyOrElement(registry, part).ToHandleChecked());
6761 i::Handle<i::Object> symbol =
6762 i::Object::GetPropertyOrElement(symbols, name).ToHandleChecked();
6763 if (!symbol->IsSymbol()) {
6764 DCHECK(symbol->IsUndefined());
6765 symbol = isolate->factory()->NewSymbol();
6766 i::Handle<i::Symbol>::cast(symbol)->set_name(*name);
6767 i::JSObject::SetProperty(symbols, name, symbol, i::STRICT).Assert();
6769 return i::Handle<i::Symbol>::cast(symbol);
6773 Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
6774 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6775 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6776 i::Handle<i::String> part = i_isolate->factory()->for_string();
6777 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6781 Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
6782 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6783 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6784 i::Handle<i::String> part = i_isolate->factory()->for_api_string();
6785 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6789 Local<Symbol> v8::Symbol::GetIterator(Isolate* isolate) {
6790 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6791 return Utils::ToLocal(i_isolate->factory()->iterator_symbol());
6795 Local<Symbol> v8::Symbol::GetUnscopables(Isolate* isolate) {
6796 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6797 return Utils::ToLocal(i_isolate->factory()->unscopables_symbol());
6801 Local<Symbol> v8::Symbol::GetToStringTag(Isolate* isolate) {
6802 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6803 return Utils::ToLocal(i_isolate->factory()->to_string_tag_symbol());
6807 Local<Number> v8::Number::New(Isolate* isolate, double value) {
6808 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6809 if (std::isnan(value)) {
6810 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6811 value = std::numeric_limits<double>::quiet_NaN();
6813 ENTER_V8(internal_isolate);
6814 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6815 return Utils::NumberToLocal(result);
6819 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
6820 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6821 if (i::Smi::IsValid(value)) {
6822 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
6825 ENTER_V8(internal_isolate);
6826 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6827 return Utils::IntegerToLocal(result);
6831 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
6832 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6833 bool fits_into_int32_t = (value & (1 << 31)) == 0;
6834 if (fits_into_int32_t) {
6835 return Integer::New(isolate, static_cast<int32_t>(value));
6837 ENTER_V8(internal_isolate);
6838 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6839 return Utils::IntegerToLocal(result);
6843 void Isolate::CollectAllGarbage(const char* gc_reason) {
6844 i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
6845 DCHECK_EQ(heap->gc_state(), i::Heap::NOT_IN_GC);
6846 if (heap->incremental_marking()->IsStopped()) {
6847 if (heap->incremental_marking()->CanBeActivated()) {
6848 heap->StartIncrementalMarking(
6849 i::Heap::kNoGCFlags,
6850 kGCCallbackFlagSynchronousPhantomCallbackProcessing, gc_reason);
6852 heap->CollectAllGarbage(
6853 i::Heap::kNoGCFlags, gc_reason,
6854 kGCCallbackFlagSynchronousPhantomCallbackProcessing);
6857 // Incremental marking is turned on an has already been started.
6859 // TODO(mlippautz): Compute the time slice for incremental marking based on
6861 double deadline = heap->MonotonicallyIncreasingTimeInMs() +
6862 i::FLAG_external_allocation_limit_incremental_time;
6863 heap->AdvanceIncrementalMarking(
6864 0, deadline, i::IncrementalMarking::StepActions(
6865 i::IncrementalMarking::GC_VIA_STACK_GUARD,
6866 i::IncrementalMarking::FORCE_MARKING,
6867 i::IncrementalMarking::FORCE_COMPLETION));
6872 HeapProfiler* Isolate::GetHeapProfiler() {
6873 i::HeapProfiler* heap_profiler =
6874 reinterpret_cast<i::Isolate*>(this)->heap_profiler();
6875 return reinterpret_cast<HeapProfiler*>(heap_profiler);
6879 CpuProfiler* Isolate::GetCpuProfiler() {
6880 i::CpuProfiler* cpu_profiler =
6881 reinterpret_cast<i::Isolate*>(this)->cpu_profiler();
6882 return reinterpret_cast<CpuProfiler*>(cpu_profiler);
6886 bool Isolate::InContext() {
6887 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6888 return isolate->context() != NULL;
6892 v8::Local<v8::Context> Isolate::GetCurrentContext() {
6893 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6894 i::Context* context = isolate->context();
6895 if (context == NULL) return Local<Context>();
6896 i::Context* native_context = context->native_context();
6897 if (native_context == NULL) return Local<Context>();
6898 return Utils::ToLocal(i::Handle<i::Context>(native_context));
6902 v8::Local<v8::Context> Isolate::GetCallingContext() {
6903 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6904 i::Handle<i::Object> calling = isolate->GetCallingNativeContext();
6905 if (calling.is_null()) return Local<Context>();
6906 return Utils::ToLocal(i::Handle<i::Context>::cast(calling));
6910 v8::Local<v8::Context> Isolate::GetEnteredContext() {
6911 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6912 i::Handle<i::Object> last =
6913 isolate->handle_scope_implementer()->LastEnteredContext();
6914 if (last.is_null()) return Local<Context>();
6915 return Utils::ToLocal(i::Handle<i::Context>::cast(last));
6919 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
6920 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6922 // If we're passed an empty handle, we throw an undefined exception
6923 // to deal more gracefully with out of memory situations.
6924 if (value.IsEmpty()) {
6925 isolate->ScheduleThrow(isolate->heap()->undefined_value());
6927 isolate->ScheduleThrow(*Utils::OpenHandle(*value));
6929 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
6933 void Isolate::SetObjectGroupId(internal::Object** object, UniqueId id) {
6934 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6935 internal_isolate->global_handles()->SetObjectGroupId(
6936 v8::internal::Handle<v8::internal::Object>(object).location(),
6941 void Isolate::SetReferenceFromGroup(UniqueId id, internal::Object** object) {
6942 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6943 internal_isolate->global_handles()->SetReferenceFromGroup(
6945 v8::internal::Handle<v8::internal::Object>(object).location());
6949 void Isolate::SetReference(internal::Object** parent,
6950 internal::Object** child) {
6951 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6952 i::Object** parent_location =
6953 v8::internal::Handle<v8::internal::Object>(parent).location();
6954 internal_isolate->global_handles()->SetReference(
6955 reinterpret_cast<i::HeapObject**>(parent_location),
6956 v8::internal::Handle<v8::internal::Object>(child).location());
6960 void Isolate::AddGCPrologueCallback(GCCallback callback, GCType gc_type) {
6961 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6962 isolate->heap()->AddGCPrologueCallback(callback, gc_type);
6966 void Isolate::RemoveGCPrologueCallback(GCCallback callback) {
6967 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6968 isolate->heap()->RemoveGCPrologueCallback(callback);
6972 void Isolate::AddGCEpilogueCallback(GCCallback callback, GCType gc_type) {
6973 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6974 isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
6978 void Isolate::RemoveGCEpilogueCallback(GCCallback callback) {
6979 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6980 isolate->heap()->RemoveGCEpilogueCallback(callback);
6984 void V8::AddGCPrologueCallback(GCCallback callback, GCType gc_type) {
6985 i::Isolate* isolate = i::Isolate::Current();
6986 isolate->heap()->AddGCPrologueCallback(
6987 reinterpret_cast<v8::Isolate::GCCallback>(callback), gc_type, false);
6991 void V8::AddGCEpilogueCallback(GCCallback callback, GCType gc_type) {
6992 i::Isolate* isolate = i::Isolate::Current();
6993 isolate->heap()->AddGCEpilogueCallback(
6994 reinterpret_cast<v8::Isolate::GCCallback>(callback), gc_type, false);
6998 void Isolate::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
7000 AllocationAction action) {
7001 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7002 isolate->memory_allocator()->AddMemoryAllocationCallback(
7003 callback, space, action);
7007 void Isolate::RemoveMemoryAllocationCallback(
7008 MemoryAllocationCallback callback) {
7009 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7010 isolate->memory_allocator()->RemoveMemoryAllocationCallback(
7015 void Isolate::TerminateExecution() {
7016 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7017 isolate->stack_guard()->RequestTerminateExecution();
7021 bool Isolate::IsExecutionTerminating() {
7022 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7023 return IsExecutionTerminatingCheck(isolate);
7027 void Isolate::CancelTerminateExecution() {
7028 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7029 isolate->stack_guard()->ClearTerminateExecution();
7030 isolate->CancelTerminateExecution();
7034 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
7035 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7036 isolate->RequestInterrupt(callback, data);
7040 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
7041 CHECK(i::FLAG_expose_gc);
7042 if (type == kMinorGarbageCollection) {
7043 reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
7044 i::NEW_SPACE, "Isolate::RequestGarbageCollection",
7045 kGCCallbackFlagForced);
7047 DCHECK_EQ(kFullGarbageCollection, type);
7048 reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
7049 i::Heap::kAbortIncrementalMarkingMask,
7050 "Isolate::RequestGarbageCollection", kGCCallbackFlagForced);
7055 Isolate* Isolate::GetCurrent() {
7056 i::Isolate* isolate = i::Isolate::Current();
7057 return reinterpret_cast<Isolate*>(isolate);
7061 Isolate* Isolate::New(const Isolate::CreateParams& params) {
7062 i::Isolate* isolate = new i::Isolate(false);
7063 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7064 CHECK(params.array_buffer_allocator != NULL);
7065 isolate->set_array_buffer_allocator(params.array_buffer_allocator);
7066 if (params.snapshot_blob != NULL) {
7067 isolate->set_snapshot_blob(params.snapshot_blob);
7069 isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
7071 if (params.entry_hook) {
7072 isolate->set_function_entry_hook(params.entry_hook);
7074 if (params.code_event_handler) {
7075 isolate->InitializeLoggingAndCounters();
7076 isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
7077 params.code_event_handler);
7079 if (params.counter_lookup_callback) {
7080 v8_isolate->SetCounterFunction(params.counter_lookup_callback);
7083 if (params.create_histogram_callback) {
7084 v8_isolate->SetCreateHistogramFunction(params.create_histogram_callback);
7087 if (params.add_histogram_sample_callback) {
7088 v8_isolate->SetAddHistogramSampleFunction(
7089 params.add_histogram_sample_callback);
7091 SetResourceConstraints(isolate, params.constraints);
7092 // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
7093 Isolate::Scope isolate_scope(v8_isolate);
7094 if (params.entry_hook || !i::Snapshot::Initialize(isolate)) {
7095 // If the isolate has a function entry hook, it needs to re-build all its
7096 // code stubs with entry hooks embedded, so don't deserialize a snapshot.
7097 if (i::Snapshot::EmbedsScript(isolate)) {
7098 // If the snapshot embeds a script, we cannot initialize the isolate
7099 // without the snapshot as a fallback. This is unlikely to happen though.
7100 V8_Fatal(__FILE__, __LINE__,
7101 "Initializing isolate from custom startup snapshot failed");
7103 isolate->Init(NULL);
7109 void Isolate::Dispose() {
7110 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7111 if (!Utils::ApiCheck(!isolate->IsInUse(),
7112 "v8::Isolate::Dispose()",
7113 "Disposing the isolate that is entered by a thread.")) {
7116 isolate->TearDown();
7120 void Isolate::Enter() {
7121 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7126 void Isolate::Exit() {
7127 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7132 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
7134 Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
7135 : on_failure_(on_failure) {
7136 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7137 if (on_failure_ == CRASH_ON_FAILURE) {
7138 internal_ = reinterpret_cast<void*>(
7139 new i::DisallowJavascriptExecution(i_isolate));
7141 DCHECK_EQ(THROW_ON_FAILURE, on_failure);
7142 internal_ = reinterpret_cast<void*>(
7143 new i::ThrowOnJavascriptExecution(i_isolate));
7148 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
7149 if (on_failure_ == CRASH_ON_FAILURE) {
7150 delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
7152 delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
7157 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
7159 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7160 internal_assert_ = reinterpret_cast<void*>(
7161 new i::AllowJavascriptExecution(i_isolate));
7162 internal_throws_ = reinterpret_cast<void*>(
7163 new i::NoThrowOnJavascriptExecution(i_isolate));
7167 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
7168 delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
7169 delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
7173 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
7175 : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
7176 isolate_->handle_scope_implementer()->IncrementCallDepth();
7180 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
7181 isolate_->handle_scope_implementer()->DecrementCallDepth();
7185 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
7186 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7187 i::Heap* heap = isolate->heap();
7188 heap_statistics->total_heap_size_ = heap->CommittedMemory();
7189 heap_statistics->total_heap_size_executable_ =
7190 heap->CommittedMemoryExecutable();
7191 heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
7192 heap_statistics->total_available_size_ = heap->Available();
7193 heap_statistics->used_heap_size_ = heap->SizeOfObjects();
7194 heap_statistics->heap_size_limit_ = heap->MaxReserved();
7198 size_t Isolate::NumberOfHeapSpaces() {
7199 return i::LAST_SPACE - i::FIRST_SPACE + 1;
7203 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7205 if (!space_statistics) return false;
7206 if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
7209 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7210 i::Heap* heap = isolate->heap();
7211 i::Space* space = heap->space(static_cast<int>(index));
7213 space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
7214 space_statistics->space_size_ = space->CommittedMemory();
7215 space_statistics->space_used_size_ = space->SizeOfObjects();
7216 space_statistics->space_available_size_ = space->Available();
7217 space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
7222 size_t Isolate::NumberOfTrackedHeapObjectTypes() {
7223 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7224 i::Heap* heap = isolate->heap();
7225 return heap->NumberOfTrackedHeapObjectTypes();
7229 bool Isolate::GetHeapObjectStatisticsAtLastGC(
7230 HeapObjectStatistics* object_statistics, size_t type_index) {
7231 if (!object_statistics) return false;
7232 if (!i::FLAG_track_gc_object_stats) return false;
7234 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7235 i::Heap* heap = isolate->heap();
7236 if (type_index >= heap->NumberOfTrackedHeapObjectTypes()) return false;
7238 const char* object_type;
7239 const char* object_sub_type;
7240 size_t object_count = heap->ObjectCountAtLastGC(type_index);
7241 size_t object_size = heap->ObjectSizeAtLastGC(type_index);
7242 if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
7243 // There should be no objects counted when the type is unknown.
7244 DCHECK_EQ(object_count, 0U);
7245 DCHECK_EQ(object_size, 0U);
7249 object_statistics->object_type_ = object_type;
7250 object_statistics->object_sub_type_ = object_sub_type;
7251 object_statistics->object_count_ = object_count;
7252 object_statistics->object_size_ = object_size;
7257 void Isolate::GetStackSample(const RegisterState& state, void** frames,
7258 size_t frames_limit, SampleInfo* sample_info) {
7259 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7260 i::TickSample::GetStackSample(isolate, state, i::TickSample::kSkipCEntryFrame,
7261 frames, frames_limit, sample_info);
7265 void Isolate::SetEventLogger(LogEventCallback that) {
7266 // Do not overwrite the event logger if we want to log explicitly.
7267 if (i::FLAG_log_internal_timer_events) return;
7268 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7269 isolate->set_event_logger(that);
7273 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
7274 if (callback == NULL) return;
7275 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7276 isolate->AddCallCompletedCallback(callback);
7280 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
7281 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7282 isolate->RemoveCallCompletedCallback(callback);
7286 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
7287 if (callback == NULL) return;
7288 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7289 isolate->SetPromiseRejectCallback(callback);
7293 void Isolate::RunMicrotasks() {
7294 reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
7298 void Isolate::EnqueueMicrotask(Local<Function> microtask) {
7299 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7300 isolate->EnqueueMicrotask(Utils::OpenHandle(*microtask));
7304 void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) {
7305 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7306 i::HandleScope scope(isolate);
7307 i::Handle<i::CallHandlerInfo> callback_info =
7308 i::Handle<i::CallHandlerInfo>::cast(
7309 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE));
7310 SET_FIELD_WRAPPED(callback_info, set_callback, microtask);
7311 SET_FIELD_WRAPPED(callback_info, set_data, data);
7312 isolate->EnqueueMicrotask(callback_info);
7316 void Isolate::SetAutorunMicrotasks(bool autorun) {
7317 reinterpret_cast<i::Isolate*>(this)->set_autorun_microtasks(autorun);
7321 bool Isolate::WillAutorunMicrotasks() const {
7322 return reinterpret_cast<const i::Isolate*>(this)->autorun_microtasks();
7326 void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
7327 reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
7331 void Isolate::SetCounterFunction(CounterLookupCallback callback) {
7332 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7333 isolate->stats_table()->SetCounterFunction(callback);
7334 isolate->InitializeLoggingAndCounters();
7335 isolate->counters()->ResetCounters();
7339 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
7340 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7341 isolate->stats_table()->SetCreateHistogramFunction(callback);
7342 isolate->InitializeLoggingAndCounters();
7343 isolate->counters()->ResetHistograms();
7347 void Isolate::SetAddHistogramSampleFunction(
7348 AddHistogramSampleCallback callback) {
7349 reinterpret_cast<i::Isolate*>(this)
7351 ->SetAddHistogramSampleFunction(callback);
7355 bool Isolate::IdleNotification(int idle_time_in_ms) {
7356 // Returning true tells the caller that it need not
7357 // continue to call IdleNotification.
7358 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7359 if (!i::FLAG_use_idle_notification) return true;
7360 return isolate->heap()->IdleNotification(idle_time_in_ms);
7364 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
7365 // Returning true tells the caller that it need not
7366 // continue to call IdleNotification.
7367 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7368 if (!i::FLAG_use_idle_notification) return true;
7369 return isolate->heap()->IdleNotification(deadline_in_seconds);
7373 void Isolate::LowMemoryNotification() {
7374 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7376 i::HistogramTimerScope idle_notification_scope(
7377 isolate->counters()->gc_low_memory_notification());
7378 isolate->heap()->CollectAllAvailableGarbage("low memory notification");
7383 int Isolate::ContextDisposedNotification(bool dependant_context) {
7384 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7385 return isolate->heap()->NotifyContextDisposed(dependant_context);
7389 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
7390 JitCodeEventHandler event_handler) {
7391 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7392 // Ensure that logging is initialized for our isolate.
7393 isolate->InitializeLoggingAndCounters();
7394 isolate->logger()->SetCodeEventHandler(options, event_handler);
7398 void Isolate::SetStackLimit(uintptr_t stack_limit) {
7399 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7401 isolate->stack_guard()->SetStackLimit(stack_limit);
7405 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
7406 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7407 if (isolate->code_range()->valid()) {
7408 *start = isolate->code_range()->start();
7409 *length_in_bytes = isolate->code_range()->size();
7412 *length_in_bytes = 0;
7417 void Isolate::SetFatalErrorHandler(FatalErrorCallback that) {
7418 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7419 isolate->set_exception_behavior(that);
7423 void Isolate::SetAllowCodeGenerationFromStringsCallback(
7424 AllowCodeGenerationFromStringsCallback callback) {
7425 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7426 isolate->set_allow_code_gen_callback(callback);
7430 bool Isolate::IsDead() {
7431 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7432 return isolate->IsDead();
7436 bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
7437 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7439 i::HandleScope scope(isolate);
7440 NeanderArray listeners(isolate->factory()->message_listeners());
7441 NeanderObject obj(isolate, 2);
7442 obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
7443 obj.set(1, data.IsEmpty() ? isolate->heap()->undefined_value()
7444 : *Utils::OpenHandle(*data));
7445 listeners.add(isolate, obj.value());
7450 void Isolate::RemoveMessageListeners(MessageCallback that) {
7451 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7453 i::HandleScope scope(isolate);
7454 NeanderArray listeners(isolate->factory()->message_listeners());
7455 for (int i = 0; i < listeners.length(); i++) {
7456 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
7458 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
7459 i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
7460 if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
7461 listeners.set(i, isolate->heap()->undefined_value());
7467 void Isolate::SetFailedAccessCheckCallbackFunction(
7468 FailedAccessCheckCallback callback) {
7469 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7470 isolate->SetFailedAccessCheckCallback(callback);
7474 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
7475 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7476 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7477 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7482 void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) {
7483 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7484 isolate->heap()->VisitExternalResources(visitor);
7488 class VisitorAdapter : public i::ObjectVisitor {
7490 explicit VisitorAdapter(PersistentHandleVisitor* visitor)
7491 : visitor_(visitor) {}
7492 virtual void VisitPointers(i::Object** start, i::Object** end) {
7495 virtual void VisitEmbedderReference(i::Object** p, uint16_t class_id) {
7496 Value* value = ToApi<Value>(i::Handle<i::Object>(p));
7497 visitor_->VisitPersistentHandle(
7498 reinterpret_cast<Persistent<Value>*>(&value), class_id);
7502 PersistentHandleVisitor* visitor_;
7506 void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
7507 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7508 i::DisallowHeapAllocation no_allocation;
7509 VisitorAdapter visitor_adapter(visitor);
7510 isolate->global_handles()->IterateAllRootsWithClassIds(&visitor_adapter);
7514 void Isolate::VisitHandlesForPartialDependence(
7515 PersistentHandleVisitor* visitor) {
7516 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7517 i::DisallowHeapAllocation no_allocation;
7518 VisitorAdapter visitor_adapter(visitor);
7519 isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds(
7524 String::Utf8Value::Utf8Value(v8::Local<v8::Value> obj)
7525 : str_(NULL), length_(0) {
7526 if (obj.IsEmpty()) return;
7527 i::Isolate* isolate = i::Isolate::Current();
7528 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7530 i::HandleScope scope(isolate);
7531 Local<Context> context = v8_isolate->GetCurrentContext();
7532 TryCatch try_catch(v8_isolate);
7534 if (!obj->ToString(context).ToLocal(&str)) return;
7535 i::Handle<i::String> i_str = Utils::OpenHandle(*str);
7536 length_ = v8::Utf8Length(*i_str, isolate);
7537 str_ = i::NewArray<char>(length_ + 1);
7538 str->WriteUtf8(str_);
7542 String::Utf8Value::~Utf8Value() {
7543 i::DeleteArray(str_);
7547 String::Value::Value(v8::Local<v8::Value> obj) : str_(NULL), length_(0) {
7548 if (obj.IsEmpty()) return;
7549 i::Isolate* isolate = i::Isolate::Current();
7550 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7552 i::HandleScope scope(isolate);
7553 Local<Context> context = v8_isolate->GetCurrentContext();
7554 TryCatch try_catch(v8_isolate);
7556 if (!obj->ToString(context).ToLocal(&str)) return;
7557 length_ = str->Length();
7558 str_ = i::NewArray<uint16_t>(length_ + 1);
7563 String::Value::~Value() {
7564 i::DeleteArray(str_);
7568 #define DEFINE_ERROR(NAME, name) \
7569 Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) { \
7570 i::Isolate* isolate = i::Isolate::Current(); \
7571 LOG_API(isolate, #NAME); \
7572 ENTER_V8(isolate); \
7575 i::HandleScope scope(isolate); \
7576 i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \
7577 i::Handle<i::JSFunction> constructor = isolate->name##_function(); \
7578 error = *isolate->factory()->NewError(constructor, message); \
7580 i::Handle<i::Object> result(error, isolate); \
7581 return Utils::ToLocal(result); \
7584 DEFINE_ERROR(RangeError, range_error)
7585 DEFINE_ERROR(ReferenceError, reference_error)
7586 DEFINE_ERROR(SyntaxError, syntax_error)
7587 DEFINE_ERROR(TypeError, type_error)
7588 DEFINE_ERROR(Error, error)
7593 Local<Message> Exception::CreateMessage(Local<Value> exception) {
7594 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7595 if (!obj->IsHeapObject()) return Local<Message>();
7596 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
7598 i::HandleScope scope(isolate);
7599 return Utils::MessageToLocal(
7600 scope.CloseAndEscape(isolate->CreateMessage(obj, NULL)));
7604 Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) {
7605 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7606 if (!obj->IsJSObject()) return Local<StackTrace>();
7607 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
7608 i::Isolate* isolate = js_obj->GetIsolate();
7610 return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj));
7614 // --- D e b u g S u p p o r t ---
7616 bool Debug::SetDebugEventListener(EventCallback that, Local<Value> data) {
7617 i::Isolate* isolate = i::Isolate::Current();
7619 i::HandleScope scope(isolate);
7620 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
7622 foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
7624 isolate->debug()->SetEventListener(foreign,
7625 Utils::OpenHandle(*data, true));
7630 void Debug::DebugBreak(Isolate* isolate) {
7631 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->RequestDebugBreak();
7635 void Debug::CancelDebugBreak(Isolate* isolate) {
7636 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7637 internal_isolate->stack_guard()->ClearDebugBreak();
7641 bool Debug::CheckDebugBreak(Isolate* isolate) {
7642 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7643 return internal_isolate->stack_guard()->CheckDebugBreak();
7647 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
7648 i::Isolate* isolate = i::Isolate::Current();
7650 isolate->debug()->SetMessageHandler(handler);
7654 void Debug::SendCommand(Isolate* isolate,
7655 const uint16_t* command,
7657 ClientData* client_data) {
7658 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7659 internal_isolate->debug()->EnqueueCommandMessage(
7660 i::Vector<const uint16_t>(command, length), client_data);
7664 MaybeLocal<Value> Debug::Call(Local<Context> context,
7665 v8::Local<v8::Function> fun,
7666 v8::Local<v8::Value> data) {
7667 PREPARE_FOR_EXECUTION(context, "v8::Debug::Call()", Value);
7668 i::Handle<i::Object> data_obj;
7669 if (data.IsEmpty()) {
7670 data_obj = isolate->factory()->undefined_value();
7672 data_obj = Utils::OpenHandle(*data);
7674 Local<Value> result;
7675 has_pending_exception =
7676 !ToLocal<Value>(isolate->debug()->Call(Utils::OpenHandle(*fun), data_obj),
7678 RETURN_ON_FAILED_EXECUTION(Value);
7679 RETURN_ESCAPED(result);
7683 Local<Value> Debug::Call(v8::Local<v8::Function> fun,
7684 v8::Local<v8::Value> data) {
7685 auto context = ContextFromHeapObject(Utils::OpenHandle(*fun));
7686 RETURN_TO_LOCAL_UNCHECKED(Call(context, fun, data), Value);
7690 MaybeLocal<Value> Debug::GetMirror(Local<Context> context,
7691 v8::Local<v8::Value> obj) {
7692 PREPARE_FOR_EXECUTION(context, "v8::Debug::GetMirror()", Value);
7693 i::Debug* isolate_debug = isolate->debug();
7694 has_pending_exception = !isolate_debug->Load();
7695 RETURN_ON_FAILED_EXECUTION(Value);
7696 i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global_object());
7697 auto name = isolate->factory()->NewStringFromStaticChars("MakeMirror");
7698 auto fun_obj = i::Object::GetProperty(debug, name).ToHandleChecked();
7699 auto v8_fun = Utils::ToLocal(i::Handle<i::JSFunction>::cast(fun_obj));
7700 const int kArgc = 1;
7701 v8::Local<v8::Value> argv[kArgc] = {obj};
7702 Local<Value> result;
7703 has_pending_exception = !v8_fun->Call(context, Utils::ToLocal(debug), kArgc,
7704 argv).ToLocal(&result);
7705 RETURN_ON_FAILED_EXECUTION(Value);
7706 RETURN_ESCAPED(result);
7710 Local<Value> Debug::GetMirror(v8::Local<v8::Value> obj) {
7711 RETURN_TO_LOCAL_UNCHECKED(GetMirror(Local<Context>(), obj), Value);
7715 void Debug::ProcessDebugMessages() {
7716 i::Isolate::Current()->debug()->ProcessDebugMessages(true);
7720 Local<Context> Debug::GetDebugContext() {
7721 i::Isolate* isolate = i::Isolate::Current();
7723 return Utils::ToLocal(isolate->debug()->GetDebugContext());
7727 void Debug::SetLiveEditEnabled(Isolate* isolate, bool enable) {
7728 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7729 internal_isolate->debug()->set_live_edit_enabled(enable);
7733 MaybeLocal<Array> Debug::GetInternalProperties(Isolate* v8_isolate,
7734 Local<Value> value) {
7735 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7737 i::Handle<i::Object> val = Utils::OpenHandle(*value);
7738 i::Handle<i::JSArray> result;
7739 if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
7740 return MaybeLocal<Array>();
7741 return Utils::ToLocal(result);
7745 Local<String> CpuProfileNode::GetFunctionName() const {
7746 i::Isolate* isolate = i::Isolate::Current();
7747 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7748 const i::CodeEntry* entry = node->entry();
7749 i::Handle<i::String> name =
7750 isolate->factory()->InternalizeUtf8String(entry->name());
7751 if (!entry->has_name_prefix()) {
7752 return ToApiHandle<String>(name);
7754 // We do not expect this to fail. Change this if it does.
7755 i::Handle<i::String> cons = isolate->factory()->NewConsString(
7756 isolate->factory()->InternalizeUtf8String(entry->name_prefix()),
7757 name).ToHandleChecked();
7758 return ToApiHandle<String>(cons);
7763 int CpuProfileNode::GetScriptId() const {
7764 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7765 const i::CodeEntry* entry = node->entry();
7766 return entry->script_id();
7770 Local<String> CpuProfileNode::GetScriptResourceName() const {
7771 i::Isolate* isolate = i::Isolate::Current();
7772 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7773 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7774 node->entry()->resource_name()));
7778 int CpuProfileNode::GetLineNumber() const {
7779 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
7783 int CpuProfileNode::GetColumnNumber() const {
7784 return reinterpret_cast<const i::ProfileNode*>(this)->
7785 entry()->column_number();
7789 unsigned int CpuProfileNode::GetHitLineCount() const {
7790 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7791 return node->GetHitLineCount();
7795 bool CpuProfileNode::GetLineTicks(LineTick* entries,
7796 unsigned int length) const {
7797 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7798 return node->GetLineTicks(entries, length);
7802 const char* CpuProfileNode::GetBailoutReason() const {
7803 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7804 return node->entry()->bailout_reason();
7808 unsigned CpuProfileNode::GetHitCount() const {
7809 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
7813 unsigned CpuProfileNode::GetCallUid() const {
7814 return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
7818 unsigned CpuProfileNode::GetNodeId() const {
7819 return reinterpret_cast<const i::ProfileNode*>(this)->id();
7823 int CpuProfileNode::GetChildrenCount() const {
7824 return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
7828 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
7829 const i::ProfileNode* child =
7830 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
7831 return reinterpret_cast<const CpuProfileNode*>(child);
7835 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
7836 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7837 return node->deopt_infos();
7841 void CpuProfile::Delete() {
7842 i::Isolate* isolate = i::Isolate::Current();
7843 i::CpuProfiler* profiler = isolate->cpu_profiler();
7844 DCHECK(profiler != NULL);
7845 profiler->DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
7849 Local<String> CpuProfile::GetTitle() const {
7850 i::Isolate* isolate = i::Isolate::Current();
7851 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7852 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7857 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
7858 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7859 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
7863 const CpuProfileNode* CpuProfile::GetSample(int index) const {
7864 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7865 return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
7869 int64_t CpuProfile::GetSampleTimestamp(int index) const {
7870 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7871 return (profile->sample_timestamp(index) - base::TimeTicks())
7876 int64_t CpuProfile::GetStartTime() const {
7877 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7878 return (profile->start_time() - base::TimeTicks()).InMicroseconds();
7882 int64_t CpuProfile::GetEndTime() const {
7883 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7884 return (profile->end_time() - base::TimeTicks()).InMicroseconds();
7888 int CpuProfile::GetSamplesCount() const {
7889 return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
7893 void CpuProfiler::SetSamplingInterval(int us) {
7895 return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
7896 base::TimeDelta::FromMicroseconds(us));
7900 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
7901 reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
7902 *Utils::OpenHandle(*title), record_samples);
7906 CpuProfile* CpuProfiler::StopProfiling(Local<String> title) {
7907 return reinterpret_cast<CpuProfile*>(
7908 reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
7909 *Utils::OpenHandle(*title)));
7913 void CpuProfiler::SetIdle(bool is_idle) {
7914 i::Isolate* isolate = reinterpret_cast<i::CpuProfiler*>(this)->isolate();
7915 v8::StateTag state = isolate->current_vm_state();
7916 DCHECK(state == v8::EXTERNAL || state == v8::IDLE);
7917 if (isolate->js_entry_sp() != NULL) return;
7919 isolate->set_current_vm_state(v8::IDLE);
7920 } else if (state == v8::IDLE) {
7921 isolate->set_current_vm_state(v8::EXTERNAL);
7926 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
7927 return const_cast<i::HeapGraphEdge*>(
7928 reinterpret_cast<const i::HeapGraphEdge*>(edge));
7932 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
7933 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
7937 Local<Value> HeapGraphEdge::GetName() const {
7938 i::Isolate* isolate = i::Isolate::Current();
7939 i::HeapGraphEdge* edge = ToInternal(this);
7940 switch (edge->type()) {
7941 case i::HeapGraphEdge::kContextVariable:
7942 case i::HeapGraphEdge::kInternal:
7943 case i::HeapGraphEdge::kProperty:
7944 case i::HeapGraphEdge::kShortcut:
7945 case i::HeapGraphEdge::kWeak:
7946 return ToApiHandle<String>(
7947 isolate->factory()->InternalizeUtf8String(edge->name()));
7948 case i::HeapGraphEdge::kElement:
7949 case i::HeapGraphEdge::kHidden:
7950 return ToApiHandle<Number>(
7951 isolate->factory()->NewNumberFromInt(edge->index()));
7952 default: UNREACHABLE();
7954 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
7958 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
7959 const i::HeapEntry* from = ToInternal(this)->from();
7960 return reinterpret_cast<const HeapGraphNode*>(from);
7964 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
7965 const i::HeapEntry* to = ToInternal(this)->to();
7966 return reinterpret_cast<const HeapGraphNode*>(to);
7970 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
7971 return const_cast<i::HeapEntry*>(
7972 reinterpret_cast<const i::HeapEntry*>(entry));
7976 HeapGraphNode::Type HeapGraphNode::GetType() const {
7977 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
7981 Local<String> HeapGraphNode::GetName() const {
7982 i::Isolate* isolate = i::Isolate::Current();
7983 return ToApiHandle<String>(
7984 isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
7988 SnapshotObjectId HeapGraphNode::GetId() const {
7989 return ToInternal(this)->id();
7993 size_t HeapGraphNode::GetShallowSize() const {
7994 return ToInternal(this)->self_size();
7998 int HeapGraphNode::GetChildrenCount() const {
7999 return ToInternal(this)->children().length();
8003 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
8004 return reinterpret_cast<const HeapGraphEdge*>(
8005 ToInternal(this)->children()[index]);
8009 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
8010 return const_cast<i::HeapSnapshot*>(
8011 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
8015 void HeapSnapshot::Delete() {
8016 i::Isolate* isolate = i::Isolate::Current();
8017 if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
8018 ToInternal(this)->Delete();
8020 // If this is the last snapshot, clean up all accessory data as well.
8021 isolate->heap_profiler()->DeleteAllSnapshots();
8026 const HeapGraphNode* HeapSnapshot::GetRoot() const {
8027 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
8031 const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
8032 return reinterpret_cast<const HeapGraphNode*>(
8033 ToInternal(this)->GetEntryById(id));
8037 int HeapSnapshot::GetNodesCount() const {
8038 return ToInternal(this)->entries().length();
8042 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
8043 return reinterpret_cast<const HeapGraphNode*>(
8044 &ToInternal(this)->entries().at(index));
8048 SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
8049 return ToInternal(this)->max_snapshot_js_object_id();
8053 void HeapSnapshot::Serialize(OutputStream* stream,
8054 HeapSnapshot::SerializationFormat format) const {
8055 Utils::ApiCheck(format == kJSON,
8056 "v8::HeapSnapshot::Serialize",
8057 "Unknown serialization format");
8058 Utils::ApiCheck(stream->GetChunkSize() > 0,
8059 "v8::HeapSnapshot::Serialize",
8060 "Invalid stream chunk size");
8061 i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
8062 serializer.Serialize(stream);
8067 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
8068 HeapProfiler::kUnknownObjectId;
8071 int HeapProfiler::GetSnapshotCount() {
8072 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
8076 const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
8077 return reinterpret_cast<const HeapSnapshot*>(
8078 reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
8082 SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) {
8083 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
8084 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
8088 Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
8089 i::Handle<i::Object> obj =
8090 reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
8091 if (obj.is_null()) return Local<Value>();
8092 return Utils::ToLocal(obj);
8096 void HeapProfiler::ClearObjectIds() {
8097 reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
8101 const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
8102 ActivityControl* control, ObjectNameResolver* resolver) {
8103 return reinterpret_cast<const HeapSnapshot*>(
8104 reinterpret_cast<i::HeapProfiler*>(this)
8105 ->TakeSnapshot(control, resolver));
8109 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
8110 reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
8115 void HeapProfiler::StopTrackingHeapObjects() {
8116 reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
8120 SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream,
8121 int64_t* timestamp_us) {
8122 i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
8123 return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
8127 void HeapProfiler::DeleteAllHeapSnapshots() {
8128 reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
8132 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
8133 WrapperInfoCallback callback) {
8134 reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
8139 size_t HeapProfiler::GetProfilerMemorySize() {
8140 return reinterpret_cast<i::HeapProfiler*>(this)->
8141 GetMemorySizeUsedByProfiler();
8145 void HeapProfiler::SetRetainedObjectInfo(UniqueId id,
8146 RetainedObjectInfo* info) {
8147 reinterpret_cast<i::HeapProfiler*>(this)->SetRetainedObjectInfo(id, info);
8151 v8::Testing::StressType internal::Testing::stress_type_ =
8152 v8::Testing::kStressTypeOpt;
8155 void Testing::SetStressRunType(Testing::StressType type) {
8156 internal::Testing::set_stress_type(type);
8160 int Testing::GetStressRuns() {
8161 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
8163 // In debug mode the code runs much slower so stressing will only make two
8172 static void SetFlagsFromString(const char* flags) {
8173 V8::SetFlagsFromString(flags, i::StrLength(flags));
8177 void Testing::PrepareStressRun(int run) {
8178 static const char* kLazyOptimizations =
8179 "--prepare-always-opt "
8180 "--max-inlined-source-size=999999 "
8181 "--max-inlined-nodes=999999 "
8182 "--max-inlined-nodes-cumulative=999999 "
8184 static const char* kForcedOptimizations = "--always-opt";
8186 // If deoptimization stressed turn on frequent deoptimization. If no value
8187 // is spefified through --deopt-every-n-times use a default default value.
8188 static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
8189 if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
8190 internal::FLAG_deopt_every_n_times == 0) {
8191 SetFlagsFromString(kDeoptEvery13Times);
8195 // As stressing in debug mode only make two runs skip the deopt stressing
8197 if (run == GetStressRuns() - 1) {
8198 SetFlagsFromString(kForcedOptimizations);
8200 SetFlagsFromString(kLazyOptimizations);
8203 if (run == GetStressRuns() - 1) {
8204 SetFlagsFromString(kForcedOptimizations);
8205 } else if (run != GetStressRuns() - 2) {
8206 SetFlagsFromString(kLazyOptimizations);
8212 // TODO(svenpanne) Deprecate this.
8213 void Testing::DeoptimizeAll() {
8214 i::Isolate* isolate = i::Isolate::Current();
8215 i::HandleScope scope(isolate);
8216 internal::Deoptimizer::DeoptimizeAll(isolate);
8220 namespace internal {
8223 void HandleScopeImplementer::FreeThreadResources() {
8228 char* HandleScopeImplementer::ArchiveThread(char* storage) {
8229 HandleScopeData* current = isolate_->handle_scope_data();
8230 handle_scope_data_ = *current;
8231 MemCopy(storage, this, sizeof(*this));
8233 ResetAfterArchive();
8234 current->Initialize();
8236 return storage + ArchiveSpacePerThread();
8240 int HandleScopeImplementer::ArchiveSpacePerThread() {
8241 return sizeof(HandleScopeImplementer);
8245 char* HandleScopeImplementer::RestoreThread(char* storage) {
8246 MemCopy(this, storage, sizeof(*this));
8247 *isolate_->handle_scope_data() = handle_scope_data_;
8248 return storage + ArchiveSpacePerThread();
8252 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
8254 bool found_block_before_deferred = false;
8256 // Iterate over all handles in the blocks except for the last.
8257 for (int i = blocks()->length() - 2; i >= 0; --i) {
8258 Object** block = blocks()->at(i);
8259 if (last_handle_before_deferred_block_ != NULL &&
8260 (last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) &&
8261 (last_handle_before_deferred_block_ >= block)) {
8262 v->VisitPointers(block, last_handle_before_deferred_block_);
8263 DCHECK(!found_block_before_deferred);
8265 found_block_before_deferred = true;
8268 v->VisitPointers(block, &block[kHandleBlockSize]);
8272 DCHECK(last_handle_before_deferred_block_ == NULL ||
8273 found_block_before_deferred);
8275 // Iterate over live handles in the last block (if any).
8276 if (!blocks()->is_empty()) {
8277 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
8280 List<Context*>* context_lists[2] = { &saved_contexts_, &entered_contexts_};
8281 for (unsigned i = 0; i < arraysize(context_lists); i++) {
8282 if (context_lists[i]->is_empty()) continue;
8283 Object** start = reinterpret_cast<Object**>(&context_lists[i]->first());
8284 v->VisitPointers(start, start + context_lists[i]->length());
8289 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
8290 HandleScopeData* current = isolate_->handle_scope_data();
8291 handle_scope_data_ = *current;
8296 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
8297 HandleScopeImplementer* scope_implementer =
8298 reinterpret_cast<HandleScopeImplementer*>(storage);
8299 scope_implementer->IterateThis(v);
8300 return storage + ArchiveSpacePerThread();
8304 DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) {
8305 DeferredHandles* deferred =
8306 new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
8308 while (!blocks_.is_empty()) {
8309 Object** block_start = blocks_.last();
8310 Object** block_limit = &block_start[kHandleBlockSize];
8311 // We should not need to check for SealHandleScope here. Assert this.
8312 DCHECK(prev_limit == block_limit ||
8313 !(block_start <= prev_limit && prev_limit <= block_limit));
8314 if (prev_limit == block_limit) break;
8315 deferred->blocks_.Add(blocks_.last());
8316 blocks_.RemoveLast();
8319 // deferred->blocks_ now contains the blocks installed on the
8320 // HandleScope stack since BeginDeferredScope was called, but in
8323 DCHECK(prev_limit == NULL || !blocks_.is_empty());
8325 DCHECK(!blocks_.is_empty() && prev_limit != NULL);
8326 DCHECK(last_handle_before_deferred_block_ != NULL);
8327 last_handle_before_deferred_block_ = NULL;
8332 void HandleScopeImplementer::BeginDeferredScope() {
8333 DCHECK(last_handle_before_deferred_block_ == NULL);
8334 last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
8338 DeferredHandles::~DeferredHandles() {
8339 isolate_->UnlinkDeferredHandles(this);
8341 for (int i = 0; i < blocks_.length(); i++) {
8342 #ifdef ENABLE_HANDLE_ZAPPING
8343 HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
8345 isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
8350 void DeferredHandles::Iterate(ObjectVisitor* v) {
8351 DCHECK(!blocks_.is_empty());
8353 DCHECK((first_block_limit_ >= blocks_.first()) &&
8354 (first_block_limit_ <= &(blocks_.first())[kHandleBlockSize]));
8356 v->VisitPointers(blocks_.first(), first_block_limit_);
8358 for (int i = 1; i < blocks_.length(); i++) {
8359 v->VisitPointers(blocks_[i], &blocks_[i][kHandleBlockSize]);
8364 void InvokeAccessorGetterCallback(
8365 v8::Local<v8::Name> property,
8366 const v8::PropertyCallbackInfo<v8::Value>& info,
8367 v8::AccessorNameGetterCallback getter) {
8368 // Leaving JavaScript.
8369 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8370 Address getter_address = reinterpret_cast<Address>(reinterpret_cast<intptr_t>(
8372 VMState<EXTERNAL> state(isolate);
8373 ExternalCallbackScope call_scope(isolate, getter_address);
8374 getter(property, info);
8378 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
8379 v8::FunctionCallback callback) {
8380 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8381 Address callback_address =
8382 reinterpret_cast<Address>(reinterpret_cast<intptr_t>(callback));
8383 VMState<EXTERNAL> state(isolate);
8384 ExternalCallbackScope call_scope(isolate, callback_address);
8389 } // namespace internal