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