blob: 4963e85c6b1d50d5ed73c1c61aba99577a5d3346 [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/base/ieee754.h"
#include "src/code-stubs.h"
#include "src/compiler.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/ffi/ffi-compiler.h"
#include "src/heap/heap.h"
#include "src/isolate-inl.h"
#include "src/snapshot/natives.h"
#include "src/snapshot/snapshot.h"
#include "src/wasm/wasm-js.h"
#if V8_I18N_SUPPORT
#include "src/i18n.h"
#endif // V8_I18N_SUPPORT
namespace v8 {
namespace internal {
Bootstrapper::Bootstrapper(Isolate* isolate)
: isolate_(isolate),
nesting_(0),
extensions_cache_(Script::TYPE_EXTENSION) {}
template <class Source>
Handle<String> Bootstrapper::SourceLookup(int index) {
DCHECK(0 <= index && index < Source::GetBuiltinsCount());
Heap* heap = isolate_->heap();
if (Source::GetSourceCache(heap)->get(index)->IsUndefined(isolate_)) {
// We can use external strings for the natives.
Vector<const char> source = Source::GetScriptSource(index);
NativesExternalStringResource* resource =
new NativesExternalStringResource(source.start(), source.length());
Handle<ExternalOneByteString> source_code =
isolate_->factory()->NewNativeSourceString(resource);
// Mark this external string with a special map.
DCHECK(source_code->is_short());
Source::GetSourceCache(heap)->set(index, *source_code);
}
Handle<Object> cached_source(Source::GetSourceCache(heap)->get(index),
isolate_);
return Handle<String>::cast(cached_source);
}
template Handle<String> Bootstrapper::SourceLookup<Natives>(int index);
template Handle<String> Bootstrapper::SourceLookup<ExperimentalNatives>(
int index);
template Handle<String> Bootstrapper::SourceLookup<ExperimentalExtraNatives>(
int index);
template Handle<String> Bootstrapper::SourceLookup<ExtraNatives>(int index);
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 != NULL && strlen(FLAG_expose_gc_as) != 0;
return flag_given ? FLAG_expose_gc_as : "gc";
}
v8::Extension* Bootstrapper::free_buffer_extension_ = NULL;
v8::Extension* Bootstrapper::gc_extension_ = NULL;
v8::Extension* Bootstrapper::externalize_string_extension_ = NULL;
v8::Extension* Bootstrapper::statistics_extension_ = NULL;
v8::Extension* Bootstrapper::trigger_failure_extension_ = NULL;
v8::Extension* Bootstrapper::ignition_statistics_extension_ = NULL;
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_ = NULL;
delete gc_extension_;
gc_extension_ = NULL;
delete externalize_string_extension_;
externalize_string_extension_ = NULL;
delete statistics_extension_;
statistics_extension_ = NULL;
delete trigger_failure_extension_;
trigger_failure_extension_ = NULL;
delete ignition_statistics_extension_;
ignition_statistics_extension_ = NULL;
}
void DeleteNativeSources(Object* maybe_array) {
if (maybe_array->IsFixedArray()) {
FixedArray* array = FixedArray::cast(maybe_array);
Isolate* isolate = array->GetIsolate();
for (int i = 0; i < array->length(); i++) {
Object* natives_source = array->get(i);
if (!natives_source->IsUndefined(isolate)) {
const NativesExternalStringResource* resource =
reinterpret_cast<const NativesExternalStringResource*>(
ExternalOneByteString::cast(natives_source)->resource());
delete resource;
}
}
}
}
void Bootstrapper::TearDown() {
DeleteNativeSources(Natives::GetSourceCache(isolate_->heap()));
DeleteNativeSources(ExperimentalNatives::GetSourceCache(isolate_->heap()));
DeleteNativeSources(ExtraNatives::GetSourceCache(isolate_->heap()));
DeleteNativeSources(
ExperimentalExtraNatives::GetSourceCache(isolate_->heap()));
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::DeserializeInternalFieldsCallback internal_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(); }
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);
// Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
Handle<JSFunction> GetRestrictedFunctionPropertiesThrower();
Handle<JSFunction> GetStrictArgumentsPoisonFunction();
Handle<JSFunction> GetThrowTypeErrorIntrinsic(Builtins::Name builtin_name);
void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
void CreateIteratorMaps(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
void InitializeGlobal_enable_fast_array_builtins();
Handle<JSFunction> InstallArrayBuffer(Handle<JSObject> target,
const char* name, Builtins::Name call,
BuiltinFunctionId id);
Handle<JSFunction> InstallInternalArray(Handle<JSObject> target,
const char* name,
ElementsKind elements_kind);
bool InstallNatives(GlobalContextType context_type);
void InstallTypedArray(const char* name, ElementsKind elements_kind,
Handle<JSFunction>* fun);
bool InstallExperimentalNatives();
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);
void MakeFunctionInstancePrototypeWritable();
void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
FunctionMode function_mode);
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_;
// Function maps. Function maps are created initially with a read only
// prototype for the processing of JS builtins. Later the function maps are
// replaced in order to make prototype writable. These are the final, writable
// prototype, maps.
Handle<Map> sloppy_function_map_writable_prototype_;
Handle<Map> strict_function_map_writable_prototype_;
Handle<Map> class_function_map_;
Handle<JSFunction> strict_poison_function_;
Handle<JSFunction> restricted_function_properties_thrower_;
BootstrapperActive active_;
friend class Bootstrapper;
};
void Bootstrapper::Iterate(ObjectVisitor* 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::DeserializeInternalFieldsCallback internal_fields_deserializer,
GlobalContextType context_type) {
HandleScope scope(isolate_);
Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template,
context_snapshot_index, internal_fields_deserializer,
context_type);
Handle<Context> env = genesis.result();
if (env.is_null() || !InstallExtensions(env, extensions)) {
return Handle<Context>();
}
return scope.CloseAndEscape(env);
}
Handle<JSGlobalProxy> Bootstrapper::NewRemoteContext(
MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template) {
HandleScope scope(isolate_);
Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template);
Handle<JSGlobalProxy> global_proxy = genesis.global_proxy();
if (global_proxy.is_null()) return Handle<JSGlobalProxy>();
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 {
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);
}
}
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);
}
Handle<JSFunction> CreateFunction(Isolate* isolate, Handle<String> name,
InstanceType type, int instance_size,
MaybeHandle<JSObject> maybe_prototype,
Builtins::Name call,
bool strict_function_map = false) {
Factory* factory = isolate->factory();
Handle<Code> call_code(isolate->builtins()->builtin(call));
Handle<JSObject> prototype;
Handle<JSFunction> result =
maybe_prototype.ToHandle(&prototype)
? factory->NewFunction(name, call_code, prototype, type,
instance_size, strict_function_map)
: factory->NewFunctionWithoutPrototype(name, call_code,
strict_function_map);
result->shared()->set_native(true);
return result;
}
Handle<JSFunction> InstallFunction(Handle<JSObject> target, Handle<Name> name,
InstanceType type, int instance_size,
MaybeHandle<JSObject> maybe_prototype,
Builtins::Name call,
PropertyAttributes attributes,
bool strict_function_map = false) {
Handle<String> name_string = Name::ToFunctionName(name).ToHandleChecked();
Handle<JSFunction> function =
CreateFunction(target->GetIsolate(), name_string, type, instance_size,
maybe_prototype, call, strict_function_map);
InstallFunction(target, name, function, name_string, attributes);
return function;
}
Handle<JSFunction> InstallFunction(Handle<JSObject> target, const char* name,
InstanceType type, int instance_size,
MaybeHandle<JSObject> maybe_prototype,
Builtins::Name call,
bool strict_function_map = false) {
Factory* const factory = target->GetIsolate()->factory();
PropertyAttributes attributes = DONT_ENUM;
return InstallFunction(target, factory->InternalizeUtf8String(name), type,
instance_size, maybe_prototype, call, attributes,
strict_function_map);
}
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,
MaybeHandle<JSObject>(), call);
if (adapt) {
fun->shared()->set_internal_formal_parameter_count(len);
} else {
fun->shared()->DontAdaptArguments();
}
fun->shared()->set_length(len);
return fun;
}
Handle<JSFunction> SimpleInstallFunction(Handle<JSObject> base,
Handle<String> name,
Builtins::Name call, int len,
bool adapt,
PropertyAttributes attrs = DONT_ENUM) {
Handle<JSFunction> fun =
SimpleCreateFunction(base->GetIsolate(), name, call, len, adapt);
InstallFunction(base, fun, name, attrs);
return fun;
}
Handle<JSFunction> SimpleInstallFunction(Handle<JSObject> base,
const char* name, Builtins::Name call,
int len, bool adapt,
PropertyAttributes attrs = DONT_ENUM) {
Factory* const factory = base->GetIsolate()->factory();
return SimpleInstallFunction(base, factory->InternalizeUtf8String(name), call,
len, adapt, attrs);
}
Handle<JSFunction> SimpleInstallFunction(Handle<JSObject> base,
const char* name, Builtins::Name call,
int len, bool adapt,
BuiltinFunctionId id) {
Handle<JSFunction> fun = SimpleInstallFunction(base, name, call, len, adapt);
fun->shared()->set_builtin_function_id(id);
return fun;
}
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();
}
Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
Handle<String> 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;
}
Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
Handle<String> name, Builtins::Name call,
bool adapt) {
return SimpleInstallGetter(base, name, name, call, adapt);
}
Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
Handle<String> 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;
}
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));
}
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) {
// Allocate the map for function instances. Maps are allocated first and their
// prototypes patched later, once empty function is created.
// Functions with this map will not have a 'prototype' property, and
// can not be used as constructors.
Handle<Map> function_without_prototype_map =
factory()->CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
native_context()->set_sloppy_function_without_prototype_map(
*function_without_prototype_map);
// Allocate the function map. This map is temporary, used only for processing
// of builtins.
// Later the map is replaced with writable prototype map, allocated below.
Handle<Map> function_map =
factory()->CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE);
native_context()->set_sloppy_function_map(*function_map);
native_context()->set_sloppy_function_with_readonly_prototype_map(
*function_map);
// The final map for functions. Writeable prototype.
// This map is installed in MakeFunctionInstancePrototypeWritable.
sloppy_function_map_writable_prototype_ =
factory()->CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE);
Factory* factory = isolate->factory();
Handle<String> object_name = factory->Object_string();
Handle<JSObject> object_function_prototype;
{ // --- O b j e c t ---
Handle<JSFunction> object_fun = factory->NewFunction(object_name);
int unused = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
int instance_size = JSObject::kHeaderSize + kPointerSize * unused;
Handle<Map> object_function_map =
factory->NewMap(JS_OBJECT_TYPE, instance_size);
object_function_map->SetInObjectProperties(unused);
JSFunction::SetInitialMap(object_fun, object_function_map,
isolate->factory()->null_value());
object_function_map->set_unused_property_fields(unused);
native_context()->set_object_function(*object_fun);
// Allocate a new prototype for the object function.
object_function_prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
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_immutable_proto(true);
object_function_prototype->set_map(*map);
native_context()->set_initial_object_prototype(*object_function_prototype);
// For bootstrapping set the array prototype to be the same as the object
// prototype, otherwise the missing initial_array_prototype will cause
// assertions during startup.
native_context()->set_initial_array_prototype(*object_function_prototype);
Accessors::FunctionSetPrototype(object_fun, object_function_prototype)
.Assert();
}
// Allocate the empty function as the prototype for function - ES6 19.2.3
Handle<Code> code(isolate->builtins()->EmptyFunction());
Handle<JSFunction> empty_function =
factory->NewFunctionWithoutPrototype(factory->empty_string(), code);
// Allocate the function map first and then patch the prototype later
Handle<Map> empty_function_map =
factory->CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
DCHECK(!empty_function_map->is_dictionary_map());
Map::SetPrototype(empty_function_map, object_function_prototype);
empty_function_map->set_is_prototype_map(true);
empty_function->set_map(*empty_function_map);
// --- 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);
// Set prototypes for the function maps.
Handle<Map> sloppy_function_map(native_context()->sloppy_function_map(),
isolate);
Handle<Map> sloppy_function_without_prototype_map(
native_context()->sloppy_function_without_prototype_map(), isolate);
Map::SetPrototype(sloppy_function_map, empty_function);
Map::SetPrototype(sloppy_function_without_prototype_map, empty_function);
Map::SetPrototype(sloppy_function_map_writable_prototype_, empty_function);
return empty_function;
}
// Creates the %ThrowTypeError% function.
Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic(
Builtins::Name builtin_name) {
Handle<String> name =
factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("ThrowTypeError"));
Handle<Code> code(isolate()->builtins()->builtin(builtin_name));
Handle<JSFunction> function =
factory()->NewFunctionWithoutPrototype(name, code, true);
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()->length()), isolate());
JSObject::SetOwnPropertyIgnoreAttributes(
function, factory()->length_string(), value,
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
.Assert();
if (JSObject::PreventExtensions(function, Object::THROW_ON_ERROR)
.IsNothing()) {
DCHECK(false);
}
return function;
}
// ECMAScript 5th Edition, 13.2.3
Handle<JSFunction> Genesis::GetRestrictedFunctionPropertiesThrower() {
if (restricted_function_properties_thrower_.is_null()) {
restricted_function_properties_thrower_ = GetThrowTypeErrorIntrinsic(
Builtins::kRestrictedFunctionPropertiesThrower);
}
return restricted_function_properties_thrower_;
}
Handle<JSFunction> Genesis::GetStrictArgumentsPoisonFunction() {
if (strict_poison_function_.is_null()) {
strict_poison_function_ = GetThrowTypeErrorIntrinsic(
Builtins::kRestrictedStrictArgumentsPropertiesThrower);
}
return strict_poison_function_;
}
void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
// Allocate map for the prototype-less strict mode instances.
Handle<Map> strict_function_without_prototype_map =
factory()->CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
native_context()->set_strict_function_without_prototype_map(
*strict_function_without_prototype_map);
// Allocate map for the strict mode functions. This map is temporary, used
// only for processing of builtins.
// Later the map is replaced with writable prototype map, allocated below.
Handle<Map> strict_function_map = factory()->CreateStrictFunctionMap(
FUNCTION_WITH_READONLY_PROTOTYPE, empty);
native_context()->set_strict_function_map(*strict_function_map);
// The final map for the strict mode functions. Writeable prototype.
// This map is installed in MakeFunctionInstancePrototypeWritable.
strict_function_map_writable_prototype_ = factory()->CreateStrictFunctionMap(
FUNCTION_WITH_WRITEABLE_PROTOTYPE, empty);
// Allocate map for classes
class_function_map_ = factory()->CreateClassFunctionMap(empty);
native_context()->set_class_function_map(*class_function_map_);
// Now that the strict mode function map is available, set up the
// restricted "arguments" and "caller" getters.
AddRestrictedFunctionProperties(empty);
}
void Genesis::CreateIteratorMaps(Handle<JSFunction> empty) {
// Create iterator-related meta-objects.
Handle<JSObject> iterator_prototype =
factory()->NewJSObject(isolate()->object_function(), TENURED);
Handle<JSFunction> iterator_prototype_iterator = SimpleCreateFunction(
isolate(), factory()->NewStringFromAsciiChecked("[Symbol.iterator]"),
Builtins::kReturnReceiver, 0, true);
JSObject::AddProperty(iterator_prototype, factory()->iterator_symbol(),
iterator_prototype_iterator, DONT_ENUM);
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, true);
SimpleInstallFunction(generator_object_prototype, "return",
Builtins::kGeneratorPrototypeReturn, 1, true);
SimpleInstallFunction(generator_object_prototype, "throw",
Builtins::kGeneratorPrototypeThrow, 1, true);
// 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, true);
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).
Handle<Map> strict_function_map(strict_function_map_writable_prototype_);
// Generator functions do not have "caller" or "arguments" accessors.
Handle<Map> generator_function_map =
Map::Copy(strict_function_map, "GeneratorFunction");
generator_function_map->set_is_constructor(false);
Map::SetPrototype(generator_function_map, generator_function_prototype);
native_context()->set_generator_function_map(*generator_function_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::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> strict_function_map(
native_context()->strict_function_without_prototype_map());
Handle<Map> async_function_map =
Map::Copy(strict_function_map, "AsyncFunction");
async_function_map->set_is_constructor(false);
Map::SetPrototype(async_function_map, async_function_prototype);
native_context()->set_async_function_map(*async_function_map);
}
void Genesis::CreateJSProxyMaps() {
// Allocate the different maps for all Proxy types.
// Next to the default proxy, we need maps indicating callable and
// constructable proxies.
Handle<Map> proxy_function_map =
Map::Copy(isolate()->sloppy_function_without_prototype_map(), "Proxy");
proxy_function_map->set_is_constructor(true);
native_context()->set_proxy_function_map(*proxy_function_map);
Handle<Map> proxy_map =
factory()->NewMap(JS_PROXY_TYPE, JSProxy::kSize, FAST_ELEMENTS);
proxy_map->set_dictionary_map(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();
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);
}
static 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);
}
void Genesis::AddRestrictedFunctionProperties(Handle<JSFunction> empty) {
PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
Handle<JSFunction> thrower = GetRestrictedFunctionPropertiesThrower();
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 = Handle<String>(heap()->empty_string());
Handle<Code> code = isolate()->builtins()->Illegal();
Handle<JSObject> prototype =
factory()->NewFunctionPrototype(isolate()->object_function());
js_global_object_function = factory()->NewFunction(
name, code, prototype, JS_GLOBAL_OBJECT_TYPE, JSGlobalObject::kSize);
#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_dictionary_map(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 = Handle<String>(heap()->empty_string());
Handle<Code> code = isolate()->builtins()->Illegal();
global_proxy_function =
factory()->NewFunction(name, code, JS_GLOBAL_PROXY_TYPE,
JSGlobalProxy::SizeWithInternalFields(0));
} 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);
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,
isolate->initial_object_prototype(),
Builtins::kErrorConstructor, DONT_ENUM);
error_fun->shared()->set_instance_class_name(*factory->Error_string());
error_fun->shared()->DontAdaptArguments();
error_fun->shared()->set_construct_stub(
*isolate->builtins()->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);
{
Handle<JSObject> prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
JSObject::AddProperty(prototype, factory->name_string(), name, DONT_ENUM);
JSObject::AddProperty(prototype, factory->message_string(),
factory->empty_string(), DONT_ENUM);
JSObject::AddProperty(prototype, factory->constructor_string(), error_fun,
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);
} 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,
Object::THROW_ON_ERROR)
.FromMaybe(false));
CHECK(JSReceiver::SetPrototype(prototype,
handle(global_error->prototype(), isolate),
false, Object::THROW_ON_ERROR)
.FromMaybe(false));
}
Accessors::FunctionSetPrototype(error_fun, prototype).Assert();
}
Handle<Map> initial_map(error_fun->initial_map());
Map::EnsureDescriptorSlack(initial_map, 1);
PropertyAttributes attribs = DONT_ENUM;
Handle<AccessorInfo> error_stack =
Accessors::ErrorStackInfo(isolate, attribs);
{
Descriptor d = Descriptor::AccessorConstant(
Handle<Name>(Name::cast(error_stack->name())), error_stack, attribs);
initial_map->AppendDescriptor(&d);
}
}
static void InstallMakeError(Isolate* isolate, Handle<Code> code,
int context_index) {
Handle<JSFunction> function =
isolate->factory()->NewFunction(isolate->factory()->empty_string(), code,
JS_OBJECT_TYPE, JSObject::kHeaderSize);
function->shared()->DontAdaptArguments();
isolate->native_context()->set(context_index, *function);
}
// 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(NULL);
// 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();
native_context()->set_osr_code_table(*factory->empty_fixed_array());
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, true);
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);
Handle<JSFunction> object_freeze = SimpleInstallFunction(
object_function, "freeze", Builtins::kObjectFreeze, 1, false);
native_context()->set_object_freeze(*object_freeze);
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, false);
native_context()->set_object_keys(*object_keys);
SimpleInstallFunction(object_function, factory->entries_string(),
Builtins::kObjectEntries, 1, false);
SimpleInstallFunction(object_function, factory->values_string(),
Builtins::kObjectValues, 1, false);
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::kObjectHasOwnProperty, 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(), "propertyIsEnumerable",
Builtins::kObjectPrototypePropertyIsEnumerable, 1, false);
SimpleInstallGetterSetter(isolate->initial_object_prototype(),
factory->proto_string(),
Builtins::kObjectPrototypeGetProto,
Builtins::kObjectPrototypeSetProto, DONT_ENUM);
}
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::kSize,
prototype, Builtins::kFunctionConstructor);
function_fun->set_prototype_or_initial_map(
*sloppy_function_map_writable_prototype_);
function_fun->shared()->DontAdaptArguments();
function_fun->shared()->SetConstructStub(
*isolate->builtins()->FunctionConstructor());
function_fun->shared()->set_length(1);
InstallWithIntrinsicDefaultProto(isolate, function_fun,
Context::FUNCTION_FUNCTION_INDEX);
// Setup the methods on the %FunctionPrototype%.
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 = InstallFunction(
prototype, factory->has_instance_symbol(), JS_OBJECT_TYPE,
JSObject::kHeaderSize, MaybeHandle<JSObject>(),
Builtins::kFunctionPrototypeHasInstance,
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
has_instance->shared()->set_builtin_function_id(kFunctionHasInstance);
native_context()->set_function_has_instance(*has_instance);
// Set the expected parameters for @@hasInstance to 1; required by builtin.
has_instance->shared()->set_internal_formal_parameter_count(1);
// Set the length for the function to satisfy ECMA-262.
has_instance->shared()->set_length(1);
// Install the "constructor" property on the %FunctionPrototype%.
JSObject::AddProperty(prototype, factory->constructor_string(),
function_fun, DONT_ENUM);
sloppy_function_map_writable_prototype_->SetConstructor(*function_fun);
strict_function_map_writable_prototype_->SetConstructor(*function_fun);
class_function_map_->SetConstructor(*function_fun);
}
{ // --- A r r a y ---
Handle<JSFunction> array_function =
InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
isolate->initial_object_prototype(),
Builtins::kArrayCode);
array_function->shared()->DontAdaptArguments();
array_function->shared()->set_builtin_function_id(kArrayCode);
// 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);
Handle<AccessorInfo> array_length =
Accessors::ArrayLengthInfo(isolate, attribs);
{ // Add length.
Descriptor d = Descriptor::AccessorConstant(
Handle<Name>(Name::cast(array_length->name())), array_length,
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);
Handle<JSFunction> is_arraylike = SimpleInstallFunction(
array_function, isolate->factory()->InternalizeUtf8String("isArray"),
Builtins::kArrayIsArray, 1, true);
native_context()->set_is_arraylike(*is_arraylike);
}
{ // --- 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));
Handle<JSFunction> next = InstallFunction(
array_iterator_prototype, "next", JS_OBJECT_TYPE, JSObject::kHeaderSize,
MaybeHandle<JSObject>(), Builtins::kArrayIteratorPrototypeNext);
next->shared()->set_builtin_function_id(kArrayIteratorNext);
// Set the expected parameters for %ArrayIteratorPrototype%.next to 0 (not
// including the receiver), as required by the builtin.
next->shared()->set_internal_formal_parameter_count(0);
// Set the length for the function to satisfy ECMA-262.
next->shared()->set_length(0);
Handle<JSFunction> array_iterator_function = CreateFunction(
isolate, factory->ArrayIterator_string(),
JS_FAST_ARRAY_VALUE_ITERATOR_TYPE, JSArrayIterator::kSize,
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,
isolate->initial_object_prototype(), Builtins::kNumberConstructor);
number_fun->shared()->DontAdaptArguments();
number_fun->shared()->SetConstructStub(
*isolate->builtins()->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);
Accessors::FunctionSetPrototype(number_fun, prototype).Assert();
// 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 i18n 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);
}
{ // --- B o o l e a n ---
Handle<JSFunction> boolean_fun =
InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
isolate->initial_object_prototype(),
Builtins::kBooleanConstructor);
boolean_fun->shared()->DontAdaptArguments();
boolean_fun->shared()->SetConstructStub(
*isolate->builtins()->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());
Accessors::FunctionSetPrototype(boolean_fun, prototype).Assert();
// 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,
isolate->initial_object_prototype(), Builtins::kStringConstructor);
string_fun->shared()->SetConstructStub(
*isolate->builtins()->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);
Handle<AccessorInfo> string_length(
Accessors::StringLengthInfo(isolate, attribs));
{ // Add length.
Descriptor d = Descriptor::AccessorConstant(factory->length_string(),
string_length, 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);
// Create the %StringPrototype%
Handle<JSValue> prototype =
Handle<JSValue>::cast(factory->NewJSObject(string_fun, TENURED));
prototype->set_value(isolate->heap()->empty_string());
Accessors::FunctionSetPrototype(string_fun, prototype).Assert();
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(), string_fun,
DONT_ENUM);
// Install the String.prototype methods.
SimpleInstallFunction(prototype, "charAt", Builtins::kStringPrototypeCharAt,
1, true);
SimpleInstallFunction(prototype, "charCodeAt",
Builtins::kStringPrototypeCharCodeAt, 1, true);
SimpleInstallFunction(prototype, "endsWith",
Builtins::kStringPrototypeEndsWith, 1, false);
SimpleInstallFunction(prototype, "includes",
Builtins::kStringPrototypeIncludes, 1, false);
SimpleInstallFunction(prototype, "indexOf",
Builtins::kStringPrototypeIndexOf, 1, false);
SimpleInstallFunction(prototype, "lastIndexOf",
Builtins::kStringPrototypeLastIndexOf, 1, false);
SimpleInstallFunction(prototype, "localeCompare",
Builtins::kStringPrototypeLocaleCompare, 1, true);
SimpleInstallFunction(prototype, "normalize",
Builtins::kStringPrototypeNormalize, 0, false);
SimpleInstallFunction(prototype, "replace",
Builtins::kStringPrototypeReplace, 2, true);
SimpleInstallFunction(prototype, "split", Builtins::kStringPrototypeSplit,
2, true);
SimpleInstallFunction(prototype, "substr", Builtins::kStringPrototypeSubstr,
2, true);
SimpleInstallFunction(prototype, "substring",
Builtins::kStringPrototypeSubstring, 2, 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);
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);
SimpleInstallFunction(prototype, "valueOf",
Builtins::kStringPrototypeValueOf, 0, true);
Handle<JSFunction> iterator = SimpleCreateFunction(
isolate, factory->NewStringFromAsciiChecked("[Symbol.iterator]"),
Builtins::kStringPrototypeIterator, 0, true);
iterator->shared()->set_builtin_function_id(kStringIterator);
JSObject::AddProperty(prototype, factory->iterator_symbol(), iterator,
static_cast<PropertyAttributes>(DONT_ENUM));
}
{ // --- 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));
Handle<JSFunction> next =
InstallFunction(string_iterator_prototype, "next", JS_OBJECT_TYPE,
JSObject::kHeaderSize, MaybeHandle<JSObject>(),
Builtins::kStringIteratorPrototypeNext);
next->shared()->set_builtin_function_id(kStringIteratorNext);
// Set the expected parameters for %StringIteratorPrototype%.next to 0 (not
// including the receiver), as required by the builtin.
next->shared()->set_internal_formal_parameter_count(0);
// Set the length for the function to satisfy ECMA-262.
next->shared()->set_length(0);
Handle<JSFunction> string_iterator_function = CreateFunction(
isolate, factory->NewStringFromAsciiChecked("StringIterator"),
JS_STRING_ITERATOR_TYPE, JSStringIterator::kSize,
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<JSObject> prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
Handle<JSFunction> symbol_fun =
InstallFunction(global, "Symbol", JS_VALUE_TYPE, JSValue::kSize,
prototype, Builtins::kSymbolConstructor);
symbol_fun->shared()->SetConstructStub(
*isolate->builtins()->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, "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());
// 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 "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(), symbol_fun,
DONT_ENUM);
// 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, 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 ---
// Builtin functions for Date.prototype.
Handle<JSObject> prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
Handle<JSFunction> date_fun =
InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize, prototype,
Builtins::kDateConstructor);
InstallWithIntrinsicDefaultProto(isolate, date_fun,
Context::DATE_FUNCTION_INDEX);
date_fun->shared()->SetConstructStub(
*isolate->builtins()->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);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(), date_fun,
DONT_ENUM);
// 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 i18n 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, 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<Code> code = isolate->builtins()->PromiseGetCapabilitiesExecutor();
Handle<SharedFunctionInfo> info =
factory->NewSharedFunctionInfo(factory->empty_string(), code, true);
info->SetConstructStub(*isolate->builtins()->JSBuiltinsConstructStub());
info->set_instance_class_name(isolate->heap()->Object_string());
info->set_internal_formal_parameter_count(2);
info->set_length(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);
InstallWithIntrinsicDefaultProto(isolate, new_promise_capability,
Context::NEW_PROMISE_CAPABILITY_INDEX);
}
{ // -- P r o m i s e
// Set catch prediction
Handle<Code> promise_code = isolate->builtins()->PromiseConstructor();
promise_code->set_is_promise_rejection(true);
Handle<JSObject> prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
Handle<JSFunction> promise_fun =
InstallFunction(global, "Promise", JS_PROMISE_TYPE, JSPromise::kSize,
prototype, Builtins::kPromiseConstructor);
InstallWithIntrinsicDefaultProto(isolate, promise_fun,
Context::PROMISE_FUNCTION_INDEX);
Handle<SharedFunctionInfo> shared(promise_fun->shared(), isolate);
shared->SetConstructStub(*isolate->builtins()->JSBuiltinsConstructStub());
shared->set_instance_class_name(isolate->heap()->Object_string());
shared->set_internal_formal_parameter_count(1);
shared->set_length(1);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(), promise_fun,
DONT_ENUM);
// 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::kPromiseThen, 2, true);
InstallWithIntrinsicDefaultProto(isolate, promise_then,
Context::PROMISE_THEN_INDEX);
Handle<JSFunction> promise_catch = SimpleInstallFunction(
prototype, "catch", Builtins::kPromiseCatch, 1, true, DONT_ENUM);
InstallWithIntrinsicDefaultProto(isolate, promise_catch,
Context::PROMISE_CATCH_INDEX);
InstallSpeciesGetter(promise_fun);
SimpleInstallFunction(promise_fun, "resolve", Builtins::kPromiseResolve, 1,
true, DONT_ENUM);
SimpleInstallFunction(promise_fun, "reject", Builtins::kPromiseReject, 1,
true, DONT_ENUM);
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);
InstallWithIntrinsicDefaultProto(
isolate, function, Context::PROMISE_INTERNAL_CONSTRUCTOR_INDEX);
}
{ // Internal: IsPromise
Handle<JSFunction> function = SimpleCreateFunction(
isolate, factory->empty_string(), Builtins::kIsPromise, 1, false);
InstallWithIntrinsicDefaultProto(isolate, function,
Context::IS_PROMISE_INDEX);
}
{ // Internal: ResolvePromise
// Also exposed as extrasUtils.resolvePromise.
Handle<JSFunction> function = SimpleCreateFunction(
isolate, factory->empty_string(), Builtins::kResolvePromise, 2, true);
function->shared()->set_native(false);
InstallWithIntrinsicDefaultProto(isolate, function,
Context::PROMISE_RESOLVE_INDEX);
}
{ // Internal: PromiseHandle
Handle<JSFunction> function = SimpleCreateFunction(
isolate, factory->empty_string(), Builtins::kPromiseHandle, 5, false);
InstallWithIntrinsicDefaultProto(isolate, function,
Context::PROMISE_HANDLE_INDEX);
// Set up catch prediction
Handle<Code> promise_handle = isolate->builtins()->PromiseHandle();
promise_handle->set_is_promise_rejection(true);
}
{ // Internal: PromiseHandleReject
Handle<JSFunction> function =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kPromiseHandleReject, 3, false);
InstallWithIntrinsicDefaultProto(isolate, function,
Context::PROMISE_HANDLE_REJECT_INDEX);
// Set up catch prediction
Handle<Code> promise_handle = isolate->builtins()->PromiseHandleReject();
promise_handle->set_is_exception_caught(true);
}
{ // Internal: InternalPromiseReject
Handle<JSFunction> function =
SimpleCreateFunction(isolate, factory->empty_string(),
Builtins::kInternalPromiseReject, 3, true);
function->shared()->set_native(false);
InstallWithIntrinsicDefaultProto(isolate, function,
Context::PROMISE_INTERNAL_REJECT_INDEX);
}
{
Handle<Code> code =
handle(isolate->builtins()->builtin(Builtins::kPromiseResolveClosure),
isolate);
Handle<SharedFunctionInfo> info =
factory->NewSharedFunctionInfo(factory->empty_string(), code, false);
info->set_internal_formal_parameter_count(1);
info->set_length(1);
native_context()->set_promise_resolve_shared_fun(*info);
code =
handle(isolate->builtins()->builtin(Builtins::kPromiseRejectClosure),
isolate);
info =
factory->NewSharedFunctionInfo(factory->empty_string(), code, false);
info->set_internal_formal_parameter_count(1);
info->set_length(1);
native_context()->set_promise_reject_shared_fun(*info);
}
}
{ // -- R e g E x p
// Builtin functions for RegExp.prototype.
Handle<JSObject> prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
Handle<JSFunction> regexp_fun =
InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
prototype, Builtins::kRegExpConstructor);
InstallWithIntrinsicDefaultProto(isolate, regexp_fun,
Context::REGEXP_FUNCTION_INDEX);
Handle<SharedFunctionInfo> shared(regexp_fun->shared(), isolate);
shared->SetConstructStub(*isolate->builtins()->JSBuiltinsConstructStub());
shared->set_instance_class_name(isolate->heap()->RegExp_string());
shared->set_internal_formal_parameter_count(2);
shared->set_length(2);
{
// RegExp.prototype setup.
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(prototype, factory->constructor_string(),
regexp_fun, DONT_ENUM);
{
Handle<JSFunction> fun = SimpleInstallFunction(
prototype, factory->exec_string(), Builtins::kRegExpPrototypeExec,
1, true, DONT_ENUM);
native_context()->set_regexp_exec_function(*fun);
}
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);
{
Handle<JSFunction> fun = SimpleCreateFunction(
isolate, factory->InternalizeUtf8String("[Symbol.match]"),
Builtins::kRegExpPrototypeMatch, 1, true);
InstallFunction(prototype, fun, factory->match_symbol(), DONT_ENUM);
}
{
Handle<JSFunction> fun = SimpleCreateFunction(
isolate, factory->InternalizeUtf8String("[Symbol.replace]"),
Builtins::kRegExpPrototypeReplace, 2, true);
InstallFunction(prototype, fun, factory->replace_symbol(), DONT_ENUM);
}
{
Handle<JSFunction> fun = SimpleCreateFunction(
isolate, factory->InternalizeUtf8String("[Symbol.search]"),
Builtins::kRegExpPrototypeSearch, 1, true);
InstallFunction(prototype, fun, factory->search_symbol(), DONT_ENUM);
}
{
Handle<JSFunction> fun = SimpleCreateFunction(
isolate, factory->InternalizeUtf8String("[Symbol.split]"),
Builtins::kRegExpPrototypeSplit, 2, true);
InstallFunction(prototype, fun, factory->split_symbol(), DONT_ENUM);
}
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(6);
INSTALL_CAPTURE_GETTER(7);
INSTALL_CAPTURE_GETTER(8);
INSTALL_CAPTURE_GETTER(9);
#undef INSTALL_CAPTURE_GETTER
}
DCHECK(regexp_fun->has_initial_map());
Handle<Map> initial_map(regexp_fun->initial_map());
DCHECK_EQ(0, initial_map->GetInObjectProperties());
Map::EnsureDescriptorSlack(initial_map, 1);
// ECMA-262, section 15.10.7.5.
PropertyAttributes writable =
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
Descriptor d = Descriptor::DataField(factory->lastIndex_string(),
JSRegExp::kLastIndexFieldIndex,
writable, Representation::Tagged());
initial_map->AppendDescriptor(&d);
static const int num_fields = JSRegExp::kInObjectFieldCount;
initial_map->SetInObjectProperties(num_fields);
initial_map->set_unused_property_fields(0);
initial_map->set_instance_size(initial_map->instance_size() +
num_fields * kPointerSize);
{ // Internal: RegExpInternalMatch
Handle<JSFunction> function =
factory->NewFunction(isolate->factory()->empty_string(),
isolate->builtins()->RegExpInternalMatch(),
JS_OBJECT_TYPE, JSObject::kHeaderSize);
function->shared()->set_internal_formal_parameter_count(2);
function->shared()->set_length(2);
function->shared()->set_native(true);
native_context()->set(Context::REGEXP_INTERNAL_MATCH, *function);
}
// Create the last match info. One for external use, and one for internal
// use when we don't want to modify the externally visible match info.
Handle<RegExpMatchInfo> last_match_info = factory->NewRegExpMatchInfo();
native_context()->set_regexp_last_match_info(*last_match_info);
Handle<RegExpMatchInfo> internal_match_info = factory->NewRegExpMatchInfo();
native_context()->set_regexp_internal_match_info(*internal_match_info);
}
{ // -- E r r o r
InstallError(isolate, global, factory->Error_string(),
Context::ERROR_FUNCTION_INDEX);
InstallMakeError(isolate, isolate->builtins()->MakeError(),
Context::MAKE_ERROR_INDEX);
}
{ // -- E v a l E r r o r
InstallError(isolate, global, factory->EvalError_string(),
Context::EVAL_ERROR_FUNCTION_INDEX);
}
{ // -- R a n g e E r r o r
InstallError(isolate, global, factory->RangeError_string(),
Context::RANGE_ERROR_FUNCTION_INDEX);
InstallMakeError(isolate, isolate->builtins()->MakeRangeError(),
Context::MAKE_RANGE_ERROR_INDEX);
}
{ // -- R e f e r e n c e E r r o r
InstallError(isolate, global, factory->ReferenceError_string(),
Context::REFERENCE_ERROR_FUNCTION_INDEX);
}
{ // -- S y n t a x E r r o r
InstallError(isolate, global, factory->SyntaxError_string(),
Context::SYNTAX_ERROR_FUNCTION_INDEX);
InstallMakeError(isolate, isolate->builtins()->MakeSyntaxError(),
Context::MAKE_SYNTAX_ERROR_INDEX);
}
{ // -- T y p e E r r o r
InstallError(isolate, global, factory->TypeError_string(),
Context::TYPE_ERROR_FUNCTION_INDEX);
InstallMakeError(isolate, isolate->builtins()->MakeTypeError(),
Context::MAKE_TYPE_ERROR_INDEX);
}
{ // -- U R I E r r o r
InstallError(isolate, global, factory->URIError_string(),
Context::URI_ERROR_FUNCTION_INDEX);
InstallMakeError(isolate, isolate->builtins()->MakeURIError(),
Context::MAKE_URI_ERROR_INDEX);
}
{ // -- C o m p i l e E r r o r
Handle<JSObject> dummy = factory->NewJSObject(isolate->object_function());
InstallError(isolate, dummy, factory->CompileError_string(),
Context::WASM_COMPILE_ERROR_FUNCTION_INDEX);
// -- L i n k E r r o r
InstallError(isolate, dummy, factory->LinkError_string(),
Context::WASM_LINK_ERROR_FUNCTION_INDEX);
// -- R u n t i m e E r r o r
InstallError(isolate, dummy, factory->RuntimeError_string(),
Context::WASM_RUNTIME_ERROR_FUNCTION_INDEX);
}
// Initialize the embedder data slot.
Handle<FixedArray> embedder_data = factory->NewFixedArray(3);
native_context()->set_embedder_data(*embedder_data);
{ // -- J S O N
Handle<String> name = factory->InternalizeUtf8String("JSON");
Handle<JSFunction> cons = factory->NewFunction(name);
JSFunction::SetInstancePrototype(cons,
Handle<Object>(native_context()->initial_object_prototype(), isolate));
Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
DCHECK(json_object->IsJSObject());
JSObject::AddProperty(global, name, json_object, DONT_ENUM);
SimpleInstallFunction(json_object, "parse", Builtins::kJsonParse, 2, false);
SimpleInstallFunction(json_object, "stringify", Builtins::kJsonStringify, 3,
true);
JSObject::AddProperty(
json_object, factory->to_string_tag_symbol(),
factory->NewStringFromAsciiChecked("JSON"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
}
{ // -- M a t h
Handle<String> name = factory->InternalizeUtf8String("Math");
Handle<JSFunction> cons = factory->NewFunction(name);
JSFunction::SetInstancePrototype(
cons,
Handle<Object>(native_context()->initial_object_prototype(), isolate));
Handle<JSObject> math = factory->NewJSObject(cons, TENURED);
DCHECK(math->IsJSObject());
JSObject::AddProperty(global, name, math, DONT_ENUM);
SimpleInstallFunction(math, "abs", Builtins::kMathAbs, 1, true);
SimpleInstallFunction(math, "acos", Builtins::kMathAcos, 1, true);
SimpleInstallFunction(math, "acosh", Builtins::kMathAcosh, 1, true);
SimpleInstallFunction(math, "asin", Builtins::kMathAsin, 1, true);
SimpleInstallFunction(math, "asinh", Builtins::kMathAsinh, 1, true);
SimpleInstallFunction(math, "atan", Builtins::kMathAtan, 1, true);
SimpleInstallFunction(math, "atanh", Builtins::kMathAtanh, 1, true);
SimpleInstallFunction(math, "atan2", Builtins::kMathAtan2, 2, true);
SimpleInstallFunction(math, "ceil", Builtins::kMathCeil, 1, true);
SimpleInstallFunction(math, "cbrt", Builtins::kMathCbrt, 1, true);
SimpleInstallFunction(math, "expm1", Builtins::kMathExpm1, 1, true);
SimpleInstallFunction(math, "clz32", Builtins::kMathClz32, 1, true);
SimpleInstallFunction(math, "cos", Builtins::kMathCos, 1, true);
SimpleInstallFunction(math, "cosh", Builtins::kMathCosh, 1, true);
SimpleInstallFunction(math, "exp", Builtins::kMathExp, 1, true);
Handle<JSFunction> math_floor =
SimpleInstallFunction(math, "floor", Builtins::kMathFloor, 1, true);
native_context()->set_math_floor(*math_floor);
SimpleInstallFunction(math, "fround", Builtins::kMathFround, 1, true);
SimpleInstallFunction(math, "hypot", Builtins::kMathHypot, 2, false);
SimpleInstallFunction(math, "imul", Builtins::kMathImul, 2, true);
SimpleInstallFunction(math, "log", Builtins::kMathLog, 1, true);
SimpleInstallFunction(math, "log1p", Builtins::kMathLog1p, 1, true);
SimpleInstallFunction(math, "log2", Builtins::kMathLog2, 1, true);
SimpleInstallFunction(math, "log10", Builtins::kMathLog10, 1, true);
SimpleInstallFunction(math, "max", Builtins::kMathMax, 2, false);
SimpleInstallFunction(math, "min", Builtins::kMathMin, 2, false);
Handle<JSFunction> math_pow =
SimpleInstallFunction(math, "pow", Builtins::kMathPow, 2, true);
native_context()->set_math_pow(*math_pow);
SimpleInstallFunction(math, "random", Builtins::kMathRandom, 0, true);
SimpleInstallFunction(math, "round", Builtins::kMathRound, 1, true);
SimpleInstallFunction(math, "sign", Builtins::kMathSign, 1, true);
SimpleInstallFunction(math, "sin", Builtins::kMathSin, 1, true);
SimpleInstallFunction(math, "sinh", Builtins::kMathSinh, 1, true);
SimpleInstallFunction(math, "sqrt", Builtins::kMathSqrt, 1, true);
SimpleInstallFunction(math, "tan", Builtins::kMathTan, 1, true);
SimpleInstallFunction(math, "tanh", Builtins::kMathTanh, 1, true);
SimpleInstallFunction(math, "trunc", Builtins::kMathTrunc, 1, true);
// Install math constants.
double const kE = base::ieee754::exp(1.0);
double const kPI = 3.1415926535897932;
InstallConstant(isolate, math, "E", factory->NewNumber(kE));
InstallConstant(isolate, math, "LN10",
factory->NewNumber(base::ieee754::log(10.0)));
InstallConstant(isolate, math, "LN2",
factory->NewNumber(base::ieee754::log(2.0)));
InstallConstant(isolate, math, "LOG10E",
factory->NewNumber(base::ieee754::log10(kE)));
InstallConstant(isolate, math, "LOG2E",
factory->NewNumber(base::ieee754::log2(kE)));
InstallConstant(isolate, math, "PI", factory->NewNumber(kPI));
InstallConstant(isolate, math, "SQRT1_2",
factory->NewNumber(std::sqrt(0.5)));
InstallConstant(isolate, math, "SQRT2", factory->NewNumber(std::sqrt(2.0)));
JSObject::AddProperty(
math, factory->to_string_tag_symbol(),
factory->NewStringFromAsciiChecked("Math"),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
}
#ifdef V8_I18N_SUPPORT
{ // -- I n t l
Handle<String> name = factory->InternalizeUtf8String("Intl");
Handle<JSFunction> cons = factory->NewFunction(name);
JSFunction::SetInstancePrototype(
cons,
Handle<Object>(native_context()->initial_object_prototype(), isolate));
Handle<JSObject> intl = factory->NewJSObject(cons, TENURED);
DCHECK(intl->IsJSObject());
JSObject::AddProperty(global, name, intl, DONT_ENUM);
Handle<JSObject> date_time_format_prototype =
factory->NewJSObject(isolate->object_function(), TENURED);
// Install the @@toStringTag property on the {prototype}.
JSObject::AddProperty(
date_time_format_prototype, factory->to_string_tag_symbol(),
factory->Object_string(),
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
Handle<JSFunction> date_time_format_constructor = InstallFunction(
intl, "DateTimeFormat", JS_OBJECT_TYPE, DateFormat::kSize,
date_time_format_prototype, Builtins::kIllegal);
JSObject::AddProperty(date_time_format_prototype,
factory->constructor_string(),
date_time_format_constructor, DONT_ENUM);
InstallWithIntrinsicDefaultProto(
isolate, date_time_format_constructor,
Context::INTL_DATE_TIME_FORMAT_FUNCTION_INDEX);