1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/init/bootstrapper.h"
6 
7 #include "src/api/api-inl.h"
8 #include "src/api/api-natives.h"
9 #include "src/base/hashmap.h"
10 #include "src/base/ieee754.h"
11 #include "src/builtins/accessors.h"
12 #include "src/codegen/compiler.h"
13 #include "src/common/globals.h"
14 #include "src/debug/debug.h"
15 #include "src/execution/isolate-inl.h"
16 #include "src/execution/microtask-queue.h"
17 #include "src/execution/protectors.h"
18 #include "src/extensions/cputracemark-extension.h"
19 #include "src/extensions/externalize-string-extension.h"
20 #include "src/extensions/gc-extension.h"
21 #include "src/extensions/ignition-statistics-extension.h"
22 #include "src/extensions/statistics-extension.h"
23 #include "src/extensions/trigger-failure-extension.h"
24 #ifdef ENABLE_VTUNE_TRACEMARK
25 #include "src/extensions/vtunedomain-support-extension.h"
26 #endif  // ENABLE_VTUNE_TRACEMARK
27 #include "src/heap/heap-inl.h"
28 #include "src/logging/counters.h"
29 #include "src/logging/log.h"
30 #include "src/numbers/math-random.h"
31 #include "src/objects/api-callbacks.h"
32 #include "src/objects/arguments.h"
33 #include "src/objects/function-kind.h"
34 #include "src/objects/hash-table-inl.h"
35 #ifdef V8_INTL_SUPPORT
36 #include "src/objects/intl-objects.h"
37 #endif  // V8_INTL_SUPPORT
38 #include "src/objects/js-array-buffer-inl.h"
39 #include "src/objects/js-array-inl.h"
40 #ifdef V8_INTL_SUPPORT
41 #include "src/objects/js-break-iterator.h"
42 #include "src/objects/js-collator.h"
43 #include "src/objects/js-date-time-format.h"
44 #include "src/objects/js-display-names.h"
45 #include "src/objects/js-list-format.h"
46 #include "src/objects/js-locale.h"
47 #include "src/objects/js-number-format.h"
48 #include "src/objects/js-plural-rules.h"
49 #endif  // V8_INTL_SUPPORT
50 #include "src/objects/js-regexp-string-iterator.h"
51 #include "src/objects/js-regexp.h"
52 #ifdef V8_INTL_SUPPORT
53 #include "src/objects/js-relative-time-format.h"
54 #include "src/objects/js-segment-iterator.h"
55 #include "src/objects/js-segmenter.h"
56 #include "src/objects/js-segments.h"
57 #endif  // V8_INTL_SUPPORT
58 #include "src/objects/js-weak-refs.h"
59 #include "src/objects/ordered-hash-table.h"
60 #include "src/objects/property-cell.h"
61 #include "src/objects/slots-inl.h"
62 #include "src/objects/templates.h"
63 #include "src/snapshot/snapshot.h"
64 #include "src/wasm/wasm-js.h"
65 #include "src/zone/zone-hashmap.h"
66 
67 namespace v8 {
68 namespace internal {
69 
Initialize(Isolate * isolate,bool create_heap_objects)70 void SourceCodeCache::Initialize(Isolate* isolate, bool create_heap_objects) {
71   cache_ = create_heap_objects ? ReadOnlyRoots(isolate).empty_fixed_array()
72                                : FixedArray();
73 }
74 
Iterate(RootVisitor * v)75 void SourceCodeCache::Iterate(RootVisitor* v) {
76   v->VisitRootPointer(Root::kExtensions, nullptr, FullObjectSlot(&cache_));
77 }
78 
Lookup(Isolate * isolate,Vector<const char> name,Handle<SharedFunctionInfo> * handle)79 bool SourceCodeCache::Lookup(Isolate* isolate, Vector<const char> name,
80                              Handle<SharedFunctionInfo>* handle) {
81   for (int i = 0; i < cache_.length(); i += 2) {
82     SeqOneByteString str = SeqOneByteString::cast(cache_.get(i));
83     if (str.IsOneByteEqualTo(Vector<const uint8_t>::cast(name))) {
84       *handle = Handle<SharedFunctionInfo>(
85           SharedFunctionInfo::cast(cache_.get(i + 1)), isolate);
86       return true;
87     }
88   }
89   return false;
90 }
91 
Add(Isolate * isolate,Vector<const char> name,Handle<SharedFunctionInfo> shared)92 void SourceCodeCache::Add(Isolate* isolate, Vector<const char> name,
93                           Handle<SharedFunctionInfo> shared) {
94   Factory* factory = isolate->factory();
95   HandleScope scope(isolate);
96   int length = cache_.length();
97   Handle<FixedArray> new_array =
98       factory->NewFixedArray(length + 2, AllocationType::kOld);
99   cache_.CopyTo(0, *new_array, 0, cache_.length());
100   cache_ = *new_array;
101   Handle<String> str =
102       factory
103           ->NewStringFromOneByte(Vector<const uint8_t>::cast(name),
104                                  AllocationType::kOld)
105           .ToHandleChecked();
106   DCHECK(!str.is_null());
107   cache_.set(length, *str);
108   cache_.set(length + 1, *shared);
109   Script::cast(shared->script()).set_type(type_);
110 }
111 
Bootstrapper(Isolate * isolate)112 Bootstrapper::Bootstrapper(Isolate* isolate)
113     : isolate_(isolate),
114       nesting_(0),
115       extensions_cache_(Script::TYPE_EXTENSION) {}
116 
Initialize(bool create_heap_objects)117 void Bootstrapper::Initialize(bool create_heap_objects) {
118   extensions_cache_.Initialize(isolate_, create_heap_objects);
119 }
120 
GCFunctionName()121 static const char* GCFunctionName() {
122   bool flag_given =
123       FLAG_expose_gc_as != nullptr && strlen(FLAG_expose_gc_as) != 0;
124   return flag_given ? FLAG_expose_gc_as : "gc";
125 }
126 
isValidCpuTraceMarkFunctionName()127 static bool isValidCpuTraceMarkFunctionName() {
128   return FLAG_expose_cputracemark_as != nullptr &&
129          strlen(FLAG_expose_cputracemark_as) != 0;
130 }
131 
InitializeOncePerProcess()132 void Bootstrapper::InitializeOncePerProcess() {
133   v8::RegisterExtension(std::make_unique<GCExtension>(GCFunctionName()));
134   v8::RegisterExtension(std::make_unique<ExternalizeStringExtension>());
135   v8::RegisterExtension(std::make_unique<StatisticsExtension>());
136   v8::RegisterExtension(std::make_unique<TriggerFailureExtension>());
137   v8::RegisterExtension(std::make_unique<IgnitionStatisticsExtension>());
138   if (isValidCpuTraceMarkFunctionName()) {
139     v8::RegisterExtension(
140         std::make_unique<CpuTraceMarkExtension>(FLAG_expose_cputracemark_as));
141   }
142 #ifdef ENABLE_VTUNE_TRACEMARK
143   v8::RegisterExtension(
144       std::make_unique<VTuneDomainSupportExtension>("vtunedomainmark"));
145 #endif  // ENABLE_VTUNE_TRACEMARK
146 }
147 
TearDown()148 void Bootstrapper::TearDown() {
149   extensions_cache_.Initialize(isolate_, false);  // Yes, symmetrical
150 }
151 
152 class Genesis {
153  public:
154   Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
155           v8::Local<v8::ObjectTemplate> global_proxy_template,
156           size_t context_snapshot_index,
157           v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
158           v8::MicrotaskQueue* microtask_queue);
159   Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
160           v8::Local<v8::ObjectTemplate> global_proxy_template);
161   ~Genesis() = default;
162 
isolate() const163   Isolate* isolate() const { return isolate_; }
factory() const164   Factory* factory() const { return isolate_->factory(); }
builtins() const165   Builtins* builtins() const { return isolate_->builtins(); }
heap() const166   Heap* heap() const { return isolate_->heap(); }
167 
result()168   Handle<Context> result() { return result_; }
169 
global_proxy()170   Handle<JSGlobalProxy> global_proxy() { return global_proxy_; }
171 
172  private:
native_context()173   Handle<NativeContext> native_context() { return native_context_; }
174 
175   // Creates some basic objects. Used for creating a context from scratch.
176   void CreateRoots();
177   // Creates the empty function.  Used for creating a context from scratch.
178   Handle<JSFunction> CreateEmptyFunction();
179   // Returns the %ThrowTypeError% intrinsic function.
180   // See ES#sec-%throwtypeerror% for details.
181   Handle<JSFunction> GetThrowTypeErrorIntrinsic();
182 
183   void CreateSloppyModeFunctionMaps(Handle<JSFunction> empty);
184   void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
185   void CreateObjectFunction(Handle<JSFunction> empty);
186   void CreateIteratorMaps(Handle<JSFunction> empty);
187   void CreateAsyncIteratorMaps(Handle<JSFunction> empty);
188   void CreateAsyncFunctionMaps(Handle<JSFunction> empty);
189   void CreateJSProxyMaps();
190 
191   // Make the "arguments" and "caller" properties throw a TypeError on access.
192   void AddRestrictedFunctionProperties(Handle<JSFunction> empty);
193 
194   // Creates the global objects using the global proxy and the template passed
195   // in through the API.  We call this regardless of whether we are building a
196   // context from scratch or using a deserialized one from the context snapshot
197   // but in the latter case we don't use the objects it produces directly, as
198   // we have to use the deserialized ones that are linked together with the
199   // rest of the context snapshot. At the end we link the global proxy and the
200   // context to each other.
201   Handle<JSGlobalObject> CreateNewGlobals(
202       v8::Local<v8::ObjectTemplate> global_proxy_template,
203       Handle<JSGlobalProxy> global_proxy);
204   // Similarly, we want to use the global that has been created by the templates
205   // passed through the API.  The global from the snapshot is detached from the
206   // other objects in the snapshot.
207   void HookUpGlobalObject(Handle<JSGlobalObject> global_object);
208   // Hooks the given global proxy into the context in the case we do not
209   // replace the global object from the deserialized native context.
210   void HookUpGlobalProxy(Handle<JSGlobalProxy> global_proxy);
211   // The native context has a ScriptContextTable that store declarative bindings
212   // made in script scopes.  Add a "this" binding to that table pointing to the
213   // global proxy.
214   void InstallGlobalThisBinding();
215   // New context initialization.  Used for creating a context from scratch.
216   void InitializeGlobal(Handle<JSGlobalObject> global_object,
217                         Handle<JSFunction> empty_function);
218   void InitializeExperimentalGlobal();
219   void InitializeIteratorFunctions();
220   void InitializeCallSiteBuiltins();
221 
222 #define DECLARE_FEATURE_INITIALIZATION(id, descr) void InitializeGlobal_##id();
223 
224   HARMONY_INPROGRESS(DECLARE_FEATURE_INITIALIZATION)
225   HARMONY_STAGED(DECLARE_FEATURE_INITIALIZATION)
226   HARMONY_SHIPPING(DECLARE_FEATURE_INITIALIZATION)
227 #undef DECLARE_FEATURE_INITIALIZATION
228   void InitializeGlobal_regexp_linear_flag();
229 
230   enum ArrayBufferKind {
231     ARRAY_BUFFER,
232     SHARED_ARRAY_BUFFER,
233   };
234   Handle<JSFunction> CreateArrayBuffer(Handle<String> name,
235                                        ArrayBufferKind array_buffer_kind);
236 
237   bool InstallABunchOfRandomThings();
238   bool InstallExtrasBindings();
239 
240   Handle<JSFunction> InstallTypedArray(const char* name,
241                                        ElementsKind elements_kind);
242   void InitializeNormalizedMapCaches();
243 
244   enum ExtensionTraversalState { UNVISITED, VISITED, INSTALLED };
245 
246   class ExtensionStates {
247    public:
248     ExtensionStates();
249     ExtensionTraversalState get_state(RegisteredExtension* extension);
250     void set_state(RegisteredExtension* extension,
251                    ExtensionTraversalState state);
252 
253    private:
254     base::HashMap map_;
255     DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
256   };
257 
258   // Used both for deserialized and from-scratch contexts to add the extensions
259   // provided.
260   static bool InstallExtensions(Isolate* isolate,
261                                 Handle<Context> native_context,
262                                 v8::ExtensionConfiguration* extensions);
263   static bool InstallAutoExtensions(Isolate* isolate,
264                                     ExtensionStates* extension_states);
265   static bool InstallRequestedExtensions(Isolate* isolate,
266                                          v8::ExtensionConfiguration* extensions,
267                                          ExtensionStates* extension_states);
268   static bool InstallExtension(Isolate* isolate, const char* name,
269                                ExtensionStates* extension_states);
270   static bool InstallExtension(Isolate* isolate,
271                                v8::RegisteredExtension* current,
272                                ExtensionStates* extension_states);
273   static bool InstallSpecialObjects(Isolate* isolate,
274                                     Handle<Context> native_context);
275   bool ConfigureApiObject(Handle<JSObject> object,
276                           Handle<ObjectTemplateInfo> object_template);
277   bool ConfigureGlobalObjects(
278       v8::Local<v8::ObjectTemplate> global_proxy_template);
279 
280   // Migrates all properties from the 'from' object to the 'to'
281   // object and overrides the prototype in 'to' with the one from
282   // 'from'.
283   void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
284   void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
285   void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
286 
287   Handle<Map> CreateInitialMapForArraySubclass(int size,
288                                                int inobject_properties);
289 
290   static bool CompileExtension(Isolate* isolate, v8::Extension* extension);
291 
292   Isolate* isolate_;
293   Handle<Context> result_;
294   Handle<NativeContext> native_context_;
295   Handle<JSGlobalProxy> global_proxy_;
296 
297   // Temporary function maps needed only during bootstrapping.
298   Handle<Map> strict_function_with_home_object_map_;
299   Handle<Map> strict_function_with_name_and_home_object_map_;
300 
301   // %ThrowTypeError%. See ES#sec-%throwtypeerror% for details.
302   Handle<JSFunction> restricted_properties_thrower_;
303 
304   BootstrapperActive active_;
305   friend class Bootstrapper;
306 };
307 
Iterate(RootVisitor * v)308 void Bootstrapper::Iterate(RootVisitor* v) {
309   extensions_cache_.Iterate(v);
310   v->Synchronize(VisitorSynchronization::kExtensions);
311 }
312 
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)313 Handle<Context> Bootstrapper::CreateEnvironment(
314     MaybeHandle<JSGlobalProxy> maybe_global_proxy,
315     v8::Local<v8::ObjectTemplate> global_proxy_template,
316     v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
317     v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
318     v8::MicrotaskQueue* microtask_queue) {
319   HandleScope scope(isolate_);
320   Handle<Context> env;
321   {
322     Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template,
323                     context_snapshot_index, embedder_fields_deserializer,
324                     microtask_queue);
325     env = genesis.result();
326     if (env.is_null() || !InstallExtensions(env, extensions)) {
327       return Handle<Context>();
328     }
329   }
330   LogAllMaps();
331   isolate_->heap()->NotifyBootstrapComplete();
332   return scope.CloseAndEscape(env);
333 }
334 
NewRemoteContext(MaybeHandle<JSGlobalProxy> maybe_global_proxy,v8::Local<v8::ObjectTemplate> global_proxy_template)335 Handle<JSGlobalProxy> Bootstrapper::NewRemoteContext(
336     MaybeHandle<JSGlobalProxy> maybe_global_proxy,
337     v8::Local<v8::ObjectTemplate> global_proxy_template) {
338   HandleScope scope(isolate_);
339   Handle<JSGlobalProxy> global_proxy;
340   {
341     Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template);
342     global_proxy = genesis.global_proxy();
343     if (global_proxy.is_null()) return Handle<JSGlobalProxy>();
344   }
345   LogAllMaps();
346   return scope.CloseAndEscape(global_proxy);
347 }
348 
LogAllMaps()349 void Bootstrapper::LogAllMaps() {
350   if (!FLAG_trace_maps || isolate_->initialized_from_snapshot()) return;
351   // Log all created Map objects that are on the heap. For snapshots the Map
352   // logging happens during deserialization in order to avoid printing Maps
353   // multiple times during partial deserialization.
354   LOG(isolate_, LogAllMaps());
355 }
356 
DetachGlobal(Handle<Context> env)357 void Bootstrapper::DetachGlobal(Handle<Context> env) {
358   isolate_->counters()->errors_thrown_per_context()->AddSample(
359       env->native_context().GetErrorsThrown());
360 
361   ReadOnlyRoots roots(isolate_);
362   Handle<JSGlobalProxy> global_proxy(env->global_proxy(), isolate_);
363   global_proxy->set_native_context(roots.null_value());
364   JSObject::ForceSetPrototype(global_proxy, isolate_->factory()->null_value());
365   global_proxy->map().SetConstructor(roots.null_value());
366   if (FLAG_track_detached_contexts) {
367     isolate_->AddDetachedContext(env);
368   }
369   DCHECK(global_proxy->IsDetached());
370 
371   env->native_context().set_microtask_queue(isolate_, nullptr);
372 }
373 
374 namespace {
375 
CreateFunction(Isolate * isolate,Handle<String> name,InstanceType type,int instance_size,int inobject_properties,Handle<HeapObject> prototype,Builtins::Name builtin_id)376 V8_NOINLINE Handle<JSFunction> CreateFunction(
377     Isolate* isolate, Handle<String> name, InstanceType type, int instance_size,
378     int inobject_properties, Handle<HeapObject> prototype,
379     Builtins::Name builtin_id) {
380   DCHECK(Builtins::HasJSLinkage(builtin_id));
381 
382   Handle<JSFunction> result;
383 
384   NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
385       name, prototype, type, instance_size, inobject_properties, builtin_id,
386       IMMUTABLE);
387 
388   result = isolate->factory()->NewFunction(args);
389   // Make the JSFunction's prototype object fast.
390   JSObject::MakePrototypesFast(handle(result->prototype(), isolate),
391                                kStartAtReceiver, isolate);
392 
393   // Make the resulting JSFunction object fast.
394   JSObject::MakePrototypesFast(result, kStartAtReceiver, isolate);
395   result->shared().set_native(true);
396   return result;
397 }
398 
CreateFunction(Isolate * isolate,const char * name,InstanceType type,int instance_size,int inobject_properties,Handle<HeapObject> prototype,Builtins::Name builtin_id)399 V8_NOINLINE Handle<JSFunction> CreateFunction(
400     Isolate* isolate, const char* name, InstanceType type, int instance_size,
401     int inobject_properties, Handle<HeapObject> prototype,
402     Builtins::Name builtin_id) {
403   return CreateFunction(
404       isolate, isolate->factory()->InternalizeUtf8String(name), type,
405       instance_size, inobject_properties, prototype, builtin_id);
406 }
407 
InstallFunction(Isolate * isolate,Handle<JSObject> target,Handle<String> name,InstanceType type,int instance_size,int inobject_properties,Handle<HeapObject> prototype,Builtins::Name call)408 V8_NOINLINE Handle<JSFunction> InstallFunction(
409     Isolate* isolate, Handle<JSObject> target, Handle<String> name,
410     InstanceType type, int instance_size, int inobject_properties,
411     Handle<HeapObject> prototype, Builtins::Name call) {
412   DCHECK(Builtins::HasJSLinkage(call));
413   Handle<JSFunction> function = CreateFunction(
414       isolate, name, type, instance_size, inobject_properties, prototype, call);
415   JSObject::AddProperty(isolate, target, name, function, DONT_ENUM);
416   return function;
417 }
418 
InstallFunction(Isolate * isolate,Handle<JSObject> target,const char * name,InstanceType type,int instance_size,int inobject_properties,Handle<HeapObject> prototype,Builtins::Name call)419 V8_NOINLINE Handle<JSFunction> InstallFunction(
420     Isolate* isolate, Handle<JSObject> target, const char* name,
421     InstanceType type, int instance_size, int inobject_properties,
422     Handle<HeapObject> prototype, Builtins::Name call) {
423   return InstallFunction(isolate, target,
424                          isolate->factory()->InternalizeUtf8String(name), type,
425                          instance_size, inobject_properties, prototype, call);
426 }
427 
SimpleCreateFunction(Isolate * isolate,Handle<String> name,Builtins::Name call,int len,bool adapt)428 V8_NOINLINE Handle<JSFunction> SimpleCreateFunction(Isolate* isolate,
429                                                     Handle<String> name,
430                                                     Builtins::Name call,
431                                                     int len, bool adapt) {
432   DCHECK(Builtins::HasJSLinkage(call));
433   name = String::Flatten(isolate, name, AllocationType::kOld);
434   NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithoutPrototype(
435       name, call, LanguageMode::kStrict);
436   Handle<JSFunction> fun = isolate->factory()->NewFunction(args);
437   // Make the resulting JSFunction object fast.
438   JSObject::MakePrototypesFast(fun, kStartAtReceiver, isolate);
439   fun->shared().set_native(true);
440 
441   if (adapt) {
442     fun->shared().set_internal_formal_parameter_count(len);
443   } else {
444     fun->shared().DontAdaptArguments();
445   }
446   fun->shared().set_length(len);
447   return fun;
448 }
449 
InstallFunctionWithBuiltinId(Isolate * isolate,Handle<JSObject> base,const char * name,Builtins::Name call,int len,bool adapt)450 V8_NOINLINE Handle<JSFunction> InstallFunctionWithBuiltinId(
451     Isolate* isolate, Handle<JSObject> base, const char* name,
452     Builtins::Name call, int len, bool adapt) {
453   Handle<String> internalized_name =
454       isolate->factory()->InternalizeUtf8String(name);
455   Handle<JSFunction> fun =
456       SimpleCreateFunction(isolate, internalized_name, call, len, adapt);
457   JSObject::AddProperty(isolate, base, internalized_name, fun, DONT_ENUM);
458   return fun;
459 }
460 
SimpleInstallFunction(Isolate * isolate,Handle<JSObject> base,const char * name,Builtins::Name call,int len,bool adapt,PropertyAttributes attrs=DONT_ENUM)461 V8_NOINLINE Handle<JSFunction> SimpleInstallFunction(
462     Isolate* isolate, Handle<JSObject> base, const char* name,
463     Builtins::Name call, int len, bool adapt,
464     PropertyAttributes attrs = DONT_ENUM) {
465   // Although function name does not have to be internalized the property name
466   // will be internalized during property addition anyway, so do it here now.
467   Handle<String> internalized_name =
468       isolate->factory()->InternalizeUtf8String(name);
469   Handle<JSFunction> fun =
470       SimpleCreateFunction(isolate, internalized_name, call, len, adapt);
471   JSObject::AddProperty(isolate, base, internalized_name, fun, attrs);
472   return fun;
473 }
474 
InstallFunctionAtSymbol(Isolate * isolate,Handle<JSObject> base,Handle<Symbol> symbol,const char * symbol_string,Builtins::Name call,int len,bool adapt,PropertyAttributes attrs=DONT_ENUM)475 V8_NOINLINE Handle<JSFunction> InstallFunctionAtSymbol(
476     Isolate* isolate, Handle<JSObject> base, Handle<Symbol> symbol,
477     const char* symbol_string, Builtins::Name call, int len, bool adapt,
478     PropertyAttributes attrs = DONT_ENUM) {
479   Handle<String> internalized_symbol =
480       isolate->factory()->InternalizeUtf8String(symbol_string);
481   Handle<JSFunction> fun =
482       SimpleCreateFunction(isolate, internalized_symbol, call, len, adapt);
483   JSObject::AddProperty(isolate, base, symbol, fun, attrs);
484   return fun;
485 }
486 
SimpleInstallGetterSetter(Isolate * isolate,Handle<JSObject> base,Handle<String> name,Builtins::Name call_getter,Builtins::Name call_setter)487 V8_NOINLINE void SimpleInstallGetterSetter(Isolate* isolate,
488                                            Handle<JSObject> base,
489                                            Handle<String> name,
490                                            Builtins::Name call_getter,
491                                            Builtins::Name call_setter) {
492   Handle<String> getter_name =
493       Name::ToFunctionName(isolate, name, isolate->factory()->get_string())
494           .ToHandleChecked();
495   Handle<JSFunction> getter =
496       SimpleCreateFunction(isolate, getter_name, call_getter, 0, true);
497 
498   Handle<String> setter_name =
499       Name::ToFunctionName(isolate, name, isolate->factory()->set_string())
500           .ToHandleChecked();
501   Handle<JSFunction> setter =
502       SimpleCreateFunction(isolate, setter_name, call_setter, 1, true);
503 
504   JSObject::DefineAccessor(base, name, getter, setter, DONT_ENUM).Check();
505 }
506 
SimpleInstallGetterSetter(Isolate * isolate,Handle<JSObject> base,const char * name,Builtins::Name call_getter,Builtins::Name call_setter)507 void SimpleInstallGetterSetter(Isolate* isolate, Handle<JSObject> base,
508                                const char* name, Builtins::Name call_getter,
509                                Builtins::Name call_setter) {
510   SimpleInstallGetterSetter(isolate, base,
511                             isolate->factory()->InternalizeUtf8String(name),
512                             call_getter, call_setter);
513 }
514 
SimpleInstallGetter(Isolate * isolate,Handle<JSObject> base,Handle<Name> name,Handle<Name> property_name,Builtins::Name call,bool adapt)515 V8_NOINLINE Handle<JSFunction> SimpleInstallGetter(
516     Isolate* isolate, Handle<JSObject> base, Handle<Name> name,
517     Handle<Name> property_name, Builtins::Name call, bool adapt) {
518   Handle<String> getter_name =
519       Name::ToFunctionName(isolate, name, isolate->factory()->get_string())
520           .ToHandleChecked();
521   Handle<JSFunction> getter =
522       SimpleCreateFunction(isolate, getter_name, call, 0, adapt);
523 
524   Handle<Object> setter = isolate->factory()->undefined_value();
525 
526   JSObject::DefineAccessor(base, property_name, getter, setter, DONT_ENUM)
527       .Check();
528 
529   return getter;
530 }
531 
SimpleInstallGetter(Isolate * isolate,Handle<JSObject> base,Handle<Name> name,Builtins::Name call,bool adapt)532 V8_NOINLINE Handle<JSFunction> SimpleInstallGetter(Isolate* isolate,
533                                                    Handle<JSObject> base,
534                                                    Handle<Name> name,
535                                                    Builtins::Name call,
536                                                    bool adapt) {
537   return SimpleInstallGetter(isolate, base, name, name, call, adapt);
538 }
539 
InstallConstant(Isolate * isolate,Handle<JSObject> holder,const char * name,Handle<Object> value)540 V8_NOINLINE void InstallConstant(Isolate* isolate, Handle<JSObject> holder,
541                                  const char* name, Handle<Object> value) {
542   JSObject::AddProperty(
543       isolate, holder, isolate->factory()->InternalizeUtf8String(name), value,
544       static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
545 }
546 
InstallTrueValuedProperty(Isolate * isolate,Handle<JSObject> holder,const char * name)547 V8_NOINLINE void InstallTrueValuedProperty(Isolate* isolate,
548                                            Handle<JSObject> holder,
549                                            const char* name) {
550   JSObject::AddProperty(isolate, holder,
551                         isolate->factory()->InternalizeUtf8String(name),
552                         isolate->factory()->true_value(), NONE);
553 }
554 
InstallSpeciesGetter(Isolate * isolate,Handle<JSFunction> constructor)555 V8_NOINLINE void InstallSpeciesGetter(Isolate* isolate,
556                                       Handle<JSFunction> constructor) {
557   Factory* factory = isolate->factory();
558   // TODO(adamk): We should be able to share a SharedFunctionInfo
559   // between all these JSFunctins.
560   SimpleInstallGetter(isolate, constructor, factory->symbol_species_string(),
561                       factory->species_symbol(), Builtins::kReturnReceiver,
562                       true);
563 }
564 
InstallToStringTag(Isolate * isolate,Handle<JSObject> holder,Handle<String> value)565 V8_NOINLINE void InstallToStringTag(Isolate* isolate, Handle<JSObject> holder,
566                                     Handle<String> value) {
567   JSObject::AddProperty(isolate, holder,
568                         isolate->factory()->to_string_tag_symbol(), value,
569                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
570 }
571 
InstallToStringTag(Isolate * isolate,Handle<JSObject> holder,const char * value)572 void InstallToStringTag(Isolate* isolate, Handle<JSObject> holder,
573                         const char* value) {
574   InstallToStringTag(isolate, holder,
575                      isolate->factory()->InternalizeUtf8String(value));
576 }
577 
578 }  // namespace
579 
CreateEmptyFunction()580 Handle<JSFunction> Genesis::CreateEmptyFunction() {
581   // Allocate the function map first and then patch the prototype later.
582   Handle<Map> empty_function_map = factory()->CreateSloppyFunctionMap(
583       FUNCTION_WITHOUT_PROTOTYPE, MaybeHandle<JSFunction>());
584   empty_function_map->set_is_prototype_map(true);
585   DCHECK(!empty_function_map->is_dictionary_map());
586 
587   // Allocate the empty function as the prototype for function according to
588   // ES#sec-properties-of-the-function-prototype-object
589   NewFunctionArgs args = NewFunctionArgs::ForBuiltin(
590       factory()->empty_string(), empty_function_map, Builtins::kEmptyFunction);
591   Handle<JSFunction> empty_function = factory()->NewFunction(args);
592   native_context()->set_empty_function(*empty_function);
593 
594   // --- E m p t y ---
595   Handle<String> source = factory()->NewStringFromStaticChars("() {}");
596   Handle<Script> script = factory()->NewScript(source);
597   script->set_type(Script::TYPE_NATIVE);
598   Handle<WeakFixedArray> infos = factory()->NewWeakFixedArray(2);
599   script->set_shared_function_infos(*infos);
600   empty_function->shared().set_raw_scope_info(
601       ReadOnlyRoots(isolate()).empty_function_scope_info());
602   empty_function->shared().DontAdaptArguments();
603   empty_function->shared().SetScript(ReadOnlyRoots(isolate()), *script, 1);
604 
605   return empty_function;
606 }
607 
CreateSloppyModeFunctionMaps(Handle<JSFunction> empty)608 void Genesis::CreateSloppyModeFunctionMaps(Handle<JSFunction> empty) {
609   Factory* factory = isolate_->factory();
610   Handle<Map> map;
611 
612   //
613   // Allocate maps for sloppy functions without prototype.
614   //
615   map = factory->CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
616   native_context()->set_sloppy_function_without_prototype_map(*map);
617 
618   //
619   // Allocate maps for sloppy functions with readonly prototype.
620   //
621   map =
622       factory->CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
623   native_context()->set_sloppy_function_with_readonly_prototype_map(*map);
624 
625   //
626   // Allocate maps for sloppy functions with writable prototype.
627   //
628   map = factory->CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE,
629                                          empty);
630   native_context()->set_sloppy_function_map(*map);
631 
632   map = factory->CreateSloppyFunctionMap(
633       FUNCTION_WITH_NAME_AND_WRITEABLE_PROTOTYPE, empty);
634   native_context()->set_sloppy_function_with_name_map(*map);
635 }
636 
GetThrowTypeErrorIntrinsic()637 Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic() {
638   if (!restricted_properties_thrower_.is_null()) {
639     return restricted_properties_thrower_;
640   }
641   Handle<String> name = factory()->empty_string();
642   NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithoutPrototype(
643       name, Builtins::kStrictPoisonPillThrower, i::LanguageMode::kStrict);
644   Handle<JSFunction> function = factory()->NewFunction(args);
645   function->shared().DontAdaptArguments();
646 
647   // %ThrowTypeError% must have a name property with an empty string value. Per
648   // spec, ThrowTypeError's name is non-configurable, unlike ordinary functions'
649   // name property. To redefine it to be non-configurable, use
650   // SetOwnPropertyIgnoreAttributes.
651   JSObject::SetOwnPropertyIgnoreAttributes(
652       function, factory()->name_string(), factory()->empty_string(),
653       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
654       .Assert();
655 
656   // length needs to be non configurable.
657   Handle<Object> value(Smi::FromInt(function->length()), isolate());
658   JSObject::SetOwnPropertyIgnoreAttributes(
659       function, factory()->length_string(), value,
660       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
661       .Assert();
662 
663   if (JSObject::PreventExtensions(function, kThrowOnError).IsNothing()) {
664     DCHECK(false);
665   }
666 
667   JSObject::MigrateSlowToFast(function, 0, "Bootstrapping");
668 
669   restricted_properties_thrower_ = function;
670   return function;
671 }
672 
CreateStrictModeFunctionMaps(Handle<JSFunction> empty)673 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
674   Factory* factory = isolate_->factory();
675   Handle<Map> map;
676 
677   //
678   // Allocate maps for strict functions without prototype.
679   //
680   map = factory->CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
681   native_context()->set_strict_function_without_prototype_map(*map);
682 
683   map = factory->CreateStrictFunctionMap(METHOD_WITH_NAME, empty);
684   native_context()->set_method_with_name_map(*map);
685 
686   map = factory->CreateStrictFunctionMap(METHOD_WITH_HOME_OBJECT, empty);
687   native_context()->set_method_with_home_object_map(*map);
688 
689   map =
690       factory->CreateStrictFunctionMap(METHOD_WITH_NAME_AND_HOME_OBJECT, empty);
691   native_context()->set_method_with_name_and_home_object_map(*map);
692 
693   //
694   // Allocate maps for strict functions with writable prototype.
695   //
696   map = factory->CreateStrictFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE,
697                                          empty);
698   native_context()->set_strict_function_map(*map);
699 
700   map = factory->CreateStrictFunctionMap(
701       FUNCTION_WITH_NAME_AND_WRITEABLE_PROTOTYPE, empty);
702   native_context()->set_strict_function_with_name_map(*map);
703 
704   strict_function_with_home_object_map_ = factory->CreateStrictFunctionMap(
705       FUNCTION_WITH_HOME_OBJECT_AND_WRITEABLE_PROTOTYPE, empty);
706   strict_function_with_name_and_home_object_map_ =
707       factory->CreateStrictFunctionMap(
708           FUNCTION_WITH_NAME_AND_HOME_OBJECT_AND_WRITEABLE_PROTOTYPE, empty);
709 
710   //
711   // Allocate maps for strict functions with readonly prototype.
712   //
713   map =
714       factory->CreateStrictFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
715   native_context()->set_strict_function_with_readonly_prototype_map(*map);
716 
717   //
718   // Allocate map for class functions.
719   //
720   map = factory->CreateClassFunctionMap(empty);
721   native_context()->set_class_function_map(*map);
722 
723   // Now that the strict mode function map is available, set up the
724   // restricted "arguments" and "caller" getters.
725   AddRestrictedFunctionProperties(empty);
726 }
727 
CreateObjectFunction(Handle<JSFunction> empty_function)728 void Genesis::CreateObjectFunction(Handle<JSFunction> empty_function) {
729   Factory* factory = isolate_->factory();
730 
731   // --- O b j e c t ---
732   int inobject_properties = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
733   int instance_size = JSObject::kHeaderSize + kTaggedSize * inobject_properties;
734 
735   Handle<JSFunction> object_fun = CreateFunction(
736       isolate_, factory->Object_string(), JS_OBJECT_TYPE, instance_size,
737       inobject_properties, factory->null_value(), Builtins::kObjectConstructor);
738   object_fun->shared().set_length(1);
739   object_fun->shared().DontAdaptArguments();
740   native_context()->set_object_function(*object_fun);
741 
742   {
743     // Finish setting up Object function's initial map.
744     Map initial_map = object_fun->initial_map();
745     initial_map.set_elements_kind(HOLEY_ELEMENTS);
746   }
747 
748   // Allocate a new prototype for the object function.
749   Handle<JSObject> object_function_prototype =
750       factory->NewFunctionPrototype(object_fun);
751 
752   Handle<Map> map =
753       Map::Copy(isolate(), handle(object_function_prototype->map(), isolate()),
754                 "EmptyObjectPrototype");
755   map->set_is_prototype_map(true);
756   // Ban re-setting Object.prototype.__proto__ to prevent Proxy security bug
757   map->set_is_immutable_proto(true);
758   object_function_prototype->set_map(*map);
759 
760   // Complete setting up empty function.
761   {
762     Handle<Map> empty_function_map(empty_function->map(), isolate_);
763     Map::SetPrototype(isolate(), empty_function_map, object_function_prototype);
764   }
765 
766   native_context()->set_initial_object_prototype(*object_function_prototype);
767   JSFunction::SetPrototype(object_fun, object_function_prototype);
768 
769   {
770     // Set up slow map for Object.create(null) instances without in-object
771     // properties.
772     Handle<Map> map(object_fun->initial_map(), isolate_);
773     map = Map::CopyInitialMapNormalized(isolate(), map);
774     Map::SetPrototype(isolate(), map, factory->null_value());
775     native_context()->set_slow_object_with_null_prototype_map(*map);
776 
777     // Set up slow map for literals with too many properties.
778     map = Map::Copy(isolate(), map, "slow_object_with_object_prototype_map");
779     Map::SetPrototype(isolate(), map, object_function_prototype);
780     native_context()->set_slow_object_with_object_prototype_map(*map);
781   }
782 }
783 
784 namespace {
785 
CreateNonConstructorMap(Isolate * isolate,Handle<Map> source_map,Handle<JSObject> prototype,const char * reason)786 Handle<Map> CreateNonConstructorMap(Isolate* isolate, Handle<Map> source_map,
787                                     Handle<JSObject> prototype,
788                                     const char* reason) {
789   Handle<Map> map = Map::Copy(isolate, source_map, reason);
790   // Ensure the resulting map has prototype slot (it is necessary for storing
791   // inital map even when the prototype property is not required).
792   if (!map->has_prototype_slot()) {
793     // Re-set the unused property fields after changing the instance size.
794     // TODO(ulan): Do not change instance size after map creation.
795     int unused_property_fields = map->UnusedPropertyFields();
796     map->set_instance_size(map->instance_size() + kTaggedSize);
797     // The prototype slot shifts the in-object properties area by one slot.
798     map->SetInObjectPropertiesStartInWords(
799         map->GetInObjectPropertiesStartInWords() + 1);
800     map->set_has_prototype_slot(true);
801     map->SetInObjectUnusedPropertyFields(unused_property_fields);
802   }
803   map->set_is_constructor(false);
804   Map::SetPrototype(isolate, map, prototype);
805   return map;
806 }
807 
808 }  // namespace
809 
CreateIteratorMaps(Handle<JSFunction> empty)810 void Genesis::CreateIteratorMaps(Handle<JSFunction> empty) {
811   // Create iterator-related meta-objects.
812   Handle<JSObject> iterator_prototype = factory()->NewJSObject(
813       isolate()->object_function(), AllocationType::kOld);
814 
815   InstallFunctionAtSymbol(isolate(), iterator_prototype,
816                           factory()->iterator_symbol(), "[Symbol.iterator]",
817                           Builtins::kReturnReceiver, 0, true);
818   native_context()->set_initial_iterator_prototype(*iterator_prototype);
819 
820   Handle<JSObject> generator_object_prototype = factory()->NewJSObject(
821       isolate()->object_function(), AllocationType::kOld);
822   native_context()->set_initial_generator_prototype(
823       *generator_object_prototype);
824   JSObject::ForceSetPrototype(generator_object_prototype, iterator_prototype);
825   Handle<JSObject> generator_function_prototype = factory()->NewJSObject(
826       isolate()->object_function(), AllocationType::kOld);
827   JSObject::ForceSetPrototype(generator_function_prototype, empty);
828 
829   InstallToStringTag(isolate(), generator_function_prototype,
830                      "GeneratorFunction");
831   JSObject::AddProperty(isolate(), generator_function_prototype,
832                         factory()->prototype_string(),
833                         generator_object_prototype,
834                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
835 
836   JSObject::AddProperty(isolate(), generator_object_prototype,
837                         factory()->constructor_string(),
838                         generator_function_prototype,
839                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
840   InstallToStringTag(isolate(), generator_object_prototype, "Generator");
841   SimpleInstallFunction(isolate(), generator_object_prototype, "next",
842                         Builtins::kGeneratorPrototypeNext, 1, false);
843   SimpleInstallFunction(isolate(), generator_object_prototype, "return",
844                         Builtins::kGeneratorPrototypeReturn, 1, false);
845   SimpleInstallFunction(isolate(), generator_object_prototype, "throw",
846                         Builtins::kGeneratorPrototypeThrow, 1, false);
847 
848   // Internal version of generator_prototype_next, flagged as non-native such
849   // that it doesn't show up in Error traces.
850   Handle<JSFunction> generator_next_internal =
851       SimpleCreateFunction(isolate(), factory()->next_string(),
852                            Builtins::kGeneratorPrototypeNext, 1, false);
853   generator_next_internal->shared().set_native(false);
854   native_context()->set_generator_next_internal(*generator_next_internal);
855 
856   // Internal version of async module functions, flagged as non-native such
857   // that they don't show up in Error traces.
858   {
859     Handle<JSFunction> async_module_evaluate_internal =
860         SimpleCreateFunction(isolate(), factory()->next_string(),
861                              Builtins::kAsyncModuleEvaluate, 1, false);
862     async_module_evaluate_internal->shared().set_native(false);
863     native_context()->set_async_module_evaluate_internal(
864         *async_module_evaluate_internal);
865 
866     Handle<JSFunction> call_async_module_fulfilled =
867         SimpleCreateFunction(isolate(), factory()->empty_string(),
868                              Builtins::kCallAsyncModuleFulfilled, 1, false);
869     native_context()->set_call_async_module_fulfilled(
870         *call_async_module_fulfilled);
871 
872     Handle<JSFunction> call_async_module_rejected =
873         SimpleCreateFunction(isolate(), factory()->empty_string(),
874                              Builtins::kCallAsyncModuleRejected, 1, false);
875     native_context()->set_call_async_module_rejected(
876         *call_async_module_rejected);
877   }
878 
879   // Create maps for generator functions and their prototypes.  Store those
880   // maps in the native context. The "prototype" property descriptor is
881   // writable, non-enumerable, and non-configurable (as per ES6 draft
882   // 04-14-15, section 25.2.4.3).
883   // Generator functions do not have "caller" or "arguments" accessors.
884   Handle<Map> map;
885   map = CreateNonConstructorMap(isolate(), isolate()->strict_function_map(),
886                                 generator_function_prototype,
887                                 "GeneratorFunction");
888   native_context()->set_generator_function_map(*map);
889 
890   map = CreateNonConstructorMap(
891       isolate(), isolate()->strict_function_with_name_map(),
892       generator_function_prototype, "GeneratorFunction with name");
893   native_context()->set_generator_function_with_name_map(*map);
894 
895   map = CreateNonConstructorMap(
896       isolate(), strict_function_with_home_object_map_,
897       generator_function_prototype, "GeneratorFunction with home object");
898   native_context()->set_generator_function_with_home_object_map(*map);
899 
900   map = CreateNonConstructorMap(isolate(),
901                                 strict_function_with_name_and_home_object_map_,
902                                 generator_function_prototype,
903                                 "GeneratorFunction with name and home object");
904   native_context()->set_generator_function_with_name_and_home_object_map(*map);
905 
906   Handle<JSFunction> object_function(native_context()->object_function(),
907                                      isolate());
908   Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
909   Map::SetPrototype(isolate(), generator_object_prototype_map,
910                     generator_object_prototype);
911   native_context()->set_generator_object_prototype_map(
912       *generator_object_prototype_map);
913 }
914 
CreateAsyncIteratorMaps(Handle<JSFunction> empty)915 void Genesis::CreateAsyncIteratorMaps(Handle<JSFunction> empty) {
916   // %AsyncIteratorPrototype%
917   // proposal-async-iteration/#sec-asynciteratorprototype
918   Handle<JSObject> async_iterator_prototype = factory()->NewJSObject(
919       isolate()->object_function(), AllocationType::kOld);
920 
921   InstallFunctionAtSymbol(
922       isolate(), async_iterator_prototype, factory()->async_iterator_symbol(),
923       "[Symbol.asyncIterator]", Builtins::kReturnReceiver, 0, true);
924   native_context()->set_initial_async_iterator_prototype(
925       *async_iterator_prototype);
926 
927   // %AsyncFromSyncIteratorPrototype%
928   // proposal-async-iteration/#sec-%asyncfromsynciteratorprototype%-object
929   Handle<JSObject> async_from_sync_iterator_prototype = factory()->NewJSObject(
930       isolate()->object_function(), AllocationType::kOld);
931   SimpleInstallFunction(isolate(), async_from_sync_iterator_prototype, "next",
932                         Builtins::kAsyncFromSyncIteratorPrototypeNext, 1,
933                         false);
934   SimpleInstallFunction(isolate(), async_from_sync_iterator_prototype, "return",
935                         Builtins::kAsyncFromSyncIteratorPrototypeReturn, 1,
936                         false);
937   SimpleInstallFunction(isolate(), async_from_sync_iterator_prototype, "throw",
938                         Builtins::kAsyncFromSyncIteratorPrototypeThrow, 1,
939                         false);
940 
941   InstallToStringTag(isolate(), async_from_sync_iterator_prototype,
942                      "Async-from-Sync Iterator");
943 
944   JSObject::ForceSetPrototype(async_from_sync_iterator_prototype,
945                               async_iterator_prototype);
946 
947   Handle<Map> async_from_sync_iterator_map = factory()->NewMap(
948       JS_ASYNC_FROM_SYNC_ITERATOR_TYPE, JSAsyncFromSyncIterator::kHeaderSize);
949   Map::SetPrototype(isolate(), async_from_sync_iterator_map,
950                     async_from_sync_iterator_prototype);
951   native_context()->set_async_from_sync_iterator_map(
952       *async_from_sync_iterator_map);
953 
954   // Async Generators
955   Handle<JSObject> async_generator_object_prototype = factory()->NewJSObject(
956       isolate()->object_function(), AllocationType::kOld);
957   Handle<JSObject> async_generator_function_prototype = factory()->NewJSObject(
958       isolate()->object_function(), AllocationType::kOld);
959 
960   // %AsyncGenerator% / %AsyncGeneratorFunction%.prototype
961   JSObject::ForceSetPrototype(async_generator_function_prototype, empty);
962 
963   // The value of AsyncGeneratorFunction.prototype.prototype is the
964   //     %AsyncGeneratorPrototype% intrinsic object.
965   // This property has the attributes
966   //     { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
967   JSObject::AddProperty(isolate(), async_generator_function_prototype,
968                         factory()->prototype_string(),
969                         async_generator_object_prototype,
970                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
971   JSObject::AddProperty(isolate(), async_generator_object_prototype,
972                         factory()->constructor_string(),
973                         async_generator_function_prototype,
974                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
975   InstallToStringTag(isolate(), async_generator_function_prototype,
976                      "AsyncGeneratorFunction");
977 
978   // %AsyncGeneratorPrototype%
979   JSObject::ForceSetPrototype(async_generator_object_prototype,
980                               async_iterator_prototype);
981   native_context()->set_initial_async_generator_prototype(
982       *async_generator_object_prototype);
983 
984   InstallToStringTag(isolate(), async_generator_object_prototype,
985                      "AsyncGenerator");
986   SimpleInstallFunction(isolate(), async_generator_object_prototype, "next",
987                         Builtins::kAsyncGeneratorPrototypeNext, 1, false);
988   SimpleInstallFunction(isolate(), async_generator_object_prototype, "return",
989                         Builtins::kAsyncGeneratorPrototypeReturn, 1, false);
990   SimpleInstallFunction(isolate(), async_generator_object_prototype, "throw",
991                         Builtins::kAsyncGeneratorPrototypeThrow, 1, false);
992 
993   // Create maps for generator functions and their prototypes.  Store those
994   // maps in the native context. The "prototype" property descriptor is
995   // writable, non-enumerable, and non-configurable (as per ES6 draft
996   // 04-14-15, section 25.2.4.3).
997   // Async Generator functions do not have "caller" or "arguments" accessors.
998   Handle<Map> map;
999   map = CreateNonConstructorMap(isolate(), isolate()->strict_function_map(),
1000                                 async_generator_function_prototype,
1001                                 "AsyncGeneratorFunction");
1002   native_context()->set_async_generator_function_map(*map);
1003 
1004   map = CreateNonConstructorMap(
1005       isolate(), isolate()->strict_function_with_name_map(),
1006       async_generator_function_prototype, "AsyncGeneratorFunction with name");
1007   native_context()->set_async_generator_function_with_name_map(*map);
1008 
1009   map =
1010       CreateNonConstructorMap(isolate(), strict_function_with_home_object_map_,
1011                               async_generator_function_prototype,
1012                               "AsyncGeneratorFunction with home object");
1013   native_context()->set_async_generator_function_with_home_object_map(*map);
1014 
1015   map = CreateNonConstructorMap(
1016       isolate(), strict_function_with_name_and_home_object_map_,
1017       async_generator_function_prototype,
1018       "AsyncGeneratorFunction with name and home object");
1019   native_context()->set_async_generator_function_with_name_and_home_object_map(
1020       *map);
1021 
1022   Handle<JSFunction> object_function(native_context()->object_function(),
1023                                      isolate());
1024   Handle<Map> async_generator_object_prototype_map = Map::Create(isolate(), 0);
1025   Map::SetPrototype(isolate(), async_generator_object_prototype_map,
1026                     async_generator_object_prototype);
1027   native_context()->set_async_generator_object_prototype_map(
1028       *async_generator_object_prototype_map);
1029 }
1030 
CreateAsyncFunctionMaps(Handle<JSFunction> empty)1031 void Genesis::CreateAsyncFunctionMaps(Handle<JSFunction> empty) {
1032   // %AsyncFunctionPrototype% intrinsic
1033   Handle<JSObject> async_function_prototype = factory()->NewJSObject(
1034       isolate()->object_function(), AllocationType::kOld);
1035   JSObject::ForceSetPrototype(async_function_prototype, empty);
1036 
1037   InstallToStringTag(isolate(), async_function_prototype, "AsyncFunction");
1038 
1039   Handle<Map> map =
1040       Map::Copy(isolate(), isolate()->strict_function_without_prototype_map(),
1041                 "AsyncFunction");
1042   Map::SetPrototype(isolate(), map, async_function_prototype);
1043   native_context()->set_async_function_map(*map);
1044 
1045   map = Map::Copy(isolate(), isolate()->method_with_name_map(),
1046                   "AsyncFunction with name");
1047   Map::SetPrototype(isolate(), map, async_function_prototype);
1048   native_context()->set_async_function_with_name_map(*map);
1049 
1050   map = Map::Copy(isolate(), isolate()->method_with_home_object_map(),
1051                   "AsyncFunction with home object");
1052   Map::SetPrototype(isolate(), map, async_function_prototype);
1053   native_context()->set_async_function_with_home_object_map(*map);
1054 
1055   map = Map::Copy(isolate(), isolate()->method_with_name_and_home_object_map(),
1056                   "AsyncFunction with name and home object");
1057   Map::SetPrototype(isolate(), map, async_function_prototype);
1058   native_context()->set_async_function_with_name_and_home_object_map(*map);
1059 }
1060 
CreateJSProxyMaps()1061 void Genesis::CreateJSProxyMaps() {
1062   // Allocate maps for all Proxy types.
1063   // Next to the default proxy, we need maps indicating callable and
1064   // constructable proxies.
1065   Handle<Map> proxy_map = factory()->NewMap(JS_PROXY_TYPE, JSProxy::kSize,
1066                                             TERMINAL_FAST_ELEMENTS_KIND);
1067   proxy_map->set_is_dictionary_map(true);
1068   proxy_map->set_may_have_interesting_symbols(true);
1069   native_context()->set_proxy_map(*proxy_map);
1070 
1071   Handle<Map> proxy_callable_map =
1072       Map::Copy(isolate_, proxy_map, "callable Proxy");
1073   proxy_callable_map->set_is_callable(true);
1074   native_context()->set_proxy_callable_map(*proxy_callable_map);
1075   proxy_callable_map->SetConstructor(native_context()->function_function());
1076 
1077   Handle<Map> proxy_constructor_map =
1078       Map::Copy(isolate_, proxy_callable_map, "constructor Proxy");
1079   proxy_constructor_map->set_is_constructor(true);
1080   native_context()->set_proxy_constructor_map(*proxy_constructor_map);
1081 
1082   {
1083     Handle<Map> map =
1084         factory()->NewMap(JS_OBJECT_TYPE, JSProxyRevocableResult::kSize,
1085                           TERMINAL_FAST_ELEMENTS_KIND, 2);
1086     Map::EnsureDescriptorSlack(isolate_, map, 2);
1087 
1088     {  // proxy
1089       Descriptor d = Descriptor::DataField(isolate(), factory()->proxy_string(),
1090                                            JSProxyRevocableResult::kProxyIndex,
1091                                            NONE, Representation::Tagged());
1092       map->AppendDescriptor(isolate(), &d);
1093     }
1094     {  // revoke
1095       Descriptor d = Descriptor::DataField(
1096           isolate(), factory()->revoke_string(),
1097           JSProxyRevocableResult::kRevokeIndex, NONE, Representation::Tagged());
1098       map->AppendDescriptor(isolate(), &d);
1099     }
1100 
1101     Map::SetPrototype(isolate(), map, isolate()->initial_object_prototype());
1102     map->SetConstructor(native_context()->object_function());
1103 
1104     native_context()->set_proxy_revocable_result_map(*map);
1105   }
1106 }
1107 
1108 namespace {
ReplaceAccessors(Isolate * isolate,Handle<Map> map,Handle<String> name,PropertyAttributes attributes,Handle<AccessorPair> accessor_pair)1109 void ReplaceAccessors(Isolate* isolate, Handle<Map> map, Handle<String> name,
1110                       PropertyAttributes attributes,
1111                       Handle<AccessorPair> accessor_pair) {
1112   DescriptorArray descriptors = map->instance_descriptors(kRelaxedLoad);
1113   InternalIndex entry = descriptors.SearchWithCache(isolate, *name, *map);
1114   Descriptor d = Descriptor::AccessorConstant(name, accessor_pair, attributes);
1115   descriptors.Replace(entry, &d);
1116 }
1117 }  // namespace
1118 
AddRestrictedFunctionProperties(Handle<JSFunction> empty)1119 void Genesis::AddRestrictedFunctionProperties(Handle<JSFunction> empty) {
1120   PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
1121   Handle<JSFunction> thrower = GetThrowTypeErrorIntrinsic();
1122   Handle<AccessorPair> accessors = factory()->NewAccessorPair();
1123   accessors->set_getter(*thrower);
1124   accessors->set_setter(*thrower);
1125 
1126   Handle<Map> map(empty->map(), isolate());
1127   ReplaceAccessors(isolate(), map, factory()->arguments_string(), rw_attribs,
1128                    accessors);
1129   ReplaceAccessors(isolate(), map, factory()->caller_string(), rw_attribs,
1130                    accessors);
1131 }
1132 
AddToWeakNativeContextList(Isolate * isolate,Context context)1133 static void AddToWeakNativeContextList(Isolate* isolate, Context context) {
1134   DCHECK(context.IsNativeContext());
1135   Heap* heap = isolate->heap();
1136 #ifdef DEBUG
1137   {  // NOLINT
1138     DCHECK(context.next_context_link().IsUndefined(isolate));
1139     // Check that context is not in the list yet.
1140     for (Object current = heap->native_contexts_list();
1141          !current.IsUndefined(isolate);
1142          current = Context::cast(current).next_context_link()) {
1143       DCHECK(current != context);
1144     }
1145   }
1146 #endif
1147   context.set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list(),
1148               UPDATE_WEAK_WRITE_BARRIER);
1149   heap->set_native_contexts_list(context);
1150 }
1151 
CreateRoots()1152 void Genesis::CreateRoots() {
1153   // Allocate the native context FixedArray first and then patch the
1154   // closure and extension object later (we need the empty function
1155   // and the global object, but in order to create those, we need the
1156   // native context).
1157   native_context_ = factory()->NewNativeContext();
1158 
1159   AddToWeakNativeContextList(isolate(), *native_context());
1160   isolate()->set_context(*native_context());
1161 
1162   // Allocate the message listeners object.
1163   {
1164     Handle<TemplateList> list = TemplateList::New(isolate(), 1);
1165     native_context()->set_message_listeners(*list);
1166   }
1167 }
1168 
InstallGlobalThisBinding()1169 void Genesis::InstallGlobalThisBinding() {
1170   Handle<ScriptContextTable> script_contexts(
1171       native_context()->script_context_table(), isolate());
1172   Handle<ScopeInfo> scope_info =
1173       ReadOnlyRoots(isolate()).global_this_binding_scope_info_handle();
1174   Handle<Context> context =
1175       factory()->NewScriptContext(native_context(), scope_info);
1176 
1177   // Go ahead and hook it up while we're at it.
1178   int slot = scope_info->ReceiverContextSlotIndex();
1179   DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
1180   context->set(slot, native_context()->global_proxy());
1181 
1182   Handle<ScriptContextTable> new_script_contexts =
1183       ScriptContextTable::Extend(script_contexts, context);
1184   native_context()->set_script_context_table(*new_script_contexts);
1185 }
1186 
CreateNewGlobals(v8::Local<v8::ObjectTemplate> global_proxy_template,Handle<JSGlobalProxy> global_proxy)1187 Handle<JSGlobalObject> Genesis::CreateNewGlobals(
1188     v8::Local<v8::ObjectTemplate> global_proxy_template,
1189     Handle<JSGlobalProxy> global_proxy) {
1190   // The argument global_proxy_template aka data is an ObjectTemplateInfo.
1191   // It has a constructor pointer that points at global_constructor which is a
1192   // FunctionTemplateInfo.
1193   // The global_proxy_constructor is used to (re)initialize the
1194   // global_proxy. The global_proxy_constructor also has a prototype_template
1195   // pointer that points at js_global_object_template which is an
1196   // ObjectTemplateInfo.
1197   // That in turn has a constructor pointer that points at
1198   // js_global_object_constructor which is a FunctionTemplateInfo.
1199   // js_global_object_constructor is used to make js_global_object_function
1200   // js_global_object_function is used to make the new global_object.
1201   //
1202   // --- G l o b a l ---
1203   // Step 1: Create a fresh JSGlobalObject.
1204   Handle<JSFunction> js_global_object_function;
1205   Handle<ObjectTemplateInfo> js_global_object_template;
1206   if (!global_proxy_template.IsEmpty()) {
1207     // Get prototype template of the global_proxy_template.
1208     Handle<ObjectTemplateInfo> data =
1209         v8::Utils::OpenHandle(*global_proxy_template);
1210     Handle<FunctionTemplateInfo> global_constructor =
1211         Handle<FunctionTemplateInfo>(
1212             FunctionTemplateInfo::cast(data->constructor()), isolate());
1213     Handle<Object> proto_template(global_constructor->GetPrototypeTemplate(),
1214                                   isolate());
1215     if (!proto_template->IsUndefined(isolate())) {
1216       js_global_object_template =
1217           Handle<ObjectTemplateInfo>::cast(proto_template);
1218     }
1219   }
1220 
1221   if (js_global_object_template.is_null()) {
1222     Handle<String> name = factory()->empty_string();
1223     Handle<JSObject> prototype =
1224         factory()->NewFunctionPrototype(isolate()->object_function());
1225     NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
1226         name, prototype, JS_GLOBAL_OBJECT_TYPE, JSGlobalObject::kHeaderSize, 0,
1227         Builtins::kIllegal, MUTABLE);
1228     js_global_object_function = factory()->NewFunction(args);
1229 #ifdef DEBUG
1230     LookupIterator it(isolate(), prototype, factory()->constructor_string(),
1231                       LookupIterator::OWN_SKIP_INTERCEPTOR);
1232     Handle<Object> value = Object::GetProperty(&it).ToHandleChecked();
1233     DCHECK(it.IsFound());
1234     DCHECK_EQ(*isolate()->object_function(), *value);
1235 #endif
1236   } else {
1237     Handle<FunctionTemplateInfo> js_global_object_constructor(
1238         FunctionTemplateInfo::cast(js_global_object_template->constructor()),
1239         isolate());
1240     js_global_object_function = ApiNatives::CreateApiFunction(
1241         isolate(), isolate()->native_context(), js_global_object_constructor,
1242         factory()->the_hole_value(), JS_GLOBAL_OBJECT_TYPE);
1243   }
1244 
1245   js_global_object_function->initial_map().set_is_prototype_map(true);
1246   js_global_object_function->initial_map().set_is_dictionary_map(true);
1247   js_global_object_function->initial_map().set_may_have_interesting_symbols(
1248       true);
1249   Handle<JSGlobalObject> global_object =
1250       factory()->NewJSGlobalObject(js_global_object_function);
1251 
1252   // Step 2: (re)initialize the global proxy object.
1253   Handle<JSFunction> global_proxy_function;
1254   if (global_proxy_template.IsEmpty()) {
1255     Handle<String> name = factory()->empty_string();
1256     NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
1257         name, factory()->the_hole_value(), JS_GLOBAL_PROXY_TYPE,
1258         JSGlobalProxy::SizeWithEmbedderFields(0), 0, Builtins::kIllegal,
1259         MUTABLE);
1260     global_proxy_function = factory()->NewFunction(args);
1261   } else {
1262     Handle<ObjectTemplateInfo> data =
1263         v8::Utils::OpenHandle(*global_proxy_template);
1264     Handle<FunctionTemplateInfo> global_constructor(
1265         FunctionTemplateInfo::cast(data->constructor()), isolate());
1266     global_proxy_function = ApiNatives::CreateApiFunction(
1267         isolate(), isolate()->native_context(), global_constructor,
1268         factory()->the_hole_value(), JS_GLOBAL_PROXY_TYPE);
1269   }
1270   global_proxy_function->initial_map().set_is_access_check_needed(true);
1271   global_proxy_function->initial_map().set_may_have_interesting_symbols(true);
1272   native_context()->set_global_proxy_function(*global_proxy_function);
1273 
1274   // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
1275   // Return the global proxy.
1276 
1277   factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
1278 
1279   // Set the native context for the global object.
1280   global_object->set_native_context(*native_context());
1281   global_object->set_global_proxy(*global_proxy);
1282   // Set the native context of the global proxy.
1283   global_proxy->set_native_context(*native_context());
1284   // Set the global proxy of the native context. If the native context has been
1285   // deserialized, the global proxy is already correctly set up by the
1286   // deserializer. Otherwise it's undefined.
1287   DCHECK(native_context()
1288              ->get(Context::GLOBAL_PROXY_INDEX)
1289              .IsUndefined(isolate()) ||
1290          native_context()->global_proxy_object() == *global_proxy);
1291   native_context()->set_global_proxy_object(*global_proxy);
1292 
1293   return global_object;
1294 }
1295 
HookUpGlobalProxy(Handle<JSGlobalProxy> global_proxy)1296 void Genesis::HookUpGlobalProxy(Handle<JSGlobalProxy> global_proxy) {
1297   // Re-initialize the global proxy with the global proxy function from the
1298   // snapshot, and then set up the link to the native context.
1299   Handle<JSFunction> global_proxy_function(
1300       native_context()->global_proxy_function(), isolate());
1301   factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
1302   Handle<JSObject> global_object(
1303       JSObject::cast(native_context()->global_object()), isolate());
1304   JSObject::ForceSetPrototype(global_proxy, global_object);
1305   global_proxy->set_native_context(*native_context());
1306   DCHECK(native_context()->global_proxy() == *global_proxy);
1307 }
1308 
HookUpGlobalObject(Handle<JSGlobalObject> global_object)1309 void Genesis::HookUpGlobalObject(Handle<JSGlobalObject> global_object) {
1310   Handle<JSGlobalObject> global_object_from_snapshot(
1311       JSGlobalObject::cast(native_context()->extension()), isolate());
1312   native_context()->set_extension(*global_object);
1313   native_context()->set_security_token(*global_object);
1314 
1315   TransferNamedProperties(global_object_from_snapshot, global_object);
1316   TransferIndexedProperties(global_object_from_snapshot, global_object);
1317 }
1318 
InstallWithIntrinsicDefaultProto(Isolate * isolate,Handle<JSFunction> function,int context_index)1319 static void InstallWithIntrinsicDefaultProto(Isolate* isolate,
1320                                              Handle<JSFunction> function,
1321                                              int context_index) {
1322   Handle<Smi> index(Smi::FromInt(context_index), isolate);
1323   JSObject::AddProperty(isolate, function,
1324                         isolate->factory()->native_context_index_symbol(),
1325                         index, NONE);
1326   isolate->native_context()->set(context_index, *function);
1327 }
1328 
InstallError(Isolate * isolate,Handle<JSObject> global,Handle<String> name,int context_index,Builtins::Name error_constructor=Builtins::kErrorConstructor,int error_function_length=1,int in_object_properties=2)1329 static void InstallError(
1330     Isolate* isolate, Handle<JSObject> global, Handle<String> name,
1331     int context_index,
1332     Builtins::Name error_constructor = Builtins::kErrorConstructor,
1333     int error_function_length = 1, int in_object_properties = 2) {
1334   Factory* factory = isolate->factory();
1335 
1336   // Most Error objects consist of a message and a stack trace.
1337   // Reserve two in-object properties for these.
1338   const int kErrorObjectSize =
1339       JSObject::kHeaderSize + in_object_properties * kTaggedSize;
1340   Handle<JSFunction> error_fun = InstallFunction(
1341       isolate, global, name, JS_ERROR_TYPE, kErrorObjectSize,
1342       in_object_properties, factory->the_hole_value(), error_constructor);
1343   error_fun->shared().DontAdaptArguments();
1344   error_fun->shared().set_length(error_function_length);
1345 
1346   if (context_index == Context::ERROR_FUNCTION_INDEX) {
1347     SimpleInstallFunction(isolate, error_fun, "captureStackTrace",
1348                           Builtins::kErrorCaptureStackTrace, 2, false);
1349   }
1350 
1351   InstallWithIntrinsicDefaultProto(isolate, error_fun, context_index);
1352 
1353   {
1354     // Setup %XXXErrorPrototype%.
1355     Handle<JSObject> prototype(JSObject::cast(error_fun->instance_prototype()),
1356                                isolate);
1357 
1358     JSObject::AddProperty(isolate, prototype, factory->name_string(), name,
1359                           DONT_ENUM);
1360     JSObject::AddProperty(isolate, prototype, factory->message_string(),
1361                           factory->empty_string(), DONT_ENUM);
1362 
1363     if (context_index == Context::ERROR_FUNCTION_INDEX) {
1364       Handle<JSFunction> to_string_fun =
1365           SimpleInstallFunction(isolate, prototype, "toString",
1366                                 Builtins::kErrorPrototypeToString, 0, true);
1367       isolate->native_context()->set_error_to_string(*to_string_fun);
1368       isolate->native_context()->set_initial_error_prototype(*prototype);
1369     } else {
1370       Handle<JSFunction> global_error = isolate->error_function();
1371       CHECK(JSReceiver::SetPrototype(error_fun, global_error, false,
1372                                      kThrowOnError)
1373                 .FromMaybe(false));
1374       CHECK(JSReceiver::SetPrototype(prototype,
1375                                      handle(global_error->prototype(), isolate),
1376                                      false, kThrowOnError)
1377                 .FromMaybe(false));
1378     }
1379   }
1380 
1381   Handle<Map> initial_map(error_fun->initial_map(), isolate);
1382   Map::EnsureDescriptorSlack(isolate, initial_map, 1);
1383 
1384   {
1385     Handle<AccessorInfo> info = factory->error_stack_accessor();
1386     Descriptor d = Descriptor::AccessorConstant(handle(info->name(), isolate),
1387                                                 info, DONT_ENUM);
1388     initial_map->AppendDescriptor(isolate, &d);
1389   }
1390 }
1391 
1392 // This is only called if we are not using snapshots.  The equivalent
1393 // work in the snapshot case is done in HookUpGlobalObject.
InitializeGlobal(Handle<JSGlobalObject> global_object,Handle<JSFunction> empty_function)1394 void Genesis::InitializeGlobal(Handle<JSGlobalObject> global_object,
1395                                Handle<JSFunction> empty_function) {
1396   // --- N a t i v e   C o n t e x t ---
1397   native_context()->set_previous(Context());
1398   // Set extension and global object.
1399   native_context()->set_extension(*global_object);
1400   // Security setup: Set the security token of the native context to the global
1401   // object. This makes the security check between two different contexts fail
1402   // by default even in case of global object reinitialization.
1403   native_context()->set_security_token(*global_object);
1404 
1405   Factory* factory = isolate_->factory();
1406 
1407   {  // -- C o n t e x t
1408     Handle<Map> map =
1409         factory->NewMap(FUNCTION_CONTEXT_TYPE, kVariableSizeSentinel);
1410     map->set_native_context(*native_context());
1411     native_context()->set_function_context_map(*map);
1412 
1413     map = factory->NewMap(CATCH_CONTEXT_TYPE, kVariableSizeSentinel);
1414     map->set_native_context(*native_context());
1415     native_context()->set_catch_context_map(*map);
1416 
1417     map = factory->NewMap(WITH_CONTEXT_TYPE, kVariableSizeSentinel);
1418     map->set_native_context(*native_context());
1419     native_context()->set_with_context_map(*map);
1420 
1421     map = factory->NewMap(DEBUG_EVALUATE_CONTEXT_TYPE, kVariableSizeSentinel);
1422     map->set_native_context(*native_context());
1423     native_context()->set_debug_evaluate_context_map(*map);
1424 
1425     map = factory->NewMap(BLOCK_CONTEXT_TYPE, kVariableSizeSentinel);
1426     map->set_native_context(*native_context());
1427     native_context()->set_block_context_map(*map);
1428 
1429     map = factory->NewMap(MODULE_CONTEXT_TYPE, kVariableSizeSentinel);
1430     map->set_native_context(*native_context());
1431     native_context()->set_module_context_map(*map);
1432 
1433     map = factory->NewMap(AWAIT_CONTEXT_TYPE, kVariableSizeSentinel);
1434     map->set_native_context(*native_context());
1435     native_context()->set_await_context_map(*map);
1436 
1437     map = factory->NewMap(SCRIPT_CONTEXT_TYPE, kVariableSizeSentinel);
1438     map->set_native_context(*native_context());
1439     native_context()->set_script_context_map(*map);
1440 
1441     map = factory->NewMap(EVAL_CONTEXT_TYPE, kVariableSizeSentinel);
1442     map->set_native_context(*native_context());
1443     native_context()->set_eval_context_map(*map);
1444 
1445     Handle<ScriptContextTable> script_context_table =
1446         factory->NewScriptContextTable();
1447     native_context()->set_script_context_table(*script_context_table);
1448     InstallGlobalThisBinding();
1449   }
1450 
1451   {  // --- O b j e c t ---
1452     Handle<String> object_name = factory->Object_string();
1453     Handle<JSFunction> object_function = isolate_->object_function();
1454     JSObject::AddProperty(isolate_, global_object, object_name, object_function,
1455                           DONT_ENUM);
1456 
1457     SimpleInstallFunction(isolate_, object_function, "assign",
1458                           Builtins::kObjectAssign, 2, false);
1459     SimpleInstallFunction(isolate_, object_function, "getOwnPropertyDescriptor",
1460                           Builtins::kObjectGetOwnPropertyDescriptor, 2, false);
1461     SimpleInstallFunction(isolate_, object_function,
1462                           "getOwnPropertyDescriptors",
1463                           Builtins::kObjectGetOwnPropertyDescriptors, 1, false);
1464     SimpleInstallFunction(isolate_, object_function, "getOwnPropertyNames",
1465                           Builtins::kObjectGetOwnPropertyNames, 1, true);
1466     SimpleInstallFunction(isolate_, object_function, "getOwnPropertySymbols",
1467                           Builtins::kObjectGetOwnPropertySymbols, 1, false);
1468     SimpleInstallFunction(isolate_, object_function, "is", Builtins::kObjectIs,
1469                           2, true);
1470     SimpleInstallFunction(isolate_, object_function, "preventExtensions",
1471                           Builtins::kObjectPreventExtensions, 1, true);
1472     SimpleInstallFunction(isolate_, object_function, "seal",
1473                           Builtins::kObjectSeal, 1, false);
1474 
1475     Handle<JSFunction> object_create = SimpleInstallFunction(
1476         isolate_, object_function, "create", Builtins::kObjectCreate, 2, false);
1477     native_context()->set_object_create(*object_create);
1478 
1479     SimpleInstallFunction(isolate_, object_function, "defineProperties",
1480                           Builtins::kObjectDefineProperties, 2, true);
1481 
1482     SimpleInstallFunction(isolate_, object_function, "defineProperty",
1483                           Builtins::kObjectDefineProperty, 3, true);
1484 
1485     SimpleInstallFunction(isolate_, object_function, "freeze",
1486                           Builtins::kObjectFreeze, 1, false);
1487 
1488     SimpleInstallFunction(isolate_, object_function, "getPrototypeOf",
1489                           Builtins::kObjectGetPrototypeOf, 1, true);
1490     SimpleInstallFunction(isolate_, object_function, "setPrototypeOf",
1491                           Builtins::kObjectSetPrototypeOf, 2, true);
1492 
1493     SimpleInstallFunction(isolate_, object_function, "isExtensible",
1494                           Builtins::kObjectIsExtensible, 1, true);
1495     SimpleInstallFunction(isolate_, object_function, "isFrozen",
1496                           Builtins::kObjectIsFrozen, 1, false);
1497 
1498     SimpleInstallFunction(isolate_, object_function, "isSealed",
1499                           Builtins::kObjectIsSealed, 1, false);
1500 
1501     SimpleInstallFunction(isolate_, object_function, "keys",
1502                           Builtins::kObjectKeys, 1, true);
1503     SimpleInstallFunction(isolate_, object_function, "entries",
1504                           Builtins::kObjectEntries, 1, true);
1505     SimpleInstallFunction(isolate_, object_function, "fromEntries",
1506                           Builtins::kObjectFromEntries, 1, false);
1507     SimpleInstallFunction(isolate_, object_function, "values",
1508                           Builtins::kObjectValues, 1, true);
1509 
1510     SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
1511                           "__defineGetter__", Builtins::kObjectDefineGetter, 2,
1512                           true);
1513     SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
1514                           "__defineSetter__", Builtins::kObjectDefineSetter, 2,
1515                           true);
1516     SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
1517                           "hasOwnProperty",
1518                           Builtins::kObjectPrototypeHasOwnProperty, 1, true);
1519     SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
1520                           "__lookupGetter__", Builtins::kObjectLookupGetter, 1,
1521                           true);
1522     SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
1523                           "__lookupSetter__", Builtins::kObjectLookupSetter, 1,
1524                           true);
1525     SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
1526                           "isPrototypeOf",
1527                           Builtins::kObjectPrototypeIsPrototypeOf, 1, true);
1528     SimpleInstallFunction(
1529         isolate_, isolate_->initial_object_prototype(), "propertyIsEnumerable",
1530         Builtins::kObjectPrototypePropertyIsEnumerable, 1, false);
1531     Handle<JSFunction> object_to_string = SimpleInstallFunction(
1532         isolate_, isolate_->initial_object_prototype(), "toString",
1533         Builtins::kObjectPrototypeToString, 0, true);
1534     native_context()->set_object_to_string(*object_to_string);
1535     Handle<JSFunction> object_value_of = SimpleInstallFunction(
1536         isolate_, isolate_->initial_object_prototype(), "valueOf",
1537         Builtins::kObjectPrototypeValueOf, 0, true);
1538     native_context()->set_object_value_of_function(*object_value_of);
1539 
1540     SimpleInstallGetterSetter(
1541         isolate_, isolate_->initial_object_prototype(), factory->proto_string(),
1542         Builtins::kObjectPrototypeGetProto, Builtins::kObjectPrototypeSetProto);
1543 
1544     SimpleInstallFunction(isolate_, isolate_->initial_object_prototype(),
1545                           "toLocaleString",
1546                           Builtins::kObjectPrototypeToLocaleString, 0, true);
1547   }
1548 
1549   Handle<JSObject> global(native_context()->global_object(), isolate());
1550 
1551   {  // --- F u n c t i o n ---
1552     Handle<JSFunction> prototype = empty_function;
1553     Handle<JSFunction> function_fun =
1554         InstallFunction(isolate_, global, "Function", JS_FUNCTION_TYPE,
1555                         JSFunction::kSizeWithPrototype, 0, prototype,
1556                         Builtins::kFunctionConstructor);
1557     // Function instances are sloppy by default.
1558     function_fun->set_prototype_or_initial_map(
1559         *isolate_->sloppy_function_map());
1560     function_fun->shared().DontAdaptArguments();
1561     function_fun->shared().set_length(1);
1562     InstallWithIntrinsicDefaultProto(isolate_, function_fun,
1563                                      Context::FUNCTION_FUNCTION_INDEX);
1564 
1565     // Setup the methods on the %FunctionPrototype%.
1566     JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
1567                           function_fun, DONT_ENUM);
1568     SimpleInstallFunction(isolate_, prototype, "apply",
1569                           Builtins::kFunctionPrototypeApply, 2, false);
1570     SimpleInstallFunction(isolate_, prototype, "bind",
1571                           Builtins::kFastFunctionPrototypeBind, 1, false);
1572     SimpleInstallFunction(isolate_, prototype, "call",
1573                           Builtins::kFunctionPrototypeCall, 1, false);
1574     Handle<JSFunction> function_to_string =
1575         SimpleInstallFunction(isolate_, prototype, "toString",
1576                               Builtins::kFunctionPrototypeToString, 0, false);
1577     native_context()->set_function_to_string(*function_to_string);
1578 
1579     // Install the @@hasInstance function.
1580     Handle<JSFunction> has_instance = InstallFunctionAtSymbol(
1581         isolate_, prototype, factory->has_instance_symbol(),
1582         "[Symbol.hasInstance]", Builtins::kFunctionPrototypeHasInstance, 1,
1583         true,
1584         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
1585     native_context()->set_function_has_instance(*has_instance);
1586 
1587     // Complete setting up function maps.
1588     {
1589       isolate_->sloppy_function_map()->SetConstructor(*function_fun);
1590       isolate_->sloppy_function_with_name_map()->SetConstructor(*function_fun);
1591       isolate_->sloppy_function_with_readonly_prototype_map()->SetConstructor(
1592           *function_fun);
1593 
1594       isolate_->strict_function_map()->SetConstructor(*function_fun);
1595       isolate_->strict_function_with_name_map()->SetConstructor(*function_fun);
1596       strict_function_with_home_object_map_->SetConstructor(*function_fun);
1597       strict_function_with_name_and_home_object_map_->SetConstructor(
1598           *function_fun);
1599       isolate_->strict_function_with_readonly_prototype_map()->SetConstructor(
1600           *function_fun);
1601 
1602       isolate_->class_function_map()->SetConstructor(*function_fun);
1603     }
1604   }
1605 
1606   Handle<JSFunction> array_prototype_to_string_fun;
1607   {  // --- A r r a y ---
1608     Handle<JSFunction> array_function = InstallFunction(
1609         isolate_, global, "Array", JS_ARRAY_TYPE, JSArray::kHeaderSize, 0,
1610         isolate_->initial_object_prototype(), Builtins::kArrayConstructor);
1611     array_function->shared().DontAdaptArguments();
1612 
1613     // This seems a bit hackish, but we need to make sure Array.length
1614     // is 1.
1615     array_function->shared().set_length(1);
1616 
1617     Handle<Map> initial_map(array_function->initial_map(), isolate());
1618 
1619     // This assert protects an optimization in
1620     // HGraphBuilder::JSArrayBuilder::EmitMapCode()
1621     DCHECK(initial_map->elements_kind() == GetInitialFastElementsKind());
1622     Map::EnsureDescriptorSlack(isolate_, initial_map, 1);
1623 
1624     PropertyAttributes attribs =
1625         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
1626 
1627     STATIC_ASSERT(JSArray::kLengthDescriptorIndex == 0);
1628     {  // Add length.
1629       Descriptor d = Descriptor::AccessorConstant(
1630           factory->length_string(), factory->array_length_accessor(), attribs);
1631       initial_map->AppendDescriptor(isolate(), &d);
1632     }
1633 
1634     InstallWithIntrinsicDefaultProto(isolate_, array_function,
1635                                      Context::ARRAY_FUNCTION_INDEX);
1636     InstallSpeciesGetter(isolate_, array_function);
1637 
1638     // Cache the array maps, needed by ArrayConstructorStub
1639     CacheInitialJSArrayMaps(isolate_, native_context(), initial_map);
1640 
1641     // Set up %ArrayPrototype%.
1642     // The %ArrayPrototype% has TERMINAL_FAST_ELEMENTS_KIND in order to ensure
1643     // that constant functions stay constant after turning prototype to setup
1644     // mode and back.
1645     Handle<JSArray> proto = factory->NewJSArray(0, TERMINAL_FAST_ELEMENTS_KIND,
1646                                                 AllocationType::kOld);
1647     JSFunction::SetPrototype(array_function, proto);
1648     native_context()->set_initial_array_prototype(*proto);
1649 
1650     SimpleInstallFunction(isolate_, array_function, "isArray",
1651                           Builtins::kArrayIsArray, 1, true);
1652     SimpleInstallFunction(isolate_, array_function, "from",
1653                           Builtins::kArrayFrom, 1, false);
1654     SimpleInstallFunction(isolate_, array_function, "of", Builtins::kArrayOf, 0,
1655                           false);
1656 
1657     JSObject::AddProperty(isolate_, proto, factory->constructor_string(),
1658                           array_function, DONT_ENUM);
1659 
1660     SimpleInstallFunction(isolate_, proto, "concat", Builtins::kArrayConcat, 1,
1661                           false);
1662     SimpleInstallFunction(isolate_, proto, "copyWithin",
1663                           Builtins::kArrayPrototypeCopyWithin, 2, false);
1664     SimpleInstallFunction(isolate_, proto, "fill",
1665                           Builtins::kArrayPrototypeFill, 1, false);
1666     SimpleInstallFunction(isolate_, proto, "find",
1667                           Builtins::kArrayPrototypeFind, 1, false);
1668     SimpleInstallFunction(isolate_, proto, "findIndex",
1669                           Builtins::kArrayPrototypeFindIndex, 1, false);
1670     SimpleInstallFunction(isolate_, proto, "lastIndexOf",
1671                           Builtins::kArrayPrototypeLastIndexOf, 1, false);
1672     SimpleInstallFunction(isolate_, proto, "pop", Builtins::kArrayPrototypePop,
1673                           0, false);
1674     SimpleInstallFunction(isolate_, proto, "push",
1675                           Builtins::kArrayPrototypePush, 1, false);
1676     SimpleInstallFunction(isolate_, proto, "reverse",
1677                           Builtins::kArrayPrototypeReverse, 0, false);
1678     SimpleInstallFunction(isolate_, proto, "shift",
1679                           Builtins::kArrayPrototypeShift, 0, false);
1680     SimpleInstallFunction(isolate_, proto, "unshift",
1681                           Builtins::kArrayPrototypeUnshift, 1, false);
1682     SimpleInstallFunction(isolate_, proto, "slice",
1683                           Builtins::kArrayPrototypeSlice, 2, false);
1684     SimpleInstallFunction(isolate_, proto, "sort",
1685                           Builtins::kArrayPrototypeSort, 1, false);
1686     SimpleInstallFunction(isolate_, proto, "splice",
1687                           Builtins::kArrayPrototypeSplice, 2, false);
1688     SimpleInstallFunction(isolate_, proto, "includes", Builtins::kArrayIncludes,
1689                           1, false);
1690     SimpleInstallFunction(isolate_, proto, "indexOf", Builtins::kArrayIndexOf,
1691                           1, false);
1692     SimpleInstallFunction(isolate_, proto, "join",
1693                           Builtins::kArrayPrototypeJoin, 1, false);
1694 
1695     {  // Set up iterator-related properties.
1696       Handle<JSFunction> keys = InstallFunctionWithBuiltinId(
1697           isolate_, proto, "keys", Builtins::kArrayPrototypeKeys, 0, true);
1698       native_context()->set_array_keys_iterator(*keys);
1699 
1700       Handle<JSFunction> entries = InstallFunctionWithBuiltinId(
1701           isolate_, proto, "entries", Builtins::kArrayPrototypeEntries, 0,
1702           true);
1703       native_context()->set_array_entries_iterator(*entries);
1704 
1705       Handle<JSFunction> values = InstallFunctionWithBuiltinId(
1706           isolate_, proto, "values", Builtins::kArrayPrototypeValues, 0, true);
1707       JSObject::AddProperty(isolate_, proto, factory->iterator_symbol(), values,
1708                             DONT_ENUM);
1709       native_context()->set_array_values_iterator(*values);
1710     }
1711 
1712     Handle<JSFunction> for_each_fun = SimpleInstallFunction(
1713         isolate_, proto, "forEach", Builtins::kArrayForEach, 1, false);
1714     native_context()->set_array_for_each_iterator(*for_each_fun);
1715     SimpleInstallFunction(isolate_, proto, "filter", Builtins::kArrayFilter, 1,
1716                           false);
1717     SimpleInstallFunction(isolate_, proto, "flat",
1718                           Builtins::kArrayPrototypeFlat, 0, false);
1719     SimpleInstallFunction(isolate_, proto, "flatMap",
1720                           Builtins::kArrayPrototypeFlatMap, 1, false);
1721     SimpleInstallFunction(isolate_, proto, "map", Builtins::kArrayMap, 1,
1722                           false);
1723     SimpleInstallFunction(isolate_, proto, "every", Builtins::kArrayEvery, 1,
1724                           false);
1725     SimpleInstallFunction(isolate_, proto, "some", Builtins::kArraySome, 1,
1726                           false);
1727     SimpleInstallFunction(isolate_, proto, "reduce", Builtins::kArrayReduce, 1,
1728                           false);
1729     SimpleInstallFunction(isolate_, proto, "reduceRight",
1730                           Builtins::kArrayReduceRight, 1, false);
1731     SimpleInstallFunction(isolate_, proto, "toLocaleString",
1732                           Builtins::kArrayPrototypeToLocaleString, 0, false);
1733     array_prototype_to_string_fun =
1734         SimpleInstallFunction(isolate_, proto, "toString",
1735                               Builtins::kArrayPrototypeToString, 0, false);
1736 
1737     Handle<JSObject> unscopables = factory->NewJSObjectWithNullProto();
1738     InstallTrueValuedProperty(isolate_, unscopables, "copyWithin");
1739     InstallTrueValuedProperty(isolate_, unscopables, "entries");
1740     InstallTrueValuedProperty(isolate_, unscopables, "fill");
1741     InstallTrueValuedProperty(isolate_, unscopables, "find");
1742     InstallTrueValuedProperty(isolate_, unscopables, "findIndex");
1743     InstallTrueValuedProperty(isolate_, unscopables, "flat");
1744     InstallTrueValuedProperty(isolate_, unscopables, "flatMap");
1745     InstallTrueValuedProperty(isolate_, unscopables, "includes");
1746     InstallTrueValuedProperty(isolate_, unscopables, "keys");
1747     InstallTrueValuedProperty(isolate_, unscopables, "values");
1748     JSObject::MigrateSlowToFast(unscopables, 0, "Bootstrapping");
1749     JSObject::AddProperty(
1750         isolate_, proto, factory->unscopables_symbol(), unscopables,
1751         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
1752 
1753     Handle<Map> map(proto->map(), isolate_);
1754     Map::SetShouldBeFastPrototypeMap(map, true, isolate_);
1755   }
1756 
1757   {  // --- A r r a y I t e r a t o r ---
1758     Handle<JSObject> iterator_prototype(
1759         native_context()->initial_iterator_prototype(), isolate());
1760 
1761     Handle<JSObject> array_iterator_prototype =
1762         factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
1763     JSObject::ForceSetPrototype(array_iterator_prototype, iterator_prototype);
1764 
1765     InstallToStringTag(isolate_, array_iterator_prototype,
1766                        factory->ArrayIterator_string());
1767 
1768     InstallFunctionWithBuiltinId(isolate_, array_iterator_prototype, "next",
1769                                  Builtins::kArrayIteratorPrototypeNext, 0,
1770                                  true);
1771 
1772     Handle<JSFunction> array_iterator_function =
1773         CreateFunction(isolate_, factory->ArrayIterator_string(),
1774                        JS_ARRAY_ITERATOR_TYPE, JSArrayIterator::kHeaderSize, 0,
1775                        array_iterator_prototype, Builtins::kIllegal);
1776     array_iterator_function->shared().set_native(false);
1777 
1778     native_context()->set_initial_array_iterator_map(
1779         array_iterator_function->initial_map());
1780     native_context()->set_initial_array_iterator_prototype(
1781         *array_iterator_prototype);
1782   }
1783 
1784   {  // --- N u m b e r ---
1785     Handle<JSFunction> number_fun = InstallFunction(
1786         isolate_, global, "Number", JS_PRIMITIVE_WRAPPER_TYPE,
1787         JSPrimitiveWrapper::kHeaderSize, 0,
1788         isolate_->initial_object_prototype(), Builtins::kNumberConstructor);
1789     number_fun->shared().DontAdaptArguments();
1790     number_fun->shared().set_length(1);
1791     InstallWithIntrinsicDefaultProto(isolate_, number_fun,
1792                                      Context::NUMBER_FUNCTION_INDEX);
1793 
1794     // Create the %NumberPrototype%
1795     Handle<JSPrimitiveWrapper> prototype = Handle<JSPrimitiveWrapper>::cast(
1796         factory->NewJSObject(number_fun, AllocationType::kOld));
1797     prototype->set_value(Smi::zero());
1798     JSFunction::SetPrototype(number_fun, prototype);
1799 
1800     // Install the "constructor" property on the {prototype}.
1801     JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
1802                           number_fun, DONT_ENUM);
1803 
1804     // Install the Number.prototype methods.
1805     SimpleInstallFunction(isolate_, prototype, "toExponential",
1806                           Builtins::kNumberPrototypeToExponential, 1, false);
1807     SimpleInstallFunction(isolate_, prototype, "toFixed",
1808                           Builtins::kNumberPrototypeToFixed, 1, false);
1809     SimpleInstallFunction(isolate_, prototype, "toPrecision",
1810                           Builtins::kNumberPrototypeToPrecision, 1, false);
1811     SimpleInstallFunction(isolate_, prototype, "toString",
1812                           Builtins::kNumberPrototypeToString, 1, false);
1813     SimpleInstallFunction(isolate_, prototype, "valueOf",
1814                           Builtins::kNumberPrototypeValueOf, 0, true);
1815 
1816     SimpleInstallFunction(isolate_, prototype, "toLocaleString",
1817                           Builtins::kNumberPrototypeToLocaleString, 0, false);
1818 
1819     // Install the Number functions.
1820     SimpleInstallFunction(isolate_, number_fun, "isFinite",
1821                           Builtins::kNumberIsFinite, 1, true);
1822     SimpleInstallFunction(isolate_, number_fun, "isInteger",
1823                           Builtins::kNumberIsInteger, 1, true);
1824     SimpleInstallFunction(isolate_, number_fun, "isNaN", Builtins::kNumberIsNaN,
1825                           1, true);
1826     SimpleInstallFunction(isolate_, number_fun, "isSafeInteger",
1827                           Builtins::kNumberIsSafeInteger, 1, true);
1828 
1829     // Install Number.parseFloat and Global.parseFloat.
1830     Handle<JSFunction> parse_float_fun =
1831         SimpleInstallFunction(isolate_, number_fun, "parseFloat",
1832                               Builtins::kNumberParseFloat, 1, true);
1833     JSObject::AddProperty(isolate_, global_object, "parseFloat",
1834                           parse_float_fun, DONT_ENUM);
1835 
1836     // Install Number.parseInt and Global.parseInt.
1837     Handle<JSFunction> parse_int_fun = SimpleInstallFunction(
1838         isolate_, number_fun, "parseInt", Builtins::kNumberParseInt, 2, true);
1839     JSObject::AddProperty(isolate_, global_object, "parseInt", parse_int_fun,
1840                           DONT_ENUM);
1841 
1842     // Install Number constants
1843     const double kMaxValue = 1.7976931348623157e+308;
1844     const double kMinValue = 5e-324;
1845     const double kMinSafeInteger = -kMaxSafeInteger;
1846     const double kEPS = 2.220446049250313e-16;
1847 
1848     InstallConstant(isolate_, number_fun, "MAX_VALUE",
1849                     factory->NewNumber(kMaxValue));
1850     InstallConstant(isolate_, number_fun, "MIN_VALUE",
1851                     factory->NewNumber(kMinValue));
1852     InstallConstant(isolate_, number_fun, "NaN", factory->nan_value());
1853     InstallConstant(isolate_, number_fun, "NEGATIVE_INFINITY",
1854                     factory->NewNumber(-V8_INFINITY));
1855     InstallConstant(isolate_, number_fun, "POSITIVE_INFINITY",
1856                     factory->infinity_value());
1857     InstallConstant(isolate_, number_fun, "MAX_SAFE_INTEGER",
1858                     factory->NewNumber(kMaxSafeInteger));
1859     InstallConstant(isolate_, number_fun, "MIN_SAFE_INTEGER",
1860                     factory->NewNumber(kMinSafeInteger));
1861     InstallConstant(isolate_, number_fun, "EPSILON", factory->NewNumber(kEPS));
1862 
1863     InstallConstant(isolate_, global, "Infinity", factory->infinity_value());
1864     InstallConstant(isolate_, global, "NaN", factory->nan_value());
1865     InstallConstant(isolate_, global, "undefined", factory->undefined_value());
1866   }
1867 
1868   {  // --- B o o l e a n ---
1869     Handle<JSFunction> boolean_fun = InstallFunction(
1870         isolate_, global, "Boolean", JS_PRIMITIVE_WRAPPER_TYPE,
1871         JSPrimitiveWrapper::kHeaderSize, 0,
1872         isolate_->initial_object_prototype(), Builtins::kBooleanConstructor);
1873     boolean_fun->shared().DontAdaptArguments();
1874     boolean_fun->shared().set_length(1);
1875     InstallWithIntrinsicDefaultProto(isolate_, boolean_fun,
1876                                      Context::BOOLEAN_FUNCTION_INDEX);
1877 
1878     // Create the %BooleanPrototype%
1879     Handle<JSPrimitiveWrapper> prototype = Handle<JSPrimitiveWrapper>::cast(
1880         factory->NewJSObject(boolean_fun, AllocationType::kOld));
1881     prototype->set_value(ReadOnlyRoots(isolate_).false_value());
1882     JSFunction::SetPrototype(boolean_fun, prototype);
1883 
1884     // Install the "constructor" property on the {prototype}.
1885     JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
1886                           boolean_fun, DONT_ENUM);
1887 
1888     // Install the Boolean.prototype methods.
1889     SimpleInstallFunction(isolate_, prototype, "toString",
1890                           Builtins::kBooleanPrototypeToString, 0, true);
1891     SimpleInstallFunction(isolate_, prototype, "valueOf",
1892                           Builtins::kBooleanPrototypeValueOf, 0, true);
1893   }
1894 
1895   {  // --- S t r i n g ---
1896     Handle<JSFunction> string_fun = InstallFunction(
1897         isolate_, global, "String", JS_PRIMITIVE_WRAPPER_TYPE,
1898         JSPrimitiveWrapper::kHeaderSize, 0,
1899         isolate_->initial_object_prototype(), Builtins::kStringConstructor);
1900     string_fun->shared().DontAdaptArguments();
1901     string_fun->shared().set_length(1);
1902     InstallWithIntrinsicDefaultProto(isolate_, string_fun,
1903                                      Context::STRING_FUNCTION_INDEX);
1904 
1905     Handle<Map> string_map = Handle<Map>(
1906         native_context()->string_function().initial_map(), isolate());
1907     string_map->set_elements_kind(FAST_STRING_WRAPPER_ELEMENTS);
1908     Map::EnsureDescriptorSlack(isolate_, string_map, 1);
1909 
1910     PropertyAttributes attribs =
1911         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1912 
1913     {  // Add length.
1914       Descriptor d = Descriptor::AccessorConstant(
1915           factory->length_string(), factory->string_length_accessor(), attribs);
1916       string_map->AppendDescriptor(isolate(), &d);
1917     }
1918 
1919     // Install the String.fromCharCode function.
1920     SimpleInstallFunction(isolate_, string_fun, "fromCharCode",
1921                           Builtins::kStringFromCharCode, 1, false);
1922 
1923     // Install the String.fromCodePoint function.
1924     SimpleInstallFunction(isolate_, string_fun, "fromCodePoint",
1925                           Builtins::kStringFromCodePoint, 1, false);
1926 
1927     // Install the String.raw function.
1928     SimpleInstallFunction(isolate_, string_fun, "raw", Builtins::kStringRaw, 1,
1929                           false);
1930 
1931     // Create the %StringPrototype%
1932     Handle<JSPrimitiveWrapper> prototype = Handle<JSPrimitiveWrapper>::cast(
1933         factory->NewJSObject(string_fun, AllocationType::kOld));
1934     prototype->set_value(ReadOnlyRoots(isolate_).empty_string());
1935     JSFunction::SetPrototype(string_fun, prototype);
1936     native_context()->set_initial_string_prototype(*prototype);
1937 
1938     // Install the "constructor" property on the {prototype}.
1939     JSObject::AddProperty(isolate_, prototype, factory->constructor_string(),
1940                           string_fun, DONT_ENUM);
1941 
1942     // Install the String.prototype methods.
1943     SimpleInstallFunction(isolate_, prototype, "anchor",
1944                           Builtins::kStringPrototypeAnchor, 1, false);
1945     SimpleInstallFunction(isolate_, prototype, "big",
1946                           Builtins::kStringPrototypeBig, 0, false);
1947     SimpleInstallFunction(isolate_, prototype, "blink",
1948                           Builtins::kStringPrototypeBlink, 0, false);
1949     SimpleInstallFunction(isolate_, prototype, "bold",
1950                           Builtins::kStringPrototypeBold, 0, false);
1951     SimpleInstallFunction(isolate_, prototype, "charAt",
1952                           Builtins::kStringPrototypeCharAt, 1, true);
1953     SimpleInstallFunction(isolate_, prototype, "charCodeAt",
1954                           Builtins::kStringPrototypeCharCodeAt, 1, true);
1955     SimpleInstallFunction(isolate_, prototype, "codePointAt",
1956                           Builtins::kStringPrototypeCodePointAt, 1, true);
1957     SimpleInstallFunction(isolate_, prototype, "concat",
1958                           Builtins::kStringPrototypeConcat, 1, false);
1959     SimpleInstallFunction(isolate_, prototype, "endsWith",
1960                           Builtins::kStringPrototypeEndsWith, 1, false);
1961     SimpleInstallFunction(isolate_, prototype, "fontcolor",
1962                           Builtins::kStringPrototypeFontcolor, 1, false);
1963     SimpleInstallFunction(isolate_, prototype, "fontsize",
1964                           Builtins::kStringPrototypeFontsize, 1, false);
1965     SimpleInstallFunction(isolate_, prototype, "fixed",
1966                           Builtins::kStringPrototypeFixed, 0, false);
1967     SimpleInstallFunction(isolate_, prototype, "includes",
1968                           Builtins::kStringPrototypeIncludes, 1, false);
1969     SimpleInstallFunction(isolate_, prototype, "indexOf",
1970                           Builtins::kStringPrototypeIndexOf, 1, false);
1971     SimpleInstallFunction(isolate_, prototype, "italics",
1972                           Builtins::kStringPrototypeItalics, 0, false);
1973     SimpleInstallFunction(isolate_, prototype, "lastIndexOf",
1974                           Builtins::kStringPrototypeLastIndexOf, 1, false);
1975     SimpleInstallFunction(isolate_, prototype, "link",
1976                           Builtins::kStringPrototypeLink, 1, false);
1977 #ifdef V8_INTL_SUPPORT
1978     SimpleInstallFunction(isolate_, prototype, "localeCompare",
1979                           Builtins::kStringPrototypeLocaleCompare, 1, false);
1980 #else
1981     SimpleInstallFunction(isolate_, prototype, "localeCompare",
1982                           Builtins::kStringPrototypeLocaleCompare, 1, true);
1983 #endif  // V8_INTL_SUPPORT
1984     SimpleInstallFunction(isolate_, prototype, "match",
1985                           Builtins::kStringPrototypeMatch, 1, true);
1986     SimpleInstallFunction(isolate_, prototype, "matchAll",
1987                           Builtins::kStringPrototypeMatchAll, 1, true);
1988 #ifdef V8_INTL_SUPPORT
1989     SimpleInstallFunction(isolate_, prototype, "normalize",
1990                           Builtins::kStringPrototypeNormalizeIntl, 0, false);
1991 #else
1992     SimpleInstallFunction(isolate_, prototype, "normalize",
1993                           Builtins::kStringPrototypeNormalize, 0, false);
1994 #endif  // V8_INTL_SUPPORT
1995     SimpleInstallFunction(isolate_, prototype, "padEnd",
1996                           Builtins::kStringPrototypePadEnd, 1, false);
1997     SimpleInstallFunction(isolate_, prototype, "padStart",
1998                           Builtins::kStringPrototypePadStart, 1, false);
1999     SimpleInstallFunction(isolate_, prototype, "repeat",
2000                           Builtins::kStringPrototypeRepeat, 1, true);
2001     SimpleInstallFunction(isolate_, prototype, "replace",
2002                           Builtins::kStringPrototypeReplace, 2, true);
2003     SimpleInstallFunction(isolate_, prototype, "search",
2004                           Builtins::kStringPrototypeSearch, 1, true);
2005     SimpleInstallFunction(isolate_, prototype, "slice",
2006                           Builtins::kStringPrototypeSlice, 2, false);
2007     SimpleInstallFunction(isolate_, prototype, "small",
2008                           Builtins::kStringPrototypeSmall, 0, false);
2009     SimpleInstallFunction(isolate_, prototype, "split",
2010                           Builtins::kStringPrototypeSplit, 2, false);
2011     SimpleInstallFunction(isolate_, prototype, "strike",
2012                           Builtins::kStringPrototypeStrike, 0, false);
2013     SimpleInstallFunction(isolate_, prototype, "sub",
2014                           Builtins::kStringPrototypeSub, 0, false);
2015     SimpleInstallFunction(isolate_, prototype, "substr",
2016                           Builtins::kStringPrototypeSubstr, 2, false);
2017     SimpleInstallFunction(isolate_, prototype, "substring",
2018                           Builtins::kStringPrototypeSubstring, 2, false);
2019     SimpleInstallFunction(isolate_, prototype, "sup",
2020                           Builtins::kStringPrototypeSup, 0, false);
2021     SimpleInstallFunction(isolate_, prototype, "startsWith",
2022                           Builtins::kStringPrototypeStartsWith, 1, false);
2023     SimpleInstallFunction(isolate_, prototype, "toString",
2024                           Builtins::kStringPrototypeToString, 0, true);
2025     SimpleInstallFunction(isolate_, prototype, "trim",
2026                           Builtins::kStringPrototypeTrim, 0, false);
2027 
2028     // Install `String.prototype.trimStart` with `trimLeft` alias.
2029     Handle<JSFunction> trim_start_fun =
2030         SimpleInstallFunction(isolate_, prototype, "trimStart",
2031                               Builtins::kStringPrototypeTrimStart, 0, false);
2032     JSObject::AddProperty(isolate_, prototype, "trimLeft", trim_start_fun,
2033                           DONT_ENUM);
2034 
2035     // Install `String.prototype.trimEnd` with `trimRight` alias.
2036     Handle<JSFunction> trim_end_fun =
2037         SimpleInstallFunction(isolate_, prototype, "trimEnd",
2038                               Builtins::kStringPrototypeTrimEnd, 0, false);
2039     JSObject::AddProperty(isolate_, prototype, "trimRight", trim_end_fun,
2040                           DONT_ENUM);
2041 
2042     SimpleInstallFunction(isolate_, prototype, "toLocaleLowerCase",
2043                           Builtins::kStringPrototypeToLocaleLowerCase, 0,
2044                           false);
2045     SimpleInstallFunction(isolate_, prototype, "toLocaleUpperCase",
2046                           Builtins::kStringPrototypeToLocaleUpperCase, 0,
2047                           false);
2048 #ifdef V8_INTL_SUPPORT
2049     SimpleInstallFunction(isolate_, prototype, "toLowerCase",
2050                           Builtins::kStringPrototypeToLowerCaseIntl, 0, true);
2051     SimpleInstallFunction(isolate_, prototype, "toUpperCase",
2052                           Builtins::kStringPrototypeToUpperCaseIntl, 0, false);
2053 #else
2054     SimpleInstallFunction(isolate_, prototype, "toLowerCase",
2055                           Builtins::kStringPrototypeToLowerCase, 0, false);
2056     SimpleInstallFunction(isolate_, prototype, "toUpperCase",
2057                           Builtins::kStringPrototypeToUpperCase, 0, false);
2058 #endif
2059     SimpleInstallFunction(isolate_, prototype, "valueOf",
2060                           Builtins::kStringPrototypeValueOf, 0, true);
2061 
2062     InstallFunctionAtSymbol(
2063         isolate_, prototype, factory->iterator_symbol(), "[Symbol.iterator]",
2064         Builtins::kStringPrototypeIterator, 0, true, DONT_ENUM);
2065   }
2066 
2067   {  // --- S t r i n g I t e r a t o r ---
2068     Handle<JSObject> iterator_prototype(
2069         native_context()->initial_iterator_prototype(), isolate());
2070 
2071     Handle<JSObject> string_iterator_prototype =
2072         factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
2073     JSObject::ForceSetPrototype(string_iterator_prototype, iterator_prototype);
2074 
2075     InstallToStringTag(isolate_, string_iterator_prototype, "String Iterator");
2076 
2077     InstallFunctionWithBuiltinId(isolate_, string_iterator_prototype, "next",
2078                                  Builtins::kStringIteratorPrototypeNext, 0,
2079                                  true);
2080 
2081     Handle<JSFunction> string_iterator_function = CreateFunction(
2082         isolate_, factory->InternalizeUtf8String("StringIterator"),
2083         JS_STRING_ITERATOR_TYPE, JSStringIterator::kHeaderSize, 0,
2084         string_iterator_prototype, Builtins::kIllegal);
2085     string_iterator_function->shared().set_native(false);
2086     native_context()->set_initial_string_iterator_map(
2087         string_iterator_function->initial_map());
2088     native_context()->set_initial_string_iterator_prototype(
2089         *string_iterator_prototype);
2090   }
2091 
2092   {  // --- S y m b o l ---
2093     Handle<JSFunction> symbol_fun = InstallFunction(
2094         isolate_, global, "Symbol", JS_PRIMITIVE_WRAPPER_TYPE,
2095         JSPrimitiveWrapper::kHeaderSize, 0, factory->the_hole_value(),
2096         Builtins::kSymbolConstructor);
2097     symbol_fun->shared().set_length(0);
2098     symbol_fun->shared().DontAdaptArguments();
2099     native_context()->set_symbol_function(*symbol_fun);
2100 
2101     // Install the Symbol.for and Symbol.keyFor functions.
2102     SimpleInstallFunction(isolate_, symbol_fun, "for", Builtins::kSymbolFor, 1,
2103                           false);
2104     SimpleInstallFunction(isolate_, symbol_fun, "keyFor",
2105                           Builtins::kSymbolKeyFor, 1, false);
2106 
2107     // Install well-known symbols.
2108     InstallConstant(isolate_, symbol_fun, "asyncIterator",
2109                     factory->async_iterator_symbol());
2110     InstallConstant(isolate_, symbol_fun, "hasInstance",
2111                     factory->has_instance_symbol());
2112     InstallConstant(isolate_, symbol_fun, "isConcatSpreadable",
2113                     factory->is_concat_spreadable_symbol());
2114     InstallConstant(isolate_, symbol_fun, "iterator",
2115                     factory->iterator_symbol());
2116     InstallConstant(isolate_, symbol_fun, "match", factory->match_symbol());
2117     InstallConstant(isolate_, symbol_fun, "matchAll",
2118                     factory->match_all_symbol());
2119     InstallConstant(isolate_, symbol_fun, "replace", factory->replace_symbol());
2120     InstallConstant(isolate_, symbol_fun, "search", factory->search_symbol());
2121     InstallConstant(isolate_, symbol_fun, "species", factory->species_symbol());
2122     InstallConstant(isolate_, symbol_fun, "split", factory->split_symbol());
2123     InstallConstant(isolate_, symbol_fun, "toPrimitive",
2124                     factory->to_primitive_symbol());
2125     InstallConstant(isolate_, symbol_fun, "toStringTag",
2126                     factory->to_string_tag_symbol());
2127     InstallConstant(isolate_, symbol_fun, "unscopables",
2128                     factory->unscopables_symbol());
2129 
2130     // Setup %SymbolPrototype%.
2131     Handle<JSObject> prototype(JSObject::cast(symbol_fun->instance_prototype()),
2132                                isolate());
2133 
2134     InstallToStringTag(isolate_, prototype, "Symbol");
2135 
2136     // Install the Symbol.prototype methods.
2137     InstallFunctionWithBuiltinId(isolate_, prototype, "toString",
2138                                  Builtins::kSymbolPrototypeToString, 0, true);
2139     InstallFunctionWithBuiltinId(isolate_, prototype, "valueOf",
2140                                  Builtins::kSymbolPrototypeValueOf, 0, true);
2141 
2142     // Install the Symbol.prototype.description getter.
2143     SimpleInstallGetter(isolate_, prototype,
2144                         factory->InternalizeUtf8String("description"),
2145                         Builtins::kSymbolPrototypeDescriptionGetter, true);
2146 
2147     // Install the @@toPrimitive function.
2148     InstallFunctionAtSymbol(
2149         isolate_, prototype, factory->to_primitive_symbol(),
2150         "[Symbol.toPrimitive]", Builtins::kSymbolPrototypeToPrimitive, 1, true,
2151         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2152   }
2153 
2154   {  // --- D a t e ---
2155     Handle<JSFunction> date_fun = InstallFunction(
2156         isolate_, global, "Date", JS_DATE_TYPE, JSDate::kHeaderSize, 0,
2157         factory->the_hole_value(), Builtins::kDateConstructor);
2158     InstallWithIntrinsicDefaultProto(isolate_, date_fun,
2159                                      Context::DATE_FUNCTION_INDEX);
2160     date_fun->shared().set_length(7);
2161     date_fun->shared().DontAdaptArguments();
2162 
2163     // Install the Date.now, Date.parse and Date.UTC functions.
2164     SimpleInstallFunction(isolate_, date_fun, "now", Builtins::kDateNow, 0,
2165                           false);
2166     SimpleInstallFunction(isolate_, date_fun, "parse", Builtins::kDateParse, 1,
2167                           false);
2168     SimpleInstallFunction(isolate_, date_fun, "UTC", Builtins::kDateUTC, 7,
2169                           false);
2170 
2171     // Setup %DatePrototype%.
2172     Handle<JSObject> prototype(JSObject::cast(date_fun->instance_prototype()),
2173                                isolate());
2174 
2175     // Install the Date.prototype methods.
2176     SimpleInstallFunction(isolate_, prototype, "toString",
2177                           Builtins::kDatePrototypeToString, 0, false);
2178     SimpleInstallFunction(isolate_, prototype, "toDateString",
2179                           Builtins::kDatePrototypeToDateString, 0, false);
2180     SimpleInstallFunction(isolate_, prototype, "toTimeString",
2181                           Builtins::kDatePrototypeToTimeString, 0, false);
2182     SimpleInstallFunction(isolate_, prototype, "toISOString",
2183                           Builtins::kDatePrototypeToISOString, 0, false);
2184     Handle<JSFunction> to_utc_string =
2185         SimpleInstallFunction(isolate_, prototype, "toUTCString",
2186                               Builtins::kDatePrototypeToUTCString, 0, false);
2187     JSObject::AddProperty(isolate_, prototype, "toGMTString", to_utc_string,
2188                           DONT_ENUM);
2189     SimpleInstallFunction(isolate_, prototype, "getDate",
2190                           Builtins::kDatePrototypeGetDate, 0, true);
2191     SimpleInstallFunction(isolate_, prototype, "setDate",
2192                           Builtins::kDatePrototypeSetDate, 1, false);
2193     SimpleInstallFunction(isolate_, prototype, "getDay",
2194                           Builtins::kDatePrototypeGetDay, 0, true);
2195     SimpleInstallFunction(isolate_, prototype, "getFullYear",
2196                           Builtins::kDatePrototypeGetFullYear, 0, true);
2197     SimpleInstallFunction(isolate_, prototype, "setFullYear",
2198                           Builtins::kDatePrototypeSetFullYear, 3, false);
2199     SimpleInstallFunction(isolate_, prototype, "getHours",
2200                           Builtins::kDatePrototypeGetHours, 0, true);
2201     SimpleInstallFunction(isolate_, prototype, "setHours",
2202                           Builtins::kDatePrototypeSetHours, 4, false);
2203     SimpleInstallFunction(isolate_, prototype, "getMilliseconds",
2204                           Builtins::kDatePrototypeGetMilliseconds, 0, true);
2205     SimpleInstallFunction(isolate_, prototype, "setMilliseconds",
2206                           Builtins::kDatePrototypeSetMilliseconds, 1, false);
2207     SimpleInstallFunction(isolate_, prototype, "getMinutes",
2208                           Builtins::kDatePrototypeGetMinutes, 0, true);
2209     SimpleInstallFunction(isolate_, prototype, "setMinutes",
2210                           Builtins::kDatePrototypeSetMinutes, 3, false);
2211     SimpleInstallFunction(isolate_, prototype, "getMonth",
2212                           Builtins::kDatePrototypeGetMonth, 0, true);
2213     SimpleInstallFunction(isolate_, prototype, "setMonth",
2214                           Builtins::kDatePrototypeSetMonth, 2, false);
2215     SimpleInstallFunction(isolate_, prototype, "getSeconds",
2216                           Builtins::kDatePrototypeGetSeconds, 0, true);
2217     SimpleInstallFunction(isolate_, prototype, "setSeconds",
2218                           Builtins::kDatePrototypeSetSeconds, 2, false);
2219     SimpleInstallFunction(isolate_, prototype, "getTime",
2220                           Builtins::kDatePrototypeGetTime, 0, true);
2221     SimpleInstallFunction(isolate_, prototype, "setTime",
2222                           Builtins::kDatePrototypeSetTime, 1, false);
2223     SimpleInstallFunction(isolate_, prototype, "getTimezoneOffset",
2224                           Builtins::kDatePrototypeGetTimezoneOffset, 0, true);
2225     SimpleInstallFunction(isolate_, prototype, "getUTCDate",
2226                           Builtins::kDatePrototypeGetUTCDate, 0, true);
2227     SimpleInstallFunction(isolate_, prototype, "setUTCDate",
2228                           Builtins::kDatePrototypeSetUTCDate, 1, false);
2229     SimpleInstallFunction(isolate_, prototype, "getUTCDay",
2230                           Builtins::kDatePrototypeGetUTCDay, 0, true);
2231     SimpleInstallFunction(isolate_, prototype, "getUTCFullYear",
2232                           Builtins::kDatePrototypeGetUTCFullYear, 0, true);
2233     SimpleInstallFunction(isolate_, prototype, "setUTCFullYear",
2234                           Builtins::kDatePrototypeSetUTCFullYear, 3, false);
2235     SimpleInstallFunction(isolate_, prototype, "getUTCHours",
2236                           Builtins::kDatePrototypeGetUTCHours, 0, true);
2237     SimpleInstallFunction(isolate_, prototype, "setUTCHours",
2238                           Builtins::kDatePrototypeSetUTCHours, 4, false);
2239     SimpleInstallFunction(isolate_, prototype, "getUTCMilliseconds",
2240                           Builtins::kDatePrototypeGetUTCMilliseconds, 0, true);
2241     SimpleInstallFunction(isolate_, prototype, "setUTCMilliseconds",
2242                           Builtins::kDatePrototypeSetUTCMilliseconds, 1, false);
2243     SimpleInstallFunction(isolate_, prototype, "getUTCMinutes",
2244                           Builtins::kDatePrototypeGetUTCMinutes, 0, true);
2245     SimpleInstallFunction(isolate_, prototype, "setUTCMinutes",
2246                           Builtins::kDatePrototypeSetUTCMinutes, 3, false);
2247     SimpleInstallFunction(isolate_, prototype, "getUTCMonth",
2248                           Builtins::kDatePrototypeGetUTCMonth, 0, true);
2249     SimpleInstallFunction(isolate_, prototype, "setUTCMonth",
2250                           Builtins::kDatePrototypeSetUTCMonth, 2, false);
2251     SimpleInstallFunction(isolate_, prototype, "getUTCSeconds",
2252                           Builtins::kDatePrototypeGetUTCSeconds, 0, true);
2253     SimpleInstallFunction(isolate_, prototype, "setUTCSeconds",
2254                           Builtins::kDatePrototypeSetUTCSeconds, 2, false);
2255     SimpleInstallFunction(isolate_, prototype, "valueOf",
2256                           Builtins::kDatePrototypeValueOf, 0, true);
2257     SimpleInstallFunction(isolate_, prototype, "getYear",
2258                           Builtins::kDatePrototypeGetYear, 0, true);
2259     SimpleInstallFunction(isolate_, prototype, "setYear",
2260                           Builtins::kDatePrototypeSetYear, 1, false);
2261     SimpleInstallFunction(isolate_, prototype, "toJSON",
2262                           Builtins::kDatePrototypeToJson, 1, false);
2263 
2264 #ifdef V8_INTL_SUPPORT
2265     SimpleInstallFunction(isolate_, prototype, "toLocaleString",
2266                           Builtins::kDatePrototypeToLocaleString, 0, false);
2267     SimpleInstallFunction(isolate_, prototype, "toLocaleDateString",
2268                           Builtins::kDatePrototypeToLocaleDateString, 0, false);
2269     SimpleInstallFunction(isolate_, prototype, "toLocaleTimeString",
2270                           Builtins::kDatePrototypeToLocaleTimeString, 0, false);
2271 #else
2272     // Install Intl fallback functions.
2273     SimpleInstallFunction(isolate_, prototype, "toLocaleString",
2274                           Builtins::kDatePrototypeToString, 0, false);
2275     SimpleInstallFunction(isolate_, prototype, "toLocaleDateString",
2276                           Builtins::kDatePrototypeToDateString, 0, false);
2277     SimpleInstallFunction(isolate_, prototype, "toLocaleTimeString",
2278                           Builtins::kDatePrototypeToTimeString, 0, false);
2279 #endif  // V8_INTL_SUPPORT
2280 
2281     // Install the @@toPrimitive function.
2282     InstallFunctionAtSymbol(
2283         isolate_, prototype, factory->to_primitive_symbol(),
2284         "[Symbol.toPrimitive]", Builtins::kDatePrototypeToPrimitive, 1, true,
2285         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2286   }
2287 
2288   {  // -- P r o m i s e
2289     Handle<JSFunction> promise_fun = InstallFunction(
2290         isolate_, global, "Promise", JS_PROMISE_TYPE,
2291         JSPromise::kSizeWithEmbedderFields, 0, factory->the_hole_value(),
2292         Builtins::kPromiseConstructor);
2293     InstallWithIntrinsicDefaultProto(isolate_, promise_fun,
2294                                      Context::PROMISE_FUNCTION_INDEX);
2295 
2296     Handle<SharedFunctionInfo> shared(promise_fun->shared(), isolate_);
2297     shared->set_internal_formal_parameter_count(1);
2298     shared->set_length(1);
2299 
2300     InstallSpeciesGetter(isolate_, promise_fun);
2301 
2302     Handle<JSFunction> promise_all = InstallFunctionWithBuiltinId(
2303         isolate_, promise_fun, "all", Builtins::kPromiseAll, 1, true);
2304     native_context()->set_promise_all(*promise_all);
2305 
2306     InstallFunctionWithBuiltinId(isolate_, promise_fun, "allSettled",
2307                                  Builtins::kPromiseAllSettled, 1, true);
2308 
2309     InstallFunctionWithBuiltinId(isolate_, promise_fun, "race",
2310                                  Builtins::kPromiseRace, 1, true);
2311 
2312     InstallFunctionWithBuiltinId(isolate_, promise_fun, "resolve",
2313                                  Builtins::kPromiseResolveTrampoline, 1, true);
2314 
2315     InstallFunctionWithBuiltinId(isolate_, promise_fun, "reject",
2316                                  Builtins::kPromiseReject, 1, true);
2317 
2318     // Setup %PromisePrototype%.
2319     Handle<JSObject> prototype(
2320         JSObject::cast(promise_fun->instance_prototype()), isolate());
2321     native_context()->set_promise_prototype(*prototype);
2322 
2323     InstallToStringTag(isolate_, prototype, factory->Promise_string());
2324 
2325     Handle<JSFunction> promise_then = InstallFunctionWithBuiltinId(
2326         isolate_, prototype, "then", Builtins::kPromisePrototypeThen, 2, true);
2327     native_context()->set_promise_then(*promise_then);
2328 
2329     Handle<JSFunction> promise_catch =
2330         InstallFunctionWithBuiltinId(isolate_, prototype, "catch",
2331                                      Builtins::kPromisePrototypeCatch, 1, true);
2332     native_context()->set_promise_catch(*promise_catch);
2333 
2334     InstallFunctionWithBuiltinId(isolate_, prototype, "finally",
2335                                  Builtins::kPromisePrototypeFinally, 1, true);
2336 
2337     DCHECK(promise_fun->HasFastProperties());
2338 
2339     Handle<Map> prototype_map(prototype->map(), isolate());
2340     Map::SetShouldBeFastPrototypeMap(prototype_map, true, isolate_);
2341 
2342     DCHECK(promise_fun->HasFastProperties());
2343   }
2344 
2345   {  // -- R e g E x p
2346     // Builtin functions for RegExp.prototype.
2347     Handle<JSFunction> regexp_fun = InstallFunction(
2348         isolate_, global, "RegExp", JS_REG_EXP_TYPE,
2349         JSRegExp::kHeaderSize + JSRegExp::kInObjectFieldCount * kTaggedSize,
2350         JSRegExp::kInObjectFieldCount, factory->the_hole_value(),
2351         Builtins::kRegExpConstructor);
2352     InstallWithIntrinsicDefaultProto(isolate_, regexp_fun,
2353                                      Context::REGEXP_FUNCTION_INDEX);
2354 
2355     Handle<SharedFunctionInfo> shared(regexp_fun->shared(), isolate_);
2356     shared->set_internal_formal_parameter_count(2);
2357     shared->set_length(2);
2358 
2359     {
2360       // Setup %RegExpPrototype%.
2361       Handle<JSObject> prototype(
2362           JSObject::cast(regexp_fun->instance_prototype()), isolate());
2363       native_context()->set_regexp_prototype(*prototype);
2364 
2365       {
2366         Handle<JSFunction> fun =
2367             SimpleInstallFunction(isolate_, prototype, "exec",
2368                                   Builtins::kRegExpPrototypeExec, 1, true);
2369         native_context()->set_regexp_exec_function(*fun);
2370         DCHECK_EQ(JSRegExp::kExecFunctionDescriptorIndex,
2371                   prototype->map().LastAdded().as_int());
2372       }
2373 
2374       SimpleInstallGetter(isolate_, prototype, factory->dotAll_string(),
2375                           Builtins::kRegExpPrototypeDotAllGetter, true);
2376       SimpleInstallGetter(isolate_, prototype, factory->flags_string(),
2377                           Builtins::kRegExpPrototypeFlagsGetter, true);
2378       SimpleInstallGetter(isolate_, prototype, factory->global_string(),
2379                           Builtins::kRegExpPrototypeGlobalGetter, true);
2380       SimpleInstallGetter(isolate_, prototype, factory->ignoreCase_string(),
2381                           Builtins::kRegExpPrototypeIgnoreCaseGetter, true);
2382       SimpleInstallGetter(isolate_, prototype, factory->multiline_string(),
2383                           Builtins::kRegExpPrototypeMultilineGetter, true);
2384       SimpleInstallGetter(isolate_, prototype, factory->source_string(),
2385                           Builtins::kRegExpPrototypeSourceGetter, true);
2386       SimpleInstallGetter(isolate_, prototype, factory->sticky_string(),
2387                           Builtins::kRegExpPrototypeStickyGetter, true);
2388       SimpleInstallGetter(isolate_, prototype, factory->unicode_string(),
2389                           Builtins::kRegExpPrototypeUnicodeGetter, true);
2390 
2391       SimpleInstallFunction(isolate_, prototype, "compile",
2392                             Builtins::kRegExpPrototypeCompile, 2, true);
2393       SimpleInstallFunction(isolate_, prototype, "toString",
2394                             Builtins::kRegExpPrototypeToString, 0, false);
2395       SimpleInstallFunction(isolate_, prototype, "test",
2396                             Builtins::kRegExpPrototypeTest, 1, true);
2397 
2398       {
2399         Handle<JSFunction> fun = InstallFunctionAtSymbol(
2400             isolate_, prototype, factory->match_symbol(), "[Symbol.match]",
2401             Builtins::kRegExpPrototypeMatch, 1, true);
2402         native_context()->set_regexp_match_function(*fun);
2403         DCHECK_EQ(JSRegExp::kSymbolMatchFunctionDescriptorIndex,
2404                   prototype->map().LastAdded().as_int());
2405       }
2406 
2407       {
2408         Handle<JSFunction> fun = InstallFunctionAtSymbol(
2409             isolate_, prototype, factory->match_all_symbol(),
2410             "[Symbol.matchAll]", Builtins::kRegExpPrototypeMatchAll, 1, true);
2411         native_context()->set_regexp_match_all_function(*fun);
2412         DCHECK_EQ(JSRegExp::kSymbolMatchAllFunctionDescriptorIndex,
2413                   prototype->map().LastAdded().as_int());
2414       }
2415 
2416       {
2417         Handle<JSFunction> fun = InstallFunctionAtSymbol(
2418             isolate_, prototype, factory->replace_symbol(), "[Symbol.replace]",
2419             Builtins::kRegExpPrototypeReplace, 2, false);
2420         native_context()->set_regexp_replace_function(*fun);
2421         DCHECK_EQ(JSRegExp::kSymbolReplaceFunctionDescriptorIndex,
2422                   prototype->map().LastAdded().as_int());
2423       }
2424 
2425       {
2426         Handle<JSFunction> fun = InstallFunctionAtSymbol(
2427             isolate_, prototype, factory->search_symbol(), "[Symbol.search]",
2428             Builtins::kRegExpPrototypeSearch, 1, true);
2429         native_context()->set_regexp_search_function(*fun);
2430         DCHECK_EQ(JSRegExp::kSymbolSearchFunctionDescriptorIndex,
2431                   prototype->map().LastAdded().as_int());
2432       }
2433 
2434       {
2435         Handle<JSFunction> fun = InstallFunctionAtSymbol(
2436             isolate_, prototype, factory->split_symbol(), "[Symbol.split]",
2437             Builtins::kRegExpPrototypeSplit, 2, false);
2438         native_context()->set_regexp_split_function(*fun);
2439         DCHECK_EQ(JSRegExp::kSymbolSplitFunctionDescriptorIndex,
2440                   prototype->map().LastAdded().as_int());
2441       }
2442 
2443       Handle<Map> prototype_map(prototype->map(), isolate());
2444       Map::SetShouldBeFastPrototypeMap(prototype_map, true, isolate_);
2445 
2446       // Store the initial RegExp.prototype map. This is used in fast-path
2447       // checks. Do not alter the prototype after this point.
2448       native_context()->set_regexp_prototype_map(*prototype_map);
2449     }
2450 
2451     {
2452       // RegExp getters and setters.
2453 
2454       InstallSpeciesGetter(isolate_, regexp_fun);
2455 
2456       // Static properties set by a successful match.
2457 
2458       SimpleInstallGetterSetter(isolate_, regexp_fun, factory->input_string(),
2459                                 Builtins::kRegExpInputGetter,
2460                                 Builtins::kRegExpInputSetter);
2461       SimpleInstallGetterSetter(isolate_, regexp_fun, "$_",
2462                                 Builtins::kRegExpInputGetter,
2463                                 Builtins::kRegExpInputSetter);
2464 
2465       SimpleInstallGetterSetter(isolate_, regexp_fun, "lastMatch",
2466                                 Builtins::kRegExpLastMatchGetter,
2467                                 Builtins::kEmptyFunction);
2468       SimpleInstallGetterSetter(isolate_, regexp_fun, "$&",
2469                                 Builtins::kRegExpLastMatchGetter,
2470                                 Builtins::kEmptyFunction);
2471 
2472       SimpleInstallGetterSetter(isolate_, regexp_fun, "lastParen",
2473                                 Builtins::kRegExpLastParenGetter,
2474                                 Builtins::kEmptyFunction);
2475       SimpleInstallGetterSetter(isolate_, regexp_fun, "$+",
2476                                 Builtins::kRegExpLastParenGetter,
2477                                 Builtins::kEmptyFunction);
2478 
2479       SimpleInstallGetterSetter(isolate_, regexp_fun, "leftContext",
2480                                 Builtins::kRegExpLeftContextGetter,
2481                                 Builtins::kEmptyFunction);
2482       SimpleInstallGetterSetter(isolate_, regexp_fun, "$`",
2483                                 Builtins::kRegExpLeftContextGetter,
2484                                 Builtins::kEmptyFunction);
2485 
2486       SimpleInstallGetterSetter(isolate_, regexp_fun, "rightContext",
2487                                 Builtins::kRegExpRightContextGetter,
2488                                 Builtins::kEmptyFunction);
2489       SimpleInstallGetterSetter(isolate_, regexp_fun, "$'",
2490                                 Builtins::kRegExpRightContextGetter,
2491                                 Builtins::kEmptyFunction);
2492 
2493 #define INSTALL_CAPTURE_GETTER(i)                                \
2494   SimpleInstallGetterSetter(isolate_, regexp_fun, "$" #i,        \
2495                             Builtins::kRegExpCapture##i##Getter, \
2496                             Builtins::kEmptyFunction)
2497       INSTALL_CAPTURE_GETTER(1);
2498       INSTALL_CAPTURE_GETTER(2);
2499       INSTALL_CAPTURE_GETTER(3);
2500       INSTALL_CAPTURE_GETTER(4);
2501       INSTALL_CAPTURE_GETTER(5);
2502       INSTALL_CAPTURE_GETTER(6);
2503       INSTALL_CAPTURE_GETTER(7);
2504       INSTALL_CAPTURE_GETTER(8);
2505       INSTALL_CAPTURE_GETTER(9);
2506 #undef INSTALL_CAPTURE_GETTER
2507     }
2508 
2509     DCHECK(regexp_fun->has_initial_map());
2510     Handle<Map> initial_map(regexp_fun->initial_map(), isolate());
2511 
2512     DCHECK_EQ(1, initial_map->GetInObjectProperties());
2513 
2514     Map::EnsureDescriptorSlack(isolate_, initial_map, 1);
2515 
2516     // ECMA-262, section 15.10.7.5.
2517     PropertyAttributes writable =
2518         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
2519     Descriptor d = Descriptor::DataField(isolate(), factory->lastIndex_string(),
2520                                          JSRegExp::kLastIndexFieldIndex,
2521                                          writable, Representation::Tagged());
2522     initial_map->AppendDescriptor(isolate(), &d);
2523 
2524     // Create the last match info.
2525     Handle<RegExpMatchInfo> last_match_info = factory->NewRegExpMatchInfo();
2526     native_context()->set_regexp_last_match_info(*last_match_info);
2527 
2528     // Install the species protector cell.
2529     {
2530       Handle<PropertyCell> cell =
2531           factory->NewPropertyCell(factory->empty_string());
2532       cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
2533       native_context()->set_regexp_species_protector(*cell);
2534     }
2535 
2536     DCHECK(regexp_fun->HasFastProperties());
2537   }
2538 
2539   {  // --- R e g E x p S t r i n g  I t e r a t o r ---
2540     Handle<JSObject> iterator_prototype(
2541         native_context()->initial_iterator_prototype(), isolate());
2542 
2543     Handle<JSObject> regexp_string_iterator_prototype = factory->NewJSObject(
2544         isolate()->object_function(), AllocationType::kOld);
2545     JSObject::ForceSetPrototype(regexp_string_iterator_prototype,
2546                                 iterator_prototype);
2547 
2548     InstallToStringTag(isolate(), regexp_string_iterator_prototype,
2549                        "RegExp String Iterator");
2550 
2551     SimpleInstallFunction(isolate(), regexp_string_iterator_prototype, "next",
2552                           Builtins::kRegExpStringIteratorPrototypeNext, 0,
2553                           true);
2554 
2555     Handle<JSFunction> regexp_string_iterator_function = CreateFunction(
2556         isolate(), "RegExpStringIterator", JS_REG_EXP_STRING_ITERATOR_TYPE,
2557         JSRegExpStringIterator::kHeaderSize, 0,
2558         regexp_string_iterator_prototype, Builtins::kIllegal);
2559     regexp_string_iterator_function->shared().set_native(false);
2560     native_context()->set_initial_regexp_string_iterator_prototype_map(
2561         regexp_string_iterator_function->initial_map());
2562   }
2563 
2564   // -- E r r o r
2565   InstallError(isolate_, global, factory->Error_string(),
2566                Context::ERROR_FUNCTION_INDEX);
2567 
2568   // -- E v a l E r r o r
2569   InstallError(isolate_, global, factory->EvalError_string(),
2570                Context::EVAL_ERROR_FUNCTION_INDEX);
2571 
2572   // -- R a n g e E r r o r
2573   InstallError(isolate_, global, factory->RangeError_string(),
2574                Context::RANGE_ERROR_FUNCTION_INDEX);
2575 
2576   // -- R e f e r e n c e E r r o r
2577   InstallError(isolate_, global, factory->ReferenceError_string(),
2578                Context::REFERENCE_ERROR_FUNCTION_INDEX);
2579 
2580   // -- S y n t a x E r r o r
2581   InstallError(isolate_, global, factory->SyntaxError_string(),
2582                Context::SYNTAX_ERROR_FUNCTION_INDEX);
2583 
2584   // -- T y p e E r r o r
2585   InstallError(isolate_, global, factory->TypeError_string(),
2586                Context::TYPE_ERROR_FUNCTION_INDEX);
2587 
2588   // -- U R I E r r o r
2589   InstallError(isolate_, global, factory->URIError_string(),
2590                Context::URI_ERROR_FUNCTION_INDEX);
2591 
2592   {  // -- C o m p i l e E r r o r
2593     Handle<JSObject> dummy = factory->NewJSObject(isolate_->object_function());
2594     InstallError(isolate_, dummy, factory->CompileError_string(),
2595                  Context::WASM_COMPILE_ERROR_FUNCTION_INDEX);
2596 
2597     // -- L i n k E r r o r
2598     InstallError(isolate_, dummy, factory->LinkError_string(),
2599                  Context::WASM_LINK_ERROR_FUNCTION_INDEX);
2600 
2601     // -- R u n t i m e E r r o r
2602     InstallError(isolate_, dummy, factory->RuntimeError_string(),
2603                  Context::WASM_RUNTIME_ERROR_FUNCTION_INDEX);
2604   }
2605 
2606   // Initialize the embedder data slot.
2607   // TODO(ishell): microtask queue pointer will be moved from native context
2608   // to the embedder data array so we don't need an empty embedder data array.
2609   Handle<EmbedderDataArray> embedder_data = factory->NewEmbedderDataArray(0);
2610   native_context()->set_embedder_data(*embedder_data);
2611 
2612   {  // -- g l o b a l T h i s
2613     Handle<JSGlobalProxy> global_proxy(native_context()->global_proxy(),
2614                                        isolate_);
2615     JSObject::AddProperty(isolate_, global, factory->globalThis_string(),
2616                           global_proxy, DONT_ENUM);
2617   }
2618 
2619   {  // -- J S O N
2620     Handle<JSObject> json_object =
2621         factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
2622     JSObject::AddProperty(isolate_, global, "JSON", json_object, DONT_ENUM);
2623     SimpleInstallFunction(isolate_, json_object, "parse", Builtins::kJsonParse,
2624                           2, false);
2625     SimpleInstallFunction(isolate_, json_object, "stringify",
2626                           Builtins::kJsonStringify, 3, true);
2627     InstallToStringTag(isolate_, json_object, "JSON");
2628   }
2629 
2630   {  // -- M a t h
2631     Handle<JSObject> math =
2632         factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
2633     JSObject::AddProperty(isolate_, global, "Math", math, DONT_ENUM);
2634     SimpleInstallFunction(isolate_, math, "abs", Builtins::kMathAbs, 1, true);
2635     SimpleInstallFunction(isolate_, math, "acos", Builtins::kMathAcos, 1, true);
2636     SimpleInstallFunction(isolate_, math, "acosh", Builtins::kMathAcosh, 1,
2637                           true);
2638     SimpleInstallFunction(isolate_, math, "asin", Builtins::kMathAsin, 1, true);
2639     SimpleInstallFunction(isolate_, math, "asinh", Builtins::kMathAsinh, 1,
2640                           true);
2641     SimpleInstallFunction(isolate_, math, "atan", Builtins::kMathAtan, 1, true);
2642     SimpleInstallFunction(isolate_, math, "atanh", Builtins::kMathAtanh, 1,
2643                           true);
2644     SimpleInstallFunction(isolate_, math, "atan2", Builtins::kMathAtan2, 2,
2645                           true);
2646     SimpleInstallFunction(isolate_, math, "ceil", Builtins::kMathCeil, 1, true);
2647     SimpleInstallFunction(isolate_, math, "cbrt", Builtins::kMathCbrt, 1, true);
2648     SimpleInstallFunction(isolate_, math, "expm1", Builtins::kMathExpm1, 1,
2649                           true);
2650     SimpleInstallFunction(isolate_, math, "clz32", Builtins::kMathClz32, 1,
2651                           true);
2652     SimpleInstallFunction(isolate_, math, "cos", Builtins::kMathCos, 1, true);
2653     SimpleInstallFunction(isolate_, math, "cosh", Builtins::kMathCosh, 1, true);
2654     SimpleInstallFunction(isolate_, math, "exp", Builtins::kMathExp, 1, true);
2655     Handle<JSFunction> math_floor = SimpleInstallFunction(
2656         isolate_, math, "floor", Builtins::kMathFloor, 1, true);
2657     native_context()->set_math_floor(*math_floor);
2658     SimpleInstallFunction(isolate_, math, "fround", Builtins::kMathFround, 1,
2659                           true);
2660     SimpleInstallFunction(isolate_, math, "hypot", Builtins::kMathHypot, 2,
2661                           false);
2662     SimpleInstallFunction(isolate_, math, "imul", Builtins::kMathImul, 2, true);
2663     SimpleInstallFunction(isolate_, math, "log", Builtins::kMathLog, 1, true);
2664     SimpleInstallFunction(isolate_, math, "log1p", Builtins::kMathLog1p, 1,
2665                           true);
2666     SimpleInstallFunction(isolate_, math, "log2", Builtins::kMathLog2, 1, true);
2667     SimpleInstallFunction(isolate_, math, "log10", Builtins::kMathLog10, 1,
2668                           true);
2669     SimpleInstallFunction(isolate_, math, "max", Builtins::kMathMax, 2, false);
2670     SimpleInstallFunction(isolate_, math, "min", Builtins::kMathMin, 2, false);
2671     Handle<JSFunction> math_pow = SimpleInstallFunction(
2672         isolate_, math, "pow", Builtins::kMathPow, 2, true);
2673     native_context()->set_math_pow(*math_pow);
2674     SimpleInstallFunction(isolate_, math, "random", Builtins::kMathRandom, 0,
2675                           true);
2676     SimpleInstallFunction(isolate_, math, "round", Builtins::kMathRound, 1,
2677                           true);
2678     SimpleInstallFunction(isolate_, math, "sign", Builtins::kMathSign, 1, true);
2679     SimpleInstallFunction(isolate_, math, "sin", Builtins::kMathSin, 1, true);
2680     SimpleInstallFunction(isolate_, math, "sinh", Builtins::kMathSinh, 1, true);
2681     SimpleInstallFunction(isolate_, math, "sqrt", Builtins::kMathSqrt, 1, true);
2682     SimpleInstallFunction(isolate_, math, "tan", Builtins::kMathTan, 1, true);
2683     SimpleInstallFunction(isolate_, math, "tanh", Builtins::kMathTanh, 1, true);
2684     SimpleInstallFunction(isolate_, math, "trunc", Builtins::kMathTrunc, 1,
2685                           true);
2686 
2687     // Install math constants.
2688     double const kE = base::ieee754::exp(1.0);
2689     double const kPI = 3.1415926535897932;
2690     InstallConstant(isolate_, math, "E", factory->NewNumber(kE));
2691     InstallConstant(isolate_, math, "LN10",
2692                     factory->NewNumber(base::ieee754::log(10.0)));
2693     InstallConstant(isolate_, math, "LN2",
2694                     factory->NewNumber(base::ieee754::log(2.0)));
2695     InstallConstant(isolate_, math, "LOG10E",
2696                     factory->NewNumber(base::ieee754::log10(kE)));
2697     InstallConstant(isolate_, math, "LOG2E",
2698                     factory->NewNumber(base::ieee754::log2(kE)));
2699     InstallConstant(isolate_, math, "PI", factory->NewNumber(kPI));
2700     InstallConstant(isolate_, math, "SQRT1_2",
2701                     factory->NewNumber(std::sqrt(0.5)));
2702     InstallConstant(isolate_, math, "SQRT2",
2703                     factory->NewNumber(std::sqrt(2.0)));
2704     InstallToStringTag(isolate_, math, "Math");
2705   }
2706 
2707   {  // -- C o n s o l e
2708     Handle<String> name = factory->InternalizeUtf8String("console");
2709     NewFunctionArgs args = NewFunctionArgs::ForFunctionWithoutCode(
2710         name, isolate_->strict_function_map(), LanguageMode::kStrict);
2711     Handle<JSFunction> cons = factory->NewFunction(args);
2712 
2713     Handle<JSObject> empty = factory->NewJSObject(isolate_->object_function());
2714     JSFunction::SetPrototype(cons, empty);
2715 
2716     Handle<JSObject> console = factory->NewJSObject(cons, AllocationType::kOld);
2717     DCHECK(console->IsJSObject());
2718     JSObject::AddProperty(isolate_, global, name, console, DONT_ENUM);
2719     SimpleInstallFunction(isolate_, console, "debug", Builtins::kConsoleDebug,
2720                           0, false, NONE);
2721     SimpleInstallFunction(isolate_, console, "error", Builtins::kConsoleError,
2722                           0, false, NONE);
2723     SimpleInstallFunction(isolate_, console, "info", Builtins::kConsoleInfo, 0,
2724                           false, NONE);
2725     SimpleInstallFunction(isolate_, console, "log", Builtins::kConsoleLog, 0,
2726                           false, NONE);
2727     SimpleInstallFunction(isolate_, console, "warn", Builtins::kConsoleWarn, 0,
2728                           false, NONE);
2729     SimpleInstallFunction(isolate_, console, "dir", Builtins::kConsoleDir, 0,
2730                           false, NONE);
2731     SimpleInstallFunction(isolate_, console, "dirxml", Builtins::kConsoleDirXml,
2732                           0, false, NONE);
2733     SimpleInstallFunction(isolate_, console, "table", Builtins::kConsoleTable,
2734                           0, false, NONE);
2735     SimpleInstallFunction(isolate_, console, "trace", Builtins::kConsoleTrace,
2736                           0, false, NONE);
2737     SimpleInstallFunction(isolate_, console, "group", Builtins::kConsoleGroup,
2738                           0, false, NONE);
2739     SimpleInstallFunction(isolate_, console, "groupCollapsed",
2740                           Builtins::kConsoleGroupCollapsed, 0, false, NONE);
2741     SimpleInstallFunction(isolate_, console, "groupEnd",
2742                           Builtins::kConsoleGroupEnd, 0, false, NONE);
2743     SimpleInstallFunction(isolate_, console, "clear", Builtins::kConsoleClear,
2744                           0, false, NONE);
2745     SimpleInstallFunction(isolate_, console, "count", Builtins::kConsoleCount,
2746                           0, false, NONE);
2747     SimpleInstallFunction(isolate_, console, "countReset",
2748                           Builtins::kConsoleCountReset, 0, false, NONE);
2749     SimpleInstallFunction(isolate_, console, "assert",
2750                           Builtins::kFastConsoleAssert, 0, false, NONE);
2751     SimpleInstallFunction(isolate_, console, "profile",
2752                           Builtins::kConsoleProfile, 0, false, NONE);
2753     SimpleInstallFunction(isolate_, console, "profileEnd",
2754                           Builtins::kConsoleProfileEnd, 0, false, NONE);
2755     SimpleInstallFunction(isolate_, console, "time", Builtins::kConsoleTime, 0,
2756                           false, NONE);
2757     SimpleInstallFunction(isolate_, console, "timeLog",
2758                           Builtins::kConsoleTimeLog, 0, false, NONE);
2759     SimpleInstallFunction(isolate_, console, "timeEnd",
2760                           Builtins::kConsoleTimeEnd, 0, false, NONE);
2761     SimpleInstallFunction(isolate_, console, "timeStamp",
2762                           Builtins::kConsoleTimeStamp, 0, false, NONE);
2763     SimpleInstallFunction(isolate_, console, "context",
2764                           Builtins::kConsoleContext, 1, true, NONE);
2765     InstallToStringTag(isolate_, console, "Object");
2766   }
2767 
2768 #ifdef V8_INTL_SUPPORT
2769   {  // -- I n t l
2770     Handle<JSObject> intl =
2771         factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
2772     JSObject::AddProperty(isolate_, global, "Intl", intl, DONT_ENUM);
2773 
2774     // ecma402 #sec-Intl-toStringTag
2775     // The initial value of the @@toStringTag property is the string value
2776     // *"Intl"*.
2777     InstallToStringTag(isolate_, intl, "Intl");
2778 
2779     SimpleInstallFunction(isolate(), intl, "getCanonicalLocales",
2780                           Builtins::kIntlGetCanonicalLocales, 1, false);
2781 
2782     {  // -- D a t e T i m e F o r m a t
2783       Handle<JSFunction> date_time_format_constructor = InstallFunction(
2784           isolate_, intl, "DateTimeFormat", JS_DATE_TIME_FORMAT_TYPE,
2785           JSDateTimeFormat::kHeaderSize, 0, factory->the_hole_value(),
2786           Builtins::kDateTimeFormatConstructor);
2787       date_time_format_constructor->shared().set_length(0);
2788       date_time_format_constructor->shared().DontAdaptArguments();
2789       InstallWithIntrinsicDefaultProto(
2790           isolate_, date_time_format_constructor,
2791           Context::INTL_DATE_TIME_FORMAT_FUNCTION_INDEX);
2792 
2793       SimpleInstallFunction(
2794           isolate(), date_time_format_constructor, "supportedLocalesOf",
2795           Builtins::kDateTimeFormatSupportedLocalesOf, 1, false);
2796 
2797       Handle<JSObject> prototype(
2798           JSObject::cast(date_time_format_constructor->prototype()), isolate_);
2799 
2800       InstallToStringTag(isolate_, prototype, "Intl.DateTimeFormat");
2801 
2802       SimpleInstallFunction(isolate_, prototype, "resolvedOptions",
2803                             Builtins::kDateTimeFormatPrototypeResolvedOptions,
2804                             0, false);
2805 
2806       SimpleInstallFunction(isolate_, prototype, "formatToParts",
2807                             Builtins::kDateTimeFormatPrototypeFormatToParts, 1,
2808                             false);
2809 
2810       SimpleInstallGetter(isolate_, prototype, factory->format_string(),
2811                           Builtins::kDateTimeFormatPrototypeFormat, false);
2812 
2813       SimpleInstallFunction(isolate_, prototype, "formatRange",
2814                             Builtins::kDateTimeFormatPrototypeFormatRange, 2,
2815                             false);
2816       SimpleInstallFunction(
2817           isolate_, prototype, "formatRangeToParts",
2818           Builtins::kDateTimeFormatPrototypeFormatRangeToParts, 2, false);
2819     }
2820 
2821     {  // -- N u m b e r F o r m a t
2822       Handle<JSFunction> number_format_constructor = InstallFunction(
2823           isolate_, intl, "NumberFormat", JS_NUMBER_FORMAT_TYPE,
2824           JSNumberFormat::kHeaderSize, 0, factory->the_hole_value(),
2825           Builtins::kNumberFormatConstructor);
2826       number_format_constructor->shared().set_length(0);
2827       number_format_constructor->shared().DontAdaptArguments();
2828       InstallWithIntrinsicDefaultProto(
2829           isolate_, number_format_constructor,
2830           Context::INTL_NUMBER_FORMAT_FUNCTION_INDEX);
2831 
2832       SimpleInstallFunction(
2833           isolate(), number_format_constructor, "supportedLocalesOf",
2834           Builtins::kNumberFormatSupportedLocalesOf, 1, false);
2835 
2836       Handle<JSObject> prototype(
2837           JSObject::cast(number_format_constructor->prototype()), isolate_);
2838 
2839       InstallToStringTag(isolate_, prototype, "Intl.NumberFormat");
2840 
2841       SimpleInstallFunction(isolate_, prototype, "resolvedOptions",
2842                             Builtins::kNumberFormatPrototypeResolvedOptions, 0,
2843                             false);
2844 
2845       SimpleInstallFunction(isolate_, prototype, "formatToParts",
2846                             Builtins::kNumberFormatPrototypeFormatToParts, 1,
2847                             false);
2848       SimpleInstallGetter(isolate_, prototype, factory->format_string(),
2849                           Builtins::kNumberFormatPrototypeFormatNumber, false);
2850     }
2851 
2852     {  // -- C o l l a t o r
2853       Handle<JSFunction> collator_constructor = InstallFunction(
2854           isolate_, intl, "Collator", JS_COLLATOR_TYPE, JSCollator::kHeaderSize,
2855           0, factory->the_hole_value(), Builtins::kCollatorConstructor);
2856       collator_constructor->shared().DontAdaptArguments();
2857       InstallWithIntrinsicDefaultProto(isolate_, collator_constructor,
2858                                        Context::INTL_COLLATOR_FUNCTION_INDEX);
2859 
2860       SimpleInstallFunction(isolate(), collator_constructor,
2861                             "supportedLocalesOf",
2862                             Builtins::kCollatorSupportedLocalesOf, 1, false);
2863 
2864       Handle<JSObject> prototype(
2865           JSObject::cast(collator_constructor->prototype()), isolate_);
2866 
2867       InstallToStringTag(isolate_, prototype, "Intl.Collator");
2868 
2869       SimpleInstallFunction(isolate_, prototype, "resolvedOptions",
2870                             Builtins::kCollatorPrototypeResolvedOptions, 0,
2871                             false);
2872 
2873       SimpleInstallGetter(isolate_, prototype, factory->compare_string(),
2874                           Builtins::kCollatorPrototypeCompare, false);
2875     }
2876 
2877     {  // -- V 8 B r e a k I t e r a t o r
2878       Handle<JSFunction> v8_break_iterator_constructor = InstallFunction(
2879           isolate_, intl, "v8BreakIterator", JS_V8_BREAK_ITERATOR_TYPE,
2880           JSV8BreakIterator::kHeaderSize, 0, factory->the_hole_value(),
2881           Builtins::kV8BreakIteratorConstructor);
2882       v8_break_iterator_constructor->shared().DontAdaptArguments();
2883 
2884       SimpleInstallFunction(
2885           isolate_, v8_break_iterator_constructor, "supportedLocalesOf",
2886           Builtins::kV8BreakIteratorSupportedLocalesOf, 1, false);
2887 
2888       Handle<JSObject> prototype(
2889           JSObject::cast(v8_break_iterator_constructor->prototype()), isolate_);
2890 
2891       InstallToStringTag(isolate_, prototype, factory->Object_string());
2892 
2893       SimpleInstallFunction(isolate_, prototype, "resolvedOptions",
2894                             Builtins::kV8BreakIteratorPrototypeResolvedOptions,
2895                             0, false);
2896 
2897       SimpleInstallGetter(isolate_, prototype, factory->adoptText_string(),
2898                           Builtins::kV8BreakIteratorPrototypeAdoptText, false);
2899 
2900       SimpleInstallGetter(isolate_, prototype, factory->first_string(),
2901                           Builtins::kV8BreakIteratorPrototypeFirst, false);
2902 
2903       SimpleInstallGetter(isolate_, prototype, factory->next_string(),
2904                           Builtins::kV8BreakIteratorPrototypeNext, false);
2905 
2906       SimpleInstallGetter(isolate_, prototype, factory->current_string(),
2907                           Builtins::kV8BreakIteratorPrototypeCurrent, false);
2908 
2909       SimpleInstallGetter(isolate_, prototype, factory->breakType_string(),
2910                           Builtins::kV8BreakIteratorPrototypeBreakType, false);
2911     }
2912 
2913     {  // -- P l u r a l R u l e s
2914       Handle<JSFunction> plural_rules_constructor = InstallFunction(
2915           isolate_, intl, "PluralRules", JS_PLURAL_RULES_TYPE,
2916           JSPluralRules::kHeaderSize, 0, factory->the_hole_value(),
2917           Builtins::kPluralRulesConstructor);
2918       plural_rules_constructor->shared().DontAdaptArguments();
2919       InstallWithIntrinsicDefaultProto(
2920           isolate_, plural_rules_constructor,
2921           Context::INTL_PLURAL_RULES_FUNCTION_INDEX);
2922 
2923       SimpleInstallFunction(isolate(), plural_rules_constructor,
2924                             "supportedLocalesOf",
2925                             Builtins::kPluralRulesSupportedLocalesOf, 1, false);
2926 
2927       Handle<JSObject> prototype(
2928           JSObject::cast(plural_rules_constructor->prototype()), isolate_);
2929 
2930       InstallToStringTag(isolate_, prototype, "Intl.PluralRules");
2931 
2932       SimpleInstallFunction(isolate_, prototype, "resolvedOptions",
2933                             Builtins::kPluralRulesPrototypeResolvedOptions, 0,
2934                             false);
2935 
2936       SimpleInstallFunction(isolate_, prototype, "select",
2937                             Builtins::kPluralRulesPrototypeSelect, 1, false);
2938     }
2939 
2940     {  // -- R e l a t i v e T i m e F o r m a t
2941       Handle<JSFunction> relative_time_format_fun = InstallFunction(
2942           isolate(), intl, "RelativeTimeFormat", JS_RELATIVE_TIME_FORMAT_TYPE,
2943           JSRelativeTimeFormat::kHeaderSize, 0, factory->the_hole_value(),
2944           Builtins::kRelativeTimeFormatConstructor);
2945       relative_time_format_fun->shared().set_length(0);
2946       relative_time_format_fun->shared().DontAdaptArguments();
2947       InstallWithIntrinsicDefaultProto(
2948           isolate_, relative_time_format_fun,
2949           Context::INTL_RELATIVE_TIME_FORMAT_FUNCTION_INDEX);
2950 
2951       SimpleInstallFunction(
2952           isolate(), relative_time_format_fun, "supportedLocalesOf",
2953           Builtins::kRelativeTimeFormatSupportedLocalesOf, 1, false);
2954 
2955       // Setup %RelativeTimeFormatPrototype%.
2956       Handle<JSObject> prototype(
2957           JSObject::cast(relative_time_format_fun->instance_prototype()),
2958           isolate());
2959 
2960       InstallToStringTag(isolate(), prototype, "Intl.RelativeTimeFormat");
2961 
2962       SimpleInstallFunction(
2963           isolate(), prototype, "resolvedOptions",
2964           Builtins::kRelativeTimeFormatPrototypeResolvedOptions, 0, false);
2965       SimpleInstallFunction(isolate(), prototype, "format",
2966                             Builtins::kRelativeTimeFormatPrototypeFormat, 2,
2967                             false);
2968       SimpleInstallFunction(isolate(), prototype, "formatToParts",
2969                             Builtins::kRelativeTimeFormatPrototypeFormatToParts,
2970                             2, false);
2971     }
2972 
2973     {  // -- L i s t F o r m a t
2974       Handle<JSFunction> list_format_fun = InstallFunction(
2975           isolate(), intl, "ListFormat", JS_LIST_FORMAT_TYPE,
2976           JSListFormat::kHeaderSize, 0, factory->the_hole_value(),
2977           Builtins::kListFormatConstructor);
2978       list_format_fun->shared().set_length(0);
2979       list_format_fun->shared().DontAdaptArguments();
2980       InstallWithIntrinsicDefaultProto(
2981           isolate_, list_format_fun, Context::INTL_LIST_FORMAT_FUNCTION_INDEX);
2982 
2983       SimpleInstallFunction(isolate(), list_format_fun, "supportedLocalesOf",
2984                             Builtins::kListFormatSupportedLocalesOf, 1, false);
2985 
2986       // Setup %ListFormatPrototype%.
2987       Handle<JSObject> prototype(
2988           JSObject::cast(list_format_fun->instance_prototype()), isolate());
2989 
2990       InstallToStringTag(isolate(), prototype, "Intl.ListFormat");
2991 
2992       SimpleInstallFunction(isolate(), prototype, "resolvedOptions",
2993                             Builtins::kListFormatPrototypeResolvedOptions, 0,
2994                             false);
2995       SimpleInstallFunction(isolate(), prototype, "format",
2996                             Builtins::kListFormatPrototypeFormat, 1, false);
2997       SimpleInstallFunction(isolate(), prototype, "formatToParts",
2998                             Builtins::kListFormatPrototypeFormatToParts, 1,
2999                             false);
3000     }
3001 
3002     {  // -- L o c a l e
3003       Handle<JSFunction> locale_fun = InstallFunction(
3004           isolate(), intl, "Locale", JS_LOCALE_TYPE, JSLocale::kHeaderSize, 0,
3005           factory->the_hole_value(), Builtins::kLocaleConstructor);
3006       InstallWithIntrinsicDefaultProto(isolate(), locale_fun,
3007                                        Context::INTL_LOCALE_FUNCTION_INDEX);
3008       locale_fun->shared().set_length(1);
3009       locale_fun->shared().DontAdaptArguments();
3010 
3011       // Setup %LocalePrototype%.
3012       Handle<JSObject> prototype(
3013           JSObject::cast(locale_fun->instance_prototype()), isolate());
3014 
3015       InstallToStringTag(isolate(), prototype, "Intl.Locale");
3016 
3017       SimpleInstallFunction(isolate(), prototype, "toString",
3018                             Builtins::kLocalePrototypeToString, 0, false);
3019       SimpleInstallFunction(isolate(), prototype, "maximize",
3020                             Builtins::kLocalePrototypeMaximize, 0, false);
3021       SimpleInstallFunction(isolate(), prototype, "minimize",
3022                             Builtins::kLocalePrototypeMinimize, 0, false);
3023       // Base locale getters.
3024       SimpleInstallGetter(isolate(), prototype, factory->language_string(),
3025                           Builtins::kLocalePrototypeLanguage, true);
3026       SimpleInstallGetter(isolate(), prototype, factory->script_string(),
3027                           Builtins::kLocalePrototypeScript, true);
3028       SimpleInstallGetter(isolate(), prototype, factory->region_string(),
3029                           Builtins::kLocalePrototypeRegion, true);
3030       SimpleInstallGetter(isolate(), prototype, factory->baseName_string(),
3031                           Builtins::kLocalePrototypeBaseName, true);
3032       // Unicode extension getters.
3033       SimpleInstallGetter(isolate(), prototype, factory->calendar_string(),
3034                           Builtins::kLocalePrototypeCalendar, true);
3035       SimpleInstallGetter(isolate(), prototype, factory->caseFirst_string(),
3036                           Builtins::kLocalePrototypeCaseFirst, true);
3037       SimpleInstallGetter(isolate(), prototype, factory->collation_string(),
3038                           Builtins::kLocalePrototypeCollation, true);
3039       SimpleInstallGetter(isolate(), prototype, factory->hourCycle_string(),
3040                           Builtins::kLocalePrototypeHourCycle, true);
3041       SimpleInstallGetter(isolate(), prototype, factory->numeric_string(),
3042                           Builtins::kLocalePrototypeNumeric, true);
3043       SimpleInstallGetter(isolate(), prototype,
3044                           factory->numberingSystem_string(),
3045                           Builtins::kLocalePrototypeNumberingSystem, true);
3046     }
3047 
3048     {  // -- D i s p l a y N a m e s
3049       Handle<JSFunction> display_names_fun = InstallFunction(
3050           isolate(), intl, "DisplayNames", JS_DISPLAY_NAMES_TYPE,
3051           JSDisplayNames::kHeaderSize, 0, factory->the_hole_value(),
3052           Builtins::kDisplayNamesConstructor);
3053       display_names_fun->shared().set_length(2);
3054       display_names_fun->shared().DontAdaptArguments();
3055       InstallWithIntrinsicDefaultProto(
3056           isolate(), display_names_fun,
3057           Context::INTL_DISPLAY_NAMES_FUNCTION_INDEX);
3058 
3059       SimpleInstallFunction(isolate(), display_names_fun, "supportedLocalesOf",
3060                             Builtins::kDisplayNamesSupportedLocalesOf, 1,
3061                             false);
3062 
3063       {
3064         // Setup %DisplayNamesPrototype%.
3065         Handle<JSObject> prototype(
3066             JSObject::cast(display_names_fun->instance_prototype()), isolate());
3067 
3068         InstallToStringTag(isolate(), prototype, "Intl.DisplayNames");
3069 
3070         SimpleInstallFunction(isolate(), prototype, "resolvedOptions",
3071                               Builtins::kDisplayNamesPrototypeResolvedOptions,
3072                               0, false);
3073 
3074         SimpleInstallFunction(isolate(), prototype, "of",
3075                               Builtins::kDisplayNamesPrototypeOf, 1, false);
3076       }
3077     }
3078   }
3079 #endif  // V8_INTL_SUPPORT
3080 
3081   {  // -- A r r a y B u f f e r
3082     Handle<String> name = factory->ArrayBuffer_string();
3083     Handle<JSFunction> array_buffer_fun = CreateArrayBuffer(name, ARRAY_BUFFER);
3084     JSObject::AddProperty(isolate_, global, name, array_buffer_fun, DONT_ENUM);
3085     InstallWithIntrinsicDefaultProto(isolate_, array_buffer_fun,
3086                                      Context::ARRAY_BUFFER_FUN_INDEX);
3087     InstallSpeciesGetter(isolate_, array_buffer_fun);
3088 
3089     Handle<JSFunction> array_buffer_noinit_fun = SimpleCreateFunction(
3090         isolate_,
3091         factory->InternalizeUtf8String(
3092             "arrayBufferConstructor_DoNotInitialize"),
3093         Builtins::kArrayBufferConstructor_DoNotInitialize, 1, false);
3094     native_context()->set_array_buffer_noinit_fun(*array_buffer_noinit_fun);
3095   }
3096 
3097   {  // -- S h a r e d A r r a y B u f f e r
3098     Handle<String> name = factory->SharedArrayBuffer_string();
3099     Handle<JSFunction> shared_array_buffer_fun =
3100         CreateArrayBuffer(name, SHARED_ARRAY_BUFFER);
3101     InstallWithIntrinsicDefaultProto(isolate_, shared_array_buffer_fun,
3102                                      Context::SHARED_ARRAY_BUFFER_FUN_INDEX);
3103     InstallSpeciesGetter(isolate_, shared_array_buffer_fun);
3104   }
3105 
3106   {  // -- A t o m i c s
3107     Handle<JSObject> atomics_object =
3108         factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
3109     native_context()->set_atomics_object(*atomics_object);
3110 
3111     SimpleInstallFunction(isolate_, atomics_object, "load",
3112                           Builtins::kAtomicsLoad, 2, true);
3113     SimpleInstallFunction(isolate_, atomics_object, "store",
3114                           Builtins::kAtomicsStore, 3, true);
3115     SimpleInstallFunction(isolate_, atomics_object, "add",
3116                           Builtins::kAtomicsAdd, 3, true);
3117     SimpleInstallFunction(isolate_, atomics_object, "sub",
3118                           Builtins::kAtomicsSub, 3, true);
3119     SimpleInstallFunction(isolate_, atomics_object, "and",
3120                           Builtins::kAtomicsAnd, 3, true);
3121     SimpleInstallFunction(isolate_, atomics_object, "or", Builtins::kAtomicsOr,
3122                           3, true);
3123     SimpleInstallFunction(isolate_, atomics_object, "xor",
3124                           Builtins::kAtomicsXor, 3, true);
3125     SimpleInstallFunction(isolate_, atomics_object, "exchange",
3126                           Builtins::kAtomicsExchange, 3, true);
3127     SimpleInstallFunction(isolate_, atomics_object, "compareExchange",
3128                           Builtins::kAtomicsCompareExchange, 4, true);
3129     SimpleInstallFunction(isolate_, atomics_object, "isLockFree",
3130                           Builtins::kAtomicsIsLockFree, 1, true);
3131     SimpleInstallFunction(isolate_, atomics_object, "wait",
3132                           Builtins::kAtomicsWait, 4, true);
3133     SimpleInstallFunction(isolate_, atomics_object, "notify",
3134                           Builtins::kAtomicsNotify, 3, true);
3135   }
3136 
3137   {  // -- T y p e d A r r a y
3138     Handle<JSFunction> typed_array_fun = CreateFunction(
3139         isolate_, factory->InternalizeUtf8String("TypedArray"),
3140         JS_TYPED_ARRAY_TYPE, JSTypedArray::kHeaderSize, 0,
3141         factory->the_hole_value(), Builtins::kTypedArrayBaseConstructor);
3142     typed_array_fun->shared().set_native(false);
3143     typed_array_fun->shared().set_length(0);
3144     InstallSpeciesGetter(isolate_, typed_array_fun);
3145     native_context()->set_typed_array_function(*typed_array_fun);
3146 
3147     SimpleInstallFunction(isolate_, typed_array_fun, "of",
3148                           Builtins::kTypedArrayOf, 0, false);
3149     SimpleInstallFunction(isolate_, typed_array_fun, "from",
3150                           Builtins::kTypedArrayFrom, 1, false);
3151 
3152     // Setup %TypedArrayPrototype%.
3153     Handle<JSObject> prototype(
3154         JSObject::cast(typed_array_fun->instance_prototype()), isolate());
3155     native_context()->set_typed_array_prototype(*prototype);
3156 
3157     // Install the "buffer", "byteOffset", "byteLength", "length"
3158     // and @@toStringTag getters on the {prototype}.
3159     SimpleInstallGetter(isolate_, prototype, factory->buffer_string(),
3160                         Builtins::kTypedArrayPrototypeBuffer, false);
3161     SimpleInstallGetter(isolate_, prototype, factory->byte_length_string(),
3162                         Builtins::kTypedArrayPrototypeByteLength, true);
3163     SimpleInstallGetter(isolate_, prototype, factory->byte_offset_string(),
3164                         Builtins::kTypedArrayPrototypeByteOffset, true);
3165     SimpleInstallGetter(isolate_, prototype, factory->length_string(),
3166                         Builtins::kTypedArrayPrototypeLength, true);
3167     SimpleInstallGetter(isolate_, prototype, factory->to_string_tag_symbol(),
3168                         Builtins::kTypedArrayPrototypeToStringTag, true);
3169 
3170     // Install "keys", "values" and "entries" methods on the {prototype}.
3171     InstallFunctionWithBuiltinId(isolate_, prototype, "entries",
3172                                  Builtins::kTypedArrayPrototypeEntries, 0,
3173                                  true);
3174 
3175     InstallFunctionWithBuiltinId(isolate_, prototype, "keys",
3176                                  Builtins::kTypedArrayPrototypeKeys, 0, true);
3177 
3178     Handle<JSFunction> values = InstallFunctionWithBuiltinId(
3179         isolate_, prototype, "values", Builtins::kTypedArrayPrototypeValues, 0,
3180         true);
3181     JSObject::AddProperty(isolate_, prototype, factory->iterator_symbol(),
3182                           values, DONT_ENUM);
3183 
3184     // TODO(caitp): alphasort accessors/methods
3185     SimpleInstallFunction(isolate_, prototype, "copyWithin",
3186                           Builtins::kTypedArrayPrototypeCopyWithin, 2, false);
3187     SimpleInstallFunction(isolate_, prototype, "every",
3188                           Builtins::kTypedArrayPrototypeEvery, 1, false);
3189     SimpleInstallFunction(isolate_, prototype, "fill",
3190                           Builtins::kTypedArrayPrototypeFill, 1, false);
3191     SimpleInstallFunction(isolate_, prototype, "filter",
3192                           Builtins::kTypedArrayPrototypeFilter, 1, false);
3193     SimpleInstallFunction(isolate_, prototype, "find",
3194                           Builtins::kTypedArrayPrototypeFind, 1, false);
3195     SimpleInstallFunction(isolate_, prototype, "findIndex",
3196                           Builtins::kTypedArrayPrototypeFindIndex, 1, false);
3197     SimpleInstallFunction(isolate_, prototype, "forEach",
3198                           Builtins::kTypedArrayPrototypeForEach, 1, false);
3199     SimpleInstallFunction(isolate_, prototype, "includes",
3200                           Builtins::kTypedArrayPrototypeIncludes, 1, false);
3201     SimpleInstallFunction(isolate_, prototype, "indexOf",
3202                           Builtins::kTypedArrayPrototypeIndexOf, 1, false);
3203     SimpleInstallFunction(isolate_, prototype, "join",
3204                           Builtins::kTypedArrayPrototypeJoin, 1, false);
3205     SimpleInstallFunction(isolate_, prototype, "lastIndexOf",
3206                           Builtins::kTypedArrayPrototypeLastIndexOf, 1, false);
3207     SimpleInstallFunction(isolate_, prototype, "map",
3208                           Builtins::kTypedArrayPrototypeMap, 1, false);
3209     SimpleInstallFunction(isolate_, prototype, "reverse",
3210                           Builtins::kTypedArrayPrototypeReverse, 0, false);
3211     SimpleInstallFunction(isolate_, prototype, "reduce",
3212                           Builtins::kTypedArrayPrototypeReduce, 1, false);
3213     SimpleInstallFunction(isolate_, prototype, "reduceRight",
3214                           Builtins::kTypedArrayPrototypeReduceRight, 1, false);
3215     SimpleInstallFunction(isolate_, prototype, "set",
3216                           Builtins::kTypedArrayPrototypeSet, 1, false);
3217     SimpleInstallFunction(isolate_, prototype, "slice",
3218                           Builtins::kTypedArrayPrototypeSlice, 2, false);
3219     SimpleInstallFunction(isolate_, prototype, "some",
3220                           Builtins::kTypedArrayPrototypeSome, 1, false);
3221     SimpleInstallFunction(isolate_, prototype, "sort",
3222                           Builtins::kTypedArrayPrototypeSort, 1, false);
3223     SimpleInstallFunction(isolate_, prototype, "subarray",
3224                           Builtins::kTypedArrayPrototypeSubArray, 2, false);
3225     SimpleInstallFunction(isolate_, prototype, "toLocaleString",
3226                           Builtins::kTypedArrayPrototypeToLocaleString, 0,
3227                           false);
3228     JSObject::AddProperty(isolate_, prototype, factory->toString_string(),
3229                           array_prototype_to_string_fun, DONT_ENUM);
3230   }
3231 
3232   {// -- T y p e d A r r a y s
3233 #define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype)                   \
3234   {                                                                    \
3235     Handle<JSFunction> fun =                                           \
3236         InstallTypedArray(#Type "Array", TYPE##_ELEMENTS);             \
3237     InstallWithIntrinsicDefaultProto(isolate_, fun,                    \
3238                                      Context::TYPE##_ARRAY_FUN_INDEX); \
3239   }
3240   TYPED_ARRAYS(INSTALL_TYPED_ARRAY)
3241 #undef INSTALL_TYPED_ARRAY
3242   }
3243 
3244   {  // -- D a t a V i e w
3245     Handle<JSFunction> data_view_fun = InstallFunction(
3246         isolate_, global, "DataView", JS_DATA_VIEW_TYPE,
3247         JSDataView::kSizeWithEmbedderFields, 0, factory->the_hole_value(),
3248         Builtins::kDataViewConstructor);
3249     InstallWithIntrinsicDefaultProto(isolate_, data_view_fun,
3250                                      Context::DATA_VIEW_FUN_INDEX);
3251     data_view_fun->shared().set_length(1);
3252     data_view_fun->shared().DontAdaptArguments();
3253 
3254     // Setup %DataViewPrototype%.
3255     Handle<JSObject> prototype(
3256         JSObject::cast(data_view_fun->instance_prototype()), isolate());
3257 
3258     InstallToStringTag(isolate_, prototype, "DataView");
3259 
3260     // Install the "buffer", "byteOffset" and "byteLength" getters
3261     // on the {prototype}.
3262     SimpleInstallGetter(isolate_, prototype, factory->buffer_string(),
3263                         Builtins::kDataViewPrototypeGetBuffer, false);
3264     SimpleInstallGetter(isolate_, prototype, factory->byte_length_string(),
3265                         Builtins::kDataViewPrototypeGetByteLength, false);
3266     SimpleInstallGetter(isolate_, prototype, factory->byte_offset_string(),
3267                         Builtins::kDataViewPrototypeGetByteOffset, false);
3268 
3269     SimpleInstallFunction(isolate_, prototype, "getInt8",
3270                           Builtins::kDataViewPrototypeGetInt8, 1, false);
3271     SimpleInstallFunction(isolate_, prototype, "setInt8",
3272                           Builtins::kDataViewPrototypeSetInt8, 2, false);
3273     SimpleInstallFunction(isolate_, prototype, "getUint8",
3274                           Builtins::kDataViewPrototypeGetUint8, 1, false);
3275     SimpleInstallFunction(isolate_, prototype, "setUint8",
3276                           Builtins::kDataViewPrototypeSetUint8, 2, false);
3277     SimpleInstallFunction(isolate_, prototype, "getInt16",
3278                           Builtins::kDataViewPrototypeGetInt16, 1, false);
3279     SimpleInstallFunction(isolate_, prototype, "setInt16",
3280                           Builtins::kDataViewPrototypeSetInt16, 2, false);
3281     SimpleInstallFunction(isolate_, prototype, "getUint16",
3282                           Builtins::kDataViewPrototypeGetUint16, 1, false);
3283     SimpleInstallFunction(isolate_, prototype, "setUint16",
3284                           Builtins::kDataViewPrototypeSetUint16, 2, false);
3285     SimpleInstallFunction(isolate_, prototype, "getInt32",
3286                           Builtins::kDataViewPrototypeGetInt32, 1, false);
3287     SimpleInstallFunction(isolate_, prototype, "setInt32",
3288                           Builtins::kDataViewPrototypeSetInt32, 2, false);
3289     SimpleInstallFunction(isolate_, prototype, "getUint32",
3290                           Builtins::kDataViewPrototypeGetUint32, 1, false);
3291     SimpleInstallFunction(isolate_, prototype, "setUint32",
3292                           Builtins::kDataViewPrototypeSetUint32, 2, false);
3293     SimpleInstallFunction(isolate_, prototype, "getFloat32",
3294                           Builtins::kDataViewPrototypeGetFloat32, 1, false);
3295     SimpleInstallFunction(isolate_, prototype, "setFloat32",
3296                           Builtins::kDataViewPrototypeSetFloat32, 2, false);
3297     SimpleInstallFunction(isolate_, prototype, "getFloat64",
3298                           Builtins::kDataViewPrototypeGetFloat64, 1, false);
3299     SimpleInstallFunction(isolate_, prototype, "setFloat64",
3300                           Builtins::kDataViewPrototypeSetFloat64, 2, false);
3301     SimpleInstallFunction(isolate_, prototype, "getBigInt64",
3302                           Builtins::kDataViewPrototypeGetBigInt64, 1, false);
3303     SimpleInstallFunction(isolate_, prototype, "setBigInt64",
3304                           Builtins::kDataViewPrototypeSetBigInt64, 2, false);
3305     SimpleInstallFunction(isolate_, prototype, "getBigUint64",
3306                           Builtins::kDataViewPrototypeGetBigUint64, 1, false);
3307     SimpleInstallFunction(isolate_, prototype, "setBigUint64",
3308                           Builtins::kDataViewPrototypeSetBigUint64, 2, false);
3309   }
3310 
3311   {  // -- M a p
3312     Handle<JSFunction> js_map_fun = InstallFunction(
3313         isolate_, global, "Map", JS_MAP_TYPE, JSMap::kHeaderSize, 0,
3314         factory->the_hole_value(), Builtins::kMapConstructor);
3315     InstallWithIntrinsicDefaultProto(isolate_, js_map_fun,
3316                                      Context::JS_MAP_FUN_INDEX);
3317 
3318     Handle<SharedFunctionInfo> shared(js_map_fun->shared(), isolate_);
3319     shared->DontAdaptArguments();
3320     shared->set_length(0);
3321 
3322     // Setup %MapPrototype%.
3323     Handle<JSObject> prototype(JSObject::cast(js_map_fun->instance_prototype()),
3324                                isolate());
3325 
3326     InstallToStringTag(isolate_, prototype, factory->Map_string());
3327 
3328     Handle<JSFunction> map_get = SimpleInstallFunction(
3329         isolate_, prototype, "get", Builtins::kMapPrototypeGet, 1, true);
3330     native_context()->set_map_get(*map_get);
3331 
3332     Handle<JSFunction> map_set = SimpleInstallFunction(
3333         isolate_, prototype, "set", Builtins::kMapPrototypeSet, 2, true);
3334     // Check that index of "set" function in JSCollection is correct.
3335     DCHECK_EQ(JSCollection::kAddFunctionDescriptorIndex,
3336               prototype->map().LastAdded().as_int());
3337     native_context()->set_map_set(*map_set);
3338 
3339     Handle<JSFunction> map_has = SimpleInstallFunction(
3340         isolate_, prototype, "has", Builtins::kMapPrototypeHas, 1, true);
3341     native_context()->set_map_has(*map_has);
3342 
3343     Handle<JSFunction> map_delete = SimpleInstallFunction(
3344         isolate_, prototype, "delete", Builtins::kMapPrototypeDelete, 1, true);
3345     native_context()->set_map_delete(*map_delete);
3346 
3347     SimpleInstallFunction(isolate_, prototype, "clear",
3348                           Builtins::kMapPrototypeClear, 0, true);
3349     Handle<JSFunction> entries =
3350         SimpleInstallFunction(isolate_, prototype, "entries",
3351                               Builtins::kMapPrototypeEntries, 0, true);
3352     JSObject::AddProperty(isolate_, prototype, factory->iterator_symbol(),
3353                           entries, DONT_ENUM);
3354     SimpleInstallFunction(isolate_, prototype, "forEach",
3355                           Builtins::kMapPrototypeForEach, 1, false);
3356     SimpleInstallFunction(isolate_, prototype, "keys",
3357                           Builtins::kMapPrototypeKeys, 0, true);
3358     SimpleInstallGetter(isolate_, prototype,
3359                         factory->InternalizeUtf8String("size"),
3360                         Builtins::kMapPrototypeGetSize, true);
3361     SimpleInstallFunction(isolate_, prototype, "values",
3362                           Builtins::kMapPrototypeValues, 0, true);
3363 
3364     native_context()->set_initial_map_prototype_map(prototype->map());
3365 
3366     InstallSpeciesGetter(isolate_, js_map_fun);
3367 
3368     DCHECK(js_map_fun->HasFastProperties());
3369 
3370     native_context()->set_js_map_map(js_map_fun->initial_map());
3371   }
3372 
3373   {  // -- B i g I n t
3374     Handle<JSFunction> bigint_fun = InstallFunction(
3375         isolate_, global, "BigInt", JS_PRIMITIVE_WRAPPER_TYPE,
3376         JSPrimitiveWrapper::kHeaderSize, 0, factory->the_hole_value(),
3377         Builtins::kBigIntConstructor);
3378     bigint_fun->shared().DontAdaptArguments();
3379     bigint_fun->shared().set_length(1);
3380     InstallWithIntrinsicDefaultProto(isolate_, bigint_fun,
3381                                      Context::BIGINT_FUNCTION_INDEX);
3382 
3383     // Install the properties of the BigInt constructor.
3384     // asUintN(bits, bigint)
3385     SimpleInstallFunction(isolate_, bigint_fun, "asUintN",
3386                           Builtins::kBigIntAsUintN, 2, false);
3387     // asIntN(bits, bigint)
3388     SimpleInstallFunction(isolate_, bigint_fun, "asIntN",
3389                           Builtins::kBigIntAsIntN, 2, false);
3390 
3391     // Set up the %BigIntPrototype%.
3392     Handle<JSObject> prototype(JSObject::cast(bigint_fun->instance_prototype()),
3393                                isolate_);
3394     JSFunction::SetPrototype(bigint_fun, prototype);
3395 
3396     // Install the properties of the BigInt.prototype.
3397     // "constructor" is created implicitly by InstallFunction() above.
3398     // toLocaleString([reserved1 [, reserved2]])
3399     SimpleInstallFunction(isolate_, prototype, "toLocaleString",
3400                           Builtins::kBigIntPrototypeToLocaleString, 0, false);
3401     // toString([radix])
3402     SimpleInstallFunction(isolate_, prototype, "toString",
3403                           Builtins::kBigIntPrototypeToString, 0, false);
3404     // valueOf()
3405     SimpleInstallFunction(isolate_, prototype, "valueOf",
3406                           Builtins::kBigIntPrototypeValueOf, 0, false);
3407     // @@toStringTag
3408     InstallToStringTag(isolate_, prototype, factory->BigInt_string());
3409   }
3410 
3411   {  // -- S e t
3412     Handle<JSFunction> js_set_fun = InstallFunction(
3413         isolate_, global, "Set", JS_SET_TYPE, JSSet::kHeaderSize, 0,
3414         factory->the_hole_value(), Builtins::kSetConstructor);
3415     InstallWithIntrinsicDefaultProto(isolate_, js_set_fun,
3416                                      Context::JS_SET_FUN_INDEX);
3417 
3418     Handle<SharedFunctionInfo> shared(js_set_fun->shared(), isolate_);
3419     shared->DontAdaptArguments();
3420     shared->set_length(0);
3421 
3422     // Setup %SetPrototype%.
3423     Handle<JSObject> prototype(JSObject::cast(js_set_fun->instance_prototype()),
3424                                isolate());
3425 
3426     InstallToStringTag(isolate_, prototype, factory->Set_string());
3427 
3428     Handle<JSFunction> set_has = SimpleInstallFunction(
3429         isolate_, prototype, "has", Builtins::kSetPrototypeHas, 1, true);
3430     native_context()->set_set_has(*set_has);
3431 
3432     Handle<JSFunction> set_add = SimpleInstallFunction(
3433         isolate_, prototype, "add", Builtins::kSetPrototypeAdd, 1, true);
3434     // Check that index of "add" function in JSCollection is correct.
3435     DCHECK_EQ(JSCollection::kAddFunctionDescriptorIndex,
3436               prototype->map().LastAdded().as_int());
3437     native_context()->set_set_add(*set_add);
3438 
3439     Handle<JSFunction> set_delete = SimpleInstallFunction(
3440         isolate_, prototype, "delete", Builtins::kSetPrototypeDelete, 1, true);
3441     native_context()->set_set_delete(*set_delete);
3442 
3443     SimpleInstallFunction(isolate_, prototype, "clear",
3444                           Builtins::kSetPrototypeClear, 0, true);
3445     SimpleInstallFunction(isolate_, prototype, "entries",
3446                           Builtins::kSetPrototypeEntries, 0, true);
3447     SimpleInstallFunction(isolate_, prototype, "forEach",
3448                           Builtins::kSetPrototypeForEach, 1, false);
3449     SimpleInstallGetter(isolate_, prototype,
3450                         factory->InternalizeUtf8String("size"),
3451                         Builtins::kSetPrototypeGetSize, true);
3452     Handle<JSFunction> values = SimpleInstallFunction(
3453         isolate_, prototype, "values", Builtins::kSetPrototypeValues, 0, true);
3454     JSObject::AddProperty(isolate_, prototype, factory->keys_string(), values,
3455                           DONT_ENUM);
3456     JSObject::AddProperty(isolate_, prototype, factory->iterator_symbol(),
3457                           values, DONT_ENUM);
3458 
3459     native_context()->set_initial_set_prototype_map(prototype->map());
3460     native_context()->set_initial_set_prototype(*prototype);
3461 
3462     InstallSpeciesGetter(isolate_, js_set_fun);
3463 
3464     DCHECK(js_set_fun->HasFastProperties());
3465 
3466     native_context()->set_js_set_map(js_set_fun->initial_map());
3467   }
3468 
3469   {  // -- J S M o d u l e N a m e s p a c e
3470     Handle<Map> map = factory->NewMap(
3471         JS_MODULE_NAMESPACE_TYPE, JSModuleNamespace::kSize,
3472         TERMINAL_FAST_ELEMENTS_KIND, JSModuleNamespace::kInObjectFieldCount);
3473     map->SetConstructor(native_context()->object_function());
3474     Map::SetPrototype(isolate(), map, isolate_->factory()->null_value());
3475     Map::EnsureDescriptorSlack(isolate_, map, 1);
3476     native_context()->set_js_module_namespace_map(*map);
3477 
3478     {  // Install @@toStringTag.
3479       PropertyAttributes attribs =
3480           static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY);
3481       Descriptor d =
3482           Descriptor::DataField(isolate(), factory->to_string_tag_symbol(),
3483                                 JSModuleNamespace::kToStringTagFieldIndex,
3484                                 attribs, Representation::Tagged());
3485       map->AppendDescriptor(isolate(), &d);
3486     }
3487   }
3488 
3489   {  // -- I t e r a t o r R e s u l t
3490     // Setup the map for IterResultObjects created from builtins in such a
3491     // way that it's exactly the same map as the one produced by object
3492     // literals in the form `{value, done}`. This way we have better sharing
3493     // of maps (i.e. less polymorphism) and also make it possible to hit the
3494     // fast-paths in various builtins (i.e. promises and collections) with
3495     // user defined iterators.
3496     Handle<Map> map = factory->ObjectLiteralMapFromCache(native_context(), 2);
3497 
3498     // value
3499     map = Map::CopyWithField(isolate(), map, factory->value_string(),
3500                              FieldType::Any(isolate()), NONE,
3501                              PropertyConstness::kConst,
3502                              Representation::Tagged(), INSERT_TRANSITION)
3503               .ToHandleChecked();
3504 
3505     // done
3506     // TODO(bmeurer): Once FLAG_modify_field_representation_inplace is always
3507     // on, we can say Representation::HeapObject() here and have the inplace
3508     // update logic take care of the case where someone ever stores a Smi into
3509     // the done field.
3510     map = Map::CopyWithField(isolate(), map, factory->done_string(),
3511                              FieldType::Any(isolate()), NONE,
3512                              PropertyConstness::kConst,
3513                              Representation::Tagged(), INSERT_TRANSITION)
3514               .ToHandleChecked();
3515 
3516     native_context()->set_iterator_result_map(*map);
3517   }
3518 
3519   {  // -- W e a k M a p
3520     Handle<JSFunction> cons = InstallFunction(
3521         isolate_, global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kHeaderSize,
3522         0, factory->the_hole_value(), Builtins::kWeakMapConstructor);
3523     InstallWithIntrinsicDefaultProto(isolate_, cons,
3524                                      Context::JS_WEAK_MAP_FUN_INDEX);
3525 
3526     Handle<SharedFunctionInfo> shared(cons->shared(), isolate_);
3527     shared->DontAdaptArguments();
3528     shared->set_length(0);
3529 
3530     // Setup %WeakMapPrototype%.
3531     Handle<JSObject> prototype(JSObject::cast(cons->instance_prototype()),
3532                                isolate());
3533 
3534     SimpleInstallFunction(isolate_, prototype, "delete",
3535                           Builtins::kWeakMapPrototypeDelete, 1, true);
3536     Handle<JSFunction> weakmap_get = SimpleInstallFunction(
3537         isolate_, prototype, "get", Builtins::kWeakMapGet, 1, true);
3538     native_context()->set_weakmap_get(*weakmap_get);
3539 
3540     Handle<JSFunction> weakmap_set = SimpleInstallFunction(
3541         isolate_, prototype, "set", Builtins::kWeakMapPrototypeSet, 2, true);
3542     // Check that index of "set" function in JSWeakCollection is correct.
3543     DCHECK_EQ(JSWeakCollection::kAddFunctionDescriptorIndex,
3544               prototype->map().LastAdded().as_int());
3545 
3546     native_context()->set_weakmap_set(*weakmap_set);
3547     SimpleInstallFunction(isolate_, prototype, "has",
3548                           Builtins::kWeakMapPrototypeHas, 1, true);
3549 
3550     InstallToStringTag(isolate_, prototype, "WeakMap");
3551 
3552     native_context()->set_initial_weakmap_prototype_map(prototype->map());
3553   }
3554 
3555   {  // -- W e a k S e t
3556     Handle<JSFunction> cons = InstallFunction(
3557         isolate_, global, "WeakSet", JS_WEAK_SET_TYPE, JSWeakSet::kHeaderSize,
3558         0, factory->the_hole_value(), Builtins::kWeakSetConstructor);
3559     InstallWithIntrinsicDefaultProto(isolate_, cons,
3560                                      Context::JS_WEAK_SET_FUN_INDEX);
3561 
3562     Handle<SharedFunctionInfo> shared(cons->shared(), isolate_);
3563     shared->DontAdaptArguments();
3564     shared->set_length(0);
3565 
3566     // Setup %WeakSetPrototype%.
3567     Handle<JSObject> prototype(JSObject::cast(cons->instance_prototype()),
3568                                isolate());
3569 
3570     SimpleInstallFunction(isolate_, prototype, "delete",
3571                           Builtins::kWeakSetPrototypeDelete, 1, true);
3572     SimpleInstallFunction(isolate_, prototype, "has",
3573                           Builtins::kWeakSetPrototypeHas, 1, true);
3574 
3575     Handle<JSFunction> weakset_add = SimpleInstallFunction(
3576         isolate_, prototype, "add", Builtins::kWeakSetPrototypeAdd, 1, true);
3577     // Check that index of "add" function in JSWeakCollection is correct.
3578     DCHECK_EQ(JSWeakCollection::kAddFunctionDescriptorIndex,
3579               prototype->map().LastAdded().as_int());
3580 
3581     native_context()->set_weakset_add(*weakset_add);
3582 
3583     InstallToStringTag(isolate_, prototype,
3584                        factory->InternalizeUtf8String("WeakSet"));
3585 
3586     native_context()->set_initial_weakset_prototype_map(prototype->map());
3587   }
3588 
3589   {  // -- P r o x y
3590     CreateJSProxyMaps();
3591     // Proxy function map has prototype slot for storing initial map but does
3592     // not have a prototype property.
3593     Handle<Map> proxy_function_map = Map::Copy(
3594         isolate_, isolate_->strict_function_without_prototype_map(), "Proxy");
3595     proxy_function_map->set_is_constructor(true);
3596 
3597     Handle<String> name = factory->Proxy_string();
3598 
3599     NewFunctionArgs args = NewFunctionArgs::ForBuiltin(
3600         name, proxy_function_map, Builtins::kProxyConstructor);
3601     Handle<JSFunction> proxy_function = factory->NewFunction(args);
3602 
3603     isolate_->proxy_map()->SetConstructor(*proxy_function);
3604 
3605     proxy_function->shared().set_internal_formal_parameter_count(2);
3606     proxy_function->shared().set_length(2);
3607 
3608     native_context()->set_proxy_function(*proxy_function);
3609     JSObject::AddProperty(isolate_, global, name, proxy_function, DONT_ENUM);
3610 
3611     DCHECK(!proxy_function->has_prototype_property());
3612 
3613     SimpleInstallFunction(isolate_, proxy_function, "revocable",
3614                           Builtins::kProxyRevocable, 2, true);
3615   }
3616 
3617   {  // -- R e f l e c t
3618     Handle<String> reflect_string = factory->InternalizeUtf8String("Reflect");
3619     Handle<JSObject> reflect =
3620         factory->NewJSObject(isolate_->object_function(), AllocationType::kOld);
3621     JSObject::AddProperty(isolate_, global, reflect_string, reflect, DONT_ENUM);
3622     InstallToStringTag(isolate_, reflect, reflect_string);
3623 
3624     SimpleInstallFunction(isolate_, reflect, "defineProperty",
3625                           Builtins::kReflectDefineProperty, 3, true);
3626 
3627     SimpleInstallFunction(isolate_, reflect, "deleteProperty",
3628                           Builtins::kReflectDeleteProperty, 2, true);
3629 
3630     Handle<JSFunction> apply = SimpleInstallFunction(
3631         isolate_, reflect, "apply", Builtins::kReflectApply, 3, false);
3632     native_context()->set_reflect_apply(*apply);
3633 
3634     Handle<JSFunction> construct = SimpleInstallFunction(
3635         isolate_, reflect, "construct", Builtins::kReflectConstruct, 2, false);
3636     native_context()->set_reflect_construct(*construct);
3637 
3638     SimpleInstallFunction(isolate_, reflect, "get", Builtins::kReflectGet, 2,
3639                           false);
3640     SimpleInstallFunction(isolate_, reflect, "getOwnPropertyDescriptor",
3641                           Builtins::kReflectGetOwnPropertyDescriptor, 2, true);
3642     SimpleInstallFunction(isolate_, reflect, "getPrototypeOf",
3643                           Builtins::kReflectGetPrototypeOf, 1, true);
3644     SimpleInstallFunction(isolate_, reflect, "has", Builtins::kReflectHas, 2,
3645                           true);
3646     SimpleInstallFunction(isolate_, reflect, "isExtensible",
3647                           Builtins::kReflectIsExtensible, 1, true);
3648     SimpleInstallFunction(isolate_, reflect, "ownKeys",
3649                           Builtins::kReflectOwnKeys, 1, true);
3650     SimpleInstallFunction(isolate_, reflect, "preventExtensions",
3651                           Builtins::kReflectPreventExtensions, 1, true);
3652     SimpleInstallFunction(isolate_, reflect, "set", Builtins::kReflectSet, 3,
3653                           false);
3654     SimpleInstallFunction(isolate_, reflect, "setPrototypeOf",
3655                           Builtins::kReflectSetPrototypeOf, 2, true);
3656   }
3657 
3658   {  // --- B o u n d F u n c t i o n
3659     Handle<Map> map =
3660         factory->NewMap(JS_BOUND_FUNCTION_TYPE, JSBoundFunction::kHeaderSize,
3661                         TERMINAL_FAST_ELEMENTS_KIND, 0);
3662     map->SetConstructor(native_context()->object_function());
3663     map->set_is_callable(true);
3664     Map::SetPrototype(isolate(), map, empty_function);
3665 
3666     PropertyAttributes roc_attribs =
3667         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
3668     Map::EnsureDescriptorSlack(isolate_, map, 2);
3669 
3670     {  // length
3671       Descriptor d = Descriptor::AccessorConstant(
3672           factory->length_string(), factory->bound_function_length_accessor(),
3673           roc_attribs);
3674       map->AppendDescriptor(isolate(), &d);
3675     }
3676 
3677     {  // name
3678       Descriptor d = Descriptor::AccessorConstant(
3679           factory->name_string(), factory->bound_function_name_accessor(),
3680           roc_attribs);
3681       map->AppendDescriptor(isolate(), &d);
3682     }
3683     native_context()->set_bound_function_without_constructor_map(*map);
3684 
3685     map = Map::Copy(isolate_, map, "IsConstructor");
3686     map->set_is_constructor(true);
3687     native_context()->set_bound_function_with_constructor_map(*map);
3688   }
3689 
3690   {  // --- sloppy arguments map
3691     Handle<String> arguments_string = factory->Arguments_string();
3692     NewFunctionArgs args = NewFunctionArgs::ForBuiltinWithPrototype(
3693         arguments_string, isolate_->initial_object_prototype(),
3694         JS_ARGUMENTS_OBJECT_TYPE, JSSloppyArgumentsObject::kSize, 2,
3695         Builtins::kIllegal, MUTABLE);
3696     Handle<JSFunction> function = factory->NewFunction(args);
3697     Handle<Map> map(function->initial_map(), isolate());
3698 
3699     // Create the descriptor array for the arguments object.
3700     Map::EnsureDescriptorSlack(isolate_, map, 2);
3701 
3702     {  // length
3703       Descriptor d =
3704           Descriptor::DataField(isolate(), factory->length_string(),
3705                                 JSSloppyArgumentsObject::kLengthIndex,
3706                                 DONT_ENUM, Representation::Tagged());
3707       map->AppendDescriptor(isolate(), &d);
3708     }
3709     {  // callee
3710       Descriptor d =
3711           Descriptor::DataField(isolate(), factory->callee_string(),
3712                                 JSSloppyArgumentsObject::kCalleeIndex,
3713                                 DONT_ENUM, Representation::Tagged());
3714       map->AppendDescriptor(isolate(), &d);
3715     }
3716     // @@iterator method is added later.
3717 
3718     native_context()->set_sloppy_arguments_map(*map);
3719 
3720     DCHECK(!map->is_dictionary_map());
3721     DCHECK(IsObjectElementsKind(map->elements_kind()));
3722   }
3723 
3724   {  // --- fast and slow aliased arguments map
3725     Handle<Map> map = isolate_->sloppy_arguments_map();
3726     map = Map::Copy(isolate_, map, "FastAliasedArguments");
3727     map->set_elements_kind(FAST_SLOPPY_ARGUMENTS_ELEMENTS);
3728     DCHECK_EQ(2, map->GetInObjectProperties());
3729     native_context()->set_fast_aliased_arguments_map(*map);
3730 
3731     map = Map::Copy(isolate_, map, "SlowAliasedArguments");
3732     map->set_elements_kind(SLOW_SLOPPY_ARGUMENTS_ELEMENTS);
3733     DCHECK_EQ(2, map->GetInObjectProperties());
3734     native_context()->set_slow_aliased_arguments_map(*map);
3735   }
3736 
3737   {  // --- strict mode arguments map
3738     const PropertyAttributes attributes =
3739         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
3740 
3741     // Create the ThrowTypeError function.
3742     Handle<AccessorPair> callee = factory->NewAccessorPair();
3743 
3744     Handle<JSFunction> poison = GetThrowTypeErrorIntrinsic();
3745 
3746     // Install the ThrowTypeError function.
3747     callee->set_getter(*poison);
3748     callee->set_setter(*poison);
3749 
3750     // Create the map. Allocate one in-object field for length.
3751     Handle<Map> map =
3752         factory->NewMap(JS_ARGUMENTS_OBJECT_TYPE,
3753                         JSStrictArgumentsObject::kSize, PACKED_ELEMENTS, 1);
3754     // Create the descriptor array for the arguments object.
3755     Map::EnsureDescriptorSlack(isolate_, map, 2);
3756 
3757     {  // length
3758       Descriptor d =
3759           Descriptor::DataField(isolate(), factory->length_string(),
3760                                 JSStrictArgumentsObject::kLengthIndex,
3761                                 DONT_ENUM, Representation::Tagged());
3762       map->AppendDescriptor(isolate(), &d);
3763     }
3764     {  // callee
3765       Descriptor d = Descriptor::AccessorConstant(factory->callee_string(),
3766                                                   callee, attributes);
3767       map->AppendDescriptor(isolate(), &d);
3768     }
3769     // @@iterator method is added later.
3770 
3771     DCHECK_EQ(native_context()->object_function().prototype(),
3772               *isolate_->initial_object_prototype());
3773     Map::SetPrototype(isolate(), map, isolate_->initial_object_prototype());
3774 
3775     // Copy constructor from the sloppy arguments boilerplate.
3776     map->SetConstructor(
3777         native_context()->sloppy_arguments_map().GetConstructor());
3778 
3779     native_context()->set_strict_arguments_map(*map);
3780 
3781     DCHECK(!map->is_dictionary_map());
3782     DCHECK(IsObjectElementsKind(map->elements_kind()));
3783   }
3784 
3785   {  // --- context extension
3786     // Create a function for the context extension objects.
3787     Handle<JSFunction> context_extension_fun =
3788         CreateFunction(isolate_, factory->empty_string(),
3789                        JS_CONTEXT_EXTENSION_OBJECT_TYPE, JSObject::kHeaderSize,
3790                        0, factory->the_hole_value(), Builtins::kIllegal);
3791     native_context()->set_context_extension_function(*context_extension_fun);
3792   }
3793 
3794   {
3795     // Set up the call-as-function delegate.
3796     Handle<JSFunction> delegate =
3797         SimpleCreateFunction(isolate_, factory->empty_string(),
3798                              Builtins::kHandleApiCallAsFunction, 0, false);
3799     native_context()->set_call_as_function_delegate(*delegate);
3800   }
3801 
3802   {
3803     // Set up the call-as-constructor delegate.
3804     Handle<JSFunction> delegate =
3805         SimpleCreateFunction(isolate_, factory->empty_string(),
3806                              Builtins::kHandleApiCallAsConstructor, 0, false);
3807     native_context()->set_call_as_constructor_delegate(*delegate);
3808   }
3809 }  // NOLINT(readability/fn_size)
3810 
InstallTypedArray(const char * name,ElementsKind elements_kind)3811 Handle<JSFunction> Genesis::InstallTypedArray(const char* name,
3812                                               ElementsKind elements_kind) {
3813   Handle<JSObject> global =
3814       Handle<JSObject>(native_context()->global_object(), isolate());
3815 
3816   Handle<JSObject> typed_array_prototype = isolate()->typed_array_prototype();
3817   Handle<JSFunction> typed_array_function = isolate()->typed_array_function();
3818 
3819   Handle<JSFunction> result = InstallFunction(
3820       isolate(), global, name, JS_TYPED_ARRAY_TYPE,
3821       JSTypedArray::kSizeWithEmbedderFields, 0, factory()->the_hole_value(),
3822       Builtins::kTypedArrayConstructor);
3823   result->initial_map().set_elements_kind(elements_kind);
3824 
3825   result->shared().DontAdaptArguments();
3826   result->shared().set_length(3);
3827 
3828   CHECK(JSObject::SetPrototype(result, typed_array_function, false, kDontThrow)
3829             .FromJust());
3830 
3831   Handle<Smi> bytes_per_element(
3832       Smi::FromInt(1 << ElementsKindToShiftSize(elements_kind)), isolate());
3833 
3834   InstallConstant(isolate(), result, "BYTES_PER_ELEMENT", bytes_per_element);
3835 
3836   // Setup prototype object.
3837   DCHECK(result->prototype().IsJSObject());
3838   Handle<JSObject> prototype(JSObject::cast(result->prototype()), isolate());
3839 
3840   CHECK(JSObject::SetPrototype(prototype, typed_array_prototype, false,
3841                                kDontThrow)
3842             .FromJust());
3843 
3844   InstallConstant(isolate(), prototype, "BYTES_PER_ELEMENT", bytes_per_element);
3845   return result;
3846 }
3847 
InitializeExperimentalGlobal()3848 void Genesis::InitializeExperimentalGlobal() {
3849 #define FEATURE_INITIALIZE_GLOBAL(id, descr) InitializeGlobal_##id();
3850 
3851   // Initialize features from more mature to less mature, because less mature
3852   // features may depend on more mature features having been initialized
3853   // already.
3854   HARMONY_SHIPPING(FEATURE_INITIALIZE_GLOBAL)
3855   HARMONY_STAGED(FEATURE_INITIALIZE_GLOBAL)
3856   HARMONY_INPROGRESS(FEATURE_INITIALIZE_GLOBAL)
3857 #undef FEATURE_INITIALIZE_GLOBAL
3858   InitializeGlobal_regexp_linear_flag();
3859 }
3860 
CompileExtension(Isolate * isolate,v8::Extension * extension)3861 bool Genesis::CompileExtension(Isolate* isolate, v8::Extension* extension) {
3862   Factory* factory = isolate->factory();
3863   HandleScope scope(isolate);
3864   Handle<SharedFunctionInfo> function_info;
3865 
3866   Handle<String> source =
3867       isolate->factory()
3868           ->NewExternalStringFromOneByte(extension->source())
3869           .ToHandleChecked();
3870   DCHECK(source->IsOneByteRepresentation());
3871 
3872   // If we can't find the function in the cache, we compile a new
3873   // function and insert it into the cache.
3874   Vector<const char> name = CStrVector(extension->name());
3875   SourceCodeCache* cache = isolate->bootstrapper()->extensions_cache();
3876   Handle<Context> context(isolate->context(), isolate);
3877   DCHECK(context->IsNativeContext());
3878 
3879   if (!cache->Lookup(isolate, name, &function_info)) {
3880     Handle<String> script_name =
3881         factory->NewStringFromUtf8(name).ToHandleChecked();
3882     MaybeHandle<SharedFunctionInfo> maybe_function_info =
3883         Compiler::GetSharedFunctionInfoForScript(
3884             isolate, source, Compiler::ScriptDetails(script_name),
3885             ScriptOriginOptions(), extension, nullptr,
3886             ScriptCompiler::kNoCompileOptions,
3887             ScriptCompiler::kNoCacheBecauseV8Extension, EXTENSION_CODE);
3888     if (!maybe_function_info.ToHandle(&function_info)) return false;
3889     cache->Add(isolate, name, function_info);
3890   }
3891 
3892   // Set up the function context. Conceptually, we should clone the
3893   // function before overwriting the context but since we're in a
3894   // single-threaded environment it is not strictly necessary.
3895   Handle<JSFunction> fun =
3896       factory->NewFunctionFromSharedFunctionInfo(function_info, context);
3897 
3898   // Call function using either the runtime object or the global
3899   // object as the receiver. Provide no parameters.
3900   Handle<Object> receiver = isolate->global_object();
3901   return !Execution::TryCall(isolate, fun, receiver, 0, nullptr,
3902                              Execution::MessageHandling::kKeepPending, nullptr)
3903               .is_null();
3904 }
3905 
InitializeIteratorFunctions()3906 void Genesis::InitializeIteratorFunctions() {
3907   Isolate* isolate = isolate_;
3908   Factory* factory = isolate->factory();
3909   HandleScope scope(isolate);
3910   Handle<NativeContext> native_context = isolate->native_context();
3911   Handle<JSObject> iterator_prototype(
3912       native_context->initial_iterator_prototype(), isolate);
3913 
3914   {  // -- G e n e r a t o r
3915     PrototypeIterator iter(isolate, native_context->generator_function_map());
3916     Handle<JSObject> generator_function_prototype(iter.GetCurrent<JSObject>(),
3917                                                   isolate);
3918     Handle<JSFunction> generator_function_function = CreateFunction(
3919         isolate, "GeneratorFunction", JS_FUNCTION_TYPE,
3920         JSFunction::kSizeWithPrototype, 0, generator_function_prototype,
3921         Builtins::kGeneratorFunctionConstructor);
3922     generator_function_function->set_prototype_or_initial_map(
3923         native_context->generator_function_map());
3924     generator_function_function->shared().DontAdaptArguments();
3925     generator_function_function->shared().set_length(1);
3926     InstallWithIntrinsicDefaultProto(
3927         isolate, generator_function_function,
3928         Context::GENERATOR_FUNCTION_FUNCTION_INDEX);
3929 
3930     JSObject::ForceSetPrototype(generator_function_function,
3931                                 isolate->function_function());
3932     JSObject::AddProperty(
3933         isolate, generator_function_prototype, factory->constructor_string(),
3934         generator_function_function,
3935         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
3936 
3937     native_context->generator_function_map().SetConstructor(
3938         *generator_function_function);
3939   }
3940 
3941   {  // -- A s y n c G e n e r a t o r
3942     PrototypeIterator iter(isolate,
3943                            native_context->async_generator_function_map());
3944     Handle<JSObject> async_generator_function_prototype(
3945         iter.GetCurrent<JSObject>(), isolate);
3946 
3947     Handle<JSFunction> async_generator_function_function = CreateFunction(
3948         isolate, "AsyncGeneratorFunction", JS_FUNCTION_TYPE,
3949         JSFunction::kSizeWithPrototype, 0, async_generator_function_prototype,
3950         Builtins::kAsyncGeneratorFunctionConstructor);
3951     async_generator_function_function->set_prototype_or_initial_map(
3952         native_context->async_generator_function_map());
3953     async_generator_function_function->shared().DontAdaptArguments();
3954     async_generator_function_function->shared().set_length(1);
3955     InstallWithIntrinsicDefaultProto(
3956         isolate, async_generator_function_function,
3957         Context::ASYNC_GENERATOR_FUNCTION_FUNCTION_INDEX);
3958 
3959     JSObject::ForceSetPrototype(async_generator_function_function,
3960                                 isolate->function_function());
3961 
3962     JSObject::AddProperty(
3963         isolate, async_generator_function_prototype,
3964         factory->constructor_string(), async_generator_function_function,
3965         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
3966 
3967     native_context->async_generator_function_map().SetConstructor(
3968         *async_generator_function_function);
3969   }
3970 
3971   {  // -- S e t I t e r a t o r
3972     // Setup %SetIteratorPrototype%.
3973     Handle<JSObject> prototype =
3974         factory->NewJSObject(isolate->object_function(), AllocationType::kOld);
3975     JSObject::ForceSetPrototype(prototype, iterator_prototype);
3976 
3977     InstallToStringTag(isolate, prototype, factory->SetIterator_string());
3978 
3979     // Install the next function on the {prototype}.
3980     InstallFunctionWithBuiltinId(isolate, prototype, "next",
3981                                  Builtins::kSetIteratorPrototypeNext, 0, true);
3982     native_context->set_initial_set_iterator_prototype(*prototype);
3983 
3984     // Setup SetIterator constructor.
3985     Handle<JSFunction> set_iterator_function = CreateFunction(
3986         isolate, "SetIterator", JS_SET_VALUE_ITERATOR_TYPE,
3987         JSSetIterator::kHeaderSize, 0, prototype, Builtins::kIllegal);
3988     set_iterator_function->shared().set_native(false);
3989 
3990     Handle<Map> set_value_iterator_map(set_iterator_function->initial_map(),
3991                                        isolate);
3992     native_context->set_set_value_iterator_map(*set_value_iterator_map);
3993 
3994     Handle<Map> set_key_value_iterator_map = Map::Copy(
3995         isolate, set_value_iterator_map, "JS_SET_KEY_VALUE_ITERATOR_TYPE");
3996     set_key_value_iterator_map->set_instance_type(
3997         JS_SET_KEY_VALUE_ITERATOR_TYPE);
3998     native_context->set_set_key_value_iterator_map(*set_key_value_iterator_map);
3999   }
4000 
4001   {  // -- M a p I t e r a t o r
4002     // Setup %MapIteratorPrototype%.
4003     Handle<JSObject> prototype =
4004         factory->NewJSObject(isolate->object_function(), AllocationType::kOld);
4005     JSObject::ForceSetPrototype(prototype, iterator_prototype);
4006 
4007     InstallToStringTag(isolate, prototype, factory->MapIterator_string());
4008 
4009     // Install the next function on the {prototype}.
4010     InstallFunctionWithBuiltinId(isolate, prototype, "next",
4011                                  Builtins::kMapIteratorPrototypeNext, 0, true);
4012     native_context->set_initial_map_iterator_prototype(*prototype);
4013 
4014     // Setup MapIterator constructor.
4015     Handle<JSFunction> map_iterator_function = CreateFunction(
4016         isolate, "MapIterator", JS_MAP_KEY_ITERATOR_TYPE,
4017         JSMapIterator::kHeaderSize, 0, prototype, Builtins::kIllegal);
4018     map_iterator_function->shared().set_native(false);
4019 
4020     Handle<Map> map_key_iterator_map(map_iterator_function->initial_map(),
4021                                      isolate);
4022     native_context->set_map_key_iterator_map(*map_key_iterator_map);
4023 
4024     Handle<Map> map_key_value_iterator_map = Map::Copy(
4025         isolate, map_key_iterator_map, "JS_MAP_KEY_VALUE_ITERATOR_TYPE");
4026     map_key_value_iterator_map->set_instance_type(
4027         JS_MAP_KEY_VALUE_ITERATOR_TYPE);
4028     native_context->set_map_key_value_iterator_map(*map_key_value_iterator_map);
4029 
4030     Handle<Map> map_value_iterator_map =
4031         Map::Copy(isolate, map_key_iterator_map, "JS_MAP_VALUE_ITERATOR_TYPE");
4032     map_value_iterator_map->set_instance_type(JS_MAP_VALUE_ITERATOR_TYPE);
4033     native_context->set_map_value_iterator_map(*map_value_iterator_map);
4034   }
4035 
4036   {  // -- A s y n c F u n c t i o n
4037     // Builtin functions for AsyncFunction.
4038     PrototypeIterator iter(isolate, native_context->async_function_map());
4039     Handle<JSObject> async_function_prototype(iter.GetCurrent<JSObject>(),
4040                                               isolate);
4041 
4042     Handle<JSFunction> async_function_constructor = CreateFunction(
4043         isolate, "AsyncFunction", JS_FUNCTION_TYPE,
4044         JSFunction::kSizeWithPrototype, 0, async_function_prototype,
4045         Builtins::kAsyncFunctionConstructor);
4046     async_function_constructor->set_prototype_or_initial_map(
4047         native_context->async_function_map());
4048     async_function_constructor->shared().DontAdaptArguments();
4049     async_function_constructor->shared().set_length(1);
4050     native_context->set_async_function_constructor(*async_function_constructor);
4051     JSObject::ForceSetPrototype(async_function_constructor,
4052                                 isolate->function_function());
4053 
4054     JSObject::AddProperty(
4055         isolate, async_function_prototype, factory->constructor_string(),
4056         async_function_constructor,
4057         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
4058 
4059     JSFunction::SetPrototype(async_function_constructor,
4060                              async_function_prototype);
4061 
4062     // Async functions don't have a prototype, but they use generator objects
4063     // under the hood to model the suspend/resume (in await). Instead of using
4064     // the "prototype" / initial_map machinery (like for (async) generators),
4065     // there's one global (per native context) map here that is used for the
4066     // async function generator objects. These objects never escape to user
4067     // JavaScript anyways.
4068     Handle<Map> async_function_object_map = factory->NewMap(
4069         JS_ASYNC_FUNCTION_OBJECT_TYPE, JSAsyncFunctionObject::kHeaderSize);
4070     native_context->set_async_function_object_map(*async_function_object_map);
4071   }
4072 }
4073 
InitializeCallSiteBuiltins()4074 void Genesis::InitializeCallSiteBuiltins() {
4075   Factory* factory = isolate()->factory();
4076   HandleScope scope(isolate());
4077   // -- C a l l S i t e
4078   // Builtin functions for CallSite.
4079 
4080   // CallSites are a special case; the constructor is for our private use
4081   // only, therefore we set it up as a builtin that throws. Internally, we use
4082   // CallSiteUtils::Construct to create CallSite objects.
4083 
4084   Handle<JSFunction> callsite_fun = CreateFunction(
4085       isolate(), "CallSite", JS_OBJECT_TYPE, JSObject::kHeaderSize, 0,
4086       factory->the_hole_value(), Builtins::kUnsupportedThrower);
4087   callsite_fun->shared().DontAdaptArguments();
4088   isolate()->native_context()->set_callsite_function(*callsite_fun);
4089 
4090   // Setup CallSite.prototype.
4091   Handle<JSObject> prototype(JSObject::cast(callsite_fun->instance_prototype()),
4092                              isolate());
4093 
4094   struct FunctionInfo {
4095     const char* name;
4096     Builtins::Name id;
4097   };
4098 
4099   FunctionInfo infos[] = {
4100       {"getColumnNumber", Builtins::kCallSitePrototypeGetColumnNumber},
4101       {"getEvalOrigin", Builtins::kCallSitePrototypeGetEvalOrigin},
4102       {"getFileName", Builtins::kCallSitePrototypeGetFileName},
4103       {"getFunction", Builtins::kCallSitePrototypeGetFunction},
4104       {"getFunctionName", Builtins::kCallSitePrototypeGetFunctionName},
4105       {"getLineNumber", Builtins::kCallSitePrototypeGetLineNumber},
4106       {"getMethodName", Builtins::kCallSitePrototypeGetMethodName},
4107       {"getPosition", Builtins::kCallSitePrototypeGetPosition},
4108       {"getPromiseIndex", Builtins::kCallSitePrototypeGetPromiseIndex},
4109       {"getScriptNameOrSourceURL",
4110        Builtins::kCallSitePrototypeGetScriptNameOrSourceURL},
4111       {"getThis", Builtins::kCallSitePrototypeGetThis},
4112       {"getTypeName", Builtins::kCallSitePrototypeGetTypeName},
4113       {"isAsync", Builtins::kCallSitePrototypeIsAsync},
4114       {"isConstructor", Builtins::kCallSitePrototypeIsConstructor},
4115       {"isEval", Builtins::kCallSitePrototypeIsEval},
4116       {"isNative", Builtins::kCallSitePrototypeIsNative},
4117       {"isPromiseAll", Builtins::kCallSitePrototypeIsPromiseAll},
4118       {"isToplevel", Builtins::kCallSitePrototypeIsToplevel},
4119       {"toString", Builtins::kCallSitePrototypeToString}};
4120 
4121   PropertyAttributes attrs =
4122       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
4123 
4124   Handle<JSFunction> fun;
4125   for (const FunctionInfo& info : infos) {
4126     SimpleInstallFunction(isolate(), prototype, info.name, info.id, 0, true,
4127                           attrs);
4128   }
4129 }
4130 
4131 #define EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(id) \
4132   void Genesis::InitializeGlobal_##id() {}
4133 
4134 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_private_methods)
EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_regexp_sequence)4135 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_regexp_sequence)
4136 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_top_level_await)
4137 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_logical_assignment)
4138 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_import_assertions)
4139 
4140 #ifdef V8_INTL_SUPPORT
4141 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_intl_displaynames_date_types)
4142 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_intl_dateformat_day_period)
4143 #endif  // V8_INTL_SUPPORT
4144 
4145 #undef EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE
4146 
4147 void Genesis::InitializeGlobal_harmony_atomics_waitasync() {
4148   if (!FLAG_harmony_atomics_waitasync) return;
4149   SimpleInstallFunction(isolate(), isolate()->atomics_object(), "waitAsync",
4150                         Builtins::kAtomicsWaitAsync, 4, true);
4151 }
4152 
InitializeGlobal_harmony_sharedarraybuffer()4153 void Genesis::InitializeGlobal_harmony_sharedarraybuffer() {
4154   if (!FLAG_harmony_sharedarraybuffer) return;
4155 
4156   Handle<JSGlobalObject> global(native_context()->global_object(), isolate());
4157 
4158   JSObject::AddProperty(isolate_, global, "SharedArrayBuffer",
4159                         isolate()->shared_array_buffer_fun(), DONT_ENUM);
4160 }
4161 
InitializeGlobal_harmony_atomics()4162 void Genesis::InitializeGlobal_harmony_atomics() {
4163   if (!FLAG_harmony_atomics) return;
4164 
4165   Handle<JSGlobalObject> global(native_context()->global_object(), isolate());
4166 
4167   JSObject::AddProperty(isolate_, global, "Atomics",
4168                         isolate()->atomics_object(), DONT_ENUM);
4169   InstallToStringTag(isolate_, isolate()->atomics_object(), "Atomics");
4170 }
4171 
InitializeGlobal_harmony_weak_refs()4172 void Genesis::InitializeGlobal_harmony_weak_refs() {
4173   if (!FLAG_harmony_weak_refs) return;
4174 
4175   Factory* factory = isolate()->factory();
4176   Handle<JSGlobalObject> global(native_context()->global_object(), isolate());
4177 
4178   {
4179     // Create %FinalizationRegistry%
4180     Handle<JSFunction> finalization_registry_fun = InstallFunction(
4181         isolate(), global, factory->FinalizationRegistry_string(),
4182         JS_FINALIZATION_REGISTRY_TYPE, JSFinalizationRegistry::kHeaderSize, 0,
4183         factory->the_hole_value(), Builtins::kFinalizationRegistryConstructor);
4184     InstallWithIntrinsicDefaultProto(
4185         isolate(), finalization_registry_fun,
4186         Context::JS_FINALIZATION_REGISTRY_FUNCTION_INDEX);
4187 
4188     finalization_registry_fun->shared().DontAdaptArguments();
4189     finalization_registry_fun->shared().set_length(1);
4190 
4191     Handle<JSObject> finalization_registry_prototype(
4192         JSObject::cast(finalization_registry_fun->instance_prototype()),
4193         isolate());
4194 
4195     InstallToStringTag(isolate(), finalization_registry_prototype,
4196                        factory->FinalizationRegistry_string());
4197 
4198     SimpleInstallFunction(isolate(), finalization_registry_prototype,
4199                           "register", Builtins::kFinalizationRegistryRegister,
4200                           2, false);
4201 
4202     SimpleInstallFunction(isolate(), finalization_registry_prototype,
4203                           "unregister",
4204                           Builtins::kFinalizationRegistryUnregister, 1, false);
4205 
4206     // The cleanupSome function is created but not exposed, as it is used
4207     // internally by InvokeFinalizationRegistryCleanupFromTask.
4208     //
4209     // It is exposed by FLAG_harmony_weak_refs_with_cleanup_some.
4210     Handle<JSFunction> cleanup_some_fun = SimpleCreateFunction(
4211         isolate(), factory->InternalizeUtf8String("cleanupSome"),
4212         Builtins::kFinalizationRegistryPrototypeCleanupSome, 0, false);
4213     native_context()->set_finalization_registry_cleanup_some(*cleanup_some_fun);
4214   }
4215   {
4216     // Create %WeakRef%
4217     Handle<JSFunction> weak_ref_fun = InstallFunction(
4218         isolate(), global, factory->WeakRef_string(), JS_WEAK_REF_TYPE,
4219         JSWeakRef::kHeaderSize, 0, factory->the_hole_value(),
4220         Builtins::kWeakRefConstructor);
4221     InstallWithIntrinsicDefaultProto(isolate(), weak_ref_fun,
4222                                      Context::JS_WEAK_REF_FUNCTION_INDEX);
4223 
4224     weak_ref_fun->shared().DontAdaptArguments();
4225     weak_ref_fun->shared().set_length(1);
4226 
4227     Handle<JSObject> weak_ref_prototype(
4228         JSObject::cast(weak_ref_fun->instance_prototype()), isolate());
4229 
4230     InstallToStringTag(isolate(), weak_ref_prototype,
4231                        factory->WeakRef_string());
4232 
4233     SimpleInstallFunction(isolate(), weak_ref_prototype, "deref",
4234                           Builtins::kWeakRefDeref, 0, true);
4235   }
4236 }
4237 
InitializeGlobal_harmony_weak_refs_with_cleanup_some()4238 void Genesis::InitializeGlobal_harmony_weak_refs_with_cleanup_some() {
4239   if (!FLAG_harmony_weak_refs_with_cleanup_some) return;
4240   DCHECK(FLAG_harmony_weak_refs);
4241 
4242   Handle<JSFunction> finalization_registry_fun =
4243       isolate()->js_finalization_registry_fun();
4244   Handle<JSObject> finalization_registry_prototype(
4245       JSObject::cast(finalization_registry_fun->instance_prototype()),
4246       isolate());
4247 
4248   JSObject::AddProperty(isolate(), finalization_registry_prototype,
4249                         factory()->InternalizeUtf8String("cleanupSome"),
4250                         isolate()->finalization_registry_cleanup_some(),
4251                         DONT_ENUM);
4252 }
4253 
InitializeGlobal_harmony_promise_any()4254 void Genesis::InitializeGlobal_harmony_promise_any() {
4255   if (!FLAG_harmony_promise_any) {
4256     return;
4257   }
4258 
4259   Factory* factory = isolate()->factory();
4260   Handle<JSGlobalObject> global(native_context()->global_object(), isolate());
4261 
4262   InstallError(isolate_, global, factory->AggregateError_string(),
4263                Context::AGGREGATE_ERROR_FUNCTION_INDEX,
4264                Builtins::kAggregateErrorConstructor, 2, 2);
4265 
4266   // Setup %AggregateErrorPrototype%.
4267   Handle<JSFunction> aggregate_error_function(
4268       native_context()->aggregate_error_function(), isolate());
4269   Handle<JSObject> prototype(
4270       JSObject::cast(aggregate_error_function->instance_prototype()),
4271       isolate());
4272 
4273   Handle<JSFunction> promise_fun(
4274       JSFunction::cast(
4275           isolate()->native_context()->get(Context::PROMISE_FUNCTION_INDEX)),
4276       isolate());
4277   Handle<JSFunction> promise_any = InstallFunctionWithBuiltinId(
4278       isolate_, promise_fun, "any", Builtins::kPromiseAny, 1, true);
4279   native_context()->set_promise_any(*promise_any);
4280 }
4281 
InitializeGlobal_harmony_regexp_match_indices()4282 void Genesis::InitializeGlobal_harmony_regexp_match_indices() {
4283   if (!FLAG_harmony_regexp_match_indices) return;
4284 
4285   // Add indices accessor to JSRegExpResult's initial map.
4286   Handle<Map> initial_map(native_context()->regexp_result_map(), isolate());
4287   Descriptor d = Descriptor::AccessorConstant(
4288       factory()->indices_string(), factory()->regexp_result_indices_accessor(),
4289       NONE);
4290   Map::EnsureDescriptorSlack(isolate(), initial_map, 1);
4291   initial_map->AppendDescriptor(isolate(), &d);
4292 }
4293 
InitializeGlobal_harmony_string_replaceall()4294 void Genesis::InitializeGlobal_harmony_string_replaceall() {
4295   if (!FLAG_harmony_string_replaceall) return;
4296 
4297   Handle<JSFunction> string_fun(native_context()->string_function(), isolate());
4298   Handle<JSObject> string_prototype(
4299       JSObject::cast(string_fun->instance_prototype()), isolate());
4300 
4301   SimpleInstallFunction(isolate(), string_prototype, "replaceAll",
4302                         Builtins::kStringPrototypeReplaceAll, 2, true);
4303 }
4304 
InitializeGlobal_regexp_linear_flag()4305 void Genesis::InitializeGlobal_regexp_linear_flag() {
4306   if (!FLAG_enable_experimental_regexp_engine) return;
4307 
4308   Handle<JSFunction> regexp_fun(native_context()->regexp_function(), isolate());
4309   Handle<JSObject> regexp_prototype(
4310       JSObject::cast(regexp_fun->instance_prototype()), isolate());
4311   SimpleInstallGetter(isolate(), regexp_prototype,
4312                       isolate()->factory()->linear_string(),
4313                       Builtins::kRegExpPrototypeLinearGetter, true);
4314 
4315   // Store regexp prototype map again after change.
4316   native_context()->set_regexp_prototype_map(regexp_prototype->map());
4317 }
4318 
4319 #ifdef V8_INTL_SUPPORT
4320 
InitializeGlobal_harmony_intl_segmenter()4321 void Genesis::InitializeGlobal_harmony_intl_segmenter() {
4322   if (!FLAG_harmony_intl_segmenter) return;
4323   Handle<JSObject> intl = Handle<JSObject>::cast(
4324       JSReceiver::GetProperty(
4325           isolate(),
4326           Handle<JSReceiver>(native_context()->global_object(), isolate()),
4327           factory()->InternalizeUtf8String("Intl"))
4328           .ToHandleChecked());
4329 
4330   Handle<JSFunction> segmenter_fun = InstallFunction(
4331       isolate(), intl, "Segmenter", JS_SEGMENTER_TYPE, JSSegmenter::kHeaderSize,
4332       0, factory()->the_hole_value(), Builtins::kSegmenterConstructor);
4333   segmenter_fun->shared().set_length(0);
4334   segmenter_fun->shared().DontAdaptArguments();
4335   InstallWithIntrinsicDefaultProto(isolate_, segmenter_fun,
4336                                    Context::INTL_SEGMENTER_FUNCTION_INDEX);
4337 
4338   SimpleInstallFunction(isolate(), segmenter_fun, "supportedLocalesOf",
4339                         Builtins::kSegmenterSupportedLocalesOf, 1, false);
4340 
4341   {
4342     // Setup %SegmenterPrototype%.
4343     Handle<JSObject> prototype(
4344         JSObject::cast(segmenter_fun->instance_prototype()), isolate());
4345 
4346     // #sec-intl.segmenter.prototype-@@tostringtag
4347     //
4348     // Intl.Segmenter.prototype [ @@toStringTag ]
4349     //
4350     // The initial value of the @@toStringTag property is the String value
4351     // "Intl.Segmenter".
4352     InstallToStringTag(isolate(), prototype, "Intl.Segmenter");
4353 
4354     SimpleInstallFunction(isolate(), prototype, "resolvedOptions",
4355                           Builtins::kSegmenterPrototypeResolvedOptions, 0,
4356                           false);
4357 
4358     SimpleInstallFunction(isolate(), prototype, "segment",
4359                           Builtins::kSegmenterPrototypeSegment, 1, false);
4360   }
4361 
4362   {
4363     // Setup %SegmentsPrototype%.
4364     Handle<JSObject> prototype = factory()->NewJSObject(
4365         isolate()->object_function(), AllocationType::kOld);
4366 
4367     Handle<String> name_string =
4368         Name::ToFunctionName(isolate(), isolate()->factory()->Segments_string())
4369             .ToHandleChecked();
4370     Handle<JSFunction> segments_fun = CreateFunction(
4371         isolate(), name_string, JS_SEGMENTS_TYPE, JSSegments::kHeaderSize, 0,
4372         prototype, Builtins::kIllegal);
4373     segments_fun->shared().set_native(false);
4374     segments_fun->shared().set_length(0);
4375     segments_fun->shared().DontAdaptArguments();
4376 
4377     SimpleInstallFunction(isolate(), prototype, "containing",
4378                           Builtins::kSegmentsPrototypeContaining, 1, false);
4379 
4380     InstallFunctionAtSymbol(
4381         isolate_, prototype, factory()->iterator_symbol(), "[Symbol.iterator]",
4382         Builtins::kSegmentsPrototypeIterator, 0, true, DONT_ENUM);
4383 
4384     Handle<Map> segments_map(segments_fun->initial_map(), isolate());
4385     native_context()->set_intl_segments_map(*segments_map);
4386   }
4387 
4388   {
4389     // Setup %SegmentIteratorPrototype%.
4390     Handle<JSObject> iterator_prototype(
4391         native_context()->initial_iterator_prototype(), isolate());
4392 
4393     Handle<JSObject> prototype = factory()->NewJSObject(
4394         isolate()->object_function(), AllocationType::kOld);
4395     JSObject::ForceSetPrototype(prototype, iterator_prototype);
4396 
4397     // #sec-%segmentiteratorprototype%.@@tostringtag
4398     //
4399     // %SegmentIteratorPrototype% [ @@toStringTag ]
4400     //
4401     // The initial value of the @@toStringTag property is the String value
4402     // "Segmenter String Iterator".
4403     InstallToStringTag(isolate(), prototype, "Segmenter String Iterator");
4404 
4405     SimpleInstallFunction(isolate(), prototype, "next",
4406                           Builtins::kSegmentIteratorPrototypeNext, 0, false);
4407 
4408     // Setup SegmentIterator constructor.
4409     Handle<String> name_string =
4410         Name::ToFunctionName(isolate(),
4411                              isolate()->factory()->SegmentIterator_string())
4412             .ToHandleChecked();
4413     Handle<JSFunction> segment_iterator_fun = CreateFunction(
4414         isolate(), name_string, JS_SEGMENT_ITERATOR_TYPE,
4415         JSSegmentIterator::kHeaderSize, 0, prototype, Builtins::kIllegal);
4416     segment_iterator_fun->shared().set_native(false);
4417 
4418     Handle<Map> segment_iterator_map(segment_iterator_fun->initial_map(),
4419                                      isolate());
4420     native_context()->set_intl_segment_iterator_map(*segment_iterator_map);
4421   }
4422 }
4423 
4424 #endif  // V8_INTL_SUPPORT
4425 
CreateArrayBuffer(Handle<String> name,ArrayBufferKind array_buffer_kind)4426 Handle<JSFunction> Genesis::CreateArrayBuffer(
4427     Handle<String> name, ArrayBufferKind array_buffer_kind) {
4428   // Create the %ArrayBufferPrototype%
4429   // Setup the {prototype} with the given {name} for @@toStringTag.
4430   Handle<JSObject> prototype = factory()->NewJSObject(
4431       isolate()->object_function(), AllocationType::kOld);
4432   InstallToStringTag(isolate(), prototype, name);
4433 
4434   // Allocate the constructor with the given {prototype}.
4435   Handle<JSFunction> array_buffer_fun =
4436       CreateFunction(isolate(), name, JS_ARRAY_BUFFER_TYPE,
4437                      JSArrayBuffer::kSizeWithEmbedderFields, 0, prototype,
4438                      Builtins::kArrayBufferConstructor);
4439   array_buffer_fun->shared().DontAdaptArguments();
4440   array_buffer_fun->shared().set_length(1);
4441 
4442   // Install the "constructor" property on the {prototype}.
4443   JSObject::AddProperty(isolate(), prototype, factory()->constructor_string(),
4444                         array_buffer_fun, DONT_ENUM);
4445 
4446   switch (array_buffer_kind) {
4447     case ARRAY_BUFFER:
4448       InstallFunctionWithBuiltinId(isolate(), array_buffer_fun, "isView",
4449                                    Builtins::kArrayBufferIsView, 1, true);
4450 
4451       // Install the "byteLength" getter on the {prototype}.
4452       SimpleInstallGetter(isolate(), prototype, factory()->byte_length_string(),
4453                           Builtins::kArrayBufferPrototypeGetByteLength, false);
4454 
4455       SimpleInstallFunction(isolate(), prototype, "slice",
4456                             Builtins::kArrayBufferPrototypeSlice, 2, true);
4457       break;
4458 
4459     case SHARED_ARRAY_BUFFER:
4460       // Install the "byteLength" getter on the {prototype}.
4461       SimpleInstallGetter(isolate(), prototype, factory()->byte_length_string(),
4462                           Builtins::kSharedArrayBufferPrototypeGetByteLength,
4463                           false);
4464 
4465       SimpleInstallFunction(isolate(), prototype, "slice",
4466                             Builtins::kSharedArrayBufferPrototypeSlice, 2,
4467                             true);
4468       break;
4469   }
4470 
4471   return array_buffer_fun;
4472 }
4473 
4474 // TODO(jgruber): Refactor this into some kind of meaningful organization. There
4475 // is likely no reason remaining for these objects to be installed here. For
4476 // example, global object setup done in this function could likely move to
4477 // InitializeGlobal.
InstallABunchOfRandomThings()4478 bool Genesis::InstallABunchOfRandomThings() {
4479   HandleScope scope(isolate());
4480 
4481   auto fast_template_instantiations_cache = isolate()->factory()->NewFixedArray(
4482       TemplateInfo::kFastTemplateInstantiationsCacheSize);
4483   native_context()->set_fast_template_instantiations_cache(
4484       *fast_template_instantiations_cache);
4485 
4486   auto slow_template_instantiations_cache = SimpleNumberDictionary::New(
4487       isolate(), ApiNatives::kInitialFunctionCacheSize);
4488   native_context()->set_slow_template_instantiations_cache(
4489       *slow_template_instantiations_cache);
4490 
4491   // Store the map for the %ObjectPrototype% after the natives has been compiled
4492   // and the Object function has been set up.
4493   {
4494     Handle<JSFunction> object_function(native_context()->object_function(),
4495                                        isolate());
4496     DCHECK(JSObject::cast(object_function->initial_map().prototype())
4497                .HasFastProperties());
4498     native_context()->set_object_function_prototype_map(
4499         HeapObject::cast(object_function->initial_map().prototype()).map());
4500   }
4501 
4502   // Store the map for the %StringPrototype% after the natives has been compiled
4503   // and the String function has been set up.
4504   Handle<JSFunction> string_function(native_context()->string_function(),
4505                                      isolate());
4506   JSObject string_function_prototype =
4507       JSObject::cast(string_function->initial_map().prototype());
4508   DCHECK(string_function_prototype.HasFastProperties());
4509   native_context()->set_string_function_prototype_map(
4510       string_function_prototype.map());
4511 
4512   Handle<JSGlobalObject> global_object =
4513       handle(native_context()->global_object(), isolate());
4514 
4515   // Install Global.decodeURI.
4516   InstallFunctionWithBuiltinId(isolate(), global_object, "decodeURI",
4517                                Builtins::kGlobalDecodeURI, 1, false);
4518 
4519   // Install Global.decodeURIComponent.
4520   InstallFunctionWithBuiltinId(isolate(), global_object, "decodeURIComponent",
4521                                Builtins::kGlobalDecodeURIComponent, 1, false);
4522 
4523   // Install Global.encodeURI.
4524   InstallFunctionWithBuiltinId(isolate(), global_object, "encodeURI",
4525                                Builtins::kGlobalEncodeURI, 1, false);
4526 
4527   // Install Global.encodeURIComponent.
4528   InstallFunctionWithBuiltinId(isolate(), global_object, "encodeURIComponent",
4529                                Builtins::kGlobalEncodeURIComponent, 1, false);
4530 
4531   // Install Global.escape.
4532   InstallFunctionWithBuiltinId(isolate(), global_object, "escape",
4533                                Builtins::kGlobalEscape, 1, false);
4534 
4535   // Install Global.unescape.
4536   InstallFunctionWithBuiltinId(isolate(), global_object, "unescape",
4537                                Builtins::kGlobalUnescape, 1, false);
4538 
4539   // Install Global.eval.
4540   {
4541     Handle<JSFunction> eval = SimpleInstallFunction(
4542         isolate(), global_object, "eval", Builtins::kGlobalEval, 1, false);
4543     native_context()->set_global_eval_fun(*eval);
4544   }
4545 
4546   // Install Global.isFinite
4547   InstallFunctionWithBuiltinId(isolate(), global_object, "isFinite",
4548                                Builtins::kGlobalIsFinite, 1, true);
4549 
4550   // Install Global.isNaN
4551   InstallFunctionWithBuiltinId(isolate(), global_object, "isNaN",
4552                                Builtins::kGlobalIsNaN, 1, true);
4553 
4554   // Install Array builtin functions.
4555   {
4556     Handle<JSFunction> array_constructor(native_context()->array_function(),
4557                                          isolate());
4558     Handle<JSArray> proto(JSArray::cast(array_constructor->prototype()),
4559                           isolate());
4560 
4561     // Verification of important array prototype properties.
4562     Object length = proto->length();
4563     CHECK(length.IsSmi());
4564     CHECK_EQ(Smi::ToInt(length), 0);
4565     CHECK(proto->HasSmiOrObjectElements());
4566     // This is necessary to enable fast checks for absence of elements
4567     // on Array.prototype and below.
4568     proto->set_elements(ReadOnlyRoots(heap()).empty_fixed_array());
4569   }
4570 
4571   // Create a map for accessor property descriptors (a variant of JSObject
4572   // that predefines four properties get, set, configurable and enumerable).
4573   {
4574     // AccessorPropertyDescriptor initial map.
4575     Handle<Map> map =
4576         factory()->NewMap(JS_OBJECT_TYPE, JSAccessorPropertyDescriptor::kSize,
4577                           TERMINAL_FAST_ELEMENTS_KIND, 4);
4578     // Create the descriptor array for the property descriptor object.
4579     Map::EnsureDescriptorSlack(isolate(), map, 4);
4580 
4581     {  // get
4582       Descriptor d =
4583           Descriptor::DataField(isolate(), factory()->get_string(),
4584                                 JSAccessorPropertyDescriptor::kGetIndex, NONE,
4585                                 Representation::Tagged());
4586       map->AppendDescriptor(isolate(), &d);
4587     }
4588     {  // set
4589       Descriptor d =
4590           Descriptor::DataField(isolate(), factory()->set_string(),
4591                                 JSAccessorPropertyDescriptor::kSetIndex, NONE,
4592                                 Representation::Tagged());
4593       map->AppendDescriptor(isolate(), &d);
4594     }
4595     {  // enumerable
4596       Descriptor d =
4597           Descriptor::DataField(isolate(), factory()->enumerable_string(),
4598                                 JSAccessorPropertyDescriptor::kEnumerableIndex,
4599                                 NONE, Representation::Tagged());
4600       map->AppendDescriptor(isolate(), &d);
4601     }
4602     {  // configurable
4603       Descriptor d = Descriptor::DataField(
4604           isolate(), factory()->configurable_string(),
4605           JSAccessorPropertyDescriptor::kConfigurableIndex, NONE,
4606           Representation::Tagged());
4607       map->AppendDescriptor(isolate(), &d);
4608     }
4609 
4610     Map::SetPrototype(isolate(), map, isolate()->initial_object_prototype());
4611     map->SetConstructor(native_context()->object_function());
4612 
4613     native_context()->set_accessor_property_descriptor_map(*map);
4614   }
4615 
4616   // Create a map for data property descriptors (a variant of JSObject
4617   // that predefines four properties value, writable, configurable and
4618   // enumerable).
4619   {
4620     // DataPropertyDescriptor initial map.
4621     Handle<Map> map =
4622         factory()->NewMap(JS_OBJECT_TYPE, JSDataPropertyDescriptor::kSize,
4623                           TERMINAL_FAST_ELEMENTS_KIND, 4);
4624     // Create the descriptor array for the property descriptor object.
4625     Map::EnsureDescriptorSlack(isolate(), map, 4);
4626 
4627     {  // value
4628       Descriptor d =
4629           Descriptor::DataField(isolate(), factory()->value_string(),
4630                                 JSDataPropertyDescriptor::kValueIndex, NONE,
4631                                 Representation::Tagged());
4632       map->AppendDescriptor(isolate(), &d);
4633     }
4634     {  // writable
4635       Descriptor d =
4636           Descriptor::DataField(isolate(), factory()->writable_string(),
4637                                 JSDataPropertyDescriptor::kWritableIndex, NONE,
4638                                 Representation::Tagged());
4639       map->AppendDescriptor(isolate(), &d);
4640     }
4641     {  // enumerable
4642       Descriptor d =
4643           Descriptor::DataField(isolate(), factory()->enumerable_string(),
4644                                 JSDataPropertyDescriptor::kEnumerableIndex,
4645                                 NONE, Representation::Tagged());
4646       map->AppendDescriptor(isolate(), &d);
4647     }
4648     {  // configurable
4649       Descriptor d =
4650           Descriptor::DataField(isolate(), factory()->configurable_string(),
4651                                 JSDataPropertyDescriptor::kConfigurableIndex,
4652                                 NONE, Representation::Tagged());
4653       map->AppendDescriptor(isolate(), &d);
4654     }
4655 
4656     Map::SetPrototype(isolate(), map, isolate()->initial_object_prototype());
4657     map->SetConstructor(native_context()->object_function());
4658 
4659     native_context()->set_data_property_descriptor_map(*map);
4660   }
4661 
4662   // Create a constructor for RegExp results (a variant of Array that
4663   // predefines the properties index, input, and groups).
4664   {
4665     // JSRegExpResult initial map.
4666     // Add additional slack to the initial map in case regexp_match_indices
4667     // are enabled to account for the additional descriptor.
4668     Handle<Map> initial_map = CreateInitialMapForArraySubclass(
4669         JSRegExpResult::kSize, JSRegExpResult::kInObjectPropertyCount);
4670 
4671     // index descriptor.
4672     {
4673       Descriptor d = Descriptor::DataField(isolate(), factory()->index_string(),
4674                                            JSRegExpResult::kIndexIndex, NONE,
4675                                            Representation::Tagged());
4676       initial_map->AppendDescriptor(isolate(), &d);
4677     }
4678 
4679     // input descriptor.
4680     {
4681       Descriptor d = Descriptor::DataField(isolate(), factory()->input_string(),
4682                                            JSRegExpResult::kInputIndex, NONE,
4683                                            Representation::Tagged());
4684       initial_map->AppendDescriptor(isolate(), &d);
4685     }
4686 
4687     // groups descriptor.
4688     {
4689       Descriptor d = Descriptor::DataField(
4690           isolate(), factory()->groups_string(), JSRegExpResult::kGroupsIndex,
4691           NONE, Representation::Tagged());
4692       initial_map->AppendDescriptor(isolate(), &d);
4693     }
4694 
4695     // Private internal only fields. All of the remaining fields have special
4696     // symbols to prevent their use in Javascript.
4697     {
4698       PropertyAttributes attribs = DONT_ENUM;
4699 
4700       // cached_indices_or_regexp descriptor.
4701       {
4702         Descriptor d = Descriptor::DataField(
4703             isolate(),
4704             factory()->regexp_result_cached_indices_or_regexp_symbol(),
4705             JSRegExpResult::kCachedIndicesOrRegExpIndex, attribs,
4706             Representation::Tagged());
4707         initial_map->AppendDescriptor(isolate(), &d);
4708       }
4709 
4710       // names descriptor.
4711       {
4712         Descriptor d = Descriptor::DataField(
4713             isolate(), factory()->regexp_result_names_symbol(),
4714             JSRegExpResult::kNamesIndex, attribs, Representation::Tagged());
4715         initial_map->AppendDescriptor(isolate(), &d);
4716       }
4717 
4718       // regexp_input_index descriptor.
4719       {
4720         Descriptor d = Descriptor::DataField(
4721             isolate(), factory()->regexp_result_regexp_input_symbol(),
4722             JSRegExpResult::kRegExpInputIndex, attribs,
4723             Representation::Tagged());
4724         initial_map->AppendDescriptor(isolate(), &d);
4725       }
4726 
4727       // regexp_last_index descriptor.
4728       {
4729         Descriptor d = Descriptor::DataField(
4730             isolate(), factory()->regexp_result_regexp_last_index_symbol(),
4731             JSRegExpResult::kRegExpLastIndex, attribs,
4732             Representation::Tagged());
4733         initial_map->AppendDescriptor(isolate(), &d);
4734       }
4735     }
4736 
4737     native_context()->set_regexp_result_map(*initial_map);
4738   }
4739 
4740   // Create a constructor for JSRegExpResultIndices (a variant of Array that
4741   // predefines the groups property).
4742   {
4743     // JSRegExpResultIndices initial map.
4744     Handle<Map> initial_map = CreateInitialMapForArraySubclass(
4745         JSRegExpResultIndices::kSize,
4746         JSRegExpResultIndices::kInObjectPropertyCount);
4747 
4748     // groups descriptor.
4749     {
4750       Descriptor d = Descriptor::DataField(
4751           isolate(), factory()->groups_string(),
4752           JSRegExpResultIndices::kGroupsIndex, NONE, Representation::Tagged());
4753       initial_map->AppendDescriptor(isolate(), &d);
4754       DCHECK_EQ(initial_map->LastAdded().as_int(),
4755                 JSRegExpResultIndices::kGroupsDescriptorIndex);
4756     }
4757 
4758     native_context()->set_regexp_result_indices_map(*initial_map);
4759   }
4760 
4761   // Add @@iterator method to the arguments object maps.
4762   {
4763     PropertyAttributes attribs = DONT_ENUM;
4764     Handle<AccessorInfo> arguments_iterator =
4765         factory()->arguments_iterator_accessor();
4766     {
4767       Descriptor d = Descriptor::AccessorConstant(factory()->iterator_symbol(),
4768                                                   arguments_iterator, attribs);
4769       Handle<Map> map(native_context()->sloppy_arguments_map(), isolate());
4770       Map::EnsureDescriptorSlack(isolate(), map, 1);
4771       map->AppendDescriptor(isolate(), &d);
4772     }
4773     {
4774       Descriptor d = Descriptor::AccessorConstant(factory()->iterator_symbol(),
4775                                                   arguments_iterator, attribs);
4776       Handle<Map> map(native_context()->fast_aliased_arguments_map(),
4777                       isolate());
4778       Map::EnsureDescriptorSlack(isolate(), map, 1);
4779       map->AppendDescriptor(isolate(), &d);
4780     }
4781     {
4782       Descriptor d = Descriptor::AccessorConstant(factory()->iterator_symbol(),
4783                                                   arguments_iterator, attribs);
4784       Handle<Map> map(native_context()->slow_aliased_arguments_map(),
4785                       isolate());
4786       Map::EnsureDescriptorSlack(isolate(), map, 1);
4787       map->AppendDescriptor(isolate(), &d);
4788     }
4789     {
4790       Descriptor d = Descriptor::AccessorConstant(factory()->iterator_symbol(),
4791                                                   arguments_iterator, attribs);
4792       Handle<Map> map(native_context()->strict_arguments_map(), isolate());
4793       Map::EnsureDescriptorSlack(isolate(), map, 1);
4794       map->AppendDescriptor(isolate(), &d);
4795     }
4796   }
4797   {
4798     Handle<OrderedHashSet> promises =
4799         OrderedHashSet::Allocate(isolate(), 0).ToHandleChecked();
4800     native_context()->set_atomics_waitasync_promises(*promises);
4801   }
4802 
4803   return true;
4804 }
4805 
InstallExtrasBindings()4806 bool Genesis::InstallExtrasBindings() {
4807   HandleScope scope(isolate());
4808 
4809   Handle<JSObject> extras_binding = factory()->NewJSObjectWithNullProto();
4810 
4811   // binding.isTraceCategoryEnabled(category)
4812   SimpleInstallFunction(isolate(), extras_binding, "isTraceCategoryEnabled",
4813                         Builtins::kIsTraceCategoryEnabled, 1, true);
4814 
4815   // binding.trace(phase, category, name, id, data)
4816   SimpleInstallFunction(isolate(), extras_binding, "trace", Builtins::kTrace, 5,
4817                         true);
4818 
4819   native_context()->set_extras_binding_object(*extras_binding);
4820 
4821   return true;
4822 }
4823 
InitializeNormalizedMapCaches()4824 void Genesis::InitializeNormalizedMapCaches() {
4825   Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
4826   native_context()->set_normalized_map_cache(*cache);
4827 }
4828 
InstallExtensions(Handle<Context> native_context,v8::ExtensionConfiguration * extensions)4829 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
4830                                      v8::ExtensionConfiguration* extensions) {
4831   // Don't install extensions into the snapshot.
4832   if (isolate_->serializer_enabled()) return true;
4833   BootstrapperActive active(this);
4834   SaveAndSwitchContext saved_context(isolate_, *native_context);
4835   return Genesis::InstallExtensions(isolate_, native_context, extensions) &&
4836          Genesis::InstallSpecialObjects(isolate_, native_context);
4837 }
4838 
InstallSpecialObjects(Isolate * isolate,Handle<Context> native_context)4839 bool Genesis::InstallSpecialObjects(Isolate* isolate,
4840                                     Handle<Context> native_context) {
4841   HandleScope scope(isolate);
4842 
4843   Handle<JSObject> Error = isolate->error_function();
4844   Handle<String> name = isolate->factory()->stackTraceLimit_string();
4845   Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit), isolate);
4846   JSObject::AddProperty(isolate, Error, name, stack_trace_limit, NONE);
4847 
4848   if (FLAG_expose_wasm) {
4849     // Install the internal data structures into the isolate and expose on
4850     // the global object.
4851     WasmJs::Install(isolate, true);
4852   } else if (FLAG_validate_asm) {
4853     // Install the internal data structures only; these are needed for asm.js
4854     // translated to Wasm to work correctly.
4855     WasmJs::Install(isolate, false);
4856   }
4857 
4858   return true;
4859 }
4860 
Hash(RegisteredExtension * extension)4861 static uint32_t Hash(RegisteredExtension* extension) {
4862   return v8::internal::ComputePointerHash(extension);
4863 }
4864 
ExtensionStates()4865 Genesis::ExtensionStates::ExtensionStates() : map_(8) {}
4866 
get_state(RegisteredExtension * extension)4867 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
4868     RegisteredExtension* extension) {
4869   base::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension));
4870   if (entry == nullptr) {
4871     return UNVISITED;
4872   }
4873   return static_cast<ExtensionTraversalState>(
4874       reinterpret_cast<intptr_t>(entry->value));
4875 }
4876 
set_state(RegisteredExtension * extension,ExtensionTraversalState state)4877 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
4878                                          ExtensionTraversalState state) {
4879   map_.LookupOrInsert(extension, Hash(extension))->value =
4880       reinterpret_cast<void*>(static_cast<intptr_t>(state));
4881 }
4882 
InstallExtensions(Isolate * isolate,Handle<Context> native_context,v8::ExtensionConfiguration * extensions)4883 bool Genesis::InstallExtensions(Isolate* isolate,
4884                                 Handle<Context> native_context,
4885                                 v8::ExtensionConfiguration* extensions) {
4886   ExtensionStates extension_states;  // All extensions have state UNVISITED.
4887   return InstallAutoExtensions(isolate, &extension_states) &&
4888          (!FLAG_expose_gc ||
4889           InstallExtension(isolate, "v8/gc", &extension_states)) &&
4890          (!FLAG_expose_externalize_string ||
4891           InstallExtension(isolate, "v8/externalize", &extension_states)) &&
4892          (!TracingFlags::is_gc_stats_enabled() ||
4893           InstallExtension(isolate, "v8/statistics", &extension_states)) &&
4894          (!FLAG_expose_trigger_failure ||
4895           InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
4896          (!FLAG_trace_ignition_dispatches ||
4897           InstallExtension(isolate, "v8/ignition-statistics",
4898                            &extension_states)) &&
4899          (!isValidCpuTraceMarkFunctionName() ||
4900           InstallExtension(isolate, "v8/cpumark", &extension_states)) &&
4901 #ifdef ENABLE_VTUNE_TRACEMARK
4902          (!FLAG_enable_vtune_domain_support ||
4903           InstallExtension(isolate, "v8/vtunedomain", &extension_states)) &&
4904 #endif  // ENABLE_VTUNE_TRACEMARK
4905          InstallRequestedExtensions(isolate, extensions, &extension_states);
4906 }
4907 
InstallAutoExtensions(Isolate * isolate,ExtensionStates * extension_states)4908 bool Genesis::InstallAutoExtensions(Isolate* isolate,
4909                                     ExtensionStates* extension_states) {
4910   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
4911        it != nullptr; it = it->next()) {
4912     if (it->extension()->auto_enable() &&
4913         !InstallExtension(isolate, it, extension_states)) {
4914       return false;
4915     }
4916   }
4917   return true;
4918 }
4919 
InstallRequestedExtensions(Isolate * isolate,v8::ExtensionConfiguration * extensions,ExtensionStates * extension_states)4920 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
4921                                          v8::ExtensionConfiguration* extensions,
4922                                          ExtensionStates* extension_states) {
4923   for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
4924     if (!InstallExtension(isolate, *it, extension_states)) return false;
4925   }
4926   return true;
4927 }
4928 
4929 // Installs a named extension.  This methods is unoptimized and does
4930 // not scale well if we want to support a large number of extensions.
InstallExtension(Isolate * isolate,const char * name,ExtensionStates * extension_states)4931 bool Genesis::InstallExtension(Isolate* isolate, const char* name,
4932                                ExtensionStates* extension_states) {
4933   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
4934        it != nullptr; it = it->next()) {
4935     if (strcmp(name, it->extension()->name()) == 0) {
4936       return InstallExtension(isolate, it, extension_states);
4937     }
4938   }
4939   return Utils::ApiCheck(false, "v8::Context::New()",
4940                          "Cannot find required extension");
4941 }
4942 
InstallExtension(Isolate * isolate,v8::RegisteredExtension * current,ExtensionStates * extension_states)4943 bool Genesis::InstallExtension(Isolate* isolate,
4944                                v8::RegisteredExtension* current,
4945                                ExtensionStates* extension_states) {
4946   HandleScope scope(isolate);
4947 
4948   if (extension_states->get_state(current) == INSTALLED) return true;
4949   // The current node has already been visited so there must be a
4950   // cycle in the dependency graph; fail.
4951   if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
4952                        "v8::Context::New()", "Circular extension dependency")) {
4953     return false;
4954   }
4955   DCHECK(extension_states->get_state(current) == UNVISITED);
4956   extension_states->set_state(current, VISITED);
4957   v8::Extension* extension = current->extension();
4958   // Install the extension's dependencies
4959   for (int i = 0; i < extension->dependency_count(); i++) {
4960     if (!InstallExtension(isolate, extension->dependencies()[i],
4961                           extension_states)) {
4962       return false;
4963     }
4964   }
4965   // We do not expect this to throw an exception. Change this if it does.
4966   bool result = CompileExtension(isolate, extension);
4967   DCHECK(isolate->has_pending_exception() != result);
4968   if (!result) {
4969     // We print out the name of the extension that fail to install.
4970     // When an error is thrown during bootstrapping we automatically print
4971     // the line number at which this happened to the console in the isolate
4972     // error throwing functionality.
4973     base::OS::PrintError("Error installing extension '%s'.\n",
4974                          current->extension()->name());
4975     isolate->clear_pending_exception();
4976   }
4977   extension_states->set_state(current, INSTALLED);
4978   return result;
4979 }
4980 
ConfigureGlobalObjects(v8::Local<v8::ObjectTemplate> global_proxy_template)4981 bool Genesis::ConfigureGlobalObjects(
4982     v8::Local<v8::ObjectTemplate> global_proxy_template) {
4983   Handle<JSObject> global_proxy(native_context()->global_proxy(), isolate());
4984   Handle<JSObject> global_object(native_context()->global_object(), isolate());
4985 
4986   if (!global_proxy_template.IsEmpty()) {
4987     // Configure the global proxy object.
4988     Handle<ObjectTemplateInfo> global_proxy_data =
4989         v8::Utils::OpenHandle(*global_proxy_template);
4990     if (!ConfigureApiObject(global_proxy, global_proxy_data)) return false;
4991 
4992     // Configure the global object.
4993     Handle<FunctionTemplateInfo> proxy_constructor(
4994         FunctionTemplateInfo::cast(global_proxy_data->constructor()),
4995         isolate());
4996     if (!proxy_constructor->GetPrototypeTemplate().IsUndefined(isolate())) {
4997       Handle<ObjectTemplateInfo> global_object_data(
4998           ObjectTemplateInfo::cast(proxy_constructor->GetPrototypeTemplate()),
4999           isolate());
5000       if (!ConfigureApiObject(global_object, global_object_data)) return false;
5001     }
5002   }
5003 
5004   JSObject::ForceSetPrototype(global_proxy, global_object);
5005 
5006   native_context()->set_array_buffer_map(
5007       native_context()->array_buffer_fun().initial_map());
5008 
5009   return true;
5010 }
5011 
ConfigureApiObject(Handle<JSObject> object,Handle<ObjectTemplateInfo> object_template)5012 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
5013                                  Handle<ObjectTemplateInfo> object_template) {
5014   DCHECK(!object_template.is_null());
5015   DCHECK(FunctionTemplateInfo::cast(object_template->constructor())
5016              .IsTemplateFor(object->map()));
5017 
5018   MaybeHandle<JSObject> maybe_obj =
5019       ApiNatives::InstantiateObject(object->GetIsolate(), object_template);
5020   Handle<JSObject> instantiated_template;
5021   if (!maybe_obj.ToHandle(&instantiated_template)) {
5022     DCHECK(isolate()->has_pending_exception());
5023     isolate()->clear_pending_exception();
5024     return false;
5025   }
5026   TransferObject(instantiated_template, object);
5027   return true;
5028 }
5029 
PropertyAlreadyExists(Isolate * isolate,Handle<JSObject> to,Handle<Name> key)5030 static bool PropertyAlreadyExists(Isolate* isolate, Handle<JSObject> to,
5031                                   Handle<Name> key) {
5032   LookupIterator it(isolate, to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
5033   CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
5034   return it.IsFound();
5035 }
5036 
TransferNamedProperties(Handle<JSObject> from,Handle<JSObject> to)5037 void Genesis::TransferNamedProperties(Handle<JSObject> from,
5038                                       Handle<JSObject> to) {
5039   // If JSObject::AddProperty asserts due to already existing property,
5040   // it is likely due to both global objects sharing property name(s).
5041   // Merging those two global objects is impossible.
5042   // The global template must not create properties that already exist
5043   // in the snapshotted global object.
5044   if (from->HasFastProperties()) {
5045     Handle<DescriptorArray> descs = Handle<DescriptorArray>(
5046         from->map().instance_descriptors(kRelaxedLoad), isolate());
5047     for (InternalIndex i : from->map().IterateOwnDescriptors()) {
5048       PropertyDetails details = descs->GetDetails(i);
5049       if (details.location() == kField) {
5050         if (details.kind() == kData) {
5051           HandleScope inner(isolate());
5052           Handle<Name> key = Handle<Name>(descs->GetKey(i), isolate());
5053           // If the property is already there we skip it.
5054           if (PropertyAlreadyExists(isolate(), to, key)) continue;
5055           FieldIndex index = FieldIndex::ForDescriptor(from->map(), i);
5056           Handle<Object> value =
5057               JSObject::FastPropertyAt(from, details.representation(), index);
5058           JSObject::AddProperty(isolate(), to, key, value,
5059                                 details.attributes());
5060         } else {
5061           DCHECK_EQ(kAccessor, details.kind());
5062           UNREACHABLE();
5063         }
5064 
5065       } else {
5066         DCHECK_EQ(kDescriptor, details.location());
5067         DCHECK_EQ(kAccessor, details.kind());
5068         Handle<Name> key(descs->GetKey(i), isolate());
5069         // If the property is already there we skip it.
5070         if (PropertyAlreadyExists(isolate(), to, key)) continue;
5071         HandleScope inner(isolate());
5072         DCHECK(!to->HasFastProperties());
5073         // Add to dictionary.
5074         Handle<Object> value(descs->GetStrongValue(i), isolate());
5075         PropertyDetails d(kAccessor, details.attributes(),
5076                           PropertyCellType::kMutable);
5077         JSObject::SetNormalizedProperty(to, key, value, d);
5078       }
5079     }
5080   } else if (from->IsJSGlobalObject()) {
5081     // Copy all keys and values in enumeration order.
5082     Handle<GlobalDictionary> properties(
5083         JSGlobalObject::cast(*from).global_dictionary(), isolate());
5084     Handle<FixedArray> indices =
5085         GlobalDictionary::IterationIndices(isolate(), properties);
5086     for (int i = 0; i < indices->length(); i++) {
5087       InternalIndex index(Smi::ToInt(indices->get(i)));
5088       Handle<PropertyCell> cell(properties->CellAt(index), isolate());
5089       Handle<Name> key(cell->name(), isolate());
5090       // If the property is already there we skip it.
5091       if (PropertyAlreadyExists(isolate(), to, key)) continue;
5092       // Set the property.
5093       Handle<Object> value(cell->value(), isolate());
5094       if (value->IsTheHole(isolate())) continue;
5095       PropertyDetails details = cell->property_details();
5096       if (details.kind() != kData) continue;
5097       JSObject::AddProperty(isolate(), to, key, value, details.attributes());
5098     }
5099   } else {
5100     // Copy all keys and values in enumeration order.
5101     Handle<NameDictionary> properties =
5102         Handle<NameDictionary>(from->property_dictionary(), isolate());
5103     Handle<FixedArray> key_indices =
5104         NameDictionary::IterationIndices(isolate(), properties);
5105     ReadOnlyRoots roots(isolate());
5106     for (int i = 0; i < key_indices->length(); i++) {
5107       InternalIndex key_index(Smi::ToInt(key_indices->get(i)));
5108       Object raw_key = properties->KeyAt(key_index);
5109       DCHECK(properties->IsKey(roots, raw_key));
5110       DCHECK(raw_key.IsName());
5111       Handle<Name> key(Name::cast(raw_key), isolate());
5112       // If the property is already there we skip it.
5113       if (PropertyAlreadyExists(isolate(), to, key)) continue;
5114       // Set the property.
5115       Handle<Object> value =
5116           Handle<Object>(properties->ValueAt(key_index), isolate());
5117       DCHECK(!value->IsCell());
5118       DCHECK(!value->IsTheHole(isolate()));
5119       PropertyDetails details = properties->DetailsAt(key_index);
5120       DCHECK_EQ(kData, details.kind());
5121       JSObject::AddProperty(isolate(), to, key, value, details.attributes());
5122     }
5123   }
5124 }
5125 
TransferIndexedProperties(Handle<JSObject> from,Handle<JSObject> to)5126 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
5127                                         Handle<JSObject> to) {
5128   // Cloning the elements array is sufficient.
5129   Handle<FixedArray> from_elements =
5130       Handle<FixedArray>(FixedArray::cast(from->elements()), isolate());
5131   Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
5132   to->set_elements(*to_elements);
5133 }
5134 
TransferObject(Handle<JSObject> from,Handle<JSObject> to)5135 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
5136   HandleScope outer(isolate());
5137 
5138   DCHECK(!from->IsJSArray());
5139   DCHECK(!to->IsJSArray());
5140 
5141   TransferNamedProperties(from, to);
5142   TransferIndexedProperties(from, to);
5143 
5144   // Transfer the prototype (new map is needed).
5145   Handle<HeapObject> proto(from->map().prototype(), isolate());
5146   JSObject::ForceSetPrototype(to, proto);
5147 }
5148 
CreateInitialMapForArraySubclass(int size,int inobject_properties)5149 Handle<Map> Genesis::CreateInitialMapForArraySubclass(int size,
5150                                                       int inobject_properties) {
5151   // Find global.Array.prototype to inherit from.
5152   Handle<JSFunction> array_constructor(native_context()->array_function(),
5153                                        isolate());
5154   Handle<JSObject> array_prototype(native_context()->initial_array_prototype(),
5155                                    isolate());
5156 
5157   // Add initial map.
5158   Handle<Map> initial_map = factory()->NewMap(
5159       JS_ARRAY_TYPE, size, TERMINAL_FAST_ELEMENTS_KIND, inobject_properties);
5160   initial_map->SetConstructor(*array_constructor);
5161 
5162   // Set prototype on map.
5163   initial_map->set_has_non_instance_prototype(false);
5164   Map::SetPrototype(isolate(), initial_map, array_prototype);
5165 
5166   // Update map with length accessor from Array.
5167   static constexpr int kTheLengthAccessor = 1;
5168   Map::EnsureDescriptorSlack(isolate(), initial_map,
5169                              inobject_properties + kTheLengthAccessor);
5170 
5171   // length descriptor.
5172   {
5173     JSFunction array_function = native_context()->array_function();
5174     Handle<DescriptorArray> array_descriptors(
5175         array_function.initial_map().instance_descriptors(kRelaxedLoad),
5176         isolate());
5177     Handle<String> length = factory()->length_string();
5178     InternalIndex old = array_descriptors->SearchWithCache(
5179         isolate(), *length, array_function.initial_map());
5180     DCHECK(old.is_found());
5181     Descriptor d = Descriptor::AccessorConstant(
5182         length, handle(array_descriptors->GetStrongValue(old), isolate()),
5183         array_descriptors->GetDetails(old).attributes());
5184     initial_map->AppendDescriptor(isolate(), &d);
5185   }
5186   return initial_map;
5187 }
5188 
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)5189 Genesis::Genesis(
5190     Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
5191     v8::Local<v8::ObjectTemplate> global_proxy_template,
5192     size_t context_snapshot_index,
5193     v8::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
5194     v8::MicrotaskQueue* microtask_queue)
5195     : isolate_(isolate), active_(isolate->bootstrapper()) {
5196   RuntimeCallTimerScope rcs_timer(isolate, RuntimeCallCounterId::kGenesis);
5197   result_ = Handle<Context>::null();
5198   global_proxy_ = Handle<JSGlobalProxy>::null();
5199 
5200   // Before creating the roots we must save the context and restore it
5201   // on all function exits.
5202   SaveContext saved_context(isolate);
5203 
5204   // The deserializer needs to hook up references to the global proxy.
5205   // Create an uninitialized global proxy now if we don't have one
5206   // and initialize it later in CreateNewGlobals.
5207   Handle<JSGlobalProxy> global_proxy;
5208   if (!maybe_global_proxy.ToHandle(&global_proxy)) {
5209     int instance_size = 0;
5210     if (context_snapshot_index > 0) {
5211       // The global proxy function to reinitialize this global proxy is in the
5212       // context that is yet to be deserialized. We need to prepare a global
5213       // proxy of the correct size.
5214       Object size = isolate->heap()->serialized_global_proxy_sizes().get(
5215           static_cast<int>(context_snapshot_index) - 1);
5216       instance_size = Smi::ToInt(size);
5217     } else {
5218       instance_size = JSGlobalProxy::SizeWithEmbedderFields(
5219           global_proxy_template.IsEmpty()
5220               ? 0
5221               : global_proxy_template->InternalFieldCount());
5222     }
5223     global_proxy =
5224         isolate->factory()->NewUninitializedJSGlobalProxy(instance_size);
5225   }
5226 
5227   // We can only de-serialize a context if the isolate was initialized from
5228   // a snapshot. Otherwise we have to build the context from scratch.
5229   // Also create a context from scratch to expose natives, if required by flag.
5230   DCHECK(native_context_.is_null());
5231   if (isolate->initialized_from_snapshot()) {
5232     Handle<Context> context;
5233     if (Snapshot::NewContextFromSnapshot(isolate, global_proxy,
5234                                          context_snapshot_index,
5235                                          embedder_fields_deserializer)
5236             .ToHandle(&context)) {
5237       native_context_ = Handle<NativeContext>::cast(context);
5238     }
5239   }
5240 
5241   if (!native_context().is_null()) {
5242     AddToWeakNativeContextList(isolate, *native_context());
5243     isolate->set_context(*native_context());
5244     isolate->counters()->contexts_created_by_snapshot()->Increment();
5245 
5246     if (context_snapshot_index == 0) {
5247       Handle<JSGlobalObject> global_object =
5248           CreateNewGlobals(global_proxy_template, global_proxy);
5249       HookUpGlobalObject(global_object);
5250 
5251       if (!ConfigureGlobalObjects(global_proxy_template)) return;
5252     } else {
5253       // The global proxy needs to be integrated into the native context.
5254       HookUpGlobalProxy(global_proxy);
5255     }
5256     DCHECK(!global_proxy->IsDetachedFrom(native_context()->global_object()));
5257   } else {
5258     DCHECK(native_context().is_null());
5259 
5260     base::ElapsedTimer timer;
5261     if (FLAG_profile_deserialization) timer.Start();
5262     DCHECK_EQ(0u, context_snapshot_index);
5263     // We get here if there was no context snapshot.
5264     CreateRoots();
5265     MathRandom::InitializeContext(isolate, native_context());
5266     Handle<JSFunction> empty_function = CreateEmptyFunction();
5267     CreateSloppyModeFunctionMaps(empty_function);
5268     CreateStrictModeFunctionMaps(empty_function);
5269     CreateObjectFunction(empty_function);
5270     CreateIteratorMaps(empty_function);
5271     CreateAsyncIteratorMaps(empty_function);
5272     CreateAsyncFunctionMaps(empty_function);
5273     Handle<JSGlobalObject> global_object =
5274         CreateNewGlobals(global_proxy_template, global_proxy);
5275     InitializeGlobal(global_object, empty_function);
5276     InitializeNormalizedMapCaches();
5277     InitializeIteratorFunctions();
5278     InitializeCallSiteBuiltins();
5279 
5280     if (!InstallABunchOfRandomThings()) return;
5281     if (!InstallExtrasBindings()) return;
5282     if (!ConfigureGlobalObjects(global_proxy_template)) return;
5283 
5284     isolate->counters()->contexts_created_from_scratch()->Increment();
5285 
5286     if (FLAG_profile_deserialization) {
5287       double ms = timer.Elapsed().InMillisecondsF();
5288       PrintF("[Initializing context from scratch took %0.3f ms]\n", ms);
5289     }
5290   }
5291 
5292   // TODO(v8:10391): The reason is that the NativeContext::microtask_queue
5293   // serialization is not actually supported, and therefore the field is
5294   // serialized as raw data instead of being serialized as ExternalReference.
5295   // As a result, when V8 heap sandbox is enabled, the external pointer entry
5296   // is not allocated for microtask queue field during deserialization, so we
5297   // allocate it manually here.
5298   native_context()->AllocateExternalPointerEntries(isolate);
5299 
5300   native_context()->set_microtask_queue(
5301       isolate, microtask_queue ? static_cast<MicrotaskQueue*>(microtask_queue)
5302                                : isolate->default_microtask_queue());
5303 
5304   // Install experimental natives. Do not include them into the
5305   // snapshot as we should be able to turn them off at runtime. Re-installing
5306   // them after they have already been deserialized would also fail.
5307   if (!isolate->serializer_enabled()) {
5308     InitializeExperimentalGlobal();
5309 
5310     // Store String.prototype's map again in case it has been changed by
5311     // experimental natives.
5312     Handle<JSFunction> string_function(native_context()->string_function(),
5313                                        isolate);
5314     JSObject string_function_prototype =
5315         JSObject::cast(string_function->initial_map().prototype());
5316     DCHECK(string_function_prototype.HasFastProperties());
5317     native_context()->set_string_function_prototype_map(
5318         string_function_prototype.map());
5319   }
5320 
5321   if (FLAG_disallow_code_generation_from_strings) {
5322     native_context()->set_allow_code_gen_from_strings(
5323         ReadOnlyRoots(isolate).false_value());
5324   }
5325 
5326   // We created new functions, which may require debug instrumentation.
5327   if (isolate->debug()->is_active()) {
5328     isolate->debug()->InstallDebugBreakTrampoline();
5329   }
5330 
5331   native_context()->ResetErrorsThrown();
5332   result_ = native_context();
5333 }
5334 
Genesis(Isolate * isolate,MaybeHandle<JSGlobalProxy> maybe_global_proxy,v8::Local<v8::ObjectTemplate> global_proxy_template)5335 Genesis::Genesis(Isolate* isolate,
5336                  MaybeHandle<JSGlobalProxy> maybe_global_proxy,
5337                  v8::Local<v8::ObjectTemplate> global_proxy_template)
5338     : isolate_(isolate), active_(isolate->bootstrapper()) {
5339   result_ = Handle<Context>::null();
5340   global_proxy_ = Handle<JSGlobalProxy>::null();
5341 
5342   // Before creating the roots we must save the context and restore it
5343   // on all function exits.
5344   SaveContext saved_context(isolate);
5345 
5346   const int proxy_size = JSGlobalProxy::SizeWithEmbedderFields(
5347       global_proxy_template->InternalFieldCount());
5348 
5349   Handle<JSGlobalProxy> global_proxy;
5350   if (!maybe_global_proxy.ToHandle(&global_proxy)) {
5351     global_proxy = factory()->NewUninitializedJSGlobalProxy(proxy_size);
5352   }
5353 
5354   // Create a remote object as the global object.
5355   Handle<ObjectTemplateInfo> global_proxy_data =
5356       Utils::OpenHandle(*global_proxy_template);
5357   Handle<FunctionTemplateInfo> global_constructor(
5358       FunctionTemplateInfo::cast(global_proxy_data->constructor()), isolate);
5359 
5360   Handle<ObjectTemplateInfo> global_object_template(
5361       ObjectTemplateInfo::cast(global_constructor->GetPrototypeTemplate()),
5362       isolate);
5363   Handle<JSObject> global_object =
5364       ApiNatives::InstantiateRemoteObject(global_object_template)
5365           .ToHandleChecked();
5366 
5367   // (Re)initialize the global proxy object.
5368   DCHECK_EQ(global_proxy_data->embedder_field_count(),
5369             global_proxy_template->InternalFieldCount());
5370   Handle<Map> global_proxy_map = isolate->factory()->NewMap(
5371       JS_GLOBAL_PROXY_TYPE, proxy_size, TERMINAL_FAST_ELEMENTS_KIND);
5372   global_proxy_map->set_is_access_check_needed(true);
5373   global_proxy_map->set_may_have_interesting_symbols(true);
5374 
5375   // A remote global proxy has no native context.
5376   global_proxy->set_native_context(ReadOnlyRoots(heap()).null_value());
5377 
5378   // Configure the hidden prototype chain of the global proxy.
5379   JSObject::ForceSetPrototype(global_proxy, global_object);
5380   global_proxy->map().SetConstructor(*global_constructor);
5381 
5382   global_proxy_ = global_proxy;
5383 }
5384 
5385 // Support for thread preemption.
5386 
5387 // Reserve space for statics needing saving and restoring.
ArchiveSpacePerThread()5388 int Bootstrapper::ArchiveSpacePerThread() { return sizeof(NestingCounterType); }
5389 
5390 // Archive statics that are thread-local.
ArchiveState(char * to)5391 char* Bootstrapper::ArchiveState(char* to) {
5392   *reinterpret_cast<NestingCounterType*>(to) = nesting_;
5393   nesting_ = 0;
5394   return to + sizeof(NestingCounterType);
5395 }
5396 
5397 // Restore statics that are thread-local.
RestoreState(char * from)5398 char* Bootstrapper::RestoreState(char* from) {
5399   nesting_ = *reinterpret_cast<NestingCounterType*>(from);
5400   return from + sizeof(NestingCounterType);
5401 }
5402 
5403 // Called when the top-level V8 mutex is destroyed.
FreeThreadResources()5404 void Bootstrapper::FreeThreadResources() { DCHECK(!IsActive()); }
5405 
5406 }  // namespace internal
5407 }  // namespace v8
5408