blob: f35e1d7c4ec701374e3ff8d81dc7a1efc58f828d [file] [log] [blame]
// 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-natives.h"
#include "src/api.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/objects/js-regexp.h"
#include "src/snapshot/natives.h"
#include "src/snapshot/snapshot.h"
#include "src/wasm/wasm-js.h"
#if V8_INTL_SUPPORT
#include "src/objects/intl-objects.h"
#endif // V8_INTL_SUPPORT
#if V8_OS_STARBOARD
#include "src/poems.h"
#endif
namespace v8 {
namespace internal {
void SourceCodeCache::Initialize(Isolate* isolate, bool create_heap_objects) {
cache_ = create_heap_objects ? isolate->heap()->empty_fixed_array() : nullptr;
}
bool SourceCodeCache::Lookup(Vector<const char> name,
Handle<SharedFunctionInfo>* handle) {
for (int i = 0; i < cache_->length(); i += 2) {
SeqOneByteString* str = SeqOneByteString::cast(cache_->get(i));
if (str->IsUtf8EqualTo(name)) {
*handle = Handle<SharedFunctionInfo>(
SharedFunctionInfo::cast(cache_->get(i + 1)));
return true;
}
}
return false;
}
void SourceCodeCache::Add(Vector<const char> name,
Handle<SharedFunctionInfo> shared) {
Isolate* isolate = shared->GetIsolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
int length = cache_->length();
Handle<FixedArray> new_array = factory->NewFixedArray(length + 2, TENURED);
cache_->CopyTo(0, *new_array, 0, cache_->length());
cache_ = *new_array;
Handle<String> str =
factory->NewStringFromOneByte(Vector<const uint8_t>::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<String> Bootstrapper::GetNativeSource(NativeType type, int index) {
NativesExternalStringResource* resource =
new NativesExternalStringResource(type, index);
Handle<ExternalOneByteString> source_code =
isolate_->factory()->NewNativeSourceString(resource);
isolate_->heap()->RegisterExternalString(*source_code);
DCHECK(source_code->is_short());
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 BASE_EMBEDDED {
public:
Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template,
size_t context_snapshot_index,
v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
GlobalContextType context_type);
Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template);
~Genesis() { }
Isolate* isolate() const { return isolate_; }
Factory* factory() const { return isolate_->factory(); }
Builtins* builtins() const { return isolate_->builtins(); }
Heap* heap() const { return isolate_->heap(); }
Handle<Context> result() { return result_; }
Handle<JSGlobalProxy> global_proxy() { return global_proxy_; }
private:
Handle<Context> 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<JSFunction> CreateEmptyFunction(Isolate* isolate);
// Returns the %ThrowTypeError% intrinsic function.
// See ES#sec-%throwtypeerror% for details.
Handle<JSFunction> GetThrowTypeErrorIntrinsic();
void CreateSloppyModeFunctionMaps(Handle<JSFunction> empty);
void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
void CreateObjectFunction(Handle<JSFunction> empty);
void CreateIteratorMaps(Handle<JSFunction> empty);
void CreateAsyncIteratorMaps(Handle<JSFunction> empty);
void CreateAsyncFunctionMaps(Handle<JSFunction> empty);
void CreateJSProxyMaps();
// Make the "arguments" and "caller" properties throw a TypeError on access.
void AddRestrictedFunctionProperties(Handle<JSFunction> 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<JSGlobalObject> CreateNewGlobals(
v8::Local<v8::ObjectTemplate> global_proxy_template,
Handle<JSGlobalProxy> 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<JSGlobalObject> 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<JSGlobalProxy> 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<JSGlobalObject> global_object,
Handle<JSFunction> 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<JSFunction> CreateArrayBuffer(Handle<String> name,
ArrayBufferKind array_buffer_kind);
Handle<JSFunction> InstallInternalArray(Handle<JSObject> target,
const char* name,
ElementsKind elements_kind);
bool InstallNatives(GlobalContextType context_type);
Handle<JSFunction> 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(Handle<Context> 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(Handle<Context> native_context);
bool ConfigureApiObject(Handle<JSObject> object,
Handle<ObjectTemplateInfo> object_template);
bool ConfigureGlobalObjects(
v8::Local<v8::ObjectTemplate> 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<JSObject> from, Handle<JSObject> to);
void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
static bool CallUtilsFunction(Isolate* isolate, const char* name);
static bool CompileExtension(Isolate* isolate, v8::Extension* extension);
Isolate* isolate_;
Handle<Context> result_;
Handle<Context> native_context_;
Handle<JSGlobalProxy> global_proxy_;
// Temporary function maps needed only during bootstrapping.
Handle<Map> strict_function_with_home_object_map_;
Handle<Map> strict_function_with_name_and_home_object_map_;
// %ThrowTypeError%. See ES#sec-%throwtypeerror% for details.
Handle<JSFunction> restricted_properties_thrower_;
BootstrapperActive active_;
friend class Bootstrapper;
};
void Bootstrapper::Iterate(RootVisitor* v) {
extensions_cache_.Iterate(v);
v->Synchronize(VisitorSynchronization::kExtensions);
}
Handle<Context> Bootstrapper::CreateEnvironment(
MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template,
v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
GlobalContextType context_type) {
HandleScope scope(isolate_);
Handle<Context> 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<Context>();
}
}
// Log all maps created during bootstrapping.
if (FLAG_trace_maps) LOG(isolate_, LogMaps());
return scope.CloseAndEscape(env);
}
Handle<JSGlobalProxy> Bootstrapper::NewRemoteContext(
MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template) {
HandleScope scope(isolate_);
Handle<JSGlobalProxy> global_proxy;
{
Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template);
global_proxy = genesis.global_proxy();
if (global_proxy.is_null()) return Handle<JSGlobalProxy>();
}
// Log all maps created during bootstrapping.
if (FLAG_trace_maps) LOG(isolate_, LogMaps());
return scope.CloseAndEscape(global_proxy);
}
void Bootstrapper::DetachGlobal(Handle<Context> env) {
Isolate* isolate = env->GetIsolate();
isolate->counters()->errors_thrown_per_context()->AddSample(
env->GetErrorsThrown());
Heap* heap = isolate->heap();
Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
global_proxy->set_native_context(heap->null_value());
JSObject::ForceSetPrototype(global_proxy, isolate->factory()->null_value());
global_proxy->map()->SetConstructor(heap->null_value());
if (FLAG_track_detached_contexts) {
env->GetIsolate()->AddDetachedContext(env);
}
}
namespace {
// Non-construct case.
V8_NOINLINE Handle<SharedFunctionInfo> SimpleCreateSharedFunctionInfo(
Isolate* isolate, Builtins::Name builtin_id, Handle<String> name, int len) {
Handle<Code> code = isolate->builtins()->builtin_handle(builtin_id);
const bool kNotConstructor = false;
Handle<SharedFunctionInfo> shared = isolate->factory()->NewSharedFunctionInfo(
name, code, kNotConstructor, kNormalFunction, builtin_id);
shared->set_internal_formal_parameter_count(len);
shared->set_length(len);
return shared;
}
// Construct case.
V8_NOINLINE Handle<SharedFunctionInfo> SimpleCreateSharedFunctionInfo(
Isolate* isolate, Builtins::Name builtin_id, Handle<String> name,
Handle<String> instance_class_name, int len) {
Handle<Code> code = isolate->builtins()->builtin_handle(builtin_id);
const bool kIsConstructor = true;
Handle<SharedFunctionInfo> shared = isolate->factory()->NewSharedFunctionInfo(
name, code, kIsConstructor, kNormalFunction, builtin_id);
shared->SetConstructStub(*BUILTIN_CODE(isolate, JSBuiltinsConstructStub));
shared->set_instance_class_name(*instance_class_name);
shared->set_internal_formal_parameter_count(len);
shared->set_length(len);
return shared;
}
V8_NOINLINE void InstallFunction(Handle<JSObject> target,
Handle<Name> property_name,
Handle<JSFunction> function,
Handle<String> function_name,
PropertyAttributes attributes = DONT_ENUM) {
JSObject::AddProperty(target, property_name, function, attributes);
if (target->IsJSGlobalObject()) {
function->shared()->set_instance_class_name(*function_name);
}
}
V8_NOINLINE void InstallFunction(Handle<JSObject> target,
Handle<JSFunction> function, Handle<Name> name,
PropertyAttributes attributes = DONT_ENUM) {
Handle<String> name_string = Name::ToFunctionName(name).ToHandleChecked();
InstallFunction(target, name, function, name_string, attributes);
}
V8_NOINLINE Handle<JSFunction> CreateFunction(
Isolate* isolate, Handle<String> name, InstanceType type, int instance_size,
int inobject_properties, MaybeHandle<Object> maybe_prototype,
Builtins::Name builtin_id) {
Handle<Code> code(isolate->builtins()->builtin(builtin_id));
Handle<Object> prototype;
Handle<JSFunction> result;
if (maybe_prototype.ToHandle(&prototype)) {
NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
name, code, 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, code, 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<JSFunction> InstallFunction(
Handle<JSObject> target, Handle<Name> name, InstanceType type,
int instance_size, int inobject_properties,
MaybeHandle<Object> maybe_prototype, Builtins::Name call,
PropertyAttributes attributes) {
Handle<String> name_string = Name::ToFunctionName(name).ToHandleChecked();
Handle<JSFunction> function =
CreateFunction(target->GetIsolate(), name_string, type, instance_size,
inobject_properties, maybe_prototype, call);
InstallFunction(target, name, function, name_string, attributes);
return function;
}
V8_NOINLINE Handle<JSFunction> InstallFunction(
Handle<JSObject> target, const char* name, InstanceType type,
int instance_size, int inobject_properties,
MaybeHandle<Object> maybe_prototype, Builtins::Name call) {
Factory* const factory = target->GetIsolate()->factory();
PropertyAttributes attributes = DONT_ENUM;
return InstallFunction(target, factory->InternalizeUtf8String(name), type,
instance_size, inobject_properties, maybe_prototype,
call, attributes);
}
V8_NOINLINE Handle<JSFunction> SimpleCreateFunction(Isolate* isolate,
Handle<String> name,
Builtins::Name call,
int len, bool adapt) {
Handle<JSFunction> fun =
CreateFunction(isolate, name, JS_OBJECT_TYPE, JSObject::kHeaderSize, 0,
MaybeHandle<JSObject>(), 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<JSFunction> SimpleInstallFunction(
Handle<JSObject> base, Handle<Name> property_name,
Handle<String> function_name, Builtins::Name call, int len, bool adapt,
PropertyAttributes attrs = DONT_ENUM,
BuiltinFunctionId id = kInvalidBuiltinFunctionId) {
Handle<JSFunction> fun =
SimpleCreateFunction(base->GetIsolate(), function_name, call, len, adapt);
if (id != kInvalidBuiltinFunctionId) {
fun->shared()->set_builtin_function_id(id);
}
InstallFunction(base, fun, property_name, attrs);
return fun;
}
V8_NOINLINE Handle<JSFunction> SimpleInstallFunction(
Handle<JSObject> base, Handle<String> name, Builtins::Name call, int len,
bool adapt, PropertyAttributes attrs = DONT_ENUM,
BuiltinFunctionId id = kInvalidBuiltinFunctionId) {
return SimpleInstallFunction(base, name, name, call, len, adapt, attrs, id);
}
V8_NOINLINE Handle<JSFunction> SimpleInstallFunction(
Handle<JSObject> base, Handle<Name> property_name,
const char* function_name, Builtins::Name call, int len, bool adapt,
PropertyAttributes attrs = DONT_ENUM,
BuiltinFunctionId id = kInvalidBuiltinFunctionId) {
Factory* const factory = base->GetIsolate()->factory();
// Function name does not have to be internalized.
return SimpleInstallFunction(
base, property_name, factory->NewStringFromAsciiChecked(function_name),
call, len, adapt, attrs, id);
}
V8_NOINLINE Handle<JSFunction> SimpleInstallFunction(
Handle<JSObject> base, const char* name, Builtins::Name call, int len,
bool adapt, PropertyAttributes attrs = DONT_ENUM,
BuiltinFunctionId id = kInvalidBuiltinFunctionId) {
Factory* const factory = base->GetIsolate()->factory();
// 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(base, factory->InternalizeUtf8String(name), call,
len, adapt, attrs, id);
}
V8_NOINLINE Handle<JSFunction> SimpleInstallFunction(Handle<JSObject> base,
const char* name,
Builtins::Name call,
int len, bool adapt,
BuiltinFunctionId id) {
return SimpleInstallFunction(base, name, call, len, adapt, DONT_ENUM, id);
}
V8_NOINLINE void SimpleInstallGetterSetter(Handle<JSObject> base,
Handle<String> name,
Builtins::Name call_getter,
Builtins::Name call_setter,
PropertyAttributes attribs) {
Isolate* const isolate = base->GetIsolate();
Handle<String> getter_name =
Name::ToFunctionName(name, isolate->factory()->get_string())
.ToHandleChecked();
Handle<JSFunction> getter =
SimpleCreateFunction(isolate, getter_name, call_getter, 0, true);
Handle<String> setter_name =
Name::ToFunctionName(name, isolate->factory()->set_string())
.ToHandleChecked();
Handle<JSFunction> setter =
SimpleCreateFunction(isolate, setter_name, call_setter, 1, true);
JSObject::DefineAccessor(base, name, getter, setter, attribs).Check();
}
V8_NOINLINE Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
Handle<Name> name,
Handle<Name> property_name,
Builtins::Name call,
bool adapt) {
Isolate* const isolate = base->GetIsolate();
Handle<String> getter_name =
Name::ToFunctionName(name, isolate->factory()->get_string())
.ToHandleChecked();
Handle<JSFunction> getter =
SimpleCreateFunction(isolate, getter_name, call, 0, adapt);
Handle<Object> setter = isolate->factory()->undefined_value();
JSObject::DefineAccessor(base, property_name, getter, setter, DONT_ENUM)
.Check();
return getter;
}
V8_NOINLINE Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
Handle<Name> name,
Builtins::Name call,
bool adapt) {
return SimpleInstallGetter(base, name, name, call, adapt);
}
V8_NOINLINE Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
Handle<Name> name,
Builtins::Name call,
bool adapt,
BuiltinFunctionId id) {
Handle<JSFunction> fun = SimpleInstallGetter(base, name, call, adapt);
fun->shared()->set_builtin_function_id(id);
return fun;
}
V8_NOINLINE void InstallConstant(Isolate* isolate, Handle<JSObject> holder,
const char* name, Handle<Object> value) {
JSObject::AddProperty(
holder, isolate->factory()->NewStringFromAsciiChecked(name), value,
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
}
V8_NOINLINE void InstallSpeciesGetter(Handle<JSFunction> constructor) {
Factory* factory = constructor->GetIsolate()->factory();
// TODO(adamk): We should be able to share a SharedFunctionInfo
// between all these JSFunctins.
SimpleInstallGetter(constructor, factory->symbol_species_string(),
factory->species_symbol(), Builtins::kReturnReceiver,
true);
}
} // namespace
Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
Factory* factory = isolate->factory();
// Allocate the function map first and then patch the prototype later.
Handle<Map> empty_function_map = factory->CreateSloppyFunctionMap(
FUNCTION_WITHOUT_PROTOTYPE, MaybeHandle<JSFunction>());
empty_function_map->set_is_prototype_map(true);
DCHECK(!empty_function_map->is_dictionary_map());
// Allocate the empty function as the prototype for function according to
// ES#sec-properties-of-the-function-prototype-object
Handle<Code> code(BUILTIN_CODE(isolate, EmptyFunction));
NewFunctionArgs args =
NewFunctionArgs::ForBuiltin(factory->empty_string(), code,
empty_function_map, Builtins::kEmptyFunction);
Handle<JSFunction> empty_function = factory->NewFunction(args);
// --- E m p t y ---
Handle<String> source = factory->NewStringFromStaticChars("() {}");
Handle<Script> script = factory->NewScript(source);
script->set_type(Script::TYPE_NATIVE);
Handle<FixedArray> infos = factory->NewFixedArray(2);
script->set_shared_function_infos(*infos);
empty_function->shared()->set_start_position(0);
empty_function->shared()->set_end_position(source->length());
empty_function->shared()->set_function_literal_id(1);
empty_function->shared()->DontAdaptArguments();
SharedFunctionInfo::SetScript(handle(empty_function->shared()), script);
return empty_function;
}
void Genesis::CreateSloppyModeFunctionMaps(Handle<JSFunction> empty) {
Factory* factory = isolate_->factory();
Handle<Map> map;
//
// Allocate maps for sloppy functions without prototype.
//
map = factory->CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
native_context()->set_sloppy_function_without_prototype_map(*map);
//
// Allocate maps for sloppy functions with readonly prototype.
//
map =
factory->CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
native_context()->set_sloppy_function_with_readonly_prototype_map(*map);
//
// Allocate maps for sloppy functions with writable prototype.
//
map = factory->CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE,
empty);
native_context()->set_sloppy_function_map(*map);
map = factory->CreateSloppyFunctionMap(
FUNCTION_WITH_NAME_AND_WRITEABLE_PROTOTYPE, empty);
native_context()->set_sloppy_function_with_name_map(*map);
}
Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic() {
if (!restricted_properties_thrower_.is_null()) {
return restricted_properties_thrower_;
}
Handle<String> name(factory()->empty_string());
Handle<Code> code = BUILTIN_CODE(isolate(), StrictPoisonPillThrower);
NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithoutPrototype(
name, code, Builtins::kStrictPoisonPillThrower, i::LanguageMode::kStrict);
Handle<JSFunction> function = factory()->NewFunction(args);
function->shared()->DontAdaptArguments();
// %ThrowTypeError% must not have a name property.
if (JSReceiver::DeleteProperty(function, factory()->name_string())
.IsNothing()) {
DCHECK(false);
}
// length needs to be non configurable.
Handle<Object> value(Smi::FromInt(function->shared()->GetLength()),
isolate());
JSObject::SetOwnPropertyIgnoreAttributes(
function, factory()->length_string(), value,
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
.Assert();
if (JSObject::PreventExtensions(function, kThrowOnError).IsNothing()) {
DCHECK(false);
}
JSObject::MigrateSlowToFast(function, 0, "Bootstrapping");
restricted_properties_thrower_ = function;
return function;
}
void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
Factory* factory = isolate_->factory();
Handle<Map> map;
//
// Allocate maps for strict functions without prototype.
//
map = factory->CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
native_context()->set_strict_function_without_prototype_map(*map);
map = factory->CreateStrictFunctionMap(METHOD_WITH_NAME, empty);
native_context()->set_method_with_name_map(*map);
map = factory->CreateStrictFunctionMap(METHOD_WITH_HOME_OBJECT, empty);
native_context()->set_method_with_home_object_map(*map);
map =
factory->CreateStrictFunctionMap(METHOD_WITH_NAME_AND_HOME_OBJECT, empty);
native_context()->set_method_with_name_and_home_object_map(*map);
//
// Allocate maps for strict functions with writable prototype.
//
map = factory->CreateStrictFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE,
empty);
native_context()->set_strict_function_map(*map);
map = factory->CreateStrictFunctionMap(
FUNCTION_WITH_NAME_AND_WRITEABLE_PROTOTYPE, empty);
native_context()->set_strict_function_with_name_map(*map);
strict_function_with_home_object_map_ = factory->CreateStrictFunctionMap(
FUNCTION_WITH_HOME_OBJECT_AND_WRITEABLE_PROTOTYPE, empty);
strict_function_with_name_and_home_object_map_ =
factory->CreateStrictFunctionMap(
FUNCTION_WITH_NAME_AND_HOME_OBJECT_AND_WRITEABLE_PROTOTYPE, empty);
//
// Allocate maps for strict functions with readonly prototype.
//
map =
factory->CreateStrictFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
native_context()->set_strict_function_with_readonly_prototype_map(*map);
//
// Allocate map for class functions.
//
map = factory->CreateClassFunctionMap(empty);
native_context()->set_class_function_map(*map);
// Now that the strict mode function map is available, set up the
// restricted "arguments" and "caller" getters.
AddRestrictedFunctionProperties(empty);
}
void Genesis::CreateObjectFunction(Handle<JSFunction> empty_function) {
Factory* factory = isolate_->factory();
// --- O b j e c t ---
int inobject_properties = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
int instance_size =
JSObject::kHeaderSize + kPointerSize * inobject_properties;
Handle<JSFunction> object_fun = CreateFunction(
isolate_, factory->Object_string(), JS_OBJECT_TYPE, instance_size,
inobject_properties, factory->null_value(), Builtins::kObjectConstructor);
object_fun->shared()->set_length(1);
object_fun->shared()->DontAdaptArguments();
object_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate_, ObjectConstructor_ConstructStub));
native_context()->set_object_function(*object_fun);
{
// Finish setting up Object function's initial map.
Map* initial_map = object_fun->initial_map();
initial_map->set_elements_kind(HOLEY_ELEMENTS);
}
// Allocate a new prototype for the object function.
Handle<JSObject> object_function_prototype =
factory->NewFunctionPrototype(object_fun);
Handle<Map> map = Map::Copy(handle(object_function_prototype->map()),
"EmptyObjectPrototype");
map->set_is_prototype_map(true);
// Ban re-setting Object.prototype.__proto__ to prevent Proxy security bug
map->set_is_immutable_proto(true);
object_function_prototype->set_map(*map);
// Complete setting up empty function.
{
Handle<Map> empty_function_map(empty_function->map(), isolate_);
Map::SetPrototype(empty_function_map, object_function_prototype);
}
native_context()->set_initial_object_prototype(*object_function_prototype);
JSFunction::SetPrototype(object_fun, object_function_prototype);
{
// Set up slow map for Object.create(null) instances without in-object
// properties.
Handle<Map> map(object_fun->initial_map(), isolate_);
map = Map::CopyInitialMapNormalized(map);
Map::SetPrototype(map, factory->null_value());
native_context()->set_slow_object_with_null_prototype_map(*map);
// Set up slow map for literals with too many properties.
map = Map::Copy(map, "slow_object_with_object_prototype_map");
Map::SetPrototype(map, object_function_prototype);
native_context()->set_slow_object_with_object_prototype_map(*map);
}
}
namespace {
Handle<Map> CreateNonConstructorMap(Handle<Map> source_map,
Handle<JSObject> prototype,
const char* reason) {
Handle<Map> map = Map::Copy(source_map, reason);
// Ensure the resulting map has prototype slot (it is necessary for storing
// inital map even when the prototype property is not required).
if (!map->has_prototype_slot()) {
// Re-set the unused property fields after changing the instance size.
// TODO(ulan): Do not change instance size after map creation.
int unused_property_fields = map->UnusedPropertyFields();
map->set_instance_size(map->instance_size() + kPointerSize);
// The prototype slot shifts the in-object properties area by one slot.
map->SetInObjectPropertiesStartInWords(
map->GetInObjectPropertiesStartInWords() + 1);
map->set_has_prototype_slot(true);
map->SetInObjectUnusedPropertyFields(unused_property_fields);
}
map->set_is_constructor(false);
Map::SetPrototype(map, prototype);
return map;
}
} // namespace
void Genesis::CreateIteratorMaps(Handle<JSFunction> empty) {
// Create iterator-related meta-objects.
Handle<JSObject> iterator_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
SimpleInstallFunction(iterator_prototype, factory()->iterator_symbol(),
"[Symbol.iterator]", Builtins::kReturnReceiver, 0,
true);
native_context()->set_initial_iterator_prototype(*iterator_prototype);
Handle<JSObject> generator_object_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
native_context()->set_initial_generator_prototype(
*generator_object_prototype);
JSObject::ForceSetPrototype(generator_object_prototype, iterator_prototype);
Handle<JSObject> generator_function_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
JSObject::ForceSetPrototype(generator_function_prototype, empty);
JSObject::AddProperty(
generator_function_prototype, factory()->to_string_tag_symbol(),
factory()->NewStringFromAsciiChecked("GeneratorFunction"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
JSObject::AddProperty(generator_function_prototype,
factory()->prototype_string(),
generator_object_prototype,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
JSObject::AddProperty(generator_object_prototype,
factory()->constructor_string(),
generator_function_prototype,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
JSObject::AddProperty(generator_object_prototype,
factory()->to_string_tag_symbol(),
factory()->NewStringFromAsciiChecked("Generator"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
SimpleInstallFunction(generator_object_prototype, "next",
Builtins::kGeneratorPrototypeNext, 1, false);
SimpleInstallFunction(generator_object_prototype, "return",
Builtins::kGeneratorPrototypeReturn, 1, false);
SimpleInstallFunction(generator_object_prototype, "throw",
Builtins::kGeneratorPrototypeThrow, 1, false);
// Internal version of generator_prototype_next, flagged as non-native such
// that it doesn't show up in Error traces.
Handle<JSFunction> generator_next_internal =
SimpleCreateFunction(isolate(), factory()->next_string(),
Builtins::kGeneratorPrototypeNext, 1, false);
generator_next_internal->shared()->set_native(false);
native_context()->set_generator_next_internal(*generator_next_internal);
// Create maps for generator functions and their prototypes. Store those
// maps in the native context. The "prototype" property descriptor is
// writable, non-enumerable, and non-configurable (as per ES6 draft
// 04-14-15, section 25.2.4.3).
// Generator functions do not have "caller" or "arguments" accessors.
Handle<Map> map;
map = CreateNonConstructorMap(isolate()->strict_function_map(),
generator_function_prototype,
"GeneratorFunction");
native_context()->set_generator_function_map(*map);
map = CreateNonConstructorMap(isolate()->strict_function_with_name_map(),
generator_function_prototype,
"GeneratorFunction with name");
native_context()->set_generator_function_with_name_map(*map);
map = CreateNonConstructorMap(strict_function_with_home_object_map_,
generator_function_prototype,
"GeneratorFunction with home object");
native_context()->set_generator_function_with_home_object_map(*map);
map = CreateNonConstructorMap(strict_function_with_name_and_home_object_map_,
generator_function_prototype,
"GeneratorFunction with name and home object");
native_context()->set_generator_function_with_name_and_home_object_map(*map);
Handle<JSFunction> object_function(native_context()->object_function());
Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
Map::SetPrototype(generator_object_prototype_map, generator_object_prototype);
native_context()->set_generator_object_prototype_map(
*generator_object_prototype_map);
}
void Genesis::CreateAsyncIteratorMaps(Handle<JSFunction> empty) {
// %AsyncIteratorPrototype%
// proposal-async-iteration/#sec-asynciteratorprototype
Handle<JSObject> async_iterator_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
SimpleInstallFunction(
async_iterator_prototype, factory()->async_iterator_symbol(),
"[Symbol.asyncIterator]", Builtins::kReturnReceiver, 0, true);
// %AsyncFromSyncIteratorPrototype%
// proposal-async-iteration/#sec-%asyncfromsynciteratorprototype%-object
Handle<JSObject> async_from_sync_iterator_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
SimpleInstallFunction(async_from_sync_iterator_prototype,
factory()->next_string(),
Builtins::kAsyncFromSyncIteratorPrototypeNext, 1, true);
SimpleInstallFunction(
async_from_sync_iterator_prototype, factory()->return_string(),
Builtins::kAsyncFromSyncIteratorPrototypeReturn, 1, true);
SimpleInstallFunction(
async_from_sync_iterator_prototype, factory()->throw_string(),
Builtins::kAsyncFromSyncIteratorPrototypeThrow, 1, true);
JSObject::AddProperty(
async_from_sync_iterator_prototype, factory()->to_string_tag_symbol(),
factory()->NewStringFromAsciiChecked("Async-from-Sync Iterator"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
JSObject::ForceSetPrototype(async_from_sync_iterator_prototype,
async_iterator_prototype);
Handle<Map> async_from_sync_iterator_map = factory()->NewMap(
JS_ASYNC_FROM_SYNC_ITERATOR_TYPE, JSAsyncFromSyncIterator::kSize);
Map::SetPrototype(async_from_sync_iterator_map,
async_from_sync_iterator_prototype);
native_context()->set_async_from_sync_iterator_map(
*async_from_sync_iterator_map);
// Async Generators
Handle<String> AsyncGeneratorFunction_string =
factory()->NewStringFromAsciiChecked("AsyncGeneratorFunction", TENURED);
Handle<JSObject> async_generator_object_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
Handle<JSObject> async_generator_function_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
// %AsyncGenerator% / %AsyncGeneratorFunction%.prototype
JSObject::ForceSetPrototype(async_generator_function_prototype, empty);
// The value of AsyncGeneratorFunction.prototype.prototype is the
// %AsyncGeneratorPrototype% intrinsic object.
// This property has the attributes
// { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
JSObject::AddProperty(async_generator_function_prototype,
factory()->prototype_string(),
async_generator_object_prototype,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
JSObject::AddProperty(async_generator_function_prototype,
factory()->to_string_tag_symbol(),
AsyncGeneratorFunction_string,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
// %AsyncGeneratorPrototype%
JSObject::ForceSetPrototype(async_generator_object_prototype,
async_iterator_prototype);
native_context()->set_initial_async_generator_prototype(
*async_generator_object_prototype);
JSObject::AddProperty(async_generator_object_prototype,
factory()->to_string_tag_symbol(),
factory()->NewStringFromAsciiChecked("AsyncGenerator"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
SimpleInstallFunction(async_generator_object_prototype, "next",
Builtins::kAsyncGeneratorPrototypeNext, 1, false);
SimpleInstallFunction(async_generator_object_prototype, "return",
Builtins::kAsyncGeneratorPrototypeReturn, 1, false);
SimpleInstallFunction(async_generator_object_prototype, "throw",
Builtins::kAsyncGeneratorPrototypeThrow, 1, false);
// Create maps for generator functions and their prototypes. Store those
// maps in the native context. The "prototype" property descriptor is
// writable, non-enumerable, and non-configurable (as per ES6 draft
// 04-14-15, section 25.2.4.3).
// Async Generator functions do not have "caller" or "arguments" accessors.
Handle<Map> map;
map = CreateNonConstructorMap(isolate()->strict_function_map(),
async_generator_function_prototype,
"AsyncGeneratorFunction");
native_context()->set_async_generator_function_map(*map);
map = CreateNonConstructorMap(isolate()->strict_function_with_name_map(),
async_generator_function_prototype,
"AsyncGeneratorFunction with name");
native_context()->set_async_generator_function_with_name_map(*map);
map = CreateNonConstructorMap(strict_function_with_home_object_map_,
async_generator_function_prototype,
"AsyncGeneratorFunction with home object");
native_context()->set_async_generator_function_with_home_object_map(*map);
map = CreateNonConstructorMap(
strict_function_with_name_and_home_object_map_,
async_generator_function_prototype,
"AsyncGeneratorFunction with name and home object");
native_context()->set_async_generator_function_with_name_and_home_object_map(
*map);
Handle<JSFunction> object_function(native_context()->object_function());
Handle<Map> async_generator_object_prototype_map = Map::Create(isolate(), 0);
Map::SetPrototype(async_generator_object_prototype_map,
async_generator_object_prototype);
native_context()->set_async_generator_object_prototype_map(
*async_generator_object_prototype_map);
}
void Genesis::CreateAsyncFunctionMaps(Handle<JSFunction> empty) {
// %AsyncFunctionPrototype% intrinsic
Handle<JSObject> async_function_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
JSObject::ForceSetPrototype(async_function_prototype, empty);
JSObject::AddProperty(async_function_prototype,
factory()->to_string_tag_symbol(),
factory()->NewStringFromAsciiChecked("AsyncFunction"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
Handle<Map> map;
map = CreateNonConstructorMap(
isolate()->strict_function_without_prototype_map(),
async_function_prototype, "AsyncFunction");
native_context()->set_async_function_map(*map);
map = CreateNonConstructorMap(isolate()->method_with_name_map(),
async_function_prototype,
"AsyncFunction with name");
native_context()->set_async_function_with_name_map(*map);
map = CreateNonConstructorMap(isolate()->method_with_home_object_map(),
async_function_prototype,
"AsyncFunction with home object");
native_context()->set_async_function_with_home_object_map(*map);
map = CreateNonConstructorMap(
isolate()->method_with_name_and_home_object_map(),
async_function_prototype, "AsyncFunction with name and home object");
native_context()->set_async_function_with_name_and_home_object_map(*map);
}
void Genesis::CreateJSProxyMaps() {
// Allocate maps for all Proxy types.
// Next to the default proxy, we need maps indicating callable and
// constructable proxies.
Handle<Map> proxy_map = factory()->NewMap(JS_PROXY_TYPE, JSProxy::kSize,
TERMINAL_FAST_ELEMENTS_KIND);
proxy_map->set_is_dictionary_map(true);
proxy_map->set_may_have_interesting_symbols(true);
native_context()->set_proxy_map(*proxy_map);
Handle<Map> proxy_callable_map = Map::Copy(proxy_map, "callable Proxy");
proxy_callable_map->set_is_callable(true);
native_context()->set_proxy_callable_map(*proxy_callable_map);
proxy_callable_map->SetConstructor(native_context()->function_function());
Handle<Map> proxy_constructor_map =
Map::Copy(proxy_callable_map, "constructor Proxy");
proxy_constructor_map->set_is_constructor(true);
native_context()->set_proxy_constructor_map(*proxy_constructor_map);
{
Handle<Map> map =
factory()->NewMap(JS_OBJECT_TYPE, JSProxyRevocableResult::kSize,
TERMINAL_FAST_ELEMENTS_KIND, 2);
Map::EnsureDescriptorSlack(map, 2);
{ // proxy
Descriptor d = Descriptor::DataField(factory()->proxy_string(),
JSProxyRevocableResult::kProxyIndex,
NONE, Representation::Tagged());
map->AppendDescriptor(&d);
}
{ // revoke
Descriptor d = Descriptor::DataField(factory()->revoke_string(),
JSProxyRevocableResult::kRevokeIndex,
NONE, Representation::Tagged());
map->AppendDescriptor(&d);
}
Map::SetPrototype(map, isolate()->initial_object_prototype());
map->SetConstructor(native_context()->object_function());
native_context()->set_proxy_revocable_result_map(*map);
}
}
namespace {
void ReplaceAccessors(Handle<Map> map, Handle<String> name,
PropertyAttributes attributes,
Handle<AccessorPair> accessor_pair) {
DescriptorArray* descriptors = map->instance_descriptors();
int idx = descriptors->SearchWithCache(map->GetIsolate(), *name, *map);
Descriptor d = Descriptor::AccessorConstant(name, accessor_pair, attributes);
descriptors->Replace(idx, &d);
}
} // namespace
void Genesis::AddRestrictedFunctionProperties(Handle<JSFunction> empty) {
PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
Handle<JSFunction> thrower = GetThrowTypeErrorIntrinsic();
Handle<AccessorPair> accessors = factory()->NewAccessorPair();
accessors->set_getter(*thrower);
accessors->set_setter(*thrower);
Handle<Map> map(empty->map());
ReplaceAccessors(map, factory()->arguments_string(), rw_attribs, accessors);
ReplaceAccessors(map, factory()->caller_string(), rw_attribs, accessors);
}
static void AddToWeakNativeContextList(Context* context) {
DCHECK(context->IsNativeContext());
Isolate* isolate = context->GetIsolate();
Heap* heap = isolate->heap();
#ifdef DEBUG
{ // NOLINT
DCHECK(context->next_context_link()->IsUndefined(isolate));
// Check that context is not in the list yet.
for (Object* current = heap->native_contexts_list();
!current->IsUndefined(isolate);
current = Context::cast(current)->next_context_link()) {
DCHECK(current != context);
}
}
#endif
context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list(),
UPDATE_WEAK_WRITE_BARRIER);
heap->set_native_contexts_list(context);
}
void Genesis::CreateRoots() {
// Allocate the native context FixedArray first and then patch the
// closure and extension object later (we need the empty function
// and the global object, but in order to create those, we need the
// native context).
native_context_ = factory()->NewNativeContext();
AddToWeakNativeContextList(*native_context());
isolate()->set_context(*native_context());
// Allocate the message listeners object.
{
Handle<TemplateList> list = TemplateList::New(isolate(), 1);
native_context()->set_message_listeners(*list);
}
}
void Genesis::InstallGlobalThisBinding() {
Handle<ScriptContextTable> script_contexts(
native_context()->script_context_table());
Handle<ScopeInfo> scope_info = ScopeInfo::CreateGlobalThisBinding(isolate());
Handle<JSFunction> closure(native_context()->closure());
Handle<Context> context = factory()->NewScriptContext(closure, scope_info);
// Go ahead and hook it up while we're at it.
int slot = scope_info->ReceiverContextSlotIndex();
DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
context->set(slot, native_context()->global_proxy());
Handle<ScriptContextTable> new_script_contexts =
ScriptContextTable::Extend(script_contexts, context);
native_context()->set_script_context_table(*new_script_contexts);
}
Handle<JSGlobalObject> Genesis::CreateNewGlobals(
v8::Local<v8::ObjectTemplate> global_proxy_template,
Handle<JSGlobalProxy> global_proxy) {
// The argument global_proxy_template aka data is an ObjectTemplateInfo.
// It has a constructor pointer that points at global_constructor which is a
// FunctionTemplateInfo.
// The global_proxy_constructor is used to (re)initialize the
// global_proxy. The global_proxy_constructor also has a prototype_template
// pointer that points at js_global_object_template which is an
// ObjectTemplateInfo.
// That in turn has a constructor pointer that points at
// js_global_object_constructor which is a FunctionTemplateInfo.
// js_global_object_constructor is used to make js_global_object_function
// js_global_object_function is used to make the new global_object.
//
// --- G l o b a l ---
// Step 1: Create a fresh JSGlobalObject.
Handle<JSFunction> js_global_object_function;
Handle<ObjectTemplateInfo> js_global_object_template;
if (!global_proxy_template.IsEmpty()) {
// Get prototype template of the global_proxy_template.
Handle<ObjectTemplateInfo> data =
v8::Utils::OpenHandle(*global_proxy_template);
Handle<FunctionTemplateInfo> global_constructor =
Handle<FunctionTemplateInfo>(
FunctionTemplateInfo::cast(data->constructor()));
Handle<Object> proto_template(global_constructor->prototype_template(),
isolate());
if (!proto_template->IsUndefined(isolate())) {
js_global_object_template =
Handle<ObjectTemplateInfo>::cast(proto_template);
}
}
if (js_global_object_template.is_null()) {
Handle<String> name(factory()->empty_string());
Handle<Code> code = BUILTIN_CODE(isolate(), Illegal);
Handle<JSObject> prototype =
factory()->NewFunctionPrototype(isolate()->object_function());
NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
name, code, prototype, JS_GLOBAL_OBJECT_TYPE, JSGlobalObject::kSize, 0,
Builtins::kIllegal, MUTABLE);
js_global_object_function = factory()->NewFunction(args);
#ifdef DEBUG
LookupIterator it(prototype, factory()->constructor_string(),
LookupIterator::OWN_SKIP_INTERCEPTOR);
Handle<Object> value = Object::GetProperty(&it).ToHandleChecked();
DCHECK(it.IsFound());
DCHECK_EQ(*isolate()->object_function(), *value);
#endif
} else {
Handle<FunctionTemplateInfo> js_global_object_constructor(
FunctionTemplateInfo::cast(js_global_object_template->constructor()));
js_global_object_function = ApiNatives::CreateApiFunction(
isolate(), js_global_object_constructor, factory()->the_hole_value(),
ApiNatives::GlobalObjectType);
}
js_global_object_function->initial_map()->set_is_prototype_map(true);
js_global_object_function->initial_map()->set_is_dictionary_map(true);
js_global_object_function->initial_map()->set_may_have_interesting_symbols(
true);
Handle<JSGlobalObject> global_object =
factory()->NewJSGlobalObject(js_global_object_function);
// Step 2: (re)initialize the global proxy object.
Handle<JSFunction> global_proxy_function;
if (global_proxy_template.IsEmpty()) {
Handle<String> name(factory()->empty_string());
Handle<Code> code = BUILTIN_CODE(isolate(), Illegal);
NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
name, code, factory()->the_hole_value(), JS_GLOBAL_PROXY_TYPE,
JSGlobalProxy::SizeWithEmbedderFields(0), 0, Builtins::kIllegal,
MUTABLE);
global_proxy_function = factory()->NewFunction(args);
} else {
Handle<ObjectTemplateInfo> data =
v8::Utils::OpenHandle(*global_proxy_template);
Handle<FunctionTemplateInfo> global_constructor(
FunctionTemplateInfo::cast(data->constructor()));
global_proxy_function = ApiNatives::CreateApiFunction(
isolate(), global_constructor, factory()->the_hole_value(),
ApiNatives::GlobalProxyType);
}
Handle<String> global_name = factory()->global_string();
global_proxy_function->shared()->set_instance_class_name(*global_name);
global_proxy_function->initial_map()->set_is_access_check_needed(true);
global_proxy_function->initial_map()->set_has_hidden_prototype(true);
global_proxy_function->initial_map()->set_may_have_interesting_symbols(true);
native_context()->set_global_proxy_function(*global_proxy_function);
// Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
// Return the global proxy.
factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
// Set the native context for the global object.
global_object->set_native_context(*native_context());
global_object->set_global_proxy(*global_proxy);
// Set the native context of the global proxy.
global_proxy->set_native_context(*native_context());
// Set the global proxy of the native context. If the native context has been
// deserialized, the global proxy is already correctly set up by the
// deserializer. Otherwise it's undefined.
DCHECK(native_context()
->get(Context::GLOBAL_PROXY_INDEX)
->IsUndefined(isolate()) ||
native_context()->global_proxy() == *global_proxy);
native_context()->set_global_proxy(*global_proxy);
return global_object;
}
void Genesis::HookUpGlobalProxy(Handle<JSGlobalProxy> global_proxy) {
// Re-initialize the global proxy with the global proxy function from the
// snapshot, and then set up the link to the native context.
Handle<JSFunction> global_proxy_function(
native_context()->global_proxy_function());
factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
Handle<JSObject> global_object(
JSObject::cast(native_context()->global_object()));
JSObject::ForceSetPrototype(global_proxy, global_object);
global_proxy->set_native_context(*native_context());
DCHECK(native_context()->global_proxy() == *global_proxy);
}
void Genesis::HookUpGlobalObject(Handle<JSGlobalObject> global_object) {
Handle<JSGlobalObject> global_object_from_snapshot(
JSGlobalObject::cast(native_context()->extension()));
native_context()->set_extension(*global_object);
native_context()->set_security_token(*global_object);
TransferNamedProperties(global_object_from_snapshot, global_object);
TransferIndexedProperties(global_object_from_snapshot, global_object);
}
static void InstallWithIntrinsicDefaultProto(Isolate* isolate,
Handle<JSFunction> function,
int context_index) {
Handle<Smi> index(Smi::FromInt(context_index), isolate);
JSObject::AddProperty(
function, isolate->factory()->native_context_index_symbol(), index, NONE);
isolate->native_context()->set(context_index, *function);
}
static void InstallError(Isolate* isolate, Handle<JSObject> global,
Handle<String> name, int context_index) {
Factory* factory = isolate->factory();
Handle<JSFunction> error_fun = InstallFunction(
global, name, JS_ERROR_TYPE, JSObject::kHeaderSize, 0,
factory->the_hole_value(), Builtins::kErrorConstructor, DONT_ENUM);
error_fun->shared()->set_instance_class_name(*factory->Error_string());
error_fun->shared()->DontAdaptArguments();
error_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate, ErrorConstructor));
error_fun->shared()->set_length(1);
if (context_index == Context::ERROR_FUNCTION_INDEX) {
SimpleInstallFunction(error_fun, "captureStackTrace",
Builtins::kErrorCaptureStackTrace, 2, false);
}
InstallWithIntrinsicDefaultProto(isolate, error_fun, context_index);
{
// Setup %XXXErrorPrototype%.
Handle<JSObject> prototype(JSObject::cast(error_fun->instance_prototype()));
JSObject::AddProperty(prototype, factory->name_string(), name, DONT_ENUM);
JSObject::AddProperty(prototype, factory->message_string(),
factory->empty_string(), DONT_ENUM);
if (context_index == Context::ERROR_FUNCTION_INDEX) {
Handle<JSFunction> to_string_fun =
SimpleInstallFunction(prototype, factory->toString_string(),
Builtins::kErrorPrototypeToString, 0, true);
isolate->native_context()->set_error_to_string(*to_string_fun);
isolate->native_context()->set_initial_error_prototype(*prototype);
} else {
DCHECK(isolate->native_context()->error_to_string()->IsJSFunction());
InstallFunction(prototype, isolate->error_to_string(),
factory->toString_string(), DONT_ENUM);
Handle<JSFunction> global_error = isolate->error_function();
CHECK(JSReceiver::SetPrototype(error_fun, global_error, false,
kThrowOnError)
.FromMaybe(false));
CHECK(JSReceiver::SetPrototype(prototype,
handle(global_error->prototype(), isolate),
false, kThrowOnError)
.FromMaybe(false));
}
}
Handle<Map> initial_map(error_fun->initial_map());
Map::EnsureDescriptorSlack(initial_map, 1);
{
Handle<AccessorInfo> info = factory->error_stack_accessor();
Descriptor d = Descriptor::AccessorConstant(handle(info->name(), isolate),
info, DONT_ENUM);
initial_map->AppendDescriptor(&d);
}
}
namespace {
void InstallMakeError(Isolate* isolate, int builtin_id, int context_index) {
Handle<Code> code(isolate->builtins()->builtin(builtin_id));
NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
isolate->factory()->empty_string(), code,
isolate->factory()->the_hole_value(), JS_OBJECT_TYPE,
JSObject::kHeaderSize, 0, builtin_id, MUTABLE);
Handle<JSFunction> function = isolate->factory()->NewFunction(args);
function->shared()->DontAdaptArguments();
isolate->native_context()->set(context_index, *function);
}
} // namespace
// This is only called if we are not using snapshots. The equivalent
// work in the snapshot case is done in HookUpGlobalObject.
void Genesis::InitializeGlobal(Handle<JSGlobalObject> global_object,
Handle<JSFunction> empty_function,
GlobalContextType context_type) {
// --- N a t i v e C o n t e x t ---
// Use the empty function as closure (no scope info).
native_context()->set_closure(*empty_function);
native_context()->set_previous(nullptr);
// Set extension and global object.
native_context()->set_extension(*global_object);
// Security setup: Set the security token of the native context to the global
// object. This makes the security check between two different contexts fail
// by default even in case of global object reinitialization.
native_context()->set_security_token(*global_object);
Isolate* isolate = global_object->GetIsolate();
Factory* factory = isolate->factory();
Handle<ScriptContextTable> script_context_table =
factory->NewScriptContextTable();
native_context()->set_script_context_table(*script_context_table);
InstallGlobalThisBinding();
{ // --- O b j e c t ---
Handle<String> object_name = factory->Object_string();
Handle<JSFunction> object_function = isolate->object_function();
JSObject::AddProperty(global_object, object_name, object_function,
DONT_ENUM);
SimpleInstallFunction(object_function, factory->assign_string(),
Builtins::kObjectAssign, 2, false);
SimpleInstallFunction(object_function, "getOwnPropertyDescriptor",
Builtins::kObjectGetOwnPropertyDescriptor, 2, false);
SimpleInstallFunction(object_function,
factory->getOwnPropertyDescriptors_string(),
Builtins::kObjectGetOwnPropertyDescriptors, 1, false);
SimpleInstallFunction(object_function, "getOwnPropertyNames",
Builtins::kObjectGetOwnPropertyNames, 1, false);
SimpleInstallFunction(object_function, "getOwnPropertySymbols",
Builtins::kObjectGetOwnPropertySymbols, 1, false);
SimpleInstallFunction(object_function, "is",
Builtins::kObjectIs, 2, true);
SimpleInstallFunction(object_function, "preventExtensions",
Builtins::kObjectPreventExtensions, 1, false);
SimpleInstallFunction(object_function, "seal",
Builtins::kObjectSeal, 1, false);
Handle<JSFunction> object_create =
SimpleInstallFunction(object_function, factory->create_string(),
Builtins::kObjectCreate, 2, false);
native_context()->set_object_create(*object_create);
Handle<JSFunction> object_define_properties = SimpleInstallFunction(
object_function, "defineProperties",
Builtins::kObjectDefineProperties, 2, true);
native_context()->set_object_define_properties(*object_define_properties);
Handle<JSFunction> object_define_property = SimpleInstallFunction(
object_function, factory->defineProperty_string(),
Builtins::kObjectDefineProperty, 3, true);
native_context()->set_object_define_property(*object_define_property);
SimpleInstallFunction(object_function, "freeze", Builtins::kObjectFreeze, 1,
false);
Handle<JSFunction> object_get_prototype_of = SimpleInstallFunction(
object_function, "getPrototypeOf", Builtins::kObjectGetPrototypeOf,
1, false);
native_context()->set_object_get_prototype_of(*object_get_prototype_of);
SimpleInstallFunction(object_function, "setPrototypeOf",
Builtins::kObjectSetPrototypeOf, 2, false);
Handle<JSFunction> object_is_extensible = SimpleInstallFunction(
object_function, "isExtensible", Builtins::kObjectIsExtensible,
1, false);
native_context()->set_object_is_extensible(*object_is_extensible);
Handle<JSFunction> object_is_frozen = SimpleInstallFunction(
object_function, "isFrozen", Builtins::kObjectIsFrozen, 1, false);
native_context()->set_object_is_frozen(*object_is_frozen);
Handle<JSFunction> object_is_sealed = SimpleInstallFunction(
object_function, "isSealed", Builtins::kObjectIsSealed, 1, false);
native_context()->set_object_is_sealed(*object_is_sealed);
Handle<JSFunction> object_keys = SimpleInstallFunction(
object_function, "keys", Builtins::kObjectKeys, 1, true);
native_context()->set_object_keys(*object_keys);
SimpleInstallFunction(object_function, factory->entries_string(),
Builtins::kObjectEntries, 1, true);
SimpleInstallFunction(object_function, factory->values_string(),
Builtins::kObjectValues, 1, true);
SimpleInstallFunction(isolate->initial_object_prototype(),
"__defineGetter__", Builtins::kObjectDefineGetter, 2,
true);
SimpleInstallFunction(isolate->initial_object_prototype(),
"__defineSetter__", Builtins::kObjectDefineSetter, 2,
true);
SimpleInstallFunction(isolate->initial_object_prototype(), "hasOwnProperty",
Builtins::kObjectPrototypeHasOwnProperty, 1, true);
SimpleInstallFunction(isolate->initial_object_prototype(),
"__lookupGetter__", Builtins::kObjectLookupGetter, 1,
true);
SimpleInstallFunction(isolate->initial_object_prototype(),
"__lookupSetter__", Builtins::kObjectLookupSetter, 1,
true);
SimpleInstallFunction(isolate->initial_object_prototype(), "isPrototypeOf",
Builtins::kObjectPrototypeIsPrototypeOf, 1, true);
SimpleInstallFunction(
isolate->initial_object_prototype(), "propertyIsEnumerable",
Builtins::kObjectPrototypePropertyIsEnumerable, 1, false);
Handle<JSFunction> object_to_string = SimpleInstallFunction(
isolate->initial_object_prototype(), factory->toString_string(),
Builtins::kObjectPrototypeToString, 0, true);
native_context()->set_object_to_string(*object_to_string);
Handle<JSFunction> object_value_of = SimpleInstallFunction(
isolate->initial_object_prototype(), "valueOf",
Builtins::kObjectPrototypeValueOf, 0, true);
native_context()->set_object_value_of(*object_value_of);
SimpleInstallGetterSetter(isolate->initial_object_prototype(),
factory->proto_string(),
Builtins::kObjectPrototypeGetProto,
Builtins::kObjectPrototypeSetProto, DONT_ENUM);
SimpleInstallFunction(isolate->initial_object_prototype(), "toLocaleString",
Builtins::kObjectPrototypeToLocaleString, 0, true);
}
Handle<JSObject> global(native_context()->global_object());
{ // --- F u n c t i o n ---
Handle<JSFunction> prototype = empty_function;
Handle<JSFunction> function_fun = InstallFunction(
global, "Function", JS_FUNCTION_TYPE, JSFunction::kSizeWithPrototype, 0,
prototype, Builtins::kFunctionConstructor);
// Function instances are sloppy by default.
function_fun->set_prototype_or_initial_map(*isolate->sloppy_function_map());
function_fun->shared()->DontAdaptArguments();
function_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate, FunctionConstructor));
function_fun->shared()->set_length(1);
InstallWithIntrinsicDefaultProto(isolate, function_fun,
Context::FUNCTION_FUNCTION_INDEX);
// Setup the methods on the %FunctionPrototype%.
JSObject::AddProperty(prototype, factory->constructor_string(),
function_fun, DONT_ENUM);
SimpleInstallFunction(prototype, factory->apply_string(),
Builtins::kFunctionPrototypeApply, 2, false);
SimpleInstallFunction(prototype, factory->bind_string(),
Builtins::kFastFunctionPrototypeBind, 1, false);
SimpleInstallFunction(prototype, factory->call_string(),
Builtins::kFunctionPrototypeCall, 1, false);
SimpleInstallFunction(prototype, factory->toString_string(),
Builtins::kFunctionPrototypeToString, 0, false);
// Install the @@hasInstance function.
Handle<JSFunction> has_instance = SimpleInstallFunction(
prototype, factory->has_instance_symbol(), "[Symbol.hasInstance]",
Builtins::kFunctionPrototypeHasInstance, 1, true,
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY),
kFunctionHasInstance);
native_context()->set_function_has_instance(*has_instance);
// Complete setting up function maps.
{
isolate->sloppy_function_map()->SetConstructor(*function_fun);
isolate->sloppy_function_with_name_map()->SetConstructor(*function_fun);
isolate->sloppy_function_with_readonly_prototype_map()->SetConstructor(
*function_fun);
isolate->strict_function_map()->SetConstructor(*function_fun);
isolate->strict_function_with_name_map()->SetConstructor(*function_fun);
strict_function_with_home_object_map_->SetConstructor(*function_fun);
strict_function_with_name_and_home_object_map_->SetConstructor(
*function_fun);
isolate->strict_function_with_readonly_prototype_map()->SetConstructor(
*function_fun);
isolate->class_function_map()->SetConstructor(*function_fun);
}
}
{ // --- A s y n c F r o m S y n c I t e r a t o r
Handle<SharedFunctionInfo> info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kAsyncIteratorValueUnwrap, factory->empty_string(),
1);
native_context()->set_async_iterator_value_unwrap_shared_fun(*info);
}
{ // --- A s y n c G e n e r a t o r ---
Handle<JSFunction> await_caught =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kAsyncGeneratorAwaitCaught, 1, false);
native_context()->set_async_generator_await_caught(*await_caught);
Handle<JSFunction> await_uncaught =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kAsyncGeneratorAwaitUncaught, 1, false);
native_context()->set_async_generator_await_uncaught(*await_uncaught);
Handle<SharedFunctionInfo> info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kAsyncGeneratorAwaitResolveClosure,
factory->empty_string(), 1);
native_context()->set_async_generator_await_resolve_shared_fun(*info);
info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kAsyncGeneratorAwaitRejectClosure,
factory->empty_string(), 1);
native_context()->set_async_generator_await_reject_shared_fun(*info);
info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kAsyncGeneratorYieldResolveClosure,
factory->empty_string(), 1);
native_context()->set_async_generator_yield_resolve_shared_fun(*info);
info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kAsyncGeneratorReturnResolveClosure,
factory->empty_string(), 1);
native_context()->set_async_generator_return_resolve_shared_fun(*info);
info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kAsyncGeneratorReturnClosedResolveClosure,
factory->empty_string(), 1);
native_context()->set_async_generator_return_closed_resolve_shared_fun(
*info);
info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kAsyncGeneratorReturnClosedRejectClosure,
factory->empty_string(), 1);
native_context()->set_async_generator_return_closed_reject_shared_fun(
*info);
}
{ // --- A r r a y ---
Handle<JSFunction> array_function = InstallFunction(
global, "Array", JS_ARRAY_TYPE, JSArray::kSize, 0,
isolate->initial_object_prototype(), Builtins::kArrayConstructor);
array_function->shared()->DontAdaptArguments();
array_function->shared()->set_builtin_function_id(kArrayConstructor);
// This seems a bit hackish, but we need to make sure Array.length
// is 1.
array_function->shared()->set_length(1);
Handle<Map> initial_map(array_function->initial_map());
// This assert protects an optimization in
// HGraphBuilder::JSArrayBuilder::EmitMapCode()
DCHECK(initial_map->elements_kind() == GetInitialFastElementsKind());
Map::EnsureDescriptorSlack(initial_map, 1);
PropertyAttributes attribs = static_cast<PropertyAttributes>(
DONT_ENUM | DONT_DELETE);
{ // Add length.
Descriptor d = Descriptor::AccessorConstant(
factory->length_string(), factory->array_length_accessor(), attribs);
initial_map->AppendDescriptor(&d);
}
InstallWithIntrinsicDefaultProto(isolate, array_function,
Context::ARRAY_FUNCTION_INDEX);
InstallSpeciesGetter(array_function);
// Cache the array maps, needed by ArrayConstructorStub
CacheInitialJSArrayMaps(native_context(), initial_map);
ArrayConstructorStub array_constructor_stub(isolate);
Handle<Code> code = array_constructor_stub.GetCode();
array_function->shared()->SetConstructStub(*code);
// Set up %ArrayPrototype%.
// The %ArrayPrototype% has TERMINAL_FAST_ELEMENTS_KIND in order to ensure
// that constant functions stay constant after turning prototype to setup
// mode and back when constant field tracking is enabled.
Handle<JSArray> proto =
factory->NewJSArray(0, TERMINAL_FAST_ELEMENTS_KIND, TENURED);
JSFunction::SetPrototype(array_function, proto);
native_context()->set_initial_array_prototype(*proto);
Handle<JSFunction> is_arraylike = SimpleInstallFunction(
array_function, "isArray", Builtins::kArrayIsArray, 1, true);
native_context()->set_is_arraylike(*is_arraylike);
JSObject::AddProperty(proto, factory->constructor_string(), array_function,
DONT_ENUM);
SimpleInstallFunction(proto, "concat", Builtins::kArrayConcat, 1, false);
SimpleInstallFunction(proto, "find", Builtins::kArrayPrototypeFind, 1,
false);
SimpleInstallFunction(proto, "findIndex",
Builtins::kArrayPrototypeFindIndex, 1, false);
SimpleInstallFunction(proto, "pop", Builtins::kArrayPrototypePop, 0, false);
SimpleInstallFunction(proto, "push", Builtins::kArrayPrototypePush, 1,
false);
SimpleInstallFunction(proto, "shift", Builtins::kArrayPrototypeShift, 0,
false);
SimpleInstallFunction(proto, "unshift", Builtins::kArrayUnshift, 1, false);
if (FLAG_enable_experimental_builtins) {
SimpleInstallFunction(proto, "slice", Builtins::kArrayPrototypeSlice, 2,
false);
} else {
SimpleInstallFunction(proto, "slice", Builtins::kArraySlice, 2, false);
}
SimpleInstallFunction(proto, "splice", Builtins::kArraySplice, 2, false);
SimpleInstallFunction(proto, "includes", Builtins::kArrayIncludes, 1,
false);
SimpleInstallFunction(proto, "indexOf", Builtins::kArrayIndexOf, 1, false);
SimpleInstallFunction(proto, "keys", Builtins::kArrayPrototypeKeys, 0, true,
kArrayKeys);
SimpleInstallFunction(proto, "entries", Builtins::kArrayPrototypeEntries, 0,
true, kArrayEntries);
SimpleInstallFunction(proto, factory->iterator_symbol(), "values",
Builtins::kArrayPrototypeValues, 0, true, DONT_ENUM,
kArrayValues);
SimpleInstallFunction(proto, "forEach", Builtins::kArrayForEach, 1, false);
SimpleInstallFunction(proto, "filter", Builtins::kArrayFilter, 1, false);
SimpleInstallFunction(proto, "map", Builtins::kArrayMap, 1, false);
SimpleInstallFunction(proto, "every", Builtins::kArrayEvery, 1, false);
SimpleInstallFunction(proto, "some", Builtins::kArraySome, 1, false);
SimpleInstallFunction(proto, "reduce", Builtins::kArrayReduce, 1, false);
SimpleInstallFunction(proto, "reduceRight", Builtins::kArrayReduceRight, 1,
false);
}
{ // --- A r r a y I t e r a t o r ---
Handle<JSObject> iterator_prototype(
native_context()->initial_iterator_prototype());
Handle<JSObject> array_iterator_prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
JSObject::ForceSetPrototype(array_iterator_prototype, iterator_prototype);
JSObject::AddProperty(
array_iterator_prototype, factory->to_string_tag_symbol(),
factory->ArrayIterator_string(),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
SimpleInstallFunction(array_iterator_prototype, "next",
Builtins::kArrayIteratorPrototypeNext, 0, true,
kArrayIteratorNext);
Handle<JSFunction> array_iterator_function = CreateFunction(
isolate, factory->ArrayIterator_string(),
JS_FAST_ARRAY_VALUE_ITERATOR_TYPE, JSArrayIterator::kSize, 0,
array_iterator_prototype, Builtins::kIllegal);
array_iterator_function->shared()->set_native(false);
array_iterator_function->shared()->set_instance_class_name(
isolate->heap()->ArrayIterator_string());
native_context()->set_initial_array_iterator_prototype(
*array_iterator_prototype);
native_context()->set_initial_array_iterator_prototype_map(
array_iterator_prototype->map());
Handle<Map> initial_map(array_iterator_function->initial_map(), isolate);
#define ARRAY_ITERATOR_LIST(V) \
V(TYPED_ARRAY, KEY, typed_array, key) \
V(FAST_ARRAY, KEY, fast_array, key) \
V(GENERIC_ARRAY, KEY, array, key) \
V(UINT8_ARRAY, KEY_VALUE, uint8_array, key_value) \
V(INT8_ARRAY, KEY_VALUE, int8_array, key_value) \
V(UINT16_ARRAY, KEY_VALUE, uint16_array, key_value) \
V(INT16_ARRAY, KEY_VALUE, int16_array, key_value) \
V(UINT32_ARRAY, KEY_VALUE, uint32_array, key_value) \
V(INT32_ARRAY, KEY_VALUE, int32_array, key_value) \
V(FLOAT32_ARRAY, KEY_VALUE, float32_array, key_value) \
V(FLOAT64_ARRAY, KEY_VALUE, float64_array, key_value) \
V(UINT8_CLAMPED_ARRAY, KEY_VALUE, uint8_clamped_array, key_value) \
V(FAST_SMI_ARRAY, KEY_VALUE, fast_smi_array, key_value) \
V(FAST_HOLEY_SMI_ARRAY, KEY_VALUE, fast_holey_smi_array, key_value) \
V(FAST_ARRAY, KEY_VALUE, fast_array, key_value) \
V(FAST_HOLEY_ARRAY, KEY_VALUE, fast_holey_array, key_value) \
V(FAST_DOUBLE_ARRAY, KEY_VALUE, fast_double_array, key_value) \
V(FAST_HOLEY_DOUBLE_ARRAY, KEY_VALUE, fast_holey_double_array, key_value) \
V(GENERIC_ARRAY, KEY_VALUE, array, key_value) \
V(UINT8_ARRAY, VALUE, uint8_array, value) \
V(INT8_ARRAY, VALUE, int8_array, value) \
V(UINT16_ARRAY, VALUE, uint16_array, value) \
V(INT16_ARRAY, VALUE, int16_array, value) \
V(UINT32_ARRAY, VALUE, uint32_array, value) \
V(INT32_ARRAY, VALUE, int32_array, value) \
V(FLOAT32_ARRAY, VALUE, float32_array, value) \
V(FLOAT64_ARRAY, VALUE, float64_array, value) \
V(UINT8_CLAMPED_ARRAY, VALUE, uint8_clamped_array, value) \
V(FAST_SMI_ARRAY, VALUE, fast_smi_array, value) \
V(FAST_HOLEY_SMI_ARRAY, VALUE, fast_holey_smi_array, value) \
V(FAST_ARRAY, VALUE, fast_array, value) \
V(FAST_HOLEY_ARRAY, VALUE, fast_holey_array, value) \
V(FAST_DOUBLE_ARRAY, VALUE, fast_double_array, value) \
V(FAST_HOLEY_DOUBLE_ARRAY, VALUE, fast_holey_double_array, value) \
V(GENERIC_ARRAY, VALUE, array, value)
#define CREATE_ARRAY_ITERATOR_MAP(PREFIX, SUFFIX, prefix, suffix) \
do { \
const InstanceType type = JS_##PREFIX##_##SUFFIX##_ITERATOR_TYPE; \
Handle<Map> map = \
Map::Copy(initial_map, "JS_" #PREFIX "_" #SUFFIX "_ITERATOR_TYPE"); \
map->set_instance_type(type); \
native_context()->set_##prefix##_##suffix##_iterator_map(*map); \
} while (0);
ARRAY_ITERATOR_LIST(CREATE_ARRAY_ITERATOR_MAP)
#undef CREATE_ARRAY_ITERATOR_MAP
#undef ARRAY_ITERATOR_LIST
}
{ // --- N u m b e r ---
Handle<JSFunction> number_fun = InstallFunction(
global, "Number", JS_VALUE_TYPE, JSValue::kSize, 0,
isolate->initial_object_prototype(), Builtins::kNumberConstructor);
number_fun->shared()->set_builtin_function_id(kNumberConstructor);
number_fun->shared()->DontAdaptArguments();
number_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate, NumberConstructor_ConstructStub));
number_fun->shared()->set_length(1);
InstallWithIntrinsicDefaultProto(isolate, number_fun,
Context::NUMBER_FUNCTION_INDEX);
// Create the %NumberPrototype%
Handle<JSValue> prototype =
Handle<JSValue>::cast(factory->NewJSObject(number_fun, TENURED));
prototype->set_value(Smi::kZero);
JSFunction::SetPrototype(number_fun, prototype);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(), number_fun,
DONT_ENUM);
// Install the Number.prototype methods.
SimpleInstallFunction(prototype, "toExponential",
Builtins::kNumberPrototypeToExponential, 1, false);
SimpleInstallFunction(prototype, "toFixed",
Builtins::kNumberPrototypeToFixed, 1, false);
SimpleInstallFunction(prototype, "toPrecision",
Builtins::kNumberPrototypeToPrecision, 1, false);
SimpleInstallFunction(prototype, "toString",
Builtins::kNumberPrototypeToString, 1, false);
SimpleInstallFunction(prototype, "valueOf",
Builtins::kNumberPrototypeValueOf, 0, true);
// Install Intl fallback functions.
SimpleInstallFunction(prototype, "toLocaleString",
Builtins::kNumberPrototypeToLocaleString, 0, false);
// Install the Number functions.
SimpleInstallFunction(number_fun, "isFinite", Builtins::kNumberIsFinite, 1,
true);
SimpleInstallFunction(number_fun, "isInteger", Builtins::kNumberIsInteger,
1, true);
SimpleInstallFunction(number_fun, "isNaN", Builtins::kNumberIsNaN, 1, true);
SimpleInstallFunction(number_fun, "isSafeInteger",
Builtins::kNumberIsSafeInteger, 1, true);
// Install Number.parseFloat and Global.parseFloat.
Handle<JSFunction> parse_float_fun = SimpleInstallFunction(
number_fun, "parseFloat", Builtins::kNumberParseFloat, 1, true);
JSObject::AddProperty(global_object,
factory->NewStringFromAsciiChecked("parseFloat"),
parse_float_fun, DONT_ENUM);
// Install Number.parseInt and Global.parseInt.
Handle<JSFunction> parse_int_fun = SimpleInstallFunction(
number_fun, "parseInt", Builtins::kNumberParseInt, 2, true);
JSObject::AddProperty(global_object,
factory->NewStringFromAsciiChecked("parseInt"),
parse_int_fun, DONT_ENUM);
// Install Number constants
double kMaxValue = 1.7976931348623157e+308;
double kMinValue = 5e-324;
double kMaxSafeInt = 9007199254740991;
double kMinSafeInt = -9007199254740991;
double kEPS = 2.220446049250313e-16;
Handle<Object> infinity = factory->infinity_value();
Handle<Object> nan = factory->nan_value();
Handle<String> nan_name = factory->NewStringFromAsciiChecked("NaN");
JSObject::AddProperty(
number_fun, factory->NewStringFromAsciiChecked("MAX_VALUE"),
factory->NewNumber(kMaxValue),
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
number_fun, factory->NewStringFromAsciiChecked("MIN_VALUE"),
factory->NewNumber(kMinValue),
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
number_fun, nan_name, nan,
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
number_fun, factory->NewStringFromAsciiChecked("NEGATIVE_INFINITY"),
factory->NewNumber(-V8_INFINITY),
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
number_fun, factory->NewStringFromAsciiChecked("POSITIVE_INFINITY"),
infinity,
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
number_fun, factory->NewStringFromAsciiChecked("MAX_SAFE_INTEGER"),
factory->NewNumber(kMaxSafeInt),
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
number_fun, factory->NewStringFromAsciiChecked("MIN_SAFE_INTEGER"),
factory->NewNumber(kMinSafeInt),
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
number_fun, factory->NewStringFromAsciiChecked("EPSILON"),
factory->NewNumber(kEPS),
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
global, factory->NewStringFromAsciiChecked("Infinity"), infinity,
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
global, nan_name, nan,
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
JSObject::AddProperty(
global, factory->NewStringFromAsciiChecked("undefined"),
factory->undefined_value(),
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
}
{ // --- B o o l e a n ---
Handle<JSFunction> boolean_fun = InstallFunction(
global, "Boolean", JS_VALUE_TYPE, JSValue::kSize, 0,
isolate->initial_object_prototype(), Builtins::kBooleanConstructor);
boolean_fun->shared()->DontAdaptArguments();
boolean_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate, BooleanConstructor_ConstructStub));
boolean_fun->shared()->set_length(1);
InstallWithIntrinsicDefaultProto(isolate, boolean_fun,
Context::BOOLEAN_FUNCTION_INDEX);
// Create the %BooleanPrototype%
Handle<JSValue> prototype =
Handle<JSValue>::cast(factory->NewJSObject(boolean_fun, TENURED));
prototype->set_value(isolate->heap()->false_value());
JSFunction::SetPrototype(boolean_fun, prototype);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(), boolean_fun,
DONT_ENUM);
// Install the Boolean.prototype methods.
SimpleInstallFunction(prototype, "toString",
Builtins::kBooleanPrototypeToString, 0, true);
SimpleInstallFunction(prototype, "valueOf",
Builtins::kBooleanPrototypeValueOf, 0, true);
}
{ // --- S t r i n g ---
Handle<JSFunction> string_fun = InstallFunction(
global, "String", JS_VALUE_TYPE, JSValue::kSize, 0,
isolate->initial_object_prototype(), Builtins::kStringConstructor);
string_fun->shared()->set_builtin_function_id(kStringConstructor);
string_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate, StringConstructor_ConstructStub));
string_fun->shared()->DontAdaptArguments();
string_fun->shared()->set_length(1);
InstallWithIntrinsicDefaultProto(isolate, string_fun,
Context::STRING_FUNCTION_INDEX);
Handle<Map> string_map =
Handle<Map>(native_context()->string_function()->initial_map());
string_map->set_elements_kind(FAST_STRING_WRAPPER_ELEMENTS);
Map::EnsureDescriptorSlack(string_map, 1);
PropertyAttributes attribs = static_cast<PropertyAttributes>(
DONT_ENUM | DONT_DELETE | READ_ONLY);
{ // Add length.
Descriptor d = Descriptor::AccessorConstant(
factory->length_string(), factory->string_length_accessor(), attribs);
string_map->AppendDescriptor(&d);
}
// Install the String.fromCharCode function.
SimpleInstallFunction(string_fun, "fromCharCode",
Builtins::kStringFromCharCode, 1, false);
// Install the String.fromCodePoint function.
SimpleInstallFunction(string_fun, "fromCodePoint",
Builtins::kStringFromCodePoint, 1, false);
// Install the String.raw function.
SimpleInstallFunction(string_fun, "raw", Builtins::kStringRaw, 1, false);
// Create the %StringPrototype%
Handle<JSValue> prototype =
Handle<JSValue>::cast(factory->NewJSObject(string_fun, TENURED));
prototype->set_value(isolate->heap()->empty_string());
JSFunction::SetPrototype(string_fun, prototype);
native_context()->set_initial_string_prototype(*prototype);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(), string_fun,
DONT_ENUM);
// Install the String.prototype methods.
SimpleInstallFunction(prototype, "anchor", Builtins::kStringPrototypeAnchor,
1, true);
SimpleInstallFunction(prototype, "big", Builtins::kStringPrototypeBig, 0,
true);
SimpleInstallFunction(prototype, "blink", Builtins::kStringPrototypeBlink,
0, true);
SimpleInstallFunction(prototype, "bold", Builtins::kStringPrototypeBold, 0,
true);
SimpleInstallFunction(prototype, "charAt", Builtins::kStringPrototypeCharAt,
1, true);
SimpleInstallFunction(prototype, "charCodeAt",
Builtins::kStringPrototypeCharCodeAt, 1, true);
SimpleInstallFunction(prototype, "codePointAt",
Builtins::kStringPrototypeCodePointAt, 1, true);
SimpleInstallFunction(prototype, "concat", Builtins::kStringPrototypeConcat,
1, false);
SimpleInstallFunction(prototype, "endsWith",
Builtins::kStringPrototypeEndsWith, 1, false);
SimpleInstallFunction(prototype, "fontcolor",
Builtins::kStringPrototypeFontcolor, 1, true);
SimpleInstallFunction(prototype, "fontsize",
Builtins::kStringPrototypeFontsize, 1, true);
SimpleInstallFunction(prototype, "fixed", Builtins::kStringPrototypeFixed,
0, true);
SimpleInstallFunction(prototype, "includes",
Builtins::kStringPrototypeIncludes, 1, false);
SimpleInstallFunction(prototype, "indexOf",
Builtins::kStringPrototypeIndexOf, 1, false);
SimpleInstallFunction(prototype, "italics",
Builtins::kStringPrototypeItalics, 0, true);
SimpleInstallFunction(prototype, "lastIndexOf",
Builtins::kStringPrototypeLastIndexOf, 1, false);
SimpleInstallFunction(prototype, "link", Builtins::kStringPrototypeLink, 1,
true);
SimpleInstallFunction(prototype, "localeCompare",
Builtins::kStringPrototypeLocaleCompare, 1, true);
SimpleInstallFunction(prototype, "match", Builtins::kStringPrototypeMatch,
1, true);
#ifdef V8_INTL_SUPPORT
SimpleInstallFunction(prototype, "normalize",
Builtins::kStringPrototypeNormalizeIntl, 0, false);
#else
SimpleInstallFunction(prototype, "normalize",
Builtins::kStringPrototypeNormalize, 0, false);
#endif // V8_INTL_SUPPORT
SimpleInstallFunction(prototype, "padEnd", Builtins::kStringPrototypePadEnd,
1, false);
SimpleInstallFunction(prototype, "padStart",
Builtins::kStringPrototypePadStart, 1, false);
SimpleInstallFunction(prototype, "repeat", Builtins::kStringPrototypeRepeat,
1, true);
SimpleInstallFunction(prototype, "replace",
Builtins::kStringPrototypeReplace, 2, true);
SimpleInstallFunction(prototype, "search", Builtins::kStringPrototypeSearch,
1, true);
SimpleInstallFunction(prototype, "slice", Builtins::kStringPrototypeSlice,
2, false);
SimpleInstallFunction(prototype, "small", Builtins::kStringPrototypeSmall,
0, true);
SimpleInstallFunction(prototype, "split", Builtins::kStringPrototypeSplit,
2, false);
SimpleInstallFunction(prototype, "strike", Builtins::kStringPrototypeStrike,
0, true);
SimpleInstallFunction(prototype, "sub", Builtins::kStringPrototypeSub, 0,
true);
SimpleInstallFunction(prototype, "substr", Builtins::kStringPrototypeSubstr,
2, false);
SimpleInstallFunction(prototype, "substring",
Builtins::kStringPrototypeSubstring, 2, false);
SimpleInstallFunction(prototype, "sup", Builtins::kStringPrototypeSup, 0,
true);
SimpleInstallFunction(prototype, "startsWith",
Builtins::kStringPrototypeStartsWith, 1, false);
SimpleInstallFunction(prototype, "toString",
Builtins::kStringPrototypeToString, 0, true);
SimpleInstallFunction(prototype, "trim", Builtins::kStringPrototypeTrim, 0,
false);
SimpleInstallFunction(prototype, "trimLeft",
Builtins::kStringPrototypeTrimLeft, 0, false);
SimpleInstallFunction(prototype, "trimRight",
Builtins::kStringPrototypeTrimRight, 0, false);
#ifdef V8_INTL_SUPPORT
SimpleInstallFunction(prototype, "toLowerCase",
Builtins::kStringPrototypeToLowerCaseIntl, 0, true);
SimpleInstallFunction(prototype, "toUpperCase",
Builtins::kStringPrototypeToUpperCaseIntl, 0, false);
#else
SimpleInstallFunction(prototype, "toLocaleLowerCase",
Builtins::kStringPrototypeToLocaleLowerCase, 0,
false);
SimpleInstallFunction(prototype, "toLocaleUpperCase",
Builtins::kStringPrototypeToLocaleUpperCase, 0,
false);
SimpleInstallFunction(prototype, "toLowerCase",
Builtins::kStringPrototypeToLowerCase, 0, false);
SimpleInstallFunction(prototype, "toUpperCase",
Builtins::kStringPrototypeToUpperCase, 0, false);
#endif
SimpleInstallFunction(prototype, "valueOf",
Builtins::kStringPrototypeValueOf, 0, true);
SimpleInstallFunction(prototype, factory->iterator_symbol(),
"[Symbol.iterator]",
Builtins::kStringPrototypeIterator, 0, true,
DONT_ENUM, kStringIterator);
}
{ // --- S t r i n g I t e r a t o r ---
Handle<JSObject> iterator_prototype(
native_context()->initial_iterator_prototype());
Handle<JSObject> string_iterator_prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
JSObject::ForceSetPrototype(string_iterator_prototype, iterator_prototype);
JSObject::AddProperty(
string_iterator_prototype, factory->to_string_tag_symbol(),
factory->NewStringFromAsciiChecked("String Iterator"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
SimpleInstallFunction(string_iterator_prototype, "next",
Builtins::kStringIteratorPrototypeNext, 0, true,
kStringIteratorNext);
Handle<JSFunction> string_iterator_function = CreateFunction(
isolate, factory->NewStringFromAsciiChecked("StringIterator"),
JS_STRING_ITERATOR_TYPE, JSStringIterator::kSize, 0,
string_iterator_prototype, Builtins::kIllegal);
string_iterator_function->shared()->set_native(false);
native_context()->set_string_iterator_map(
string_iterator_function->initial_map());
}
{ // --- S y m b o l ---
Handle<JSFunction> symbol_fun = InstallFunction(
global, "Symbol", JS_VALUE_TYPE, JSValue::kSize, 0,
factory->the_hole_value(), Builtins::kSymbolConstructor);
symbol_fun->shared()->set_builtin_function_id(kSymbolConstructor);
symbol_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate, SymbolConstructor_ConstructStub));
symbol_fun->shared()->set_length(0);
symbol_fun->shared()->DontAdaptArguments();
native_context()->set_symbol_function(*symbol_fun);
// Install the Symbol.for and Symbol.keyFor functions.
SimpleInstallFunction(symbol_fun, "for", Builtins::kSymbolFor, 1, false);
SimpleInstallFunction(symbol_fun, "keyFor", Builtins::kSymbolKeyFor, 1,
false);
// Install well-known symbols.
InstallConstant(isolate, symbol_fun, "asyncIterator",
factory->async_iterator_symbol());
InstallConstant(isolate, symbol_fun, "hasInstance",
factory->has_instance_symbol());
InstallConstant(isolate, symbol_fun, "isConcatSpreadable",
factory->is_concat_spreadable_symbol());
InstallConstant(isolate, symbol_fun, "iterator",
factory->iterator_symbol());
InstallConstant(isolate, symbol_fun, "match", factory->match_symbol());
InstallConstant(isolate, symbol_fun, "replace", factory->replace_symbol());
InstallConstant(isolate, symbol_fun, "search", factory->search_symbol());
InstallConstant(isolate, symbol_fun, "species", factory->species_symbol());
InstallConstant(isolate, symbol_fun, "split", factory->split_symbol());
InstallConstant(isolate, symbol_fun, "toPrimitive",
factory->to_primitive_symbol());
InstallConstant(isolate, symbol_fun, "toStringTag",
factory->to_string_tag_symbol());
InstallConstant(isolate, symbol_fun, "unscopables",
factory->unscopables_symbol());
// Setup %SymbolPrototype%.
Handle<JSObject> prototype(
JSObject::cast(symbol_fun->instance_prototype()));
// Install the @@toStringTag property on the {prototype}.
JSObject::AddProperty(
prototype, factory->to_string_tag_symbol(),
factory->NewStringFromAsciiChecked("Symbol"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
// Install the Symbol.prototype methods.
SimpleInstallFunction(prototype, "toString",
Builtins::kSymbolPrototypeToString, 0, true);
SimpleInstallFunction(prototype, "valueOf",
Builtins::kSymbolPrototypeValueOf, 0, true);
// Install the @@toPrimitive function.
Handle<JSFunction> to_primitive = InstallFunction(
prototype, factory->to_primitive_symbol(), JS_OBJECT_TYPE,
JSObject::kHeaderSize, 0, MaybeHandle<JSObject>(),
Builtins::kSymbolPrototypeToPrimitive,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
// Set the expected parameters for @@toPrimitive to 1; required by builtin.
to_primitive->shared()->set_internal_formal_parameter_count(1);
// Set the length for the function to satisfy ECMA-262.
to_primitive->shared()->set_length(1);
}
{ // --- D a t e ---
Handle<JSFunction> date_fun =
InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize, 0,
factory->the_hole_value(), Builtins::kDateConstructor);
InstallWithIntrinsicDefaultProto(isolate, date_fun,
Context::DATE_FUNCTION_INDEX);
date_fun->shared()->SetConstructStub(
*BUILTIN_CODE(isolate, DateConstructor_ConstructStub));
date_fun->shared()->set_length(7);
date_fun->shared()->DontAdaptArguments();
// Install the Date.now, Date.parse and Date.UTC functions.
SimpleInstallFunction(date_fun, "now", Builtins::kDateNow, 0, false);
SimpleInstallFunction(date_fun, "parse", Builtins::kDateParse, 1, false);
SimpleInstallFunction(date_fun, "UTC", Builtins::kDateUTC, 7, false);
// Setup %DatePrototype%.
Handle<JSObject> prototype(JSObject::cast(date_fun->instance_prototype()));
// Install the Date.prototype methods.
SimpleInstallFunction(prototype, "toString",
Builtins::kDatePrototypeToString, 0, false);
SimpleInstallFunction(prototype, "toDateString",
Builtins::kDatePrototypeToDateString, 0, false);
SimpleInstallFunction(prototype, "toTimeString",
Builtins::kDatePrototypeToTimeString, 0, false);
SimpleInstallFunction(prototype, "toISOString",
Builtins::kDatePrototypeToISOString, 0, false);
Handle<JSFunction> to_utc_string =
SimpleInstallFunction(prototype, "toUTCString",
Builtins::kDatePrototypeToUTCString, 0, false);
InstallFunction(prototype, to_utc_string,
factory->InternalizeUtf8String("toGMTString"), DONT_ENUM);
SimpleInstallFunction(prototype, "getDate", Builtins::kDatePrototypeGetDate,
0, true);
SimpleInstallFunction(prototype, "setDate", Builtins::kDatePrototypeSetDate,
1, false);
SimpleInstallFunction(prototype, "getDay", Builtins::kDatePrototypeGetDay,
0, true);
SimpleInstallFunction(prototype, "getFullYear",
Builtins::kDatePrototypeGetFullYear, 0, true);
SimpleInstallFunction(prototype, "setFullYear",
Builtins::kDatePrototypeSetFullYear, 3, false);
SimpleInstallFunction(prototype, "getHours",
Builtins::kDatePrototypeGetHours, 0, true);
SimpleInstallFunction(prototype, "setHours",
Builtins::kDatePrototypeSetHours, 4, false);
SimpleInstallFunction(prototype, "getMilliseconds",
Builtins::kDatePrototypeGetMilliseconds, 0, true);
SimpleInstallFunction(prototype, "setMilliseconds",
Builtins::kDatePrototypeSetMilliseconds, 1, false);
SimpleInstallFunction(prototype, "getMinutes",
Builtins::kDatePrototypeGetMinutes, 0, true);
SimpleInstallFunction(prototype, "setMinutes",
Builtins::kDatePrototypeSetMinutes, 3, false);
SimpleInstallFunction(prototype, "getMonth",
Builtins::kDatePrototypeGetMonth, 0, true);
SimpleInstallFunction(prototype, "setMonth",
Builtins::kDatePrototypeSetMonth, 2, false);
SimpleInstallFunction(prototype, "getSeconds",
Builtins::kDatePrototypeGetSeconds, 0, true);
SimpleInstallFunction(prototype, "setSeconds",
Builtins::kDatePrototypeSetSeconds, 2, false);
SimpleInstallFunction(prototype, "getTime", Builtins::kDatePrototypeGetTime,
0, true);
SimpleInstallFunction(prototype, "setTime", Builtins::kDatePrototypeSetTime,
1, false);
SimpleInstallFunction(prototype, "getTimezoneOffset",
Builtins::kDatePrototypeGetTimezoneOffset, 0, true);
SimpleInstallFunction(prototype, "getUTCDate",
Builtins::kDatePrototypeGetUTCDate, 0, true);
SimpleInstallFunction(prototype, "setUTCDate",
Builtins::kDatePrototypeSetUTCDate, 1, false);
SimpleInstallFunction(prototype, "getUTCDay",
Builtins::kDatePrototypeGetUTCDay, 0, true);
SimpleInstallFunction(prototype, "getUTCFullYear",
Builtins::kDatePrototypeGetUTCFullYear, 0, true);
SimpleInstallFunction(prototype, "setUTCFullYear",
Builtins::kDatePrototypeSetUTCFullYear, 3, false);
SimpleInstallFunction(prototype, "getUTCHours",
Builtins::kDatePrototypeGetUTCHours, 0, true);
SimpleInstallFunction(prototype, "setUTCHours",
Builtins::kDatePrototypeSetUTCHours, 4, false);
SimpleInstallFunction(prototype, "getUTCMilliseconds",
Builtins::kDatePrototypeGetUTCMilliseconds, 0, true);
SimpleInstallFunction(prototype, "setUTCMilliseconds",
Builtins::kDatePrototypeSetUTCMilliseconds, 1, false);
SimpleInstallFunction(prototype, "getUTCMinutes",
Builtins::kDatePrototypeGetUTCMinutes, 0, true);
SimpleInstallFunction(prototype, "setUTCMinutes",
Builtins::kDatePrototypeSetUTCMinutes, 3, false);
SimpleInstallFunction(prototype, "getUTCMonth",
Builtins::kDatePrototypeGetUTCMonth, 0, true);
SimpleInstallFunction(prototype, "setUTCMonth",
Builtins::kDatePrototypeSetUTCMonth, 2, false);
SimpleInstallFunction(prototype, "getUTCSeconds",
Builtins::kDatePrototypeGetUTCSeconds, 0, true);
SimpleInstallFunction(prototype, "setUTCSeconds",
Builtins::kDatePrototypeSetUTCSeconds, 2, false);
SimpleInstallFunction(prototype, "valueOf", Builtins::kDatePrototypeValueOf,
0, true);
SimpleInstallFunction(prototype, "getYear", Builtins::kDatePrototypeGetYear,
0, true);
SimpleInstallFunction(prototype, "setYear", Builtins::kDatePrototypeSetYear,
1, false);
SimpleInstallFunction(prototype, "toJSON", Builtins::kDatePrototypeToJson,
1, false);
// Install Intl fallback functions.
SimpleInstallFunction(prototype, "toLocaleString",
Builtins::kDatePrototypeToString, 0, false);
SimpleInstallFunction(prototype, "toLocaleDateString",
Builtins::kDatePrototypeToDateString, 0, false);
SimpleInstallFunction(prototype, "toLocaleTimeString",
Builtins::kDatePrototypeToTimeString, 0, false);
// Install the @@toPrimitive function.
Handle<JSFunction> to_primitive = InstallFunction(
prototype, factory->to_primitive_symbol(), JS_OBJECT_TYPE,
JSObject::kHeaderSize, 0, MaybeHandle<JSObject>(),
Builtins::kDatePrototypeToPrimitive,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
// Set the expected parameters for @@toPrimitive to 1; required by builtin.
to_primitive->shared()->set_internal_formal_parameter_count(1);
// Set the length for the function to satisfy ECMA-262.
to_primitive->shared()->set_length(1);
}
{
Handle<SharedFunctionInfo> info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kPromiseGetCapabilitiesExecutor,
factory->empty_string(), factory->Object_string(), 2);
native_context()->set_promise_get_capabilities_executor_shared_fun(*info);
// %new_promise_capability(C, debugEvent)
Handle<JSFunction> new_promise_capability =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kNewPromiseCapability, 2, false);
native_context()->set_new_promise_capability(*new_promise_capability);
}
{ // -- P r o m i s e
Handle<JSFunction> promise_fun = InstallFunction(
global, "Promise", JS_PROMISE_TYPE, JSPromise::kSizeWithEmbedderFields,
0, factory->the_hole_value(), Builtins::kPromiseConstructor);
InstallWithIntrinsicDefaultProto(isolate, promise_fun,
Context::PROMISE_FUNCTION_INDEX);
Handle<SharedFunctionInfo> shared(promise_fun->shared(), isolate);
shared->SetConstructStub(*BUILTIN_CODE(isolate, JSBuiltinsConstructStub));
shared->set_instance_class_name(isolate->heap()->Object_string());
shared->set_internal_formal_parameter_count(1);
shared->set_length(1);
InstallSpeciesGetter(promise_fun);
SimpleInstallFunction(promise_fun, "all", Builtins::kPromiseAll, 1, true);
SimpleInstallFunction(promise_fun, "race", Builtins::kPromiseRace, 1, true);
SimpleInstallFunction(promise_fun, "resolve",
Builtins::kPromiseResolveWrapper, 1, true);
SimpleInstallFunction(promise_fun, "reject", Builtins::kPromiseReject, 1,
true);
// Setup %PromisePrototype%.
Handle<JSObject> prototype(
JSObject::cast(promise_fun->instance_prototype()));
// Install the @@toStringTag property on the {prototype}.
JSObject::AddProperty(
prototype, factory->to_string_tag_symbol(), factory->Promise_string(),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
Handle<JSFunction> promise_then =
SimpleInstallFunction(prototype, isolate->factory()->then_string(),
Builtins::kPromisePrototypeThen, 2, true);
native_context()->set_promise_then(*promise_then);
Handle<JSFunction> promise_catch = SimpleInstallFunction(
prototype, "catch", Builtins::kPromisePrototypeCatch, 1, true);
native_context()->set_promise_catch(*promise_catch);
// Force the Promise constructor to fast properties, so that we can use the
// fast paths for various things like
//
// x instanceof Promise
//
// etc. We should probably come up with a more principled approach once
// the JavaScript builtins are gone.
JSObject::MigrateSlowToFast(Handle<JSObject>::cast(promise_fun), 0,
"Bootstrapping");
Handle<Map> prototype_map(prototype->map());
Map::SetShouldBeFastPrototypeMap(prototype_map, true, isolate);
// Store the initial Promise.prototype map. This is used in fast-path
// checks. Do not alter the prototype after this point.
native_context()->set_promise_prototype_map(*prototype_map);
{ // Internal: PromiseInternalConstructor
// Also exposed as extrasUtils.createPromise.
Handle<JSFunction> function =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kPromiseInternalConstructor, 1, true);
function->shared()->set_native(false);
native_context()->set_promise_internal_constructor(*function);
}
{ // Internal: IsPromise
Handle<JSFunction> function = SimpleCreateFunction(
isolate, factory->empty_string(), Builtins::kIsPromise, 1, false);
native_context()->set_is_promise(*function);
}
{ // Internal: ResolvePromise
// Also exposed as extrasUtils.resolvePromise.
Handle<JSFunction> function = SimpleCreateFunction(
isolate, factory->empty_string(), Builtins::kResolvePromise, 2, true);
function->shared()->set_native(false);
native_context()->set_promise_resolve(*function);
}
{ // Internal: PromiseHandle
Handle<JSFunction> function =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kPromiseHandleJS, 5, false);
native_context()->set_promise_handle(*function);
}
{ // Internal: PromiseHandleReject
Handle<JSFunction> function =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kPromiseHandleReject, 3, false);
native_context()->set_promise_handle_reject(*function);
}
{ // Internal: InternalPromiseReject
Handle<JSFunction> function =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kInternalPromiseReject, 3, true);
function->shared()->set_native(false);
native_context()->set_promise_internal_reject(*function);
}
{
Handle<SharedFunctionInfo> info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kPromiseResolveClosure, factory->empty_string(),
1);
native_context()->set_promise_resolve_shared_fun(*info);
info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kPromiseRejectClosure, factory->empty_string(), 1);
native_context()->set_promise_reject_shared_fun(*info);
}
{
Handle<SharedFunctionInfo> info = SimpleCreateSharedFunctionInfo(
isolate, Builtins::kPromiseAllResolveElementClosure,
factory->empty_string(), 1);
native_context()->set_promise_all_resolve_element_shared_fun(*info);
}
// Force the Promise constructor to fast properties, so that we can use the
// fast paths for various things like
//
// x instanceof Promise
//
// etc. We should probably come up with a more principled approach once
// the JavaScript builtins are gone.
JSObject::MigrateSlowToFast(promise_fun, 0, "Bootstrapping");
}
{ // -- R e g E x p
// Builtin functions for RegExp.prototype.
Handle<JSFunction> regexp_fun = InstallFunction(
global, "RegExp", JS_REGEXP_TYPE,
JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize,
JSRegExp::kInObjectFieldCount, factory->the_hole_value(),
Builtins::kRegExpConstructor);
InstallWithIntrinsicDefaultProto(isolate, regexp_fun,
Context::REGEXP_FUNCTION_INDEX);
Handle<SharedFunctionInfo> shared(regexp_fun->shared(), isolate);
shared->SetConstructStub(*BUILTIN_CODE(isolate, JSBuiltinsConstructStub));
shared->set_instance_class_name(isolate->heap()->RegExp_string());
shared->set_internal_formal_parameter_count(2);
shared->set_length(2);
{
// Setup %RegExpPrototype%.
Handle<JSObject> prototype(
JSObject::cast(regexp_fun->instance_prototype()));
{
Handle<JSFunction> fun = SimpleInstallFunction(
prototype, factory->exec_string(), Builtins::kRegExpPrototypeExec,
1, true, DONT_ENUM);
native_context()->set_regexp_exec_function(*fun);
}
SimpleInstallGetter(prototype, factory->dotAll_string(),
Builtins::kRegExpPrototypeDotAllGetter, true);
SimpleInstallGetter(prototype, factory->flags_string(),
Builtins::kRegExpPrototypeFlagsGetter, true);
SimpleInstallGetter(prototype, factory->global_string(),
Builtins::kRegExpPrototypeGlobalGetter, true);
SimpleInstallGetter(prototype, factory->ignoreCase_string(),
Builtins::kRegExpPrototypeIgnoreCaseGetter, true);
SimpleInstallGetter(prototype, factory->multiline_string(),
Builtins::kRegExpPrototypeMultilineGetter, true);
SimpleInstallGetter(prototype, factory->source_string(),
Builtins::kRegExpPrototypeSourceGetter, true);
SimpleInstallGetter(prototype, factory->sticky_string(),
Builtins::kRegExpPrototypeStickyGetter, true);
SimpleInstallGetter(prototype, factory->unicode_string(),
Builtins::kRegExpPrototypeUnicodeGetter, true);
SimpleInstallFunction(prototype, "compile",
Builtins::kRegExpPrototypeCompile, 2, true,
DONT_ENUM);
SimpleInstallFunction(prototype, factory->toString_string(),
Builtins::kRegExpPrototypeToString, 0, false,
DONT_ENUM);
SimpleInstallFunction(prototype, "test", Builtins::kRegExpPrototypeTest,
1, true, DONT_ENUM);
SimpleInstallFunction(prototype, factory->match_symbol(),
"[Symbol.match]", Builtins::kRegExpPrototypeMatch,
1, true);
SimpleInstallFunction(prototype, factory->replace_symbol(),
"[Symbol.replace]",
Builtins::kRegExpPrototypeReplace, 2, false);
SimpleInstallFunction(prototype, factory->search_symbol(),
"[Symbol.search]", Builtins::kRegExpPrototypeSearch,
1, true);
SimpleInstallFunction(prototype, factory->split_symbol(),
"[Symbol.split]", Builtins::kRegExpPrototypeSplit,
2, false);
Handle<Map> prototype_map(prototype->map());
Map::SetShouldBeFastPrototypeMap(prototype_map, true, isolate);
// Store the initial RegExp.prototype map. This is used in fast-path
// checks. Do not alter the prototype after this point.
native_context()->set_regexp_prototype_map(*prototype_map);
}
{
// RegExp getters and setters.
InstallSpeciesGetter(regexp_fun);
// Static properties set by a successful match.
const PropertyAttributes no_enum = DONT_ENUM;
SimpleInstallGetterSetter(regexp_fun, factory->input_string(),
Builtins::kRegExpInputGetter,
Builtins::kRegExpInputSetter, no_enum);
SimpleInstallGetterSetter(
regexp_fun, factory->InternalizeUtf8String("$_"),
Builtins::kRegExpInputGetter, Builtins::kRegExpInputSetter, no_enum);
SimpleInstallGetterSetter(
regexp_fun, factory->InternalizeUtf8String("lastMatch"),
Builtins::kRegExpLastMatchGetter, Builtins::kEmptyFunction, no_enum);
SimpleInstallGetterSetter(
regexp_fun, factory->InternalizeUtf8String("$&"),
Builtins::kRegExpLastMatchGetter, Builtins::kEmptyFunction, no_enum);
SimpleInstallGetterSetter(
regexp_fun, factory->InternalizeUtf8String("lastParen"),
Builtins::kRegExpLastParenGetter, Builtins::kEmptyFunction, no_enum);
SimpleInstallGetterSetter(
regexp_fun, factory->InternalizeUtf8String("$+"),
Builtins::kRegExpLastParenGetter, Builtins::kEmptyFunction, no_enum);
SimpleInstallGetterSetter(regexp_fun,
factory->InternalizeUtf8String("leftContext"),
Builtins::kRegExpLeftContextGetter,
Builtins::kEmptyFunction, no_enum);
SimpleInstallGetterSetter(regexp_fun,
factory->InternalizeUtf8String("$`"),
Builtins::kRegExpLeftContextGetter,
Builtins::kEmptyFunction, no_enum);
SimpleInstallGetterSetter(regexp_fun,
factory->InternalizeUtf8String("rightContext"),
Builtins::kRegExpRightContextGetter,
Builtins::kEmptyFunction, no_enum);
SimpleInstallGetterSetter(regexp_fun,
factory->InternalizeUtf8String("$'"),
Builtins::kRegExpRightContextGetter,
Builtins::kEmptyFunction, no_enum);
#define INSTALL_CAPTURE_GETTER(i) \
SimpleInstallGetterSetter( \
regexp_fun, factory->InternalizeUtf8String("$" #i), \
Builtins::kRegExpCapture##i##Getter, Builtins::kEmptyFunction, no_enum)
INSTALL_CAPTURE_GETTER(1);
INSTALL_CAPTURE_GETTER(2);
INSTALL_CAPTURE_GETTER(3);
INSTALL_CAPTURE_GETTER(4);
INSTALL_CAPTURE_GETTER(5);
INSTALL_CAPTURE_GETTER(