// Copyright 2014 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/bootstrapper.h" #include "src/accessors.h" #include "src/api-inl.h" #include "src/api-natives.h" #include "src/base/ieee754.h" #include "src/code-stubs.h" #include "src/compiler.h" #include "src/debug/debug.h" #include "src/extensions/externalize-string-extension.h" #include "src/extensions/free-buffer-extension.h" #include "src/extensions/gc-extension.h" #include "src/extensions/ignition-statistics-extension.h" #include "src/extensions/statistics-extension.h" #include "src/extensions/trigger-failure-extension.h" #include "src/heap/heap.h" #include "src/isolate-inl.h" #include "src/math-random.h" #include "src/objects/api-callbacks.h" #include "src/objects/arguments.h" #include "src/objects/builtin-function-id.h" #include "src/objects/hash-table-inl.h" #ifdef V8_INTL_SUPPORT #include "src/objects/intl-objects.h" #endif // V8_INTL_SUPPORT #include "src/objects/js-array-buffer-inl.h" #include "src/objects/js-array-inl.h" #ifdef V8_INTL_SUPPORT #include "src/objects/js-break-iterator.h" #include "src/objects/js-collator.h" #include "src/objects/js-date-time-format.h" #include "src/objects/js-list-format.h" #include "src/objects/js-locale.h" #include "src/objects/js-number-format.h" #include "src/objects/js-plural-rules.h" #endif // V8_INTL_SUPPORT #include "src/objects/js-regexp-string-iterator.h" #include "src/objects/js-regexp.h" #ifdef V8_INTL_SUPPORT #include "src/objects/js-relative-time-format.h" #include "src/objects/js-segmenter.h" #endif // V8_INTL_SUPPORT #include "src/objects/templates.h" #include "src/snapshot/natives.h" #include "src/snapshot/snapshot.h" #include "src/wasm/wasm-js.h" namespace v8 { namespace internal { void SourceCodeCache::Initialize(Isolate* isolate, bool create_heap_objects) { cache_ = create_heap_objects ? ReadOnlyRoots(isolate).empty_fixed_array() : nullptr; } bool SourceCodeCache::Lookup(Isolate* isolate, Vector name, Handle* handle) { for (int i = 0; i < cache_->length(); i += 2) { SeqOneByteString* str = SeqOneByteString::cast(cache_->get(i)); if (str->IsUtf8EqualTo(name)) { *handle = Handle( SharedFunctionInfo::cast(cache_->get(i + 1)), isolate); return true; } } return false; } void SourceCodeCache::Add(Isolate* isolate, Vector name, Handle shared) { Factory* factory = isolate->factory(); HandleScope scope(isolate); int length = cache_->length(); Handle new_array = factory->NewFixedArray(length + 2, TENURED); cache_->CopyTo(0, *new_array, 0, cache_->length()); cache_ = *new_array; Handle str = factory->NewStringFromOneByte(Vector::cast(name), TENURED) .ToHandleChecked(); DCHECK(!str.is_null()); cache_->set(length, *str); cache_->set(length + 1, *shared); Script::cast(shared->script())->set_type(type_); } Bootstrapper::Bootstrapper(Isolate* isolate) : isolate_(isolate), nesting_(0), extensions_cache_(Script::TYPE_EXTENSION) {} Handle Bootstrapper::GetNativeSource(NativeType type, int index) { NativesExternalStringResource* resource = new NativesExternalStringResource(type, index); Handle source_code = isolate_->factory()->NewNativeSourceString(resource); DCHECK(source_code->is_uncached()); return source_code; } void Bootstrapper::Initialize(bool create_heap_objects) { extensions_cache_.Initialize(isolate_, create_heap_objects); } static const char* GCFunctionName() { bool flag_given = FLAG_expose_gc_as != nullptr && strlen(FLAG_expose_gc_as) != 0; return flag_given ? FLAG_expose_gc_as : "gc"; } v8::Extension* Bootstrapper::free_buffer_extension_ = nullptr; v8::Extension* Bootstrapper::gc_extension_ = nullptr; v8::Extension* Bootstrapper::externalize_string_extension_ = nullptr; v8::Extension* Bootstrapper::statistics_extension_ = nullptr; v8::Extension* Bootstrapper::trigger_failure_extension_ = nullptr; v8::Extension* Bootstrapper::ignition_statistics_extension_ = nullptr; void Bootstrapper::InitializeOncePerProcess() { free_buffer_extension_ = new FreeBufferExtension; v8::RegisterExtension(free_buffer_extension_); gc_extension_ = new GCExtension(GCFunctionName()); v8::RegisterExtension(gc_extension_); externalize_string_extension_ = new ExternalizeStringExtension; v8::RegisterExtension(externalize_string_extension_); statistics_extension_ = new StatisticsExtension; v8::RegisterExtension(statistics_extension_); trigger_failure_extension_ = new TriggerFailureExtension; v8::RegisterExtension(trigger_failure_extension_); ignition_statistics_extension_ = new IgnitionStatisticsExtension; v8::RegisterExtension(ignition_statistics_extension_); } void Bootstrapper::TearDownExtensions() { delete free_buffer_extension_; free_buffer_extension_ = nullptr; delete gc_extension_; gc_extension_ = nullptr; delete externalize_string_extension_; externalize_string_extension_ = nullptr; delete statistics_extension_; statistics_extension_ = nullptr; delete trigger_failure_extension_; trigger_failure_extension_ = nullptr; delete ignition_statistics_extension_; ignition_statistics_extension_ = nullptr; } void Bootstrapper::TearDown() { extensions_cache_.Initialize(isolate_, false); // Yes, symmetrical } class Genesis { public: Genesis(Isolate* isolate, MaybeHandle maybe_global_proxy, v8::Local global_proxy_template, size_t context_snapshot_index, v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer, GlobalContextType context_type); Genesis(Isolate* isolate, MaybeHandle maybe_global_proxy, v8::Local global_proxy_template); ~Genesis() = default; Isolate* isolate() const { return isolate_; } Factory* factory() const { return isolate_->factory(); } Builtins* builtins() const { return isolate_->builtins(); } Heap* heap() const { return isolate_->heap(); } Handle result() { return result_; } Handle global_proxy() { return global_proxy_; } private: Handle native_context() { return native_context_; } // Creates some basic objects. Used for creating a context from scratch. void CreateRoots(); // Creates the empty function. Used for creating a context from scratch. Handle CreateEmptyFunction(); // Returns the %ThrowTypeError% intrinsic function. // See ES#sec-%throwtypeerror% for details. Handle GetThrowTypeErrorIntrinsic(); void CreateSloppyModeFunctionMaps(Handle empty); void CreateStrictModeFunctionMaps(Handle empty); void CreateObjectFunction(Handle empty); void CreateIteratorMaps(Handle empty); void CreateAsyncIteratorMaps(Handle empty); void CreateAsyncFunctionMaps(Handle empty); void CreateJSProxyMaps(); // Make the "arguments" and "caller" properties throw a TypeError on access. void AddRestrictedFunctionProperties(Handle empty); // Creates the global objects using the global proxy and the template passed // in through the API. We call this regardless of whether we are building a // context from scratch or using a deserialized one from the partial snapshot // but in the latter case we don't use the objects it produces directly, as // we have to use the deserialized ones that are linked together with the // rest of the context snapshot. At the end we link the global proxy and the // context to each other. Handle CreateNewGlobals( v8::Local global_proxy_template, Handle global_proxy); // Similarly, we want to use the global that has been created by the templates // passed through the API. The global from the snapshot is detached from the // other objects in the snapshot. void HookUpGlobalObject(Handle global_object); // Hooks the given global proxy into the context in the case we do not // replace the global object from the deserialized native context. void HookUpGlobalProxy(Handle global_proxy); // The native context has a ScriptContextTable that store declarative bindings // made in script scopes. Add a "this" binding to that table pointing to the // global proxy. void InstallGlobalThisBinding(); // New context initialization. Used for creating a context from scratch. void InitializeGlobal(Handle global_object, Handle empty_function, GlobalContextType context_type); void InitializeExperimentalGlobal(); // Depending on the situation, expose and/or get rid of the utils object. void ConfigureUtilsObject(GlobalContextType context_type); #define DECLARE_FEATURE_INITIALIZATION(id, descr) \ void InitializeGlobal_##id(); HARMONY_INPROGRESS(DECLARE_FEATURE_INITIALIZATION) HARMONY_STAGED(DECLARE_FEATURE_INITIALIZATION) HARMONY_SHIPPING(DECLARE_FEATURE_INITIALIZATION) #undef DECLARE_FEATURE_INITIALIZATION enum ArrayBufferKind { ARRAY_BUFFER, SHARED_ARRAY_BUFFER, }; Handle CreateArrayBuffer(Handle name, ArrayBufferKind array_buffer_kind); Handle InstallInternalArray(Handle target, const char* name, ElementsKind elements_kind); bool InstallNatives(GlobalContextType context_type); Handle InstallTypedArray(const char* name, ElementsKind elements_kind); bool InstallExtraNatives(); bool InstallExperimentalExtraNatives(); bool InstallDebuggerNatives(); void InstallBuiltinFunctionIds(); void InstallExperimentalBuiltinFunctionIds(); void InitializeNormalizedMapCaches(); enum ExtensionTraversalState { UNVISITED, VISITED, INSTALLED }; class ExtensionStates { public: ExtensionStates(); ExtensionTraversalState get_state(RegisteredExtension* extension); void set_state(RegisteredExtension* extension, ExtensionTraversalState state); private: base::HashMap map_; DISALLOW_COPY_AND_ASSIGN(ExtensionStates); }; // Used both for deserialized and from-scratch contexts to add the extensions // provided. static bool InstallExtensions(Isolate* isolate, Handle native_context, v8::ExtensionConfiguration* extensions); static bool InstallAutoExtensions(Isolate* isolate, ExtensionStates* extension_states); static bool InstallRequestedExtensions(Isolate* isolate, v8::ExtensionConfiguration* extensions, ExtensionStates* extension_states); static bool InstallExtension(Isolate* isolate, const char* name, ExtensionStates* extension_states); static bool InstallExtension(Isolate* isolate, v8::RegisteredExtension* current, ExtensionStates* extension_states); static bool InstallSpecialObjects(Isolate* isolate, Handle native_context); bool ConfigureApiObject(Handle object, Handle object_template); bool ConfigureGlobalObjects( v8::Local global_proxy_template); // Migrates all properties from the 'from' object to the 'to' // object and overrides the prototype in 'to' with the one from // 'from'. void TransferObject(Handle from, Handle to); void TransferNamedProperties(Handle from, Handle to); void TransferIndexedProperties(Handle from, Handle to); static bool CallUtilsFunction(Isolate* isolate, const char* name); static bool CompileExtension(Isolate* isolate, v8::Extension* extension); Isolate* isolate_; Handle result_; Handle native_context_; Handle global_proxy_; // Temporary function maps needed only during bootstrapping. Handle strict_function_with_home_object_map_; Handle strict_function_with_name_and_home_object_map_; // %ThrowTypeError%. See ES#sec-%throwtypeerror% for details. Handle restricted_properties_thrower_; BootstrapperActive active_; friend class Bootstrapper; }; void Bootstrapper::Iterate(RootVisitor* v) { extensions_cache_.Iterate(v); v->Synchronize(VisitorSynchronization::kExtensions); } Handle Bootstrapper::CreateEnvironment( MaybeHandle maybe_global_proxy, v8::Local global_proxy_template, v8::ExtensionConfiguration* extensions, size_t context_snapshot_index, v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer, GlobalContextType context_type) { HandleScope scope(isolate_); Handle env; { Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template, context_snapshot_index, embedder_fields_deserializer, context_type); env = genesis.result(); if (env.is_null() || !InstallExtensions(env, extensions)) { return Handle(); } } // Log all maps created during bootstrapping. if (FLAG_trace_maps) LOG(isolate_, LogMaps()); return scope.CloseAndEscape(env); } Handle Bootstrapper::NewRemoteContext( MaybeHandle maybe_global_proxy, v8::Local global_proxy_template) { HandleScope scope(isolate_); Handle global_proxy; { Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template); global_proxy = genesis.global_proxy(); if (global_proxy.is_null()) return Handle(); } // Log all maps created during bootstrapping. if (FLAG_trace_maps) LOG(isolate_, LogMaps()); return scope.CloseAndEscape(global_proxy); } void Bootstrapper::DetachGlobal(Handle env) { isolate_->counters()->errors_thrown_per_context()->AddSample( env->GetErrorsThrown()); ReadOnlyRoots roots(isolate_); Handle global_proxy(JSGlobalProxy::cast(env->global_proxy()), isolate_); global_proxy->set_native_context(roots.null_value()); JSObject::ForceSetPrototype(global_proxy, isolate_->factory()->null_value()); global_proxy->map()->SetConstructor(roots.null_value()); if (FLAG_track_detached_contexts) { isolate_->AddDetachedContext(env); } } namespace { V8_NOINLINE Handle SimpleCreateSharedFunctionInfo( Isolate* isolate, Builtins::Name builtin_id, Handle name, int len, FunctionKind kind = FunctionKind::kNormalFunction) { Handle shared = isolate->factory()->NewSharedFunctionInfoForBuiltin(name, builtin_id, kind); shared->set_internal_formal_parameter_count(len); shared->set_length(len); return shared; } V8_NOINLINE Handle SimpleCreateBuiltinSharedFunctionInfo( Isolate* isolate, Builtins::Name builtin_id, Handle name, int len) { Handle shared = isolate->factory()->NewSharedFunctionInfoForBuiltin(name, builtin_id, kNormalFunction); shared->set_internal_formal_parameter_count(len); shared->set_length(len); return shared; } V8_NOINLINE void InstallFunction(Isolate* isolate, Handle target, Handle property_name, Handle function, Handle function_name, PropertyAttributes attributes = DONT_ENUM) { JSObject::AddProperty(isolate, target, property_name, function, attributes); } V8_NOINLINE void InstallFunction(Isolate* isolate, Handle target, Handle function, Handle name, PropertyAttributes attributes = DONT_ENUM) { Handle name_string = Name::ToFunctionName(isolate, name).ToHandleChecked(); InstallFunction(isolate, target, name, function, name_string, attributes); } V8_NOINLINE Handle CreateFunction( Isolate* isolate, Handle name, InstanceType type, int instance_size, int inobject_properties, MaybeHandle maybe_prototype, Builtins::Name builtin_id) { Handle prototype; Handle result; if (maybe_prototype.ToHandle(&prototype)) { NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype( name, prototype, type, instance_size, inobject_properties, builtin_id, IMMUTABLE); result = isolate->factory()->NewFunction(args); // Make the JSFunction's prototype object fast. JSObject::MakePrototypesFast(handle(result->prototype(), isolate), kStartAtReceiver, isolate); } else { NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithoutPrototype( name, builtin_id, LanguageMode::kStrict); result = isolate->factory()->NewFunction(args); } // Make the resulting JSFunction object fast. JSObject::MakePrototypesFast(result, kStartAtReceiver, isolate); result->shared()->set_native(true); return result; } V8_NOINLINE Handle InstallFunction( Isolate* isolate, Handle target, Handle name, InstanceType type, int instance_size, int inobject_properties, MaybeHandle maybe_prototype, Builtins::Name call, PropertyAttributes attributes) { Handle name_string = Name::ToFunctionName(isolate, name).ToHandleChecked(); Handle function = CreateFunction(isolate, name_string, type, instance_size, inobject_properties, maybe_prototype, call); InstallFunction(isolate, target, name, function, name_string, attributes); return function; } V8_NOINLINE Handle InstallFunction( Isolate* isolate, Handle target, const char* name, InstanceType type, int instance_size, int inobject_properties, MaybeHandle maybe_prototype, Builtins::Name call) { PropertyAttributes attributes = DONT_ENUM; return InstallFunction( isolate, target, isolate->factory()->InternalizeUtf8String(name), type, instance_size, inobject_properties, maybe_prototype, call, attributes); } V8_NOINLINE Handle SimpleCreateFunction(Isolate* isolate, Handle name, Builtins::Name call, int len, bool adapt) { Handle fun = CreateFunction(isolate, name, JS_OBJECT_TYPE, JSObject::kHeaderSize, 0, MaybeHandle(), call); if (adapt) { fun->shared()->set_internal_formal_parameter_count(len); } else { fun->shared()->DontAdaptArguments(); } fun->shared()->set_length(len); return fun; } V8_NOINLINE Handle SimpleInstallFunction( Isolate* isolate, Handle base, Handle property_name, Handle function_name, Builtins::Name call, int len, bool adapt, PropertyAttributes attrs = DONT_ENUM, BuiltinFunctionId id = BuiltinFunctionId::kInvalidBuiltinFunctionId) { Handle fun = SimpleCreateFunction(isolate, function_name, call, len, adapt); if (id != BuiltinFunctionId::kInvalidBuiltinFunctionId) { fun->shared()->set_builtin_function_id(id); } InstallFunction(isolate, base, fun, property_name, attrs); return fun; } V8_NOINLINE Handle SimpleInstallFunction( Isolate* isolate, Handle base, Handle name, Builtins::Name call, int len, bool adapt, PropertyAttributes attrs = DONT_ENUM, BuiltinFunctionId id = BuiltinFunctionId::kInvalidBuiltinFunctionId) { return SimpleInstallFunction(isolate, base, name, name, call, len, adapt, attrs, id); } V8_NOINLINE Handle SimpleInstallFunction( Isolate* isolate, Handle base, Handle property_name, const char* function_name, Builtins::Name call, int len, bool adapt, PropertyAttributes attrs = DONT_ENUM, BuiltinFunctionId id = BuiltinFunctionId::kInvalidBuiltinFunctionId) { return SimpleInstallFunction( isolate, base, property_name, isolate->factory()->InternalizeUtf8String(function_name), call, len, adapt, attrs, id); } V8_NOINLINE Handle SimpleInstallFunction( Isolate* isolate, Handle base, const char* name, Builtins::Name call, int len, bool adapt, PropertyAttributes attrs = DONT_ENUM, BuiltinFunctionId id = BuiltinFunctionId::kInvalidBuiltinFunctionId) { // Although function name does not have to be internalized the property name // will be internalized during property addition anyway, so do it here now. return SimpleInstallFunction(isolate, base, isolate->factory()->InternalizeUtf8String(name), call, len, adapt, attrs, id); } V8_NOINLINE Handle SimpleInstallFunction( Isolate* isolate, Handle base, const char* name, Builtins::Name call, int len, bool adapt, BuiltinFunctionId id) { return SimpleInstallFunction(isolate, base, name, call, len, adapt, DONT_ENUM, id); } V8_NOINLINE void SimpleInstallGetterSetter(Isolate* isolate, Handle base, Handle name, Builtins::Name call_getter, Builtins::Name call_setter, PropertyAttributes attribs) { Handle getter_name = Name::ToFunctionName(isolate, name, isolate->factory()->get_string()) .ToHandleChecked(); Handle getter = SimpleCreateFunction(isolate, getter_name, call_getter, 0, true); Handle setter_name = Name::ToFunctionName(isolate, name, isolate->factory()->set_string()) .ToHandleChecked(); Handle setter = SimpleCreateFunction(isolate, setter_name, call_setter, 1, true); JSObject::DefineAccessor(base, name, getter, setter, attribs).Check(); } V8_NOINLINE Handle SimpleInstallGetter( Isolate* isolate, Handle base, Handle name, Handle property_name, Builtins::Name call, bool adapt) { Handle getter_name = Name::ToFunctionName(isolate, name, isolate->factory()->get_string()) .ToHandleChecked(); Handle getter = SimpleCreateFunction(isolate, getter_name, call, 0, adapt); Handle setter = isolate->factory()->undefined_value(); JSObject::DefineAccessor(base, property_name, getter, setter, DONT_ENUM) .Check(); return getter; } V8_NOINLINE Handle SimpleInstallGetter(Isolate* isolate, Handle base, Handle name, Builtins::Name call, bool adapt) { return SimpleInstallGetter(isolate, base, name, name, call, adapt); } V8_NOINLINE Handle SimpleInstallGetter( Isolate* isolate, Handle base, Handle name, Builtins::Name call, bool adapt, BuiltinFunctionId id) { Handle fun = SimpleInstallGetter(isolate, base, name, call, adapt); fun->shared()->set_builtin_function_id(id); return fun; } V8_NOINLINE void InstallConstant(Isolate* isolate, Handle holder, const char* name, Handle value) { JSObject::AddProperty( isolate, holder, isolate->factory()->InternalizeUtf8String(name), value, static_cast(DONT_DELETE | DONT_ENUM | READ_ONLY)); } V8_NOINLINE void InstallSpeciesGetter(Isolate* isolate, Handle constructor) { Factory* factory = isolate->factory(); // TODO(adamk): We should be able to share a SharedFunctionInfo // between all these JSFunctins. SimpleInstallGetter(isolate, constructor, factory->symbol_species_string(), factory->species_symbol(), Builtins::kReturnReceiver, true); } } // namespace Handle Genesis::CreateEmptyFunction() { // Allocate the function map first and then patch the prototype later. Handle empty_function_map = factory()->CreateSloppyFunctionMap( FUNCTION_WITHOUT_PROTOTYPE, MaybeHandle()); empty_function_map->set_is_prototype_map(true); DCHECK(!empty_function_map->is_dictionary_map()); // Allocate ScopeInfo for the empty function. Handle scope_info = ScopeInfo::CreateForEmptyFunction(isolate()); // Allocate the empty function as the prototype for function according to // ES#sec-properties-of-the-function-prototype-object NewFunctionArgs args = NewFunctionArgs::ForBuiltin( factory()->empty_string(), empty_function_map, Builtins::kEmptyFunction); Handle empty_function = factory()->NewFunction(args); native_context()->set_empty_function(*empty_function); // --- E m p t y --- Handle source = factory()->NewStringFromStaticChars("() {}"); Handle