| // Copyright 2012 the V8 project authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| #include "src/api.h" |
| |
| #include <string.h> // For memcpy, strlen. |
| #ifdef V8_USE_ADDRESS_SANITIZER |
| #include <sanitizer/asan_interface.h> |
| #endif // V8_USE_ADDRESS_SANITIZER |
| #include <cmath> // For isnan. |
| #include <limits> |
| #include <vector> |
| #include "include/v8-debug.h" |
| #include "include/v8-experimental.h" |
| #include "include/v8-profiler.h" |
| #include "include/v8-testing.h" |
| #include "include/v8-util.h" |
| #include "src/accessors.h" |
| #include "src/api-experimental.h" |
| #include "src/api-natives.h" |
| #include "src/assert-scope.h" |
| #include "src/background-parsing-task.h" |
| #include "src/base/functional.h" |
| #include "src/base/platform/platform.h" |
| #include "src/base/platform/time.h" |
| #include "src/base/utils/random-number-generator.h" |
| #include "src/bootstrapper.h" |
| #include "src/char-predicates-inl.h" |
| #include "src/code-stubs.h" |
| #include "src/compiler.h" |
| #include "src/context-measure.h" |
| #include "src/contexts.h" |
| #include "src/conversions-inl.h" |
| #include "src/counters.h" |
| #include "src/debug/debug.h" |
| #include "src/deoptimizer.h" |
| #include "src/execution.h" |
| #include "src/gdb-jit.h" |
| #include "src/global-handles.h" |
| #include "src/icu_util.h" |
| #include "src/isolate-inl.h" |
| #include "src/json-parser.h" |
| #include "src/json-stringifier.h" |
| #include "src/messages.h" |
| #include "src/parsing/parser.h" |
| #include "src/parsing/scanner-character-streams.h" |
| #include "src/pending-compilation-error-handler.h" |
| #include "src/profiler/cpu-profiler.h" |
| #include "src/profiler/heap-profiler.h" |
| #include "src/profiler/heap-snapshot-generator-inl.h" |
| #include "src/profiler/profile-generator-inl.h" |
| #include "src/profiler/tick-sample.h" |
| #include "src/property-descriptor.h" |
| #include "src/property-details.h" |
| #include "src/property.h" |
| #include "src/prototype.h" |
| #include "src/runtime-profiler.h" |
| #include "src/runtime/runtime.h" |
| #include "src/simulator.h" |
| #include "src/snapshot/natives.h" |
| #include "src/snapshot/snapshot.h" |
| #include "src/startup-data-util.h" |
| #include "src/tracing/trace-event.h" |
| #include "src/unicode-inl.h" |
| #include "src/v8.h" |
| #include "src/v8threads.h" |
| #include "src/version.h" |
| #include "src/vm-state-inl.h" |
| |
| namespace v8 { |
| |
| #define LOG_API(isolate, class_name, function_name) \ |
| i::RuntimeCallTimerScope _runtime_timer( \ |
| isolate, &i::RuntimeCallStats::API_##class_name##_##function_name); \ |
| LOG(isolate, ApiEntryCall("v8::" #class_name "::" #function_name)) |
| |
| #define ENTER_V8(isolate) i::VMState<v8::OTHER> __state__((isolate)) |
| |
| #define PREPARE_FOR_EXECUTION_GENERIC(isolate, context, class_name, \ |
| function_name, bailout_value, \ |
| HandleScopeClass, do_callback) \ |
| if (IsExecutionTerminatingCheck(isolate)) { \ |
| return bailout_value; \ |
| } \ |
| HandleScopeClass handle_scope(isolate); \ |
| CallDepthScope call_depth_scope(isolate, context, do_callback); \ |
| LOG_API(isolate, class_name, function_name); \ |
| ENTER_V8(isolate); \ |
| bool has_pending_exception = false |
| |
| #define PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ |
| bailout_value, HandleScopeClass, \ |
| do_callback) \ |
| auto isolate = context.IsEmpty() \ |
| ? i::Isolate::Current() \ |
| : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \ |
| PREPARE_FOR_EXECUTION_GENERIC(isolate, context, class_name, function_name, \ |
| bailout_value, HandleScopeClass, do_callback); |
| |
| #define PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, class_name, function_name, \ |
| T) \ |
| PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(), class_name, \ |
| function_name, MaybeLocal<T>(), \ |
| InternalEscapableScope, false); |
| |
| #define PREPARE_FOR_EXECUTION(context, class_name, function_name, T) \ |
| PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ |
| MaybeLocal<T>(), InternalEscapableScope, \ |
| false) |
| |
| #define PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, class_name, \ |
| function_name, T) \ |
| PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ |
| MaybeLocal<T>(), InternalEscapableScope, \ |
| true) |
| |
| #define PREPARE_FOR_EXECUTION_PRIMITIVE(context, class_name, function_name, T) \ |
| PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ |
| Nothing<T>(), i::HandleScope, false) |
| |
| #define EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, value) \ |
| do { \ |
| if (has_pending_exception) { \ |
| call_depth_scope.Escape(); \ |
| return value; \ |
| } \ |
| } while (false) |
| |
| |
| #define RETURN_ON_FAILED_EXECUTION(T) \ |
| EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, MaybeLocal<T>()) |
| |
| |
| #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \ |
| EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, Nothing<T>()) |
| |
| |
| #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \ |
| return maybe_local.FromMaybe(Local<T>()); |
| |
| |
| #define RETURN_ESCAPED(value) return handle_scope.Escape(value); |
| |
| |
| namespace { |
| |
| Local<Context> ContextFromHeapObject(i::Handle<i::Object> obj) { |
| return reinterpret_cast<v8::Isolate*>(i::HeapObject::cast(*obj)->GetIsolate()) |
| ->GetCurrentContext(); |
| } |
| |
| class InternalEscapableScope : public v8::EscapableHandleScope { |
| public: |
| explicit inline InternalEscapableScope(i::Isolate* isolate) |
| : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {} |
| }; |
| |
| |
| #ifdef DEBUG |
| void CheckMicrotasksScopesConsistency(i::Isolate* isolate) { |
| auto handle_scope_implementer = isolate->handle_scope_implementer(); |
| if (handle_scope_implementer->microtasks_policy() == |
| v8::MicrotasksPolicy::kScoped) { |
| DCHECK(handle_scope_implementer->GetMicrotasksScopeDepth() || |
| !handle_scope_implementer->DebugMicrotasksScopeDepthIsZero()); |
| } |
| } |
| #endif |
| |
| |
| class CallDepthScope { |
| public: |
| explicit CallDepthScope(i::Isolate* isolate, Local<Context> context, |
| bool do_callback) |
| : isolate_(isolate), |
| context_(context), |
| escaped_(false), |
| do_callback_(do_callback) { |
| // TODO(dcarney): remove this when blink stops crashing. |
| DCHECK(!isolate_->external_caught_exception()); |
| isolate_->IncrementJsCallsFromApiCounter(); |
| isolate_->handle_scope_implementer()->IncrementCallDepth(); |
| if (!context_.IsEmpty()) context_->Enter(); |
| if (do_callback_) isolate_->FireBeforeCallEnteredCallback(); |
| } |
| ~CallDepthScope() { |
| if (!context_.IsEmpty()) context_->Exit(); |
| if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth(); |
| if (do_callback_) isolate_->FireCallCompletedCallback(); |
| #ifdef DEBUG |
| if (do_callback_) CheckMicrotasksScopesConsistency(isolate_); |
| #endif |
| } |
| |
| void Escape() { |
| DCHECK(!escaped_); |
| escaped_ = true; |
| auto handle_scope_implementer = isolate_->handle_scope_implementer(); |
| handle_scope_implementer->DecrementCallDepth(); |
| bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero(); |
| isolate_->OptionalRescheduleException(call_depth_is_zero); |
| } |
| |
| private: |
| i::Isolate* const isolate_; |
| Local<Context> context_; |
| bool escaped_; |
| bool do_callback_; |
| }; |
| |
| } // namespace |
| |
| |
| static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate, |
| i::Handle<i::Script> script) { |
| i::Handle<i::Object> scriptName(i::Script::GetNameOrSourceURL(script)); |
| i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate); |
| v8::Isolate* v8_isolate = |
| reinterpret_cast<v8::Isolate*>(script->GetIsolate()); |
| ScriptOriginOptions options(script->origin_options()); |
| v8::ScriptOrigin origin( |
| Utils::ToLocal(scriptName), |
| v8::Integer::New(v8_isolate, script->line_offset()), |
| v8::Integer::New(v8_isolate, script->column_offset()), |
| v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()), |
| v8::Integer::New(v8_isolate, script->id()), |
| v8::Boolean::New(v8_isolate, options.IsEmbedderDebugScript()), |
| Utils::ToLocal(source_map_url), |
| v8::Boolean::New(v8_isolate, options.IsOpaque())); |
| return origin; |
| } |
| |
| |
| // --- E x c e p t i o n B e h a v i o r --- |
| |
| |
| void i::FatalProcessOutOfMemory(const char* location) { |
| i::V8::FatalProcessOutOfMemory(location, false); |
| } |
| |
| |
| // When V8 cannot allocated memory FatalProcessOutOfMemory is called. |
| // The default fatal error handler is called and execution is stopped. |
| void i::V8::FatalProcessOutOfMemory(const char* location, bool is_heap_oom) { |
| i::Isolate* isolate = i::Isolate::Current(); |
| char last_few_messages[Heap::kTraceRingBufferSize + 1]; |
| char js_stacktrace[Heap::kStacktraceBufferSize + 1]; |
| memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1); |
| memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1); |
| |
| i::HeapStats heap_stats; |
| int start_marker; |
| heap_stats.start_marker = &start_marker; |
| int new_space_size; |
| heap_stats.new_space_size = &new_space_size; |
| int new_space_capacity; |
| heap_stats.new_space_capacity = &new_space_capacity; |
| intptr_t old_space_size; |
| heap_stats.old_space_size = &old_space_size; |
| intptr_t old_space_capacity; |
| heap_stats.old_space_capacity = &old_space_capacity; |
| intptr_t code_space_size; |
| heap_stats.code_space_size = &code_space_size; |
| intptr_t code_space_capacity; |
| heap_stats.code_space_capacity = &code_space_capacity; |
| intptr_t map_space_size; |
| heap_stats.map_space_size = &map_space_size; |
| intptr_t map_space_capacity; |
| heap_stats.map_space_capacity = &map_space_capacity; |
| intptr_t lo_space_size; |
| heap_stats.lo_space_size = &lo_space_size; |
| int global_handle_count; |
| heap_stats.global_handle_count = &global_handle_count; |
| int weak_global_handle_count; |
| heap_stats.weak_global_handle_count = &weak_global_handle_count; |
| int pending_global_handle_count; |
| heap_stats.pending_global_handle_count = &pending_global_handle_count; |
| int near_death_global_handle_count; |
| heap_stats.near_death_global_handle_count = &near_death_global_handle_count; |
| int free_global_handle_count; |
| heap_stats.free_global_handle_count = &free_global_handle_count; |
| intptr_t memory_allocator_size; |
| heap_stats.memory_allocator_size = &memory_allocator_size; |
| intptr_t memory_allocator_capacity; |
| heap_stats.memory_allocator_capacity = &memory_allocator_capacity; |
| int objects_per_type[LAST_TYPE + 1] = {0}; |
| heap_stats.objects_per_type = objects_per_type; |
| int size_per_type[LAST_TYPE + 1] = {0}; |
| heap_stats.size_per_type = size_per_type; |
| int os_error; |
| heap_stats.os_error = &os_error; |
| heap_stats.last_few_messages = last_few_messages; |
| heap_stats.js_stacktrace = js_stacktrace; |
| int end_marker; |
| heap_stats.end_marker = &end_marker; |
| if (isolate->heap()->HasBeenSetUp()) { |
| // BUG(1718): Don't use the take_snapshot since we don't support |
| // HeapIterator here without doing a special GC. |
| isolate->heap()->RecordStats(&heap_stats, false); |
| char* first_newline = strchr(last_few_messages, '\n'); |
| if (first_newline == NULL || first_newline[1] == '\0') |
| first_newline = last_few_messages; |
| PrintF("\n<--- Last few GCs --->\n%s\n", first_newline); |
| PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace); |
| } |
| Utils::ApiCheck(false, location, is_heap_oom |
| ? "Allocation failed - JavaScript heap out of memory" |
| : "Allocation failed - process out of memory"); |
| // If the fatal error handler returns, we stop execution. |
| FATAL("API fatal error handler returned after process out of memory"); |
| } |
| |
| |
| void Utils::ReportApiFailure(const char* location, const char* message) { |
| i::Isolate* isolate = i::Isolate::Current(); |
| FatalErrorCallback callback = isolate->exception_behavior(); |
| if (callback == NULL) { |
| base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location, |
| message); |
| base::OS::Abort(); |
| } else { |
| callback(location, message); |
| } |
| isolate->SignalFatalError(); |
| } |
| |
| |
| static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) { |
| if (isolate->has_scheduled_exception()) { |
| return isolate->scheduled_exception() == |
| isolate->heap()->termination_exception(); |
| } |
| return false; |
| } |
| |
| |
| void V8::SetNativesDataBlob(StartupData* natives_blob) { |
| i::V8::SetNativesBlob(natives_blob); |
| } |
| |
| |
| void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) { |
| i::V8::SetSnapshotBlob(snapshot_blob); |
| } |
| |
| namespace { |
| |
| class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { |
| public: |
| virtual void* Allocate(size_t length) { |
| void* data = AllocateUninitialized(length); |
| return data == NULL ? data : memset(data, 0, length); |
| } |
| virtual void* AllocateUninitialized(size_t length) { return malloc(length); } |
| virtual void Free(void* data, size_t) { free(data); } |
| }; |
| |
| bool RunExtraCode(Isolate* isolate, Local<Context> context, |
| const char* utf8_source, const char* name) { |
| base::ElapsedTimer timer; |
| timer.Start(); |
| Context::Scope context_scope(context); |
| TryCatch try_catch(isolate); |
| Local<String> source_string; |
| if (!String::NewFromUtf8(isolate, utf8_source, NewStringType::kNormal) |
| .ToLocal(&source_string)) { |
| return false; |
| } |
| Local<String> resource_name = |
| String::NewFromUtf8(isolate, name, NewStringType::kNormal) |
| .ToLocalChecked(); |
| ScriptOrigin origin(resource_name); |
| ScriptCompiler::Source source(source_string, origin); |
| Local<Script> script; |
| if (!ScriptCompiler::Compile(context, &source).ToLocal(&script)) return false; |
| if (script->Run(context).IsEmpty()) return false; |
| if (i::FLAG_profile_deserialization) { |
| i::PrintF("Executing custom snapshot script %s took %0.3f ms\n", name, |
| timer.Elapsed().InMillisecondsF()); |
| } |
| timer.Stop(); |
| CHECK(!try_catch.HasCaught()); |
| return true; |
| } |
| |
| struct SnapshotCreatorData { |
| explicit SnapshotCreatorData(Isolate* isolate) |
| : isolate_(isolate), |
| contexts_(isolate), |
| templates_(isolate), |
| created_(false) {} |
| |
| static SnapshotCreatorData* cast(void* data) { |
| return reinterpret_cast<SnapshotCreatorData*>(data); |
| } |
| |
| ArrayBufferAllocator allocator_; |
| Isolate* isolate_; |
| PersistentValueVector<Context> contexts_; |
| PersistentValueVector<Template> templates_; |
| bool created_; |
| }; |
| |
| } // namespace |
| |
| SnapshotCreator::SnapshotCreator(intptr_t* external_references, |
| StartupData* existing_snapshot) { |
| i::Isolate* internal_isolate = new i::Isolate(true); |
| Isolate* isolate = reinterpret_cast<Isolate*>(internal_isolate); |
| SnapshotCreatorData* data = new SnapshotCreatorData(isolate); |
| data->isolate_ = isolate; |
| internal_isolate->set_array_buffer_allocator(&data->allocator_); |
| internal_isolate->set_api_external_references(external_references); |
| isolate->Enter(); |
| if (existing_snapshot) { |
| internal_isolate->set_snapshot_blob(existing_snapshot); |
| i::Snapshot::Initialize(internal_isolate); |
| } else { |
| internal_isolate->Init(nullptr); |
| } |
| data_ = data; |
| } |
| |
| SnapshotCreator::~SnapshotCreator() { |
| SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); |
| DCHECK(data->created_); |
| Isolate* isolate = data->isolate_; |
| isolate->Exit(); |
| isolate->Dispose(); |
| delete data; |
| } |
| |
| Isolate* SnapshotCreator::GetIsolate() { |
| return SnapshotCreatorData::cast(data_)->isolate_; |
| } |
| |
| size_t SnapshotCreator::AddContext(Local<Context> context) { |
| DCHECK(!context.IsEmpty()); |
| SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); |
| DCHECK(!data->created_); |
| Isolate* isolate = data->isolate_; |
| CHECK_EQ(isolate, context->GetIsolate()); |
| size_t index = static_cast<int>(data->contexts_.Size()); |
| data->contexts_.Append(context); |
| return index; |
| } |
| |
| size_t SnapshotCreator::AddTemplate(Local<Template> template_obj) { |
| DCHECK(!template_obj.IsEmpty()); |
| SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); |
| DCHECK(!data->created_); |
| DCHECK_EQ(reinterpret_cast<i::Isolate*>(data->isolate_), |
| Utils::OpenHandle(*template_obj)->GetIsolate()); |
| size_t index = static_cast<int>(data->templates_.Size()); |
| data->templates_.Append(template_obj); |
| return index; |
| } |
| |
| StartupData SnapshotCreator::CreateBlob( |
| SnapshotCreator::FunctionCodeHandling function_code_handling) { |
| SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); |
| i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_); |
| DCHECK(!data->created_); |
| |
| { |
| int num_templates = static_cast<int>(data->templates_.Size()); |
| i::HandleScope scope(isolate); |
| i::Handle<i::FixedArray> templates = |
| isolate->factory()->NewFixedArray(num_templates, i::TENURED); |
| for (int i = 0; i < num_templates; i++) { |
| templates->set(i, *v8::Utils::OpenHandle(*data->templates_.Get(i))); |
| } |
| isolate->heap()->SetSerializedTemplates(*templates); |
| data->templates_.Clear(); |
| } |
| |
| // If we don't do this then we end up with a stray root pointing at the |
| // context even after we have disposed of the context. |
| isolate->heap()->CollectAllAvailableGarbage("mksnapshot"); |
| isolate->heap()->CompactWeakFixedArrays(); |
| |
| i::DisallowHeapAllocation no_gc_from_here_on; |
| |
| int num_contexts = static_cast<int>(data->contexts_.Size()); |
| i::List<i::Object*> contexts(num_contexts); |
| for (int i = 0; i < num_contexts; i++) { |
| i::HandleScope scope(isolate); |
| i::Handle<i::Context> context = |
| v8::Utils::OpenHandle(*data->contexts_.Get(i)); |
| contexts.Add(*context); |
| } |
| data->contexts_.Clear(); |
| |
| i::StartupSerializer startup_serializer(isolate, function_code_handling); |
| startup_serializer.SerializeStrongReferences(); |
| |
| // Serialize each context with a new partial serializer. |
| i::List<i::SnapshotData*> context_snapshots(num_contexts); |
| for (int i = 0; i < num_contexts; i++) { |
| i::PartialSerializer partial_serializer(isolate, &startup_serializer); |
| partial_serializer.Serialize(&contexts[i]); |
| context_snapshots.Add(new i::SnapshotData(&partial_serializer)); |
| } |
| |
| startup_serializer.SerializeWeakReferencesAndDeferred(); |
| i::SnapshotData startup_snapshot(&startup_serializer); |
| StartupData result = |
| i::Snapshot::CreateSnapshotBlob(&startup_snapshot, &context_snapshots); |
| |
| // Delete heap-allocated context snapshot instances. |
| for (const auto& context_snapshot : context_snapshots) { |
| delete context_snapshot; |
| } |
| data->created_ = true; |
| return result; |
| } |
| |
| StartupData V8::CreateSnapshotDataBlob(const char* embedded_source) { |
| // Create a new isolate and a new context from scratch, optionally run |
| // a script to embed, and serialize to create a snapshot blob. |
| StartupData result = {nullptr, 0}; |
| base::ElapsedTimer timer; |
| timer.Start(); |
| { |
| SnapshotCreator snapshot_creator; |
| Isolate* isolate = snapshot_creator.GetIsolate(); |
| { |
| HandleScope scope(isolate); |
| Local<Context> context = Context::New(isolate); |
| if (embedded_source != NULL && |
| !RunExtraCode(isolate, context, embedded_source, "<embedded>")) { |
| return result; |
| } |
| snapshot_creator.AddContext(context); |
| } |
| result = snapshot_creator.CreateBlob( |
| SnapshotCreator::FunctionCodeHandling::kClear); |
| } |
| |
| if (i::FLAG_profile_deserialization) { |
| i::PrintF("Creating snapshot took %0.3f ms\n", |
| timer.Elapsed().InMillisecondsF()); |
| } |
| timer.Stop(); |
| return result; |
| } |
| |
| StartupData V8::WarmUpSnapshotDataBlob(StartupData cold_snapshot_blob, |
| const char* warmup_source) { |
| CHECK(cold_snapshot_blob.raw_size > 0 && cold_snapshot_blob.data != NULL); |
| CHECK(warmup_source != NULL); |
| // Use following steps to create a warmed up snapshot blob from a cold one: |
| // - Create a new isolate from the cold snapshot. |
| // - Create a new context to run the warmup script. This will trigger |
| // compilation of executed functions. |
| // - Create a new context. This context will be unpolluted. |
| // - Serialize the isolate and the second context into a new snapshot blob. |
| StartupData result = {nullptr, 0}; |
| base::ElapsedTimer timer; |
| timer.Start(); |
| { |
| SnapshotCreator snapshot_creator(nullptr, &cold_snapshot_blob); |
| Isolate* isolate = snapshot_creator.GetIsolate(); |
| { |
| HandleScope scope(isolate); |
| Local<Context> context = Context::New(isolate); |
| if (!RunExtraCode(isolate, context, warmup_source, "<warm-up>")) { |
| return result; |
| } |
| } |
| { |
| HandleScope handle_scope(isolate); |
| isolate->ContextDisposedNotification(false); |
| Local<Context> context = Context::New(isolate); |
| snapshot_creator.AddContext(context); |
| } |
| result = snapshot_creator.CreateBlob( |
| SnapshotCreator::FunctionCodeHandling::kKeep); |
| } |
| |
| if (i::FLAG_profile_deserialization) { |
| i::PrintF("Warming up snapshot took %0.3f ms\n", |
| timer.Elapsed().InMillisecondsF()); |
| } |
| timer.Stop(); |
| return result; |
| } |
| |
| |
| void V8::SetFlagsFromString(const char* str, int length) { |
| i::FlagList::SetFlagsFromString(str, length); |
| } |
| |
| |
| void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) { |
| i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags); |
| } |
| |
| |
| RegisteredExtension* RegisteredExtension::first_extension_ = NULL; |
| |
| |
| RegisteredExtension::RegisteredExtension(Extension* extension) |
| : extension_(extension) { } |
| |
| |
| void RegisteredExtension::Register(RegisteredExtension* that) { |
| that->next_ = first_extension_; |
| first_extension_ = that; |
| } |
| |
| |
| void RegisteredExtension::UnregisterAll() { |
| RegisteredExtension* re = first_extension_; |
| while (re != NULL) { |
| RegisteredExtension* next = re->next(); |
| delete re; |
| re = next; |
| } |
| first_extension_ = NULL; |
| } |
| |
| |
| void RegisterExtension(Extension* that) { |
| RegisteredExtension* extension = new RegisteredExtension(that); |
| RegisteredExtension::Register(extension); |
| } |
| |
| |
| Extension::Extension(const char* name, |
| const char* source, |
| int dep_count, |
| const char** deps, |
| int source_length) |
| : name_(name), |
| source_length_(source_length >= 0 ? |
| source_length : |
| (source ? static_cast<int>(strlen(source)) : 0)), |
| source_(source, source_length_), |
| dep_count_(dep_count), |
| deps_(deps), |
| auto_enable_(false) { |
| CHECK(source != NULL || source_length_ == 0); |
| } |
| |
| |
| ResourceConstraints::ResourceConstraints() |
| : max_semi_space_size_(0), |
| max_old_space_size_(0), |
| max_executable_size_(0), |
| stack_limit_(NULL), |
| code_range_size_(0) { } |
| |
| void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory, |
| uint64_t virtual_memory_limit) { |
| #if V8_OS_ANDROID |
| // Android has higher physical memory requirements before raising the maximum |
| // heap size limits since it has no swap space. |
| const uint64_t low_limit = 512ul * i::MB; |
| const uint64_t medium_limit = 1ul * i::GB; |
| const uint64_t high_limit = 2ul * i::GB; |
| #else |
| const uint64_t low_limit = 512ul * i::MB; |
| const uint64_t medium_limit = 768ul * i::MB; |
| const uint64_t high_limit = 1ul * i::GB; |
| #endif |
| |
| if (physical_memory <= low_limit) { |
| set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeLowMemoryDevice); |
| set_max_old_space_size(i::Heap::kMaxOldSpaceSizeLowMemoryDevice); |
| set_max_executable_size(i::Heap::kMaxExecutableSizeLowMemoryDevice); |
| } else if (physical_memory <= medium_limit) { |
| set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeMediumMemoryDevice); |
| set_max_old_space_size(i::Heap::kMaxOldSpaceSizeMediumMemoryDevice); |
| set_max_executable_size(i::Heap::kMaxExecutableSizeMediumMemoryDevice); |
| } else if (physical_memory <= high_limit) { |
| set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHighMemoryDevice); |
| set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHighMemoryDevice); |
| set_max_executable_size(i::Heap::kMaxExecutableSizeHighMemoryDevice); |
| } else { |
| set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHugeMemoryDevice); |
| set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHugeMemoryDevice); |
| set_max_executable_size(i::Heap::kMaxExecutableSizeHugeMemoryDevice); |
| } |
| |
| if (virtual_memory_limit > 0 && i::kRequiresCodeRange) { |
| // Reserve no more than 1/8 of the memory for the code range, but at most |
| // kMaximalCodeRangeSize. |
| set_code_range_size( |
| i::Min(i::kMaximalCodeRangeSize / i::MB, |
| static_cast<size_t>((virtual_memory_limit >> 3) / i::MB))); |
| } |
| } |
| |
| |
| void SetResourceConstraints(i::Isolate* isolate, |
| const ResourceConstraints& constraints) { |
| int semi_space_size = constraints.max_semi_space_size(); |
| int old_space_size = constraints.max_old_space_size(); |
| int max_executable_size = constraints.max_executable_size(); |
| size_t code_range_size = constraints.code_range_size(); |
| if (semi_space_size != 0 || old_space_size != 0 || |
| max_executable_size != 0 || code_range_size != 0) { |
| isolate->heap()->ConfigureHeap(semi_space_size, old_space_size, |
| max_executable_size, code_range_size); |
| } |
| if (constraints.stack_limit() != NULL) { |
| uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit()); |
| isolate->stack_guard()->SetStackLimit(limit); |
| } |
| } |
| |
| |
| i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** obj) { |
| LOG_API(isolate, Persistent, New); |
| i::Handle<i::Object> result = isolate->global_handles()->Create(*obj); |
| #ifdef VERIFY_HEAP |
| if (i::FLAG_verify_heap) { |
| (*obj)->ObjectVerify(); |
| } |
| #endif // VERIFY_HEAP |
| return result.location(); |
| } |
| |
| |
| i::Object** V8::CopyPersistent(i::Object** obj) { |
| i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj); |
| #ifdef VERIFY_HEAP |
| if (i::FLAG_verify_heap) { |
| (*obj)->ObjectVerify(); |
| } |
| #endif // VERIFY_HEAP |
| return result.location(); |
| } |
| |
| void V8::RegisterExternallyReferencedObject(i::Object** object, |
| i::Isolate* isolate) { |
| isolate->heap()->RegisterExternallyReferencedObject(object); |
| } |
| |
| void V8::MakeWeak(i::Object** location, void* parameter, |
| int internal_field_index1, int internal_field_index2, |
| WeakCallbackInfo<void>::Callback weak_callback) { |
| WeakCallbackType type = WeakCallbackType::kParameter; |
| if (internal_field_index1 == 0) { |
| if (internal_field_index2 == 1) { |
| type = WeakCallbackType::kInternalFields; |
| } else { |
| DCHECK_EQ(internal_field_index2, -1); |
| type = WeakCallbackType::kInternalFields; |
| } |
| } else { |
| DCHECK_EQ(internal_field_index1, -1); |
| DCHECK_EQ(internal_field_index2, -1); |
| } |
| i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type); |
| } |
| |
| void V8::MakeWeak(i::Object** location, void* parameter, |
| WeakCallbackInfo<void>::Callback weak_callback, |
| WeakCallbackType type) { |
| i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type); |
| } |
| |
| void V8::MakeWeak(i::Object*** location_addr) { |
| i::GlobalHandles::MakeWeak(location_addr); |
| } |
| |
| void* V8::ClearWeak(i::Object** location) { |
| return i::GlobalHandles::ClearWeakness(location); |
| } |
| |
| void V8::DisposeGlobal(i::Object** location) { |
| i::GlobalHandles::Destroy(location); |
| } |
| |
| |
| void V8::Eternalize(Isolate* v8_isolate, Value* value, int* index) { |
| i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); |
| i::Object* object = *Utils::OpenHandle(value); |
| isolate->eternal_handles()->Create(isolate, object, index); |
| } |
| |
| |
| Local<Value> V8::GetEternal(Isolate* v8_isolate, int index) { |
| i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); |
| return Utils::ToLocal(isolate->eternal_handles()->Get(index)); |
| } |
| |
| |
| void V8::FromJustIsNothing() { |
| Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing."); |
| } |
| |
| |
| void V8::ToLocalEmpty() { |
| Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal."); |
| } |
| |
| |
| void V8::InternalFieldOutOfBounds(int index) { |
| Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback, |
| "WeakCallbackInfo::GetInternalField", |
| "Internal field out of bounds."); |
| } |
| |
| |
| // --- H a n d l e s --- |
| |
| |
| HandleScope::HandleScope(Isolate* isolate) { |
| Initialize(isolate); |
| } |
| |
| |
| void HandleScope::Initialize(Isolate* isolate) { |
| i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| // We do not want to check the correct usage of the Locker class all over the |
| // place, so we do it only here: Without a HandleScope, an embedder can do |
| // almost nothing, so it is enough to check in this central place. |
| // We make an exception if the serializer is enabled, which means that the |
| // Isolate is exclusively used to create a snapshot. |
| Utils::ApiCheck( |
| !v8::Locker::IsActive() || |
| internal_isolate->thread_manager()->IsLockedByCurrentThread() || |
| internal_isolate->serializer_enabled(), |
| "HandleScope::HandleScope", |
| "Entering the V8 API without proper locking in place"); |
| i::HandleScopeData* current = internal_isolate->handle_scope_data(); |
| isolate_ = internal_isolate; |
| prev_next_ = current->next; |
| prev_limit_ = current->limit; |
| current->level++; |
| } |
| |
| |
| HandleScope::~HandleScope() { |
| i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_); |
| } |
| |
| |
| int HandleScope::NumberOfHandles(Isolate* isolate) { |
| return i::HandleScope::NumberOfHandles( |
| reinterpret_cast<i::Isolate*>(isolate)); |
| } |
| |
| |
| i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) { |
| return i::HandleScope::CreateHandle(isolate, value); |
| } |
| |
| |
| i::Object** HandleScope::CreateHandle(i::HeapObject* heap_object, |
| i::Object* value) { |
| DCHECK(heap_object->IsHeapObject()); |
| return i::HandleScope::CreateHandle(heap_object->GetIsolate(), value); |
| } |
| |
| |
| EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) { |
| i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); |
| escape_slot_ = CreateHandle(isolate, isolate->heap()->the_hole_value()); |
| Initialize(v8_isolate); |
| } |
| |
| |
| i::Object** EscapableHandleScope::Escape(i::Object** escape_value) { |
| i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap(); |
| Utils::ApiCheck((*escape_slot_)->IsTheHole(heap->isolate()), |
| "EscapeableHandleScope::Escape", "Escape value set twice"); |
| if (escape_value == NULL) { |
| *escape_slot_ = heap->undefined_value(); |
| return NULL; |
| } |
| *escape_slot_ = *escape_value; |
| return escape_slot_; |
| } |
| |
| |
| SealHandleScope::SealHandleScope(Isolate* isolate) { |
| i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| |
| isolate_ = internal_isolate; |
| i::HandleScopeData* current = internal_isolate->handle_scope_data(); |
| prev_limit_ = current->limit; |
| current->limit = current->next; |
| prev_sealed_level_ = current->sealed_level; |
| current->sealed_level = current->level; |
| } |
| |
| |
| SealHandleScope::~SealHandleScope() { |
| i::HandleScopeData* current = isolate_->handle_scope_data(); |
| DCHECK_EQ(current->next, current->limit); |
| current->limit = prev_limit_; |
| DCHECK_EQ(current->level, current->sealed_level); |
| current->sealed_level = prev_sealed_level_; |
| } |
| |
| |
| void Context::Enter() { |
| i::Handle<i::Context> env = Utils::OpenHandle(this); |
| i::Isolate* isolate = env->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScopeImplementer* impl = isolate->handle_scope_implementer(); |
| impl->EnterContext(env); |
| impl->SaveContext(isolate->context()); |
| isolate->set_context(*env); |
| } |
| |
| |
| void Context::Exit() { |
| i::Handle<i::Context> env = Utils::OpenHandle(this); |
| i::Isolate* isolate = env->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScopeImplementer* impl = isolate->handle_scope_implementer(); |
| if (!Utils::ApiCheck(impl->LastEnteredContextWas(env), |
| "v8::Context::Exit()", |
| "Cannot exit non-entered context")) { |
| return; |
| } |
| impl->LeaveContext(); |
| isolate->set_context(impl->RestoreContext()); |
| } |
| |
| |
| static void* DecodeSmiToAligned(i::Object* value, const char* location) { |
| Utils::ApiCheck(value->IsSmi(), location, "Not a Smi"); |
| return reinterpret_cast<void*>(value); |
| } |
| |
| |
| static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) { |
| i::Smi* smi = reinterpret_cast<i::Smi*>(value); |
| Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned"); |
| return smi; |
| } |
| |
| |
| static i::Handle<i::FixedArray> EmbedderDataFor(Context* context, |
| int index, |
| bool can_grow, |
| const char* location) { |
| i::Handle<i::Context> env = Utils::OpenHandle(context); |
| i::Isolate* isolate = env->GetIsolate(); |
| bool ok = |
| Utils::ApiCheck(env->IsNativeContext(), |
| location, |
| "Not a native context") && |
| Utils::ApiCheck(index >= 0, location, "Negative index"); |
| if (!ok) return i::Handle<i::FixedArray>(); |
| i::Handle<i::FixedArray> data(env->embedder_data()); |
| if (index < data->length()) return data; |
| if (!Utils::ApiCheck(can_grow, location, "Index too large")) { |
| return i::Handle<i::FixedArray>(); |
| } |
| int new_size = i::Max(index, data->length() << 1) + 1; |
| int grow_by = new_size - data->length(); |
| data = isolate->factory()->CopyFixedArrayAndGrow(data, grow_by); |
| env->set_embedder_data(*data); |
| return data; |
| } |
| |
| |
| v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) { |
| const char* location = "v8::Context::GetEmbedderData()"; |
| i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location); |
| if (data.is_null()) return Local<Value>(); |
| i::Handle<i::Object> result(data->get(index), data->GetIsolate()); |
| return Utils::ToLocal(result); |
| } |
| |
| |
| void Context::SetEmbedderData(int index, v8::Local<Value> value) { |
| const char* location = "v8::Context::SetEmbedderData()"; |
| i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location); |
| if (data.is_null()) return; |
| i::Handle<i::Object> val = Utils::OpenHandle(*value); |
| data->set(index, *val); |
| DCHECK_EQ(*Utils::OpenHandle(*value), |
| *Utils::OpenHandle(*GetEmbedderData(index))); |
| } |
| |
| |
| void* Context::SlowGetAlignedPointerFromEmbedderData(int index) { |
| const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()"; |
| i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location); |
| if (data.is_null()) return NULL; |
| return DecodeSmiToAligned(data->get(index), location); |
| } |
| |
| |
| void Context::SetAlignedPointerInEmbedderData(int index, void* value) { |
| const char* location = "v8::Context::SetAlignedPointerInEmbedderData()"; |
| i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location); |
| data->set(index, EncodeAlignedAsSmi(value, location)); |
| DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index)); |
| } |
| |
| |
| // --- N e a n d e r --- |
| |
| |
| // A constructor cannot easily return an error value, therefore it is necessary |
| // to check for a dead VM with ON_BAILOUT before constructing any Neander |
| // objects. To remind you about this there is no HandleScope in the |
| // NeanderObject constructor. When you add one to the site calling the |
| // constructor you should check that you ensured the VM was not dead first. |
| NeanderObject::NeanderObject(v8::internal::Isolate* isolate, int size) { |
| ENTER_V8(isolate); |
| value_ = isolate->factory()->NewNeanderObject(); |
| i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size); |
| value_->set_elements(*elements); |
| } |
| |
| |
| int NeanderObject::size() { |
| return i::FixedArray::cast(value_->elements())->length(); |
| } |
| |
| |
| NeanderArray::NeanderArray(v8::internal::Isolate* isolate) : obj_(isolate, 2) { |
| obj_.set(0, i::Smi::FromInt(0)); |
| } |
| |
| |
| int NeanderArray::length() { |
| return i::Smi::cast(obj_.get(0))->value(); |
| } |
| |
| |
| i::Object* NeanderArray::get(int offset) { |
| DCHECK_LE(0, offset); |
| DCHECK_LT(offset, length()); |
| return obj_.get(offset + 1); |
| } |
| |
| |
| // This method cannot easily return an error value, therefore it is necessary |
| // to check for a dead VM with ON_BAILOUT before calling it. To remind you |
| // about this there is no HandleScope in this method. When you add one to the |
| // site calling this method you should check that you ensured the VM was not |
| // dead first. |
| void NeanderArray::add(i::Isolate* isolate, i::Handle<i::Object> value) { |
| int length = this->length(); |
| int size = obj_.size(); |
| if (length == size - 1) { |
| i::Factory* factory = isolate->factory(); |
| i::Handle<i::FixedArray> new_elms = factory->NewFixedArray(2 * size); |
| for (int i = 0; i < length; i++) |
| new_elms->set(i + 1, get(i)); |
| obj_.value()->set_elements(*new_elms); |
| } |
| obj_.set(length + 1, *value); |
| obj_.set(0, i::Smi::FromInt(length + 1)); |
| } |
| |
| |
| void NeanderArray::set(int index, i::Object* value) { |
| if (index < 0 || index >= this->length()) return; |
| obj_.set(index + 1, value); |
| } |
| |
| |
| // --- T e m p l a t e --- |
| |
| |
| static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) { |
| that->set_number_of_properties(0); |
| that->set_tag(i::Smi::FromInt(type)); |
| } |
| |
| |
| void Template::Set(v8::Local<Name> name, v8::Local<Data> value, |
| v8::PropertyAttribute attribute) { |
| auto templ = Utils::OpenHandle(this); |
| i::Isolate* isolate = templ->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto value_obj = Utils::OpenHandle(*value); |
| CHECK(!value_obj->IsJSReceiver() || value_obj->IsTemplateInfo()); |
| if (value_obj->IsObjectTemplateInfo()) { |
| templ->set_serial_number(i::Smi::FromInt(0)); |
| if (templ->IsFunctionTemplateInfo()) { |
| i::Handle<i::FunctionTemplateInfo>::cast(templ)->set_do_not_cache(true); |
| } |
| } |
| i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name), |
| value_obj, |
| static_cast<i::PropertyAttributes>(attribute)); |
| } |
| |
| |
| void Template::SetAccessorProperty( |
| v8::Local<v8::Name> name, |
| v8::Local<FunctionTemplate> getter, |
| v8::Local<FunctionTemplate> setter, |
| v8::PropertyAttribute attribute, |
| v8::AccessControl access_control) { |
| // TODO(verwaest): Remove |access_control|. |
| DCHECK_EQ(v8::DEFAULT, access_control); |
| auto templ = Utils::OpenHandle(this); |
| auto isolate = templ->GetIsolate(); |
| ENTER_V8(isolate); |
| DCHECK(!name.IsEmpty()); |
| DCHECK(!getter.IsEmpty() || !setter.IsEmpty()); |
| i::HandleScope scope(isolate); |
| i::ApiNatives::AddAccessorProperty( |
| isolate, templ, Utils::OpenHandle(*name), |
| Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true), |
| static_cast<i::PropertyAttributes>(attribute)); |
| } |
| |
| |
| // --- F u n c t i o n T e m p l a t e --- |
| static void InitializeFunctionTemplate( |
| i::Handle<i::FunctionTemplateInfo> info) { |
| InitializeTemplate(info, Consts::FUNCTION_TEMPLATE); |
| info->set_flag(0); |
| } |
| |
| static Local<ObjectTemplate> ObjectTemplateNew( |
| i::Isolate* isolate, v8::Local<FunctionTemplate> constructor, |
| bool do_not_cache); |
| |
| Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() { |
| i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(i_isolate); |
| i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(), |
| i_isolate); |
| if (result->IsUndefined(i_isolate)) { |
| // Do not cache prototype objects. |
| result = Utils::OpenHandle( |
| *ObjectTemplateNew(i_isolate, Local<FunctionTemplate>(), true)); |
| Utils::OpenHandle(this)->set_prototype_template(*result); |
| } |
| return ToApiHandle<ObjectTemplate>(result); |
| } |
| |
| |
| static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info, |
| const char* func) { |
| Utils::ApiCheck(!info->instantiated(), func, |
| "FunctionTemplate already instantiated"); |
| } |
| |
| |
| void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit"); |
| i::Isolate* isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| info->set_parent_template(*Utils::OpenHandle(*value)); |
| } |
| |
| |
| static Local<FunctionTemplate> FunctionTemplateNew( |
| i::Isolate* isolate, FunctionCallback callback, |
| experimental::FastAccessorBuilder* fast_handler, v8::Local<Value> data, |
| v8::Local<Signature> signature, int length, bool do_not_cache) { |
| i::Handle<i::Struct> struct_obj = |
| isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE); |
| i::Handle<i::FunctionTemplateInfo> obj = |
| i::Handle<i::FunctionTemplateInfo>::cast(struct_obj); |
| InitializeFunctionTemplate(obj); |
| obj->set_do_not_cache(do_not_cache); |
| int next_serial_number = 0; |
| if (!do_not_cache) { |
| next_serial_number = isolate->heap()->GetNextTemplateSerialNumber(); |
| } |
| obj->set_serial_number(i::Smi::FromInt(next_serial_number)); |
| if (callback != 0) { |
| if (data.IsEmpty()) { |
| data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); |
| } |
| Utils::ToLocal(obj)->SetCallHandler(callback, data, fast_handler); |
| } |
| obj->set_length(length); |
| obj->set_undetectable(false); |
| obj->set_needs_access_check(false); |
| obj->set_accept_any_receiver(true); |
| if (!signature.IsEmpty()) |
| obj->set_signature(*Utils::OpenHandle(*signature)); |
| return Utils::ToLocal(obj); |
| } |
| |
| |
| Local<FunctionTemplate> FunctionTemplate::New(Isolate* isolate, |
| FunctionCallback callback, |
| v8::Local<Value> data, |
| v8::Local<Signature> signature, |
| int length) { |
| i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| // Changes to the environment cannot be captured in the snapshot. Expect no |
| // function templates when the isolate is created for serialization. |
| LOG_API(i_isolate, FunctionTemplate, New); |
| ENTER_V8(i_isolate); |
| return FunctionTemplateNew(i_isolate, callback, nullptr, data, signature, |
| length, false); |
| } |
| |
| MaybeLocal<FunctionTemplate> FunctionTemplate::FromSnapshot(Isolate* isolate, |
| size_t index) { |
| i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| i::FixedArray* templates = i_isolate->heap()->serialized_templates(); |
| int int_index = static_cast<int>(index); |
| if (int_index < templates->length()) { |
| i::Object* info = templates->get(int_index); |
| if (info->IsFunctionTemplateInfo()) { |
| return Utils::ToLocal(i::Handle<i::FunctionTemplateInfo>( |
| i::FunctionTemplateInfo::cast(info))); |
| } |
| } |
| return Local<FunctionTemplate>(); |
| } |
| |
| Local<FunctionTemplate> FunctionTemplate::NewWithFastHandler( |
| Isolate* isolate, FunctionCallback callback, |
| experimental::FastAccessorBuilder* fast_handler, v8::Local<Value> data, |
| v8::Local<Signature> signature, int length) { |
| i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| DCHECK(!i_isolate->serializer_enabled()); |
| LOG_API(i_isolate, FunctionTemplate, NewWithFastHandler); |
| ENTER_V8(i_isolate); |
| return FunctionTemplateNew(i_isolate, callback, fast_handler, data, signature, |
| length, false); |
| } |
| |
| |
| Local<Signature> Signature::New(Isolate* isolate, |
| Local<FunctionTemplate> receiver) { |
| return Utils::SignatureToLocal(Utils::OpenHandle(*receiver)); |
| } |
| |
| |
| Local<AccessorSignature> AccessorSignature::New( |
| Isolate* isolate, Local<FunctionTemplate> receiver) { |
| return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver)); |
| } |
| |
| |
| #define SET_FIELD_WRAPPED(obj, setter, cdata) do { \ |
| i::Handle<i::Object> foreign = FromCData(obj->GetIsolate(), cdata); \ |
| (obj)->setter(*foreign); \ |
| } while (false) |
| |
| |
| void FunctionTemplate::SetCallHandler( |
| FunctionCallback callback, v8::Local<Value> data, |
| experimental::FastAccessorBuilder* fast_handler) { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler"); |
| i::Isolate* isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| i::Handle<i::Struct> struct_obj = |
| isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE); |
| i::Handle<i::CallHandlerInfo> obj = |
| i::Handle<i::CallHandlerInfo>::cast(struct_obj); |
| SET_FIELD_WRAPPED(obj, set_callback, callback); |
| i::MaybeHandle<i::Code> code = |
| i::experimental::BuildCodeFromFastAccessorBuilder(fast_handler); |
| if (!code.is_null()) { |
| obj->set_fast_handler(*code.ToHandleChecked()); |
| } |
| if (data.IsEmpty()) { |
| data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); |
| } |
| obj->set_data(*Utils::OpenHandle(*data)); |
| info->set_call_code(*obj); |
| } |
| |
| |
| static i::Handle<i::AccessorInfo> SetAccessorInfoProperties( |
| i::Handle<i::AccessorInfo> obj, v8::Local<Name> name, |
| v8::AccessControl settings, v8::PropertyAttribute attributes, |
| v8::Local<AccessorSignature> signature) { |
| obj->set_name(*Utils::OpenHandle(*name)); |
| if (settings & ALL_CAN_READ) obj->set_all_can_read(true); |
| if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true); |
| obj->set_property_attributes(static_cast<i::PropertyAttributes>(attributes)); |
| if (!signature.IsEmpty()) { |
| obj->set_expected_receiver_type(*Utils::OpenHandle(*signature)); |
| } |
| return obj; |
| } |
| |
| namespace { |
| |
| template <typename Getter, typename Setter> |
| i::Handle<i::AccessorInfo> MakeAccessorInfo( |
| v8::Local<Name> name, Getter getter, Setter setter, v8::Local<Value> data, |
| v8::AccessControl settings, v8::PropertyAttribute attributes, |
| v8::Local<AccessorSignature> signature, bool is_special_data_property) { |
| i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate(); |
| i::Handle<i::AccessorInfo> obj = isolate->factory()->NewAccessorInfo(); |
| SET_FIELD_WRAPPED(obj, set_getter, getter); |
| if (is_special_data_property && setter == nullptr) { |
| setter = reinterpret_cast<Setter>(&i::Accessors::ReconfigureToDataProperty); |
| } |
| SET_FIELD_WRAPPED(obj, set_setter, setter); |
| i::Address redirected = obj->redirected_getter(); |
| if (redirected != nullptr) SET_FIELD_WRAPPED(obj, set_js_getter, redirected); |
| if (data.IsEmpty()) { |
| data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); |
| } |
| obj->set_data(*Utils::OpenHandle(*data)); |
| obj->set_is_special_data_property(is_special_data_property); |
| return SetAccessorInfoProperties(obj, name, settings, attributes, signature); |
| } |
| |
| } // namespace |
| |
| Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() { |
| i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true); |
| if (!Utils::ApiCheck(!handle.is_null(), |
| "v8::FunctionTemplate::InstanceTemplate()", |
| "Reading from empty handle")) { |
| return Local<ObjectTemplate>(); |
| } |
| i::Isolate* isolate = handle->GetIsolate(); |
| ENTER_V8(isolate); |
| if (handle->instance_template()->IsUndefined(isolate)) { |
| Local<ObjectTemplate> templ = |
| ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle)); |
| handle->set_instance_template(*Utils::OpenHandle(*templ)); |
| } |
| i::Handle<i::ObjectTemplateInfo> result( |
| i::ObjectTemplateInfo::cast(handle->instance_template())); |
| return Utils::ToLocal(result); |
| } |
| |
| |
| void FunctionTemplate::SetLength(int length) { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength"); |
| auto isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| info->set_length(length); |
| } |
| |
| |
| void FunctionTemplate::SetClassName(Local<String> name) { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName"); |
| auto isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| info->set_class_name(*Utils::OpenHandle(*name)); |
| } |
| |
| |
| void FunctionTemplate::SetAcceptAnyReceiver(bool value) { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver"); |
| auto isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| info->set_accept_any_receiver(value); |
| } |
| |
| |
| void FunctionTemplate::SetHiddenPrototype(bool value) { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype"); |
| auto isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| info->set_hidden_prototype(value); |
| } |
| |
| |
| void FunctionTemplate::ReadOnlyPrototype() { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype"); |
| auto isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| info->set_read_only_prototype(true); |
| } |
| |
| |
| void FunctionTemplate::RemovePrototype() { |
| auto info = Utils::OpenHandle(this); |
| EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype"); |
| auto isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| info->set_remove_prototype(true); |
| } |
| |
| |
| // --- O b j e c t T e m p l a t e --- |
| |
| |
| Local<ObjectTemplate> ObjectTemplate::New( |
| Isolate* isolate, v8::Local<FunctionTemplate> constructor) { |
| return New(reinterpret_cast<i::Isolate*>(isolate), constructor); |
| } |
| |
| |
| Local<ObjectTemplate> ObjectTemplate::New() { |
| return New(i::Isolate::Current(), Local<FunctionTemplate>()); |
| } |
| |
| static Local<ObjectTemplate> ObjectTemplateNew( |
| i::Isolate* isolate, v8::Local<FunctionTemplate> constructor, |
| bool do_not_cache) { |
| LOG_API(isolate, ObjectTemplate, New); |
| ENTER_V8(isolate); |
| i::Handle<i::Struct> struct_obj = |
| isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE); |
| i::Handle<i::ObjectTemplateInfo> obj = |
| i::Handle<i::ObjectTemplateInfo>::cast(struct_obj); |
| InitializeTemplate(obj, Consts::OBJECT_TEMPLATE); |
| int next_serial_number = 0; |
| if (!do_not_cache) { |
| next_serial_number = isolate->heap()->GetNextTemplateSerialNumber(); |
| } |
| obj->set_serial_number(i::Smi::FromInt(next_serial_number)); |
| if (!constructor.IsEmpty()) |
| obj->set_constructor(*Utils::OpenHandle(*constructor)); |
| obj->set_internal_field_count(i::Smi::FromInt(0)); |
| return Utils::ToLocal(obj); |
| } |
| |
| Local<ObjectTemplate> ObjectTemplate::New( |
| i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) { |
| return ObjectTemplateNew(isolate, constructor, false); |
| } |
| |
| MaybeLocal<ObjectTemplate> ObjectTemplate::FromSnapshot(Isolate* isolate, |
| size_t index) { |
| i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| i::FixedArray* templates = i_isolate->heap()->serialized_templates(); |
| int int_index = static_cast<int>(index); |
| if (int_index < templates->length()) { |
| i::Object* info = templates->get(int_index); |
| if (info->IsObjectTemplateInfo()) { |
| return Utils::ToLocal( |
| i::Handle<i::ObjectTemplateInfo>(i::ObjectTemplateInfo::cast(info))); |
| } |
| } |
| return Local<ObjectTemplate>(); |
| } |
| |
| // Ensure that the object template has a constructor. If no |
| // constructor is available we create one. |
| static i::Handle<i::FunctionTemplateInfo> EnsureConstructor( |
| i::Isolate* isolate, |
| ObjectTemplate* object_template) { |
| i::Object* obj = Utils::OpenHandle(object_template)->constructor(); |
| if (!obj->IsUndefined(isolate)) { |
| i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj); |
| return i::Handle<i::FunctionTemplateInfo>(info, isolate); |
| } |
| Local<FunctionTemplate> templ = |
| FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate)); |
| i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ); |
| constructor->set_instance_template(*Utils::OpenHandle(object_template)); |
| Utils::OpenHandle(object_template)->set_constructor(*constructor); |
| return constructor; |
| } |
| |
| |
| template <typename Getter, typename Setter, typename Data, typename Template> |
| static bool TemplateSetAccessor(Template* template_obj, v8::Local<Name> name, |
| Getter getter, Setter setter, Data data, |
| AccessControl settings, |
| PropertyAttribute attribute, |
| v8::Local<AccessorSignature> signature, |
| bool is_special_data_property) { |
| auto info = Utils::OpenHandle(template_obj); |
| auto isolate = info->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto obj = MakeAccessorInfo(name, getter, setter, data, settings, attribute, |
| signature, is_special_data_property); |
| if (obj.is_null()) return false; |
| i::ApiNatives::AddNativeDataProperty(isolate, info, obj); |
| return true; |
| } |
| |
| |
| void Template::SetNativeDataProperty(v8::Local<String> name, |
| AccessorGetterCallback getter, |
| AccessorSetterCallback setter, |
| v8::Local<Value> data, |
| PropertyAttribute attribute, |
| v8::Local<AccessorSignature> signature, |
| AccessControl settings) { |
| TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, |
| signature, true); |
| } |
| |
| |
| void Template::SetNativeDataProperty(v8::Local<Name> name, |
| AccessorNameGetterCallback getter, |
| AccessorNameSetterCallback setter, |
| v8::Local<Value> data, |
| PropertyAttribute attribute, |
| v8::Local<AccessorSignature> signature, |
| AccessControl settings) { |
| TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, |
| signature, true); |
| } |
| |
| |
| void Template::SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic, |
| PropertyAttribute attribute) { |
| auto templ = Utils::OpenHandle(this); |
| i::Isolate* isolate = templ->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name), |
| intrinsic, |
| static_cast<i::PropertyAttributes>(attribute)); |
| } |
| |
| |
| void ObjectTemplate::SetAccessor(v8::Local<String> name, |
| AccessorGetterCallback getter, |
| AccessorSetterCallback setter, |
| v8::Local<Value> data, AccessControl settings, |
| PropertyAttribute attribute, |
| v8::Local<AccessorSignature> signature) { |
| TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, |
| signature, i::FLAG_disable_old_api_accessors); |
| } |
| |
| |
| void ObjectTemplate::SetAccessor(v8::Local<Name> name, |
| AccessorNameGetterCallback getter, |
| AccessorNameSetterCallback setter, |
| v8::Local<Value> data, AccessControl settings, |
| PropertyAttribute attribute, |
| v8::Local<AccessorSignature> signature) { |
| TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, |
| signature, i::FLAG_disable_old_api_accessors); |
| } |
| |
| template <typename Getter, typename Setter, typename Query, typename Deleter, |
| typename Enumerator> |
| static i::Handle<i::InterceptorInfo> CreateInterceptorInfo( |
| i::Isolate* isolate, Getter getter, Setter setter, Query query, |
| Deleter remover, Enumerator enumerator, Local<Value> data, |
| PropertyHandlerFlags flags) { |
| auto obj = i::Handle<i::InterceptorInfo>::cast( |
| isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE)); |
| obj->set_flags(0); |
| |
| if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter); |
| if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter); |
| if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query); |
| if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover); |
| if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator); |
| obj->set_can_intercept_symbols( |
| !(static_cast<int>(flags) & |
| static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings))); |
| obj->set_all_can_read(static_cast<int>(flags) & |
| static_cast<int>(PropertyHandlerFlags::kAllCanRead)); |
| obj->set_non_masking(static_cast<int>(flags) & |
| static_cast<int>(PropertyHandlerFlags::kNonMasking)); |
| |
| if (data.IsEmpty()) { |
| data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); |
| } |
| obj->set_data(*Utils::OpenHandle(*data)); |
| return obj; |
| } |
| |
| template <typename Getter, typename Setter, typename Query, typename Deleter, |
| typename Enumerator> |
| static void ObjectTemplateSetNamedPropertyHandler(ObjectTemplate* templ, |
| Getter getter, Setter setter, |
| Query query, Deleter remover, |
| Enumerator enumerator, |
| Local<Value> data, |
| PropertyHandlerFlags flags) { |
| i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto cons = EnsureConstructor(isolate, templ); |
| EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler"); |
| auto obj = CreateInterceptorInfo(isolate, getter, setter, query, remover, |
| enumerator, data, flags); |
| cons->set_named_property_handler(*obj); |
| } |
| |
| |
| void ObjectTemplate::SetNamedPropertyHandler( |
| NamedPropertyGetterCallback getter, NamedPropertySetterCallback setter, |
| NamedPropertyQueryCallback query, NamedPropertyDeleterCallback remover, |
| NamedPropertyEnumeratorCallback enumerator, Local<Value> data) { |
| ObjectTemplateSetNamedPropertyHandler( |
| this, getter, setter, query, remover, enumerator, data, |
| PropertyHandlerFlags::kOnlyInterceptStrings); |
| } |
| |
| |
| void ObjectTemplate::SetHandler( |
| const NamedPropertyHandlerConfiguration& config) { |
| ObjectTemplateSetNamedPropertyHandler( |
| this, config.getter, config.setter, config.query, config.deleter, |
| config.enumerator, config.data, config.flags); |
| } |
| |
| |
| void ObjectTemplate::MarkAsUndetectable() { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto cons = EnsureConstructor(isolate, this); |
| EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable"); |
| cons->set_undetectable(true); |
| } |
| |
| |
| void ObjectTemplate::SetAccessCheckCallback(AccessCheckCallback callback, |
| Local<Value> data) { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto cons = EnsureConstructor(isolate, this); |
| EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallback"); |
| |
| i::Handle<i::Struct> struct_info = |
| isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE); |
| i::Handle<i::AccessCheckInfo> info = |
| i::Handle<i::AccessCheckInfo>::cast(struct_info); |
| |
| SET_FIELD_WRAPPED(info, set_callback, callback); |
| info->set_named_interceptor(nullptr); |
| info->set_indexed_interceptor(nullptr); |
| |
| if (data.IsEmpty()) { |
| data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); |
| } |
| info->set_data(*Utils::OpenHandle(*data)); |
| |
| cons->set_access_check_info(*info); |
| cons->set_needs_access_check(true); |
| } |
| |
| void ObjectTemplate::SetAccessCheckCallbackAndHandler( |
| AccessCheckCallback callback, |
| const NamedPropertyHandlerConfiguration& named_handler, |
| const IndexedPropertyHandlerConfiguration& indexed_handler, |
| Local<Value> data) { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto cons = EnsureConstructor(isolate, this); |
| EnsureNotInstantiated( |
| cons, "v8::ObjectTemplate::SetAccessCheckCallbackWithHandler"); |
| |
| i::Handle<i::Struct> struct_info = |
| isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE); |
| i::Handle<i::AccessCheckInfo> info = |
| i::Handle<i::AccessCheckInfo>::cast(struct_info); |
| |
| SET_FIELD_WRAPPED(info, set_callback, callback); |
| auto named_interceptor = CreateInterceptorInfo( |
| isolate, named_handler.getter, named_handler.setter, named_handler.query, |
| named_handler.deleter, named_handler.enumerator, named_handler.data, |
| named_handler.flags); |
| info->set_named_interceptor(*named_interceptor); |
| auto indexed_interceptor = CreateInterceptorInfo( |
| isolate, indexed_handler.getter, indexed_handler.setter, |
| indexed_handler.query, indexed_handler.deleter, |
| indexed_handler.enumerator, indexed_handler.data, indexed_handler.flags); |
| info->set_indexed_interceptor(*indexed_interceptor); |
| |
| if (data.IsEmpty()) { |
| data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); |
| } |
| info->set_data(*Utils::OpenHandle(*data)); |
| |
| cons->set_access_check_info(*info); |
| cons->set_needs_access_check(true); |
| } |
| |
| void ObjectTemplate::SetHandler( |
| const IndexedPropertyHandlerConfiguration& config) { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto cons = EnsureConstructor(isolate, this); |
| EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler"); |
| auto obj = CreateInterceptorInfo( |
| isolate, config.getter, config.setter, config.query, config.deleter, |
| config.enumerator, config.data, config.flags); |
| cons->set_indexed_property_handler(*obj); |
| } |
| |
| |
| void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback, |
| Local<Value> data) { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| auto cons = EnsureConstructor(isolate, this); |
| EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler"); |
| i::Handle<i::Struct> struct_obj = |
| isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE); |
| i::Handle<i::CallHandlerInfo> obj = |
| i::Handle<i::CallHandlerInfo>::cast(struct_obj); |
| SET_FIELD_WRAPPED(obj, set_callback, callback); |
| if (data.IsEmpty()) { |
| data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); |
| } |
| obj->set_data(*Utils::OpenHandle(*data)); |
| cons->set_instance_call_handler(*obj); |
| } |
| |
| |
| int ObjectTemplate::InternalFieldCount() { |
| return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value(); |
| } |
| |
| |
| void ObjectTemplate::SetInternalFieldCount(int value) { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| if (!Utils::ApiCheck(i::Smi::IsValid(value), |
| "v8::ObjectTemplate::SetInternalFieldCount()", |
| "Invalid internal field count")) { |
| return; |
| } |
| ENTER_V8(isolate); |
| if (value > 0) { |
| // The internal field count is set by the constructor function's |
| // construct code, so we ensure that there is a constructor |
| // function to do the setting. |
| EnsureConstructor(isolate, this); |
| } |
| Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value)); |
| } |
| |
| |
| // --- S c r i p t s --- |
| |
| |
| // Internally, UnboundScript is a SharedFunctionInfo, and Script is a |
| // JSFunction. |
| |
| ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_, |
| BufferPolicy buffer_policy_) |
| : data(data_), |
| length(length_), |
| rejected(false), |
| buffer_policy(buffer_policy_) {} |
| |
| |
| ScriptCompiler::CachedData::~CachedData() { |
| if (buffer_policy == BufferOwned) { |
| delete[] data; |
| } |
| } |
| |
| |
| bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; } |
| |
| |
| void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); } |
| |
| |
| ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream, |
| Encoding encoding) |
| : impl_(new i::StreamedSource(stream, encoding)) {} |
| |
| |
| ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; } |
| |
| |
| const ScriptCompiler::CachedData* |
| ScriptCompiler::StreamedSource::GetCachedData() const { |
| return impl_->cached_data.get(); |
| } |
| |
| |
| Local<Script> UnboundScript::BindToCurrentContext() { |
| i::Handle<i::HeapObject> obj = |
| i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this)); |
| i::Handle<i::SharedFunctionInfo> |
| function_info(i::SharedFunctionInfo::cast(*obj), obj->GetIsolate()); |
| i::Isolate* isolate = obj->GetIsolate(); |
| |
| i::Handle<i::JSReceiver> global(isolate->native_context()->global_object()); |
| i::Handle<i::JSFunction> function = |
| obj->GetIsolate()->factory()->NewFunctionFromSharedFunctionInfo( |
| function_info, isolate->native_context()); |
| return ToApiHandle<Script>(function); |
| } |
| |
| |
| int UnboundScript::GetId() { |
| i::Handle<i::HeapObject> obj = |
| i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this)); |
| i::Isolate* isolate = obj->GetIsolate(); |
| LOG_API(isolate, UnboundScript, GetId); |
| i::HandleScope scope(isolate); |
| i::Handle<i::SharedFunctionInfo> function_info( |
| i::SharedFunctionInfo::cast(*obj)); |
| i::Handle<i::Script> script(i::Script::cast(function_info->script())); |
| return script->id(); |
| } |
| |
| |
| int UnboundScript::GetLineNumber(int code_pos) { |
| i::Handle<i::SharedFunctionInfo> obj = |
| i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); |
| i::Isolate* isolate = obj->GetIsolate(); |
| LOG_API(isolate, UnboundScript, GetLineNumber); |
| if (obj->script()->IsScript()) { |
| i::Handle<i::Script> script(i::Script::cast(obj->script())); |
| return i::Script::GetLineNumber(script, code_pos); |
| } else { |
| return -1; |
| } |
| } |
| |
| |
| Local<Value> UnboundScript::GetScriptName() { |
| i::Handle<i::SharedFunctionInfo> obj = |
| i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); |
| i::Isolate* isolate = obj->GetIsolate(); |
| LOG_API(isolate, UnboundScript, GetName); |
| if (obj->script()->IsScript()) { |
| i::Object* name = i::Script::cast(obj->script())->name(); |
| return Utils::ToLocal(i::Handle<i::Object>(name, isolate)); |
| } else { |
| return Local<String>(); |
| } |
| } |
| |
| |
| Local<Value> UnboundScript::GetSourceURL() { |
| i::Handle<i::SharedFunctionInfo> obj = |
| i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); |
| i::Isolate* isolate = obj->GetIsolate(); |
| LOG_API(isolate, UnboundScript, GetSourceURL); |
| if (obj->script()->IsScript()) { |
| i::Object* url = i::Script::cast(obj->script())->source_url(); |
| return Utils::ToLocal(i::Handle<i::Object>(url, isolate)); |
| } else { |
| return Local<String>(); |
| } |
| } |
| |
| |
| Local<Value> UnboundScript::GetSourceMappingURL() { |
| i::Handle<i::SharedFunctionInfo> obj = |
| i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); |
| i::Isolate* isolate = obj->GetIsolate(); |
| LOG_API(isolate, UnboundScript, GetSourceMappingURL); |
| if (obj->script()->IsScript()) { |
| i::Object* url = i::Script::cast(obj->script())->source_mapping_url(); |
| return Utils::ToLocal(i::Handle<i::Object>(url, isolate)); |
| } else { |
| return Local<String>(); |
| } |
| } |
| |
| |
| MaybeLocal<Value> Script::Run(Local<Context> context) { |
| PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, Script, Run, Value) |
| i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true); |
| i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy()); |
| i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate); |
| TRACE_EVENT0("v8", "V8.Execute"); |
| auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this)); |
| i::Handle<i::Object> receiver = isolate->global_proxy(); |
| Local<Value> result; |
| has_pending_exception = |
| !ToLocal<Value>(i::Execution::Call(isolate, fun, receiver, 0, NULL), |
| &result); |
| RETURN_ON_FAILED_EXECUTION(Value); |
| RETURN_ESCAPED(result); |
| } |
| |
| |
| Local<Value> Script::Run() { |
| auto self = Utils::OpenHandle(this, true); |
| // If execution is terminating, Compile(..)->Run() requires this |
| // check. |
| if (self.is_null()) return Local<Value>(); |
| auto context = ContextFromHeapObject(self); |
| RETURN_TO_LOCAL_UNCHECKED(Run(context), Value); |
| } |
| |
| |
| Local<UnboundScript> Script::GetUnboundScript() { |
| i::Handle<i::Object> obj = Utils::OpenHandle(this); |
| return ToApiHandle<UnboundScript>( |
| i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared())); |
| } |
| |
| |
| MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal( |
| Isolate* v8_isolate, Source* source, CompileOptions options, |
| bool is_module) { |
| i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); |
| PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, ScriptCompiler, CompileUnbound, |
| UnboundScript); |
| |
| // Don't try to produce any kind of cache when the debugger is loaded. |
| if (isolate->debug()->is_loaded() && |
| (options == kProduceParserCache || options == kProduceCodeCache)) { |
| options = kNoCompileOptions; |
| } |
| |
| i::ScriptData* script_data = NULL; |
| if (options == kConsumeParserCache || options == kConsumeCodeCache) { |
| DCHECK(source->cached_data); |
| // ScriptData takes care of pointer-aligning the data. |
| script_data = new i::ScriptData(source->cached_data->data, |
| source->cached_data->length); |
| } |
| |
| i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string)); |
| i::Handle<i::SharedFunctionInfo> result; |
| { |
| i::HistogramTimerScope total(isolate->counters()->compile_script(), true); |
| TRACE_EVENT0("v8", "V8.CompileScript"); |
| i::Handle<i::Object> name_obj; |
| i::Handle<i::Object> source_map_url; |
| int line_offset = 0; |
| int column_offset = 0; |
| if (!source->resource_name.IsEmpty()) { |
| name_obj = Utils::OpenHandle(*(source->resource_name)); |
| } |
| if (!source->resource_line_offset.IsEmpty()) { |
| line_offset = static_cast<int>(source->resource_line_offset->Value()); |
| } |
| if (!source->resource_column_offset.IsEmpty()) { |
| column_offset = |
| static_cast<int>(source->resource_column_offset->Value()); |
| } |
| if (!source->source_map_url.IsEmpty()) { |
| source_map_url = Utils::OpenHandle(*(source->source_map_url)); |
| } |
| result = i::Compiler::GetSharedFunctionInfoForScript( |
| str, name_obj, line_offset, column_offset, source->resource_options, |
| source_map_url, isolate->native_context(), NULL, &script_data, options, |
| i::NOT_NATIVES_CODE, is_module); |
| has_pending_exception = result.is_null(); |
| if (has_pending_exception && script_data != NULL) { |
| // This case won't happen during normal operation; we have compiled |
| // successfully and produced cached data, and but the second compilation |
| // of the same source code fails. |
| delete script_data; |
| script_data = NULL; |
| } |
| RETURN_ON_FAILED_EXECUTION(UnboundScript); |
| |
| if ((options == kProduceParserCache || options == kProduceCodeCache) && |
| script_data != NULL) { |
| // script_data now contains the data that was generated. source will |
| // take the ownership. |
| source->cached_data = new CachedData( |
| script_data->data(), script_data->length(), CachedData::BufferOwned); |
| script_data->ReleaseDataOwnership(); |
| } else if (options == kConsumeParserCache || options == kConsumeCodeCache) { |
| source->cached_data->rejected = script_data->rejected(); |
| } |
| delete script_data; |
| } |
| RETURN_ESCAPED(ToApiHandle<UnboundScript>(result)); |
| } |
| |
| |
| MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript( |
| Isolate* v8_isolate, Source* source, CompileOptions options) { |
| return CompileUnboundInternal(v8_isolate, source, options, false); |
| } |
| |
| |
| Local<UnboundScript> ScriptCompiler::CompileUnbound(Isolate* v8_isolate, |
| Source* source, |
| CompileOptions options) { |
| RETURN_TO_LOCAL_UNCHECKED( |
| CompileUnboundInternal(v8_isolate, source, options, false), |
| UnboundScript); |
| } |
| |
| |
| MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context, |
| Source* source, |
| CompileOptions options) { |
| auto isolate = context->GetIsolate(); |
| auto maybe = CompileUnboundInternal(isolate, source, options, false); |
| Local<UnboundScript> result; |
| if (!maybe.ToLocal(&result)) return MaybeLocal<Script>(); |
| v8::Context::Scope scope(context); |
| return result->BindToCurrentContext(); |
| } |
| |
| |
| Local<Script> ScriptCompiler::Compile( |
| Isolate* v8_isolate, |
| Source* source, |
| CompileOptions options) { |
| auto context = v8_isolate->GetCurrentContext(); |
| RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, options), Script); |
| } |
| |
| |
| MaybeLocal<Script> ScriptCompiler::CompileModule(Local<Context> context, |
| Source* source, |
| CompileOptions options) { |
| auto isolate = context->GetIsolate(); |
| auto maybe = CompileUnboundInternal(isolate, source, options, true); |
| Local<UnboundScript> generic; |
| if (!maybe.ToLocal(&generic)) return MaybeLocal<Script>(); |
| v8::Context::Scope scope(context); |
| return generic->BindToCurrentContext(); |
| } |
| |
| |
| class IsIdentifierHelper { |
| public: |
| IsIdentifierHelper() : is_identifier_(false), first_char_(true) {} |
| |
| bool Check(i::String* string) { |
| i::ConsString* cons_string = i::String::VisitFlat(this, string, 0); |
| if (cons_string == NULL) return is_identifier_; |
| // We don't support cons strings here. |
| return false; |
| } |
| void VisitOneByteString(const uint8_t* chars, int length) { |
| for (int i = 0; i < length; ++i) { |
| if (first_char_) { |
| first_char_ = false; |
| is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]); |
| } else { |
| is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]); |
| } |
| } |
| } |
| void VisitTwoByteString(const uint16_t* chars, int length) { |
| for (int i = 0; i < length; ++i) { |
| if (first_char_) { |
| first_char_ = false; |
| is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]); |
| } else { |
| is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]); |
| } |
| } |
| } |
| |
| private: |
| bool is_identifier_; |
| bool first_char_; |
| i::UnicodeCache unicode_cache_; |
| DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper); |
| }; |
| |
| |
| MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext( |
| Local<Context> v8_context, Source* source, size_t arguments_count, |
| Local<String> arguments[], size_t context_extension_count, |
| Local<Object> context_extensions[]) { |
| PREPARE_FOR_EXECUTION(v8_context, ScriptCompiler, CompileFunctionInContext, |
| Function); |
| i::Handle<i::String> source_string; |
| auto factory = isolate->factory(); |
| if (arguments_count) { |
| source_string = factory->NewStringFromStaticChars("(function("); |
| for (size_t i = 0; i < arguments_count; ++i) { |
| IsIdentifierHelper helper; |
| if (!helper.Check(*Utils::OpenHandle(*arguments[i]))) { |
| return Local<Function>(); |
| } |
| has_pending_exception = |
| !factory->NewConsString(source_string, |
| Utils::OpenHandle(*arguments[i])) |
| .ToHandle(&source_string); |
| RETURN_ON_FAILED_EXECUTION(Function); |
| if (i + 1 == arguments_count) continue; |
| has_pending_exception = |
| !factory->NewConsString(source_string, |
| factory->LookupSingleCharacterStringFromCode( |
| ',')).ToHandle(&source_string); |
| RETURN_ON_FAILED_EXECUTION(Function); |
| } |
| auto brackets = factory->NewStringFromStaticChars("){"); |
| has_pending_exception = !factory->NewConsString(source_string, brackets) |
| .ToHandle(&source_string); |
| RETURN_ON_FAILED_EXECUTION(Function); |
| } else { |
| source_string = factory->NewStringFromStaticChars("(function(){"); |
| } |
| |
| int scope_position = source_string->length(); |
| has_pending_exception = |
| !factory->NewConsString(source_string, |
| Utils::OpenHandle(*source->source_string)) |
| .ToHandle(&source_string); |
| RETURN_ON_FAILED_EXECUTION(Function); |
| // Include \n in case the source contains a line end comment. |
| auto brackets = factory->NewStringFromStaticChars("\n})"); |
| has_pending_exception = |
| !factory->NewConsString(source_string, brackets).ToHandle(&source_string); |
| RETURN_ON_FAILED_EXECUTION(Function); |
| |
| i::Handle<i::Context> context = Utils::OpenHandle(*v8_context); |
| i::Handle<i::SharedFunctionInfo> outer_info(context->closure()->shared(), |
| isolate); |
| for (size_t i = 0; i < context_extension_count; ++i) { |
| i::Handle<i::JSReceiver> extension = |
| Utils::OpenHandle(*context_extensions[i]); |
| if (!extension->IsJSObject()) return Local<Function>(); |
| i::Handle<i::JSFunction> closure(context->closure(), isolate); |
| context = factory->NewWithContext(closure, context, extension); |
| } |
| |
| i::Handle<i::Object> name_obj; |
| int eval_scope_position = 0; |
| int eval_position = i::RelocInfo::kNoPosition; |
| int line_offset = 0; |
| int column_offset = 0; |
| if (!source->resource_name.IsEmpty()) { |
| name_obj = Utils::OpenHandle(*(source->resource_name)); |
| } |
| if (!source->resource_line_offset.IsEmpty()) { |
| line_offset = static_cast<int>(source->resource_line_offset->Value()); |
| } |
| if (!source->resource_column_offset.IsEmpty()) { |
| column_offset = static_cast<int>(source->resource_column_offset->Value()); |
| } |
| i::Handle<i::JSFunction> fun; |
| has_pending_exception = |
| !i::Compiler::GetFunctionFromEval( |
| source_string, outer_info, context, i::SLOPPY, |
| i::ONLY_SINGLE_FUNCTION_LITERAL, eval_scope_position, eval_position, |
| line_offset, column_offset - scope_position, name_obj, |
| source->resource_options) |
| .ToHandle(&fun); |
| if (has_pending_exception) { |
| isolate->ReportPendingMessages(); |
| } |
| RETURN_ON_FAILED_EXECUTION(Function); |
| |
| i::Handle<i::Object> result; |
| has_pending_exception = |
| !i::Execution::Call(isolate, fun, |
| Utils::OpenHandle(*v8_context->Global()), 0, |
| nullptr).ToHandle(&result); |
| RETURN_ON_FAILED_EXECUTION(Function); |
| RETURN_ESCAPED( |
| Utils::CallableToLocal(i::Handle<i::JSFunction>::cast(result))); |
| } |
| |
| |
| Local<Function> ScriptCompiler::CompileFunctionInContext( |
| Isolate* v8_isolate, Source* source, Local<Context> v8_context, |
| size_t arguments_count, Local<String> arguments[], |
| size_t context_extension_count, Local<Object> context_extensions[]) { |
| RETURN_TO_LOCAL_UNCHECKED( |
| CompileFunctionInContext(v8_context, source, arguments_count, arguments, |
| context_extension_count, context_extensions), |
| Function); |
| } |
| |
| |
| ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript( |
| Isolate* v8_isolate, StreamedSource* source, CompileOptions options) { |
| i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); |
| return new i::BackgroundParsingTask(source->impl(), options, |
| i::FLAG_stack_size, isolate); |
| } |
| |
| |
| MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context, |
| StreamedSource* v8_source, |
| Local<String> full_source_string, |
| const ScriptOrigin& origin) { |
| PREPARE_FOR_EXECUTION(context, ScriptCompiler, Compile, Script); |
| i::StreamedSource* source = v8_source->impl(); |
| i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string)); |
| i::Handle<i::Script> script = isolate->factory()->NewScript(str); |
| if (!origin.ResourceName().IsEmpty()) { |
| script->set_name(*Utils::OpenHandle(*(origin.ResourceName()))); |
| } |
| if (!origin.ResourceLineOffset().IsEmpty()) { |
| script->set_line_offset( |
| static_cast<int>(origin.ResourceLineOffset()->Value())); |
| } |
| if (!origin.ResourceColumnOffset().IsEmpty()) { |
| script->set_column_offset( |
| static_cast<int>(origin.ResourceColumnOffset()->Value())); |
| } |
| script->set_origin_options(origin.Options()); |
| if (!origin.SourceMapUrl().IsEmpty()) { |
| script->set_source_mapping_url( |
| *Utils::OpenHandle(*(origin.SourceMapUrl()))); |
| } |
| |
| source->info->set_script(script); |
| source->info->set_context(isolate->native_context()); |
| |
| // Do the parsing tasks which need to be done on the main thread. This will |
| // also handle parse errors. |
| source->parser->Internalize(isolate, script, |
| source->info->literal() == nullptr); |
| source->parser->HandleSourceURLComments(isolate, script); |
| |
| i::Handle<i::SharedFunctionInfo> result; |
| if (source->info->literal() != nullptr) { |
| // Parsing has succeeded. |
| result = i::Compiler::GetSharedFunctionInfoForStreamedScript( |
| script, source->info.get(), str->length()); |
| } |
| has_pending_exception = result.is_null(); |
| if (has_pending_exception) isolate->ReportPendingMessages(); |
| RETURN_ON_FAILED_EXECUTION(Script); |
| |
| source->info->clear_script(); // because script goes out of scope. |
| |
| Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result); |
| if (generic.IsEmpty()) return Local<Script>(); |
| Local<Script> bound = generic->BindToCurrentContext(); |
| if (bound.IsEmpty()) return Local<Script>(); |
| RETURN_ESCAPED(bound); |
| } |
| |
| |
| Local<Script> ScriptCompiler::Compile(Isolate* v8_isolate, |
| StreamedSource* v8_source, |
| Local<String> full_source_string, |
| const ScriptOrigin& origin) { |
| auto context = v8_isolate->GetCurrentContext(); |
| RETURN_TO_LOCAL_UNCHECKED( |
| Compile(context, v8_source, full_source_string, origin), Script); |
| } |
| |
| |
| uint32_t ScriptCompiler::CachedDataVersionTag() { |
| return static_cast<uint32_t>(base::hash_combine( |
| internal::Version::Hash(), internal::FlagList::Hash(), |
| static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures()))); |
| } |
| |
| |
| MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source, |
| ScriptOrigin* origin) { |
| if (origin) { |
| ScriptCompiler::Source script_source(source, *origin); |
| return ScriptCompiler::Compile(context, &script_source); |
| } |
| ScriptCompiler::Source script_source(source); |
| return ScriptCompiler::Compile(context, &script_source); |
| } |
| |
| |
| Local<Script> Script::Compile(v8::Local<String> source, |
| v8::ScriptOrigin* origin) { |
| auto str = Utils::OpenHandle(*source); |
| auto context = ContextFromHeapObject(str); |
| RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, origin), Script); |
| } |
| |
| |
| Local<Script> Script::Compile(v8::Local<String> source, |
| v8::Local<String> file_name) { |
| auto str = Utils::OpenHandle(*source); |
| auto context = ContextFromHeapObject(str); |
| ScriptOrigin origin(file_name); |
| return Compile(context, source, &origin).FromMaybe(Local<Script>()); |
| } |
| |
| |
| // --- E x c e p t i o n s --- |
| |
| |
| v8::TryCatch::TryCatch() |
| : isolate_(i::Isolate::Current()), |
| next_(isolate_->try_catch_handler()), |
| is_verbose_(false), |
| can_continue_(true), |
| capture_message_(true), |
| rethrow_(false), |
| has_terminated_(false) { |
| ResetInternal(); |
| // Special handling for simulators which have a separate JS stack. |
| js_stack_comparable_address_ = |
| reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch( |
| isolate_, v8::internal::GetCurrentStackPosition())); |
| isolate_->RegisterTryCatchHandler(this); |
| } |
| |
| |
| v8::TryCatch::TryCatch(v8::Isolate* isolate) |
| : isolate_(reinterpret_cast<i::Isolate*>(isolate)), |
| next_(isolate_->try_catch_handler()), |
| is_verbose_(false), |
| can_continue_(true), |
| capture_message_(true), |
| rethrow_(false), |
| has_terminated_(false) { |
| ResetInternal(); |
| // Special handling for simulators which have a separate JS stack. |
| js_stack_comparable_address_ = |
| reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch( |
| isolate_, v8::internal::GetCurrentStackPosition())); |
| isolate_->RegisterTryCatchHandler(this); |
| } |
| |
| |
| v8::TryCatch::~TryCatch() { |
| if (rethrow_) { |
| v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_); |
| v8::HandleScope scope(isolate); |
| v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception()); |
| if (HasCaught() && capture_message_) { |
| // If an exception was caught and rethrow_ is indicated, the saved |
| // message, script, and location need to be restored to Isolate TLS |
| // for reuse. capture_message_ needs to be disabled so that Throw() |
| // does not create a new message. |
| isolate_->thread_local_top()->rethrowing_message_ = true; |
| isolate_->RestorePendingMessageFromTryCatch(this); |
| } |
| isolate_->UnregisterTryCatchHandler(this); |
| v8::internal::SimulatorStack::UnregisterCTryCatch(isolate_); |
| reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc); |
| DCHECK(!isolate_->thread_local_top()->rethrowing_message_); |
| } else { |
| if (HasCaught() && isolate_->has_scheduled_exception()) { |
| // If an exception was caught but is still scheduled because no API call |
| // promoted it, then it is canceled to prevent it from being propagated. |
| // Note that this will not cancel termination exceptions. |
| isolate_->CancelScheduledExceptionFromTryCatch(this); |
| } |
| isolate_->UnregisterTryCatchHandler(this); |
| v8::internal::SimulatorStack::UnregisterCTryCatch(isolate_); |
| } |
| } |
| |
| |
| bool v8::TryCatch::HasCaught() const { |
| return !reinterpret_cast<i::Object*>(exception_)->IsTheHole(isolate_); |
| } |
| |
| |
| bool v8::TryCatch::CanContinue() const { |
| return can_continue_; |
| } |
| |
| |
| bool v8::TryCatch::HasTerminated() const { |
| return has_terminated_; |
| } |
| |
| |
| v8::Local<v8::Value> v8::TryCatch::ReThrow() { |
| if (!HasCaught()) return v8::Local<v8::Value>(); |
| rethrow_ = true; |
| return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_)); |
| } |
| |
| |
| v8::Local<Value> v8::TryCatch::Exception() const { |
| if (HasCaught()) { |
| // Check for out of memory exception. |
| i::Object* exception = reinterpret_cast<i::Object*>(exception_); |
| return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_)); |
| } else { |
| return v8::Local<Value>(); |
| } |
| } |
| |
| |
| MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const { |
| if (!HasCaught()) return v8::Local<Value>(); |
| i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_); |
| if (!raw_obj->IsJSObject()) return v8::Local<Value>(); |
| PREPARE_FOR_EXECUTION(context, TryCatch, StackTrace, Value); |
| i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_); |
| i::Handle<i::String> name = isolate->factory()->stack_string(); |
| Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name); |
| has_pending_exception = !maybe.IsJust(); |
| RETURN_ON_FAILED_EXECUTION(Value); |
| if (!maybe.FromJust()) return v8::Local<Value>(); |
| Local<Value> result; |
| has_pending_exception = |
| !ToLocal<Value>(i::JSReceiver::GetProperty(obj, name), &result); |
| RETURN_ON_FAILED_EXECUTION(Value); |
| RETURN_ESCAPED(result); |
| } |
| |
| |
| v8::Local<Value> v8::TryCatch::StackTrace() const { |
| auto context = reinterpret_cast<v8::Isolate*>(isolate_)->GetCurrentContext(); |
| RETURN_TO_LOCAL_UNCHECKED(StackTrace(context), Value); |
| } |
| |
| |
| v8::Local<v8::Message> v8::TryCatch::Message() const { |
| i::Object* message = reinterpret_cast<i::Object*>(message_obj_); |
| DCHECK(message->IsJSMessageObject() || message->IsTheHole(isolate_)); |
| if (HasCaught() && !message->IsTheHole(isolate_)) { |
| return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_)); |
| } else { |
| return v8::Local<v8::Message>(); |
| } |
| } |
| |
| |
| void v8::TryCatch::Reset() { |
| if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) { |
| // If an exception was caught but is still scheduled because no API call |
| // promoted it, then it is canceled to prevent it from being propagated. |
| // Note that this will not cancel termination exceptions. |
| isolate_->CancelScheduledExceptionFromTryCatch(this); |
| } |
| ResetInternal(); |
| } |
| |
| |
| void v8::TryCatch::ResetInternal() { |
| i::Object* the_hole = isolate_->heap()->the_hole_value(); |
| exception_ = the_hole; |
| message_obj_ = the_hole; |
| } |
| |
| |
| void v8::TryCatch::SetVerbose(bool value) { |
| is_verbose_ = value; |
| } |
| |
| |
| void v8::TryCatch::SetCaptureMessage(bool value) { |
| capture_message_ = value; |
| } |
| |
| |
| // --- M e s s a g e --- |
| |
| |
| Local<String> Message::Get() const { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate)); |
| i::Handle<i::Object> obj = Utils::OpenHandle(this); |
| i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj); |
| Local<String> result = Utils::ToLocal(raw_result); |
| return scope.Escape(result); |
| } |
| |
| |
| ScriptOrigin Message::GetScriptOrigin() const { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this)); |
| auto script_wraper = i::Handle<i::Object>(message->script(), isolate); |
| auto script_value = i::Handle<i::JSValue>::cast(script_wraper); |
| i::Handle<i::Script> script(i::Script::cast(script_value->value())); |
| return GetScriptOriginForScript(isolate, script); |
| } |
| |
| |
| v8::Local<Value> Message::GetScriptResourceName() const { |
| return GetScriptOrigin().ResourceName(); |
| } |
| |
| |
| v8::Local<v8::StackTrace> Message::GetStackTrace() const { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate)); |
| auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this)); |
| i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate); |
| if (!stackFramesObj->IsJSArray()) return v8::Local<v8::StackTrace>(); |
| auto stackTrace = i::Handle<i::JSArray>::cast(stackFramesObj); |
| return scope.Escape(Utils::StackTraceToLocal(stackTrace)); |
| } |
| |
| |
| Maybe<int> Message::GetLineNumber(Local<Context> context) const { |
| PREPARE_FOR_EXECUTION_PRIMITIVE(context, Message, GetLineNumber, int); |
| i::Handle<i::JSFunction> fun = isolate->message_get_line_number(); |
| i::Handle<i::Object> undefined = isolate->factory()->undefined_value(); |
| i::Handle<i::Object> args[] = {Utils::OpenHandle(this)}; |
| i::Handle<i::Object> result; |
| has_pending_exception = |
| !i::Execution::Call(isolate, fun, undefined, arraysize(args), args) |
| .ToHandle(&result); |
| RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int); |
| return Just(static_cast<int>(result->Number())); |
| } |
| |
| |
| int Message::GetLineNumber() const { |
| auto context = ContextFromHeapObject(Utils::OpenHandle(this)); |
| return GetLineNumber(context).FromMaybe(0); |
| } |
| |
| |
| int Message::GetStartPosition() const { |
| auto self = Utils::OpenHandle(this); |
| return self->start_position(); |
| } |
| |
| |
| int Message::GetEndPosition() const { |
| auto self = Utils::OpenHandle(this); |
| return self->end_position(); |
| } |
| |
| |
| Maybe<int> Message::GetStartColumn(Local<Context> context) const { |
| PREPARE_FOR_EXECUTION_PRIMITIVE(context, Message, GetStartColumn, int); |
| i::Handle<i::JSFunction> fun = isolate->message_get_column_number(); |
| i::Handle<i::Object> undefined = isolate->factory()->undefined_value(); |
| i::Handle<i::Object> args[] = {Utils::OpenHandle(this)}; |
| i::Handle<i::Object> result; |
| has_pending_exception = |
| !i::Execution::Call(isolate, fun, undefined, arraysize(args), args) |
| .ToHandle(&result); |
| RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int); |
| return Just(static_cast<int>(result->Number())); |
| } |
| |
| |
| int Message::GetStartColumn() const { |
| auto context = ContextFromHeapObject(Utils::OpenHandle(this)); |
| const int default_value = kNoColumnInfo; |
| return GetStartColumn(context).FromMaybe(default_value); |
| } |
| |
| |
| Maybe<int> Message::GetEndColumn(Local<Context> context) const { |
| auto self = Utils::OpenHandle(this); |
| PREPARE_FOR_EXECUTION_PRIMITIVE(context, Message, GetEndColumn, int); |
| i::Handle<i::JSFunction> fun = isolate->message_get_column_number(); |
| i::Handle<i::Object> undefined = isolate->factory()->undefined_value(); |
| i::Handle<i::Object> args[] = {self}; |
| i::Handle<i::Object> result; |
| has_pending_exception = |
| !i::Execution::Call(isolate, fun, undefined, arraysize(args), args) |
| .ToHandle(&result); |
| RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int); |
| int start = self->start_position(); |
| int end = self->end_position(); |
| return Just(static_cast<int>(result->Number()) + (end - start)); |
| } |
| |
| |
| int Message::GetEndColumn() const { |
| auto context = ContextFromHeapObject(Utils::OpenHandle(this)); |
| const int default_value = kNoColumnInfo; |
| return GetEndColumn(context).FromMaybe(default_value); |
| } |
| |
| |
| bool Message::IsSharedCrossOrigin() const { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| auto self = Utils::OpenHandle(this); |
| auto script = i::Handle<i::JSValue>::cast( |
| i::Handle<i::Object>(self->script(), isolate)); |
| return i::Script::cast(script->value()) |
| ->origin_options() |
| .IsSharedCrossOrigin(); |
| } |
| |
| bool Message::IsOpaque() const { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| auto self = Utils::OpenHandle(this); |
| auto script = i::Handle<i::JSValue>::cast( |
| i::Handle<i::Object>(self->script(), isolate)); |
| return i::Script::cast(script->value())->origin_options().IsOpaque(); |
| } |
| |
| |
| MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const { |
| PREPARE_FOR_EXECUTION(context, Message, GetSourceLine, String); |
| i::Handle<i::JSFunction> fun = isolate->message_get_source_line(); |
| i::Handle<i::Object> undefined = isolate->factory()->undefined_value(); |
| i::Handle<i::Object> args[] = {Utils::OpenHandle(this)}; |
| i::Handle<i::Object> result; |
| has_pending_exception = |
| !i::Execution::Call(isolate, fun, undefined, arraysize(args), args) |
| .ToHandle(&result); |
| RETURN_ON_FAILED_EXECUTION(String); |
| Local<String> str; |
| if (result->IsString()) { |
| str = Utils::ToLocal(i::Handle<i::String>::cast(result)); |
| } |
| RETURN_ESCAPED(str); |
| } |
| |
| |
| Local<String> Message::GetSourceLine() const { |
| auto context = ContextFromHeapObject(Utils::OpenHandle(this)); |
| RETURN_TO_LOCAL_UNCHECKED(GetSourceLine(context), String) |
| } |
| |
| |
| void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) { |
| i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| ENTER_V8(i_isolate); |
| i_isolate->PrintCurrentStackTrace(out); |
| } |
| |
| |
| // --- S t a c k T r a c e --- |
| |
| Local<StackFrame> StackTrace::GetFrame(uint32_t index) const { |
| i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); |
| ENTER_V8(isolate); |
| EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate)); |
| auto self = Utils::OpenHandle(this); |
| auto obj = i::JSReceiver::GetElement(isolate, self, index).ToHandleChecked(); |
| auto jsobj = i::Handle<i::JSObject>::cast(obj); |
| return scope.Escape(Utils::StackFrameToLocal(jsobj)); |
| } |
| |
| |
| int StackTrace::GetFrameCount() const { |
| return i::Smi::cast(Utils::OpenHandle(this)->length())->value(); |
| } |
| |
| |
| Local<Array> StackTrace::AsArray() { |
| return Utils::ToLocal(Utils::OpenHandle(this)); |
| } |
| |
| |
| Local<StackTrace> StackTrace::CurrentStackTrace( |
| Isolate* isolate, |
| int frame_limit, |
| StackTraceOptions options) { |
| i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); |
| ENTER_V8(i_isolate); |
| // TODO(dcarney): remove when ScriptDebugServer is fixed. |
| options = static_cast<StackTraceOptions>( |
| static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins); |
| i::Handle<i::JSArray> stackTrace = |
| i_isolate->CaptureCurrentStackTrace(frame_limit, options); |
| return Utils::StackTraceToLocal(stackTrace); |
| } |
| |
| |
| // --- S t a c k F r a m e --- |
| |
| static int getIntProperty(const StackFrame* f, const char* propertyName, |
| int defaultValue) { |
| i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate(); |
| ENTER_V8(isolate); |
| i::HandleScope scope(isolate); |
| i::Handle<i::JSObject> self = Utils::OpenHandle(f); |
| i::Handle<i::Object> obj = |
| i::JSReceiver::GetProperty(isolate, self, propertyName).ToHandleChecked(); |
| return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue; |
| } |
| |
| |
| int |