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/code-stubs.h"
24 #include "src/compiler.h"
25 #include "src/contexts.h"
26 #include "src/conversions-inl.h"
27 #include "src/counters.h"
28 #include "src/cpu-profiler.h"
29 #include "src/debug.h"
30 #include "src/deoptimizer.h"
31 #include "src/execution.h"
32 #include "src/global-handles.h"
33 #include "src/heap/spaces.h"
34 #include "src/heap-profiler.h"
35 #include "src/heap-snapshot-generator-inl.h"
36 #include "src/icu_util.h"
37 #include "src/json-parser.h"
38 #include "src/messages.h"
39 #include "src/parser.h"
40 #include "src/pending-compilation-error-handler.h"
41 #include "src/profile-generator-inl.h"
42 #include "src/property.h"
43 #include "src/property-details.h"
44 #include "src/prototype.h"
45 #include "src/runtime/runtime.h"
46 #include "src/runtime-profiler.h"
47 #include "src/sampler.h"
48 #include "src/scanner-character-streams.h"
49 #include "src/simulator.h"
50 #include "src/snapshot/natives.h"
51 #include "src/snapshot/snapshot.h"
52 #include "src/startup-data-util.h"
53 #include "src/unicode-inl.h"
54 #include "src/v8threads.h"
55 #include "src/version.h"
56 #include "src/vm-state-inl.h"
61 #define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
64 #define ENTER_V8(isolate) i::VMState<v8::OTHER> __state__((isolate))
67 #define PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name, \
68 bailout_value, HandleScopeClass, \
70 if (IsExecutionTerminatingCheck(isolate)) { \
71 return bailout_value; \
73 HandleScopeClass handle_scope(isolate); \
74 CallDepthScope call_depth_scope(isolate, context, do_callback); \
75 LOG_API(isolate, function_name); \
77 bool has_pending_exception = false
80 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT( \
81 context, function_name, bailout_value, HandleScopeClass, do_callback) \
82 auto isolate = context.IsEmpty() \
83 ? i::Isolate::Current() \
84 : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \
85 PREPARE_FOR_EXECUTION_GENERIC(isolate, context, function_name, \
86 bailout_value, HandleScopeClass, do_callback);
89 #define PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, function_name, T) \
90 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(), function_name, \
91 MaybeLocal<T>(), InternalEscapableScope, \
95 #define PREPARE_FOR_EXECUTION(context, function_name, T) \
96 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
97 InternalEscapableScope, false)
100 #define PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, function_name, T) \
101 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, MaybeLocal<T>(), \
102 InternalEscapableScope, true)
105 #define PREPARE_FOR_EXECUTION_PRIMITIVE(context, function_name, T) \
106 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, function_name, Nothing<T>(), \
107 i::HandleScope, false)
110 #define EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, value) \
112 if (has_pending_exception) { \
113 call_depth_scope.Escape(); \
119 #define RETURN_ON_FAILED_EXECUTION(T) \
120 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, MaybeLocal<T>())
123 #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \
124 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, Nothing<T>())
127 #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \
128 return maybe_local.FromMaybe(Local<T>());
131 #define RETURN_ESCAPED(value) return handle_scope.Escape(value);
136 Local<Context> ContextFromHeapObject(i::Handle<i::Object> obj) {
137 return reinterpret_cast<v8::Isolate*>(i::HeapObject::cast(*obj)->GetIsolate())
138 ->GetCurrentContext();
141 class InternalEscapableScope : public v8::EscapableHandleScope {
143 explicit inline InternalEscapableScope(i::Isolate* isolate)
144 : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {}
148 class CallDepthScope {
150 explicit CallDepthScope(i::Isolate* isolate, Local<Context> context,
155 do_callback_(do_callback) {
156 // TODO(dcarney): remove this when blink stops crashing.
157 DCHECK(!isolate_->external_caught_exception());
158 isolate_->handle_scope_implementer()->IncrementCallDepth();
159 if (!context_.IsEmpty()) context_->Enter();
162 if (!context_.IsEmpty()) context_->Exit();
163 if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth();
164 if (do_callback_) isolate_->FireCallCompletedCallback();
170 auto handle_scope_implementer = isolate_->handle_scope_implementer();
171 handle_scope_implementer->DecrementCallDepth();
172 bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero();
173 isolate_->OptionalRescheduleException(call_depth_is_zero);
177 i::Isolate* const isolate_;
178 Local<Context> context_;
186 static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate,
187 i::Handle<i::Script> script) {
188 i::Handle<i::Object> scriptName(i::Script::GetNameOrSourceURL(script));
189 i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate);
190 v8::Isolate* v8_isolate =
191 reinterpret_cast<v8::Isolate*>(script->GetIsolate());
192 ScriptOriginOptions options(script->origin_options());
193 v8::ScriptOrigin origin(
194 Utils::ToLocal(scriptName),
195 v8::Integer::New(v8_isolate, script->line_offset()->value()),
196 v8::Integer::New(v8_isolate, script->column_offset()->value()),
197 v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()),
198 v8::Integer::New(v8_isolate, script->id()->value()),
199 v8::Boolean::New(v8_isolate, options.IsEmbedderDebugScript()),
200 Utils::ToLocal(source_map_url),
201 v8::Boolean::New(v8_isolate, options.IsOpaque()));
206 // --- E x c e p t i o n B e h a v i o r ---
209 void i::FatalProcessOutOfMemory(const char* location) {
210 i::V8::FatalProcessOutOfMemory(location, false);
214 // When V8 cannot allocated memory FatalProcessOutOfMemory is called.
215 // The default fatal error handler is called and execution is stopped.
216 void i::V8::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
217 i::Isolate* isolate = i::Isolate::Current();
218 char last_few_messages[Heap::kTraceRingBufferSize + 1];
219 char js_stacktrace[Heap::kStacktraceBufferSize + 1];
220 memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
221 memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1);
223 i::HeapStats heap_stats;
225 heap_stats.start_marker = &start_marker;
227 heap_stats.new_space_size = &new_space_size;
228 int new_space_capacity;
229 heap_stats.new_space_capacity = &new_space_capacity;
230 intptr_t old_space_size;
231 heap_stats.old_space_size = &old_space_size;
232 intptr_t old_space_capacity;
233 heap_stats.old_space_capacity = &old_space_capacity;
234 intptr_t code_space_size;
235 heap_stats.code_space_size = &code_space_size;
236 intptr_t code_space_capacity;
237 heap_stats.code_space_capacity = &code_space_capacity;
238 intptr_t map_space_size;
239 heap_stats.map_space_size = &map_space_size;
240 intptr_t map_space_capacity;
241 heap_stats.map_space_capacity = &map_space_capacity;
242 intptr_t lo_space_size;
243 heap_stats.lo_space_size = &lo_space_size;
244 int global_handle_count;
245 heap_stats.global_handle_count = &global_handle_count;
246 int weak_global_handle_count;
247 heap_stats.weak_global_handle_count = &weak_global_handle_count;
248 int pending_global_handle_count;
249 heap_stats.pending_global_handle_count = &pending_global_handle_count;
250 int near_death_global_handle_count;
251 heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
252 int free_global_handle_count;
253 heap_stats.free_global_handle_count = &free_global_handle_count;
254 intptr_t memory_allocator_size;
255 heap_stats.memory_allocator_size = &memory_allocator_size;
256 intptr_t memory_allocator_capacity;
257 heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
258 int objects_per_type[LAST_TYPE + 1] = {0};
259 heap_stats.objects_per_type = objects_per_type;
260 int size_per_type[LAST_TYPE + 1] = {0};
261 heap_stats.size_per_type = size_per_type;
263 heap_stats.os_error = &os_error;
264 heap_stats.last_few_messages = last_few_messages;
265 heap_stats.js_stacktrace = js_stacktrace;
267 heap_stats.end_marker = &end_marker;
268 if (isolate->heap()->HasBeenSetUp()) {
269 // BUG(1718): Don't use the take_snapshot since we don't support
270 // HeapIterator here without doing a special GC.
271 isolate->heap()->RecordStats(&heap_stats, false);
272 char* first_newline = strchr(last_few_messages, '\n');
273 if (first_newline == NULL || first_newline[1] == '\0')
274 first_newline = last_few_messages;
275 PrintF("\n<--- Last few GCs --->\n%s\n", first_newline);
276 PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace);
278 Utils::ApiCheck(false, location, "Allocation failed - process out of memory");
279 // If the fatal error handler returns, we stop execution.
280 FATAL("API fatal error handler returned after process out of memory");
284 void Utils::ReportApiFailure(const char* location, const char* message) {
285 i::Isolate* isolate = i::Isolate::Current();
286 FatalErrorCallback callback = isolate->exception_behavior();
287 if (callback == NULL) {
288 base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
292 callback(location, message);
294 isolate->SignalFatalError();
298 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
299 if (isolate->has_scheduled_exception()) {
300 return isolate->scheduled_exception() ==
301 isolate->heap()->termination_exception();
307 void V8::SetNativesDataBlob(StartupData* natives_blob) {
308 i::V8::SetNativesBlob(natives_blob);
312 void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
313 i::V8::SetSnapshotBlob(snapshot_blob);
317 bool RunExtraCode(Isolate* isolate, Local<Context> context,
318 const char* utf8_source) {
319 // Run custom script if provided.
320 base::ElapsedTimer timer;
322 TryCatch try_catch(isolate);
323 Local<String> source_string;
324 if (!String::NewFromUtf8(isolate, utf8_source, NewStringType::kNormal)
325 .ToLocal(&source_string)) {
328 Local<String> resource_name =
329 String::NewFromUtf8(isolate, "<embedded script>", NewStringType::kNormal)
331 ScriptOrigin origin(resource_name);
332 ScriptCompiler::Source source(source_string, origin);
333 Local<Script> script;
334 if (!ScriptCompiler::Compile(context, &source).ToLocal(&script)) return false;
335 if (script->Run(context).IsEmpty()) return false;
336 if (i::FLAG_profile_deserialization) {
337 i::PrintF("Executing custom snapshot script took %0.3f ms\n",
338 timer.Elapsed().InMillisecondsF());
341 CHECK(!try_catch.HasCaught());
348 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
350 virtual void* Allocate(size_t length) {
351 void* data = AllocateUninitialized(length);
352 return data == NULL ? data : memset(data, 0, length);
354 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
355 virtual void Free(void* data, size_t) { free(data); }
361 StartupData V8::CreateSnapshotDataBlob(const char* custom_source) {
362 i::Isolate* internal_isolate = new i::Isolate(true);
363 ArrayBufferAllocator allocator;
364 internal_isolate->set_array_buffer_allocator(&allocator);
365 Isolate* isolate = reinterpret_cast<Isolate*>(internal_isolate);
366 StartupData result = {NULL, 0};
368 base::ElapsedTimer timer;
370 Isolate::Scope isolate_scope(isolate);
371 internal_isolate->set_creating_default_snapshot(true);
372 internal_isolate->Init(NULL);
373 Persistent<Context> context;
374 i::Snapshot::Metadata metadata;
376 HandleScope handle_scope(isolate);
377 Local<Context> new_context = Context::New(isolate);
378 internal_isolate->set_creating_default_snapshot(false);
379 context.Reset(isolate, new_context);
380 if (custom_source != NULL) {
381 metadata.set_embeds_script(true);
382 Context::Scope context_scope(new_context);
383 if (!RunExtraCode(isolate, new_context, custom_source)) context.Reset();
386 if (!context.IsEmpty()) {
387 // Make sure all builtin scripts are cached.
389 HandleScope scope(isolate);
390 for (int i = 0; i < i::Natives::GetBuiltinsCount(); i++) {
391 internal_isolate->bootstrapper()->SourceLookup<i::Natives>(i);
394 // If we don't do this then we end up with a stray root pointing at the
395 // context even after we have disposed of the context.
396 internal_isolate->heap()->CollectAllAvailableGarbage("mksnapshot");
397 i::Object* raw_context = *v8::Utils::OpenPersistent(context);
400 i::SnapshotByteSink snapshot_sink;
401 i::StartupSerializer ser(internal_isolate, &snapshot_sink);
402 ser.SerializeStrongReferences();
404 i::SnapshotByteSink context_sink;
405 i::PartialSerializer context_ser(internal_isolate, &ser, &context_sink);
406 context_ser.Serialize(&raw_context);
407 ser.SerializeWeakReferencesAndDeferred();
409 result = i::Snapshot::CreateSnapshotBlob(ser, context_ser, metadata);
411 if (i::FLAG_profile_deserialization) {
412 i::PrintF("Creating snapshot took %0.3f ms\n",
413 timer.Elapsed().InMillisecondsF());
422 void V8::SetFlagsFromString(const char* str, int length) {
423 i::FlagList::SetFlagsFromString(str, length);
427 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
428 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
432 RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
435 RegisteredExtension::RegisteredExtension(Extension* extension)
436 : extension_(extension) { }
439 void RegisteredExtension::Register(RegisteredExtension* that) {
440 that->next_ = first_extension_;
441 first_extension_ = that;
445 void RegisteredExtension::UnregisterAll() {
446 RegisteredExtension* re = first_extension_;
448 RegisteredExtension* next = re->next();
452 first_extension_ = NULL;
456 void RegisterExtension(Extension* that) {
457 RegisteredExtension* extension = new RegisteredExtension(that);
458 RegisteredExtension::Register(extension);
462 Extension::Extension(const char* name,
468 source_length_(source_length >= 0 ?
470 (source ? static_cast<int>(strlen(source)) : 0)),
471 source_(source, source_length_),
472 dep_count_(dep_count),
474 auto_enable_(false) {
475 CHECK(source != NULL || source_length_ == 0);
479 ResourceConstraints::ResourceConstraints()
480 : max_semi_space_size_(0),
481 max_old_space_size_(0),
482 max_executable_size_(0),
484 max_available_threads_(0),
485 code_range_size_(0) { }
487 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
488 uint64_t virtual_memory_limit,
489 uint32_t number_of_processors) {
490 ConfigureDefaults(physical_memory, virtual_memory_limit);
493 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
494 uint64_t virtual_memory_limit) {
496 // Android has higher physical memory requirements before raising the maximum
497 // heap size limits since it has no swap space.
498 const uint64_t low_limit = 512ul * i::MB;
499 const uint64_t medium_limit = 1ul * i::GB;
500 const uint64_t high_limit = 2ul * i::GB;
502 const uint64_t low_limit = 512ul * i::MB;
503 const uint64_t medium_limit = 768ul * i::MB;
504 const uint64_t high_limit = 1ul * i::GB;
507 if (physical_memory <= low_limit) {
508 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeLowMemoryDevice);
509 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeLowMemoryDevice);
510 set_max_executable_size(i::Heap::kMaxExecutableSizeLowMemoryDevice);
511 } else if (physical_memory <= medium_limit) {
512 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeMediumMemoryDevice);
513 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeMediumMemoryDevice);
514 set_max_executable_size(i::Heap::kMaxExecutableSizeMediumMemoryDevice);
515 } else if (physical_memory <= high_limit) {
516 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHighMemoryDevice);
517 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHighMemoryDevice);
518 set_max_executable_size(i::Heap::kMaxExecutableSizeHighMemoryDevice);
520 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHugeMemoryDevice);
521 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHugeMemoryDevice);
522 set_max_executable_size(i::Heap::kMaxExecutableSizeHugeMemoryDevice);
525 if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
526 // Reserve no more than 1/8 of the memory for the code range, but at most
527 // kMaximalCodeRangeSize.
529 i::Min(i::kMaximalCodeRangeSize / i::MB,
530 static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
535 void SetResourceConstraints(i::Isolate* isolate,
536 const ResourceConstraints& constraints) {
537 int semi_space_size = constraints.max_semi_space_size();
538 int old_space_size = constraints.max_old_space_size();
539 int max_executable_size = constraints.max_executable_size();
540 size_t code_range_size = constraints.code_range_size();
541 if (semi_space_size != 0 || old_space_size != 0 ||
542 max_executable_size != 0 || code_range_size != 0) {
543 isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
544 max_executable_size, code_range_size);
546 if (constraints.stack_limit() != NULL) {
547 uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
548 isolate->stack_guard()->SetStackLimit(limit);
553 i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** obj) {
554 LOG_API(isolate, "Persistent::New");
555 i::Handle<i::Object> result = isolate->global_handles()->Create(*obj);
557 if (i::FLAG_verify_heap) {
558 (*obj)->ObjectVerify();
560 #endif // VERIFY_HEAP
561 return result.location();
565 i::Object** V8::CopyPersistent(i::Object** obj) {
566 i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj);
568 if (i::FLAG_verify_heap) {
569 (*obj)->ObjectVerify();
571 #endif // VERIFY_HEAP
572 return result.location();
576 void V8::MakeWeak(i::Object** object, void* parameter,
577 WeakCallback weak_callback) {
578 i::GlobalHandles::MakeWeak(object, parameter, weak_callback);
582 void V8::MakeWeak(i::Object** object, void* parameter,
583 int internal_field_index1, int internal_field_index2,
584 WeakCallbackInfo<void>::Callback weak_callback) {
585 WeakCallbackType type = WeakCallbackType::kParameter;
586 if (internal_field_index1 == 0) {
587 if (internal_field_index2 == 1) {
588 type = WeakCallbackType::kInternalFields;
590 DCHECK_EQ(internal_field_index2, -1);
591 type = WeakCallbackType::kInternalFields;
594 DCHECK_EQ(internal_field_index1, -1);
595 DCHECK_EQ(internal_field_index2, -1);
597 i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
601 void V8::MakeWeak(i::Object** object, void* parameter,
602 WeakCallbackInfo<void>::Callback weak_callback,
603 WeakCallbackType type) {
604 i::GlobalHandles::MakeWeak(object, parameter, weak_callback, type);
608 void* V8::ClearWeak(i::Object** obj) {
609 return i::GlobalHandles::ClearWeakness(obj);
613 void V8::DisposeGlobal(i::Object** obj) {
614 i::GlobalHandles::Destroy(obj);
618 void V8::Eternalize(Isolate* v8_isolate, Value* value, int* index) {
619 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
620 i::Object* object = *Utils::OpenHandle(value);
621 isolate->eternal_handles()->Create(isolate, object, index);
625 Local<Value> V8::GetEternal(Isolate* v8_isolate, int index) {
626 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
627 return Utils::ToLocal(isolate->eternal_handles()->Get(index));
631 void V8::FromJustIsNothing() {
632 Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing.");
636 void V8::ToLocalEmpty() {
637 Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal.");
641 void V8::InternalFieldOutOfBounds(int index) {
642 Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback,
643 "WeakCallbackInfo::GetInternalField",
644 "Internal field out of bounds.");
648 // --- H a n d l e s ---
651 HandleScope::HandleScope(Isolate* isolate) {
656 void HandleScope::Initialize(Isolate* isolate) {
657 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
658 // We do not want to check the correct usage of the Locker class all over the
659 // place, so we do it only here: Without a HandleScope, an embedder can do
660 // almost nothing, so it is enough to check in this central place.
661 // We make an exception if the serializer is enabled, which means that the
662 // Isolate is exclusively used to create a snapshot.
664 !v8::Locker::IsActive() ||
665 internal_isolate->thread_manager()->IsLockedByCurrentThread() ||
666 internal_isolate->serializer_enabled(),
667 "HandleScope::HandleScope",
668 "Entering the V8 API without proper locking in place");
669 i::HandleScopeData* current = internal_isolate->handle_scope_data();
670 isolate_ = internal_isolate;
671 prev_next_ = current->next;
672 prev_limit_ = current->limit;
677 HandleScope::~HandleScope() {
678 i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
682 int HandleScope::NumberOfHandles(Isolate* isolate) {
683 return i::HandleScope::NumberOfHandles(
684 reinterpret_cast<i::Isolate*>(isolate));
688 i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) {
689 return i::HandleScope::CreateHandle(isolate, value);
693 i::Object** HandleScope::CreateHandle(i::HeapObject* heap_object,
695 DCHECK(heap_object->IsHeapObject());
696 return i::HandleScope::CreateHandle(heap_object->GetIsolate(), value);
700 EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
701 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
702 escape_slot_ = CreateHandle(isolate, isolate->heap()->the_hole_value());
703 Initialize(v8_isolate);
707 i::Object** EscapableHandleScope::Escape(i::Object** escape_value) {
708 i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
709 Utils::ApiCheck(*escape_slot_ == heap->the_hole_value(),
710 "EscapeableHandleScope::Escape",
711 "Escape value set twice");
712 if (escape_value == NULL) {
713 *escape_slot_ = heap->undefined_value();
716 *escape_slot_ = *escape_value;
721 SealHandleScope::SealHandleScope(Isolate* isolate) {
722 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
724 isolate_ = internal_isolate;
725 i::HandleScopeData* current = internal_isolate->handle_scope_data();
726 prev_limit_ = current->limit;
727 current->limit = current->next;
728 prev_level_ = current->level;
733 SealHandleScope::~SealHandleScope() {
734 i::HandleScopeData* current = isolate_->handle_scope_data();
735 DCHECK_EQ(0, current->level);
736 current->level = prev_level_;
737 DCHECK_EQ(current->next, current->limit);
738 current->limit = prev_limit_;
742 void Context::Enter() {
743 i::Handle<i::Context> env = Utils::OpenHandle(this);
744 i::Isolate* isolate = env->GetIsolate();
746 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
747 impl->EnterContext(env);
748 impl->SaveContext(isolate->context());
749 isolate->set_context(*env);
753 void Context::Exit() {
754 i::Handle<i::Context> env = Utils::OpenHandle(this);
755 i::Isolate* isolate = env->GetIsolate();
757 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
758 if (!Utils::ApiCheck(impl->LastEnteredContextWas(env),
759 "v8::Context::Exit()",
760 "Cannot exit non-entered context")) {
763 impl->LeaveContext();
764 isolate->set_context(impl->RestoreContext());
768 static void* DecodeSmiToAligned(i::Object* value, const char* location) {
769 Utils::ApiCheck(value->IsSmi(), location, "Not a Smi");
770 return reinterpret_cast<void*>(value);
774 static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) {
775 i::Smi* smi = reinterpret_cast<i::Smi*>(value);
776 Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned");
781 static i::Handle<i::FixedArray> EmbedderDataFor(Context* context,
784 const char* location) {
785 i::Handle<i::Context> env = Utils::OpenHandle(context);
787 Utils::ApiCheck(env->IsNativeContext(),
789 "Not a native context") &&
790 Utils::ApiCheck(index >= 0, location, "Negative index");
791 if (!ok) return i::Handle<i::FixedArray>();
792 i::Handle<i::FixedArray> data(env->embedder_data());
793 if (index < data->length()) return data;
794 if (!Utils::ApiCheck(can_grow, location, "Index too large")) {
795 return i::Handle<i::FixedArray>();
797 int new_size = i::Max(index, data->length() << 1) + 1;
798 data = i::FixedArray::CopySize(data, new_size);
799 env->set_embedder_data(*data);
804 v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
805 const char* location = "v8::Context::GetEmbedderData()";
806 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
807 if (data.is_null()) return Local<Value>();
808 i::Handle<i::Object> result(data->get(index), data->GetIsolate());
809 return Utils::ToLocal(result);
813 void Context::SetEmbedderData(int index, v8::Local<Value> value) {
814 const char* location = "v8::Context::SetEmbedderData()";
815 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
816 if (data.is_null()) return;
817 i::Handle<i::Object> val = Utils::OpenHandle(*value);
818 data->set(index, *val);
819 DCHECK_EQ(*Utils::OpenHandle(*value),
820 *Utils::OpenHandle(*GetEmbedderData(index)));
824 void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
825 const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
826 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
827 if (data.is_null()) return NULL;
828 return DecodeSmiToAligned(data->get(index), location);
832 void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
833 const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
834 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
835 data->set(index, EncodeAlignedAsSmi(value, location));
836 DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
840 // --- N e a n d e r ---
843 // A constructor cannot easily return an error value, therefore it is necessary
844 // to check for a dead VM with ON_BAILOUT before constructing any Neander
845 // objects. To remind you about this there is no HandleScope in the
846 // NeanderObject constructor. When you add one to the site calling the
847 // constructor you should check that you ensured the VM was not dead first.
848 NeanderObject::NeanderObject(v8::internal::Isolate* isolate, int size) {
850 value_ = isolate->factory()->NewNeanderObject();
851 i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
852 value_->set_elements(*elements);
856 int NeanderObject::size() {
857 return i::FixedArray::cast(value_->elements())->length();
861 NeanderArray::NeanderArray(v8::internal::Isolate* isolate) : obj_(isolate, 2) {
862 obj_.set(0, i::Smi::FromInt(0));
866 int NeanderArray::length() {
867 return i::Smi::cast(obj_.get(0))->value();
871 i::Object* NeanderArray::get(int offset) {
873 DCHECK(offset < length());
874 return obj_.get(offset + 1);
878 // This method cannot easily return an error value, therefore it is necessary
879 // to check for a dead VM with ON_BAILOUT before calling it. To remind you
880 // about this there is no HandleScope in this method. When you add one to the
881 // site calling this method you should check that you ensured the VM was not
883 void NeanderArray::add(i::Isolate* isolate, i::Handle<i::Object> value) {
884 int length = this->length();
885 int size = obj_.size();
886 if (length == size - 1) {
887 i::Factory* factory = isolate->factory();
888 i::Handle<i::FixedArray> new_elms = factory->NewFixedArray(2 * size);
889 for (int i = 0; i < length; i++)
890 new_elms->set(i + 1, get(i));
891 obj_.value()->set_elements(*new_elms);
893 obj_.set(length + 1, *value);
894 obj_.set(0, i::Smi::FromInt(length + 1));
898 void NeanderArray::set(int index, i::Object* value) {
899 if (index < 0 || index >= this->length()) return;
900 obj_.set(index + 1, value);
904 // --- T e m p l a t e ---
907 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
908 that->set_number_of_properties(0);
909 that->set_tag(i::Smi::FromInt(type));
913 void Template::Set(v8::Local<Name> name, v8::Local<Data> value,
914 v8::PropertyAttribute attribute) {
915 auto templ = Utils::OpenHandle(this);
916 i::Isolate* isolate = templ->GetIsolate();
918 i::HandleScope scope(isolate);
919 // TODO(dcarney): split api to allow values of v8::Value or v8::TemplateInfo.
920 i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name),
921 Utils::OpenHandle(*value),
922 static_cast<PropertyAttributes>(attribute));
926 void Template::SetAccessorProperty(
927 v8::Local<v8::Name> name,
928 v8::Local<FunctionTemplate> getter,
929 v8::Local<FunctionTemplate> setter,
930 v8::PropertyAttribute attribute,
931 v8::AccessControl access_control) {
932 // TODO(verwaest): Remove |access_control|.
933 DCHECK_EQ(v8::DEFAULT, access_control);
934 auto templ = Utils::OpenHandle(this);
935 auto isolate = templ->GetIsolate();
937 DCHECK(!name.IsEmpty());
938 DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
939 i::HandleScope scope(isolate);
940 i::ApiNatives::AddAccessorProperty(
941 isolate, templ, Utils::OpenHandle(*name),
942 Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true),
943 static_cast<PropertyAttributes>(attribute));
947 // --- F u n c t i o n T e m p l a t e ---
948 static void InitializeFunctionTemplate(
949 i::Handle<i::FunctionTemplateInfo> info) {
950 InitializeTemplate(info, Consts::FUNCTION_TEMPLATE);
955 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
956 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
958 i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(),
960 if (result->IsUndefined()) {
961 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(i_isolate);
962 result = Utils::OpenHandle(*ObjectTemplate::New(isolate));
963 Utils::OpenHandle(this)->set_prototype_template(*result);
965 return ToApiHandle<ObjectTemplate>(result);
969 static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info,
971 Utils::ApiCheck(!info->instantiated(), func,
972 "FunctionTemplate already instantiated");
976 void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) {
977 auto info = Utils::OpenHandle(this);
978 EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit");
979 i::Isolate* isolate = info->GetIsolate();
981 info->set_parent_template(*Utils::OpenHandle(*value));
985 static Local<FunctionTemplate> FunctionTemplateNew(
986 i::Isolate* isolate, FunctionCallback callback, v8::Local<Value> data,
987 v8::Local<Signature> signature, int length, bool do_not_cache) {
988 i::Handle<i::Struct> struct_obj =
989 isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
990 i::Handle<i::FunctionTemplateInfo> obj =
991 i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
992 InitializeFunctionTemplate(obj);
993 obj->set_do_not_cache(do_not_cache);
994 int next_serial_number = 0;
996 next_serial_number = isolate->next_serial_number() + 1;
997 isolate->set_next_serial_number(next_serial_number);
999 obj->set_serial_number(i::Smi::FromInt(next_serial_number));
1000 if (callback != 0) {
1001 if (data.IsEmpty()) {
1002 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1004 Utils::ToLocal(obj)->SetCallHandler(callback, data);
1006 obj->set_length(length);
1007 obj->set_undetectable(false);
1008 obj->set_needs_access_check(false);
1009 obj->set_accept_any_receiver(true);
1010 if (!signature.IsEmpty())
1011 obj->set_signature(*Utils::OpenHandle(*signature));
1012 return Utils::ToLocal(obj);
1015 Local<FunctionTemplate> FunctionTemplate::New(Isolate* isolate,
1016 FunctionCallback callback,
1017 v8::Local<Value> data,
1018 v8::Local<Signature> signature,
1020 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1021 // Changes to the environment cannot be captured in the snapshot. Expect no
1022 // function templates when the isolate is created for serialization.
1023 DCHECK(!i_isolate->serializer_enabled());
1024 LOG_API(i_isolate, "FunctionTemplate::New");
1025 ENTER_V8(i_isolate);
1026 return FunctionTemplateNew(
1027 i_isolate, callback, data, signature, length, false);
1031 Local<Signature> Signature::New(Isolate* isolate,
1032 Local<FunctionTemplate> receiver) {
1033 return Utils::SignatureToLocal(Utils::OpenHandle(*receiver));
1037 Local<AccessorSignature> AccessorSignature::New(
1038 Isolate* isolate, Local<FunctionTemplate> receiver) {
1039 return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
1043 Local<TypeSwitch> TypeSwitch::New(Local<FunctionTemplate> type) {
1044 Local<FunctionTemplate> types[1] = {type};
1045 return TypeSwitch::New(1, types);
1049 Local<TypeSwitch> TypeSwitch::New(int argc, Local<FunctionTemplate> types[]) {
1050 i::Isolate* isolate = i::Isolate::Current();
1051 LOG_API(isolate, "TypeSwitch::New");
1053 i::Handle<i::FixedArray> vector = isolate->factory()->NewFixedArray(argc);
1054 for (int i = 0; i < argc; i++)
1055 vector->set(i, *Utils::OpenHandle(*types[i]));
1056 i::Handle<i::Struct> struct_obj =
1057 isolate->factory()->NewStruct(i::TYPE_SWITCH_INFO_TYPE);
1058 i::Handle<i::TypeSwitchInfo> obj =
1059 i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
1060 obj->set_types(*vector);
1061 return Utils::ToLocal(obj);
1065 int TypeSwitch::match(v8::Local<Value> value) {
1066 i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
1067 LOG_API(info->GetIsolate(), "TypeSwitch::match");
1068 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
1069 i::FixedArray* types = i::FixedArray::cast(info->types());
1070 for (int i = 0; i < types->length(); i++) {
1071 if (i::FunctionTemplateInfo::cast(types->get(i))->IsTemplateFor(*obj))
1078 #define SET_FIELD_WRAPPED(obj, setter, cdata) do { \
1079 i::Handle<i::Object> foreign = FromCData(obj->GetIsolate(), cdata); \
1080 (obj)->setter(*foreign); \
1084 void FunctionTemplate::SetCallHandler(FunctionCallback callback,
1085 v8::Local<Value> data) {
1086 auto info = Utils::OpenHandle(this);
1087 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler");
1088 i::Isolate* isolate = info->GetIsolate();
1090 i::HandleScope scope(isolate);
1091 i::Handle<i::Struct> struct_obj =
1092 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1093 i::Handle<i::CallHandlerInfo> obj =
1094 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1095 SET_FIELD_WRAPPED(obj, set_callback, callback);
1096 if (data.IsEmpty()) {
1097 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1099 obj->set_data(*Utils::OpenHandle(*data));
1100 info->set_call_code(*obj);
1104 static i::Handle<i::AccessorInfo> SetAccessorInfoProperties(
1105 i::Handle<i::AccessorInfo> obj, v8::Local<Name> name,
1106 v8::AccessControl settings, v8::PropertyAttribute attributes,
1107 v8::Local<AccessorSignature> signature) {
1108 obj->set_name(*Utils::OpenHandle(*name));
1109 if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
1110 if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
1111 obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
1112 if (!signature.IsEmpty()) {
1113 obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
1119 template <typename Getter, typename Setter>
1120 static i::Handle<i::AccessorInfo> MakeAccessorInfo(
1121 v8::Local<Name> name, Getter getter, Setter setter, v8::Local<Value> data,
1122 v8::AccessControl settings, v8::PropertyAttribute attributes,
1123 v8::Local<AccessorSignature> signature) {
1124 i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate();
1125 i::Handle<i::ExecutableAccessorInfo> obj =
1126 isolate->factory()->NewExecutableAccessorInfo();
1127 SET_FIELD_WRAPPED(obj, set_getter, getter);
1128 SET_FIELD_WRAPPED(obj, set_setter, setter);
1129 if (data.IsEmpty()) {
1130 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1132 obj->set_data(*Utils::OpenHandle(*data));
1133 return SetAccessorInfoProperties(obj, name, settings, attributes, signature);
1137 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
1138 i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
1139 if (!Utils::ApiCheck(!handle.is_null(),
1140 "v8::FunctionTemplate::InstanceTemplate()",
1141 "Reading from empty handle")) {
1142 return Local<ObjectTemplate>();
1144 i::Isolate* isolate = handle->GetIsolate();
1146 if (handle->instance_template()->IsUndefined()) {
1147 Local<ObjectTemplate> templ =
1148 ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
1149 handle->set_instance_template(*Utils::OpenHandle(*templ));
1151 i::Handle<i::ObjectTemplateInfo> result(
1152 i::ObjectTemplateInfo::cast(handle->instance_template()));
1153 return Utils::ToLocal(result);
1157 void FunctionTemplate::SetLength(int length) {
1158 auto info = Utils::OpenHandle(this);
1159 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength");
1160 auto isolate = info->GetIsolate();
1162 info->set_length(length);
1166 void FunctionTemplate::SetClassName(Local<String> name) {
1167 auto info = Utils::OpenHandle(this);
1168 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName");
1169 auto isolate = info->GetIsolate();
1171 info->set_class_name(*Utils::OpenHandle(*name));
1175 void FunctionTemplate::SetAcceptAnyReceiver(bool value) {
1176 auto info = Utils::OpenHandle(this);
1177 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
1178 auto isolate = info->GetIsolate();
1180 info->set_accept_any_receiver(value);
1184 void FunctionTemplate::SetHiddenPrototype(bool value) {
1185 auto info = Utils::OpenHandle(this);
1186 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype");
1187 auto isolate = info->GetIsolate();
1189 info->set_hidden_prototype(value);
1193 void FunctionTemplate::ReadOnlyPrototype() {
1194 auto info = Utils::OpenHandle(this);
1195 EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype");
1196 auto isolate = info->GetIsolate();
1198 info->set_read_only_prototype(true);
1202 void FunctionTemplate::RemovePrototype() {
1203 auto info = Utils::OpenHandle(this);
1204 EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype");
1205 auto isolate = info->GetIsolate();
1207 info->set_remove_prototype(true);
1211 // --- O b j e c t T e m p l a t e ---
1214 Local<ObjectTemplate> ObjectTemplate::New(
1215 Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1216 return New(reinterpret_cast<i::Isolate*>(isolate), constructor);
1220 Local<ObjectTemplate> ObjectTemplate::New() {
1221 return New(i::Isolate::Current(), Local<FunctionTemplate>());
1225 Local<ObjectTemplate> ObjectTemplate::New(
1226 i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) {
1227 // Changes to the environment cannot be captured in the snapshot. Expect no
1228 // object templates when the isolate is created for serialization.
1229 DCHECK(!isolate->serializer_enabled());
1230 LOG_API(isolate, "ObjectTemplate::New");
1232 i::Handle<i::Struct> struct_obj =
1233 isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
1234 i::Handle<i::ObjectTemplateInfo> obj =
1235 i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
1236 InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
1237 if (!constructor.IsEmpty())
1238 obj->set_constructor(*Utils::OpenHandle(*constructor));
1239 obj->set_internal_field_count(i::Smi::FromInt(0));
1240 return Utils::ToLocal(obj);
1244 // Ensure that the object template has a constructor. If no
1245 // constructor is available we create one.
1246 static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
1247 i::Isolate* isolate,
1248 ObjectTemplate* object_template) {
1249 i::Object* obj = Utils::OpenHandle(object_template)->constructor();
1250 if (!obj ->IsUndefined()) {
1251 i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj);
1252 return i::Handle<i::FunctionTemplateInfo>(info, isolate);
1254 Local<FunctionTemplate> templ =
1255 FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
1256 i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
1257 constructor->set_instance_template(*Utils::OpenHandle(object_template));
1258 Utils::OpenHandle(object_template)->set_constructor(*constructor);
1263 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1264 i::Isolate* isolate,
1265 Template* template_obj) {
1266 return Utils::OpenHandle(template_obj);
1270 // TODO(dcarney): remove this with ObjectTemplate::SetAccessor
1271 static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
1272 i::Isolate* isolate,
1273 ObjectTemplate* object_template) {
1274 EnsureConstructor(isolate, object_template);
1275 return Utils::OpenHandle(object_template);
1279 template<typename Getter, typename Setter, typename Data, typename Template>
1280 static bool TemplateSetAccessor(
1281 Template* template_obj,
1282 v8::Local<Name> name,
1286 AccessControl settings,
1287 PropertyAttribute attribute,
1288 v8::Local<AccessorSignature> signature) {
1289 auto isolate = Utils::OpenHandle(template_obj)->GetIsolate();
1291 i::HandleScope scope(isolate);
1292 auto obj = MakeAccessorInfo(name, getter, setter, data, settings, attribute,
1294 if (obj.is_null()) return false;
1295 auto info = GetTemplateInfo(isolate, template_obj);
1296 i::ApiNatives::AddNativeDataProperty(isolate, info, obj);
1301 void Template::SetNativeDataProperty(v8::Local<String> name,
1302 AccessorGetterCallback getter,
1303 AccessorSetterCallback setter,
1304 v8::Local<Value> data,
1305 PropertyAttribute attribute,
1306 v8::Local<AccessorSignature> signature,
1307 AccessControl settings) {
1308 TemplateSetAccessor(
1309 this, name, getter, setter, data, settings, attribute, signature);
1313 void Template::SetNativeDataProperty(v8::Local<Name> name,
1314 AccessorNameGetterCallback getter,
1315 AccessorNameSetterCallback setter,
1316 v8::Local<Value> data,
1317 PropertyAttribute attribute,
1318 v8::Local<AccessorSignature> signature,
1319 AccessControl settings) {
1320 TemplateSetAccessor(
1321 this, name, getter, setter, data, settings, attribute, signature);
1325 void ObjectTemplate::SetAccessor(v8::Local<String> name,
1326 AccessorGetterCallback getter,
1327 AccessorSetterCallback setter,
1328 v8::Local<Value> data, AccessControl settings,
1329 PropertyAttribute attribute,
1330 v8::Local<AccessorSignature> signature) {
1331 TemplateSetAccessor(
1332 this, name, getter, setter, data, settings, attribute, signature);
1336 void ObjectTemplate::SetAccessor(v8::Local<Name> name,
1337 AccessorNameGetterCallback getter,
1338 AccessorNameSetterCallback setter,
1339 v8::Local<Value> data, AccessControl settings,
1340 PropertyAttribute attribute,
1341 v8::Local<AccessorSignature> signature) {
1342 TemplateSetAccessor(
1343 this, name, getter, setter, data, settings, attribute, signature);
1347 template <typename Getter, typename Setter, typename Query, typename Deleter,
1348 typename Enumerator>
1349 static void ObjectTemplateSetNamedPropertyHandler(ObjectTemplate* templ,
1350 Getter getter, Setter setter,
1351 Query query, Deleter remover,
1352 Enumerator enumerator,
1354 PropertyHandlerFlags flags) {
1355 i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate();
1357 i::HandleScope scope(isolate);
1358 auto cons = EnsureConstructor(isolate, templ);
1359 EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler");
1360 auto obj = i::Handle<i::InterceptorInfo>::cast(
1361 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1363 if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1364 if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1365 if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1366 if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1367 if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1369 obj->set_can_intercept_symbols(
1370 !(static_cast<int>(flags) &
1371 static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings)));
1372 obj->set_all_can_read(static_cast<int>(flags) &
1373 static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1374 obj->set_non_masking(static_cast<int>(flags) &
1375 static_cast<int>(PropertyHandlerFlags::kNonMasking));
1377 if (data.IsEmpty()) {
1378 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1380 obj->set_data(*Utils::OpenHandle(*data));
1381 cons->set_named_property_handler(*obj);
1385 void ObjectTemplate::SetNamedPropertyHandler(
1386 NamedPropertyGetterCallback getter, NamedPropertySetterCallback setter,
1387 NamedPropertyQueryCallback query, NamedPropertyDeleterCallback remover,
1388 NamedPropertyEnumeratorCallback enumerator, Local<Value> data) {
1389 ObjectTemplateSetNamedPropertyHandler(
1390 this, getter, setter, query, remover, enumerator, data,
1391 PropertyHandlerFlags::kOnlyInterceptStrings);
1395 void ObjectTemplate::SetHandler(
1396 const NamedPropertyHandlerConfiguration& config) {
1397 ObjectTemplateSetNamedPropertyHandler(
1398 this, config.getter, config.setter, config.query, config.deleter,
1399 config.enumerator, config.data, config.flags);
1403 void ObjectTemplate::MarkAsUndetectable() {
1404 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1406 i::HandleScope scope(isolate);
1407 auto cons = EnsureConstructor(isolate, this);
1408 EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable");
1409 cons->set_undetectable(true);
1413 void ObjectTemplate::SetAccessCheckCallbacks(
1414 NamedSecurityCallback named_callback,
1415 IndexedSecurityCallback indexed_callback, Local<Value> data) {
1416 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1418 i::HandleScope scope(isolate);
1419 auto cons = EnsureConstructor(isolate, this);
1420 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallbacks");
1422 i::Handle<i::Struct> struct_info =
1423 isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE);
1424 i::Handle<i::AccessCheckInfo> info =
1425 i::Handle<i::AccessCheckInfo>::cast(struct_info);
1427 SET_FIELD_WRAPPED(info, set_named_callback, named_callback);
1428 SET_FIELD_WRAPPED(info, set_indexed_callback, indexed_callback);
1430 if (data.IsEmpty()) {
1431 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1433 info->set_data(*Utils::OpenHandle(*data));
1435 cons->set_access_check_info(*info);
1436 cons->set_needs_access_check(true);
1440 void ObjectTemplate::SetHandler(
1441 const IndexedPropertyHandlerConfiguration& config) {
1442 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1444 i::HandleScope scope(isolate);
1445 auto cons = EnsureConstructor(isolate, this);
1446 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler");
1447 auto obj = i::Handle<i::InterceptorInfo>::cast(
1448 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE));
1450 if (config.getter != 0) SET_FIELD_WRAPPED(obj, set_getter, config.getter);
1451 if (config.setter != 0) SET_FIELD_WRAPPED(obj, set_setter, config.setter);
1452 if (config.query != 0) SET_FIELD_WRAPPED(obj, set_query, config.query);
1453 if (config.deleter != 0) SET_FIELD_WRAPPED(obj, set_deleter, config.deleter);
1454 if (config.enumerator != 0) {
1455 SET_FIELD_WRAPPED(obj, set_enumerator, config.enumerator);
1458 obj->set_all_can_read(static_cast<int>(config.flags) &
1459 static_cast<int>(PropertyHandlerFlags::kAllCanRead));
1461 v8::Local<v8::Value> data = config.data;
1462 if (data.IsEmpty()) {
1463 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1465 obj->set_data(*Utils::OpenHandle(*data));
1466 cons->set_indexed_property_handler(*obj);
1470 void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
1471 Local<Value> data) {
1472 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1474 i::HandleScope scope(isolate);
1475 auto cons = EnsureConstructor(isolate, this);
1476 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
1477 i::Handle<i::Struct> struct_obj =
1478 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1479 i::Handle<i::CallHandlerInfo> obj =
1480 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1481 SET_FIELD_WRAPPED(obj, set_callback, callback);
1482 if (data.IsEmpty()) {
1483 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
1485 obj->set_data(*Utils::OpenHandle(*data));
1486 cons->set_instance_call_handler(*obj);
1490 int ObjectTemplate::InternalFieldCount() {
1491 return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
1495 void ObjectTemplate::SetInternalFieldCount(int value) {
1496 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1497 if (!Utils::ApiCheck(i::Smi::IsValid(value),
1498 "v8::ObjectTemplate::SetInternalFieldCount()",
1499 "Invalid internal field count")) {
1504 // The internal field count is set by the constructor function's
1505 // construct code, so we ensure that there is a constructor
1506 // function to do the setting.
1507 EnsureConstructor(isolate, this);
1509 Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
1513 // --- S c r i p t s ---
1516 // Internally, UnboundScript is a SharedFunctionInfo, and Script is a
1519 ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
1520 BufferPolicy buffer_policy_)
1524 buffer_policy(buffer_policy_) {}
1527 ScriptCompiler::CachedData::~CachedData() {
1528 if (buffer_policy == BufferOwned) {
1534 bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; }
1537 void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); }
1540 ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
1542 : impl_(new i::StreamedSource(stream, encoding)) {}
1545 ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; }
1548 const ScriptCompiler::CachedData*
1549 ScriptCompiler::StreamedSource::GetCachedData() const {
1550 return impl_->cached_data.get();
1554 Local<Script> UnboundScript::BindToCurrentContext() {
1555 i::Handle<i::HeapObject> obj =
1556 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1557 i::Handle<i::SharedFunctionInfo>
1558 function_info(i::SharedFunctionInfo::cast(*obj), obj->GetIsolate());
1559 i::Isolate* isolate = obj->GetIsolate();
1561 i::ScopeInfo* scope_info = function_info->scope_info();
1562 i::Handle<i::JSReceiver> global(isolate->native_context()->global_object());
1563 for (int i = 0; i < scope_info->StrongModeFreeVariableCount(); ++i) {
1564 i::Handle<i::String> name_string(scope_info->StrongModeFreeVariableName(i));
1565 i::ScriptContextTable::LookupResult result;
1566 i::Handle<i::ScriptContextTable> script_context_table(
1567 isolate->native_context()->script_context_table());
1568 if (!i::ScriptContextTable::Lookup(script_context_table, name_string,
1570 i::Handle<i::Name> name(scope_info->StrongModeFreeVariableName(i));
1571 Maybe<bool> has = i::JSReceiver::HasProperty(global, name);
1572 if (has.IsJust() && !has.FromJust()) {
1573 i::PendingCompilationErrorHandler pending_error_handler_;
1574 pending_error_handler_.ReportMessageAt(
1575 scope_info->StrongModeFreeVariableStartPosition(i),
1576 scope_info->StrongModeFreeVariableEndPosition(i),
1577 i::MessageTemplate::kStrongUnboundGlobal, name_string,
1578 i::kReferenceError);
1579 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1580 pending_error_handler_.ThrowPendingError(isolate, script);
1581 isolate->ReportPendingMessages();
1582 isolate->OptionalRescheduleException(true);
1583 return Local<Script>();
1587 i::Handle<i::JSFunction> function =
1588 obj->GetIsolate()->factory()->NewFunctionFromSharedFunctionInfo(
1589 function_info, isolate->native_context());
1590 return ToApiHandle<Script>(function);
1594 int UnboundScript::GetId() {
1595 i::Handle<i::HeapObject> obj =
1596 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
1597 i::Isolate* isolate = obj->GetIsolate();
1598 LOG_API(isolate, "v8::UnboundScript::GetId");
1599 i::HandleScope scope(isolate);
1600 i::Handle<i::SharedFunctionInfo> function_info(
1601 i::SharedFunctionInfo::cast(*obj));
1602 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1603 return script->id()->value();
1607 int UnboundScript::GetLineNumber(int code_pos) {
1608 i::Handle<i::SharedFunctionInfo> obj =
1609 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1610 i::Isolate* isolate = obj->GetIsolate();
1611 LOG_API(isolate, "UnboundScript::GetLineNumber");
1612 if (obj->script()->IsScript()) {
1613 i::Handle<i::Script> script(i::Script::cast(obj->script()));
1614 return i::Script::GetLineNumber(script, code_pos);
1621 Local<Value> UnboundScript::GetScriptName() {
1622 i::Handle<i::SharedFunctionInfo> obj =
1623 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1624 i::Isolate* isolate = obj->GetIsolate();
1625 LOG_API(isolate, "UnboundScript::GetName");
1626 if (obj->script()->IsScript()) {
1627 i::Object* name = i::Script::cast(obj->script())->name();
1628 return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
1630 return Local<String>();
1635 Local<Value> UnboundScript::GetSourceURL() {
1636 i::Handle<i::SharedFunctionInfo> obj =
1637 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1638 i::Isolate* isolate = obj->GetIsolate();
1639 LOG_API(isolate, "UnboundScript::GetSourceURL");
1640 if (obj->script()->IsScript()) {
1641 i::Object* url = i::Script::cast(obj->script())->source_url();
1642 return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1644 return Local<String>();
1649 Local<Value> UnboundScript::GetSourceMappingURL() {
1650 i::Handle<i::SharedFunctionInfo> obj =
1651 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
1652 i::Isolate* isolate = obj->GetIsolate();
1653 LOG_API(isolate, "UnboundScript::GetSourceMappingURL");
1654 if (obj->script()->IsScript()) {
1655 i::Object* url = i::Script::cast(obj->script())->source_mapping_url();
1656 return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
1658 return Local<String>();
1663 MaybeLocal<Value> Script::Run(Local<Context> context) {
1664 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Script::Run()", Value)
1665 i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy());
1666 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
1667 auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this));
1668 i::Handle<i::Object> receiver(isolate->global_proxy(), isolate);
1669 Local<Value> result;
1670 has_pending_exception =
1671 !ToLocal<Value>(i::Execution::Call(isolate, fun, receiver, 0, NULL),
1673 RETURN_ON_FAILED_EXECUTION(Value);
1674 RETURN_ESCAPED(result);
1678 Local<Value> Script::Run() {
1679 auto self = Utils::OpenHandle(this, true);
1680 // If execution is terminating, Compile(..)->Run() requires this
1682 if (self.is_null()) return Local<Value>();
1683 auto context = ContextFromHeapObject(self);
1684 RETURN_TO_LOCAL_UNCHECKED(Run(context), Value);
1688 Local<UnboundScript> Script::GetUnboundScript() {
1689 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1690 return ToApiHandle<UnboundScript>(
1691 i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared()));
1695 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal(
1696 Isolate* v8_isolate, Source* source, CompileOptions options,
1698 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1699 PREPARE_FOR_EXECUTION_WITH_ISOLATE(
1700 isolate, "v8::ScriptCompiler::CompileUnbound()", UnboundScript);
1702 // Don't try to produce any kind of cache when the debugger is loaded.
1703 if (isolate->debug()->is_loaded() &&
1704 (options == kProduceParserCache || options == kProduceCodeCache)) {
1705 options = kNoCompileOptions;
1708 i::ScriptData* script_data = NULL;
1709 if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1710 DCHECK(source->cached_data);
1711 // ScriptData takes care of pointer-aligning the data.
1712 script_data = new i::ScriptData(source->cached_data->data,
1713 source->cached_data->length);
1716 i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
1717 i::Handle<i::SharedFunctionInfo> result;
1719 i::HistogramTimerScope total(isolate->counters()->compile_script(), true);
1720 i::Handle<i::Object> name_obj;
1721 i::Handle<i::Object> source_map_url;
1722 int line_offset = 0;
1723 int column_offset = 0;
1724 if (!source->resource_name.IsEmpty()) {
1725 name_obj = Utils::OpenHandle(*(source->resource_name));
1727 if (!source->resource_line_offset.IsEmpty()) {
1728 line_offset = static_cast<int>(source->resource_line_offset->Value());
1730 if (!source->resource_column_offset.IsEmpty()) {
1732 static_cast<int>(source->resource_column_offset->Value());
1734 if (!source->source_map_url.IsEmpty()) {
1735 source_map_url = Utils::OpenHandle(*(source->source_map_url));
1737 result = i::Compiler::CompileScript(
1738 str, name_obj, line_offset, column_offset, source->resource_options,
1739 source_map_url, isolate->native_context(), NULL, &script_data, options,
1740 i::NOT_NATIVES_CODE, is_module);
1741 has_pending_exception = result.is_null();
1742 if (has_pending_exception && script_data != NULL) {
1743 // This case won't happen during normal operation; we have compiled
1744 // successfully and produced cached data, and but the second compilation
1745 // of the same source code fails.
1749 RETURN_ON_FAILED_EXECUTION(UnboundScript);
1751 if ((options == kProduceParserCache || options == kProduceCodeCache) &&
1752 script_data != NULL) {
1753 // script_data now contains the data that was generated. source will
1754 // take the ownership.
1755 source->cached_data = new CachedData(
1756 script_data->data(), script_data->length(), CachedData::BufferOwned);
1757 script_data->ReleaseDataOwnership();
1758 } else if (options == kConsumeParserCache || options == kConsumeCodeCache) {
1759 source->cached_data->rejected = script_data->rejected();
1763 RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
1767 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript(
1768 Isolate* v8_isolate, Source* source, CompileOptions options) {
1769 return CompileUnboundInternal(v8_isolate, source, options, false);
1773 Local<UnboundScript> ScriptCompiler::CompileUnbound(Isolate* v8_isolate,
1775 CompileOptions options) {
1776 RETURN_TO_LOCAL_UNCHECKED(
1777 CompileUnboundInternal(v8_isolate, source, options, false),
1782 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1784 CompileOptions options) {
1785 auto isolate = context->GetIsolate();
1786 auto maybe = CompileUnboundInternal(isolate, source, options, false);
1787 Local<UnboundScript> result;
1788 if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
1789 v8::Context::Scope scope(context);
1790 return result->BindToCurrentContext();
1794 Local<Script> ScriptCompiler::Compile(
1795 Isolate* v8_isolate,
1797 CompileOptions options) {
1798 auto context = v8_isolate->GetCurrentContext();
1799 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, options), Script);
1803 MaybeLocal<Script> ScriptCompiler::CompileModule(Local<Context> context,
1805 CompileOptions options) {
1806 CHECK(i::FLAG_harmony_modules);
1807 auto isolate = context->GetIsolate();
1808 auto maybe = CompileUnboundInternal(isolate, source, options, true);
1809 Local<UnboundScript> generic;
1810 if (!maybe.ToLocal(&generic)) return MaybeLocal<Script>();
1811 v8::Context::Scope scope(context);
1812 return generic->BindToCurrentContext();
1816 Local<Script> ScriptCompiler::CompileModule(Isolate* v8_isolate, Source* source,
1817 CompileOptions options) {
1818 auto context = v8_isolate->GetCurrentContext();
1819 RETURN_TO_LOCAL_UNCHECKED(CompileModule(context, source, options), Script);
1823 class IsIdentifierHelper {
1825 IsIdentifierHelper() : is_identifier_(false), first_char_(true) {}
1827 bool Check(i::String* string) {
1828 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
1829 if (cons_string == NULL) return is_identifier_;
1830 // We don't support cons strings here.
1833 void VisitOneByteString(const uint8_t* chars, int length) {
1834 for (int i = 0; i < length; ++i) {
1836 first_char_ = false;
1837 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1839 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1843 void VisitTwoByteString(const uint16_t* chars, int length) {
1844 for (int i = 0; i < length; ++i) {
1846 first_char_ = false;
1847 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]);
1849 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]);
1855 bool is_identifier_;
1857 i::UnicodeCache unicode_cache_;
1858 DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper);
1862 MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext(
1863 Local<Context> v8_context, Source* source, size_t arguments_count,
1864 Local<String> arguments[], size_t context_extension_count,
1865 Local<Object> context_extensions[]) {
1866 PREPARE_FOR_EXECUTION(
1867 v8_context, "v8::ScriptCompiler::CompileFunctionInContext()", Function);
1868 i::Handle<i::String> source_string;
1869 auto factory = isolate->factory();
1870 if (arguments_count) {
1871 source_string = factory->NewStringFromStaticChars("(function(");
1872 for (size_t i = 0; i < arguments_count; ++i) {
1873 IsIdentifierHelper helper;
1874 if (!helper.Check(*Utils::OpenHandle(*arguments[i]))) {
1875 return Local<Function>();
1877 has_pending_exception =
1878 !factory->NewConsString(source_string,
1879 Utils::OpenHandle(*arguments[i]))
1880 .ToHandle(&source_string);
1881 RETURN_ON_FAILED_EXECUTION(Function);
1882 if (i + 1 == arguments_count) continue;
1883 has_pending_exception =
1884 !factory->NewConsString(source_string,
1885 factory->LookupSingleCharacterStringFromCode(
1886 ',')).ToHandle(&source_string);
1887 RETURN_ON_FAILED_EXECUTION(Function);
1889 auto brackets = factory->NewStringFromStaticChars("){");
1890 has_pending_exception = !factory->NewConsString(source_string, brackets)
1891 .ToHandle(&source_string);
1892 RETURN_ON_FAILED_EXECUTION(Function);
1894 source_string = factory->NewStringFromStaticChars("(function(){");
1897 int scope_position = source_string->length();
1898 has_pending_exception =
1899 !factory->NewConsString(source_string,
1900 Utils::OpenHandle(*source->source_string))
1901 .ToHandle(&source_string);
1902 RETURN_ON_FAILED_EXECUTION(Function);
1903 // Include \n in case the source contains a line end comment.
1904 auto brackets = factory->NewStringFromStaticChars("\n})");
1905 has_pending_exception =
1906 !factory->NewConsString(source_string, brackets).ToHandle(&source_string);
1907 RETURN_ON_FAILED_EXECUTION(Function);
1909 i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
1910 i::Handle<i::SharedFunctionInfo> outer_info(context->closure()->shared(),
1912 for (size_t i = 0; i < context_extension_count; ++i) {
1913 i::Handle<i::JSObject> extension =
1914 Utils::OpenHandle(*context_extensions[i]);
1915 i::Handle<i::JSFunction> closure(context->closure(), isolate);
1916 context = factory->NewWithContext(closure, context, extension);
1919 i::Handle<i::JSFunction> fun;
1920 has_pending_exception =
1921 !i::Compiler::GetFunctionFromEval(
1922 source_string, outer_info, context, i::SLOPPY,
1923 i::ONLY_SINGLE_FUNCTION_LITERAL, scope_position).ToHandle(&fun);
1924 RETURN_ON_FAILED_EXECUTION(Function);
1926 i::Handle<i::Object> result;
1927 has_pending_exception =
1928 !i::Execution::Call(isolate, fun,
1929 Utils::OpenHandle(*v8_context->Global()), 0,
1930 nullptr).ToHandle(&result);
1931 RETURN_ON_FAILED_EXECUTION(Function);
1932 RETURN_ESCAPED(Utils::ToLocal(i::Handle<i::JSFunction>::cast(result)));
1936 Local<Function> ScriptCompiler::CompileFunctionInContext(
1937 Isolate* v8_isolate, Source* source, Local<Context> v8_context,
1938 size_t arguments_count, Local<String> arguments[],
1939 size_t context_extension_count, Local<Object> context_extensions[]) {
1940 RETURN_TO_LOCAL_UNCHECKED(
1941 CompileFunctionInContext(v8_context, source, arguments_count, arguments,
1942 context_extension_count, context_extensions),
1947 ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript(
1948 Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
1949 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1950 return new i::BackgroundParsingTask(source->impl(), options,
1951 i::FLAG_stack_size, isolate);
1955 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context,
1956 StreamedSource* v8_source,
1957 Local<String> full_source_string,
1958 const ScriptOrigin& origin) {
1959 PREPARE_FOR_EXECUTION(context, "v8::ScriptCompiler::Compile()", Script);
1960 i::StreamedSource* source = v8_source->impl();
1961 i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
1962 i::Handle<i::Script> script = isolate->factory()->NewScript(str);
1963 if (!origin.ResourceName().IsEmpty()) {
1964 script->set_name(*Utils::OpenHandle(*(origin.ResourceName())));
1966 if (!origin.ResourceLineOffset().IsEmpty()) {
1967 script->set_line_offset(i::Smi::FromInt(
1968 static_cast<int>(origin.ResourceLineOffset()->Value())));
1970 if (!origin.ResourceColumnOffset().IsEmpty()) {
1971 script->set_column_offset(i::Smi::FromInt(
1972 static_cast<int>(origin.ResourceColumnOffset()->Value())));
1974 script->set_origin_options(origin.Options());
1975 if (!origin.SourceMapUrl().IsEmpty()) {
1976 script->set_source_mapping_url(
1977 *Utils::OpenHandle(*(origin.SourceMapUrl())));
1980 source->info->set_script(script);
1981 source->info->set_context(isolate->native_context());
1983 // Do the parsing tasks which need to be done on the main thread. This will
1984 // also handle parse errors.
1985 source->parser->Internalize(isolate, script,
1986 source->info->function() == nullptr);
1987 source->parser->HandleSourceURLComments(isolate, script);
1989 i::Handle<i::SharedFunctionInfo> result;
1990 if (source->info->function() != nullptr) {
1991 // Parsing has succeeded.
1992 result = i::Compiler::CompileStreamedScript(script, source->info.get(),
1995 has_pending_exception = result.is_null();
1996 if (has_pending_exception) isolate->ReportPendingMessages();
1997 RETURN_ON_FAILED_EXECUTION(Script);
1999 source->info->clear_script(); // because script goes out of scope.
2001 Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
2002 if (generic.IsEmpty()) return Local<Script>();
2003 Local<Script> bound = generic->BindToCurrentContext();
2004 if (bound.IsEmpty()) return Local<Script>();
2005 RETURN_ESCAPED(bound);
2009 Local<Script> ScriptCompiler::Compile(Isolate* v8_isolate,
2010 StreamedSource* v8_source,
2011 Local<String> full_source_string,
2012 const ScriptOrigin& origin) {
2013 auto context = v8_isolate->GetCurrentContext();
2014 RETURN_TO_LOCAL_UNCHECKED(
2015 Compile(context, v8_source, full_source_string, origin), Script);
2019 uint32_t ScriptCompiler::CachedDataVersionTag() {
2020 return static_cast<uint32_t>(base::hash_combine(
2021 internal::Version::Hash(), internal::FlagList::Hash(),
2022 static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures())));
2026 MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source,
2027 ScriptOrigin* origin) {
2029 ScriptCompiler::Source script_source(source, *origin);
2030 return ScriptCompiler::Compile(context, &script_source);
2032 ScriptCompiler::Source script_source(source);
2033 return ScriptCompiler::Compile(context, &script_source);
2037 Local<Script> Script::Compile(v8::Local<String> source,
2038 v8::ScriptOrigin* origin) {
2039 auto str = Utils::OpenHandle(*source);
2040 auto context = ContextFromHeapObject(str);
2041 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, origin), Script);
2045 Local<Script> Script::Compile(v8::Local<String> source,
2046 v8::Local<String> file_name) {
2047 auto str = Utils::OpenHandle(*source);
2048 auto context = ContextFromHeapObject(str);
2049 ScriptOrigin origin(file_name);
2050 return Compile(context, source, &origin).FromMaybe(Local<Script>());
2054 // --- E x c e p t i o n s ---
2057 v8::TryCatch::TryCatch()
2058 : isolate_(i::Isolate::Current()),
2059 next_(isolate_->try_catch_handler()),
2061 can_continue_(true),
2062 capture_message_(true),
2064 has_terminated_(false) {
2066 // Special handling for simulators which have a separate JS stack.
2067 js_stack_comparable_address_ =
2068 reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2069 v8::internal::GetCurrentStackPosition()));
2070 isolate_->RegisterTryCatchHandler(this);
2074 v8::TryCatch::TryCatch(v8::Isolate* isolate)
2075 : isolate_(reinterpret_cast<i::Isolate*>(isolate)),
2076 next_(isolate_->try_catch_handler()),
2078 can_continue_(true),
2079 capture_message_(true),
2081 has_terminated_(false) {
2083 // Special handling for simulators which have a separate JS stack.
2084 js_stack_comparable_address_ =
2085 reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
2086 v8::internal::GetCurrentStackPosition()));
2087 isolate_->RegisterTryCatchHandler(this);
2091 v8::TryCatch::~TryCatch() {
2093 v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
2094 v8::HandleScope scope(isolate);
2095 v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
2096 if (HasCaught() && capture_message_) {
2097 // If an exception was caught and rethrow_ is indicated, the saved
2098 // message, script, and location need to be restored to Isolate TLS
2099 // for reuse. capture_message_ needs to be disabled so that Throw()
2100 // does not create a new message.
2101 isolate_->thread_local_top()->rethrowing_message_ = true;
2102 isolate_->RestorePendingMessageFromTryCatch(this);
2104 isolate_->UnregisterTryCatchHandler(this);
2105 v8::internal::SimulatorStack::UnregisterCTryCatch();
2106 reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
2107 DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
2109 if (HasCaught() && isolate_->has_scheduled_exception()) {
2110 // If an exception was caught but is still scheduled because no API call
2111 // promoted it, then it is canceled to prevent it from being propagated.
2112 // Note that this will not cancel termination exceptions.
2113 isolate_->CancelScheduledExceptionFromTryCatch(this);
2115 isolate_->UnregisterTryCatchHandler(this);
2116 v8::internal::SimulatorStack::UnregisterCTryCatch();
2121 bool v8::TryCatch::HasCaught() const {
2122 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
2126 bool v8::TryCatch::CanContinue() const {
2127 return can_continue_;
2131 bool v8::TryCatch::HasTerminated() const {
2132 return has_terminated_;
2136 v8::Local<v8::Value> v8::TryCatch::ReThrow() {
2137 if (!HasCaught()) return v8::Local<v8::Value>();
2139 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
2143 v8::Local<Value> v8::TryCatch::Exception() const {
2145 // Check for out of memory exception.
2146 i::Object* exception = reinterpret_cast<i::Object*>(exception_);
2147 return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
2149 return v8::Local<Value>();
2154 MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const {
2155 if (!HasCaught()) return v8::Local<Value>();
2156 i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
2157 if (!raw_obj->IsJSObject()) return v8::Local<Value>();
2158 PREPARE_FOR_EXECUTION(context, "v8::TryCatch::StackTrace", Value);
2159 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
2160 i::Handle<i::String> name = isolate->factory()->stack_string();
2161 Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
2162 has_pending_exception = !maybe.IsJust();
2163 RETURN_ON_FAILED_EXECUTION(Value);
2164 if (!maybe.FromJust()) return v8::Local<Value>();
2165 Local<Value> result;
2166 has_pending_exception =
2167 !ToLocal<Value>(i::Object::GetProperty(obj, name), &result);
2168 RETURN_ON_FAILED_EXECUTION(Value);
2169 RETURN_ESCAPED(result);
2173 v8::Local<Value> v8::TryCatch::StackTrace() const {
2174 auto context = reinterpret_cast<v8::Isolate*>(isolate_)->GetCurrentContext();
2175 RETURN_TO_LOCAL_UNCHECKED(StackTrace(context), Value);
2179 v8::Local<v8::Message> v8::TryCatch::Message() const {
2180 i::Object* message = reinterpret_cast<i::Object*>(message_obj_);
2181 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
2182 if (HasCaught() && !message->IsTheHole()) {
2183 return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
2185 return v8::Local<v8::Message>();
2190 void v8::TryCatch::Reset() {
2191 if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
2192 // If an exception was caught but is still scheduled because no API call
2193 // promoted it, then it is canceled to prevent it from being propagated.
2194 // Note that this will not cancel termination exceptions.
2195 isolate_->CancelScheduledExceptionFromTryCatch(this);
2201 void v8::TryCatch::ResetInternal() {
2202 i::Object* the_hole = isolate_->heap()->the_hole_value();
2203 exception_ = the_hole;
2204 message_obj_ = the_hole;
2208 void v8::TryCatch::SetVerbose(bool value) {
2209 is_verbose_ = value;
2213 void v8::TryCatch::SetCaptureMessage(bool value) {
2214 capture_message_ = value;
2218 // --- M e s s a g e ---
2221 Local<String> Message::Get() const {
2222 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2224 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2225 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2226 i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
2227 Local<String> result = Utils::ToLocal(raw_result);
2228 return scope.Escape(result);
2232 ScriptOrigin Message::GetScriptOrigin() const {
2233 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2234 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2235 auto script_wraper = i::Handle<i::Object>(message->script(), isolate);
2236 auto script_value = i::Handle<i::JSValue>::cast(script_wraper);
2237 i::Handle<i::Script> script(i::Script::cast(script_value->value()));
2238 return GetScriptOriginForScript(isolate, script);
2242 v8::Local<Value> Message::GetScriptResourceName() const {
2243 return GetScriptOrigin().ResourceName();
2247 v8::Local<v8::StackTrace> Message::GetStackTrace() const {
2248 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2250 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2251 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
2252 i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
2253 if (!stackFramesObj->IsJSArray()) return v8::Local<v8::StackTrace>();
2254 auto stackTrace = i::Handle<i::JSArray>::cast(stackFramesObj);
2255 return scope.Escape(Utils::StackTraceToLocal(stackTrace));
2259 MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
2260 i::Isolate* isolate, const char* name, i::Handle<i::Object> recv, int argc,
2261 i::Handle<i::Object> argv[]) {
2262 i::Handle<i::Object> object_fun =
2263 i::Object::GetProperty(
2264 isolate, isolate->js_builtins_object(), name).ToHandleChecked();
2265 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(object_fun);
2266 return i::Execution::Call(isolate, fun, recv, argc, argv);
2270 MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
2271 i::Isolate* isolate, const char* name, i::Handle<i::Object> data) {
2272 i::Handle<i::Object> argv[] = { data };
2273 return CallV8HeapFunction(isolate, name, isolate->js_builtins_object(),
2274 arraysize(argv), argv);
2278 Maybe<int> Message::GetLineNumber(Local<Context> context) const {
2279 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetLineNumber()", int);
2280 i::Handle<i::Object> result;
2281 has_pending_exception =
2282 !CallV8HeapFunction(isolate, "$messageGetLineNumber",
2283 Utils::OpenHandle(this)).ToHandle(&result);
2284 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2285 return Just(static_cast<int>(result->Number()));
2289 int Message::GetLineNumber() const {
2290 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2291 return GetLineNumber(context).FromMaybe(0);
2295 int Message::GetStartPosition() const {
2296 auto self = Utils::OpenHandle(this);
2297 return self->start_position();
2301 int Message::GetEndPosition() const {
2302 auto self = Utils::OpenHandle(this);
2303 return self->end_position();
2307 Maybe<int> Message::GetStartColumn(Local<Context> context) const {
2308 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetStartColumn()",
2310 auto self = Utils::OpenHandle(this);
2311 i::Handle<i::Object> start_col_obj;
2312 has_pending_exception =
2313 !CallV8HeapFunction(isolate, "$messageGetPositionInLine", self)
2314 .ToHandle(&start_col_obj);
2315 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2316 return Just(static_cast<int>(start_col_obj->Number()));
2320 int Message::GetStartColumn() const {
2321 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2322 const int default_value = kNoColumnInfo;
2323 return GetStartColumn(context).FromMaybe(default_value);
2327 Maybe<int> Message::GetEndColumn(Local<Context> context) const {
2328 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Message::GetEndColumn()", int);
2329 auto self = Utils::OpenHandle(this);
2330 i::Handle<i::Object> start_col_obj;
2331 has_pending_exception =
2332 !CallV8HeapFunction(isolate, "$messageGetPositionInLine", self)
2333 .ToHandle(&start_col_obj);
2334 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int);
2335 int start = self->start_position();
2336 int end = self->end_position();
2337 return Just(static_cast<int>(start_col_obj->Number()) + (end - start));
2341 int Message::GetEndColumn() const {
2342 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2343 const int default_value = kNoColumnInfo;
2344 return GetEndColumn(context).FromMaybe(default_value);
2348 bool Message::IsSharedCrossOrigin() const {
2349 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2351 auto self = Utils::OpenHandle(this);
2352 auto script = i::Handle<i::JSValue>::cast(
2353 i::Handle<i::Object>(self->script(), isolate));
2354 return i::Script::cast(script->value())
2356 .IsSharedCrossOrigin();
2359 bool Message::IsOpaque() const {
2360 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2362 auto self = Utils::OpenHandle(this);
2363 auto script = i::Handle<i::JSValue>::cast(
2364 i::Handle<i::Object>(self->script(), isolate));
2365 return i::Script::cast(script->value())->origin_options().IsOpaque();
2369 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const {
2370 PREPARE_FOR_EXECUTION(context, "v8::Message::GetSourceLine()", String);
2371 i::Handle<i::Object> result;
2372 has_pending_exception =
2373 !CallV8HeapFunction(isolate, "$messageGetSourceLine",
2374 Utils::OpenHandle(this)).ToHandle(&result);
2375 RETURN_ON_FAILED_EXECUTION(String);
2377 if (result->IsString()) {
2378 str = Utils::ToLocal(i::Handle<i::String>::cast(result));
2380 RETURN_ESCAPED(str);
2384 Local<String> Message::GetSourceLine() const {
2385 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
2386 RETURN_TO_LOCAL_UNCHECKED(GetSourceLine(context), String)
2390 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
2391 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2392 ENTER_V8(i_isolate);
2393 i_isolate->PrintCurrentStackTrace(out);
2397 // --- S t a c k T r a c e ---
2399 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
2400 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2402 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2403 auto self = Utils::OpenHandle(this);
2404 auto obj = i::Object::GetElement(isolate, self, index).ToHandleChecked();
2405 auto jsobj = i::Handle<i::JSObject>::cast(obj);
2406 return scope.Escape(Utils::StackFrameToLocal(jsobj));
2410 int StackTrace::GetFrameCount() const {
2411 return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
2415 Local<Array> StackTrace::AsArray() {
2416 return Utils::ToLocal(Utils::OpenHandle(this));
2420 Local<StackTrace> StackTrace::CurrentStackTrace(
2423 StackTraceOptions options) {
2424 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2425 ENTER_V8(i_isolate);
2426 // TODO(dcarney): remove when ScriptDebugServer is fixed.
2427 options = static_cast<StackTraceOptions>(
2428 static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins);
2429 i::Handle<i::JSArray> stackTrace =
2430 i_isolate->CaptureCurrentStackTrace(frame_limit, options);
2431 return Utils::StackTraceToLocal(stackTrace);
2435 // --- S t a c k F r a m e ---
2437 static int getIntProperty(const StackFrame* f, const char* propertyName,
2439 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2441 i::HandleScope scope(isolate);
2442 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2443 i::Handle<i::Object> obj =
2444 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2445 return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue;
2449 int StackFrame::GetLineNumber() const {
2450 return getIntProperty(this, "lineNumber", Message::kNoLineNumberInfo);
2454 int StackFrame::GetColumn() const {
2455 return getIntProperty(this, "column", Message::kNoColumnInfo);
2459 int StackFrame::GetScriptId() const {
2460 return getIntProperty(this, "scriptId", Message::kNoScriptIdInfo);
2464 static Local<String> getStringProperty(const StackFrame* f,
2465 const char* propertyName) {
2466 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2468 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
2469 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2470 i::Handle<i::Object> obj =
2471 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2472 return obj->IsString()
2473 ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
2478 Local<String> StackFrame::GetScriptName() const {
2479 return getStringProperty(this, "scriptName");
2483 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2484 return getStringProperty(this, "scriptNameOrSourceURL");
2488 Local<String> StackFrame::GetFunctionName() const {
2489 return getStringProperty(this, "functionName");
2493 static bool getBoolProperty(const StackFrame* f, const char* propertyName) {
2494 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
2496 i::HandleScope scope(isolate);
2497 i::Handle<i::JSObject> self = Utils::OpenHandle(f);
2498 i::Handle<i::Object> obj =
2499 i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
2500 return obj->IsTrue();
2503 bool StackFrame::IsEval() const { return getBoolProperty(this, "isEval"); }
2506 bool StackFrame::IsConstructor() const {
2507 return getBoolProperty(this, "isConstructor");
2511 // --- N a t i v e W e a k M a p ---
2513 Local<NativeWeakMap> NativeWeakMap::New(Isolate* v8_isolate) {
2514 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2516 i::Handle<i::JSWeakMap> weakmap = isolate->factory()->NewJSWeakMap();
2517 i::Runtime::WeakCollectionInitialize(isolate, weakmap);
2518 return Utils::NativeWeakMapToLocal(weakmap);
2522 void NativeWeakMap::Set(Local<Value> v8_key, Local<Value> v8_value) {
2523 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2524 i::Isolate* isolate = weak_collection->GetIsolate();
2526 i::HandleScope scope(isolate);
2527 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2528 i::Handle<i::Object> value = Utils::OpenHandle(*v8_value);
2529 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2533 i::Handle<i::ObjectHashTable> table(
2534 i::ObjectHashTable::cast(weak_collection->table()));
2535 if (!table->IsKey(*key)) {
2539 int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value();
2540 i::Runtime::WeakCollectionSet(weak_collection, key, value, hash);
2544 Local<Value> NativeWeakMap::Get(Local<Value> v8_key) {
2545 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2546 i::Isolate* isolate = weak_collection->GetIsolate();
2548 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2549 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2551 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2553 i::Handle<i::ObjectHashTable> table(
2554 i::ObjectHashTable::cast(weak_collection->table()));
2555 if (!table->IsKey(*key)) {
2557 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2559 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2560 if (lookup->IsTheHole())
2561 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
2562 return Utils::ToLocal(lookup);
2566 bool NativeWeakMap::Has(Local<Value> v8_key) {
2567 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2568 i::Isolate* isolate = weak_collection->GetIsolate();
2570 i::HandleScope scope(isolate);
2571 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2572 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2576 i::Handle<i::ObjectHashTable> table(
2577 i::ObjectHashTable::cast(weak_collection->table()));
2578 if (!table->IsKey(*key)) {
2582 i::Handle<i::Object> lookup(table->Lookup(key), isolate);
2583 return !lookup->IsTheHole();
2587 bool NativeWeakMap::Delete(Local<Value> v8_key) {
2588 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this);
2589 i::Isolate* isolate = weak_collection->GetIsolate();
2591 i::HandleScope scope(isolate);
2592 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key);
2593 if (!key->IsJSReceiver() && !key->IsSymbol()) {
2597 i::Handle<i::ObjectHashTable> table(
2598 i::ObjectHashTable::cast(weak_collection->table()));
2599 if (!table->IsKey(*key)) {
2603 return i::Runtime::WeakCollectionDelete(weak_collection, key);
2609 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) {
2610 auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2611 PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, "JSON::Parse", Value);
2612 i::Handle<i::String> string = Utils::OpenHandle(*json_string);
2613 i::Handle<i::String> source = i::String::Flatten(string);
2614 auto maybe = source->IsSeqOneByteString()
2615 ? i::JsonParser<true>::Parse(source)
2616 : i::JsonParser<false>::Parse(source);
2617 Local<Value> result;
2618 has_pending_exception = !ToLocal<Value>(maybe, &result);
2619 RETURN_ON_FAILED_EXECUTION(Value);
2620 RETURN_ESCAPED(result);
2624 Local<Value> JSON::Parse(Local<String> json_string) {
2625 auto isolate = reinterpret_cast<v8::Isolate*>(
2626 Utils::OpenHandle(*json_string)->GetIsolate());
2627 RETURN_TO_LOCAL_UNCHECKED(Parse(isolate, json_string), Value);
2633 bool Value::FullIsUndefined() const {
2634 bool result = Utils::OpenHandle(this)->IsUndefined();
2635 DCHECK_EQ(result, QuickIsUndefined());
2640 bool Value::FullIsNull() const {
2641 bool result = Utils::OpenHandle(this)->IsNull();
2642 DCHECK_EQ(result, QuickIsNull());
2647 bool Value::IsTrue() const {
2648 return Utils::OpenHandle(this)->IsTrue();
2652 bool Value::IsFalse() const {
2653 return Utils::OpenHandle(this)->IsFalse();
2657 bool Value::IsFunction() const {
2658 return Utils::OpenHandle(this)->IsJSFunction();
2662 bool Value::IsName() const {
2663 return Utils::OpenHandle(this)->IsName();
2667 bool Value::FullIsString() const {
2668 bool result = Utils::OpenHandle(this)->IsString();
2669 DCHECK_EQ(result, QuickIsString());
2674 bool Value::IsSymbol() const {
2675 return Utils::OpenHandle(this)->IsSymbol();
2679 bool Value::IsArray() const {
2680 return Utils::OpenHandle(this)->IsJSArray();
2684 bool Value::IsArrayBuffer() const {
2685 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2686 return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared();
2690 bool Value::IsArrayBufferView() const {
2691 return Utils::OpenHandle(this)->IsJSArrayBufferView();
2695 bool Value::IsTypedArray() const {
2696 return Utils::OpenHandle(this)->IsJSTypedArray();
2700 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype, size) \
2701 bool Value::Is##Type##Array() const { \
2702 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2703 return obj->IsJSTypedArray() && \
2704 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \
2708 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
2710 #undef VALUE_IS_TYPED_ARRAY
2713 bool Value::IsDataView() const {
2714 return Utils::OpenHandle(this)->IsJSDataView();
2718 bool Value::IsSharedArrayBuffer() const {
2719 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2720 return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared();
2724 bool Value::IsObject() const {
2725 return Utils::OpenHandle(this)->IsJSObject();
2729 bool Value::IsNumber() const {
2730 return Utils::OpenHandle(this)->IsNumber();
2734 #define VALUE_IS_SPECIFIC_TYPE(Type, Class) \
2735 bool Value::Is##Type() const { \
2736 i::Handle<i::Object> obj = Utils::OpenHandle(this); \
2737 if (!obj->IsHeapObject()) return false; \
2738 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate(); \
2739 return obj->HasSpecificClassOf(isolate->heap()->Class##_string()); \
2742 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, Arguments)
2743 VALUE_IS_SPECIFIC_TYPE(BooleanObject, Boolean)
2744 VALUE_IS_SPECIFIC_TYPE(NumberObject, Number)
2745 VALUE_IS_SPECIFIC_TYPE(StringObject, String)
2746 VALUE_IS_SPECIFIC_TYPE(SymbolObject, Symbol)
2747 VALUE_IS_SPECIFIC_TYPE(Date, Date)
2748 VALUE_IS_SPECIFIC_TYPE(Map, Map)
2749 VALUE_IS_SPECIFIC_TYPE(Set, Set)
2750 VALUE_IS_SPECIFIC_TYPE(WeakMap, WeakMap)
2751 VALUE_IS_SPECIFIC_TYPE(WeakSet, WeakSet)
2753 #undef VALUE_IS_SPECIFIC_TYPE
2756 bool Value::IsBoolean() const {
2757 return Utils::OpenHandle(this)->IsBoolean();
2761 bool Value::IsExternal() const {
2762 return Utils::OpenHandle(this)->IsExternal();
2766 bool Value::IsInt32() const {
2767 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2768 if (obj->IsSmi()) return true;
2769 if (obj->IsNumber()) {
2770 return i::IsInt32Double(obj->Number());
2776 bool Value::IsUint32() const {
2777 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2778 if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2779 if (obj->IsNumber()) {
2780 double value = obj->Number();
2781 return !i::IsMinusZero(value) &&
2783 value <= i::kMaxUInt32 &&
2784 value == i::FastUI2D(i::FastD2UI(value));
2790 static bool CheckConstructor(i::Isolate* isolate,
2791 i::Handle<i::JSObject> obj,
2792 const char* class_name) {
2793 i::Handle<i::Object> constr(obj->map()->GetConstructor(), isolate);
2794 if (!constr->IsJSFunction()) return false;
2795 i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(constr);
2796 return func->shared()->native() && constr.is_identical_to(
2797 i::Object::GetProperty(isolate,
2798 isolate->js_builtins_object(),
2799 class_name).ToHandleChecked());
2803 bool Value::IsNativeError() const {
2804 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2805 if (obj->IsJSObject()) {
2806 i::Handle<i::JSObject> js_obj(i::JSObject::cast(*obj));
2807 i::Isolate* isolate = js_obj->GetIsolate();
2808 return CheckConstructor(isolate, js_obj, "$Error") ||
2809 CheckConstructor(isolate, js_obj, "$EvalError") ||
2810 CheckConstructor(isolate, js_obj, "$RangeError") ||
2811 CheckConstructor(isolate, js_obj, "$ReferenceError") ||
2812 CheckConstructor(isolate, js_obj, "$SyntaxError") ||
2813 CheckConstructor(isolate, js_obj, "$TypeError") ||
2814 CheckConstructor(isolate, js_obj, "$URIError");
2821 bool Value::IsRegExp() const {
2822 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2823 return obj->IsJSRegExp();
2827 bool Value::IsGeneratorFunction() const {
2828 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2829 if (!obj->IsJSFunction()) return false;
2830 i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
2831 return func->shared()->is_generator();
2835 bool Value::IsGeneratorObject() const {
2836 return Utils::OpenHandle(this)->IsJSGeneratorObject();
2840 bool Value::IsMapIterator() const {
2841 return Utils::OpenHandle(this)->IsJSMapIterator();
2845 bool Value::IsSetIterator() const {
2846 return Utils::OpenHandle(this)->IsJSSetIterator();
2850 MaybeLocal<String> Value::ToString(Local<Context> context) const {
2851 auto obj = Utils::OpenHandle(this);
2852 if (obj->IsString()) return ToApiHandle<String>(obj);
2853 PREPARE_FOR_EXECUTION(context, "ToString", String);
2854 Local<String> result;
2855 has_pending_exception =
2856 !ToLocal<String>(i::Execution::ToString(isolate, obj), &result);
2857 RETURN_ON_FAILED_EXECUTION(String);
2858 RETURN_ESCAPED(result);
2862 Local<String> Value::ToString(Isolate* isolate) const {
2863 RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String);
2867 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const {
2868 auto obj = Utils::OpenHandle(this);
2869 if (obj->IsString()) return ToApiHandle<String>(obj);
2870 PREPARE_FOR_EXECUTION(context, "ToDetailString", String);
2871 Local<String> result;
2872 has_pending_exception =
2873 !ToLocal<String>(i::Execution::ToDetailString(isolate, obj), &result);
2874 RETURN_ON_FAILED_EXECUTION(String);
2875 RETURN_ESCAPED(result);
2879 Local<String> Value::ToDetailString(Isolate* isolate) const {
2880 RETURN_TO_LOCAL_UNCHECKED(ToDetailString(isolate->GetCurrentContext()),
2885 MaybeLocal<Object> Value::ToObject(Local<Context> context) const {
2886 auto obj = Utils::OpenHandle(this);
2887 if (obj->IsJSObject()) return ToApiHandle<Object>(obj);
2888 PREPARE_FOR_EXECUTION(context, "ToObject", Object);
2889 Local<Object> result;
2890 has_pending_exception =
2891 !ToLocal<Object>(i::Execution::ToObject(isolate, obj), &result);
2892 RETURN_ON_FAILED_EXECUTION(Object);
2893 RETURN_ESCAPED(result);
2897 Local<v8::Object> Value::ToObject(Isolate* isolate) const {
2898 RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object);
2902 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const {
2903 auto obj = Utils::OpenHandle(this);
2904 if (obj->IsBoolean()) return ToApiHandle<Boolean>(obj);
2905 auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2906 auto val = isolate->factory()->ToBoolean(obj->BooleanValue());
2907 return ToApiHandle<Boolean>(val);
2911 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const {
2912 return ToBoolean(v8_isolate->GetCurrentContext()).ToLocalChecked();
2916 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const {
2917 auto obj = Utils::OpenHandle(this);
2918 if (obj->IsNumber()) return ToApiHandle<Number>(obj);
2919 PREPARE_FOR_EXECUTION(context, "ToNumber", Number);
2920 Local<Number> result;
2921 has_pending_exception =
2922 !ToLocal<Number>(i::Execution::ToNumber(isolate, obj), &result);
2923 RETURN_ON_FAILED_EXECUTION(Number);
2924 RETURN_ESCAPED(result);
2928 Local<Number> Value::ToNumber(Isolate* isolate) const {
2929 RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number);
2933 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const {
2934 auto obj = Utils::OpenHandle(this);
2935 if (obj->IsSmi()) return ToApiHandle<Integer>(obj);
2936 PREPARE_FOR_EXECUTION(context, "ToInteger", Integer);
2937 Local<Integer> result;
2938 has_pending_exception =
2939 !ToLocal<Integer>(i::Execution::ToInteger(isolate, obj), &result);
2940 RETURN_ON_FAILED_EXECUTION(Integer);
2941 RETURN_ESCAPED(result);
2945 Local<Integer> Value::ToInteger(Isolate* isolate) const {
2946 RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer);
2950 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const {
2951 auto obj = Utils::OpenHandle(this);
2952 if (obj->IsSmi()) return ToApiHandle<Int32>(obj);
2953 Local<Int32> result;
2954 PREPARE_FOR_EXECUTION(context, "ToInt32", Int32);
2955 has_pending_exception =
2956 !ToLocal<Int32>(i::Execution::ToInt32(isolate, obj), &result);
2957 RETURN_ON_FAILED_EXECUTION(Int32);
2958 RETURN_ESCAPED(result);
2962 Local<Int32> Value::ToInt32(Isolate* isolate) const {
2963 RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32);
2967 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const {
2968 auto obj = Utils::OpenHandle(this);
2969 if (obj->IsSmi()) return ToApiHandle<Uint32>(obj);
2970 Local<Uint32> result;
2971 PREPARE_FOR_EXECUTION(context, "ToUInt32", Uint32);
2972 has_pending_exception =
2973 !ToLocal<Uint32>(i::Execution::ToUint32(isolate, obj), &result);
2974 RETURN_ON_FAILED_EXECUTION(Uint32);
2975 RETURN_ESCAPED(result);
2979 Local<Uint32> Value::ToUint32(Isolate* isolate) const {
2980 RETURN_TO_LOCAL_UNCHECKED(ToUint32(isolate->GetCurrentContext()), Uint32);
2984 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
2985 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
2986 Utils::ApiCheck(isolate != NULL &&
2988 "v8::internal::Internals::CheckInitialized()",
2989 "Isolate is not initialized or V8 has died");
2993 void External::CheckCast(v8::Value* that) {
2994 Utils::ApiCheck(Utils::OpenHandle(that)->IsExternal(),
2995 "v8::External::Cast()",
2996 "Could not convert to external");
3000 void v8::Object::CheckCast(Value* that) {
3001 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3002 Utils::ApiCheck(obj->IsJSObject(),
3003 "v8::Object::Cast()",
3004 "Could not convert to object");
3008 void v8::Function::CheckCast(Value* that) {
3009 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3010 Utils::ApiCheck(obj->IsJSFunction(),
3011 "v8::Function::Cast()",
3012 "Could not convert to function");
3016 void v8::Boolean::CheckCast(v8::Value* that) {
3017 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3018 Utils::ApiCheck(obj->IsBoolean(),
3019 "v8::Boolean::Cast()",
3020 "Could not convert to boolean");
3024 void v8::Name::CheckCast(v8::Value* that) {
3025 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3026 Utils::ApiCheck(obj->IsName(),
3028 "Could not convert to name");
3032 void v8::String::CheckCast(v8::Value* that) {
3033 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3034 Utils::ApiCheck(obj->IsString(),
3035 "v8::String::Cast()",
3036 "Could not convert to string");
3040 void v8::Symbol::CheckCast(v8::Value* that) {
3041 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3042 Utils::ApiCheck(obj->IsSymbol(),
3043 "v8::Symbol::Cast()",
3044 "Could not convert to symbol");
3048 void v8::Number::CheckCast(v8::Value* that) {
3049 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3050 Utils::ApiCheck(obj->IsNumber(),
3051 "v8::Number::Cast()",
3052 "Could not convert to number");
3056 void v8::Integer::CheckCast(v8::Value* that) {
3057 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3058 Utils::ApiCheck(obj->IsNumber(),
3059 "v8::Integer::Cast()",
3060 "Could not convert to number");
3064 void v8::Int32::CheckCast(v8::Value* that) {
3065 Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast()",
3066 "Could not convert to 32-bit signed integer");
3070 void v8::Uint32::CheckCast(v8::Value* that) {
3071 Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast()",
3072 "Could not convert to 32-bit unsigned integer");
3076 void v8::Array::CheckCast(Value* that) {
3077 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3078 Utils::ApiCheck(obj->IsJSArray(),
3079 "v8::Array::Cast()",
3080 "Could not convert to array");
3084 void v8::Map::CheckCast(Value* that) {
3085 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3086 Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast()",
3087 "Could not convert to Map");
3091 void v8::Set::CheckCast(Value* that) {
3092 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3093 Utils::ApiCheck(obj->IsJSSet(), "v8::Set::Cast()",
3094 "Could not convert to Set");
3098 void v8::Promise::CheckCast(Value* that) {
3099 Utils::ApiCheck(that->IsPromise(),
3100 "v8::Promise::Cast()",
3101 "Could not convert to promise");
3105 void v8::Promise::Resolver::CheckCast(Value* that) {
3106 Utils::ApiCheck(that->IsPromise(),
3107 "v8::Promise::Resolver::Cast()",
3108 "Could not convert to promise resolver");
3112 void v8::ArrayBuffer::CheckCast(Value* that) {
3113 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3115 obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(),
3116 "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer");
3120 void v8::ArrayBufferView::CheckCast(Value* that) {
3121 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3122 Utils::ApiCheck(obj->IsJSArrayBufferView(),
3123 "v8::ArrayBufferView::Cast()",
3124 "Could not convert to ArrayBufferView");
3128 void v8::TypedArray::CheckCast(Value* that) {
3129 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3130 Utils::ApiCheck(obj->IsJSTypedArray(),
3131 "v8::TypedArray::Cast()",
3132 "Could not convert to TypedArray");
3136 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype, size) \
3137 void v8::Type##Array::CheckCast(Value* that) { \
3138 i::Handle<i::Object> obj = Utils::OpenHandle(that); \
3140 obj->IsJSTypedArray() && \
3141 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \
3142 "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \
3146 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
3148 #undef CHECK_TYPED_ARRAY_CAST
3151 void v8::DataView::CheckCast(Value* that) {
3152 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3153 Utils::ApiCheck(obj->IsJSDataView(),
3154 "v8::DataView::Cast()",
3155 "Could not convert to DataView");
3159 void v8::SharedArrayBuffer::CheckCast(Value* that) {
3160 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3162 obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(),
3163 "v8::SharedArrayBuffer::Cast()",
3164 "Could not convert to SharedArrayBuffer");
3168 void v8::Date::CheckCast(v8::Value* that) {
3169 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3170 i::Isolate* isolate = NULL;
3171 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3172 Utils::ApiCheck(isolate != NULL &&
3173 obj->HasSpecificClassOf(isolate->heap()->Date_string()),
3175 "Could not convert to date");
3179 void v8::StringObject::CheckCast(v8::Value* that) {
3180 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3181 i::Isolate* isolate = NULL;
3182 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3183 Utils::ApiCheck(isolate != NULL &&
3184 obj->HasSpecificClassOf(isolate->heap()->String_string()),
3185 "v8::StringObject::Cast()",
3186 "Could not convert to StringObject");
3190 void v8::SymbolObject::CheckCast(v8::Value* that) {
3191 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3192 i::Isolate* isolate = NULL;
3193 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3194 Utils::ApiCheck(isolate != NULL &&
3195 obj->HasSpecificClassOf(isolate->heap()->Symbol_string()),
3196 "v8::SymbolObject::Cast()",
3197 "Could not convert to SymbolObject");
3201 void v8::NumberObject::CheckCast(v8::Value* that) {
3202 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3203 i::Isolate* isolate = NULL;
3204 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3205 Utils::ApiCheck(isolate != NULL &&
3206 obj->HasSpecificClassOf(isolate->heap()->Number_string()),
3207 "v8::NumberObject::Cast()",
3208 "Could not convert to NumberObject");
3212 void v8::BooleanObject::CheckCast(v8::Value* that) {
3213 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3214 i::Isolate* isolate = NULL;
3215 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
3216 Utils::ApiCheck(isolate != NULL &&
3217 obj->HasSpecificClassOf(isolate->heap()->Boolean_string()),
3218 "v8::BooleanObject::Cast()",
3219 "Could not convert to BooleanObject");
3223 void v8::RegExp::CheckCast(v8::Value* that) {
3224 i::Handle<i::Object> obj = Utils::OpenHandle(that);
3225 Utils::ApiCheck(obj->IsJSRegExp(),
3226 "v8::RegExp::Cast()",
3227 "Could not convert to regular expression");
3231 Maybe<bool> Value::BooleanValue(Local<Context> context) const {
3232 return Just(Utils::OpenHandle(this)->BooleanValue());
3236 bool Value::BooleanValue() const {
3237 return Utils::OpenHandle(this)->BooleanValue();
3241 Maybe<double> Value::NumberValue(Local<Context> context) const {
3242 auto obj = Utils::OpenHandle(this);
3243 if (obj->IsNumber()) return Just(obj->Number());
3244 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "NumberValue", double);
3245 i::Handle<i::Object> num;
3246 has_pending_exception = !i::Execution::ToNumber(isolate, obj).ToHandle(&num);
3247 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double);
3248 return Just(num->Number());
3252 double Value::NumberValue() const {
3253 auto obj = Utils::OpenHandle(this);
3254 if (obj->IsNumber()) return obj->Number();
3255 return NumberValue(ContextFromHeapObject(obj))
3256 .FromMaybe(std::numeric_limits<double>::quiet_NaN());
3260 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const {
3261 auto obj = Utils::OpenHandle(this);
3262 i::Handle<i::Object> num;
3263 if (obj->IsNumber()) {
3266 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "IntegerValue", int64_t);
3267 has_pending_exception =
3268 !i::Execution::ToInteger(isolate, obj).ToHandle(&num);
3269 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t);
3271 return Just(num->IsSmi() ? static_cast<int64_t>(i::Smi::cast(*num)->value())
3272 : static_cast<int64_t>(num->Number()));
3276 int64_t Value::IntegerValue() const {
3277 auto obj = Utils::OpenHandle(this);
3278 if (obj->IsNumber()) {
3280 return i::Smi::cast(*obj)->value();
3282 return static_cast<int64_t>(obj->Number());
3285 return IntegerValue(ContextFromHeapObject(obj)).FromMaybe(0);
3289 Maybe<int32_t> Value::Int32Value(Local<Context> context) const {
3290 auto obj = Utils::OpenHandle(this);
3291 if (obj->IsNumber()) return Just(NumberToInt32(*obj));
3292 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Int32Value", int32_t);
3293 i::Handle<i::Object> num;
3294 has_pending_exception = !i::Execution::ToInt32(isolate, obj).ToHandle(&num);
3295 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t);
3296 return Just(num->IsSmi() ? i::Smi::cast(*num)->value()
3297 : static_cast<int32_t>(num->Number()));
3301 int32_t Value::Int32Value() const {
3302 auto obj = Utils::OpenHandle(this);
3303 if (obj->IsNumber()) return NumberToInt32(*obj);
3304 return Int32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3308 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const {
3309 auto obj = Utils::OpenHandle(this);
3310 if (obj->IsNumber()) return Just(NumberToUint32(*obj));
3311 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Uint32Value", uint32_t);
3312 i::Handle<i::Object> num;
3313 has_pending_exception = !i::Execution::ToUint32(isolate, obj).ToHandle(&num);
3314 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t);
3315 return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::cast(*num)->value())
3316 : static_cast<uint32_t>(num->Number()));
3320 uint32_t Value::Uint32Value() const {
3321 auto obj = Utils::OpenHandle(this);
3322 if (obj->IsNumber()) return NumberToUint32(*obj);
3323 return Uint32Value(ContextFromHeapObject(obj)).FromMaybe(0);
3327 MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const {
3328 auto self = Utils::OpenHandle(this);
3329 if (self->IsSmi()) {
3330 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3331 return Local<Uint32>();
3333 PREPARE_FOR_EXECUTION(context, "ToArrayIndex", Uint32);
3334 i::Handle<i::Object> string_obj;
3335 has_pending_exception =
3336 !i::Execution::ToString(isolate, self).ToHandle(&string_obj);
3337 RETURN_ON_FAILED_EXECUTION(Uint32);
3338 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
3340 if (str->AsArrayIndex(&index)) {
3341 i::Handle<i::Object> value;
3342 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
3343 value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
3345 value = isolate->factory()->NewNumber(index);
3347 RETURN_ESCAPED(Utils::Uint32ToLocal(value));
3349 return Local<Uint32>();
3353 Local<Uint32> Value::ToArrayIndex() const {
3354 auto self = Utils::OpenHandle(this);
3355 if (self->IsSmi()) {
3356 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self);
3357 return Local<Uint32>();
3359 auto context = ContextFromHeapObject(self);
3360 RETURN_TO_LOCAL_UNCHECKED(ToArrayIndex(context), Uint32);
3364 Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const {
3365 auto self = Utils::OpenHandle(this);
3366 auto other = Utils::OpenHandle(*that);
3367 if (self->IsSmi() && other->IsSmi()) {
3368 return Just(self->Number() == other->Number());
3370 if (self->IsJSObject() && other->IsJSObject()) {
3371 return Just(*self == *other);
3373 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Value::Equals()", bool);
3374 i::Handle<i::Object> args[] = { other };
3375 i::Handle<i::Object> result;
3376 has_pending_exception =
3377 !CallV8HeapFunction(isolate, "EQUALS", self, arraysize(args), args)
3379 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3380 return Just(*result == i::Smi::FromInt(i::EQUAL));
3384 bool Value::Equals(Local<Value> that) const {
3385 auto self = Utils::OpenHandle(this);
3386 auto other = Utils::OpenHandle(*that);
3387 if (self->IsSmi() && other->IsSmi()) {
3388 return self->Number() == other->Number();
3390 if (self->IsJSObject() && other->IsJSObject()) {
3391 return *self == *other;
3393 auto heap_object = self->IsSmi() ? other : self;
3394 auto context = ContextFromHeapObject(heap_object);
3395 return Equals(context, that).FromMaybe(false);
3399 bool Value::StrictEquals(Local<Value> that) const {
3400 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3401 i::Handle<i::Object> other = Utils::OpenHandle(*that);
3403 return other->IsNumber() && obj->Number() == other->Number();
3405 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
3406 LOG_API(isolate, "StrictEquals");
3407 // Must check HeapNumber first, since NaN !== NaN.
3408 if (obj->IsHeapNumber()) {
3409 if (!other->IsNumber()) return false;
3410 double x = obj->Number();
3411 double y = other->Number();
3412 // Must check explicitly for NaN:s on Windows, but -0 works fine.
3413 return x == y && !std::isnan(x) && !std::isnan(y);
3414 } else if (*obj == *other) { // Also covers Booleans.
3416 } else if (obj->IsSmi()) {
3417 return other->IsNumber() && obj->Number() == other->Number();
3418 } else if (obj->IsString()) {
3419 return other->IsString() &&
3420 i::String::Equals(i::Handle<i::String>::cast(obj),
3421 i::Handle<i::String>::cast(other));
3422 } else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
3423 return other->IsUndefined() || other->IsUndetectableObject();
3430 bool Value::SameValue(Local<Value> that) const {
3431 auto self = Utils::OpenHandle(this);
3432 auto other = Utils::OpenHandle(*that);
3433 return self->SameValue(*other);
3437 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context,
3438 v8::Local<Value> key, v8::Local<Value> value) {
3439 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3440 auto self = Utils::OpenHandle(this);
3441 auto key_obj = Utils::OpenHandle(*key);
3442 auto value_obj = Utils::OpenHandle(*value);
3443 has_pending_exception =
3444 i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
3445 i::SLOPPY).is_null();
3446 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3451 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) {
3452 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3453 return Set(context, key, value).FromMaybe(false);
3457 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index,
3458 v8::Local<Value> value) {
3459 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3460 auto self = Utils::OpenHandle(this);
3461 auto value_obj = Utils::OpenHandle(*value);
3462 has_pending_exception =
3463 i::JSReceiver::SetElement(self, index, value_obj, i::SLOPPY).is_null();
3464 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3469 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) {
3470 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3471 return Set(context, index, value).FromMaybe(false);
3475 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3476 v8::Local<Name> key,
3477 v8::Local<Value> value) {
3478 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3480 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3481 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key);
3482 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3484 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
3485 isolate, self, key_obj, i::LookupIterator::OWN);
3486 Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3487 has_pending_exception = result.IsNothing();
3488 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3493 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context,
3495 v8::Local<Value> value) {
3496 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::CreateDataProperty()",
3498 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3499 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3501 i::LookupIterator it(isolate, self, index, i::LookupIterator::OWN);
3502 Maybe<bool> result = i::JSObject::CreateDataProperty(&it, value_obj);
3503 has_pending_exception = result.IsNothing();
3504 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3509 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context,
3510 v8::Local<Name> key,
3511 v8::Local<Value> value,
3512 v8::PropertyAttribute attributes) {
3513 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DefineOwnProperty()",
3515 auto self = Utils::OpenHandle(this);
3516 auto key_obj = Utils::OpenHandle(*key);
3517 auto value_obj = Utils::OpenHandle(*value);
3519 if (self->IsAccessCheckNeeded() && !isolate->MayAccess(self)) {
3520 isolate->ReportFailedAccessCheck(self);
3521 return Nothing<bool>();
3524 i::Handle<i::FixedArray> desc = isolate->factory()->NewFixedArray(3);
3525 desc->set(0, isolate->heap()->ToBoolean(!(attributes & v8::ReadOnly)));
3526 desc->set(1, isolate->heap()->ToBoolean(!(attributes & v8::DontEnum)));
3527 desc->set(2, isolate->heap()->ToBoolean(!(attributes & v8::DontDelete)));
3528 i::Handle<i::JSArray> desc_array =
3529 isolate->factory()->NewJSArrayWithElements(desc, i::FAST_ELEMENTS, 3);
3530 i::Handle<i::Object> args[] = {self, key_obj, value_obj, desc_array};
3531 i::Handle<i::Object> result;
3532 has_pending_exception =
3533 !CallV8HeapFunction(isolate, "$objectDefineOwnProperty",
3534 isolate->factory()->undefined_value(),
3535 arraysize(args), args).ToHandle(&result);
3536 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3537 return Just(result->BooleanValue());
3542 static i::MaybeHandle<i::Object> DefineObjectProperty(
3543 i::Handle<i::JSObject> js_object, i::Handle<i::Object> key,
3544 i::Handle<i::Object> value, PropertyAttributes attrs) {
3545 i::Isolate* isolate = js_object->GetIsolate();
3546 // Check if the given key is an array index.
3548 if (key->ToArrayIndex(&index)) {
3549 return i::JSObject::SetOwnElementIgnoreAttributes(js_object, index, value,
3553 i::Handle<i::Name> name;
3554 ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name,
3555 i::Runtime::ToName(isolate, key),
3556 i::MaybeHandle<i::Object>());
3558 return i::JSObject::DefinePropertyOrElementIgnoreAttributes(js_object, name,
3563 Maybe<bool> v8::Object::ForceSet(v8::Local<v8::Context> context,
3564 v8::Local<Value> key, v8::Local<Value> value,
3565 v8::PropertyAttribute attribs) {
3566 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Set()", bool);
3567 auto self = Utils::OpenHandle(this);
3568 auto key_obj = Utils::OpenHandle(*key);
3569 auto value_obj = Utils::OpenHandle(*value);
3570 has_pending_exception =
3571 DefineObjectProperty(self, key_obj, value_obj,
3572 static_cast<PropertyAttributes>(attribs)).is_null();
3573 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3578 bool v8::Object::ForceSet(v8::Local<Value> key, v8::Local<Value> value,
3579 v8::PropertyAttribute attribs) {
3580 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3581 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(),
3582 "v8::Object::ForceSet", false, i::HandleScope,
3584 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3585 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
3586 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3587 has_pending_exception =
3588 DefineObjectProperty(self, key_obj, value_obj,
3589 static_cast<PropertyAttributes>(attribs)).is_null();
3590 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, false);
3595 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context,
3597 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3598 auto self = Utils::OpenHandle(this);
3599 auto key_obj = Utils::OpenHandle(*key);
3600 i::Handle<i::Object> result;
3601 has_pending_exception =
3602 !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
3603 RETURN_ON_FAILED_EXECUTION(Value);
3604 RETURN_ESCAPED(Utils::ToLocal(result));
3608 Local<Value> v8::Object::Get(v8::Local<Value> key) {
3609 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3610 RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value);
3614 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) {
3615 PREPARE_FOR_EXECUTION(context, "v8::Object::Get()", Value);
3616 auto self = Utils::OpenHandle(this);
3617 i::Handle<i::Object> result;
3618 has_pending_exception =
3619 !i::Object::GetElement(isolate, self, index).ToHandle(&result);
3620 RETURN_ON_FAILED_EXECUTION(Value);
3621 RETURN_ESCAPED(Utils::ToLocal(result));
3625 Local<Value> v8::Object::Get(uint32_t index) {
3626 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3627 RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value);
3631 Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes(
3632 Local<Context> context, Local<Value> key) {
3633 PREPARE_FOR_EXECUTION_PRIMITIVE(
3634 context, "v8::Object::GetPropertyAttributes()", PropertyAttribute);
3635 auto self = Utils::OpenHandle(this);
3636 auto key_obj = Utils::OpenHandle(*key);
3637 if (!key_obj->IsName()) {
3638 has_pending_exception = !i::Execution::ToString(
3639 isolate, key_obj).ToHandle(&key_obj);
3640 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3642 auto key_name = i::Handle<i::Name>::cast(key_obj);
3643 auto result = i::JSReceiver::GetPropertyAttributes(self, key_name);
3644 has_pending_exception = result.IsNothing();
3645 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
3646 if (result.FromJust() == ABSENT) {
3647 return Just(static_cast<PropertyAttribute>(NONE));
3649 return Just(static_cast<PropertyAttribute>(result.FromJust()));
3653 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Local<Value> key) {
3654 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3655 return GetPropertyAttributes(context, key)
3656 .FromMaybe(static_cast<PropertyAttribute>(NONE));
3660 MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context,
3661 Local<String> key) {
3662 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyDescriptor()",
3664 auto obj = Utils::OpenHandle(this);
3665 auto key_name = Utils::OpenHandle(*key);
3666 i::Handle<i::Object> args[] = { obj, key_name };
3667 i::Handle<i::Object> result;
3668 has_pending_exception =
3669 !CallV8HeapFunction(isolate, "$objectGetOwnPropertyDescriptor",
3670 isolate->factory()->undefined_value(),
3671 arraysize(args), args).ToHandle(&result);
3672 RETURN_ON_FAILED_EXECUTION(Value);
3673 RETURN_ESCAPED(Utils::ToLocal(result));
3677 Local<Value> v8::Object::GetOwnPropertyDescriptor(Local<String> key) {
3678 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3679 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyDescriptor(context, key), Value);
3683 Local<Value> v8::Object::GetPrototype() {
3684 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3685 auto self = Utils::OpenHandle(this);
3686 i::PrototypeIterator iter(isolate, self);
3687 return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
3691 Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
3692 Local<Value> value) {
3693 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetPrototype()", bool);
3694 auto self = Utils::OpenHandle(this);
3695 auto value_obj = Utils::OpenHandle(*value);
3696 // We do not allow exceptions thrown while setting the prototype
3697 // to propagate outside.
3698 TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
3699 auto result = i::JSObject::SetPrototype(self, value_obj, false);
3700 has_pending_exception = result.is_null();
3701 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3706 bool v8::Object::SetPrototype(Local<Value> value) {
3707 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3708 return SetPrototype(context, value).FromMaybe(false);
3712 Local<Object> v8::Object::FindInstanceInPrototypeChain(
3713 v8::Local<FunctionTemplate> tmpl) {
3714 auto isolate = Utils::OpenHandle(this)->GetIsolate();
3715 i::PrototypeIterator iter(isolate, *Utils::OpenHandle(this),
3716 i::PrototypeIterator::START_AT_RECEIVER);
3717 auto tmpl_info = *Utils::OpenHandle(*tmpl);
3718 while (!tmpl_info->IsTemplateFor(iter.GetCurrent())) {
3720 if (iter.IsAtEnd()) {
3721 return Local<Object>();
3724 return Utils::ToLocal(
3725 i::handle(i::JSObject::cast(iter.GetCurrent()), isolate));
3729 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) {
3730 PREPARE_FOR_EXECUTION(context, "v8::Object::GetPropertyNames()", Array);
3731 auto self = Utils::OpenHandle(this);
3732 i::Handle<i::FixedArray> value;
3733 has_pending_exception = !i::JSReceiver::GetKeys(
3734 self, i::JSReceiver::INCLUDE_PROTOS).ToHandle(&value);
3735 RETURN_ON_FAILED_EXECUTION(Array);
3736 // Because we use caching to speed up enumeration it is important
3737 // to never change the result of the basic enumeration function so
3738 // we clone the result.
3739 auto elms = isolate->factory()->CopyFixedArray(value);
3740 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3741 RETURN_ESCAPED(Utils::ToLocal(result));
3745 Local<Array> v8::Object::GetPropertyNames() {
3746 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3747 RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array);
3751 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) {
3752 PREPARE_FOR_EXECUTION(context, "v8::Object::GetOwnPropertyNames()", Array);
3753 auto self = Utils::OpenHandle(this);
3754 i::Handle<i::FixedArray> value;
3755 has_pending_exception = !i::JSReceiver::GetKeys(
3756 self, i::JSReceiver::OWN_ONLY).ToHandle(&value);
3757 RETURN_ON_FAILED_EXECUTION(Array);
3758 // Because we use caching to speed up enumeration it is important
3759 // to never change the result of the basic enumeration function so
3760 // we clone the result.
3761 auto elms = isolate->factory()->CopyFixedArray(value);
3762 auto result = isolate->factory()->NewJSArrayWithElements(elms);
3763 RETURN_ESCAPED(Utils::ToLocal(result));
3767 Local<Array> v8::Object::GetOwnPropertyNames() {
3768 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3769 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array);
3773 MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) {
3774 auto self = Utils::OpenHandle(this);
3775 auto isolate = self->GetIsolate();
3776 auto v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
3777 i::Handle<i::Object> name(self->class_name(), isolate);
3778 i::Handle<i::Object> tag;
3780 // Native implementation of Object.prototype.toString (v8natives.js):
3781 // var c = %_ClassOf(this);
3782 // if (c === 'Arguments') c = 'Object';
3783 // return "[object " + c + "]";
3785 if (!name->IsString()) {
3786 return v8::String::NewFromUtf8(v8_isolate, "[object ]",
3787 NewStringType::kNormal);
3789 auto class_name = i::Handle<i::String>::cast(name);
3790 if (i::String::Equals(class_name, isolate->factory()->Arguments_string())) {
3791 return v8::String::NewFromUtf8(v8_isolate, "[object Object]",
3792 NewStringType::kNormal);
3794 if (internal::FLAG_harmony_tostring) {
3795 PREPARE_FOR_EXECUTION(context, "v8::Object::ObjectProtoToString()", String);
3796 auto toStringTag = isolate->factory()->to_string_tag_symbol();
3797 has_pending_exception = !i::Runtime::GetObjectProperty(
3798 isolate, self, toStringTag).ToHandle(&tag);
3799 RETURN_ON_FAILED_EXECUTION(String);
3800 if (tag->IsString()) {
3801 class_name = i::Handle<i::String>::cast(tag).EscapeFrom(&handle_scope);
3804 const char* prefix = "[object ";
3805 Local<String> str = Utils::ToLocal(class_name);
3806 const char* postfix = "]";
3808 int prefix_len = i::StrLength(prefix);
3809 int str_len = str->Utf8Length();
3810 int postfix_len = i::StrLength(postfix);
3812 int buf_len = prefix_len + str_len + postfix_len;
3813 i::ScopedVector<char> buf(buf_len);
3816 char* ptr = buf.start();
3817 i::MemCopy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3820 // Write real content.
3821 str->WriteUtf8(ptr, str_len);
3825 i::MemCopy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3827 // Copy the buffer into a heap-allocated string and return it.
3828 return v8::String::NewFromUtf8(v8_isolate, buf.start(),
3829 NewStringType::kNormal, buf_len);
3833 Local<String> v8::Object::ObjectProtoToString() {
3834 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3835 RETURN_TO_LOCAL_UNCHECKED(ObjectProtoToString(context), String);
3839 Local<String> v8::Object::GetConstructorName() {
3840 auto self = Utils::OpenHandle(this);
3841 i::Handle<i::String> name(self->constructor_name());
3842 return Utils::ToLocal(name);
3846 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) {
3847 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Delete()", bool);
3848 auto self = Utils::OpenHandle(this);
3849 auto key_obj = Utils::OpenHandle(*key);
3850 i::Handle<i::Object> obj;
3851 has_pending_exception =
3852 !i::Runtime::DeleteObjectProperty(isolate, self, key_obj, i::SLOPPY)
3854 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3855 return Just(obj->IsTrue());
3859 bool v8::Object::Delete(v8::Local<Value> key) {
3860 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3861 return Delete(context, key).FromMaybe(false);
3865 Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) {
3866 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3867 auto self = Utils::OpenHandle(this);
3868 auto key_obj = Utils::OpenHandle(*key);
3869 Maybe<bool> maybe = Nothing<bool>();
3870 // Check if the given key is an array index.
3872 if (key_obj->ToArrayIndex(&index)) {
3873 maybe = i::JSReceiver::HasElement(self, index);
3875 // Convert the key to a name - possibly by calling back into JavaScript.
3876 i::Handle<i::Name> name;
3877 if (i::Runtime::ToName(isolate, key_obj).ToHandle(&name)) {
3878 maybe = i::JSReceiver::HasProperty(self, name);
3881 has_pending_exception = maybe.IsNothing();
3882 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3887 bool v8::Object::Has(v8::Local<Value> key) {
3888 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3889 return Has(context, key).FromMaybe(false);
3893 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) {
3894 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::DeleteProperty()",
3896 auto self = Utils::OpenHandle(this);
3897 i::Handle<i::Object> obj;
3898 has_pending_exception =
3899 !i::JSReceiver::DeleteElement(self, index).ToHandle(&obj);
3900 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3901 return Just(obj->IsTrue());
3905 bool v8::Object::Delete(uint32_t index) {
3906 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3907 return Delete(context, index).FromMaybe(false);
3911 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) {
3912 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::Get()", bool);
3913 auto self = Utils::OpenHandle(this);
3914 auto maybe = i::JSReceiver::HasElement(self, index);
3915 has_pending_exception = maybe.IsNothing();
3916 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3921 bool v8::Object::Has(uint32_t index) {
3922 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3923 return Has(context, index).FromMaybe(false);
3927 template <typename Getter, typename Setter, typename Data>
3928 static Maybe<bool> ObjectSetAccessor(Local<Context> context, Object* obj,
3929 Local<Name> name, Getter getter,
3930 Setter setter, Data data,
3931 AccessControl settings,
3932 PropertyAttribute attributes) {
3933 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::SetAccessor()", bool);
3934 v8::Local<AccessorSignature> signature;
3935 auto info = MakeAccessorInfo(name, getter, setter, data, settings, attributes,
3937 if (info.is_null()) return Nothing<bool>();
3938 bool fast = Utils::OpenHandle(obj)->HasFastProperties();
3939 i::Handle<i::Object> result;
3940 has_pending_exception =
3941 !i::JSObject::SetAccessor(Utils::OpenHandle(obj), info).ToHandle(&result);
3942 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
3943 if (result->IsUndefined()) return Nothing<bool>();
3945 i::JSObject::MigrateSlowToFast(Utils::OpenHandle(obj), 0, "APISetAccessor");
3951 Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name,
3952 AccessorNameGetterCallback getter,
3953 AccessorNameSetterCallback setter,
3954 MaybeLocal<Value> data, AccessControl settings,
3955 PropertyAttribute attribute) {
3956 return ObjectSetAccessor(context, this, name, getter, setter,
3957 data.FromMaybe(Local<Value>()), settings, attribute);
3961 bool Object::SetAccessor(Local<String> name, AccessorGetterCallback getter,
3962 AccessorSetterCallback setter, v8::Local<Value> data,
3963 AccessControl settings, PropertyAttribute attributes) {
3964 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3965 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3966 attributes).FromMaybe(false);
3970 bool Object::SetAccessor(Local<Name> name, AccessorNameGetterCallback getter,
3971 AccessorNameSetterCallback setter,
3972 v8::Local<Value> data, AccessControl settings,
3973 PropertyAttribute attributes) {
3974 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
3975 return ObjectSetAccessor(context, this, name, getter, setter, data, settings,
3976 attributes).FromMaybe(false);
3980 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter,
3981 Local<Function> setter,
3982 PropertyAttribute attribute,
3983 AccessControl settings) {
3984 // TODO(verwaest): Remove |settings|.
3985 DCHECK_EQ(v8::DEFAULT, settings);
3986 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3988 i::HandleScope scope(isolate);
3989 i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
3990 i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
3991 if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
3992 i::JSObject::DefineAccessor(v8::Utils::OpenHandle(this),
3993 v8::Utils::OpenHandle(*name),
3996 static_cast<PropertyAttributes>(attribute));
4000 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
4002 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasOwnProperty()",
4004 auto self = Utils::OpenHandle(this);
4005 auto key_val = Utils::OpenHandle(*key);
4006 auto result = i::JSReceiver::HasOwnProperty(self, key_val);
4007 has_pending_exception = result.IsNothing();
4008 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4013 bool v8::Object::HasOwnProperty(Local<String> key) {
4014 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4015 return HasOwnProperty(context, key).FromMaybe(false);
4019 Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context,
4021 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasRealNamedProperty()",
4023 auto self = Utils::OpenHandle(this);
4024 auto key_val = Utils::OpenHandle(*key);
4025 auto result = i::JSObject::HasRealNamedProperty(self, key_val);
4026 has_pending_exception = result.IsNothing();
4027 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4032 bool v8::Object::HasRealNamedProperty(Local<String> key) {
4033 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4034 return HasRealNamedProperty(context, key).FromMaybe(false);
4038 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context,
4040 PREPARE_FOR_EXECUTION_PRIMITIVE(context,
4041 "v8::Object::HasRealIndexedProperty()", bool);
4042 auto self = Utils::OpenHandle(this);
4043 auto result = i::JSObject::HasRealElementProperty(self, index);
4044 has_pending_exception = result.IsNothing();
4045 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4050 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
4051 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4052 return HasRealIndexedProperty(context, index).FromMaybe(false);
4056 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context,
4058 PREPARE_FOR_EXECUTION_PRIMITIVE(
4059 context, "v8::Object::HasRealNamedCallbackProperty()", bool);
4060 auto self = Utils::OpenHandle(this);
4061 auto key_val = Utils::OpenHandle(*key);
4062 auto result = i::JSObject::HasRealNamedCallbackProperty(self, key_val);
4063 has_pending_exception = result.IsNothing();
4064 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
4069 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) {
4070 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4071 return HasRealNamedCallbackProperty(context, key).FromMaybe(false);
4075 bool v8::Object::HasNamedLookupInterceptor() {
4076 auto self = Utils::OpenHandle(this);
4077 return self->HasNamedInterceptor();
4081 bool v8::Object::HasIndexedLookupInterceptor() {
4082 auto self = Utils::OpenHandle(this);
4083 return self->HasIndexedInterceptor();
4087 MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4088 Local<Context> context, Local<Name> key) {
4089 PREPARE_FOR_EXECUTION(
4090 context, "v8::Object::GetRealNamedPropertyInPrototypeChain()", Value);
4091 auto self = Utils::OpenHandle(this);
4092 auto key_obj = Utils::OpenHandle(*key);
4093 i::PrototypeIterator iter(isolate, self);
4094 if (iter.IsAtEnd()) return MaybeLocal<Value>();
4095 auto proto = i::PrototypeIterator::GetCurrent(iter);
4096 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4097 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4098 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4099 Local<Value> result;
4100 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4101 RETURN_ON_FAILED_EXECUTION(Value);
4102 if (!it.IsFound()) return MaybeLocal<Value>();
4103 RETURN_ESCAPED(result);
4107 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
4108 Local<String> key) {
4109 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4110 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedPropertyInPrototypeChain(context, key),
4115 Maybe<PropertyAttribute>
4116 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(
4117 Local<Context> context, Local<Name> key) {
4118 PREPARE_FOR_EXECUTION_PRIMITIVE(
4119 context, "v8::Object::GetRealNamedPropertyAttributesInPrototypeChain()",
4121 auto self = Utils::OpenHandle(this);
4122 auto key_obj = Utils::OpenHandle(*key);
4123 i::PrototypeIterator iter(isolate, self);
4124 if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
4125 auto proto = i::PrototypeIterator::GetCurrent(iter);
4126 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4127 isolate, self, key_obj, i::Handle<i::JSReceiver>::cast(proto),
4128 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4129 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4130 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4131 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4132 if (result.FromJust() == ABSENT) {
4133 return Just(static_cast<PropertyAttribute>(NONE));
4135 return Just<PropertyAttribute>(
4136 static_cast<PropertyAttribute>(result.FromJust()));
4140 Maybe<PropertyAttribute>
4141 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(Local<String> key) {
4142 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4143 return GetRealNamedPropertyAttributesInPrototypeChain(context, key);
4147 MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context,
4149 PREPARE_FOR_EXECUTION(context, "v8::Object::GetRealNamedProperty()", Value);
4150 auto self = Utils::OpenHandle(this);
4151 auto key_obj = Utils::OpenHandle(*key);
4152 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4153 isolate, self, key_obj,
4154 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4155 Local<Value> result;
4156 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
4157 RETURN_ON_FAILED_EXECUTION(Value);
4158 if (!it.IsFound()) return MaybeLocal<Value>();
4159 RETURN_ESCAPED(result);
4163 Local<Value> v8::Object::GetRealNamedProperty(Local<String> key) {
4164 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4165 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedProperty(context, key), Value);
4169 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4170 Local<Context> context, Local<Name> key) {
4171 PREPARE_FOR_EXECUTION_PRIMITIVE(
4172 context, "v8::Object::GetRealNamedPropertyAttributes()",
4174 auto self = Utils::OpenHandle(this);
4175 auto key_obj = Utils::OpenHandle(*key);
4176 i::LookupIterator it = i::LookupIterator::PropertyOrElement(
4177 isolate, self, key_obj,
4178 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
4179 auto result = i::JSReceiver::GetPropertyAttributes(&it);
4180 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute);
4181 if (!it.IsFound()) return Nothing<PropertyAttribute>();
4182 if (result.FromJust() == ABSENT) {
4183 return Just(static_cast<PropertyAttribute>(NONE));
4185 return Just<PropertyAttribute>(
4186 static_cast<PropertyAttribute>(result.FromJust()));
4190 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes(
4191 Local<String> key) {
4192 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4193 return GetRealNamedPropertyAttributes(context, key);
4197 Local<v8::Object> v8::Object::Clone() {
4198 auto self = Utils::OpenHandle(this);
4199 auto isolate = self->GetIsolate();
4201 auto result = isolate->factory()->CopyJSObject(self);
4202 CHECK(!result.is_null());
4203 return Utils::ToLocal(result);
4207 Local<v8::Context> v8::Object::CreationContext() {
4208 auto self = Utils::OpenHandle(this);
4209 auto context = handle(self->GetCreationContext());
4210 return Utils::ToLocal(context);
4214 int v8::Object::GetIdentityHash() {
4215 auto isolate = Utils::OpenHandle(this)->GetIsolate();
4216 i::HandleScope scope(isolate);
4217 auto self = Utils::OpenHandle(this);
4218 return i::JSReceiver::GetOrCreateIdentityHash(self)->value();
4222 bool v8::Object::SetHiddenValue(v8::Local<v8::String> key,
4223 v8::Local<v8::Value> value) {
4224 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4225 if (value.IsEmpty()) return DeleteHiddenValue(key);
4227 i::HandleScope scope(isolate);
4228 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4229 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4230 i::Handle<i::String> key_string =
4231 isolate->factory()->InternalizeString(key_obj);
4232 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
4233 i::Handle<i::Object> result =
4234 i::JSObject::SetHiddenProperty(self, key_string, value_obj);
4235 return *result == *self;
4239 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Local<v8::String> key) {
4240 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4242 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4243 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4244 i::Handle<i::String> key_string =
4245 isolate->factory()->InternalizeString(key_obj);
4246 i::Handle<i::Object> result(self->GetHiddenProperty(key_string), isolate);
4247 if (result->IsTheHole()) return v8::Local<v8::Value>();
4248 return Utils::ToLocal(result);
4252 bool v8::Object::DeleteHiddenValue(v8::Local<v8::String> key) {
4253 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4255 i::HandleScope scope(isolate);
4256 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4257 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
4258 i::Handle<i::String> key_string =
4259 isolate->factory()->InternalizeString(key_obj);
4260 i::JSObject::DeleteHiddenProperty(self, key_string);
4265 bool v8::Object::IsCallable() {
4266 auto self = Utils::OpenHandle(this);
4267 return self->IsCallable();
4271 MaybeLocal<Value> Object::CallAsFunction(Local<Context> context,
4272 Local<Value> recv, int argc,
4273 Local<Value> argv[]) {
4274 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Object::CallAsFunction()",
4276 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4277 auto self = Utils::OpenHandle(this);
4278 auto recv_obj = Utils::OpenHandle(*recv);
4279 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4280 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4281 i::Handle<i::JSFunction> fun;
4282 if (self->IsJSFunction()) {
4283 fun = i::Handle<i::JSFunction>::cast(self);
4285 i::Handle<i::Object> delegate;
4286 has_pending_exception = !i::Execution::TryGetFunctionDelegate(isolate, self)
4287 .ToHandle(&delegate);
4288 RETURN_ON_FAILED_EXECUTION(Value);
4289 fun = i::Handle<i::JSFunction>::cast(delegate);
4292 Local<Value> result;
4293 has_pending_exception =
4295 i::Execution::Call(isolate, fun, recv_obj, argc, args, true),
4297 RETURN_ON_FAILED_EXECUTION(Value);
4298 RETURN_ESCAPED(result);
4302 Local<v8::Value> Object::CallAsFunction(v8::Local<v8::Value> recv, int argc,
4303 v8::Local<v8::Value> argv[]) {
4304 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4305 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4306 RETURN_TO_LOCAL_UNCHECKED(CallAsFunction(context, recv, argc, argv_cast),
4311 MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc,
4312 Local<Value> argv[]) {
4313 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context,
4314 "v8::Object::CallAsConstructor()", Value);
4315 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4316 auto self = Utils::OpenHandle(this);
4317 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4318 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4319 if (self->IsJSFunction()) {
4320 auto fun = i::Handle<i::JSFunction>::cast(self);
4321 Local<Value> result;
4322 has_pending_exception =
4323 !ToLocal<Value>(i::Execution::New(fun, argc, args), &result);
4324 RETURN_ON_FAILED_EXECUTION(Value);
4325 RETURN_ESCAPED(result);
4327 i::Handle<i::Object> delegate;
4328 has_pending_exception = !i::Execution::TryGetConstructorDelegate(
4329 isolate, self).ToHandle(&delegate);
4330 RETURN_ON_FAILED_EXECUTION(Value);
4331 if (!delegate->IsUndefined()) {
4332 auto fun = i::Handle<i::JSFunction>::cast(delegate);
4333 Local<Value> result;
4334 has_pending_exception =
4335 !ToLocal<Value>(i::Execution::Call(isolate, fun, self, argc, args),
4337 RETURN_ON_FAILED_EXECUTION(Value);
4338 DCHECK(!delegate->IsUndefined());
4339 RETURN_ESCAPED(result);
4341 return MaybeLocal<Value>();
4345 Local<v8::Value> Object::CallAsConstructor(int argc,
4346 v8::Local<v8::Value> argv[]) {
4347 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4348 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv);
4349 RETURN_TO_LOCAL_UNCHECKED(CallAsConstructor(context, argc, argv_cast), Value);
4353 MaybeLocal<Function> Function::New(Local<Context> context,
4354 FunctionCallback callback, Local<Value> data,
4356 i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate();
4357 LOG_API(isolate, "Function::New");
4359 return FunctionTemplateNew(isolate, callback, data, Local<Signature>(),
4360 length, true)->GetFunction(context);
4364 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback,
4365 Local<Value> data, int length) {
4366 return Function::New(v8_isolate->GetCurrentContext(), callback, data, length)
4367 .FromMaybe(Local<Function>());
4371 Local<v8::Object> Function::NewInstance() const {
4372 return NewInstance(Isolate::GetCurrent()->GetCurrentContext(), 0, NULL)
4373 .FromMaybe(Local<Object>());
4377 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc,
4378 v8::Local<v8::Value> argv[]) const {
4379 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::NewInstance()",
4381 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4382 auto self = Utils::OpenHandle(this);
4383 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4384 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4385 Local<Object> result;
4386 has_pending_exception =
4387 !ToLocal<Object>(i::Execution::New(self, argc, args), &result);
4388 RETURN_ON_FAILED_EXECUTION(Object);
4389 RETURN_ESCAPED(result);
4393 Local<v8::Object> Function::NewInstance(int argc,
4394 v8::Local<v8::Value> argv[]) const {
4395 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4396 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context, argc, argv), Object);
4400 MaybeLocal<v8::Value> Function::Call(Local<Context> context,
4401 v8::Local<v8::Value> recv, int argc,
4402 v8::Local<v8::Value> argv[]) {
4403 PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, "v8::Function::Call()", Value);
4404 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
4405 auto self = Utils::OpenHandle(this);
4406 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
4407 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**));
4408 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
4409 Local<Value> result;
4410 has_pending_exception =
4412 i::Execution::Call(isolate, self, recv_obj, argc, args, true),
4414 RETURN_ON_FAILED_EXECUTION(Value);
4415 RETURN_ESCAPED(result);
4419 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc,
4420 v8::Local<v8::Value> argv[]) {
4421 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
4422 RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value);
4426 void Function::SetName(v8::Local<v8::String> name) {
4427 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4428 func->shared()->set_name(*Utils::OpenHandle(*name));
4432 Local<Value> Function::GetName() const {
4433 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4434 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name(),
4435 func->GetIsolate()));
4439 Local<Value> Function::GetInferredName() const {
4440 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4441 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
4442 func->GetIsolate()));
4446 Local<Value> Function::GetDisplayName() const {
4447 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4449 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4450 i::Handle<i::String> property_name =
4451 isolate->factory()->NewStringFromStaticChars("displayName");
4452 i::Handle<i::Object> value =
4453 i::JSReceiver::GetDataProperty(func, property_name);
4454 if (value->IsString()) {
4455 i::Handle<i::String> name = i::Handle<i::String>::cast(value);
4456 if (name->length() > 0) return Utils::ToLocal(name);
4458 return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
4462 ScriptOrigin Function::GetScriptOrigin() const {
4463 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4464 if (func->shared()->script()->IsScript()) {
4465 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4466 return GetScriptOriginForScript(func->GetIsolate(), script);
4468 return v8::ScriptOrigin(Local<Value>());
4472 const int Function::kLineOffsetNotFound = -1;
4475 int Function::GetScriptLineNumber() const {
4476 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4477 if (func->shared()->script()->IsScript()) {
4478 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4479 return i::Script::GetLineNumber(script, func->shared()->start_position());
4481 return kLineOffsetNotFound;
4485 int Function::GetScriptColumnNumber() const {
4486 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4487 if (func->shared()->script()->IsScript()) {
4488 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4489 return i::Script::GetColumnNumber(script, func->shared()->start_position());
4491 return kLineOffsetNotFound;
4495 bool Function::IsBuiltin() const {
4496 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4497 return func->IsBuiltin();
4501 int Function::ScriptId() const {
4502 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4503 if (!func->shared()->script()->IsScript()) {
4504 return v8::UnboundScript::kNoScriptId;
4506 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
4507 return script->id()->value();
4511 Local<v8::Value> Function::GetBoundFunction() const {
4512 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
4513 if (!func->shared()->bound()) {
4514 return v8::Undefined(reinterpret_cast<v8::Isolate*>(func->GetIsolate()));
4516 i::Handle<i::FixedArray> bound_args = i::Handle<i::FixedArray>(
4517 i::FixedArray::cast(func->function_bindings()));
4518 i::Handle<i::Object> original(
4519 bound_args->get(i::JSFunction::kBoundFunctionIndex),
4520 func->GetIsolate());
4521 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(original));
4525 int Name::GetIdentityHash() {
4526 auto self = Utils::OpenHandle(this);
4527 return static_cast<int>(self->Hash());
4531 int String::Length() const {
4532 i::Handle<i::String> str = Utils::OpenHandle(this);
4533 return str->length();
4537 bool String::IsOneByte() const {
4538 i::Handle<i::String> str = Utils::OpenHandle(this);
4539 return str->HasOnlyOneByteChars();
4543 // Helpers for ContainsOnlyOneByteHelper
4544 template<size_t size> struct OneByteMask;
4545 template<> struct OneByteMask<4> {
4546 static const uint32_t value = 0xFF00FF00;
4548 template<> struct OneByteMask<8> {
4549 static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
4551 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
4552 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
4553 static inline bool Unaligned(const uint16_t* chars) {
4554 return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
4558 static inline const uint16_t* Align(const uint16_t* chars) {
4559 return reinterpret_cast<uint16_t*>(
4560 reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
4563 class ContainsOnlyOneByteHelper {
4565 ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
4566 bool Check(i::String* string) {
4567 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
4568 if (cons_string == NULL) return is_one_byte_;
4569 return CheckCons(cons_string);
4571 void VisitOneByteString(const uint8_t* chars, int length) {
4574 void VisitTwoByteString(const uint16_t* chars, int length) {
4575 // Accumulated bits.
4577 // Align to uintptr_t.
4578 const uint16_t* end = chars + length;
4579 while (Unaligned(chars) && chars != end) {
4582 // Read word aligned in blocks,
4583 // checking the return value at the end of each block.
4584 const uint16_t* aligned_end = Align(end);
4585 const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
4586 const int inner_loops = 16;
4587 while (chars + inner_loops*increment < aligned_end) {
4588 for (int i = 0; i < inner_loops; i++) {
4589 acc |= *reinterpret_cast<const uintptr_t*>(chars);
4592 // Check for early return.
4593 if ((acc & kOneByteMask) != 0) {
4594 is_one_byte_ = false;
4599 while (chars != end) {
4603 if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
4607 bool CheckCons(i::ConsString* cons_string) {
4609 // Check left side if flat.
4610 i::String* left = cons_string->first();
4611 i::ConsString* left_as_cons =
4612 i::String::VisitFlat(this, left, 0);
4613 if (!is_one_byte_) return false;
4614 // Check right side if flat.
4615 i::String* right = cons_string->second();
4616 i::ConsString* right_as_cons =
4617 i::String::VisitFlat(this, right, 0);
4618 if (!is_one_byte_) return false;
4619 // Standard recurse/iterate trick.
4620 if (left_as_cons != NULL && right_as_cons != NULL) {
4621 if (left->length() < right->length()) {
4622 CheckCons(left_as_cons);
4623 cons_string = right_as_cons;
4625 CheckCons(right_as_cons);
4626 cons_string = left_as_cons;
4628 // Check fast return.
4629 if (!is_one_byte_) return false;
4632 // Descend left in place.
4633 if (left_as_cons != NULL) {
4634 cons_string = left_as_cons;
4637 // Descend right in place.
4638 if (right_as_cons != NULL) {
4639 cons_string = right_as_cons;
4645 return is_one_byte_;
4648 DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
4652 bool String::ContainsOnlyOneByte() const {
4653 i::Handle<i::String> str = Utils::OpenHandle(this);
4654 if (str->HasOnlyOneByteChars()) return true;
4655 ContainsOnlyOneByteHelper helper;
4656 return helper.Check(*str);
4660 class Utf8LengthHelper : public i::AllStatic {
4663 kEndsWithLeadingSurrogate = 1 << 0,
4664 kStartsWithTrailingSurrogate = 1 << 1,
4665 kLeftmostEdgeIsCalculated = 1 << 2,
4666 kRightmostEdgeIsCalculated = 1 << 3,
4667 kLeftmostEdgeIsSurrogate = 1 << 4,
4668 kRightmostEdgeIsSurrogate = 1 << 5
4671 static const uint8_t kInitialState = 0;
4673 static inline bool EndsWithSurrogate(uint8_t state) {
4674 return state & kEndsWithLeadingSurrogate;
4677 static inline bool StartsWithSurrogate(uint8_t state) {
4678 return state & kStartsWithTrailingSurrogate;
4683 Visitor() : utf8_length_(0), state_(kInitialState) {}
4685 void VisitOneByteString(const uint8_t* chars, int length) {
4686 int utf8_length = 0;
4687 // Add in length 1 for each non-Latin1 character.
4688 for (int i = 0; i < length; i++) {
4689 utf8_length += *chars++ >> 7;
4691 // Add in length 1 for each character.
4692 utf8_length_ = utf8_length + length;
4693 state_ = kInitialState;
4696 void VisitTwoByteString(const uint16_t* chars, int length) {
4697 int utf8_length = 0;
4698 int last_character = unibrow::Utf16::kNoPreviousCharacter;
4699 for (int i = 0; i < length; i++) {
4700 uint16_t c = chars[i];
4701 utf8_length += unibrow::Utf8::Length(c, last_character);
4704 utf8_length_ = utf8_length;
4706 if (unibrow::Utf16::IsTrailSurrogate(chars[0])) {
4707 state |= kStartsWithTrailingSurrogate;
4709 if (unibrow::Utf16::IsLeadSurrogate(chars[length-1])) {
4710 state |= kEndsWithLeadingSurrogate;
4715 static i::ConsString* VisitFlat(i::String* string,
4719 i::ConsString* cons_string = i::String::VisitFlat(&visitor, string);
4720 *length = visitor.utf8_length_;
4721 *state = visitor.state_;
4728 DISALLOW_COPY_AND_ASSIGN(Visitor);
4731 static inline void MergeLeafLeft(int* length,
4733 uint8_t leaf_state) {
4734 bool edge_surrogate = StartsWithSurrogate(leaf_state);
4735 if (!(*state & kLeftmostEdgeIsCalculated)) {
4736 DCHECK(!(*state & kLeftmostEdgeIsSurrogate));
4737 *state |= kLeftmostEdgeIsCalculated
4738 | (edge_surrogate ? kLeftmostEdgeIsSurrogate : 0);
4739 } else if (EndsWithSurrogate(*state) && edge_surrogate) {
4740 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4742 if (EndsWithSurrogate(leaf_state)) {
4743 *state |= kEndsWithLeadingSurrogate;
4745 *state &= ~kEndsWithLeadingSurrogate;
4749 static inline void MergeLeafRight(int* length,
4751 uint8_t leaf_state) {
4752 bool edge_surrogate = EndsWithSurrogate(leaf_state);
4753 if (!(*state & kRightmostEdgeIsCalculated)) {
4754 DCHECK(!(*state & kRightmostEdgeIsSurrogate));
4755 *state |= (kRightmostEdgeIsCalculated
4756 | (edge_surrogate ? kRightmostEdgeIsSurrogate : 0));
4757 } else if (edge_surrogate && StartsWithSurrogate(*state)) {
4758 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4760 if (StartsWithSurrogate(leaf_state)) {
4761 *state |= kStartsWithTrailingSurrogate;
4763 *state &= ~kStartsWithTrailingSurrogate;
4767 static inline void MergeTerminal(int* length,
4769 uint8_t* state_out) {
4770 DCHECK((state & kLeftmostEdgeIsCalculated) &&
4771 (state & kRightmostEdgeIsCalculated));
4772 if (EndsWithSurrogate(state) && StartsWithSurrogate(state)) {
4773 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
4775 *state_out = kInitialState |
4776 (state & kLeftmostEdgeIsSurrogate ? kStartsWithTrailingSurrogate : 0) |
4777 (state & kRightmostEdgeIsSurrogate ? kEndsWithLeadingSurrogate : 0);
4780 static int Calculate(i::ConsString* current, uint8_t* state_out) {
4781 using namespace internal;
4782 int total_length = 0;
4783 uint8_t state = kInitialState;
4785 i::String* left = current->first();
4786 i::String* right = current->second();
4787 uint8_t right_leaf_state;
4788 uint8_t left_leaf_state;
4790 ConsString* left_as_cons =
4791 Visitor::VisitFlat(left, &leaf_length, &left_leaf_state);
4792 if (left_as_cons == NULL) {
4793 total_length += leaf_length;
4794 MergeLeafLeft(&total_length, &state, left_leaf_state);
4796 ConsString* right_as_cons =
4797 Visitor::VisitFlat(right, &leaf_length, &right_leaf_state);
4798 if (right_as_cons == NULL) {
4799 total_length += leaf_length;
4800 MergeLeafRight(&total_length, &state, right_leaf_state);
4801 if (left_as_cons != NULL) {
4802 // 1 Leaf node. Descend in place.
4803 current = left_as_cons;
4807 MergeTerminal(&total_length, state, state_out);
4808 return total_length;
4810 } else if (left_as_cons == NULL) {
4811 // 1 Leaf node. Descend in place.
4812 current = right_as_cons;
4815 // Both strings are ConsStrings.
4816 // Recurse on smallest.
4817 if (left->length() < right->length()) {
4818 total_length += Calculate(left_as_cons, &left_leaf_state);
4819 MergeLeafLeft(&total_length, &state, left_leaf_state);
4820 current = right_as_cons;
4822 total_length += Calculate(right_as_cons, &right_leaf_state);
4823 MergeLeafRight(&total_length, &state, right_leaf_state);
4824 current = left_as_cons;
4831 static inline int Calculate(i::ConsString* current) {
4832 uint8_t state = kInitialState;
4833 return Calculate(current, &state);
4837 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8LengthHelper);
4841 static int Utf8Length(i::String* str, i::Isolate* isolate) {
4842 int length = str->length();
4843 if (length == 0) return 0;
4845 i::ConsString* cons_string =
4846 Utf8LengthHelper::Visitor::VisitFlat(str, &length, &state);
4847 if (cons_string == NULL) return length;
4848 return Utf8LengthHelper::Calculate(cons_string);
4852 int String::Utf8Length() const {
4853 i::Handle<i::String> str = Utils::OpenHandle(this);
4854 i::Isolate* isolate = str->GetIsolate();
4855 return v8::Utf8Length(*str, isolate);
4859 class Utf8WriterVisitor {
4864 bool skip_capacity_check,
4865 bool replace_invalid_utf8)
4866 : early_termination_(false),
4867 last_character_(unibrow::Utf16::kNoPreviousCharacter),
4870 capacity_(capacity),
4871 skip_capacity_check_(capacity == -1 || skip_capacity_check),
4872 replace_invalid_utf8_(replace_invalid_utf8),
4873 utf16_chars_read_(0) {
4876 static int WriteEndCharacter(uint16_t character,
4880 bool replace_invalid_utf8) {
4881 using namespace unibrow;
4882 DCHECK(remaining > 0);
4883 // We can't use a local buffer here because Encode needs to modify
4884 // previous characters in the stream. We know, however, that
4885 // exactly one character will be advanced.
4886 if (Utf16::IsSurrogatePair(last_character, character)) {
4887 int written = Utf8::Encode(buffer,
4890 replace_invalid_utf8);
4891 DCHECK(written == 1);
4894 // Use a scratch buffer to check the required characters.
4895 char temp_buffer[Utf8::kMaxEncodedSize];
4896 // Can't encode using last_character as gcc has array bounds issues.
4897 int written = Utf8::Encode(temp_buffer,
4899 Utf16::kNoPreviousCharacter,
4900 replace_invalid_utf8);
4902 if (written > remaining) return 0;
4903 // Copy over the character from temp_buffer.
4904 for (int j = 0; j < written; j++) {
4905 buffer[j] = temp_buffer[j];
4910 // Visit writes out a group of code units (chars) of a v8::String to the
4911 // internal buffer_. This is done in two phases. The first phase calculates a
4912 // pesimistic estimate (writable_length) on how many code units can be safely
4913 // written without exceeding the buffer capacity and without writing the last
4914 // code unit (it could be a lead surrogate). The estimated number of code
4915 // units is then written out in one go, and the reported byte usage is used
4916 // to correct the estimate. This is repeated until the estimate becomes <= 0
4917 // or all code units have been written out. The second phase writes out code
4918 // units until the buffer capacity is reached, would be exceeded by the next
4919 // unit, or all units have been written out.
4920 template<typename Char>
4921 void Visit(const Char* chars, const int length) {
4922 using namespace unibrow;
4923 DCHECK(!early_termination_);
4924 if (length == 0) return;
4925 // Copy state to stack.
4926 char* buffer = buffer_;
4927 int last_character =
4928 sizeof(Char) == 1 ? Utf16::kNoPreviousCharacter : last_character_;
4930 // Do a fast loop where there is no exit capacity check.
4933 if (skip_capacity_check_) {
4934 fast_length = length;
4936 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4937 // Need enough space to write everything but one character.
4938 STATIC_ASSERT(Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 3);
4939 int max_size_per_char = sizeof(Char) == 1 ? 2 : 3;
4940 int writable_length =
4941 (remaining_capacity - max_size_per_char)/max_size_per_char;
4942 // Need to drop into slow loop.
4943 if (writable_length <= 0) break;
4944 fast_length = i + writable_length;
4945 if (fast_length > length) fast_length = length;
4947 // Write the characters to the stream.
4948 if (sizeof(Char) == 1) {
4949 for (; i < fast_length; i++) {
4951 Utf8::EncodeOneByte(buffer, static_cast<uint8_t>(*chars++));
4952 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4955 for (; i < fast_length; i++) {
4956 uint16_t character = *chars++;
4957 buffer += Utf8::Encode(buffer,
4960 replace_invalid_utf8_);
4961 last_character = character;
4962 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
4965 // Array is fully written. Exit.
4966 if (fast_length == length) {
4967 // Write state back out to object.
4968 last_character_ = last_character;
4970 utf16_chars_read_ += length;
4974 DCHECK(!skip_capacity_check_);
4975 // Slow loop. Must check capacity on each iteration.
4976 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
4977 DCHECK(remaining_capacity >= 0);
4978 for (; i < length && remaining_capacity > 0; i++) {
4979 uint16_t character = *chars++;
4980 // remaining_capacity is <= 3 bytes at this point, so we do not write out
4981 // an umatched lead surrogate.
4982 if (replace_invalid_utf8_ && Utf16::IsLeadSurrogate(character)) {
4983 early_termination_ = true;
4986 int written = WriteEndCharacter(character,
4990 replace_invalid_utf8_);
4992 early_termination_ = true;
4996 remaining_capacity -= written;
4997 last_character = character;
4999 // Write state back out to object.
5000 last_character_ = last_character;
5002 utf16_chars_read_ += i;
5005 inline bool IsDone() {
5006 return early_termination_;
5009 inline void VisitOneByteString(const uint8_t* chars, int length) {
5010 Visit(chars, length);
5013 inline void VisitTwoByteString(const uint16_t* chars, int length) {
5014 Visit(chars, length);
5017 int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
5018 // Write out number of utf16 characters written to the stream.
5019 if (utf16_chars_read_out != NULL) {
5020 *utf16_chars_read_out = utf16_chars_read_;
5022 // Only null terminate if all of the string was written and there's space.
5024 !early_termination_ &&
5025 (capacity_ == -1 || (buffer_ - start_) < capacity_)) {
5028 return static_cast<int>(buffer_ - start_);
5032 bool early_termination_;
5033 int last_character_;
5037 bool const skip_capacity_check_;
5038 bool const replace_invalid_utf8_;
5039 int utf16_chars_read_;
5040 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
5044 static bool RecursivelySerializeToUtf8(i::String* current,
5045 Utf8WriterVisitor* writer,
5046 int recursion_budget) {
5047 while (!writer->IsDone()) {
5048 i::ConsString* cons_string = i::String::VisitFlat(writer, current);
5049 if (cons_string == NULL) return true; // Leaf node.
5050 if (recursion_budget <= 0) return false;
5051 // Must write the left branch first.
5052 i::String* first = cons_string->first();
5053 bool success = RecursivelySerializeToUtf8(first,
5055 recursion_budget - 1);
5056 if (!success) return false;
5057 // Inline tail recurse for right branch.
5058 current = cons_string->second();
5064 int String::WriteUtf8(char* buffer,
5067 int options) const {
5068 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
5069 LOG_API(isolate, "String::WriteUtf8");
5071 i::Handle<i::String> str = Utils::OpenHandle(this);
5072 if (options & HINT_MANY_WRITES_EXPECTED) {
5073 str = i::String::Flatten(str); // Flatten the string for efficiency.
5075 const int string_length = str->length();
5076 bool write_null = !(options & NO_NULL_TERMINATION);
5077 bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
5078 int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
5079 // First check if we can just write the string without checking capacity.
5080 if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
5081 Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
5082 const int kMaxRecursion = 100;
5083 bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
5084 if (success) return writer.CompleteWrite(write_null, nchars_ref);
5085 } else if (capacity >= string_length) {
5086 // First check that the buffer is large enough.
5087 int utf8_bytes = v8::Utf8Length(*str, str->GetIsolate());
5088 if (utf8_bytes <= capacity) {
5089 // one-byte fast path.
5090 if (utf8_bytes == string_length) {
5091 WriteOneByte(reinterpret_cast<uint8_t*>(buffer), 0, capacity, options);
5092 if (nchars_ref != NULL) *nchars_ref = string_length;
5093 if (write_null && (utf8_bytes+1 <= capacity)) {
5094 return string_length + 1;
5096 return string_length;
5098 if (write_null && (utf8_bytes+1 > capacity)) {
5099 options |= NO_NULL_TERMINATION;
5101 // Recurse once without a capacity limit.
5102 // This will get into the first branch above.
5103 // TODO(dcarney) Check max left rec. in Utf8Length and fall through.
5104 return WriteUtf8(buffer, -1, nchars_ref, options);
5107 // Recursive slow path can potentially be unreasonable slow. Flatten.
5108 str = i::String::Flatten(str);
5109 Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
5110 i::String::VisitFlat(&writer, *str);
5111 return writer.CompleteWrite(write_null, nchars_ref);
5115 template<typename CharType>
5116 static inline int WriteHelper(const String* string,
5121 i::Isolate* isolate = Utils::OpenHandle(string)->GetIsolate();
5122 LOG_API(isolate, "String::Write");
5124 DCHECK(start >= 0 && length >= -1);
5125 i::Handle<i::String> str = Utils::OpenHandle(string);
5126 isolate->string_tracker()->RecordWrite(str);
5127 if (options & String::HINT_MANY_WRITES_EXPECTED) {
5128 // Flatten the string for efficiency. This applies whether we are
5129 // using StringCharacterStream or Get(i) to access the characters.
5130 str = i::String::Flatten(str);
5132 int end = start + length;
5133 if ((length == -1) || (length > str->length() - start) )
5134 end = str->length();
5135 if (end < 0) return 0;
5136 i::String::WriteToFlat(*str, buffer, start, end);
5137 if (!(options & String::NO_NULL_TERMINATION) &&
5138 (length == -1 || end - start < length)) {
5139 buffer[end - start] = '\0';
5145 int String::WriteOneByte(uint8_t* buffer,
5148 int options) const {
5149 return WriteHelper(this, buffer, start, length, options);
5153 int String::Write(uint16_t* buffer,
5156 int options) const {
5157 return WriteHelper(this, buffer, start, length, options);
5161 bool v8::String::IsExternal() const {
5162 i::Handle<i::String> str = Utils::OpenHandle(this);
5163 return i::StringShape(*str).IsExternalTwoByte();
5167 bool v8::String::IsExternalOneByte() const {
5168 i::Handle<i::String> str = Utils::OpenHandle(this);
5169 return i::StringShape(*str).IsExternalOneByte();
5173 void v8::String::VerifyExternalStringResource(
5174 v8::String::ExternalStringResource* value) const {
5175 i::Handle<i::String> str = Utils::OpenHandle(this);
5176 const v8::String::ExternalStringResource* expected;
5177 if (i::StringShape(*str).IsExternalTwoByte()) {
5178 const void* resource =
5179 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5180 expected = reinterpret_cast<const ExternalStringResource*>(resource);
5184 CHECK_EQ(expected, value);
5187 void v8::String::VerifyExternalStringResourceBase(
5188 v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
5189 i::Handle<i::String> str = Utils::OpenHandle(this);
5190 const v8::String::ExternalStringResourceBase* expected;
5191 Encoding expectedEncoding;
5192 if (i::StringShape(*str).IsExternalOneByte()) {
5193 const void* resource =
5194 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5195 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5196 expectedEncoding = ONE_BYTE_ENCODING;
5197 } else if (i::StringShape(*str).IsExternalTwoByte()) {
5198 const void* resource =
5199 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
5200 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
5201 expectedEncoding = TWO_BYTE_ENCODING;
5205 str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
5207 CHECK_EQ(expected, value);
5208 CHECK_EQ(expectedEncoding, encoding);
5211 const v8::String::ExternalOneByteStringResource*
5212 v8::String::GetExternalOneByteStringResource() const {
5213 i::Handle<i::String> str = Utils::OpenHandle(this);
5214 if (i::StringShape(*str).IsExternalOneByte()) {
5215 const void* resource =
5216 i::Handle<i::ExternalOneByteString>::cast(str)->resource();
5217 return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
5224 Local<Value> Symbol::Name() const {
5225 i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
5226 i::Handle<i::Object> name(sym->name(), sym->GetIsolate());
5227 return Utils::ToLocal(name);
5231 double Number::Value() const {
5232 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5233 return obj->Number();
5237 bool Boolean::Value() const {
5238 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5239 return obj->IsTrue();
5243 int64_t Integer::Value() const {
5244 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5246 return i::Smi::cast(*obj)->value();
5248 return static_cast<int64_t>(obj->Number());
5253 int32_t Int32::Value() const {
5254 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5256 return i::Smi::cast(*obj)->value();
5258 return static_cast<int32_t>(obj->Number());
5263 uint32_t Uint32::Value() const {
5264 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5266 return i::Smi::cast(*obj)->value();
5268 return static_cast<uint32_t>(obj->Number());
5273 int v8::Object::InternalFieldCount() {
5274 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5275 return obj->GetInternalFieldCount();
5279 static bool InternalFieldOK(i::Handle<i::JSObject> obj,
5281 const char* location) {
5282 return Utils::ApiCheck(index < obj->GetInternalFieldCount(),
5284 "Internal field out of bounds");
5288 Local<Value> v8::Object::SlowGetInternalField(int index) {
5289 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5290 const char* location = "v8::Object::GetInternalField()";
5291 if (!InternalFieldOK(obj, index, location)) return Local<Value>();
5292 i::Handle<i::Object> value(obj->GetInternalField(index), obj->GetIsolate());
5293 return Utils::ToLocal(value);
5297 void v8::Object::SetInternalField(int index, v8::Local<Value> value) {
5298 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5299 const char* location = "v8::Object::SetInternalField()";
5300 if (!InternalFieldOK(obj, index, location)) return;
5301 i::Handle<i::Object> val = Utils::OpenHandle(*value);
5302 obj->SetInternalField(index, *val);
5306 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
5307 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5308 const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
5309 if (!InternalFieldOK(obj, index, location)) return NULL;
5310 return DecodeSmiToAligned(obj->GetInternalField(index), location);
5314 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
5315 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
5316 const char* location = "v8::Object::SetAlignedPointerInInternalField()";
5317 if (!InternalFieldOK(obj, index, location)) return;
5318 obj->SetInternalField(index, EncodeAlignedAsSmi(value, location));
5319 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
5323 static void* ExternalValue(i::Object* obj) {
5324 // Obscure semantics for undefined, but somehow checked in our unit tests...
5325 if (obj->IsUndefined()) return NULL;
5326 i::Object* foreign = i::JSObject::cast(obj)->GetInternalField(0);
5327 return i::Foreign::cast(foreign)->foreign_address();
5331 // --- E n v i r o n m e n t ---
5334 void v8::V8::InitializePlatform(Platform* platform) {
5335 i::V8::InitializePlatform(platform);
5339 void v8::V8::ShutdownPlatform() {
5340 i::V8::ShutdownPlatform();
5344 bool v8::V8::Initialize() {
5345 i::V8::Initialize();
5346 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5353 void v8::V8::SetEntropySource(EntropySource entropy_source) {
5354 base::RandomNumberGenerator::SetEntropySource(entropy_source);
5358 void v8::V8::SetReturnAddressLocationResolver(
5359 ReturnAddressLocationResolver return_address_resolver) {
5360 i::V8::SetReturnAddressLocationResolver(return_address_resolver);
5363 void v8::V8::SetArrayBufferAllocator(
5364 ArrayBuffer::Allocator* allocator) {
5365 if (!Utils::ApiCheck(i::V8::ArrayBufferAllocator() == NULL,
5366 "v8::V8::SetArrayBufferAllocator",
5367 "ArrayBufferAllocator might only be set once"))
5369 i::V8::SetArrayBufferAllocator(allocator);
5373 bool v8::V8::Dispose() {
5375 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
5376 i::DisposeNatives();
5382 HeapStatistics::HeapStatistics(): total_heap_size_(0),
5383 total_heap_size_executable_(0),
5384 total_physical_size_(0),
5386 heap_size_limit_(0) { }
5389 HeapSpaceStatistics::HeapSpaceStatistics(): space_name_(0),
5391 space_used_size_(0),
5392 space_available_size_(0),
5393 physical_space_size_(0) { }
5396 HeapObjectStatistics::HeapObjectStatistics()
5397 : object_type_(nullptr),
5398 object_sub_type_(nullptr),
5403 bool v8::V8::InitializeICU(const char* icu_data_file) {
5404 return i::InitializeICU(icu_data_file);
5408 void v8::V8::InitializeExternalStartupData(const char* directory_path) {
5409 i::InitializeExternalStartupData(directory_path);
5413 void v8::V8::InitializeExternalStartupData(const char* natives_blob,
5414 const char* snapshot_blob) {
5415 i::InitializeExternalStartupData(natives_blob, snapshot_blob);
5419 const char* v8::V8::GetVersion() {
5420 return i::Version::GetVersion();
5424 static i::Handle<i::Context> CreateEnvironment(
5425 i::Isolate* isolate, v8::ExtensionConfiguration* extensions,
5426 v8::Local<ObjectTemplate> global_template,
5427 v8::Local<Value> maybe_global_proxy) {
5428 i::Handle<i::Context> env;
5430 // Enter V8 via an ENTER_V8 scope.
5433 v8::Local<ObjectTemplate> proxy_template = global_template;
5434 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
5435 i::Handle<i::FunctionTemplateInfo> global_constructor;
5437 if (!global_template.IsEmpty()) {
5438 // Make sure that the global_template has a constructor.
5439 global_constructor = EnsureConstructor(isolate, *global_template);
5441 // Create a fresh template for the global proxy object.
5442 proxy_template = ObjectTemplate::New(
5443 reinterpret_cast<v8::Isolate*>(isolate));
5444 proxy_constructor = EnsureConstructor(isolate, *proxy_template);
5446 // Set the global template to be the prototype template of
5447 // global proxy template.
5448 proxy_constructor->set_prototype_template(
5449 *Utils::OpenHandle(*global_template));
5451 // Migrate security handlers from global_template to
5452 // proxy_template. Temporarily removing access check
5453 // information from the global template.
5454 if (!global_constructor->access_check_info()->IsUndefined()) {
5455 proxy_constructor->set_access_check_info(
5456 global_constructor->access_check_info());
5457 proxy_constructor->set_needs_access_check(
5458 global_constructor->needs_access_check());
5459 global_constructor->set_needs_access_check(false);
5460 global_constructor->set_access_check_info(
5461 isolate->heap()->undefined_value());
5465 i::Handle<i::Object> proxy = Utils::OpenHandle(*maybe_global_proxy, true);
5466 i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
5467 if (!proxy.is_null()) {
5468 maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(proxy);
5470 // Create the environment.
5471 env = isolate->bootstrapper()->CreateEnvironment(
5472 maybe_proxy, proxy_template, extensions);
5474 // Restore the access check info on the global template.
5475 if (!global_template.IsEmpty()) {
5476 DCHECK(!global_constructor.is_null());
5477 DCHECK(!proxy_constructor.is_null());
5478 global_constructor->set_access_check_info(
5479 proxy_constructor->access_check_info());
5480 global_constructor->set_needs_access_check(
5481 proxy_constructor->needs_access_check());
5489 Local<Context> v8::Context::New(v8::Isolate* external_isolate,
5490 v8::ExtensionConfiguration* extensions,
5491 v8::Local<ObjectTemplate> global_template,
5492 v8::Local<Value> global_object) {
5493 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
5494 LOG_API(isolate, "Context::New");
5495 i::HandleScope scope(isolate);
5496 ExtensionConfiguration no_extensions;
5497 if (extensions == NULL) extensions = &no_extensions;
5498 i::Handle<i::Context> env =
5499 CreateEnvironment(isolate, extensions, global_template, global_object);
5500 if (env.is_null()) {
5501 if (isolate->has_pending_exception()) {
5502 isolate->OptionalRescheduleException(true);
5504 return Local<Context>();
5506 return Utils::ToLocal(scope.CloseAndEscape(env));
5510 void v8::Context::SetSecurityToken(Local<Value> token) {
5511 i::Handle<i::Context> env = Utils::OpenHandle(this);
5512 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
5513 env->set_security_token(*token_handle);
5517 void v8::Context::UseDefaultSecurityToken() {
5518 i::Handle<i::Context> env = Utils::OpenHandle(this);
5519 env->set_security_token(env->global_object());
5523 Local<Value> v8::Context::GetSecurityToken() {
5524 i::Handle<i::Context> env = Utils::OpenHandle(this);
5525 i::Isolate* isolate = env->GetIsolate();
5526 i::Object* security_token = env->security_token();
5527 i::Handle<i::Object> token_handle(security_token, isolate);
5528 return Utils::ToLocal(token_handle);
5532 v8::Isolate* Context::GetIsolate() {
5533 i::Handle<i::Context> env = Utils::OpenHandle(this);
5534 return reinterpret_cast<Isolate*>(env->GetIsolate());
5538 v8::Local<v8::Object> Context::Global() {
5539 i::Handle<i::Context> context = Utils::OpenHandle(this);
5540 i::Isolate* isolate = context->GetIsolate();
5541 i::Handle<i::Object> global(context->global_proxy(), isolate);
5542 // TODO(dcarney): This should always return the global proxy
5543 // but can't presently as calls to GetProtoype will return the wrong result.
5544 if (i::Handle<i::JSGlobalProxy>::cast(
5545 global)->IsDetachedFrom(context->global_object())) {
5546 global = i::Handle<i::Object>(context->global_object(), isolate);
5548 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
5552 void Context::DetachGlobal() {
5553 i::Handle<i::Context> context = Utils::OpenHandle(this);
5554 i::Isolate* isolate = context->GetIsolate();
5556 isolate->bootstrapper()->DetachGlobal(context);
5560 Local<v8::Object> Context::GetExtrasExportsObject() {
5561 i::Handle<i::Context> context = Utils::OpenHandle(this);
5562 i::Isolate* isolate = context->GetIsolate();
5563 i::Handle<i::JSObject> exports(context->extras_exports_object(), isolate);
5564 return Utils::ToLocal(exports);
5568 void Context::AllowCodeGenerationFromStrings(bool allow) {
5569 i::Handle<i::Context> context = Utils::OpenHandle(this);
5570 i::Isolate* isolate = context->GetIsolate();
5572 context->set_allow_code_gen_from_strings(
5573 allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
5577 bool Context::IsCodeGenerationFromStringsAllowed() {
5578 i::Handle<i::Context> context = Utils::OpenHandle(this);
5579 return !context->allow_code_gen_from_strings()->IsFalse();
5583 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) {
5584 i::Handle<i::Context> context = Utils::OpenHandle(this);
5585 i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
5586 context->set_error_message_for_code_gen_from_strings(*error_handle);
5590 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) {
5591 PREPARE_FOR_EXECUTION(context, "v8::ObjectTemplate::NewInstance()", Object);
5592 auto self = Utils::OpenHandle(this);
5593 Local<Object> result;
5594 has_pending_exception =
5595 !ToLocal<Object>(i::ApiNatives::InstantiateObject(self), &result);
5596 RETURN_ON_FAILED_EXECUTION(Object);
5597 RETURN_ESCAPED(result);
5601 Local<v8::Object> ObjectTemplate::NewInstance() {
5602 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5603 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object);
5607 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) {
5608 PREPARE_FOR_EXECUTION(context, "v8::FunctionTemplate::GetFunction()",
5610 auto self = Utils::OpenHandle(this);
5611 Local<Function> result;
5612 has_pending_exception =
5613 !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result);
5614 RETURN_ON_FAILED_EXECUTION(Function);
5615 RETURN_ESCAPED(result);
5619 Local<v8::Function> FunctionTemplate::GetFunction() {
5620 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
5621 RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function);
5625 bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) {
5626 auto self = Utils::OpenHandle(this);
5627 auto obj = Utils::OpenHandle(*value);
5628 return self->IsTemplateFor(*obj);
5632 Local<External> v8::External::New(Isolate* isolate, void* value) {
5633 STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
5634 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5635 LOG_API(i_isolate, "External::New");
5636 ENTER_V8(i_isolate);
5637 i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
5638 return Utils::ExternalToLocal(external);
5642 void* External::Value() const {
5643 return ExternalValue(*Utils::OpenHandle(this));
5647 // anonymous namespace for string creation helper functions
5650 inline int StringLength(const char* string) {
5651 return i::StrLength(string);
5655 inline int StringLength(const uint8_t* string) {
5656 return i::StrLength(reinterpret_cast<const char*>(string));
5660 inline int StringLength(const uint16_t* string) {
5662 while (string[length] != '\0')
5669 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5670 v8::NewStringType type,
5671 i::Vector<const char> string) {
5672 if (type == v8::NewStringType::kInternalized) {
5673 return factory->InternalizeUtf8String(string);
5675 return factory->NewStringFromUtf8(string);
5680 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5681 v8::NewStringType type,
5682 i::Vector<const uint8_t> string) {
5683 if (type == v8::NewStringType::kInternalized) {
5684 return factory->InternalizeOneByteString(string);
5686 return factory->NewStringFromOneByte(string);
5691 inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
5692 v8::NewStringType type,
5693 i::Vector<const uint16_t> string) {
5694 if (type == v8::NewStringType::kInternalized) {
5695 return factory->InternalizeTwoByteString(string);
5697 return factory->NewStringFromTwoByte(string);
5701 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength);
5704 template <typename Char>
5705 inline MaybeLocal<String> NewString(Isolate* v8_isolate, const char* location,
5706 const char* env, const Char* data,
5707 v8::NewStringType type, int length) {
5708 i::Isolate* isolate = reinterpret_cast<internal::Isolate*>(v8_isolate);
5709 if (length == 0) return String::Empty(v8_isolate);
5710 // TODO(dcarney): throw a context free exception.
5711 if (length > i::String::kMaxLength) return MaybeLocal<String>();
5713 LOG_API(isolate, env);
5714 if (length < 0) length = StringLength(data);
5715 i::Handle<i::String> result =
5716 NewString(isolate->factory(), type, i::Vector<const Char>(data, length))
5718 return Utils::ToLocal(result);
5721 } // anonymous namespace
5724 Local<String> String::NewFromUtf8(Isolate* isolate,
5728 RETURN_TO_LOCAL_UNCHECKED(
5729 NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5730 data, static_cast<v8::NewStringType>(type), length),
5735 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data,
5736 v8::NewStringType type, int length) {
5737 return NewString(isolate, "v8::String::NewFromUtf8()", "String::NewFromUtf8",
5738 data, type, length);
5742 Local<String> String::NewFromOneByte(Isolate* isolate,
5743 const uint8_t* data,
5746 RETURN_TO_LOCAL_UNCHECKED(
5747 NewString(isolate, "v8::String::NewFromOneByte()",
5748 "String::NewFromOneByte", data,
5749 static_cast<v8::NewStringType>(type), length),
5754 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data,
5755 v8::NewStringType type, int length) {
5756 return NewString(isolate, "v8::String::NewFromOneByte()",
5757 "String::NewFromOneByte", data, type, length);
5761 Local<String> String::NewFromTwoByte(Isolate* isolate,
5762 const uint16_t* data,
5765 RETURN_TO_LOCAL_UNCHECKED(
5766 NewString(isolate, "v8::String::NewFromTwoByte()",
5767 "String::NewFromTwoByte", data,
5768 static_cast<v8::NewStringType>(type), length),
5773 MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate,
5774 const uint16_t* data,
5775 v8::NewStringType type, int length) {
5776 return NewString(isolate, "v8::String::NewFromTwoByte()",
5777 "String::NewFromTwoByte", data, type, length);
5781 Local<String> v8::String::Concat(Local<String> left, Local<String> right) {
5782 i::Handle<i::String> left_string = Utils::OpenHandle(*left);
5783 i::Isolate* isolate = left_string->GetIsolate();
5785 LOG_API(isolate, "v8::String::Concat");
5786 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
5787 // If we are steering towards a range error, do not wait for the error to be
5788 // thrown, and return the null handle instead.
5789 if (left_string->length() + right_string->length() > i::String::kMaxLength) {
5790 return Local<String>();
5792 i::Handle<i::String> result = isolate->factory()->NewConsString(
5793 left_string, right_string).ToHandleChecked();
5794 return Utils::ToLocal(result);
5798 MaybeLocal<String> v8::String::NewExternalTwoByte(
5799 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5800 CHECK(resource && resource->data());
5801 // TODO(dcarney): throw a context free exception.
5802 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5803 return MaybeLocal<String>();
5805 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5806 ENTER_V8(i_isolate);
5807 LOG_API(i_isolate, "String::NewExternalTwoByte");
5808 i::Handle<i::String> string = i_isolate->factory()
5809 ->NewExternalStringFromTwoByte(resource)
5811 i_isolate->heap()->external_string_table()->AddString(*string);
5812 return Utils::ToLocal(string);
5816 Local<String> v8::String::NewExternal(
5817 Isolate* isolate, v8::String::ExternalStringResource* resource) {
5818 RETURN_TO_LOCAL_UNCHECKED(NewExternalTwoByte(isolate, resource), String);
5822 MaybeLocal<String> v8::String::NewExternalOneByte(
5823 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5824 CHECK(resource && resource->data());
5825 // TODO(dcarney): throw a context free exception.
5826 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
5827 return MaybeLocal<String>();
5829 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5830 ENTER_V8(i_isolate);
5831 LOG_API(i_isolate, "String::NewExternalOneByte");
5832 i::Handle<i::String> string = i_isolate->factory()
5833 ->NewExternalStringFromOneByte(resource)
5835 i_isolate->heap()->external_string_table()->AddString(*string);
5836 return Utils::ToLocal(string);
5840 Local<String> v8::String::NewExternal(
5841 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
5842 RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String);
5846 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
5847 i::Handle<i::String> obj = Utils::OpenHandle(this);
5848 i::Isolate* isolate = obj->GetIsolate();
5849 if (i::StringShape(*obj).IsExternal()) {
5850 return false; // Already an external string.
5853 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
5856 if (isolate->heap()->IsInGCPostProcessing()) {
5859 CHECK(resource && resource->data());
5861 bool result = obj->MakeExternal(resource);
5862 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5863 DCHECK(!CanMakeExternal() || result);
5865 DCHECK(obj->IsExternalString());
5866 isolate->heap()->external_string_table()->AddString(*obj);
5872 bool v8::String::MakeExternal(
5873 v8::String::ExternalOneByteStringResource* resource) {
5874 i::Handle<i::String> obj = Utils::OpenHandle(this);
5875 i::Isolate* isolate = obj->GetIsolate();
5876 if (i::StringShape(*obj).IsExternal()) {
5877 return false; // Already an external string.
5880 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
5883 if (isolate->heap()->IsInGCPostProcessing()) {
5886 CHECK(resource && resource->data());
5888 bool result = obj->MakeExternal(resource);
5889 // Assert that if CanMakeExternal(), then externalizing actually succeeds.
5890 DCHECK(!CanMakeExternal() || result);
5892 DCHECK(obj->IsExternalString());
5893 isolate->heap()->external_string_table()->AddString(*obj);
5899 bool v8::String::CanMakeExternal() {
5900 i::Handle<i::String> obj = Utils::OpenHandle(this);
5901 i::Isolate* isolate = obj->GetIsolate();
5903 if (isolate->string_tracker()->IsFreshUnusedString(obj)) return false;
5904 int size = obj->Size(); // Byte size of the original string.
5905 if (size < i::ExternalString::kShortSize) return false;
5906 i::StringShape shape(*obj);
5907 return !shape.IsExternal();
5911 Isolate* v8::Object::GetIsolate() {
5912 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
5913 return reinterpret_cast<Isolate*>(i_isolate);
5917 Local<v8::Object> v8::Object::New(Isolate* isolate) {
5918 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5919 LOG_API(i_isolate, "Object::New");
5920 ENTER_V8(i_isolate);
5921 i::Handle<i::JSObject> obj =
5922 i_isolate->factory()->NewJSObject(i_isolate->object_function());
5923 return Utils::ToLocal(obj);
5927 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
5928 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5929 LOG_API(i_isolate, "NumberObject::New");
5930 ENTER_V8(i_isolate);
5931 i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
5932 i::Handle<i::Object> obj =
5933 i::Object::ToObject(i_isolate, number).ToHandleChecked();
5934 return Utils::ToLocal(obj);
5938 double v8::NumberObject::ValueOf() const {
5939 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5940 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5941 i::Isolate* isolate = jsvalue->GetIsolate();
5942 LOG_API(isolate, "NumberObject::NumberValue");
5943 return jsvalue->value()->Number();
5947 Local<v8::Value> v8::BooleanObject::New(bool value) {
5948 i::Isolate* isolate = i::Isolate::Current();
5949 LOG_API(isolate, "BooleanObject::New");
5951 i::Handle<i::Object> boolean(value
5952 ? isolate->heap()->true_value()
5953 : isolate->heap()->false_value(),
5955 i::Handle<i::Object> obj =
5956 i::Object::ToObject(isolate, boolean).ToHandleChecked();
5957 return Utils::ToLocal(obj);
5961 bool v8::BooleanObject::ValueOf() const {
5962 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5963 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5964 i::Isolate* isolate = jsvalue->GetIsolate();
5965 LOG_API(isolate, "BooleanObject::BooleanValue");
5966 return jsvalue->value()->IsTrue();
5970 Local<v8::Value> v8::StringObject::New(Local<String> value) {
5971 i::Handle<i::String> string = Utils::OpenHandle(*value);
5972 i::Isolate* isolate = string->GetIsolate();
5973 LOG_API(isolate, "StringObject::New");
5975 i::Handle<i::Object> obj =
5976 i::Object::ToObject(isolate, string).ToHandleChecked();
5977 return Utils::ToLocal(obj);
5981 Local<v8::String> v8::StringObject::ValueOf() const {
5982 i::Handle<i::Object> obj = Utils::OpenHandle(this);
5983 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
5984 i::Isolate* isolate = jsvalue->GetIsolate();
5985 LOG_API(isolate, "StringObject::StringValue");
5986 return Utils::ToLocal(
5987 i::Handle<i::String>(i::String::cast(jsvalue->value())));
5991 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) {
5992 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5993 LOG_API(i_isolate, "SymbolObject::New");
5994 ENTER_V8(i_isolate);
5995 i::Handle<i::Object> obj = i::Object::ToObject(
5996 i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
5997 return Utils::ToLocal(obj);
6001 Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
6002 i::Handle<i::Object> obj = Utils::OpenHandle(this);
6003 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
6004 i::Isolate* isolate = jsvalue->GetIsolate();
6005 LOG_API(isolate, "SymbolObject::SymbolValue");
6006 return Utils::ToLocal(
6007 i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value())));
6011 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) {
6012 if (std::isnan(time)) {
6013 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6014 time = std::numeric_limits<double>::quiet_NaN();
6016 PREPARE_FOR_EXECUTION(context, "Date::New", Value);
6017 Local<Value> result;
6018 has_pending_exception =
6019 !ToLocal<Value>(i::Execution::NewDate(isolate, time), &result);
6020 RETURN_ON_FAILED_EXECUTION(Value);
6021 RETURN_ESCAPED(result);
6025 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
6026 auto context = isolate->GetCurrentContext();
6027 RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value);
6031 double v8::Date::ValueOf() const {
6032 i::Handle<i::Object> obj = Utils::OpenHandle(this);
6033 i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
6034 i::Isolate* isolate = jsdate->GetIsolate();
6035 LOG_API(isolate, "Date::NumberValue");
6036 return jsdate->value()->Number();
6040 void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) {
6041 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6042 LOG_API(i_isolate, "Date::DateTimeConfigurationChangeNotification");
6043 ENTER_V8(i_isolate);
6044 i_isolate->date_cache()->ResetDateCache();
6045 if (!i_isolate->eternal_handles()->Exists(
6046 i::EternalHandles::DATE_CACHE_VERSION)) {
6049 i::Handle<i::FixedArray> date_cache_version =
6050 i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton(
6051 i::EternalHandles::DATE_CACHE_VERSION));
6052 DCHECK_EQ(1, date_cache_version->length());
6053 CHECK(date_cache_version->get(0)->IsSmi());
6054 date_cache_version->set(
6056 i::Smi::FromInt(i::Smi::cast(date_cache_version->get(0))->value() + 1));
6060 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
6061 i::Isolate* isolate = i::Isolate::Current();
6062 uint8_t flags_buf[3];
6064 if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
6065 if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
6066 if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
6067 DCHECK(num_flags <= static_cast<int>(arraysize(flags_buf)));
6068 return isolate->factory()->InternalizeOneByteString(
6069 i::Vector<const uint8_t>(flags_buf, num_flags));
6073 MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context,
6074 Local<String> pattern, Flags flags) {
6075 PREPARE_FOR_EXECUTION(context, "RegExp::New", RegExp);
6076 Local<v8::RegExp> result;
6077 has_pending_exception =
6078 !ToLocal<RegExp>(i::Execution::NewJSRegExp(Utils::OpenHandle(*pattern),
6079 RegExpFlagsToString(flags)),
6081 RETURN_ON_FAILED_EXECUTION(RegExp);
6082 RETURN_ESCAPED(result);
6086 Local<v8::RegExp> v8::RegExp::New(Local<String> pattern, Flags flags) {
6088 reinterpret_cast<Isolate*>(Utils::OpenHandle(*pattern)->GetIsolate());
6089 auto context = isolate->GetCurrentContext();
6090 RETURN_TO_LOCAL_UNCHECKED(New(context, pattern, flags), RegExp);
6094 Local<v8::String> v8::RegExp::GetSource() const {
6095 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6096 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
6100 // Assert that the static flags cast in GetFlags is valid.
6101 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag) \
6102 STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) == \
6103 static_cast<int>(i::JSRegExp::internal_flag))
6104 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
6105 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
6106 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
6107 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
6108 #undef REGEXP_FLAG_ASSERT_EQ
6110 v8::RegExp::Flags v8::RegExp::GetFlags() const {
6111 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
6112 return static_cast<RegExp::Flags>(obj->GetFlags().value());
6116 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
6117 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6118 LOG_API(i_isolate, "Array::New");
6119 ENTER_V8(i_isolate);
6120 int real_length = length > 0 ? length : 0;
6121 i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
6122 i::Handle<i::Object> length_obj =
6123 i_isolate->factory()->NewNumberFromInt(real_length);
6124 obj->set_length(*length_obj);
6125 return Utils::ToLocal(obj);
6129 uint32_t v8::Array::Length() const {
6130 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
6131 i::Object* length = obj->length();
6132 if (length->IsSmi()) {
6133 return i::Smi::cast(length)->value();
6135 return static_cast<uint32_t>(length->Number());
6140 MaybeLocal<Object> Array::CloneElementAt(Local<Context> context,
6142 PREPARE_FOR_EXECUTION(context, "v8::Array::CloneElementAt()", Object);
6143 auto self = Utils::OpenHandle(this);
6144 if (!self->HasFastObjectElements()) return Local<Object>();
6145 i::FixedArray* elms = i::FixedArray::cast(self->elements());
6146 i::Object* paragon = elms->get(index);
6147 if (!paragon->IsJSObject()) return Local<Object>();
6148 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
6149 Local<Object> result;
6150 has_pending_exception =
6151 !ToLocal<Object>(isolate->factory()->CopyJSObject(paragon_handle),
6153 RETURN_ON_FAILED_EXECUTION(Object);
6154 RETURN_ESCAPED(result);
6158 Local<Object> Array::CloneElementAt(uint32_t index) {
6159 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6160 RETURN_TO_LOCAL_UNCHECKED(CloneElementAt(context, index), Object);
6164 Local<v8::Map> v8::Map::New(Isolate* isolate) {
6165 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6166 LOG_API(i_isolate, "Map::New");
6167 ENTER_V8(i_isolate);
6168 i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
6169 return Utils::ToLocal(obj);
6173 size_t v8::Map::Size() const {
6174 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6175 return i::OrderedHashMap::cast(obj->table())->NumberOfElements();
6180 auto self = Utils::OpenHandle(this);
6181 i::Isolate* isolate = self->GetIsolate();
6182 LOG_API(isolate, "Map::Clear");
6184 i::Runtime::JSMapClear(isolate, self);
6188 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) {
6189 PREPARE_FOR_EXECUTION(context, "Map::Get", Value);
6190 auto self = Utils::OpenHandle(this);
6191 Local<Value> result;
6192 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6193 has_pending_exception =
6194 !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self,
6195 arraysize(argv), argv, false),
6197 RETURN_ON_FAILED_EXECUTION(Value);
6198 RETURN_ESCAPED(result);
6202 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key,
6203 Local<Value> value) {
6204 PREPARE_FOR_EXECUTION(context, "Map::Set", Map);
6205 auto self = Utils::OpenHandle(this);
6206 i::Handle<i::Object> result;
6207 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key),
6208 Utils::OpenHandle(*value)};
6209 has_pending_exception =
6210 !i::Execution::Call(isolate, isolate->map_set(), self, arraysize(argv),
6211 argv, false).ToHandle(&result);
6212 RETURN_ON_FAILED_EXECUTION(Map);
6213 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6217 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) {
6218 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Has", bool);
6219 auto self = Utils::OpenHandle(this);
6220 i::Handle<i::Object> result;
6221 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6222 has_pending_exception =
6223 !i::Execution::Call(isolate, isolate->map_has(), self, arraysize(argv),
6224 argv, false).ToHandle(&result);
6225 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6226 return Just(result->IsTrue());
6230 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) {
6231 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Map::Delete", bool);
6232 auto self = Utils::OpenHandle(this);
6233 i::Handle<i::Object> result;
6234 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6235 has_pending_exception =
6236 !i::Execution::Call(isolate, isolate->map_delete(), self, arraysize(argv),
6237 argv, false).ToHandle(&result);
6238 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6239 return Just(result->IsTrue());
6243 Local<Array> Map::AsArray() const {
6244 i::Handle<i::JSMap> obj = Utils::OpenHandle(this);
6245 i::Isolate* isolate = obj->GetIsolate();
6246 i::Factory* factory = isolate->factory();
6247 LOG_API(isolate, "Map::AsArray");
6249 i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(obj->table()));
6250 int size = table->NumberOfElements();
6251 int length = size * 2;
6252 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6253 for (int i = 0; i < size; ++i) {
6254 if (table->KeyAt(i)->IsTheHole()) continue;
6255 result->set(i * 2, table->KeyAt(i));
6256 result->set(i * 2 + 1, table->ValueAt(i));
6258 i::Handle<i::JSArray> result_array =
6259 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6260 return Utils::ToLocal(result_array);
6264 MaybeLocal<Map> Map::FromArray(Local<Context> context, Local<Array> array) {
6265 PREPARE_FOR_EXECUTION(context, "Map::FromArray", Map);
6266 if (array->Length() % 2 != 0) {
6267 return MaybeLocal<Map>();
6269 i::Handle<i::Object> result;
6270 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6271 has_pending_exception =
6272 !i::Execution::Call(isolate, isolate->map_from_array(),
6273 isolate->factory()->undefined_value(),
6274 arraysize(argv), argv, false).ToHandle(&result);
6275 RETURN_ON_FAILED_EXECUTION(Map);
6276 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
6280 Local<v8::Set> v8::Set::New(Isolate* isolate) {
6281 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6282 LOG_API(i_isolate, "Set::New");
6283 ENTER_V8(i_isolate);
6284 i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
6285 return Utils::ToLocal(obj);
6289 size_t v8::Set::Size() const {
6290 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6291 return i::OrderedHashSet::cast(obj->table())->NumberOfElements();
6296 auto self = Utils::OpenHandle(this);
6297 i::Isolate* isolate = self->GetIsolate();
6298 LOG_API(isolate, "Set::Clear");
6300 i::Runtime::JSSetClear(isolate, self);
6304 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) {
6305 PREPARE_FOR_EXECUTION(context, "Set::Add", Set);
6306 auto self = Utils::OpenHandle(this);
6307 i::Handle<i::Object> result;
6308 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6309 has_pending_exception =
6310 !i::Execution::Call(isolate, isolate->set_add(), self, arraysize(argv),
6311 argv, false).ToHandle(&result);
6312 RETURN_ON_FAILED_EXECUTION(Set);
6313 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6317 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) {
6318 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Has", bool);
6319 auto self = Utils::OpenHandle(this);
6320 i::Handle<i::Object> result;
6321 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6322 has_pending_exception =
6323 !i::Execution::Call(isolate, isolate->set_has(), self, arraysize(argv),
6324 argv, false).ToHandle(&result);
6325 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6326 return Just(result->IsTrue());
6330 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) {
6331 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Set::Delete", bool);
6332 auto self = Utils::OpenHandle(this);
6333 i::Handle<i::Object> result;
6334 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)};
6335 has_pending_exception =
6336 !i::Execution::Call(isolate, isolate->set_delete(), self, arraysize(argv),
6337 argv, false).ToHandle(&result);
6338 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6339 return Just(result->IsTrue());
6343 Local<Array> Set::AsArray() const {
6344 i::Handle<i::JSSet> obj = Utils::OpenHandle(this);
6345 i::Isolate* isolate = obj->GetIsolate();
6346 i::Factory* factory = isolate->factory();
6347 LOG_API(isolate, "Set::AsArray");
6349 i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(obj->table()));
6350 int length = table->NumberOfElements();
6351 i::Handle<i::FixedArray> result = factory->NewFixedArray(length);
6352 for (int i = 0; i < length; ++i) {
6353 i::Object* key = table->KeyAt(i);
6354 if (!key->IsTheHole()) {
6355 result->set(i, key);
6358 i::Handle<i::JSArray> result_array =
6359 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length);
6360 return Utils::ToLocal(result_array);
6364 MaybeLocal<Set> Set::FromArray(Local<Context> context, Local<Array> array) {
6365 PREPARE_FOR_EXECUTION(context, "Set::FromArray", Set);
6366 i::Handle<i::Object> result;
6367 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*array)};
6368 has_pending_exception =
6369 !i::Execution::Call(isolate, isolate->set_from_array(),
6370 isolate->factory()->undefined_value(),
6371 arraysize(argv), argv, false).ToHandle(&result);
6372 RETURN_ON_FAILED_EXECUTION(Set);
6373 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
6377 bool Value::IsPromise() const {
6378 auto self = Utils::OpenHandle(this);
6379 return i::Object::IsPromise(self);
6383 MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) {
6384 PREPARE_FOR_EXECUTION(context, "Promise::Resolver::New", Resolver);
6385 i::Handle<i::Object> result;
6386 has_pending_exception = !i::Execution::Call(
6388 isolate->promise_create(),
6389 isolate->factory()->undefined_value(),
6391 false).ToHandle(&result);
6392 RETURN_ON_FAILED_EXECUTION(Promise::Resolver);
6393 RETURN_ESCAPED(Local<Promise::Resolver>::Cast(Utils::ToLocal(result)));
6397 Local<Promise::Resolver> Promise::Resolver::New(Isolate* isolate) {
6398 RETURN_TO_LOCAL_UNCHECKED(New(isolate->GetCurrentContext()),
6403 Local<Promise> Promise::Resolver::GetPromise() {
6404 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6405 return Local<Promise>::Cast(Utils::ToLocal(promise));
6409 Maybe<bool> Promise::Resolver::Resolve(Local<Context> context,
6410 Local<Value> value) {
6411 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6412 auto self = Utils::OpenHandle(this);
6413 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6414 has_pending_exception = i::Execution::Call(
6416 isolate->promise_resolve(),
6417 isolate->factory()->undefined_value(),
6418 arraysize(argv), argv,
6420 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6425 void Promise::Resolver::Resolve(Local<Value> value) {
6426 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6427 USE(Resolve(context, value));
6431 Maybe<bool> Promise::Resolver::Reject(Local<Context> context,
6432 Local<Value> value) {
6433 PREPARE_FOR_EXECUTION_PRIMITIVE(context, "Promise::Resolver::Resolve", bool);
6434 auto self = Utils::OpenHandle(this);
6435 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)};
6436 has_pending_exception = i::Execution::Call(
6438 isolate->promise_reject(),
6439 isolate->factory()->undefined_value(),
6440 arraysize(argv), argv,
6442 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
6447 void Promise::Resolver::Reject(Local<Value> value) {
6448 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6449 USE(Reject(context, value));
6453 MaybeLocal<Promise> Promise::Chain(Local<Context> context,
6454 Local<Function> handler) {
6455 PREPARE_FOR_EXECUTION(context, "Promise::Chain", Promise);
6456 auto self = Utils::OpenHandle(this);
6457 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*handler)};
6458 i::Handle<i::Object> result;
6459 has_pending_exception =
6460 !i::Execution::Call(isolate, isolate->promise_chain(), self,
6461 arraysize(argv), argv, false).ToHandle(&result);
6462 RETURN_ON_FAILED_EXECUTION(Promise);
6463 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6467 Local<Promise> Promise::Chain(Local<Function> handler) {
6468 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6469 RETURN_TO_LOCAL_UNCHECKED(Chain(context, handler), Promise);
6473 MaybeLocal<Promise> Promise::Catch(Local<Context> context,
6474 Local<Function> handler) {
6475 PREPARE_FOR_EXECUTION(context, "Promise::Catch", Promise);
6476 auto self = Utils::OpenHandle(this);
6477 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6478 i::Handle<i::Object> result;
6479 has_pending_exception =
6480 !i::Execution::Call(isolate, isolate->promise_catch(), self,
6481 arraysize(argv), argv, false).ToHandle(&result);
6482 RETURN_ON_FAILED_EXECUTION(Promise);
6483 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6487 Local<Promise> Promise::Catch(Local<Function> handler) {
6488 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6489 RETURN_TO_LOCAL_UNCHECKED(Catch(context, handler), Promise);
6493 MaybeLocal<Promise> Promise::Then(Local<Context> context,
6494 Local<Function> handler) {
6495 PREPARE_FOR_EXECUTION(context, "Promise::Then", Promise);
6496 auto self = Utils::OpenHandle(this);
6497 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
6498 i::Handle<i::Object> result;
6499 has_pending_exception =
6500 !i::Execution::Call(isolate, isolate->promise_then(), self,
6501 arraysize(argv), argv, false).ToHandle(&result);
6502 RETURN_ON_FAILED_EXECUTION(Promise);
6503 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
6507 Local<Promise> Promise::Then(Local<Function> handler) {
6508 auto context = ContextFromHeapObject(Utils::OpenHandle(this));
6509 RETURN_TO_LOCAL_UNCHECKED(Then(context, handler), Promise);
6513 bool Promise::HasHandler() {
6514 i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
6515 i::Isolate* isolate = promise->GetIsolate();
6516 LOG_API(isolate, "Promise::HasRejectHandler");
6518 i::Handle<i::Symbol> key = isolate->factory()->promise_has_handler_symbol();
6519 return i::JSReceiver::GetDataProperty(promise, key)->IsTrue();
6523 bool v8::ArrayBuffer::IsExternal() const {
6524 return Utils::OpenHandle(this)->is_external();
6528 bool v8::ArrayBuffer::IsNeuterable() const {
6529 return Utils::OpenHandle(this)->is_neuterable();
6533 v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
6534 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6535 i::Isolate* isolate = self->GetIsolate();
6536 Utils::ApiCheck(!self->is_external(), "v8::ArrayBuffer::Externalize",
6537 "ArrayBuffer already externalized");
6538 self->set_is_external(true);
6539 isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6540 self->backing_store());
6542 return GetContents();
6546 v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() {
6547 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6548 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6550 contents.data_ = self->backing_store();
6551 contents.byte_length_ = byte_length;
6556 void v8::ArrayBuffer::Neuter() {
6557 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6558 i::Isolate* isolate = obj->GetIsolate();
6559 Utils::ApiCheck(obj->is_external(),
6560 "v8::ArrayBuffer::Neuter",
6561 "Only externalized ArrayBuffers can be neutered");
6562 Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter",
6563 "Only neuterable ArrayBuffers can be neutered");
6564 LOG_API(obj->GetIsolate(), "v8::ArrayBuffer::Neuter()");
6566 i::Runtime::NeuterArrayBuffer(obj);
6570 size_t v8::ArrayBuffer::ByteLength() const {
6571 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6572 return static_cast<size_t>(obj->byte_length()->Number());
6576 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
6577 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6578 LOG_API(i_isolate, "v8::ArrayBuffer::New(size_t)");
6579 ENTER_V8(i_isolate);
6580 i::Handle<i::JSArrayBuffer> obj =
6581 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6582 i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length);
6583 return Utils::ToLocal(obj);
6587 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
6589 ArrayBufferCreationMode mode) {
6590 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6591 LOG_API(i_isolate, "v8::ArrayBuffer::New(void*, size_t)");
6592 ENTER_V8(i_isolate);
6593 i::Handle<i::JSArrayBuffer> obj =
6594 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared);
6595 i::Runtime::SetupArrayBuffer(i_isolate, obj,
6596 mode == ArrayBufferCreationMode::kExternalized,
6598 return Utils::ToLocal(obj);
6602 Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
6603 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6604 i::Handle<i::JSArrayBuffer> buffer;
6605 if (obj->IsJSDataView()) {
6606 i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj));
6607 DCHECK(data_view->buffer()->IsJSArrayBuffer());
6608 buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()));
6610 DCHECK(obj->IsJSTypedArray());
6611 buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
6613 return Utils::ToLocal(buffer);
6617 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
6618 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6619 i::Isolate* isolate = self->GetIsolate();
6620 size_t byte_offset = i::NumberToSize(isolate, self->byte_offset());
6621 size_t bytes_to_copy =
6622 i::Min(byte_length, i::NumberToSize(isolate, self->byte_length()));
6623 if (bytes_to_copy) {
6624 i::DisallowHeapAllocation no_gc;
6625 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6626 const char* source = reinterpret_cast<char*>(buffer->backing_store());
6627 if (source == nullptr) {
6628 DCHECK(self->IsJSTypedArray());
6629 i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self));
6630 i::Handle<i::FixedTypedArrayBase> fixed_array(
6631 i::FixedTypedArrayBase::cast(typed_array->elements()));
6632 source = reinterpret_cast<char*>(fixed_array->DataPtr());
6634 memcpy(dest, source + byte_offset, bytes_to_copy);
6636 return bytes_to_copy;
6640 bool v8::ArrayBufferView::HasBuffer() const {
6641 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this);
6642 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer()));
6643 return buffer->backing_store() != nullptr;
6647 size_t v8::ArrayBufferView::ByteOffset() {
6648 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6649 return static_cast<size_t>(obj->byte_offset()->Number());
6653 size_t v8::ArrayBufferView::ByteLength() {
6654 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
6655 return static_cast<size_t>(obj->byte_length()->Number());
6659 size_t v8::TypedArray::Length() {
6660 i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
6661 return static_cast<size_t>(obj->length_value());
6665 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype, size) \
6666 Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer, \
6667 size_t byte_offset, size_t length) { \
6668 i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate(); \
6670 "v8::" #Type "Array::New(Local<ArrayBuffer>, size_t, size_t)"); \
6671 ENTER_V8(isolate); \
6672 if (!Utils::ApiCheck(length <= static_cast<size_t>(i::Smi::kMaxValue), \
6674 "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
6675 "length exceeds max allowed value")) { \
6676 return Local<Type##Array>(); \
6678 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \
6679 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6680 i::kExternal##Type##Array, buffer, byte_offset, length); \
6681 return Utils::ToLocal##Type##Array(obj); \
6683 Local<Type##Array> Type##Array::New( \
6684 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, \
6686 CHECK(i::FLAG_harmony_sharedarraybuffer); \
6687 i::Isolate* isolate = \
6688 Utils::OpenHandle(*shared_array_buffer)->GetIsolate(); \
6689 LOG_API(isolate, "v8::" #Type \
6690 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)"); \
6691 ENTER_V8(isolate); \
6692 if (!Utils::ApiCheck( \
6693 length <= static_cast<size_t>(i::Smi::kMaxValue), \
6695 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)", \
6696 "length exceeds max allowed value")) { \
6697 return Local<Type##Array>(); \
6699 i::Handle<i::JSArrayBuffer> buffer = \
6700 Utils::OpenHandle(*shared_array_buffer); \
6701 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \
6702 i::kExternal##Type##Array, buffer, byte_offset, length); \
6703 return Utils::ToLocal##Type##Array(obj); \
6707 TYPED_ARRAYS(TYPED_ARRAY_NEW)
6708 #undef TYPED_ARRAY_NEW
6710 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer,
6711 size_t byte_offset, size_t byte_length) {
6712 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
6713 i::Isolate* isolate = buffer->GetIsolate();
6714 LOG_API(isolate, "v8::DataView::New(Local<ArrayBuffer>, size_t, size_t)");
6716 i::Handle<i::JSDataView> obj =
6717 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6718 return Utils::ToLocal(obj);
6722 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer,
6723 size_t byte_offset, size_t byte_length) {
6724 CHECK(i::FLAG_harmony_sharedarraybuffer);
6725 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer);
6726 i::Isolate* isolate = buffer->GetIsolate();
6728 "v8::DataView::New(Local<SharedArrayBuffer>, size_t, size_t)");
6730 i::Handle<i::JSDataView> obj =
6731 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length);
6732 return Utils::ToLocal(obj);
6736 bool v8::SharedArrayBuffer::IsExternal() const {
6737 return Utils::OpenHandle(this)->is_external();
6741 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
6742 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6743 i::Isolate* isolate = self->GetIsolate();
6744 Utils::ApiCheck(!self->is_external(), "v8::SharedArrayBuffer::Externalize",
6745 "SharedArrayBuffer already externalized");
6746 self->set_is_external(true);
6747 isolate->heap()->UnregisterArrayBuffer(isolate->heap()->InNewSpace(*self),
6748 self->backing_store());
6749 return GetContents();
6753 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
6754 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this);
6755 size_t byte_length = static_cast<size_t>(self->byte_length()->Number());
6757 contents.data_ = self->backing_store();
6758 contents.byte_length_ = byte_length;
6763 size_t v8::SharedArrayBuffer::ByteLength() const {
6764 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
6765 return static_cast<size_t>(obj->byte_length()->Number());
6769 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate,
6770 size_t byte_length) {
6771 CHECK(i::FLAG_harmony_sharedarraybuffer);
6772 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6773 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(size_t)");
6774 ENTER_V8(i_isolate);
6775 i::Handle<i::JSArrayBuffer> obj =
6776 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6777 i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length, true,
6778 i::SharedFlag::kShared);
6779 return Utils::ToLocalShared(obj);
6783 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
6784 Isolate* isolate, void* data, size_t byte_length,
6785 ArrayBufferCreationMode mode) {
6786 CHECK(i::FLAG_harmony_sharedarraybuffer);
6787 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6788 LOG_API(i_isolate, "v8::SharedArrayBuffer::New(void*, size_t)");
6789 ENTER_V8(i_isolate);
6790 i::Handle<i::JSArrayBuffer> obj =
6791 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared);
6792 i::Runtime::SetupArrayBuffer(i_isolate, obj,
6793 mode == ArrayBufferCreationMode::kExternalized,
6794 data, byte_length, i::SharedFlag::kShared);
6795 return Utils::ToLocalShared(obj);
6799 Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
6800 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6801 LOG_API(i_isolate, "Symbol::New()");
6802 ENTER_V8(i_isolate);
6803 i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
6804 if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
6805 return Utils::ToLocal(result);
6809 static i::Handle<i::Symbol> SymbolFor(i::Isolate* isolate,
6810 i::Handle<i::String> name,
6811 i::Handle<i::String> part) {
6812 i::Handle<i::JSObject> registry = isolate->GetSymbolRegistry();
6813 i::Handle<i::JSObject> symbols =
6814 i::Handle<i::JSObject>::cast(
6815 i::Object::GetPropertyOrElement(registry, part).ToHandleChecked());
6816 i::Handle<i::Object> symbol =
6817 i::Object::GetPropertyOrElement(symbols, name).ToHandleChecked();
6818 if (!symbol->IsSymbol()) {
6819 DCHECK(symbol->IsUndefined());
6820 symbol = isolate->factory()->NewSymbol();
6821 i::Handle<i::Symbol>::cast(symbol)->set_name(*name);
6822 i::JSObject::SetProperty(symbols, name, symbol, i::STRICT).Assert();
6824 return i::Handle<i::Symbol>::cast(symbol);
6828 Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
6829 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6830 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6831 i::Handle<i::String> part = i_isolate->factory()->for_string();
6832 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6836 Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
6837 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6838 i::Handle<i::String> i_name = Utils::OpenHandle(*name);
6839 i::Handle<i::String> part = i_isolate->factory()->for_api_string();
6840 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
6844 Local<Symbol> v8::Symbol::GetIterator(Isolate* isolate) {
6845 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6846 return Utils::ToLocal(i_isolate->factory()->iterator_symbol());
6850 Local<Symbol> v8::Symbol::GetUnscopables(Isolate* isolate) {
6851 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6852 return Utils::ToLocal(i_isolate->factory()->unscopables_symbol());
6856 Local<Symbol> v8::Symbol::GetToStringTag(Isolate* isolate) {
6857 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
6858 return Utils::ToLocal(i_isolate->factory()->to_string_tag_symbol());
6862 Local<Number> v8::Number::New(Isolate* isolate, double value) {
6863 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6864 if (std::isnan(value)) {
6865 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
6866 value = std::numeric_limits<double>::quiet_NaN();
6868 ENTER_V8(internal_isolate);
6869 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6870 return Utils::NumberToLocal(result);
6874 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
6875 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6876 if (i::Smi::IsValid(value)) {
6877 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
6880 ENTER_V8(internal_isolate);
6881 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6882 return Utils::IntegerToLocal(result);
6886 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
6887 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
6888 bool fits_into_int32_t = (value & (1 << 31)) == 0;
6889 if (fits_into_int32_t) {
6890 return Integer::New(isolate, static_cast<int32_t>(value));
6892 ENTER_V8(internal_isolate);
6893 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
6894 return Utils::IntegerToLocal(result);
6898 void Isolate::CollectAllGarbage(const char* gc_reason) {
6899 reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
6900 i::Heap::kNoGCFlags, gc_reason);
6904 HeapProfiler* Isolate::GetHeapProfiler() {
6905 i::HeapProfiler* heap_profiler =
6906 reinterpret_cast<i::Isolate*>(this)->heap_profiler();
6907 return reinterpret_cast<HeapProfiler*>(heap_profiler);
6911 CpuProfiler* Isolate::GetCpuProfiler() {
6912 i::CpuProfiler* cpu_profiler =
6913 reinterpret_cast<i::Isolate*>(this)->cpu_profiler();
6914 return reinterpret_cast<CpuProfiler*>(cpu_profiler);
6918 bool Isolate::InContext() {
6919 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6920 return isolate->context() != NULL;
6924 v8::Local<v8::Context> Isolate::GetCurrentContext() {
6925 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6926 i::Context* context = isolate->context();
6927 if (context == NULL) return Local<Context>();
6928 i::Context* native_context = context->native_context();
6929 if (native_context == NULL) return Local<Context>();
6930 return Utils::ToLocal(i::Handle<i::Context>(native_context));
6934 v8::Local<v8::Context> Isolate::GetCallingContext() {
6935 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6936 i::Handle<i::Object> calling = isolate->GetCallingNativeContext();
6937 if (calling.is_null()) return Local<Context>();
6938 return Utils::ToLocal(i::Handle<i::Context>::cast(calling));
6942 v8::Local<v8::Context> Isolate::GetEnteredContext() {
6943 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6944 i::Handle<i::Object> last =
6945 isolate->handle_scope_implementer()->LastEnteredContext();
6946 if (last.is_null()) return Local<Context>();
6947 return Utils::ToLocal(i::Handle<i::Context>::cast(last));
6951 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
6952 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6954 // If we're passed an empty handle, we throw an undefined exception
6955 // to deal more gracefully with out of memory situations.
6956 if (value.IsEmpty()) {
6957 isolate->ScheduleThrow(isolate->heap()->undefined_value());
6959 isolate->ScheduleThrow(*Utils::OpenHandle(*value));
6961 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
6965 void Isolate::SetObjectGroupId(internal::Object** object, UniqueId id) {
6966 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6967 internal_isolate->global_handles()->SetObjectGroupId(
6968 v8::internal::Handle<v8::internal::Object>(object).location(),
6973 void Isolate::SetReferenceFromGroup(UniqueId id, internal::Object** object) {
6974 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6975 internal_isolate->global_handles()->SetReferenceFromGroup(
6977 v8::internal::Handle<v8::internal::Object>(object).location());
6981 void Isolate::SetReference(internal::Object** parent,
6982 internal::Object** child) {
6983 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
6984 i::Object** parent_location =
6985 v8::internal::Handle<v8::internal::Object>(parent).location();
6986 internal_isolate->global_handles()->SetReference(
6987 reinterpret_cast<i::HeapObject**>(parent_location),
6988 v8::internal::Handle<v8::internal::Object>(child).location());
6992 void Isolate::AddGCPrologueCallback(GCPrologueCallback callback,
6994 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
6995 isolate->heap()->AddGCPrologueCallback(callback, gc_type);
6999 void Isolate::RemoveGCPrologueCallback(GCPrologueCallback callback) {
7000 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7001 isolate->heap()->RemoveGCPrologueCallback(callback);
7005 void Isolate::AddGCEpilogueCallback(GCEpilogueCallback callback,
7007 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7008 isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
7012 void Isolate::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
7013 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7014 isolate->heap()->RemoveGCEpilogueCallback(callback);
7018 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
7019 i::Isolate* isolate = i::Isolate::Current();
7020 isolate->heap()->AddGCPrologueCallback(
7021 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback),
7027 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
7028 i::Isolate* isolate = i::Isolate::Current();
7029 isolate->heap()->AddGCEpilogueCallback(
7030 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback),
7036 void Isolate::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
7038 AllocationAction action) {
7039 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7040 isolate->memory_allocator()->AddMemoryAllocationCallback(
7041 callback, space, action);
7045 void Isolate::RemoveMemoryAllocationCallback(
7046 MemoryAllocationCallback callback) {
7047 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7048 isolate->memory_allocator()->RemoveMemoryAllocationCallback(
7053 void Isolate::TerminateExecution() {
7054 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7055 isolate->stack_guard()->RequestTerminateExecution();
7059 bool Isolate::IsExecutionTerminating() {
7060 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7061 return IsExecutionTerminatingCheck(isolate);
7065 void Isolate::CancelTerminateExecution() {
7066 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7067 isolate->stack_guard()->ClearTerminateExecution();
7068 isolate->CancelTerminateExecution();
7072 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
7073 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7074 isolate->RequestInterrupt(callback, data);
7078 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
7079 CHECK(i::FLAG_expose_gc);
7080 if (type == kMinorGarbageCollection) {
7081 reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
7082 i::NEW_SPACE, "Isolate::RequestGarbageCollection",
7083 kGCCallbackFlagForced);
7085 DCHECK_EQ(kFullGarbageCollection, type);
7086 reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
7087 i::Heap::kAbortIncrementalMarkingMask,
7088 "Isolate::RequestGarbageCollection", kGCCallbackFlagForced);
7093 Isolate* Isolate::GetCurrent() {
7094 i::Isolate* isolate = i::Isolate::Current();
7095 return reinterpret_cast<Isolate*>(isolate);
7099 Isolate* Isolate::New() {
7100 Isolate::CreateParams create_params;
7101 return New(create_params);
7105 Isolate* Isolate::New(const Isolate::CreateParams& params) {
7106 i::Isolate* isolate = new i::Isolate(false);
7107 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7108 if (params.array_buffer_allocator != NULL) {
7109 isolate->set_array_buffer_allocator(params.array_buffer_allocator);
7111 isolate->set_array_buffer_allocator(i::V8::ArrayBufferAllocator());
7113 if (params.snapshot_blob != NULL) {
7114 isolate->set_snapshot_blob(params.snapshot_blob);
7116 isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
7118 if (params.entry_hook) {
7119 isolate->set_function_entry_hook(params.entry_hook);
7121 if (params.code_event_handler) {
7122 isolate->InitializeLoggingAndCounters();
7123 isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
7124 params.code_event_handler);
7126 if (params.counter_lookup_callback) {
7127 v8_isolate->SetCounterFunction(params.counter_lookup_callback);
7130 if (params.create_histogram_callback) {
7131 v8_isolate->SetCreateHistogramFunction(params.create_histogram_callback);
7134 if (params.add_histogram_sample_callback) {
7135 v8_isolate->SetAddHistogramSampleFunction(
7136 params.add_histogram_sample_callback);
7138 SetResourceConstraints(isolate, params.constraints);
7139 // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
7140 Isolate::Scope isolate_scope(v8_isolate);
7141 if (params.entry_hook || !i::Snapshot::Initialize(isolate)) {
7142 // If the isolate has a function entry hook, it needs to re-build all its
7143 // code stubs with entry hooks embedded, so don't deserialize a snapshot.
7144 if (i::Snapshot::EmbedsScript(isolate)) {
7145 // If the snapshot embeds a script, we cannot initialize the isolate
7146 // without the snapshot as a fallback. This is unlikely to happen though.
7147 V8_Fatal(__FILE__, __LINE__,
7148 "Initializing isolate from custom startup snapshot failed");
7150 isolate->Init(NULL);
7156 void Isolate::Dispose() {
7157 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7158 if (!Utils::ApiCheck(!isolate->IsInUse(),
7159 "v8::Isolate::Dispose()",
7160 "Disposing the isolate that is entered by a thread.")) {
7163 isolate->TearDown();
7167 void Isolate::Enter() {
7168 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7173 void Isolate::Exit() {
7174 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7179 void Isolate::SetAbortOnUncaughtExceptionCallback(
7180 AbortOnUncaughtExceptionCallback callback) {
7181 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7182 isolate->SetAbortOnUncaughtExceptionCallback(callback);
7186 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
7188 Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
7189 : on_failure_(on_failure) {
7190 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7191 if (on_failure_ == CRASH_ON_FAILURE) {
7192 internal_ = reinterpret_cast<void*>(
7193 new i::DisallowJavascriptExecution(i_isolate));
7195 DCHECK_EQ(THROW_ON_FAILURE, on_failure);
7196 internal_ = reinterpret_cast<void*>(
7197 new i::ThrowOnJavascriptExecution(i_isolate));
7202 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
7203 if (on_failure_ == CRASH_ON_FAILURE) {
7204 delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
7206 delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
7211 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
7213 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7214 internal_assert_ = reinterpret_cast<void*>(
7215 new i::AllowJavascriptExecution(i_isolate));
7216 internal_throws_ = reinterpret_cast<void*>(
7217 new i::NoThrowOnJavascriptExecution(i_isolate));
7221 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
7222 delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
7223 delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
7227 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
7229 : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
7230 isolate_->handle_scope_implementer()->IncrementCallDepth();
7234 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
7235 isolate_->handle_scope_implementer()->DecrementCallDepth();
7239 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
7240 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7241 i::Heap* heap = isolate->heap();
7242 heap_statistics->total_heap_size_ = heap->CommittedMemory();
7243 heap_statistics->total_heap_size_executable_ =
7244 heap->CommittedMemoryExecutable();
7245 heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
7246 heap_statistics->total_available_size_ = heap->Available();
7247 heap_statistics->used_heap_size_ = heap->SizeOfObjects();
7248 heap_statistics->heap_size_limit_ = heap->MaxReserved();
7252 size_t Isolate::NumberOfHeapSpaces() {
7253 return i::LAST_SPACE - i::FIRST_SPACE + 1;
7257 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7259 if (!space_statistics) return false;
7260 if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
7263 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7264 i::Heap* heap = isolate->heap();
7265 i::Space* space = heap->space(static_cast<int>(index));
7267 space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
7268 space_statistics->space_size_ = space->CommittedMemory();
7269 space_statistics->space_used_size_ = space->SizeOfObjects();
7270 space_statistics->space_available_size_ = space->Available();
7271 space_statistics->physical_space_size_ = space->CommittedPhysicalMemory();
7276 size_t Isolate::NumberOfTrackedHeapObjectTypes() {
7277 return i::Heap::OBJECT_STATS_COUNT;
7281 bool Isolate::GetHeapObjectStatisticsAtLastGC(
7282 HeapObjectStatistics* object_statistics, size_t type_index) {
7283 if (!object_statistics) return false;
7284 if (type_index >= i::Heap::OBJECT_STATS_COUNT) return false;
7285 if (!i::FLAG_track_gc_object_stats) return false;
7287 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7288 i::Heap* heap = isolate->heap();
7289 const char* object_type;
7290 const char* object_sub_type;
7291 size_t object_count = heap->object_count_last_gc(type_index);
7292 size_t object_size = heap->object_size_last_gc(type_index);
7293 if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
7294 // There should be no objects counted when the type is unknown.
7295 DCHECK_EQ(object_count, 0U);
7296 DCHECK_EQ(object_size, 0U);
7300 object_statistics->object_type_ = object_type;
7301 object_statistics->object_sub_type_ = object_sub_type;
7302 object_statistics->object_count_ = object_count;
7303 object_statistics->object_size_ = object_size;
7308 void Isolate::GetStackSample(const RegisterState& state, void** frames,
7309 size_t frames_limit, SampleInfo* sample_info) {
7310 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7311 i::TickSample::GetStackSample(isolate, state, i::TickSample::kSkipCEntryFrame,
7312 frames, frames_limit, sample_info);
7316 void Isolate::SetEventLogger(LogEventCallback that) {
7317 // Do not overwrite the event logger if we want to log explicitly.
7318 if (i::FLAG_log_internal_timer_events) return;
7319 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7320 isolate->set_event_logger(that);
7324 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
7325 if (callback == NULL) return;
7326 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7327 isolate->AddCallCompletedCallback(callback);
7331 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
7332 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7333 isolate->RemoveCallCompletedCallback(callback);
7337 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
7338 if (callback == NULL) return;
7339 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7340 isolate->SetPromiseRejectCallback(callback);
7344 void Isolate::RunMicrotasks() {
7345 reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
7349 void Isolate::EnqueueMicrotask(Local<Function> microtask) {
7350 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7351 isolate->EnqueueMicrotask(Utils::OpenHandle(*microtask));
7355 void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) {
7356 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7357 i::HandleScope scope(isolate);
7358 i::Handle<i::CallHandlerInfo> callback_info =
7359 i::Handle<i::CallHandlerInfo>::cast(
7360 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE));
7361 SET_FIELD_WRAPPED(callback_info, set_callback, microtask);
7362 SET_FIELD_WRAPPED(callback_info, set_data, data);
7363 isolate->EnqueueMicrotask(callback_info);
7367 void Isolate::SetAutorunMicrotasks(bool autorun) {
7368 reinterpret_cast<i::Isolate*>(this)->set_autorun_microtasks(autorun);
7372 bool Isolate::WillAutorunMicrotasks() const {
7373 return reinterpret_cast<const i::Isolate*>(this)->autorun_microtasks();
7377 void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
7378 reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
7382 void Isolate::SetCounterFunction(CounterLookupCallback callback) {
7383 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7384 isolate->stats_table()->SetCounterFunction(callback);
7385 isolate->InitializeLoggingAndCounters();
7386 isolate->counters()->ResetCounters();
7390 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
7391 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7392 isolate->stats_table()->SetCreateHistogramFunction(callback);
7393 isolate->InitializeLoggingAndCounters();
7394 isolate->counters()->ResetHistograms();
7398 void Isolate::SetAddHistogramSampleFunction(
7399 AddHistogramSampleCallback callback) {
7400 reinterpret_cast<i::Isolate*>(this)
7402 ->SetAddHistogramSampleFunction(callback);
7406 bool Isolate::IdleNotification(int idle_time_in_ms) {
7407 // Returning true tells the caller that it need not
7408 // continue to call IdleNotification.
7409 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7410 if (!i::FLAG_use_idle_notification) return true;
7411 return isolate->heap()->IdleNotification(idle_time_in_ms);
7415 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) {
7416 // Returning true tells the caller that it need not
7417 // continue to call IdleNotification.
7418 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7419 if (!i::FLAG_use_idle_notification) return true;
7420 return isolate->heap()->IdleNotification(deadline_in_seconds);
7424 void Isolate::LowMemoryNotification() {
7425 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7427 i::HistogramTimerScope idle_notification_scope(
7428 isolate->counters()->gc_low_memory_notification());
7429 isolate->heap()->CollectAllAvailableGarbage("low memory notification");
7434 int Isolate::ContextDisposedNotification(bool dependant_context) {
7435 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7436 return isolate->heap()->NotifyContextDisposed(dependant_context);
7440 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
7441 JitCodeEventHandler event_handler) {
7442 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7443 // Ensure that logging is initialized for our isolate.
7444 isolate->InitializeLoggingAndCounters();
7445 isolate->logger()->SetCodeEventHandler(options, event_handler);
7449 void Isolate::SetStackLimit(uintptr_t stack_limit) {
7450 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7452 isolate->stack_guard()->SetStackLimit(stack_limit);
7456 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
7457 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7458 if (isolate->code_range()->valid()) {
7459 *start = isolate->code_range()->start();
7460 *length_in_bytes = isolate->code_range()->size();
7463 *length_in_bytes = 0;
7468 void Isolate::SetFatalErrorHandler(FatalErrorCallback that) {
7469 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7470 isolate->set_exception_behavior(that);
7474 void Isolate::SetAllowCodeGenerationFromStringsCallback(
7475 AllowCodeGenerationFromStringsCallback callback) {
7476 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7477 isolate->set_allow_code_gen_callback(callback);
7481 bool Isolate::IsDead() {
7482 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7483 return isolate->IsDead();
7487 bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
7488 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7490 i::HandleScope scope(isolate);
7491 NeanderArray listeners(isolate->factory()->message_listeners());
7492 NeanderObject obj(isolate, 2);
7493 obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
7494 obj.set(1, data.IsEmpty() ? isolate->heap()->undefined_value()
7495 : *Utils::OpenHandle(*data));
7496 listeners.add(isolate, obj.value());
7501 void Isolate::RemoveMessageListeners(MessageCallback that) {
7502 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7504 i::HandleScope scope(isolate);
7505 NeanderArray listeners(isolate->factory()->message_listeners());
7506 for (int i = 0; i < listeners.length(); i++) {
7507 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
7509 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
7510 i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
7511 if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
7512 listeners.set(i, isolate->heap()->undefined_value());
7518 void Isolate::SetFailedAccessCheckCallbackFunction(
7519 FailedAccessCheckCallback callback) {
7520 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7521 isolate->SetFailedAccessCheckCallback(callback);
7525 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
7526 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7527 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7528 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7533 void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) {
7534 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7535 isolate->heap()->VisitExternalResources(visitor);
7539 class VisitorAdapter : public i::ObjectVisitor {
7541 explicit VisitorAdapter(PersistentHandleVisitor* visitor)
7542 : visitor_(visitor) {}
7543 virtual void VisitPointers(i::Object** start, i::Object** end) {
7546 virtual void VisitEmbedderReference(i::Object** p, uint16_t class_id) {
7547 Value* value = ToApi<Value>(i::Handle<i::Object>(p));
7548 visitor_->VisitPersistentHandle(
7549 reinterpret_cast<Persistent<Value>*>(&value), class_id);
7553 PersistentHandleVisitor* visitor_;
7557 void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
7558 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7559 i::DisallowHeapAllocation no_allocation;
7560 VisitorAdapter visitor_adapter(visitor);
7561 isolate->global_handles()->IterateAllRootsWithClassIds(&visitor_adapter);
7565 void Isolate::VisitHandlesForPartialDependence(
7566 PersistentHandleVisitor* visitor) {
7567 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
7568 i::DisallowHeapAllocation no_allocation;
7569 VisitorAdapter visitor_adapter(visitor);
7570 isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds(
7575 String::Utf8Value::Utf8Value(v8::Local<v8::Value> obj)
7576 : str_(NULL), length_(0) {
7577 if (obj.IsEmpty()) return;
7578 i::Isolate* isolate = i::Isolate::Current();
7579 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7581 i::HandleScope scope(isolate);
7582 Local<Context> context = v8_isolate->GetCurrentContext();
7583 TryCatch try_catch(v8_isolate);
7585 if (!obj->ToString(context).ToLocal(&str)) return;
7586 i::Handle<i::String> i_str = Utils::OpenHandle(*str);
7587 length_ = v8::Utf8Length(*i_str, isolate);
7588 str_ = i::NewArray<char>(length_ + 1);
7589 str->WriteUtf8(str_);
7593 String::Utf8Value::~Utf8Value() {
7594 i::DeleteArray(str_);
7598 String::Value::Value(v8::Local<v8::Value> obj) : str_(NULL), length_(0) {
7599 if (obj.IsEmpty()) return;
7600 i::Isolate* isolate = i::Isolate::Current();
7601 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
7603 i::HandleScope scope(isolate);
7604 Local<Context> context = v8_isolate->GetCurrentContext();
7605 TryCatch try_catch(v8_isolate);
7607 if (!obj->ToString(context).ToLocal(&str)) return;
7608 length_ = str->Length();
7609 str_ = i::NewArray<uint16_t>(length_ + 1);
7614 String::Value::~Value() {
7615 i::DeleteArray(str_);
7619 #define DEFINE_ERROR(NAME) \
7620 Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) { \
7621 i::Isolate* isolate = i::Isolate::Current(); \
7622 LOG_API(isolate, #NAME); \
7623 ENTER_V8(isolate); \
7626 i::HandleScope scope(isolate); \
7627 i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \
7628 error = *isolate->factory()->NewError("$" #NAME, message); \
7630 i::Handle<i::Object> result(error, isolate); \
7631 return Utils::ToLocal(result); \
7634 DEFINE_ERROR(RangeError)
7635 DEFINE_ERROR(ReferenceError)
7636 DEFINE_ERROR(SyntaxError)
7637 DEFINE_ERROR(TypeError)
7643 Local<Message> Exception::CreateMessage(Local<Value> exception) {
7644 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7645 if (!obj->IsHeapObject()) return Local<Message>();
7646 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
7648 i::HandleScope scope(isolate);
7649 return Utils::MessageToLocal(
7650 scope.CloseAndEscape(isolate->CreateMessage(obj, NULL)));
7654 Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) {
7655 i::Handle<i::Object> obj = Utils::OpenHandle(*exception);
7656 if (!obj->IsJSObject()) return Local<StackTrace>();
7657 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj);
7658 i::Isolate* isolate = js_obj->GetIsolate();
7660 return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj));
7664 // --- D e b u g S u p p o r t ---
7666 bool Debug::SetDebugEventListener(EventCallback that, Local<Value> data) {
7667 i::Isolate* isolate = i::Isolate::Current();
7669 i::HandleScope scope(isolate);
7670 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
7672 foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
7674 isolate->debug()->SetEventListener(foreign,
7675 Utils::OpenHandle(*data, true));
7680 void Debug::DebugBreak(Isolate* isolate) {
7681 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->RequestDebugBreak();
7685 void Debug::CancelDebugBreak(Isolate* isolate) {
7686 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7687 internal_isolate->stack_guard()->ClearDebugBreak();
7691 bool Debug::CheckDebugBreak(Isolate* isolate) {
7692 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7693 return internal_isolate->stack_guard()->CheckDebugBreak();
7697 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
7698 i::Isolate* isolate = i::Isolate::Current();
7700 isolate->debug()->SetMessageHandler(handler);
7704 void Debug::SendCommand(Isolate* isolate,
7705 const uint16_t* command,
7707 ClientData* client_data) {
7708 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7709 internal_isolate->debug()->EnqueueCommandMessage(
7710 i::Vector<const uint16_t>(command, length), client_data);
7714 MaybeLocal<Value> Debug::Call(Local<Context> context,
7715 v8::Local<v8::Function> fun,
7716 v8::Local<v8::Value> data) {
7717 PREPARE_FOR_EXECUTION(context, "v8::Debug::Call()", Value);
7718 i::Handle<i::Object> data_obj;
7719 if (data.IsEmpty()) {
7720 data_obj = isolate->factory()->undefined_value();
7722 data_obj = Utils::OpenHandle(*data);
7724 Local<Value> result;
7725 has_pending_exception =
7726 !ToLocal<Value>(isolate->debug()->Call(Utils::OpenHandle(*fun), data_obj),
7728 RETURN_ON_FAILED_EXECUTION(Value);
7729 RETURN_ESCAPED(result);
7733 Local<Value> Debug::Call(v8::Local<v8::Function> fun,
7734 v8::Local<v8::Value> data) {
7735 auto context = ContextFromHeapObject(Utils::OpenHandle(*fun));
7736 RETURN_TO_LOCAL_UNCHECKED(Call(context, fun, data), Value);
7740 MaybeLocal<Value> Debug::GetMirror(Local<Context> context,
7741 v8::Local<v8::Value> obj) {
7742 PREPARE_FOR_EXECUTION(context, "v8::Debug::GetMirror()", Value);
7743 i::Debug* isolate_debug = isolate->debug();
7744 has_pending_exception = !isolate_debug->Load();
7745 RETURN_ON_FAILED_EXECUTION(Value);
7746 i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global_object());
7747 auto name = isolate->factory()->NewStringFromStaticChars("MakeMirror");
7748 auto fun_obj = i::Object::GetProperty(debug, name).ToHandleChecked();
7749 auto v8_fun = Utils::ToLocal(i::Handle<i::JSFunction>::cast(fun_obj));
7750 const int kArgc = 1;
7751 v8::Local<v8::Value> argv[kArgc] = {obj};
7752 Local<Value> result;
7753 has_pending_exception = !v8_fun->Call(context, Utils::ToLocal(debug), kArgc,
7754 argv).ToLocal(&result);
7755 RETURN_ON_FAILED_EXECUTION(Value);
7756 RETURN_ESCAPED(result);
7760 Local<Value> Debug::GetMirror(v8::Local<v8::Value> obj) {
7761 RETURN_TO_LOCAL_UNCHECKED(GetMirror(Local<Context>(), obj), Value);
7765 void Debug::ProcessDebugMessages() {
7766 i::Isolate::Current()->debug()->ProcessDebugMessages(true);
7770 Local<Context> Debug::GetDebugContext() {
7771 i::Isolate* isolate = i::Isolate::Current();
7773 return Utils::ToLocal(isolate->debug()->GetDebugContext());
7777 void Debug::SetLiveEditEnabled(Isolate* isolate, bool enable) {
7778 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
7779 internal_isolate->debug()->set_live_edit_enabled(enable);
7783 MaybeLocal<Array> Debug::GetInternalProperties(Isolate* v8_isolate,
7784 Local<Value> value) {
7785 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7787 i::Handle<i::Object> val = Utils::OpenHandle(*value);
7788 i::Handle<i::JSArray> result;
7789 if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
7790 return MaybeLocal<Array>();
7791 return Utils::ToLocal(result);
7795 Local<String> CpuProfileNode::GetFunctionName() const {
7796 i::Isolate* isolate = i::Isolate::Current();
7797 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7798 const i::CodeEntry* entry = node->entry();
7799 i::Handle<i::String> name =
7800 isolate->factory()->InternalizeUtf8String(entry->name());
7801 if (!entry->has_name_prefix()) {
7802 return ToApiHandle<String>(name);
7804 // We do not expect this to fail. Change this if it does.
7805 i::Handle<i::String> cons = isolate->factory()->NewConsString(
7806 isolate->factory()->InternalizeUtf8String(entry->name_prefix()),
7807 name).ToHandleChecked();
7808 return ToApiHandle<String>(cons);
7813 int CpuProfileNode::GetScriptId() const {
7814 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7815 const i::CodeEntry* entry = node->entry();
7816 return entry->script_id();
7820 Local<String> CpuProfileNode::GetScriptResourceName() const {
7821 i::Isolate* isolate = i::Isolate::Current();
7822 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7823 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7824 node->entry()->resource_name()));
7828 int CpuProfileNode::GetLineNumber() const {
7829 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
7833 int CpuProfileNode::GetColumnNumber() const {
7834 return reinterpret_cast<const i::ProfileNode*>(this)->
7835 entry()->column_number();
7839 unsigned int CpuProfileNode::GetHitLineCount() const {
7840 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7841 return node->GetHitLineCount();
7845 bool CpuProfileNode::GetLineTicks(LineTick* entries,
7846 unsigned int length) const {
7847 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7848 return node->GetLineTicks(entries, length);
7852 const char* CpuProfileNode::GetBailoutReason() const {
7853 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7854 return node->entry()->bailout_reason();
7858 unsigned CpuProfileNode::GetHitCount() const {
7859 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
7863 unsigned CpuProfileNode::GetCallUid() const {
7864 return reinterpret_cast<const i::ProfileNode*>(this)->function_id();
7868 unsigned CpuProfileNode::GetNodeId() const {
7869 return reinterpret_cast<const i::ProfileNode*>(this)->id();
7873 int CpuProfileNode::GetChildrenCount() const {
7874 return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
7878 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
7879 const i::ProfileNode* child =
7880 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
7881 return reinterpret_cast<const CpuProfileNode*>(child);
7885 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
7886 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
7887 return node->deopt_infos();
7891 void CpuProfile::Delete() {
7892 i::Isolate* isolate = i::Isolate::Current();
7893 i::CpuProfiler* profiler = isolate->cpu_profiler();
7894 DCHECK(profiler != NULL);
7895 profiler->DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
7899 Local<String> CpuProfile::GetTitle() const {
7900 i::Isolate* isolate = i::Isolate::Current();
7901 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7902 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
7907 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
7908 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7909 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
7913 const CpuProfileNode* CpuProfile::GetSample(int index) const {
7914 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7915 return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
7919 int64_t CpuProfile::GetSampleTimestamp(int index) const {
7920 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7921 return (profile->sample_timestamp(index) - base::TimeTicks())
7926 int64_t CpuProfile::GetStartTime() const {
7927 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7928 return (profile->start_time() - base::TimeTicks()).InMicroseconds();
7932 int64_t CpuProfile::GetEndTime() const {
7933 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
7934 return (profile->end_time() - base::TimeTicks()).InMicroseconds();
7938 int CpuProfile::GetSamplesCount() const {
7939 return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
7943 void CpuProfiler::SetSamplingInterval(int us) {
7945 return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
7946 base::TimeDelta::FromMicroseconds(us));
7950 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) {
7951 reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
7952 *Utils::OpenHandle(*title), record_samples);
7956 CpuProfile* CpuProfiler::StopProfiling(Local<String> title) {
7957 return reinterpret_cast<CpuProfile*>(
7958 reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
7959 *Utils::OpenHandle(*title)));
7963 void CpuProfiler::SetIdle(bool is_idle) {
7964 i::Isolate* isolate = reinterpret_cast<i::CpuProfiler*>(this)->isolate();
7965 v8::StateTag state = isolate->current_vm_state();
7966 DCHECK(state == v8::EXTERNAL || state == v8::IDLE);
7967 if (isolate->js_entry_sp() != NULL) return;
7969 isolate->set_current_vm_state(v8::IDLE);
7970 } else if (state == v8::IDLE) {
7971 isolate->set_current_vm_state(v8::EXTERNAL);
7976 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
7977 return const_cast<i::HeapGraphEdge*>(
7978 reinterpret_cast<const i::HeapGraphEdge*>(edge));
7982 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
7983 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
7987 Local<Value> HeapGraphEdge::GetName() const {
7988 i::Isolate* isolate = i::Isolate::Current();
7989 i::HeapGraphEdge* edge = ToInternal(this);
7990 switch (edge->type()) {
7991 case i::HeapGraphEdge::kContextVariable:
7992 case i::HeapGraphEdge::kInternal:
7993 case i::HeapGraphEdge::kProperty:
7994 case i::HeapGraphEdge::kShortcut:
7995 case i::HeapGraphEdge::kWeak:
7996 return ToApiHandle<String>(
7997 isolate->factory()->InternalizeUtf8String(edge->name()));
7998 case i::HeapGraphEdge::kElement:
7999 case i::HeapGraphEdge::kHidden:
8000 return ToApiHandle<Number>(
8001 isolate->factory()->NewNumberFromInt(edge->index()));
8002 default: UNREACHABLE();
8004 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
8008 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
8009 const i::HeapEntry* from = ToInternal(this)->from();
8010 return reinterpret_cast<const HeapGraphNode*>(from);
8014 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
8015 const i::HeapEntry* to = ToInternal(this)->to();
8016 return reinterpret_cast<const HeapGraphNode*>(to);
8020 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
8021 return const_cast<i::HeapEntry*>(
8022 reinterpret_cast<const i::HeapEntry*>(entry));
8026 HeapGraphNode::Type HeapGraphNode::GetType() const {
8027 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
8031 Local<String> HeapGraphNode::GetName() const {
8032 i::Isolate* isolate = i::Isolate::Current();
8033 return ToApiHandle<String>(
8034 isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
8038 SnapshotObjectId HeapGraphNode::GetId() const {
8039 return ToInternal(this)->id();
8043 size_t HeapGraphNode::GetShallowSize() const {
8044 return ToInternal(this)->self_size();
8048 int HeapGraphNode::GetChildrenCount() const {
8049 return ToInternal(this)->children().length();
8053 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
8054 return reinterpret_cast<const HeapGraphEdge*>(
8055 ToInternal(this)->children()[index]);
8059 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
8060 return const_cast<i::HeapSnapshot*>(
8061 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
8065 void HeapSnapshot::Delete() {
8066 i::Isolate* isolate = i::Isolate::Current();
8067 if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
8068 ToInternal(this)->Delete();
8070 // If this is the last snapshot, clean up all accessory data as well.
8071 isolate->heap_profiler()->DeleteAllSnapshots();
8076 const HeapGraphNode* HeapSnapshot::GetRoot() const {
8077 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
8081 const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
8082 return reinterpret_cast<const HeapGraphNode*>(
8083 ToInternal(this)->GetEntryById(id));
8087 int HeapSnapshot::GetNodesCount() const {
8088 return ToInternal(this)->entries().length();
8092 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
8093 return reinterpret_cast<const HeapGraphNode*>(
8094 &ToInternal(this)->entries().at(index));
8098 SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
8099 return ToInternal(this)->max_snapshot_js_object_id();
8103 void HeapSnapshot::Serialize(OutputStream* stream,
8104 HeapSnapshot::SerializationFormat format) const {
8105 Utils::ApiCheck(format == kJSON,
8106 "v8::HeapSnapshot::Serialize",
8107 "Unknown serialization format");
8108 Utils::ApiCheck(stream->GetChunkSize() > 0,
8109 "v8::HeapSnapshot::Serialize",
8110 "Invalid stream chunk size");
8111 i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
8112 serializer.Serialize(stream);
8117 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId
8118 HeapProfiler::kUnknownObjectId;
8121 int HeapProfiler::GetSnapshotCount() {
8122 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
8126 const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
8127 return reinterpret_cast<const HeapSnapshot*>(
8128 reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
8132 SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) {
8133 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
8134 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
8138 Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
8139 i::Handle<i::Object> obj =
8140 reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
8141 if (obj.is_null()) return Local<Value>();
8142 return Utils::ToLocal(obj);
8146 void HeapProfiler::ClearObjectIds() {
8147 reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
8151 const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
8152 ActivityControl* control, ObjectNameResolver* resolver) {
8153 return reinterpret_cast<const HeapSnapshot*>(
8154 reinterpret_cast<i::HeapProfiler*>(this)
8155 ->TakeSnapshot(control, resolver));
8159 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
8160 reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
8165 void HeapProfiler::StopTrackingHeapObjects() {
8166 reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
8170 SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream,
8171 int64_t* timestamp_us) {
8172 i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
8173 return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
8177 void HeapProfiler::DeleteAllHeapSnapshots() {
8178 reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
8182 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
8183 WrapperInfoCallback callback) {
8184 reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
8189 size_t HeapProfiler::GetProfilerMemorySize() {
8190 return reinterpret_cast<i::HeapProfiler*>(this)->
8191 GetMemorySizeUsedByProfiler();
8195 void HeapProfiler::SetRetainedObjectInfo(UniqueId id,
8196 RetainedObjectInfo* info) {
8197 reinterpret_cast<i::HeapProfiler*>(this)->SetRetainedObjectInfo(id, info);
8201 v8::Testing::StressType internal::Testing::stress_type_ =
8202 v8::Testing::kStressTypeOpt;
8205 void Testing::SetStressRunType(Testing::StressType type) {
8206 internal::Testing::set_stress_type(type);
8210 int Testing::GetStressRuns() {
8211 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
8213 // In debug mode the code runs much slower so stressing will only make two
8222 static void SetFlagsFromString(const char* flags) {
8223 V8::SetFlagsFromString(flags, i::StrLength(flags));
8227 void Testing::PrepareStressRun(int run) {
8228 static const char* kLazyOptimizations =
8229 "--prepare-always-opt "
8230 "--max-inlined-source-size=999999 "
8231 "--max-inlined-nodes=999999 "
8232 "--max-inlined-nodes-cumulative=999999 "
8234 static const char* kForcedOptimizations = "--always-opt";
8236 // If deoptimization stressed turn on frequent deoptimization. If no value
8237 // is spefified through --deopt-every-n-times use a default default value.
8238 static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
8239 if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
8240 internal::FLAG_deopt_every_n_times == 0) {
8241 SetFlagsFromString(kDeoptEvery13Times);
8245 // As stressing in debug mode only make two runs skip the deopt stressing
8247 if (run == GetStressRuns() - 1) {
8248 SetFlagsFromString(kForcedOptimizations);
8250 SetFlagsFromString(kLazyOptimizations);
8253 if (run == GetStressRuns() - 1) {
8254 SetFlagsFromString(kForcedOptimizations);
8255 } else if (run != GetStressRuns() - 2) {
8256 SetFlagsFromString(kLazyOptimizations);
8262 // TODO(svenpanne) Deprecate this.
8263 void Testing::DeoptimizeAll() {
8264 i::Isolate* isolate = i::Isolate::Current();
8265 i::HandleScope scope(isolate);
8266 internal::Deoptimizer::DeoptimizeAll(isolate);
8270 namespace internal {
8273 void HandleScopeImplementer::FreeThreadResources() {
8278 char* HandleScopeImplementer::ArchiveThread(char* storage) {
8279 HandleScopeData* current = isolate_->handle_scope_data();
8280 handle_scope_data_ = *current;
8281 MemCopy(storage, this, sizeof(*this));
8283 ResetAfterArchive();
8284 current->Initialize();
8286 return storage + ArchiveSpacePerThread();
8290 int HandleScopeImplementer::ArchiveSpacePerThread() {
8291 return sizeof(HandleScopeImplementer);
8295 char* HandleScopeImplementer::RestoreThread(char* storage) {
8296 MemCopy(this, storage, sizeof(*this));
8297 *isolate_->handle_scope_data() = handle_scope_data_;
8298 return storage + ArchiveSpacePerThread();
8302 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
8304 bool found_block_before_deferred = false;
8306 // Iterate over all handles in the blocks except for the last.
8307 for (int i = blocks()->length() - 2; i >= 0; --i) {
8308 Object** block = blocks()->at(i);
8309 if (last_handle_before_deferred_block_ != NULL &&
8310 (last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) &&
8311 (last_handle_before_deferred_block_ >= block)) {
8312 v->VisitPointers(block, last_handle_before_deferred_block_);
8313 DCHECK(!found_block_before_deferred);
8315 found_block_before_deferred = true;
8318 v->VisitPointers(block, &block[kHandleBlockSize]);
8322 DCHECK(last_handle_before_deferred_block_ == NULL ||
8323 found_block_before_deferred);
8325 // Iterate over live handles in the last block (if any).
8326 if (!blocks()->is_empty()) {
8327 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
8330 List<Context*>* context_lists[2] = { &saved_contexts_, &entered_contexts_};
8331 for (unsigned i = 0; i < arraysize(context_lists); i++) {
8332 if (context_lists[i]->is_empty()) continue;
8333 Object** start = reinterpret_cast<Object**>(&context_lists[i]->first());
8334 v->VisitPointers(start, start + context_lists[i]->length());
8339 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
8340 HandleScopeData* current = isolate_->handle_scope_data();
8341 handle_scope_data_ = *current;
8346 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
8347 HandleScopeImplementer* scope_implementer =
8348 reinterpret_cast<HandleScopeImplementer*>(storage);
8349 scope_implementer->IterateThis(v);
8350 return storage + ArchiveSpacePerThread();
8354 DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) {
8355 DeferredHandles* deferred =
8356 new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
8358 while (!blocks_.is_empty()) {
8359 Object** block_start = blocks_.last();
8360 Object** block_limit = &block_start[kHandleBlockSize];
8361 // We should not need to check for SealHandleScope here. Assert this.
8362 DCHECK(prev_limit == block_limit ||
8363 !(block_start <= prev_limit && prev_limit <= block_limit));
8364 if (prev_limit == block_limit) break;
8365 deferred->blocks_.Add(blocks_.last());
8366 blocks_.RemoveLast();
8369 // deferred->blocks_ now contains the blocks installed on the
8370 // HandleScope stack since BeginDeferredScope was called, but in
8373 DCHECK(prev_limit == NULL || !blocks_.is_empty());
8375 DCHECK(!blocks_.is_empty() && prev_limit != NULL);
8376 DCHECK(last_handle_before_deferred_block_ != NULL);
8377 last_handle_before_deferred_block_ = NULL;
8382 void HandleScopeImplementer::BeginDeferredScope() {
8383 DCHECK(last_handle_before_deferred_block_ == NULL);
8384 last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
8388 DeferredHandles::~DeferredHandles() {
8389 isolate_->UnlinkDeferredHandles(this);
8391 for (int i = 0; i < blocks_.length(); i++) {
8392 #ifdef ENABLE_HANDLE_ZAPPING
8393 HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
8395 isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
8400 void DeferredHandles::Iterate(ObjectVisitor* v) {
8401 DCHECK(!blocks_.is_empty());
8403 DCHECK((first_block_limit_ >= blocks_.first()) &&
8404 (first_block_limit_ <= &(blocks_.first())[kHandleBlockSize]));
8406 v->VisitPointers(blocks_.first(), first_block_limit_);
8408 for (int i = 1; i < blocks_.length(); i++) {
8409 v->VisitPointers(blocks_[i], &blocks_[i][kHandleBlockSize]);
8414 void InvokeAccessorGetterCallback(
8415 v8::Local<v8::Name> property,
8416 const v8::PropertyCallbackInfo<v8::Value>& info,
8417 v8::AccessorNameGetterCallback getter) {
8418 // Leaving JavaScript.
8419 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8420 Address getter_address = reinterpret_cast<Address>(reinterpret_cast<intptr_t>(
8422 VMState<EXTERNAL> state(isolate);
8423 ExternalCallbackScope call_scope(isolate, getter_address);
8424 getter(property, info);
8428 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
8429 v8::FunctionCallback callback) {
8430 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
8431 Address callback_address =
8432 reinterpret_cast<Address>(reinterpret_cast<intptr_t>(callback));
8433 VMState<EXTERNAL> state(isolate);
8434 ExternalCallbackScope call_scope(isolate, callback_address);
8439 } // namespace internal