blob: 5fbc1ca76b7f9bf987444493edcaf52efaddcd75 [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/init/bootstrapper.h"
#include "src/api/api-inl.h"
#include "src/api/api-natives.h"
#include "src/base/hashmap.h"
#include "src/base/ieee754.h"
#include "src/builtins/accessors.h"
#include "src/codegen/compiler.h"
#include "src/common/globals.h"
#include "src/debug/debug.h"
#include "src/execution/isolate-inl.h"
#include "src/execution/microtask-queue.h"
#include "src/execution/protectors.h"
#include "src/extensions/cputracemark-extension.h"
#include "src/extensions/externalize-string-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/logging/runtime-call-stats-scope.h"
#include "src/objects/instance-type.h"
#include "src/objects/objects.h"
#ifdef ENABLE_VTUNE_TRACEMARK
#include "src/extensions/vtunedomain-support-extension.h"
#endif // ENABLE_VTUNE_TRACEMARK
#include "src/heap/heap-inl.h"
#include "src/logging/counters.h"
#include "src/logging/log.h"
#include "src/numbers/math-random.h"
#include "src/objects/api-callbacks.h"
#include "src/objects/arguments.h"
#include "src/objects/function-kind.h"
#include "src/objects/hash-table-inl.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/intl-objects.h"
#endif // V8_INTL_SUPPORT
#include "src/objects/js-array-buffer-inl.h"
#include "src/objects/js-array-inl.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/js-break-iterator.h"
#include "src/objects/js-collator.h"
#include "src/objects/js-date-time-format.h"
#include "src/objects/js-display-names.h"
#include "src/objects/js-list-format.h"
#include "src/objects/js-locale.h"
#include "src/objects/js-number-format.h"
#include "src/objects/js-plural-rules.h"
#endif // V8_INTL_SUPPORT
#include "src/objects/js-regexp-string-iterator.h"
#include "src/objects/js-regexp.h"
#include "src/objects/js-shadow-realms.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/js-relative-time-format.h"
#include "src/objects/js-segment-iterator.h"
#include "src/objects/js-segmenter.h"
#include "src/objects/js-segments.h"
#endif // V8_INTL_SUPPORT
#include "src/codegen/script-details.h"
#include "src/objects/js-struct.h"
#include "src/objects/js-temporal-objects-inl.h"
#include "src/objects/js-weak-refs.h"
#include "src/objects/ordered-hash-table.h"
#include "src/objects/property-cell.h"
#include "src/objects/slots-inl.h"
#include "src/objects/swiss-name-dictionary-inl.h"
#include "src/objects/templates.h"
#include "src/snapshot/snapshot.h"
#include "src/zone/zone-hashmap.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/wasm-js.h"
#endif // V8_ENABLE_WEBASSEMBLY
namespace v8 {
namespace internal {
void SourceCodeCache::Initialize(Isolate* isolate, bool create_heap_objects) {
cache_ = create_heap_objects ? ReadOnlyRoots(isolate).empty_fixed_array()
: FixedArray();
}
void SourceCodeCache::Iterate(RootVisitor* v) {
v->VisitRootPointer(Root::kExtensions, nullptr, FullObjectSlot(&cache_));
}
bool SourceCodeCache::Lookup(Isolate* isolate, base::Vector<const char> name,
Handle<SharedFunctionInfo>* handle) {
for (int i = 0; i < cache_.length(); i += 2) {
SeqOneByteString str = SeqOneByteString::cast(cache_.get(i));
if (str.IsOneByteEqualTo(name)) {
*handle = Handle<SharedFunctionInfo>(
SharedFunctionInfo::cast(cache_.get(i + 1)), isolate);
return true;
}
}
return false;
}
void SourceCodeCache::Add(Isolate* isolate, base::Vector<const char> name,
Handle<SharedFunctionInfo> shared) {
Factory* factory = isolate->factory();
HandleScope scope(isolate);
int length = cache_.length();
Handle<FixedArray> new_array =
factory->NewFixedArray(length + 2, AllocationType::kOld);
cache_.CopyTo(0, *new_array, 0, cache_.length());
cache_ = *new_array;
Handle<String> str =
factory
->NewStringFromOneByte(base::Vector<const uint8_t>::cast(name),
AllocationType::kOld)
.ToHandleChecked();
DCHECK(!str.is_null());
cache_.set(length, *str);
cache_.set(length + 1, *shared);
Script::cast(shared->script()).set_type(type_);
}
Bootstrapper::Bootstrapper(Isolate* isolate)
: isolate_(isolate),
nesting_(0),
extensions_cache_(Script::TYPE_EXTENSION) {}
void Bootstrapper::Initialize(bool create_heap_objects) {
extensions_cache_.Initialize(isolate_, create_heap_objects);
}
static const char* GCFunctionName() {
bool flag_given =
FLAG_expose_gc_as != nullptr && strlen(FLAG_expose_gc_as) != 0;
return flag_given ? FLAG_expose_gc_as : "gc";
}
static bool isValidCpuTraceMarkFunctionName() {
return FLAG_expose_cputracemark_as != nullptr &&
strlen(FLAG_expose_cputracemark_as) != 0;
}
void Bootstrapper::InitializeOncePerProcess() {
v8::RegisterExtension(std::make_unique<GCExtension>(GCFunctionName()));
v8::RegisterExtension(std::make_unique<ExternalizeStringExtension>());
v8::RegisterExtension(std::make_unique<StatisticsExtension>());
v8::RegisterExtension(std::make_unique<TriggerFailureExtension>());
v8::RegisterExtension(std::make_unique<IgnitionStatisticsExtension>());
if (isValidCpuTraceMarkFunctionName()) {
v8::RegisterExtension(
std::make_unique<CpuTraceMarkExtension>(FLAG_expose_cputracemark_as));
}
#ifdef ENABLE_VTUNE_TRACEMARK
v8::RegisterExtension(
std::make_unique<VTuneDomainSupportExtension>("vtunedomainmark"));
#endif // ENABLE_VTUNE_TRACEMARK
}
void Bootstrapper::TearDown() {
extensions_cache_.Initialize(isolate_, false); // Yes, symmetrical
}
class Genesis {
public:
Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template,
size_t context_snapshot_index,
v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
v8::MicrotaskQueue* microtask_queue);
Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template);
~Genesis() = default;
Isolate* isolate() const { return isolate_; }
Factory* factory() const { return isolate_->factory(); }
Builtins* builtins() const { return isolate_->builtins(); }
Heap* heap() const { return isolate_->heap(); }
Handle<Context> result() { return result_; }
Handle<JSGlobalProxy> global_proxy() { return global_proxy_; }
private:
Handle<NativeContext> 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();
// Returns the %ThrowTypeError% intrinsic function.
// See ES#sec-%throwtypeerror% for details.
Handle<JSFunction> GetThrowTypeErrorIntrinsic();
void CreateSloppyModeFunctionMaps(Handle<JSFunction> empty);
void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
void CreateObjectFunction(Handle<JSFunction> empty);
void CreateIteratorMaps(Handle<JSFunction> empty);
void CreateAsyncIteratorMaps(Handle<JSFunction> empty);
void CreateAsyncFunctionMaps(Handle<JSFunction> empty);
void CreateJSProxyMaps();
// Make the "arguments" and "caller" properties throw a TypeError on access.
void AddRestrictedFunctionProperties(Handle<JSFunction> empty);
// Creates the global objects using the global proxy and the template passed
// in through the API. We call this regardless of whether we are building a
// context from scratch or using a deserialized one from the context 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);
void InitializeExperimentalGlobal();
void InitializeIteratorFunctions();
void InitializeCallSiteBuiltins();
void InitializeConsole(Handle<JSObject> extras_binding);
#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_regexp_linear_flag();
enum ArrayBufferKind { ARRAY_BUFFER, SHARED_ARRAY_BUFFER };
Handle<JSFunction> CreateArrayBuffer(Handle<String> name,
ArrayBufferKind array_buffer_kind);
bool InstallABunchOfRandomThings();
bool InstallExtrasBindings();
Handle<JSFunction> InstallTypedArray(const char* name,
ElementsKind elements_kind,
InstanceType constructor_type,
int rab_gsab_initial_map_index);
void InitializeMapCaches();
enum ExtensionTraversalState { UNVISITED, VISITED, INSTALLED };
class ExtensionStates {
public:
ExtensionStates();
ExtensionStates(const ExtensionStates&) = delete;
ExtensionStates& operator=(const ExtensionStates&) = delete;
ExtensionTraversalState get_state(RegisteredExtension* extension);
void set_state(RegisteredExtension* extension,
ExtensionTraversalState state);
private:
base::HashMap map_;
};
// Used both for deserialized and from-scratch contexts to add the extensions
// provided.
static bool InstallExtensions(Isolate* isolate,
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(Isolate* isolate,
Handle<Context> native_context);
bool ConfigureApiObject(Handle<JSObject> object,
Handle<ObjectTemplateInfo> object_template);
bool ConfigureGlobalObject(
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);
Handle<Map> CreateInitialMapForArraySubclass(int size,
int inobject_properties);
static bool CompileExtension(Isolate* isolate, v8::Extension* extension);
Isolate* isolate_;
Handle<Context> result_;
Handle<NativeContext> native_context_;
Handle<JSGlobalProxy> global_proxy_;
// %ThrowTypeError%. See ES#sec-%throwtypeerror% for details.
Handle<JSFunction> restricted_properties_thrower_;
BootstrapperActive active_;
friend class Bootstrapper;
};
void Bootstrapper::Iterate(RootVisitor* v) {
extensions_cache_.Iterate(v);
v->Synchronize(VisitorSynchronization::kExtensions);
}
Handle<Context> Bootstrapper::CreateEnvironment(
MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template,
v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
v8::MicrotaskQueue* microtask_queue) {
HandleScope scope(isolate_);
Handle<Context> env;
{
Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template,
context_snapshot_index, embedder_fields_deserializer,
microtask_queue);
env = genesis.result();
if (env.is_null() || !InstallExtensions(env, extensions)) {
return Handle<Context>();
}
}
LogAllMaps();
isolate_->heap()->NotifyBootstrapComplete();
return scope.CloseAndEscape(env);
}
Handle<JSGlobalProxy> Bootstrapper::NewRemoteContext(
MaybeHandle<JSGlobalProxy> maybe_global_proxy,
v8::Local<v8::ObjectTemplate> global_proxy_template) {
HandleScope scope(isolate_);
Handle<JSGlobalProxy> global_proxy;
{
Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template);
global_proxy = genesis.global_proxy();
if (global_proxy.is_null()) return Handle<JSGlobalProxy>();
}
LogAllMaps();
return scope.CloseAndEscape(global_proxy);
}
void Bootstrapper::LogAllMaps() {
if (!FLAG_log_maps || isolate_->initialized_from_snapshot()) return;
// Log all created Map objects that are on the heap. For snapshots the Map
// logging happens during deserialization in order to avoid printing Maps
// multiple times during partial deserialization.
LOG(isolate_, LogAllMaps());
}
namespace {
#ifdef DEBUG
bool IsFunctionMapOrSpecialBuiltin(Handle<Map> map, Builtin builtin,
Handle<Context> context) {
// During bootstrapping some of these maps could be not created yet.
return ((*map == context->get(Context::STRICT_FUNCTION_MAP_INDEX)) ||
(*map == context->get(
Context::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX)) ||
(*map ==
context->get(
Context::STRICT_FUNCTION_WITH_READONLY_PROTOTYPE_MAP_INDEX)) ||
// Check if it's a creation of an empty or Proxy function during
// bootstrapping.
(builtin == Builtin::kEmptyFunction ||
builtin == Builtin::kProxyConstructor));
}
#endif // DEBUG
V8_NOINLINE Handle<JSFunction> CreateFunctionForBuiltin(Isolate* isolate,
Handle<String> name,
Handle<Map> map,
Builtin builtin) {
Factory* factory = isolate->factory();
Handle<NativeContext> context(isolate->native_context());
DCHECK(IsFunctionMapOrSpecialBuiltin(map, builtin, context));
Handle<SharedFunctionInfo> info =
factory->NewSharedFunctionInfoForBuiltin(name, builtin);
info->set_language_mode(LanguageMode::kStrict);
return Factory::JSFunctionBuilder{isolate, info, context}
.set_map(map)
.Build();
}
V8_NOINLINE Handle<JSFunction> CreateFunctionForBuiltinWithPrototype(
Isolate* isolate, Handle<String> name, Builtin builtin,
Handle<HeapObject> prototype, InstanceType type, int instance_size,
int inobject_properties, MutableMode prototype_mutability) {
Factory* factory = isolate->factory();
Handle<NativeContext> context(isolate->native_context());
Handle<Map> map =
prototype_mutability == MUTABLE
? isolate->strict_function_map()
: isolate->strict_function_with_readonly_prototype_map();
DCHECK(IsFunctionMapOrSpecialBuiltin(map, builtin, context));
Handle<SharedFunctionInfo> info =
factory->NewSharedFunctionInfoForBuiltin(name, builtin);
info->set_language_mode(LanguageMode::kStrict);
info->set_expected_nof_properties(inobject_properties);
Handle<JSFunction> result =
Factory::JSFunctionBuilder{isolate, info, context}.set_map(map).Build();
ElementsKind elements_kind;
switch (type) {
case JS_ARRAY_TYPE:
elements_kind = PACKED_SMI_ELEMENTS;
break;
case JS_ARGUMENTS_OBJECT_TYPE:
elements_kind = PACKED_ELEMENTS;
break;
default:
elements_kind = TERMINAL_FAST_ELEMENTS_KIND;
break;
}
Handle<Map> initial_map =
factory->NewMap(type, instance_size, elements_kind, inobject_properties);
if (type == JS_FUNCTION_TYPE) {
DCHECK_EQ(instance_size, JSFunction::kSizeWithPrototype);
// Since we are creating an initial map for JSFunction objects with
// prototype slot, set the respective bit.
initial_map->set_has_prototype_slot(true);
}
// TODO(littledan): Why do we have this is_generator test when
// NewFunctionPrototype already handles finding an appropriately
// shared prototype?
if (!IsResumableFunction(info->kind()) && prototype->IsTheHole(isolate)) {
prototype = factory->NewFunctionPrototype(result);
}
JSFunction::SetInitialMap(isolate, result, initial_map, prototype);
return result;
}
V8_NOINLINE Handle<JSFunction> CreateFunctionForBuiltinWithoutPrototype(
Isolate* isolate, Handle<String> name, Builtin builtin) {
Factory* factory = isolate->factory();
Handle<NativeContext> context(isolate->native_context());
Handle<Map> map = isolate->strict_function_without_prototype_map();
DCHECK(IsFunctionMapOrSpecialBuiltin(map, builtin, context));
Handle<SharedFunctionInfo> info =
factory->NewSharedFunctionInfoForBuiltin(name, builtin);
info->set_language_mode(LanguageMode::kStrict);
return Factory::JSFunctionBuilder{isolate, info, context}
.set_map(map)
.Build();
}
V8_NOINLINE Handle<JSFunction> CreateFunction(
Isolate* isolate, Handle<String> name, InstanceType type, int instance_size,
int inobject_properties, Handle<HeapObject> prototype, Builtin builtin) {
DCHECK(Builtins::HasJSLinkage(builtin));
Handle<JSFunction> result = CreateFunctionForBuiltinWithPrototype(
isolate, name, builtin, prototype, type, instance_size,
inobject_properties, IMMUTABLE);
// Make the JSFunction's prototype object fast.
JSObject::MakePrototypesFast(handle(result->prototype(), isolate),
kStartAtReceiver, isolate);
// Make the resulting JSFunction object fast.
JSObject::MakePrototypesFast(result, kStartAtReceiver, isolate);
result->shared().set_native(true);
return result;
}
V8_NOINLINE Handle<JSFunction> CreateFunction(
Isolate* isolate, const char* name, InstanceType type, int instance_size,
int inobject_properties, Handle<HeapObject> prototype, Builtin builtin) {
return CreateFunction(isolate,
isolate->factory()->InternalizeUtf8String(name), type,
instance_size, inobject_properties, prototype, builtin);
}
V8_NOINLINE Handle<JSFunction> InstallFunction(
Isolate* isolate, Handle<JSObject> target, Handle<String> name,
InstanceType type, int instance_size, int inobject_properties,
Handle<HeapObject> prototype, Builtin call) {
DCHECK(Builtins::HasJSLinkage(call));
Handle<JSFunction> function = CreateFunction(
isolate, name, type, instance_size, inobject_properties, prototype, call);
JSObject::AddProperty(isolate, target, name, function, DONT_ENUM);
return function;
}
V8_NOINLINE Handle<JSFunction> InstallFunction(
Isolate* isolate, Handle<JSObject> target, const char* name,
InstanceType type, int instance_size, int inobject_properties,
Handle<HeapObject> prototype, Builtin call) {
return InstallFunction(isolate, target,
isolate->factory()->InternalizeUtf8String(name), type,
instance_size, inobject_properties, prototype, call);
}
// This sets a constructor instance type on the constructor map which will be
// used in IsXxxConstructor() predicates. Having such predicates helps figuring
// out if a protector cell should be invalidated. If there are no protector
// cell checks required for constructor, this function must not be used.
// Note, this function doesn't create a copy of the constructor's map. So it's
// better to set constructor instance type after all the properties are added
// to the constructor and thus the map is already guaranteed to be unique.
V8_NOINLINE void SetConstructorInstanceType(Isolate* isolate,
Handle<JSFunction> constructor,
InstanceType constructor_type) {
DCHECK(InstanceTypeChecker::IsJSFunction(constructor_type));
DCHECK_NE(constructor_type, JS_FUNCTION_TYPE);
Map map = constructor->map();
// Check we don't accidentally change one of the existing maps.
DCHECK_NE(map, *isolate->strict_function_map());
DCHECK_NE(map, *isolate->strict_function_with_readonly_prototype_map());
// Constructor function map is always a root map, and thus we don't have to
// deal with updating the whole transition tree.
DCHECK(map.GetBackPointer().IsUndefined(isolate));
DCHECK_EQ(JS_FUNCTION_TYPE, map.instance_type());
map.set_instance_type(constructor_type);
}
V8_NOINLINE Handle<JSFunction> SimpleCreateFunction(Isolate* isolate,
Handle<String> name,
Builtin call, int len,
bool adapt) {
DCHECK(Builtins::HasJSLinkage(call));
name = String::Flatten(isolate, name, AllocationType::kOld);
Handle<JSFunction> fun =
CreateFunctionForBuiltinWithoutPrototype(isolate, name, call);
// Make the resulting JSFunction object fast.
JSObject::MakePrototypesFast(fun, kStartAtReceiver, isolate);
fun->shared().set_native(true);
if (adapt) {
fun->shared().set_internal_formal_parameter_count(JSParameterCount(len));
} else {
fun->shared().DontAdaptArguments();
}
fun->shared().set_length(len);
return fun;
}
V8_NOINLINE Handle<JSFunction> InstallFunctionWithBuiltinId(
Isolate* isolate, Handle<JSObject> base, const char* name, Builtin call,
int len, bool adapt) {
Handle<String> internalized_name =
isolate->factory()->InternalizeUtf8String(name);
Handle<JSFunction> fun =
SimpleCreateFunction(isolate, internalized_name, call, len, adapt);
JSObject::AddProperty(isolate, base, internalized_name, fun, DONT_ENUM);
return fun;
}
V8_NOINLINE Handle<JSFunction> SimpleInstallFunction(
Isolate* isolate, Handle<JSObject> base, const char* name, Builtin call,
int len, bool adapt, PropertyAttributes attrs = DONT_ENUM) {
// Although function name does not have to be internalized the property name
// will be internalized during property addition anyway, so do it here now.
Handle<String> internalized_name =
isolate->factory()->InternalizeUtf8String(name);
Handle<JSFunction> fun =
SimpleCreateFunction(isolate, internalized_name, call, len, adapt);
JSObject::AddProperty(isolate, base, internalized_name, fun, attrs);
return fun;
}
V8_NOINLINE Handle<JSFunction> InstallFunctionAtSymbol(
Isolate* isolate, Handle<JSObject> base, Handle<Symbol> symbol,
const char* symbol_string, Builtin call, int len, bool adapt,
PropertyAttributes attrs = DONT_ENUM) {
Handle<String> internalized_symbol =
isolate->factory()->InternalizeUtf8String(symbol_string);
Handle<JSFunction> fun =
SimpleCreateFunction(isolate, internalized_symbol, call, len, adapt);
JSObject::AddProperty(isolate, base, symbol, fun, attrs);
return fun;
}
V8_NOINLINE void SimpleInstallGetterSetter(Isolate* isolate,
Handle<JSObject> base,
Handle<String> name,
Builtin call_getter,
Builtin call_setter) {
Handle<String> getter_name =
Name::ToFunctionName(isolate, name, isolate->factory()->get_string())
.ToHandleChecked();
Handle<JSFunction> getter =
SimpleCreateFunction(isolate, getter_name, call_getter, 0, true);
Handle<String> setter_name =
Name::ToFunctionName(isolate, name, isolate->factory()->set_string())
.ToHandleChecked();
Handle<JSFunction> setter =
SimpleCreateFunction(isolate, setter_name, call_setter, 1, true);
JSObject::DefineAccessor(base, name, getter, setter, DONT_ENUM).Check();
}
void SimpleInstallGetterSetter(Isolate* isolate, Handle<JSObject> base,
const char* name, Builtin call_getter,
Builtin call_setter) {
SimpleInstallGetterSetter(isolate, base,
isolate->factory()->InternalizeUtf8String(name),
call_getter, call_setter);
}
V8_NOINLINE Handle<JSFunction> SimpleInstallGetter(Isolate* isolate,
Handle<JSObject> base,
Handle<Name> name,
Handle<Name> property_name,
Builtin call, bool adapt) {
Handle<String> getter_name =
Name::ToFunctionName(isolate, name, isolate->factory()->get_string())
.ToHandleChecked();
Handle<JSFunction> getter =
SimpleCreateFunction(isolate, getter_name, call, 0, adapt);
Handle<Object> setter = isolate->factory()->undefined_value();
JSObject::DefineAccessor(base, property_name, getter, setter, DONT_ENUM)
.Check();
return getter;
}
V8_NOINLINE Handle<JSFunction> SimpleInstallGetter(Isolate* isolate,
Handle<JSObject> base,
Handle<Name> name,
Builtin call, bool adapt) {
return SimpleInstallGetter(isolate, base, name, name, call, adapt);
}
V8_NOINLINE void InstallConstant(Isolate* isolate, Handle<JSObject> holder,
const char* name, Handle<Object> value) {
JSObject::AddProperty(
isolate, holder, isolate->factory()->InternalizeUtf8String(name), value,
static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
}
V8_NOINLINE void InstallTrueValuedProperty(Isolate* isolate,
Handle<JSObject> holder,
const char* name) {
JSObject::AddProperty(isolate, holder,
isolate->factory()->InternalizeUtf8String(name),
isolate->factory()->true_value(), NONE);
}
V8_NOINLINE void InstallSpeciesGetter(Isolate* isolate,
Handle<JSFunction> constructor) {
Factory* factory = isolate->factory();
// TODO(adamk): We should be able to share a SharedFunctionInfo
// between all these JSFunctins.
SimpleInstallGetter(isolate, constructor, factory->symbol_species_string(),
factory->species_symbol(), Builtin::kReturnReceiver,
true);
}
V8_NOINLINE void InstallToStringTag(Isolate* isolate, Handle<JSObject> holder,
Handle<String> value) {
JSObject::AddProperty(isolate, holder,
isolate->factory()->to_string_tag_symbol(), value,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
}
void InstallToStringTag(Isolate* isolate, Handle<JSObject> holder,
const char* value) {
InstallToStringTag(isolate, holder,
isolate->factory()->InternalizeUtf8String(value));
}
} // namespace
Handle<JSFunction> Genesis::CreateEmptyFunction() {
// Allocate the function map first and then patch the prototype later.
Handle<Map> empty_function_map = factory()->CreateSloppyFunctionMap(
FUNCTION_WITHOUT_PROTOTYPE, MaybeHandle<JSFunction>());
empty_function_map->set_is_prototype_map(true);
DCHECK(!empty_function_map->is_dictionary_map());
// Allocate the empty function as the prototype for function according to
// ES#sec-properties-of-the-function-prototype-object
Handle<JSFunction> empty_function =
CreateFunctionForBuiltin(isolate(), factory()->empty_string(),
empty_function_map, Builtin::kEmptyFunction);
native_context()->set_empty_function(*empty_function);
// --- E m p t y ---
Handle<String> source = factory()->NewStringFromStaticChars("() {}");
Handle<Script> script = factory()->NewScript(source);
script->set_type(Script::TYPE_NATIVE);
Handle<WeakFixedArray> infos = factory()->NewWeakFixedArray(2);
script->set_shared_function_infos(*infos);
empty_function->shared().set_raw_scope_info(
ReadOnlyRoots(isolate()).empty_function_scope_info());
empty_function->shared().DontAdaptArguments();
empty_function->shared().SetScript(ReadOnlyRoots(isolate()), *script, 1);
return empty_function;
}
void Genesis::CreateSloppyModeFunctionMaps(Handle<JSFunction> empty) {
Factory* factory = isolate_->factory();
Handle<Map> map;
//
// Allocate maps for sloppy functions without prototype.
//
map = factory->CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
native_context()->set_sloppy_function_without_prototype_map(*map);
//
// Allocate maps for sloppy functions with readonly prototype.
//
map =
factory->CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
native_context()->set_sloppy_function_with_readonly_prototype_map(*map);
//
// Allocate maps for sloppy functions with writable prototype.
//
map = factory->CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE,
empty);
native_context()->set_sloppy_function_map(*map);
map = factory->CreateSloppyFunctionMap(
FUNCTION_WITH_NAME_AND_WRITEABLE_PROTOTYPE, empty);
native_context()->set_sloppy_function_with_name_map(*map);
}
Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic() {
if (!restricted_properties_thrower_.is_null()) {
return restricted_properties_thrower_;
}
Handle<String> name = factory()->empty_string();
Handle<JSFunction> function = CreateFunctionForBuiltinWithoutPrototype(
isolate(), name, Builtin::kStrictPoisonPillThrower);
function->shared().DontAdaptArguments();
// %ThrowTypeError% must have a name property with an empty string value. Per
// spec, ThrowTypeError's name is non-configurable, unlike ordinary functions'
// name property. To redefine it to be non-configurable, use
// SetOwnPropertyIgnoreAttributes.
JSObject::SetOwnPropertyIgnoreAttributes(
function, factory()->name_string(), factory()->empty_string(),
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
.Assert();
// length needs to be non configurable.
Handle<Object> value(Smi::FromInt(function->length()), isolate());
JSObject::SetOwnPropertyIgnoreAttributes(
function, factory()->length_string(), value,
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
.Assert();
if (JSObject::PreventExtensions(function, kThrowOnError).IsNothing()) {
DCHECK(false);
}
JSObject::MigrateSlowToFast(function, 0, "Bootstrapping");
restricted_properties_thrower_ = function;
return function;
}
void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
Factory* factory = isolate_->factory();
Handle<Map> map;
//
// Allocate maps for strict functions without prototype.
//
map = factory->CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
native_context()->set_strict_function_without_prototype_map(*map);
map = factory->CreateStrictFunctionMap(METHOD_WITH_NAME, empty);
native_context()->set_method_with_name_map(*map);
//
// Allocate maps for strict functions with writable prototype.
//
map = factory->CreateStrictFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE,
empty);
native_context()->set_strict_function_map(*map);
map = factory->CreateStrictFunctionMap(
FUNCTION_WITH_NAME_AND_WRITEABLE_PROTOTYPE, empty);
native_context()->set_strict_function_with_name_map(*map);
//
// Allocate maps for strict functions with readonly prototype.
//
map =
factory->CreateStrictFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
native_context()->set_strict_function_with_readonly_prototype_map(*map);
//
// Allocate map for class functions.
//
map = factory->CreateClassFunctionMap(empty);
native_context()->set_class_function_map(*map);
// Now that the strict mode function map is available, set up the
// restricted "arguments" and "caller" getters.
AddRestrictedFunctionProperties(empty);
}
void Genesis::CreateObjectFunction(Handle<JSFunction> empty_function) {
Factory* factory = isolate_->factory();
// --- O b j e c t ---
int inobject_properties = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
int instance_size = JSObject::kHeaderSize + kTaggedSize * inobject_properties;
Handle<JSFunction> object_fun = CreateFunction(
isolate_, factory->Object_string(), JS_OBJECT_TYPE, instance_size,
inobject_properties, factory->null_value(), Builtin::kObjectConstructor);
object_fun->shared().set_length(1);
object_fun->shared().DontAdaptArguments();
native_context()->set_object_function(*object_fun);
{
// Finish setting up Object function's initial map.
Map initial_map = object_fun->initial_map();
initial_map.set_elements_kind(HOLEY_ELEMENTS);
}
// Allocate a new prototype for the object function.
Handle<JSObject> object_function_prototype =
factory->NewFunctionPrototype(object_fun);
{
Handle<Map> map = Map::Copy(
isolate(), handle(object_function_prototype->map(), isolate()),
"EmptyObjectPrototype");
map->set_is_prototype_map(true);
// Ban re-setting Object.prototype.__proto__ to prevent Proxy security bug
map->set_is_immutable_proto(true);
object_function_prototype->set_map(*map);
}
// Complete setting up empty function.
{
Handle<Map> empty_function_map(empty_function->map(), isolate_);
Map::SetPrototype(isolate(), empty_function_map, object_function_prototype);
}
native_context()->set_initial_object_prototype(*object_function_prototype);
JSFunction::SetPrototype(object_fun, object_function_prototype);
object_function_prototype->map().set_instance_type(JS_OBJECT_PROTOTYPE_TYPE);
{
// Set up slow map for Object.create(null) instances without in-object
// properties.
Handle<Map> map(object_fun->initial_map(), isolate_);
map = Map::CopyInitialMapNormalized(isolate(), map);
Map::SetPrototype(isolate(), map, factory->null_value());
native_context()->set_slow_object_with_null_prototype_map(*map);
// Set up slow map for literals with too many properties.
map = Map::Copy(isolate(), map, "slow_object_with_object_prototype_map");
Map::SetPrototype(isolate(), map, object_function_prototype);
native_context()->set_slow_object_with_object_prototype_map(*map);
}
}
namespace {
Handle<Map> CreateNonConstructorMap(Isolate* isolate, Handle<Map> source_map,
Handle<JSObject> prototype,
const char* reason) {
Handle<Map> map = Map::Copy(isolate, source_map, reason);
// Ensure the resulting map has prototype slot (it is necessary for storing
// inital map even when the prototype property is not required).
if (!map->has_prototype_slot()) {
// Re-set the unused property fields after changing the instance size.
int unused_property_fields = map->UnusedPropertyFields();
map->set_instance_size(map->instance_size() + kTaggedSize);
// The prototype slot shifts the in-object properties area by one slot.
map->SetInObjectPropertiesStartInWords(
map->GetInObjectPropertiesStartInWords() + 1);
map->set_has_prototype_slot(true);
map->SetInObjectUnusedPropertyFields(unused_property_fields);
}
map->set_is_constructor(false);
Map::SetPrototype(isolate, map, prototype);
return map;
}
} // namespace
void Genesis::CreateIteratorMaps(Handle<JSFunction> empty) {
// Create iterator-related meta-objects.
Handle<JSObject> iterator_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
InstallFunctionAtSymbol(isolate(), iterator_prototype,
factory()->iterator_symbol(), "[Symbol.iterator]",
Builtin::kReturnReceiver, 0, true);
native_context()->set_initial_iterator_prototype(*iterator_prototype);
CHECK_NE(iterator_prototype->map().ptr(),
isolate_->initial_object_prototype()->map().ptr());
iterator_prototype->map().set_instance_type(JS_ITERATOR_PROTOTYPE_TYPE);
Handle<JSObject> generator_object_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
native_context()->set_initial_generator_prototype(
*generator_object_prototype);
JSObject::ForceSetPrototype(isolate(), generator_object_prototype,
iterator_prototype);
Handle<JSObject> generator_function_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
JSObject::ForceSetPrototype(isolate(), generator_function_prototype, empty);
InstallToStringTag(isolate(), generator_function_prototype,
"GeneratorFunction");
JSObject::AddProperty(isolate(), generator_function_prototype,
factory()->prototype_string(),
generator_object_prototype,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
JSObject::AddProperty(isolate(), generator_object_prototype,
factory()->constructor_string(),
generator_function_prototype,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
InstallToStringTag(isolate(), generator_object_prototype, "Generator");
SimpleInstallFunction(isolate(), generator_object_prototype, "next",
Builtin::kGeneratorPrototypeNext, 1, false);
SimpleInstallFunction(isolate(), generator_object_prototype, "return",
Builtin::kGeneratorPrototypeReturn, 1, false);
SimpleInstallFunction(isolate(), generator_object_prototype, "throw",
Builtin::kGeneratorPrototypeThrow, 1, false);
// Internal version of generator_prototype_next, flagged as non-native such
// that it doesn't show up in Error traces.
Handle<JSFunction> generator_next_internal =
SimpleCreateFunction(isolate(), factory()->next_string(),
Builtin::kGeneratorPrototypeNext, 1, false);
generator_next_internal->shared().set_native(false);
native_context()->set_generator_next_internal(*generator_next_internal);
// Internal version of async module functions, flagged as non-native such
// that they don't show up in Error traces.
{
Handle<JSFunction> async_module_evaluate_internal =
SimpleCreateFunction(isolate(), factory()->next_string(),
Builtin::kAsyncModuleEvaluate, 1, false);
async_module_evaluate_internal->shared().set_native(false);
native_context()->set_async_module_evaluate_internal(
*async_module_evaluate_internal);
Handle<JSFunction> call_async_module_fulfilled =
SimpleCreateFunction(isolate(), factory()->empty_string(),
Builtin::kCallAsyncModuleFulfilled, 1, false);
call_async_module_fulfilled->shared().set_native(false);
native_context()->set_call_async_module_fulfilled(
*call_async_module_fulfilled);
Handle<JSFunction> call_async_module_rejected =
SimpleCreateFunction(isolate(), factory()->empty_string(),
Builtin::kCallAsyncModuleRejected, 1, false);
call_async_module_rejected->shared().set_native(false);
native_context()->set_call_async_module_rejected(
*call_async_module_rejected);
}
// Create maps for generator functions and their prototypes. Store those
// maps in the native context. The "prototype" property descriptor is
// writable, non-enumerable, and non-configurable (as per ES6 draft
// 04-14-15, section 25.2.4.3).
// Generator functions do not have "caller" or "arguments" accessors.
Handle<Map> map;
map = CreateNonConstructorMap(isolate(), isolate()->strict_function_map(),
generator_function_prototype,
"GeneratorFunction");
native_context()->set_generator_function_map(*map);
map = CreateNonConstructorMap(
isolate(), isolate()->strict_function_with_name_map(),
generator_function_prototype, "GeneratorFunction with name");
native_context()->set_generator_function_with_name_map(*map);
Handle<JSFunction> object_function(native_context()->object_function(),
isolate());
Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
Map::SetPrototype(isolate(), generator_object_prototype_map,
generator_object_prototype);
native_context()->set_generator_object_prototype_map(
*generator_object_prototype_map);
}
void Genesis::CreateAsyncIteratorMaps(Handle<JSFunction> empty) {
// %AsyncIteratorPrototype%
// proposal-async-iteration/#sec-asynciteratorprototype
Handle<JSObject> async_iterator_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
InstallFunctionAtSymbol(
isolate(), async_iterator_prototype, factory()->async_iterator_symbol(),
"[Symbol.asyncIterator]", Builtin::kReturnReceiver, 0, true);
native_context()->set_initial_async_iterator_prototype(
*async_iterator_prototype);
// %AsyncFromSyncIteratorPrototype%
// proposal-async-iteration/#sec-%asyncfromsynciteratorprototype%-object
Handle<JSObject> async_from_sync_iterator_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
SimpleInstallFunction(isolate(), async_from_sync_iterator_prototype, "next",
Builtin::kAsyncFromSyncIteratorPrototypeNext, 1, false);
SimpleInstallFunction(isolate(), async_from_sync_iterator_prototype, "return",
Builtin::kAsyncFromSyncIteratorPrototypeReturn, 1,
false);
SimpleInstallFunction(isolate(), async_from_sync_iterator_prototype, "throw",
Builtin::kAsyncFromSyncIteratorPrototypeThrow, 1,
false);
InstallToStringTag(isolate(), async_from_sync_iterator_prototype,
"Async-from-Sync Iterator");
JSObject::ForceSetPrototype(isolate(), async_from_sync_iterator_prototype,
async_iterator_prototype);
Handle<Map> async_from_sync_iterator_map = factory()->NewMap(
JS_ASYNC_FROM_SYNC_ITERATOR_TYPE, JSAsyncFromSyncIterator::kHeaderSize);
Map::SetPrototype(isolate(), async_from_sync_iterator_map,
async_from_sync_iterator_prototype);
native_context()->set_async_from_sync_iterator_map(
*async_from_sync_iterator_map);
// Async Generators
Handle<JSObject> async_generator_object_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
Handle<JSObject> async_generator_function_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
// %AsyncGenerator% / %AsyncGeneratorFunction%.prototype
JSObject::ForceSetPrototype(isolate(), async_generator_function_prototype,
empty);
// The value of AsyncGeneratorFunction.prototype.prototype is the
// %AsyncGeneratorPrototype% intrinsic object.
// This property has the attributes
// { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
JSObject::AddProperty(isolate(), async_generator_function_prototype,
factory()->prototype_string(),
async_generator_object_prototype,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
JSObject::AddProperty(isolate(), async_generator_object_prototype,
factory()->constructor_string(),
async_generator_function_prototype,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
InstallToStringTag(isolate(), async_generator_function_prototype,
"AsyncGeneratorFunction");
// %AsyncGeneratorPrototype%
JSObject::ForceSetPrototype(isolate(), async_generator_object_prototype,
async_iterator_prototype);
native_context()->set_initial_async_generator_prototype(
*async_generator_object_prototype);
InstallToStringTag(isolate(), async_generator_object_prototype,
"AsyncGenerator");
SimpleInstallFunction(isolate(), async_generator_object_prototype, "next",
Builtin::kAsyncGeneratorPrototypeNext, 1, false);
SimpleInstallFunction(isolate(), async_generator_object_prototype, "return",
Builtin::kAsyncGeneratorPrototypeReturn, 1, false);
SimpleInstallFunction(isolate(), async_generator_object_prototype, "throw",
Builtin::kAsyncGeneratorPrototypeThrow, 1, false);
// Create maps for generator functions and their prototypes. Store those
// maps in the native context. The "prototype" property descriptor is
// writable, non-enumerable, and non-configurable (as per ES6 draft
// 04-14-15, section 25.2.4.3).
// Async Generator functions do not have "caller" or "arguments" accessors.
Handle<Map> map;
map = CreateNonConstructorMap(isolate(), isolate()->strict_function_map(),
async_generator_function_prototype,
"AsyncGeneratorFunction");
native_context()->set_async_generator_function_map(*map);
map = CreateNonConstructorMap(
isolate(), isolate()->strict_function_with_name_map(),
async_generator_function_prototype, "AsyncGeneratorFunction with name");
native_context()->set_async_generator_function_with_name_map(*map);
Handle<JSFunction> object_function(native_context()->object_function(),
isolate());
Handle<Map> async_generator_object_prototype_map = Map::Create(isolate(), 0);
Map::SetPrototype(isolate(), async_generator_object_prototype_map,
async_generator_object_prototype);
native_context()->set_async_generator_object_prototype_map(
*async_generator_object_prototype_map);
}
void Genesis::CreateAsyncFunctionMaps(Handle<JSFunction> empty) {
// %AsyncFunctionPrototype% intrinsic
Handle<JSObject> async_function_prototype = factory()->NewJSObject(
isolate()->object_function(), AllocationType::kOld);
JSObject::ForceSetPrototype(isolate(), async_function_prototype, empty);
InstallToStringTag(isolate(), async_function_prototype, "AsyncFunction");
Handle<Map> map =
Map::Copy(isolate(), isolate()->strict_function_without_prototype_map(),
"AsyncFunction");
Map::SetPrototype(isolate(), map, async_function_prototype);
native_context()->set_async_function_map(*map);
map = Map::Copy(isolate(), isolate()->method_with_name_map(),
"AsyncFunction with name");
Map::SetPrototype(isolate(), map, async_function_prototype);
native_context()->set_async_function_with_name_map(*map);
}
void Genesis::CreateJSProxyMaps() {
// Allocate maps for all Proxy types.
// Next to the default proxy, we need maps indicating callable and
// constructable proxies.
Handle<Map> proxy_map = factory()->NewMap(JS_PROXY_TYPE, JSProxy::kSize,
TERMINAL_FAST_ELEMENTS_KIND);
proxy_map->set_is_dictionary_map(true);
proxy_map->set_may_have_interesting_symbols(true);
native_context()->set_proxy_map(*proxy_map);
Handle<Map> proxy_callable_map =
Map::Copy(isolate_, proxy_map, "callable Proxy");
proxy_callable_map->set_is_callable(true);
native_context()->set_proxy_callable_map(*proxy_callable_map);
proxy_callable_map->SetConstructor(native_context()->function_function());
Handle<Map> proxy_constructor_map =
Map::Copy(isolate_, proxy_callable_map, "constructor Proxy");
proxy_constructor_map->set_is_constructor(true);
native_context()->set_proxy_constructor_map(*proxy_constructor_map);
{
Handle<Map> map =
factory()->NewMap(JS_OBJECT_TYPE, JSProxyRevocableResult::kSize,
TERMINAL_FAST_ELEMENTS_KIND, 2);
Map::EnsureDescriptorSlack(isolate_, map, 2);
{ // proxy
Descriptor d = Descriptor::DataField(isolate(), factory()->proxy_string(),
JSProxyRevocableResult::kProxyIndex,
NONE, Representation::Tagged());
map->AppendDescriptor(isolate(), &d);
}
{ // revoke
Descriptor d = Descriptor::DataField(
isolate(), factory()->revoke_string(),
JSProxyRevocableResult::kRevokeIndex, NONE, Representation::Tagged());
map->AppendDescriptor(isolate(), &d);
}
Map::SetPrototype(isolate(), map, isolate()->initial_object_prototype());
map->SetConstructor(native_context()->object_function());
native_context()->set_proxy_revocable_result_map(*map);
}
}
namespace {
void ReplaceAccessors(Isolate* isolate, Handle<Map> map, Handle<String> name,
PropertyAttributes attributes,
Handle<AccessorPair> accessor_pair) {
DescriptorArray descriptors = map->instance_descriptors(isolate);
InternalIndex entry = descriptors.SearchWithCache(isolate, *name, *map);
Descriptor d = Descriptor::AccessorConstant(name, accessor_pair, attributes);
descriptors.Replace(entry, &d);
}
} // namespace
void Genesis::AddRestrictedFunctionProperties(Handle<JSFunction> empty) {
PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
Handle<JSFunction> thrower = GetThrowTypeErrorIntrinsic();
Handle<AccessorPair> accessors = factory()->NewAccessorPair();
accessors->set_getter(*thrower);
accessors->set_setter(*thrower);
Handle<Map> map(empty->map(), isolate());
ReplaceAccessors(isolate(), map, factory()->arguments_string(), rw_attribs,
accessors);
ReplaceAccessors(isolate(), map, factory()->caller_string(), rw_attribs,
accessors);
}
static void AddToWeakNativeContextList(Isolate* isolate, Context context) {
DCHECK(context.IsNativeContext());
Heap* heap = isolate->heap();
#ifdef DEBUG
{
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(isolate(), *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(), isolate());
Handle<ScopeInfo> scope_info =
ReadOnlyRoots(isolate()).global_this_binding_scope_info_handle();
Handle<Context> context =
factory()->NewScriptContext(native_context(), 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(isolate(), 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()), isolate());
Handle<Object> proto_template(global_constructor->GetPrototypeTemplate(),
isolate());
if (!proto_template->IsUndefined(isolate())) {
js_global_object_template =
Handle<ObjectTemplateInfo>::cast(proto_template);
}
}
if (js_global_object_template.is_null()) {
Handle<String> name = factory()->empty_string();
Handle<JSObject> prototype =
factory()->NewFunctionPrototype(isolate()->object_function());
js_global_object_function = CreateFunctionForBuiltinWithPrototype(
isolate(), name, Builtin::kIllegal, prototype, JS_GLOBAL_OBJECT_TYPE,
JSGlobalObject::kHeaderSize, 0, MUTABLE);
#ifdef DEBUG
LookupIterator it(isolate(), 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()),
isolate());
js_global_object_function = ApiNatives::CreateApiFunction(
isolate(), isolate()->native_context(), js_global_object_constructor,
factory()->the_hole_value(), JS_GLOBAL_OBJECT_TYPE);
}
js_global_object_function->initial_map().set_is_prototype_map(true);
js_global_object_function->initial_map().set_is_dictionary_map(true);
js_global_object_function->initial_map().set_may_have_interesting_symbols(
true);
Handle<JSGlobalObject> global_object =
factory()->NewJSGlobalObject(js_global_object_function);
// Step 2: (re)initialize the global proxy object.
Handle<JSFunction> global_proxy_function;
if (global_proxy_template.IsEmpty()) {
Handle<String> name = factory()->empty_string();
global_proxy_function = CreateFunctionForBuiltinWithPrototype(
isolate(), name, Builtin::kIllegal, factory()->the_hole_value(),
JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::SizeWithEmbedderFields(0), 0,
MUTABLE);
} else {
Handle<ObjectTemplateInfo> data =
v8::Utils::OpenHandle(*global_proxy_template);
Handle<FunctionTemplateInfo> global_constructor(
FunctionTemplateInfo::cast(data->constructor()), isolate());
global_proxy_function = ApiNatives::CreateApiFunction(
isolate(), isolate()->native_context(), global_constructor,
factory()->the_hole_value(), JS_GLOBAL_PROXY_TYPE);
}
global_proxy_function->initial_map().set_is_access_check_needed(true);
global_proxy_function->initial_map().set_may_have_interesting_symbols(true);
native_context()->set_global_proxy_function(*global_proxy_function);
// Set the global object as the (hidden) __proto__ of the global proxy after
// ConfigureGlobalObject
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_object() == *global_proxy);
native_context()->set_global_proxy_object(*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(), isolate());
factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
Handle<JSObject> global_object(
JSObject::cast(native_context()->global_object()), isolate());
JSObject::ForceSetPrototype(isolate(), 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()), isolate());
native_context()->set_extension(*global_object);
native_context()->set_security_token(*global_object);
TransferNamedProperties(global_object_from_snapshot, global_object);
if (global_object_from_snapshot->HasDictionaryElements()) {
JSObject::NormalizeElements(global_object);
}
DCHECK_EQ(global_object_from_snapshot->GetElementsKind(),
global_object->GetElementsKind());
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(isolate, function,
isolate->factory()->native_context_index_symbol(),
index, NONE);
isolate->native_context()->set(context_index, *function, UPDATE_WRITE_BARRIER,
kReleaseStore);
}
static void InstallError(Isolate* isolate, Handle<JSObject> global,
Handle<String> name, int context_index,
Builtin error_constructor = Builtin::kErrorConstructor,
int error_function_length = 1,
int in_object_properties = 2) {
Factory* factory = isolate->factory();
if (FLAG_harmony_error_cause) {
in_object_properties += 1;
}
// Most Error objects consist of a message and a stack trace.
// Reserve two in-object properties for these.
const int kErrorObjectSize =
JSObject::kHeaderSize + in_object_properties * kTaggedSize;
Handle<JSFunction> error_fun = InstallFunction(
isolate, global, name, JS_ERROR_TYPE, kErrorObjectSize,
in_object_properties, factory->the_hole_value(), error_constructor);
error_fun->shared().DontAdaptArguments();
error_fun->shared().set_length(error_function_length);
if (context_index == Context::ERROR_FUNCTION_INDEX) {
SimpleInstallFunction(isolate, error_fun, "captureStackTrace",
Builtin::kErrorCaptureStackTrace, 2, false);
}
InstallWithIntrinsicDefaultProto(isolate, error_fun, context_index);
{
// Setup %XXXErrorPrototype%.
Handle<JSObject> prototype(JSObject::cast(error_fun->instance_prototype()),
isolate);
JSObject::AddProperty(isolate, prototype, factory->name_string(), name,
DONT_ENUM);
JSObject::AddProperty(isolate, prototype, factory->message_string(),
factory->empty_string(), DONT_ENUM);
if (context_index == Context::ERROR_FUNCTION_INDEX) {
Handle<JSFunction> to_string_fun =
SimpleInstallFunction(isolate, prototype, "toString",
Builtin::kErrorPrototypeToString, 0, true);
isolate->native_context()->set_error_to_string(*to_string_fun);
isolate->native_context()->set_initial_error_prototype(*prototype);
} else {
Handle<JSFunction> global_error = isolate->error_function();
CHECK(JSReceiver::SetPrototype(isolate, error_fun, global_error, false,
kThrowOnError)
.FromMaybe(false));
CHECK(JSReceiver::SetPrototype(isolate, prototype,
handle(global_error->prototype(), isolate),
false, kThrowOnError)
.FromMaybe(false));
}
}
Handle<Map> initial_map(error_fun->initial_map(), isolate);
Map::EnsureDescriptorSlack(isolate, initial_map, 1);
{
Handle<AccessorInfo> info = factory->error_stack_accessor();
Descriptor d = Descriptor::AccessorConstant(handle(info->name(), isolate),
info, DONT_ENUM);
initial_map->AppendDescriptor(isolate, &d);
}
}
// 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) {
// --- N a t i v e C o n t e x t ---
// 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);
Factory* factory = isolate_->factory();
{ // -- C o n t e x t
Handle<Map> map =
factory->NewMap(FUNCTION_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_function_context_map(*map);
map = factory->NewMap(CATCH_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_catch_context_map(*map);
map = factory->NewMap(WITH_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_with_context_map(*map);
map = factory->NewMap(DEBUG_EVALUATE_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_debug_evaluate_context_map(*map);
map = factory->NewMap(BLOCK_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_block_context_map(*map);
map = factory->NewMap(MODULE_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_module_context_map(*map);
map = factory->NewMap(AWAIT_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_await_context_map(*map);
map = factory->NewMap(SCRIPT_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_script_context_map(*map);
map = factory->NewMap(EVAL_CONTEXT_TYPE, kVariableSizeSentinel);
map->set_native_context(*native_context());
native_context()->set_eval_context_map(*map);
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(isolate_, global_object, object_name, object_function,
DONT_ENUM);
SimpleInstallFunction(isolate_, object_function, "assign",
Builtin::kObjectAssign, 2, false);
SimpleInstallFunction(isolate_, object_function, "getOwnPropertyDescriptor",
Builtin::kObjectGetOwnPropertyDescriptor, 2, false);
SimpleInstallFunction(isolate_, object_function,
"getOwnPropertyDescriptors",
Builtin::kObjectGetOwnPropertyDescriptors, 1, false);
SimpleInstallFunction(isolate_, object_function, "getOwnPropertyNames",
Builtin::kObjectGetOwnPropertyNames, 1, true);
SimpleInstallFunction(isolate_, object_function, "getOwnPropertySymbols",
Builtin::kObjectGetOwnPropertySymbols, 1, false);
SimpleInstallFunction(isolate_, object_function, "is", Builtin::kObjectIs,
2, true);
SimpleInstallFunction(isolate_, object_function, "preventExtensions",
Builtin::kObjectPreventExtensions, 1, true);
SimpleInstallFunction(isolate_, object_function, "seal",
Builtin::kObjectSeal, 1, false);
SimpleInstallFunction(isolate_, object_function, "create",
Builtin::kObjectCreate, 2, false);
SimpleInstallFunction(isolate_, object_function, "defineProperties",
Builtin::kObjectDefineProperties, 2, true);
SimpleInstallFunction(isolate_, object_function, "defineProperty",
Builtin::kObjectDefineProperty, 3, true);
SimpleInstallFunction(isolate_, object_function, "freeze",
Builtin::kObjectFreeze, 1, false);
SimpleInstallFunction(isolate_, object_function, "getPrototypeOf",
Builtin::kObjectGetPrototypeOf, 1, true);
SimpleInstallFunction(isolate_, object_function, "setPrototypeOf",
Builtin::kObjectSetPrototypeOf, 2, true);
SimpleInstallFunction(isolate_, object_function, "isExtensible",
Builtin::kObjectIsExtensible, 1, true);
SimpleInstallFunction(isolate_, object_function, "isFrozen",
Builtin::kObjectIsFrozen, 1, false);
SimpleInstallFunction(isolate_, object_function, "isSealed",
Builtin::kObjectIsSealed, 1, false);
SimpleInstallFunction(isolate_, object_function, "keys",
Builtin::kObjectKeys, 1, true);
SimpleInstallFunction(isolate_, object_function, "entries",
Builtin::kObjectEntries, 1, true);
SimpleInstallFunction(isolate_, object_function, "fromEntries",
Builtin::kObjectFromEntries, 1, false);
SimpleInstallFunction(isolate_, object_function, "values",
Builtin::kObjectValues, 1, true);
SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
"__defineGetter__", Builtin::kObjectDefineGetter, 2,
true);
SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
"__defineSetter__", Builtin::kObjectDefineSetter, 2,
true);
SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
"hasOwnProperty",
Builtin::kObjectPrototypeHasOwnProperty, 1, true);
SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
"__lookupGetter__", Builtin::kObjectLookupGetter, 1,
true);
SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
"__lookupSetter__", Builtin::kObjectLookupSetter, 1,
true);
SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
"isPrototypeOf",
Builtin::kObjectPrototypeIsPrototypeOf, 1, true);
SimpleInstallFunction(
isolate_, isolate_->initial_object_prototype(), "propertyIsEnumerable",
Builtin::kObjectPrototypePropertyIsEnumerable, 1, false);
Handle<JSFunction> object_to_string = SimpleInstallFunction(
isolate_, isolate_->initial_object_prototype(), "toString",
Builtin::kObjectPrototypeToString, 0, true);
native_context()->set_object_to_string(*object_to_string);
Handle<JSFunction> object_value_of = SimpleInstallFunction(
isolate_, isolate_->initial_object_prototype(), "valueOf",
Builtin::kObjectPrototypeValueOf, 0, true);
native_context()->set_object_value_of_function(*object_value_of);
SimpleInstallGetterSetter(
isolate_, isolate_->initial_object_prototype(), factory->proto_string(),
Builtin::kObjectPrototypeGetProto, Builtin::kObjectPrototypeSetProto);
SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
"toLocaleString",
Builtin::kObjectPrototypeToLocaleString, 0, true);
}
Handle<JSObject> global(native_context()->global_object(), isolate());
{ // --- F u n c t i o n ---
Handle<JSFunction> prototype = empty_function;
Handle<JSFunction> function_fun =
InstallFunction(isolate_, global, "Function", JS_FUNCTION_TYPE,
JSFunction::kSizeWithPrototype, 0, prototype,
Builtin::kFunctionConstructor);
// Function instances are sloppy by default.
function_fun->set_prototype_or_initial_map(*isolate_->sloppy_function_map(),
kReleaseStore);
function_fun->shared().DontAdaptArguments();
function_fun->shared().set_length(1);
InstallWithIntrinsicDefaultProto(isolate_, function_fun,
Context::FUNCTION_FUNCTION_INDEX);
native_context()->set_function_prototype(*prototype);
// Setup the methods on the %FunctionPrototype%.
JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
function_fun, DONT_ENUM);
Handle<JSFunction> function_prototype_apply =
SimpleInstallFunction(isolate_, prototype, "apply",
Builtin::kFunctionPrototypeApply, 2, false);
native_context()->set_function_prototype_apply(*function_prototype_apply);
SimpleInstallFunction(isolate_, prototype, "bind",
Builtin::kFastFunctionPrototypeBind, 1, false);
SimpleInstallFunction(isolate_, prototype, "call",
Builtin::kFunctionPrototypeCall, 1, false);
Handle<JSFunction> function_to_string =
SimpleInstallFunction(isolate_, prototype, "toString",
Builtin::kFunctionPrototypeToString, 0, false);
native_context()->set_function_to_string(*function_to_string);
// Install the @@hasInstance function.
Handle<JSFunction> has_instance = InstallFunctionAtSymbol(
isolate_, prototype, factory->has_instance_symbol(),
"[Symbol.hasInstance]", Builtin::kFunctionPrototypeHasInstance, 1, true,
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
native_context()->set_function_has_instance(*has_instance);
// Complete setting up function maps.
{
isolate_->sloppy_function_map()->SetConstructor(*function_fun);
isolate_->sloppy_function_with_name_map()->SetConstructor(*function_fun);
isolate_->sloppy_function_with_readonly_prototype_map()->SetConstructor(
*function_fun);
isolate_->strict_function_map()->SetConstructor(*function_fun);
isolate_->strict_function_with_name_map()->SetConstructor(*function_fun);
isolate_->strict_function_with_readonly_prototype_map()->SetConstructor(
*function_fun);
isolate_->class_function_map()->SetConstructor(*function_fun);
}
}
Handle<JSFunction> array_prototype_to_string_fun;
{ // --- A r r a y ---
Handle<JSFunction> array_function = InstallFunction(
isolate_, global, "Array", JS_ARRAY_TYPE, JSArray::kHeaderSize, 0,
isolate_->initial_object_prototype(), Builtin::kArrayConstructor);
array_function->shared().DontAdaptArguments();
// 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(), isolate());
// This assert protects an optimization in
// HGraphBuilder::JSArrayBuilder::EmitMapCode()
DCHECK(initial_map->elements_kind() == GetInitialFastElementsKind());
Map::EnsureDescriptorSlack(isolate_, initial_map, 1);
PropertyAttributes attribs =
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
STATIC_ASSERT(JSArray::kLengthDescriptorIndex == 0);
{ // Add length.
Descriptor d = Descriptor::AccessorConstant(
factory->length_string(), factory->array_length_accessor(), attribs);
initial_map->AppendDescriptor(isolate(), &d);
}
InstallWithIntrinsicDefaultProto(isolate_, array_function,
Context::ARRAY_FUNCTION_INDEX);
InstallSpeciesGetter(isolate_, array_function);
// Cache the array maps, needed by ArrayConstructorStub
CacheInitialJSArrayMaps(isolate_, native_context(), initial_map);
// Set up %ArrayPrototype%.
// The %ArrayPrototype% has TERMINAL_FAST_ELEMENTS_KIND in order to ensure
// that constant functions stay constant after turning prototype to setup
// mode and back.
Handle<JSArray> proto = factory->NewJSArray(0, TERMINAL_FAST_ELEMENTS_KIND,
AllocationType::kOld);
JSFunction::SetPrototype(array_function, proto);
native_context()->set_initial_array_prototype(*proto);
SimpleInstallFunction(isolate_, array_function, "isArray",
Builtin::kArrayIsArray, 1, true);
SimpleInstallFunction(isolate_, array_function, "from", Builtin::kArrayFrom,
1, false);
SimpleInstallFunction(isolate_, array_function, "of", Builtin::kArrayOf, 0,
false);
SetConstructorInstanceType(isolate_, array_function,
JS_ARRAY_CONSTRUCTOR_TYPE);
JSObject::AddProperty(isolate_, proto, factory->constructor_string(),
array_function, DONT_ENUM);
SimpleInstallFunction(isolate_, proto, "concat",
Builtin::kArrayPrototypeConcat, 1, false);
SimpleInstallFunction(isolate_, proto, "copyWithin",
Builtin::kArrayPrototypeCopyWithin, 2, false);
SimpleInstallFunction(isolate_, proto, "fill", Builtin::kArrayPrototypeFill,
1, false);
SimpleInstallFunction(isolate_, proto, "find", Builtin::kArrayPrototypeFind,
1, false);
SimpleInstallFunction(isolate_, proto, "findIndex",
Builtin::kArrayPrototypeFindIndex, 1, false);
SimpleInstallFunction(isolate_, proto, "lastIndexOf",
Builtin::kArrayPrototypeLastIndexOf, 1, false);
SimpleInstallFunction(isolate_, proto, "pop", Builtin::kArrayPrototypePop,
0, false);
SimpleInstallFunction(isolate_, proto, "push", Builtin::kArrayPrototypePush,
1, false);
SimpleInstallFunction(isolate_, proto, "reverse",
Builtin::kArrayPrototypeReverse, 0, false);
SimpleInstallFunction(isolate_, proto, "shift",
Builtin::kArrayPrototypeShift, 0, false);
SimpleInstallFunction(isolate_, proto, "unshift",
Builtin::kArrayPrototypeUnshift, 1, false);
SimpleInstallFunction(isolate_, proto, "slice",
Builtin::kArrayPrototypeSlice, 2, false);
SimpleInstallFunction(isolate_, proto, "sort", Builtin::kArrayPrototypeSort,
1, false);
SimpleInstallFunction(isolate_, proto, "splice",
Builtin::kArrayPrototypeSplice, 2, false);
SimpleInstallFunction(isolate_, proto, "includes", Builtin::kArrayIncludes,
1, false);
SimpleInstallFunction(isolate_, proto, "indexOf", Builtin::kArrayIndexOf, 1,
false);
SimpleInstallFunction(isolate_, proto, "join", Builtin::kArrayPrototypeJoin,
1, false);
{ // Set up iterator-related properties.
Handle<JSFunction> keys = InstallFunctionWithBuiltinId(
isolate_, proto, "keys", Builtin::kArrayPrototypeKeys, 0, true);
native_context()->set_array_keys_iterator(*keys);
Handle<JSFunction> entries = InstallFunctionWithBuiltinId(
isolate_, proto, "entries", Builtin::kArrayPrototypeEntries, 0, true);
native_context()->set_array_entries_iterator(*entries);
Handle<JSFunction> values = InstallFunctionWithBuiltinId(
isolate_, proto, "values", Builtin::kArrayPrototypeValues, 0, true);
JSObject::AddProperty(isolate_, proto, factory->iterator_symbol(), values,
DONT_ENUM);
native_context()->set_array_values_iterator(*values);
}
Handle<JSFunction> for_each_fun = SimpleInstallFunction(
isolate_, proto, "forEach", Builtin::kArrayForEach, 1, false);
native_context()->set_array_for_each_iterator(*for_each_fun);
SimpleInstallFunction(isolate_, proto, "filter", Builtin::kArrayFilter, 1,
false);
SimpleInstallFunction(isolate_, proto, "flat", Builtin::kArrayPrototypeFlat,
0, false);
SimpleInstallFunction(isolate_, proto, "flatMap",
Builtin::kArrayPrototypeFlatMap, 1, false);
SimpleInstallFunction(isolate_, proto, "map", Builtin::kArrayMap, 1, false);
SimpleInstallFunction(isolate_, proto, "every", Builtin::kArrayEvery, 1,
false);
SimpleInstallFunction(isolate_, proto, "some", Builtin::kArraySome, 1,
false);
SimpleInstallFunction(isolate_, proto, "reduce", Builtin::kArrayReduce, 1,
false);
SimpleInstallFunction(isolate_, proto, "reduceRight",
Builtin::kArrayReduceRight, 1, false);
SimpleInstallFunction(isolate_, proto, "toLocaleString",
Builtin::kArrayPrototypeToLocaleString, 0, false);
array_prototype_to_string_fun =
SimpleInstallFunction(isolate_, proto, "toString",
Builtin::kArrayPrototypeToString, 0, false);
Handle<JSObject> unscopables = factory->NewJSObjectWithNullProto();
InstallTrueValuedProperty(isolate_, unscopables, "copyWithin");
InstallTrueValuedProperty(isolate_, unscopables, "entries");
InstallTrueValuedProperty(isolate_, unscopables, "fill");
InstallTrueValuedProperty(isolate_, unscopables, "find");
InstallTrueValuedProperty(isolate_, unscopables, "findIndex");
InstallTrueValuedProperty(isolate_, unscopables, "flat");
InstallTrueValuedProperty(isolate_, unscopables, "flatMap");
InstallTrueValuedProperty(isolate_, unscopables, "includes");
InstallTrueValuedProperty(isolate_, unscopables, "keys");
InstallTrueValuedProperty(isolate_, unscopables, "values");
JSObject::MigrateSlowToFast(unscopables, 0, "Bootstrapping");
JSObject::AddProperty(
isolate_, proto, factory->unscopables_symbol(), unscopables,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
Handle<Map> map(proto->map(), isolate_);
Map::SetShouldBeFastPrototypeMap(map, true, isolate_);
}
{ // --- A r r a y I t e r a t o r ---
Handle<JSObject> iterator_prototype(
native_context()->initial_iterator_prototype(), isolate());
Handle<JSObject> array_iterator_prototype =
factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
JSObject::ForceSetPrototype(isolate(), array_iterator_prototype,
iterator_prototype);
CHECK_NE(array_iterator_prototype->map().ptr(),
isolate_->initial_object_prototype()->map().ptr());
array_iterator_prototype->map().set_instance_type(
JS_ARRAY_ITERATOR_PROTOTYPE_TYPE);
InstallToStringTag(isolate_, array_iterator_prototype,
factory->ArrayIterator_string());
InstallFunctionWithBuiltinId(isolate_, array_iterator_prototype, "next",
Builtin::kArrayIteratorPrototypeNext, 0, true);
Handle<JSFunction> array_iterator_function =
CreateFunction(isolate_, factory->ArrayIterator_string(),
JS_ARRAY_ITERATOR_TYPE, JSArrayIterator::kHeaderSize, 0,
array_iterator_prototype, Builtin::kIllegal);
array_iterator_function->shared().set_native(false);
native_context()->set_initial_array_iterator_map(
array_iterator_function->initial_map());
native_context()->set_initial_array_iterator_prototype(
*array_iterator_prototype);
}
{ // --- N u m b e r ---
Handle<JSFunction> number_fun = InstallFunction(
isolate_, global, "Number", JS_PRIMITIVE_WRAPPER_TYPE,
JSPrimitiveWrapper::kHeaderSize, 0,
isolate_->initial_object_prototype(), Builtin::kNumberConstructor);
number_fun->shared().DontAdaptArguments();
number_fun->shared().set_length(1);
InstallWithIntrinsicDefaultProto(isolate_, number_fun,
Context::NUMBER_FUNCTION_INDEX);
// Create the %NumberPrototype%
Handle<JSPrimitiveWrapper> prototype = Handle<JSPrimitiveWrapper>::cast(
factory->NewJSObject(number_fun, AllocationType::kOld));
prototype->set_value(Smi::zero());
JSFunction::SetPrototype(number_fun, prototype);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
number_fun, DONT_ENUM);
// Install the Number.prototype methods.
SimpleInstallFunction(isolate_, prototype, "toExponential",
Builtin::kNumberPrototypeToExponential, 1, false);
SimpleInstallFunction(isolate_, prototype, "toFixed",
Builtin::kNumberPrototypeToFixed, 1, false);
SimpleInstallFunction(isolate_, prototype, "toPrecision",
Builtin::kNumberPrototypeToPrecision, 1, false);
SimpleInstallFunction(isolate_, prototype, "toString",
Builtin::kNumberPrototypeToString, 1, false);
SimpleInstallFunction(isolate_, prototype, "valueOf",
Builtin::kNumberPrototypeValueOf, 0, true);
SimpleInstallFunction(isolate_, prototype, "toLocaleString",
Builtin::kNumberPrototypeToLocaleString, 0, false);
// Install the Number functions.
SimpleInstallFunction(isolate_, number_fun, "isFinite",
Builtin::kNumberIsFinite, 1, true);
SimpleInstallFunction(isolate_, number_fun, "isInteger",
Builtin::kNumberIsInteger, 1, true);
SimpleInstallFunction(isolate_, number_fun, "isNaN", Builtin::kNumberIsNaN,
1, true);
SimpleInstallFunction(isolate_, number_fun, "isSafeInteger",
Builtin::kNumberIsSafeInteger, 1, true);
// Install Number.parseFloat and Global.parseFloat.
Handle<JSFunction> parse_float_fun =
SimpleInstallFunction(isolate_, number_fun, "parseFloat",
Builtin::kNumberParseFloat, 1, true);
JSObject::AddProperty(isolate_, global_object, "parseFloat",
parse_float_fun, DONT_ENUM);
native_context()->set_global_parse_float_fun(*parse_float_fun);
// Install Number.parseInt and Global.parseInt.
Handle<JSFunction> parse_int_fun = SimpleInstallFunction(
isolate_, number_fun, "parseInt", Builtin::kNumberParseInt, 2, true);
JSObject::AddProperty(isolate_, global_object, "parseInt", parse_int_fun,
DONT_ENUM);
native_context()->set_global_parse_int_fun(*parse_int_fun);
// Install Number constants
const double kMaxValue = 1.7976931348623157e+308;
const double kMinValue = 5e-324;
const double kEPS = 2.220446049250313e-16;
InstallConstant(isolate_, number_fun, "MAX_VALUE",
factory->NewNumber(kMaxValue));
InstallConstant(isolate_, number_fun, "MIN_VALUE",
factory->NewNumber(kMinValue));
InstallConstant(isolate_, number_fun, "NaN", factory->nan_value());
InstallConstant(isolate_, number_fun, "NEGATIVE_INFINITY",
factory->NewNumber(-V8_INFINITY));
InstallConstant(isolate_, number_fun, "POSITIVE_INFINITY",
factory->infinity_value());
InstallConstant(isolate_, number_fun, "MAX_SAFE_INTEGER",
factory->NewNumber(kMaxSafeInteger));
InstallConstant(isolate_, number_fun, "MIN_SAFE_INTEGER",
factory->NewNumber(kMinSafeInteger));
InstallConstant(isolate_, number_fun, "EPSILON", factory->NewNumber(kEPS));
InstallConstant(isolate_, global, "Infinity", factory->infinity_value());
InstallConstant(isolate_, global, "NaN", factory->nan_value());
InstallConstant(isolate_, global, "undefined", factory->undefined_value());
}
{ // --- B o o l e a n ---
Handle<JSFunction> boolean_fun = InstallFunction(
isolate_, global, "Boolean", JS_PRIMITIVE_WRAPPER_TYPE,
JSPrimitiveWrapper::kHeaderSize, 0,
isolate_->initial_object_prototype(), Builtin::kBooleanConstructor);
boolean_fun->shared().DontAdaptArguments();
boolean_fun->shared().set_length(1);
InstallWithIntrinsicDefaultProto(isolate_, boolean_fun,
Context::BOOLEAN_FUNCTION_INDEX);
// Create the %BooleanPrototype%
Handle<JSPrimitiveWrapper> prototype = Handle<JSPrimitiveWrapper>::cast(
factory->NewJSObject(boolean_fun, AllocationType::kOld));
prototype->set_value(ReadOnlyRoots(isolate_).false_value());
JSFunction::SetPrototype(boolean_fun, prototype);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
boolean_fun, DONT_ENUM);
// Install the Boolean.prototype methods.
SimpleInstallFunction(isolate_, prototype, "toString",
Builtin::kBooleanPrototypeToString, 0, true);
SimpleInstallFunction(isolate_, prototype, "valueOf",
Builtin::kBooleanPrototypeValueOf, 0, true);
}
{ // --- S t r i n g ---
Handle<JSFunction> string_fun = InstallFunction(
isolate_, global, "String", JS_PRIMITIVE_WRAPPER_TYPE,
JSPrimitiveWrapper::kHeaderSize, 0,
isolate_->initial_object_prototype(), Builtin::kStringConstructor);
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(), isolate());
string_map->set_elements_kind(FAST_STRING_WRAPPER_ELEMENTS);
Map::EnsureDescriptorSlack(isolate_, string_map, 1);
PropertyAttributes attribs =
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
{ // Add length.
Descriptor d = Descriptor::AccessorConstant(
factory->length_string(), factory->string_length_accessor(), attribs);
string_map->AppendDescriptor(isolate(), &d);
}
// Install the String.fromCharCode function.
SimpleInstallFunction(isolate_, string_fun, "fromCharCode",
Builtin::kStringFromCharCode, 1, false);
// Install the String.fromCodePoint function.
SimpleInstallFunction(isolate_, string_fun, "fromCodePoint",
Builtin::kStringFromCodePoint, 1, false);
// Install the String.raw function.
SimpleInstallFunction(isolate_, string_fun, "raw", Builtin::kStringRaw, 1,
false);
// Create the %StringPrototype%
Handle<JSPrimitiveWrapper> prototype = Handle<JSPrimitiveWrapper>::cast(
factory->NewJSObject(string_fun, AllocationType::kOld));
prototype->set_value(ReadOnlyRoots(isolate_).empty_string());
JSFunction::SetPrototype(string_fun, prototype);
native_context()->set_initial_string_prototype(*prototype);
// Install the "constructor" property on the {prototype}.
JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
string_fun, DONT_ENUM);
// Install the String.prototype methods.
SimpleInstallFunction(isolate_, prototype, "anchor",
Builtin::kStringPrototypeAnchor, 1, false);
SimpleInstallFunction(isolate_, prototype, "big",
Builtin::kStringPrototypeBig, 0, false);
SimpleInstallFunction(isolate_, prototype, "blink",
Builtin::kStringPrototypeBlink, 0, false);
SimpleInstallFunction(isolate_, prototype, "bold",
Builtin::kStringPrototypeBold, 0, false);
SimpleInstallFunction(isolate_, prototype, "charAt",
Builtin::kStringPrototypeCharAt, 1, true);
SimpleInstallFunction(isolate_, prototype, "charCodeAt",
Builtin::kStringPrototypeCharCodeAt, 1, true);
SimpleInstallFunction(isolate_, prototype, "codePointAt",
Builtin::kStringPrototypeCodePointAt, 1, true);
SimpleInstallFunction(isolate_, prototype, "concat",
Builtin::kStringPrototypeConcat, 1, false);
SimpleInstallFunction(isolate_, prototype, "endsWith",
Builtin::kStringPrototypeEndsWith, 1, false);
SimpleInstallFunction(isolate_, prototype, "fontcolor",
Builtin::kStringPrototypeFontcolor, 1, false);
SimpleInstallFunction(isolate_, prototype, "fontsize",
Builtin::kStringPrototypeFontsize, 1, false);
SimpleInstallFunction(isolate_, prototype, "fixed",
Builtin::kStringPrototypeFixed, 0, false);
SimpleInstallFunction(isolate_, prototype, "includes",
Builtin::kStringPrototypeIncludes, 1, false);
SimpleInstallFunction(isolate_, prototype, "indexOf",
Builtin::kStringPrototypeIndexOf, 1, false);
SimpleInstallFunction(isolate_, prototype, "italics",
Builtin::kStringPrototypeItalics, 0, false);
SimpleInstallFunction(isolate_, prototype, "lastIndexOf",
Builtin::kStringPrototypeLastIndexOf, 1, false);
SimpleInstallFunction(isolate_, prototype, "link",
Builtin::kStringPrototypeLink, 1, false);
#ifdef V8_INTL_SUPPORT
SimpleInstallFunction(isolate_, prototype, "localeCompare",
Builtin::kStringPrototypeLocaleCompare, 1, false);
#else
SimpleInstallFunction(isolate_, prototype, "localeCompare",
Builtin::kStringPrototypeLocaleCompare, 1, true);
#endif // V8_INTL_SUPPORT
SimpleInstallFunction(isolate_, prototype, "match",
Builtin::kStringPrototypeMatch, 1, true);
SimpleInstallFunction(isolate_, prototype, "matchAll",
Builtin::kStringPrototypeMatchAll, 1, true);
#ifdef V8_INTL_SUPPORT
SimpleInstallFunction(isolate_, prototype, "normalize",
Builtin::kStringPrototypeNormalizeIntl, 0, false);
#else
SimpleInstallFunction(isolate_, prototype, "normalize",
Builtin::kStringPrototypeNormalize, 0, false);
#endif // V8_INTL_SUPPORT
SimpleInstallFunction(isolate_, prototype, "padEnd",
Builtin::kStringPrototypePadEnd, 1, false);
SimpleInstallFunction(isolate_, prototype, "padStart",
Builtin::kStringPrototypePadStart, 1, false);
SimpleInstallFunction(isolate_, prototype, "repeat",
Builtin::kStringPrototypeRepeat, 1, true);
SimpleInstallFunction(isolate_, prototype, "replace",
Builtin::kStringPrototypeReplace, 2, true);
SimpleInstallFunction(isolate(), prototype, "replaceAll",
Builtin::kStringPrototypeReplaceAll, 2, true);
SimpleInstallFunction(isolate_, prototype, "search",
Builtin::kStringPrototypeSearch, 1, true);
SimpleInstallFunction(isolate_, prototype, "slice",
Builtin::kStringPrototypeSlice, 2, false);
SimpleInstallFunction(isolate_, prototype, "small",
Builtin::kStringPrototypeSmall, 0, false);
SimpleInstallFunction(isolate_, prototype, "split",
Builtin::kStringPrototypeSplit, 2, false);
SimpleInstallFunction(isolate_, prototype, "strike",
Builtin::kStringPrototypeStrike, 0, false);
SimpleInstallFunction(isolate_, prototype, "sub",
Builtin::kStringPrototypeSub, 0, false);
SimpleInstallFunction(isolate_, prototype, "substr",
Builtin::kStringPrototypeSubstr, 2, false);
SimpleInstallFunction(isolate_, prototype, "substring",
Builtin::kStringPrototypeSubstring, 2, false);
SimpleInstallFunction(isolate_, prototype, "sup",
Builtin::kStringPrototypeSup, 0, false);
SimpleInstallFunction(isolate_, prototype, "startsWith",
Builtin::kStringPrototypeStartsWith, 1, false);
SimpleInstallFunction(isolate_, prototype, "toString",
Builtin::kStringPrototypeToString, 0, true);
SimpleInstallFunction(isolate_, prototype, "trim",
Builtin::kStringPrototypeTrim, 0, false);
// Install `String.prototype.trimStart` with `trimLeft` alias.
Handle<JSFunction> trim_start_fun =
SimpleInstallFunction(isolate_, prototype, "trimStart",
Builtin::kStringPrototypeTrimStart, 0, false);
JSObject::AddProperty(isolate_, prototype, "trimLeft", trim_start_fun,
DONT_ENUM);
// Install `String.prototype.trimEnd` with `trimRight` alias.
Handle<JSFunction> trim_end_fun =
SimpleInstallFunction(isolate_, prototype, "trimEnd",
Builtin::kStringPrototypeTrimEnd, 0, false);
JSObject::AddProperty(isolate_, prototype, "trimRight", trim_end_fun,
DONT_ENUM);
SimpleInstallFunction(isolate_, prototype, "toLocaleLowerCase",
Builtin::kStringPrototypeToLocaleLowerCase, 0, false);
SimpleInstallFunction(isolate_, prototype, "toLocaleUpperCase",
Builtin::kStringPrototypeToLocaleUpperCase, 0, false);
#ifdef V8_INTL_SUPPORT
SimpleInstallFunction(isolate_, prototype, "toLowerCase",
Builtin::kStringPrototypeToLowerCaseIntl, 0, true);
SimpleInstallFunction(isolate_, prototype, "toUpperCase",
Builtin::kStringPrototypeToUpperCaseIntl, 0, false);
#else
SimpleInstallFunction(isolate_, prototype, "toLowerCase",
Builtin::kStringPrototypeToLowerCase, 0, false);
SimpleInstallFunction(isolate_, prototype, "toUpperCase",
Builtin::kStringPrototypeToUpperCase, 0, false);
#endif
SimpleInstallFunction(isolate_, prototype, "valueOf",
Builtin::kStringPrototypeValueOf, 0, true);
InstallFunctionAtSymbol(
isolate_, prototype, factory->iterator_symbol(), "[Symbol.iterator]",
Builtin::kStringPrototypeIterator, 0, true, 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(), isolate());
Handle<JSObject> string_iterator_prototype =
factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
JSObject::ForceSetPrototype(isolate(), string_iterator_prototype,
iterator_prototype);
CHECK_NE(string_iterator_prototype->map().ptr(),
isolate_->initial_object_prototype()->map().ptr());
string_iterator_prototype->map().set_instance_type(
JS_STRING_ITERATOR_PROTOTYPE_TYPE);
InstallToStringTag(isolate_, string_iterator_prototype, "String Iterator");
InstallFunctionWithBuiltinId(isolate_, string_iterator_prototype, "next",
Builtin::kStringIteratorPrototypeNext, 0,
true);
Handle<JSFunction> string_iterator_function = CreateFunction(
isolate_, factory->InternalizeUtf8String("StringIterator"),
JS_STRING_ITERATOR_TYPE, JSStringIterator::kHeaderSize, 0,
string_iterator_prototype, Builtin::kIllegal);
string_iterator_function->shared().set_native(false);
native_context()->set_initial_string_iterator_map(
string_iterator_function->initial_map());
native_context()->set_initial_string_iterator_prototype(
*string_iterator_prototype);
}
{ // --- S y m b o l ---
Handle<JSFunction> symbol_fun =
InstallFunction(isolate_, global, "Symbol", JS_PRIMITIVE_WRAPPER_TYPE,
JSPrimitiveWrapper::kHeaderSize, 0,
factory->the_hole_value(), Builtin::kSymbolConstructor);
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(isolate_, symbol_fun, "for", Builtin::kSymbolFor, 1,
false);
SimpleInstallFunction(isolate_, symbol_fun, "keyFor",
Builtin::kSymbolKeyFor, 1, false);
// Install well-known symbols.
InstallConstant(isolate_, symbol_fun, "asyncIterator",
factory->async_iterator_symbol());
InstallConstant(isolate_, symbol_fun, "hasInstance",
factory->has_instance_symbol());
InstallConstant(isolate_, symbol_fun, "isConcatSpreadable",
factory->is_concat_spreadable_symbol());
InstallConstant(isolate_, symbol_fun, "iterator",
factory->iterator_symbol());
InstallConstant(isolate_, symbol_fun, "match", factory->match_symbol());
InstallConstant(isolate_, symbol_fun, "matchAll",
factory->match_all_symbol());
InstallConstant(isolate_, symbol_fun, "replace", factory->replace_symbol());
InstallConstant(isolate_, symbol_fun, "search", factory->search_symbol());
InstallConstant(isolate_, symbol_fun, "species", factory->species_symbol());
InstallConstant(isolate_, symbol_fun, "split", factory->split_symbol());
InstallConstant(isolate_, symbol_fun, "toPrimitive",
factory->to_primitive_symbol());
InstallConstant(isolate_, symbol_fun, "toStringTag",
factory->to_string_tag_symbol());
InstallConstant(isolate_, symbol_fun, "unscopables",
factory->unscopables_symbol());
// Setup %SymbolPrototype%.
Handle<JSObject> prototype(JSObject::cast(symbol_fun->instance_prototype()),
isolate());
InstallToStringTag(isolate_, prototype, "Symbol");
// Install the Symbol.prototype methods.
InstallFunctionWithBuiltinId(isolate_, prototype, "toString",
Builtin::kSymbolPrototypeToString, 0, true);
InstallFunctionWithBuiltinId(isolate_, prototype, "valueOf",
Builtin::kSymbolPrototypeValueOf, 0, true);
// Install the Symbol.prototype.description getter.
SimpleInstallGetter(isolate_, prototype,
factory->InternalizeUtf8String("description"),
Builtin::kSymbolPrototypeDescriptionGetter, true);
// Install the @@toPrimitive function.
InstallFunctionAtSymbol(
isolate_, prototype, factory->to_primitive_symbol(),
"[Symbol.toPrimitive]", Builtin::kSymbolPrototypeToPrimitive, 1, true,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
}
{ // --- D a t e ---
Handle<JSFunction> date_fun = InstallFunction(
isolate_, global, "Date", JS_DATE_TYPE, JSDate::kHeaderSize, 0,
factory->the_hole_value(), Builtin::kDateConstructor);
InstallWithIntrinsicDefaultProto(isolate_, date_fun,
Context::DATE_FUNCTION_INDEX);
date_fun->shared().set_length(7);
date_fun->shared().DontAdaptArguments();
// Install the Date.now, Date.parse and Date.UTC functions.
SimpleInstallFunction(isolate_, date_fun, "now", Builtin::kDateNow, 0,
false);
SimpleInstallFunction(isolate_, date_fun, "parse", Builtin::kDateParse, 1,
false);
SimpleInstallFunction(isolate_, date_fun, "UTC", Builtin::kDateUTC, 7,
false);
// Setup %DatePrototype%.
Handle<JSObject> prototype(JSObject::cast(date_fun->instance_prototype()),
isolate());
// Install the Date.prototype methods.
SimpleInstallFunction(isolate_, prototype, "toString",
Builtin::kDatePrototypeToString, 0, false);
SimpleInstallFunction(isolate_, prototype, "toDateString",
Builtin::kDatePrototypeToDateString, 0, false);
SimpleInstallFunction(isolate_, prototype, "toTimeString",
Builtin::kDatePrototypeToTimeString, 0, false);
SimpleInstallFunction(isolate_, prototype, "toISOString",
Builtin::kDatePrototypeToISOString, 0, false);
Handle<JSFunction> to_utc_string =
SimpleInstallFunction(isolate_, prototype, "toUTCString",
Builtin::kDatePrototypeToUTCString, 0, false);
JSObject::AddProperty(isolate_, prototype, "toGMTString", to_utc_string,
DONT_ENUM);
SimpleInstallFunction(isolate_, prototype, "getDate",
Builtin::kDatePrototypeGetDate, 0, true);
SimpleInstallFunction(isolate_, prototype, "setDate",
Builtin::kDatePrototypeSetDate, 1, false);
SimpleInstallFunction(isolate_, prototype, "getDay",
Builtin::kDatePrototypeGetDay, 0, true);
SimpleInstallFunction(isolate_, prototype, "getFullYear",
Builtin::kDatePrototypeGetFullYear, 0, true);
SimpleInstallFunction(isolate_, prototype, "setFullYear",
Builtin::kDatePrototypeSetFullYear, 3, false);
SimpleInstallFunction(isolate_, prototype, "getHours",
Builtin::kDatePrototypeGetHours, 0, true);
SimpleInstallFunction(isolate_, prototype, "setHours",
Builtin::kDatePrototypeSetHours, 4, false);
SimpleInstallFunction(isolate_, prototype, "getMilliseconds",
Builtin::kDatePrototypeGetMilliseconds, 0, true);
SimpleInstallFunction(isolate_, prototype, "setMilliseconds",
Builtin::kDatePrototypeSetMilliseconds, 1, false);
SimpleInstallFunction(isolate_, prototype, "getMinutes",
Builtin::kDatePrototypeGetMinutes, 0, true);
SimpleInstallFunction(isolate_, prototype, "setMinutes",
Builtin::kDatePrototypeSetMinutes, 3, false);
SimpleInstallFunction(isolate_, prototype, "getMonth",
Builtin::kDatePrototypeGetMonth, 0, true);
SimpleInstallFunction(isolate_, prototype, "setMonth",
Builtin::kDatePrototypeSetMonth, 2, false);
SimpleInstallFunction(isolate_, prototype, "getSeconds",
Builtin::kDatePrototypeGetSeconds, 0, true);
SimpleInstallFunction(isolate_, prototype, "setSeconds",
Builtin::kDatePrototypeSetSeconds, 2, false);
SimpleInstallFunction(isolate_, prototype, "getTime",
Builtin::kDatePrototypeGetTime, 0, true);
SimpleInstallFunction(isolate_, prototype, "setTime",
Builtin::kDatePrototypeSetTime, 1, false);
SimpleInstallFunction(isolate_, prototype, "getTimezoneOffset",
Builtin::kDatePrototypeGetTimezoneOffset, 0, true);
SimpleInstallFunction(isolate_, prototype, "getUTCDate",
Builtin::kDatePrototypeGetUTCDate, 0, true);
SimpleInstallFunction(isolate_, prototype, "setUTCDate",
Builtin::kDatePrototypeSetUTCDate, 1, false);
SimpleInstallFunction(isolate_, prototype, "getUTCDay",
Builtin::kDatePrototypeGetUTCDay, 0, true);
SimpleInstallFunction(isolate_, prototype, "getUTCFullYear",
Builtin::kDatePrototypeGetUTCFullYear, 0, true);
SimpleInstallFunction(isolate_, prototype, "setUTCFullYear",
Builtin::kDatePrototypeSetUTCFullYear, 3, false);
SimpleInstallFunction(isolate_, prototype, "getUTCHours",
Builtin::kDatePrototypeGetUTCHours, 0, true);
SimpleInstallFunction(isolate_, prototype, "setUTCHours",
Builtin::kDatePrototypeSetUTCHours, 4, false);
SimpleInstallFunction(isolate_, prototype, "getUTCMilliseconds",
Builtin::kDatePrototypeGetUTCMilliseconds, 0, true);
SimpleInstallFunction(isolate_, prototype, "setUTCMilliseconds",
Builtin::kDatePrototypeSetUTCMilliseconds, 1, false);
SimpleInstallFunction(isolate_, prototype, "getUTCMinutes",
Builtin::kDatePrototypeGetUTCMinutes, 0, true);
SimpleInstallFunction(isolate_, prototype, "setUTCMinutes",
Builtin::kDatePrototypeSetUTCMinutes, 3, false);
SimpleInstallFunction(isolate_, prototype, "getUTCMonth",
Builtin::kDatePrototypeGetUTCMonth, 0, true);
SimpleInstallFunction(isolate_, prototype, "setUTCMonth",
Builtin::kDatePrototypeSetUTCMonth, 2, false);
SimpleInstallFunction(isolate_, prototype, "getUTCSeconds",
Builtin::kDatePrototypeGetUTCSeconds, 0, true);
SimpleInstallFunction(isolate_, prototype, "setUTCSeconds",
Builtin::kDatePrototypeSetUTCSeconds, 2, false);
SimpleInstallFunction(isolate_, prototype, "valueOf",
Builtin::kDatePrototypeValueOf, 0, true);
SimpleInstallFunction(isolate_, prototype, "getYear",
Builtin::kDatePrototypeGetYear, 0, true);
SimpleInstallFunction(isolate_, prototype, "setYear",
Builtin::kDatePrototypeSetYear, 1, false);
SimpleInstallFunction(isolate_, prototype, "toJSON",
Builtin::kDatePrototypeToJson, 1, false);
#ifdef V8_INTL_SUPPORT
SimpleInstallFunction(isolate_, prototype, "toLocaleString",
Builtin::kDatePrototypeToLocaleString, 0, false);
SimpleInstallFunction(isolate_, prototype, "toLocaleDateString",
Builtin::kDatePrototypeToLocaleDateString, 0, false);
SimpleInstallFunction(isolate_, prototype, "toLocaleTimeString",
Builtin::kDatePrototypeToLocaleTimeString, 0, false);
#else
// Install Intl fallback functions.
SimpleInstallFunction(isolate_, prototype, "toLocaleString",
Builtin::kDatePrototypeToString, 0, false);
SimpleInstallFunction(isolate_, prototype, "toLocaleDateString",
Builtin::kDatePrototypeToDateString, 0, false);
SimpleInstallFunction(isolate_, prototype, "toLocaleTimeString",
Builtin::kDatePrototypeToTimeString, 0, false);
#endif // V8_INTL_SUPPORT
// Install the @@toPrimitive function.
InstallFunctionAtSymbol(
isolate_, prototype, factory->to_primitive_symbol(),
"[Symbol.toPrimitive]", Builtin::kDatePrototypeToPrimitive, 1, true,
static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
}
{ // -- P r o m i s e
Handle<JSFunction> promise_fun = InstallFunction(
isolate_, global, "Promise", JS_PROMISE_TYPE,
JSPromise::kSizeWithEmbedderFields, 0, factory->the_hole_value(),
Builtin::kPromiseConstructor);
InstallWithIntrinsicDefaultProto(isolate_, promise_fun,
Context::PROMISE_FUNCTION_INDEX);
Handle<SharedFunctionInfo> shared(promise_fun->shared(), isolate_);
shared->set_internal_formal_parameter_count(JSParameterCount(1));
shared->set_length(1);
InstallSpeciesGetter(isolate_, promise_fun);
Handle<JSFunction> promise_all = InstallFunctionWithBuiltinId(
isolate_, promise_fun, "all", Builtin::kPromiseAll, 1, true);
native_context()->set_promise_all(*promise_all);
InstallFunctionWithBuiltinId(isolate_, promise_fun, "allSettled",
Builtin::kPromiseAllSettled, 1, true);
Handle<JSFunction> promise_any = InstallFunctionWithBuiltinId(
isolate_, promise_fun, "any", Builtin::kPromiseAny, 1, true);
native_context()->set_promise_any(*promise_any);
InstallFunctionWithBuiltinId(isolate_, promise_fun, "race",
Builtin::kPromiseRace, 1, true);
InstallFunctionWithBuiltinId(isolate_, promise_fun, "resolve",
Builtin::kPromiseResolveTrampoline, 1, true);
InstallFunctionWithBuiltinId(isolate_, promise_fun, "reject",
Builtin::kPromiseReject, 1, true);
SetConstructorInstanceType(isolate_, promise_fun,
JS_PROMISE_CONSTRUCTOR_TYPE);
// Setup %PromisePrototype%.
Handle<JSObject> prototype(
JSObject::cast(promise_fun->instance_prototype()), isolate());
native_context()->set_promise_prototype(*prototype);
InstallToStringTag(isolate_, prototype, factory->Promise_string());
Handle<JSFunction> promise_then = InstallFunctionWithBuiltinId(
isolate_, prototype, "then", Builtin::kPromisePrototypeThen, 2, true);
native_context()->set_promise_then(*promise_then);
InstallFunctionWithBuiltinId(isolate_, prototype, "catch",
Builtin::kPromisePrototypeCatch, 1, true);
InstallFunctionWithBuiltinId(isolate_, prototype, "finally",
Builtin::kPromisePrototypeFinally, 1, true);
DCHECK(promise_fun->HasFastProperties());
Handle<Map> prototype_map(prototype->map(), isolate());
Map::SetShouldBeFastPrototypeMap(prototype_map, true, isolate_);
CHECK_NE(prototype->map().ptr(),
isolate_->initial_object_prototype()->map().ptr());
prototype->map().set_instance_type(JS_PROMISE_PROTOTYPE_TYPE);
DCHECK(promise_fun->HasFastProperties());
}
{ // -- R e g E x p
// Builtin functions for RegExp.prototype.
Handle<JSFunction> regexp_fun = InstallFunction(
isolate_, global, "RegExp", JS_REG_EXP_TYPE,
JSRegExp::kHeaderSize + JSRegExp::kInObjectFieldCount * kTaggedSize,
JSRegExp::kInObjectFieldCount, factory->the_hole_value(),
Builtin::kRegExpConstructor);
InstallWithIntrinsicDefaultProto(isolate_, regexp_fun,
Context::REGEXP_FUNCTION_INDEX);
Handle<SharedFunctionInfo> shared(regexp_fun->shared(), isolate_);
shared->set_internal_formal_parameter_count(JSParameterCount(2));
shared->set_length(2);
{
// Setup %RegExpPrototype%.
Handle<JSObject> prototype(
JSObject::cast(regexp_fun->instance_prototype()), isolate());
native_context()->set_regexp_prototype(*prototype);
{
Handle<JSFunction> fun =
SimpleInstallFunction(isolate_, prototype, "exec",
Builtin::kRegExpPrototypeExec, 1, true);
native_context()->set_regexp_exec_function(*fun);
DCHECK_EQ(JSRegExp::kExecFunctionDescriptorIndex,
prototype->map().LastAdded().as_int());
}
SimpleInstallGetter(isolate_, prototype, factory->dotAll_string(),
Builtin::kRegExpPrototypeDotAllGetter, true);
SimpleInstallGetter(isolate_, prototype, factory->flags_string(),
Builtin::kRegExpPrototypeFlagsGetter, true);
SimpleInstallGetter(isolate_, prototype, factory->global_string(),
Builtin::kRegExpPrototypeGlobalGetter, true);
SimpleInstallGetter(isolate(), prototype, factory->hasIndices_string(),
Builtin::kRegExpPrototypeHasIndicesGetter, true);
SimpleInstallGetter(isolate_, prototype, factory->ignoreCase_string(),
Builtin::kRegExpPrototypeIgnoreCaseGetter, true);
SimpleInstallGetter(isolate_, prototype, factory->multiline_string(),
Builtin::kRegExpPrototypeMultilineGetter, true);
SimpleInstallGetter(isolate_, prototype, factory->source_string(),
Builtin::kRegExpPrototypeSourceGetter, true);
SimpleInstallGetter(isolate_, prototype, factory->sticky_string(),
Builtin::kRegExpPrototypeStickyGetter, true);
SimpleInstallGetter(isolate_, prototype, factory->unicode_string(),
Builtin::kRegExpPrototypeUnicodeGetter, true);
SimpleInstallFunction(isolate_, prototype, "compile",
Builtin::kRegExpPrototypeCompile, 2, true);
SimpleInstallFunction(isolate_, prototype, "toString",
Builtin::kRegExpPrototypeToString, 0, false);
SimpleInstallFunction(isolate_, prototype, "test",
Builtin::kRegExpPrototypeTest, 1, true);
{
Handle<JSFunction> fun = InstallFunctionAtSymbol(
isolate_, prototype, factory->match_symbol(), "[Symbol.match]",
Builtin::kRegExpPrototypeMatch, 1, true);
native_context()->set_regexp_match_function(*fun);
DCHECK_EQ(JSRegExp::kSymbolMatchFunctionDescriptorIndex,
prototype->map().LastAdded().as_int());
}
{
Handle<JSFunction> fun = InstallFunctionAtSymbol(
isolate_, prototype, factory->match_all_symbol(),
"[Symbol.matchAll]", Builtin::kRegExpPrototypeMatchAll, 1, true);
native_context()->set_regexp_match_all_function(*fun);
DCHECK_EQ(JSRegExp::kSymbolMatchAllFunctionDescriptorIndex,
prototype->map().LastAdded().as_int());
}
{
Handle<JSFunction> fun = InstallFunctionAtSymbol(
isolate_, prototype, factory->replace_symbol(), "[Symbol.replace]",
Builtin::kRegExpPrototypeReplace, 2, false);
native_context()->set_regexp_replace_function(*fun);
DCHECK_EQ(JSRegExp::kSymbolReplaceFunctionDescriptorIndex,
prototype->map().LastAdded().as_int());
}
{
Handle<JSFunction> fun = InstallFunctionAtSymbol(
isolate_, prototype, factory->search_symbol(), "[Symbol.search]",
Builtin::kRegExpPrototypeSearch, 1, true);
native_context()->set_regexp_search_function(*fun);
DCHECK_EQ(JSRegExp::kSymbolSearchFunctionDescriptorIndex,
prototype->map().LastAdded().as_int());
}
{
Handle<JSFunction> fun = InstallFunctionAtSymbol(
isolate_, prototype, factory->split_symbol(), "[Symbol.split]",
Builtin::kRegExpPrototypeSplit, 2, false);
native_context()->set_regexp_split_function(*fun);
DCHECK_EQ(JSRegExp::kSymbolSplitFunctionDescriptorIndex,
prototype->map().LastAdded().as_int());
}
Handle<Map> prototype_map(prototype->map(), isolate());
Map::SetShouldBeFastPrototypeMap(prototype_map, true, isolate_);
CHECK_NE((*prototype_map).ptr(),
isolate_->initial_object_prototype()->map().ptr());
prototype_map->set_instance_type(JS_REG_EXP_PROTOTYPE_TYPE);
// 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(isolate_, regexp_fun);
// Static properties set by a successful match.
SimpleInstallGetterSetter(isolate_, regexp_fun, factory->input_string(),
Builtin::kRegExpInputGetter,
Builtin::kRegExpInputSetter);
SimpleInstallGetterSetter(isolate_, regexp_fun, "$_",
Builtin::kRegExpInputGetter,
Builtin::kRegExpInputSetter);
SimpleInstallGetterSetter(isolate_, regexp_fun, "lastMatch",
Builtin::kRegExpLastMatchGetter,
Builtin::kEmptyFunction);
SimpleInstallGetterSetter(isolate_, regexp_fun, "$&",
Builtin::kRegExpLastMatchGetter,
Builtin::kEmptyFunction);
SimpleInstallGetterSetter(isolate_, regexp_fun, "lastParen",
Builtin::kRegExpLastParenGetter,
Builtin::kEmptyFunction);
SimpleInstallGetterSetter(isolate_, regexp_fun, "$+",
Builtin::kRegExpLastParenGetter,
Builtin::kEmptyFunction);
SimpleInstallGetterSetter(isolate_, regexp_fun, "leftContext",
Builtin::kRegExpLeftContextGetter,
Builtin::kEmptyFunction);
SimpleInstallGetterSetter(isolate_, regexp_fun, "$`",
Builtin::kRegExpLeftContextGetter,
Builtin::kEmptyFunction);
SimpleInstallGetterSetter(isolate_, regexp_fun, "rightContext",
Builtin::kRegExpRightContextGetter,
Builtin::kEmptyFunction);
SimpleInstallGetterSetter(isolate_, regexp_fun, "$'",
Builtin::kRegExpRightContextGetter,
Builtin::kEmptyFunction);
#define INSTALL_CAPTURE_GETTER(i) \
SimpleInstallGetterSetter(isolate_, regexp_fun, "$" #i, \
Builtin::kRegExpCapture##i##Getter, \
Builtin::kEmptyFunction)
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
}
SetConstructorInstanceType(isolate_, regexp_fun,
JS_REG_EXP_CONSTRUCTOR_TYPE);
DCHECK(regexp_fun->has_initial_map());
Handle<Map> initial_map(regexp_fun->initial_map(), isolate());
DCHECK_EQ(1, initial_map->GetInObjectProperties());
Map::EnsureDescriptorSlack(isolate_, initial_map, 1);
// ECMA-262, section 15.10.7.5.
PropertyAttributes writable =
static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
Descriptor d = Descriptor