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