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/base/ieee754.h"
10 #include "src/code-stubs.h"
11 #include "src/compiler.h"
12 #include "src/extensions/externalize-string-extension.h"
13 #include "src/extensions/free-buffer-extension.h"
14 #include "src/extensions/gc-extension.h"
15 #include "src/extensions/ignition-statistics-extension.h"
16 #include "src/extensions/statistics-extension.h"
17 #include "src/extensions/trigger-failure-extension.h"
18 #include "src/heap/heap.h"
19 #include "src/isolate-inl.h"
20 #include "src/snapshot/natives.h"
21 #include "src/snapshot/snapshot.h"
22 #include "src/wasm/wasm-js.h"
23 
24 namespace v8 {
25 namespace internal {
26 
Bootstrapper(Isolate * isolate)27 Bootstrapper::Bootstrapper(Isolate* isolate)
28     : isolate_(isolate),
29       nesting_(0),
30       extensions_cache_(Script::TYPE_EXTENSION) {}
31 
32 template <class Source>
SourceLookup(int index)33 Handle<String> Bootstrapper::SourceLookup(int index) {
34   DCHECK(0 <= index && index < Source::GetBuiltinsCount());
35   Heap* heap = isolate_->heap();
36   if (Source::GetSourceCache(heap)->get(index)->IsUndefined(isolate_)) {
37     // We can use external strings for the natives.
38     Vector<const char> source = Source::GetScriptSource(index);
39     NativesExternalStringResource* resource =
40         new NativesExternalStringResource(source.start(), source.length());
41     Handle<ExternalOneByteString> source_code =
42         isolate_->factory()->NewNativeSourceString(resource);
43     // Mark this external string with a special map.
44     DCHECK(source_code->is_short());
45     Source::GetSourceCache(heap)->set(index, *source_code);
46   }
47   Handle<Object> cached_source(Source::GetSourceCache(heap)->get(index),
48                                isolate_);
49   return Handle<String>::cast(cached_source);
50 }
51 
52 
53 template Handle<String> Bootstrapper::SourceLookup<Natives>(int index);
54 template Handle<String> Bootstrapper::SourceLookup<ExperimentalNatives>(
55     int index);
56 template Handle<String> Bootstrapper::SourceLookup<ExperimentalExtraNatives>(
57     int index);
58 template Handle<String> Bootstrapper::SourceLookup<ExtraNatives>(int index);
59 
60 
Initialize(bool create_heap_objects)61 void Bootstrapper::Initialize(bool create_heap_objects) {
62   extensions_cache_.Initialize(isolate_, create_heap_objects);
63 }
64 
65 
GCFunctionName()66 static const char* GCFunctionName() {
67   bool flag_given = FLAG_expose_gc_as != NULL && strlen(FLAG_expose_gc_as) != 0;
68   return flag_given ? FLAG_expose_gc_as : "gc";
69 }
70 
71 
72 v8::Extension* Bootstrapper::free_buffer_extension_ = NULL;
73 v8::Extension* Bootstrapper::gc_extension_ = NULL;
74 v8::Extension* Bootstrapper::externalize_string_extension_ = NULL;
75 v8::Extension* Bootstrapper::statistics_extension_ = NULL;
76 v8::Extension* Bootstrapper::trigger_failure_extension_ = NULL;
77 v8::Extension* Bootstrapper::ignition_statistics_extension_ = NULL;
78 
InitializeOncePerProcess()79 void Bootstrapper::InitializeOncePerProcess() {
80   free_buffer_extension_ = new FreeBufferExtension;
81   v8::RegisterExtension(free_buffer_extension_);
82   gc_extension_ = new GCExtension(GCFunctionName());
83   v8::RegisterExtension(gc_extension_);
84   externalize_string_extension_ = new ExternalizeStringExtension;
85   v8::RegisterExtension(externalize_string_extension_);
86   statistics_extension_ = new StatisticsExtension;
87   v8::RegisterExtension(statistics_extension_);
88   trigger_failure_extension_ = new TriggerFailureExtension;
89   v8::RegisterExtension(trigger_failure_extension_);
90   ignition_statistics_extension_ = new IgnitionStatisticsExtension;
91   v8::RegisterExtension(ignition_statistics_extension_);
92 }
93 
94 
TearDownExtensions()95 void Bootstrapper::TearDownExtensions() {
96   delete free_buffer_extension_;
97   free_buffer_extension_ = NULL;
98   delete gc_extension_;
99   gc_extension_ = NULL;
100   delete externalize_string_extension_;
101   externalize_string_extension_ = NULL;
102   delete statistics_extension_;
103   statistics_extension_ = NULL;
104   delete trigger_failure_extension_;
105   trigger_failure_extension_ = NULL;
106   delete ignition_statistics_extension_;
107   ignition_statistics_extension_ = NULL;
108 }
109 
110 
DeleteNativeSources(Object * maybe_array)111 void DeleteNativeSources(Object* maybe_array) {
112   if (maybe_array->IsFixedArray()) {
113     FixedArray* array = FixedArray::cast(maybe_array);
114     Isolate* isolate = array->GetIsolate();
115     for (int i = 0; i < array->length(); i++) {
116       Object* natives_source = array->get(i);
117       if (!natives_source->IsUndefined(isolate)) {
118         const NativesExternalStringResource* resource =
119             reinterpret_cast<const NativesExternalStringResource*>(
120                 ExternalOneByteString::cast(natives_source)->resource());
121         delete resource;
122       }
123     }
124   }
125 }
126 
127 
TearDown()128 void Bootstrapper::TearDown() {
129   DeleteNativeSources(Natives::GetSourceCache(isolate_->heap()));
130   DeleteNativeSources(ExperimentalNatives::GetSourceCache(isolate_->heap()));
131   DeleteNativeSources(ExtraNatives::GetSourceCache(isolate_->heap()));
132   DeleteNativeSources(
133       ExperimentalExtraNatives::GetSourceCache(isolate_->heap()));
134 
135   extensions_cache_.Initialize(isolate_, false);  // Yes, symmetrical
136 }
137 
138 
139 class Genesis BASE_EMBEDDED {
140  public:
141   Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
142           v8::Local<v8::ObjectTemplate> global_proxy_template,
143           v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
144           GlobalContextType context_type);
145   Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
146           v8::Local<v8::ObjectTemplate> global_proxy_template);
~Genesis()147   ~Genesis() { }
148 
isolate() const149   Isolate* isolate() const { return isolate_; }
factory() const150   Factory* factory() const { return isolate_->factory(); }
heap() const151   Heap* heap() const { return isolate_->heap(); }
152 
result()153   Handle<Context> result() { return result_; }
154 
global_proxy()155   Handle<JSGlobalProxy> global_proxy() { return global_proxy_; }
156 
157  private:
native_context()158   Handle<Context> native_context() { return native_context_; }
159 
160   // Creates some basic objects. Used for creating a context from scratch.
161   void CreateRoots();
162   // Creates the empty function.  Used for creating a context from scratch.
163   Handle<JSFunction> CreateEmptyFunction(Isolate* isolate);
164   // Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
165   Handle<JSFunction> GetRestrictedFunctionPropertiesThrower();
166   Handle<JSFunction> GetStrictArgumentsPoisonFunction();
167   Handle<JSFunction> GetThrowTypeErrorIntrinsic(Builtins::Name builtin_name);
168 
169   void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
170   void CreateIteratorMaps(Handle<JSFunction> empty);
171   void CreateAsyncFunctionMaps(Handle<JSFunction> empty);
172   void CreateJSProxyMaps();
173 
174   // Make the "arguments" and "caller" properties throw a TypeError on access.
175   void AddRestrictedFunctionProperties(Handle<JSFunction> empty);
176 
177   // Creates the global objects using the global proxy and the template passed
178   // in through the API.  We call this regardless of whether we are building a
179   // context from scratch or using a deserialized one from the partial snapshot
180   // but in the latter case we don't use the objects it produces directly, as
181   // we have to used the deserialized ones that are linked together with the
182   // rest of the context snapshot.
183   Handle<JSGlobalObject> CreateNewGlobals(
184       v8::Local<v8::ObjectTemplate> global_proxy_template,
185       Handle<JSGlobalProxy> global_proxy);
186   // Hooks the given global proxy into the context.  If the context was created
187   // by deserialization then this will unhook the global proxy that was
188   // deserialized, leaving the GC to pick it up.
189   void HookUpGlobalProxy(Handle<JSGlobalObject> global_object,
190                          Handle<JSGlobalProxy> global_proxy);
191   // Similarly, we want to use the global that has been created by the templates
192   // passed through the API.  The global from the snapshot is detached from the
193   // other objects in the snapshot.
194   void HookUpGlobalObject(Handle<JSGlobalObject> global_object);
195   // The native context has a ScriptContextTable that store declarative bindings
196   // made in script scopes.  Add a "this" binding to that table pointing to the
197   // global proxy.
198   void InstallGlobalThisBinding();
199   // New context initialization.  Used for creating a context from scratch.
200   void InitializeGlobal(Handle<JSGlobalObject> global_object,
201                         Handle<JSFunction> empty_function,
202                         GlobalContextType context_type);
203   void InitializeExperimentalGlobal();
204   // Depending on the situation, expose and/or get rid of the utils object.
205   void ConfigureUtilsObject(GlobalContextType context_type);
206 
207 #define DECLARE_FEATURE_INITIALIZATION(id, descr) \
208   void InitializeGlobal_##id();
209 
210   HARMONY_INPROGRESS(DECLARE_FEATURE_INITIALIZATION)
211   HARMONY_STAGED(DECLARE_FEATURE_INITIALIZATION)
212   HARMONY_SHIPPING(DECLARE_FEATURE_INITIALIZATION)
213 #undef DECLARE_FEATURE_INITIALIZATION
214 
215   Handle<JSFunction> InstallArrayBuffer(Handle<JSObject> target,
216                                         const char* name, Builtins::Name call,
217                                         BuiltinFunctionId id);
218   Handle<JSFunction> InstallInternalArray(Handle<JSObject> target,
219                                           const char* name,
220                                           ElementsKind elements_kind);
221   bool InstallNatives(GlobalContextType context_type);
222 
223   void InstallTypedArray(const char* name, ElementsKind elements_kind,
224                          Handle<JSFunction>* fun);
225   bool InstallExperimentalNatives();
226   bool InstallExtraNatives();
227   bool InstallExperimentalExtraNatives();
228   bool InstallDebuggerNatives();
229   void InstallBuiltinFunctionIds();
230   void InstallExperimentalBuiltinFunctionIds();
231   void InitializeNormalizedMapCaches();
232 
233   enum ExtensionTraversalState {
234     UNVISITED, VISITED, INSTALLED
235   };
236 
237   class ExtensionStates {
238    public:
239     ExtensionStates();
240     ExtensionTraversalState get_state(RegisteredExtension* extension);
241     void set_state(RegisteredExtension* extension,
242                    ExtensionTraversalState state);
243    private:
244     base::HashMap map_;
245     DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
246   };
247 
248   // Used both for deserialized and from-scratch contexts to add the extensions
249   // provided.
250   static bool InstallExtensions(Handle<Context> native_context,
251                                 v8::ExtensionConfiguration* extensions);
252   static bool InstallAutoExtensions(Isolate* isolate,
253                                     ExtensionStates* extension_states);
254   static bool InstallRequestedExtensions(Isolate* isolate,
255                                          v8::ExtensionConfiguration* extensions,
256                                          ExtensionStates* extension_states);
257   static bool InstallExtension(Isolate* isolate,
258                                const char* name,
259                                ExtensionStates* extension_states);
260   static bool InstallExtension(Isolate* isolate,
261                                v8::RegisteredExtension* current,
262                                ExtensionStates* extension_states);
263   static bool InstallSpecialObjects(Handle<Context> native_context);
264   bool ConfigureApiObject(Handle<JSObject> object,
265                           Handle<ObjectTemplateInfo> object_template);
266   bool ConfigureGlobalObjects(
267       v8::Local<v8::ObjectTemplate> global_proxy_template);
268 
269   // Migrates all properties from the 'from' object to the 'to'
270   // object and overrides the prototype in 'to' with the one from
271   // 'from'.
272   void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
273   void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
274   void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
275 
276   void MakeFunctionInstancePrototypeWritable();
277 
278   void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
279                                            FunctionMode function_mode);
280 
281   static bool CallUtilsFunction(Isolate* isolate, const char* name);
282 
283   static bool CompileExtension(Isolate* isolate, v8::Extension* extension);
284 
285   Isolate* isolate_;
286   Handle<Context> result_;
287   Handle<Context> native_context_;
288   Handle<JSGlobalProxy> global_proxy_;
289 
290   // Function maps. Function maps are created initially with a read only
291   // prototype for the processing of JS builtins. Later the function maps are
292   // replaced in order to make prototype writable. These are the final, writable
293   // prototype, maps.
294   Handle<Map> sloppy_function_map_writable_prototype_;
295   Handle<Map> strict_function_map_writable_prototype_;
296   Handle<JSFunction> strict_poison_function_;
297   Handle<JSFunction> restricted_function_properties_thrower_;
298 
299   BootstrapperActive active_;
300   friend class Bootstrapper;
301 };
302 
303 
Iterate(ObjectVisitor * v)304 void Bootstrapper::Iterate(ObjectVisitor* v) {
305   extensions_cache_.Iterate(v);
306   v->Synchronize(VisitorSynchronization::kExtensions);
307 }
308 
CreateEnvironment(MaybeHandle<JSGlobalProxy> maybe_global_proxy,v8::Local<v8::ObjectTemplate> global_proxy_template,v8::ExtensionConfiguration * extensions,size_t context_snapshot_index,GlobalContextType context_type)309 Handle<Context> Bootstrapper::CreateEnvironment(
310     MaybeHandle<JSGlobalProxy> maybe_global_proxy,
311     v8::Local<v8::ObjectTemplate> global_proxy_template,
312     v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
313     GlobalContextType context_type) {
314   HandleScope scope(isolate_);
315   Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template,
316                   extensions, context_snapshot_index, context_type);
317   Handle<Context> env = genesis.result();
318   if (env.is_null() || !InstallExtensions(env, extensions)) {
319     return Handle<Context>();
320   }
321   return scope.CloseAndEscape(env);
322 }
323 
NewRemoteContext(MaybeHandle<JSGlobalProxy> maybe_global_proxy,v8::Local<v8::ObjectTemplate> global_proxy_template)324 Handle<JSGlobalProxy> Bootstrapper::NewRemoteContext(
325     MaybeHandle<JSGlobalProxy> maybe_global_proxy,
326     v8::Local<v8::ObjectTemplate> global_proxy_template) {
327   HandleScope scope(isolate_);
328   Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template);
329   Handle<JSGlobalProxy> global_proxy = genesis.global_proxy();
330   if (global_proxy.is_null()) return Handle<JSGlobalProxy>();
331   return scope.CloseAndEscape(global_proxy);
332 }
333 
DetachGlobal(Handle<Context> env)334 void Bootstrapper::DetachGlobal(Handle<Context> env) {
335   env->GetIsolate()->counters()->errors_thrown_per_context()->AddSample(
336     env->GetErrorsThrown());
337 
338   Factory* factory = env->GetIsolate()->factory();
339   Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
340   global_proxy->set_native_context(*factory->null_value());
341   JSObject::ForceSetPrototype(global_proxy, factory->null_value());
342   global_proxy->map()->SetConstructor(*factory->null_value());
343   if (FLAG_track_detached_contexts) {
344     env->GetIsolate()->AddDetachedContext(env);
345   }
346 }
347 
348 namespace {
349 
InstallFunction(Handle<JSObject> target,Handle<Name> property_name,Handle<JSFunction> function,Handle<String> function_name,PropertyAttributes attributes=DONT_ENUM)350 void InstallFunction(Handle<JSObject> target, Handle<Name> property_name,
351                      Handle<JSFunction> function, Handle<String> function_name,
352                      PropertyAttributes attributes = DONT_ENUM) {
353   JSObject::AddProperty(target, property_name, function, attributes);
354   if (target->IsJSGlobalObject()) {
355     function->shared()->set_instance_class_name(*function_name);
356   }
357   function->shared()->set_native(true);
358 }
359 
InstallFunction(Handle<JSObject> target,Handle<JSFunction> function,Handle<Name> name,PropertyAttributes attributes=DONT_ENUM)360 void InstallFunction(Handle<JSObject> target, Handle<JSFunction> function,
361                      Handle<Name> name,
362                      PropertyAttributes attributes = DONT_ENUM) {
363   Handle<String> name_string = Name::ToFunctionName(name).ToHandleChecked();
364   InstallFunction(target, name, function, name_string, attributes);
365 }
366 
CreateFunction(Isolate * isolate,Handle<String> name,InstanceType type,int instance_size,MaybeHandle<JSObject> maybe_prototype,Builtins::Name call,bool strict_function_map=false)367 Handle<JSFunction> CreateFunction(Isolate* isolate, Handle<String> name,
368                                   InstanceType type, int instance_size,
369                                   MaybeHandle<JSObject> maybe_prototype,
370                                   Builtins::Name call,
371                                   bool strict_function_map = false) {
372   Factory* factory = isolate->factory();
373   Handle<Code> call_code(isolate->builtins()->builtin(call));
374   Handle<JSObject> prototype;
375   return maybe_prototype.ToHandle(&prototype)
376              ? factory->NewFunction(name, call_code, prototype, type,
377                                     instance_size, strict_function_map)
378              : factory->NewFunctionWithoutPrototype(name, call_code,
379                                                     strict_function_map);
380 }
381 
InstallFunction(Handle<JSObject> target,Handle<Name> name,InstanceType type,int instance_size,MaybeHandle<JSObject> maybe_prototype,Builtins::Name call,PropertyAttributes attributes,bool strict_function_map=false)382 Handle<JSFunction> InstallFunction(Handle<JSObject> target, Handle<Name> name,
383                                    InstanceType type, int instance_size,
384                                    MaybeHandle<JSObject> maybe_prototype,
385                                    Builtins::Name call,
386                                    PropertyAttributes attributes,
387                                    bool strict_function_map = false) {
388   Handle<String> name_string = Name::ToFunctionName(name).ToHandleChecked();
389   Handle<JSFunction> function =
390       CreateFunction(target->GetIsolate(), name_string, type, instance_size,
391                      maybe_prototype, call, strict_function_map);
392   InstallFunction(target, name, function, name_string, attributes);
393   return function;
394 }
395 
InstallFunction(Handle<JSObject> target,const char * name,InstanceType type,int instance_size,MaybeHandle<JSObject> maybe_prototype,Builtins::Name call,bool strict_function_map=false)396 Handle<JSFunction> InstallFunction(Handle<JSObject> target, const char* name,
397                                    InstanceType type, int instance_size,
398                                    MaybeHandle<JSObject> maybe_prototype,
399                                    Builtins::Name call,
400                                    bool strict_function_map = false) {
401   Factory* const factory = target->GetIsolate()->factory();
402   PropertyAttributes attributes = DONT_ENUM;
403   return InstallFunction(target, factory->InternalizeUtf8String(name), type,
404                          instance_size, maybe_prototype, call, attributes,
405                          strict_function_map);
406 }
407 
SimpleCreateFunction(Isolate * isolate,Handle<String> name,Builtins::Name call,int len,bool adapt)408 Handle<JSFunction> SimpleCreateFunction(Isolate* isolate, Handle<String> name,
409                                         Builtins::Name call, int len,
410                                         bool adapt) {
411   Handle<JSFunction> fun =
412       CreateFunction(isolate, name, JS_OBJECT_TYPE, JSObject::kHeaderSize,
413                      MaybeHandle<JSObject>(), call);
414   if (adapt) {
415     fun->shared()->set_internal_formal_parameter_count(len);
416   } else {
417     fun->shared()->DontAdaptArguments();
418   }
419   fun->shared()->set_length(len);
420   return fun;
421 }
422 
SimpleInstallFunction(Handle<JSObject> base,Handle<String> name,Builtins::Name call,int len,bool adapt,PropertyAttributes attrs=DONT_ENUM)423 Handle<JSFunction> SimpleInstallFunction(Handle<JSObject> base,
424                                          Handle<String> name,
425                                          Builtins::Name call, int len,
426                                          bool adapt,
427                                          PropertyAttributes attrs = DONT_ENUM) {
428   Handle<JSFunction> fun =
429       SimpleCreateFunction(base->GetIsolate(), name, call, len, adapt);
430   InstallFunction(base, fun, name, attrs);
431   return fun;
432 }
433 
SimpleInstallFunction(Handle<JSObject> base,const char * name,Builtins::Name call,int len,bool adapt,PropertyAttributes attrs=DONT_ENUM)434 Handle<JSFunction> SimpleInstallFunction(Handle<JSObject> base,
435                                          const char* name, Builtins::Name call,
436                                          int len, bool adapt,
437                                          PropertyAttributes attrs = DONT_ENUM) {
438   Factory* const factory = base->GetIsolate()->factory();
439   return SimpleInstallFunction(base, factory->InternalizeUtf8String(name), call,
440                                len, adapt, attrs);
441 }
442 
SimpleInstallFunction(Handle<JSObject> base,const char * name,Builtins::Name call,int len,bool adapt,BuiltinFunctionId id)443 Handle<JSFunction> SimpleInstallFunction(Handle<JSObject> base,
444                                          const char* name, Builtins::Name call,
445                                          int len, bool adapt,
446                                          BuiltinFunctionId id) {
447   Handle<JSFunction> fun = SimpleInstallFunction(base, name, call, len, adapt);
448   fun->shared()->set_builtin_function_id(id);
449   return fun;
450 }
451 
SimpleInstallGetterSetter(Handle<JSObject> base,Handle<String> name,Builtins::Name call_getter,Builtins::Name call_setter,PropertyAttributes attribs)452 void SimpleInstallGetterSetter(Handle<JSObject> base, Handle<String> name,
453                                Builtins::Name call_getter,
454                                Builtins::Name call_setter,
455                                PropertyAttributes attribs) {
456   Isolate* const isolate = base->GetIsolate();
457 
458   Handle<String> getter_name =
459       Name::ToFunctionName(name, isolate->factory()->get_string())
460           .ToHandleChecked();
461   Handle<JSFunction> getter =
462       SimpleCreateFunction(isolate, getter_name, call_getter, 0, true);
463   getter->shared()->set_native(true);
464 
465   Handle<String> setter_name =
466       Name::ToFunctionName(name, isolate->factory()->set_string())
467           .ToHandleChecked();
468   Handle<JSFunction> setter =
469       SimpleCreateFunction(isolate, setter_name, call_setter, 1, true);
470   setter->shared()->set_native(true);
471 
472   JSObject::DefineAccessor(base, name, getter, setter, attribs).Check();
473 }
474 
SimpleInstallGetter(Handle<JSObject> base,Handle<String> name,Handle<Name> property_name,Builtins::Name call,bool adapt)475 Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
476                                        Handle<String> name,
477                                        Handle<Name> property_name,
478                                        Builtins::Name call, bool adapt) {
479   Isolate* const isolate = base->GetIsolate();
480 
481   Handle<String> getter_name =
482       Name::ToFunctionName(name, isolate->factory()->get_string())
483           .ToHandleChecked();
484   Handle<JSFunction> getter =
485       SimpleCreateFunction(isolate, getter_name, call, 0, adapt);
486   getter->shared()->set_native(true);
487 
488   Handle<Object> setter = isolate->factory()->undefined_value();
489 
490   JSObject::DefineAccessor(base, property_name, getter, setter, DONT_ENUM)
491       .Check();
492 
493   return getter;
494 }
495 
SimpleInstallGetter(Handle<JSObject> base,Handle<String> name,Builtins::Name call,bool adapt)496 Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
497                                        Handle<String> name, Builtins::Name call,
498                                        bool adapt) {
499   return SimpleInstallGetter(base, name, name, call, adapt);
500 }
501 
SimpleInstallGetter(Handle<JSObject> base,Handle<String> name,Builtins::Name call,bool adapt,BuiltinFunctionId id)502 Handle<JSFunction> SimpleInstallGetter(Handle<JSObject> base,
503                                        Handle<String> name, Builtins::Name call,
504                                        bool adapt, BuiltinFunctionId id) {
505   Handle<JSFunction> fun = SimpleInstallGetter(base, name, call, adapt);
506   fun->shared()->set_builtin_function_id(id);
507   return fun;
508 }
509 
510 }  // namespace
511 
CreateEmptyFunction(Isolate * isolate)512 Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
513   // Allocate the map for function instances. Maps are allocated first and their
514   // prototypes patched later, once empty function is created.
515 
516   // Functions with this map will not have a 'prototype' property, and
517   // can not be used as constructors.
518   Handle<Map> function_without_prototype_map =
519       factory()->CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
520   native_context()->set_sloppy_function_without_prototype_map(
521       *function_without_prototype_map);
522 
523   // Allocate the function map. This map is temporary, used only for processing
524   // of builtins.
525   // Later the map is replaced with writable prototype map, allocated below.
526   Handle<Map> function_map =
527       factory()->CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE);
528   native_context()->set_sloppy_function_map(*function_map);
529   native_context()->set_sloppy_function_with_readonly_prototype_map(
530       *function_map);
531 
532   // The final map for functions. Writeable prototype.
533   // This map is installed in MakeFunctionInstancePrototypeWritable.
534   sloppy_function_map_writable_prototype_ =
535       factory()->CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE);
536   Factory* factory = isolate->factory();
537 
538   Handle<String> object_name = factory->Object_string();
539 
540   Handle<JSObject> object_function_prototype;
541 
542   {  // --- O b j e c t ---
543     Handle<JSFunction> object_fun = factory->NewFunction(object_name);
544     int unused = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
545     int instance_size = JSObject::kHeaderSize + kPointerSize * unused;
546     Handle<Map> object_function_map =
547         factory->NewMap(JS_OBJECT_TYPE, instance_size);
548     object_function_map->SetInObjectProperties(unused);
549     JSFunction::SetInitialMap(object_fun, object_function_map,
550                               isolate->factory()->null_value());
551     object_function_map->set_unused_property_fields(unused);
552 
553     native_context()->set_object_function(*object_fun);
554 
555     // Allocate a new prototype for the object function.
556     object_function_prototype =
557         factory->NewJSObject(isolate->object_function(), TENURED);
558     Handle<Map> map = Map::Copy(handle(object_function_prototype->map()),
559                                 "EmptyObjectPrototype");
560     map->set_is_prototype_map(true);
561     // Ban re-setting Object.prototype.__proto__ to prevent Proxy security bug
562     map->set_immutable_proto(true);
563     object_function_prototype->set_map(*map);
564 
565     native_context()->set_initial_object_prototype(*object_function_prototype);
566     // For bootstrapping set the array prototype to be the same as the object
567     // prototype, otherwise the missing initial_array_prototype will cause
568     // assertions during startup.
569     native_context()->set_initial_array_prototype(*object_function_prototype);
570     Accessors::FunctionSetPrototype(object_fun, object_function_prototype)
571         .Assert();
572   }
573 
574   // Allocate the empty function as the prototype for function - ES6 19.2.3
575   Handle<Code> code(isolate->builtins()->EmptyFunction());
576   Handle<JSFunction> empty_function =
577       factory->NewFunctionWithoutPrototype(factory->empty_string(), code);
578 
579   // Allocate the function map first and then patch the prototype later
580   Handle<Map> empty_function_map =
581       factory->CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
582   DCHECK(!empty_function_map->is_dictionary_map());
583   Map::SetPrototype(empty_function_map, object_function_prototype);
584   empty_function_map->set_is_prototype_map(true);
585 
586   empty_function->set_map(*empty_function_map);
587 
588   // --- E m p t y ---
589   Handle<String> source = factory->NewStringFromStaticChars("() {}");
590   Handle<Script> script = factory->NewScript(source);
591   script->set_type(Script::TYPE_NATIVE);
592   empty_function->shared()->set_start_position(0);
593   empty_function->shared()->set_end_position(source->length());
594   empty_function->shared()->DontAdaptArguments();
595   SharedFunctionInfo::SetScript(handle(empty_function->shared()), script);
596 
597   // Set prototypes for the function maps.
598   Handle<Map> sloppy_function_map(native_context()->sloppy_function_map(),
599                                   isolate);
600   Handle<Map> sloppy_function_without_prototype_map(
601       native_context()->sloppy_function_without_prototype_map(), isolate);
602   Map::SetPrototype(sloppy_function_map, empty_function);
603   Map::SetPrototype(sloppy_function_without_prototype_map, empty_function);
604   Map::SetPrototype(sloppy_function_map_writable_prototype_, empty_function);
605 
606   return empty_function;
607 }
608 
609 
610 // Creates the %ThrowTypeError% function.
GetThrowTypeErrorIntrinsic(Builtins::Name builtin_name)611 Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic(
612     Builtins::Name builtin_name) {
613   Handle<String> name =
614       factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("ThrowTypeError"));
615   Handle<Code> code(isolate()->builtins()->builtin(builtin_name));
616   Handle<JSFunction> function =
617       factory()->NewFunctionWithoutPrototype(name, code, true);
618   function->shared()->DontAdaptArguments();
619 
620   // %ThrowTypeError% must not have a name property.
621   if (JSReceiver::DeleteProperty(function, factory()->name_string())
622           .IsNothing()) {
623     DCHECK(false);
624   }
625 
626   // length needs to be non configurable.
627   Handle<Object> value(Smi::FromInt(function->shared()->length()), isolate());
628   JSObject::SetOwnPropertyIgnoreAttributes(
629       function, factory()->length_string(), value,
630       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
631       .Assert();
632 
633   if (JSObject::PreventExtensions(function, Object::THROW_ON_ERROR)
634           .IsNothing()) {
635     DCHECK(false);
636   }
637 
638   return function;
639 }
640 
641 
642 // ECMAScript 5th Edition, 13.2.3
GetRestrictedFunctionPropertiesThrower()643 Handle<JSFunction> Genesis::GetRestrictedFunctionPropertiesThrower() {
644   if (restricted_function_properties_thrower_.is_null()) {
645     restricted_function_properties_thrower_ = GetThrowTypeErrorIntrinsic(
646         Builtins::kRestrictedFunctionPropertiesThrower);
647   }
648   return restricted_function_properties_thrower_;
649 }
650 
651 
GetStrictArgumentsPoisonFunction()652 Handle<JSFunction> Genesis::GetStrictArgumentsPoisonFunction() {
653   if (strict_poison_function_.is_null()) {
654     strict_poison_function_ = GetThrowTypeErrorIntrinsic(
655         Builtins::kRestrictedStrictArgumentsPropertiesThrower);
656   }
657   return strict_poison_function_;
658 }
659 
660 
CreateStrictModeFunctionMaps(Handle<JSFunction> empty)661 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
662   // Allocate map for the prototype-less strict mode instances.
663   Handle<Map> strict_function_without_prototype_map =
664       factory()->CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
665   native_context()->set_strict_function_without_prototype_map(
666       *strict_function_without_prototype_map);
667 
668   // Allocate map for the strict mode functions. This map is temporary, used
669   // only for processing of builtins.
670   // Later the map is replaced with writable prototype map, allocated below.
671   Handle<Map> strict_function_map = factory()->CreateStrictFunctionMap(
672       FUNCTION_WITH_READONLY_PROTOTYPE, empty);
673   native_context()->set_strict_function_map(*strict_function_map);
674 
675   // The final map for the strict mode functions. Writeable prototype.
676   // This map is installed in MakeFunctionInstancePrototypeWritable.
677   strict_function_map_writable_prototype_ = factory()->CreateStrictFunctionMap(
678       FUNCTION_WITH_WRITEABLE_PROTOTYPE, empty);
679 
680   // Now that the strict mode function map is available, set up the
681   // restricted "arguments" and "caller" getters.
682   AddRestrictedFunctionProperties(empty);
683 }
684 
CreateIteratorMaps(Handle<JSFunction> empty)685 void Genesis::CreateIteratorMaps(Handle<JSFunction> empty) {
686   // Create iterator-related meta-objects.
687   Handle<JSObject> iterator_prototype =
688       factory()->NewJSObject(isolate()->object_function(), TENURED);
689 
690   Handle<JSFunction> iterator_prototype_iterator = SimpleCreateFunction(
691       isolate(), factory()->NewStringFromAsciiChecked("[Symbol.iterator]"),
692       Builtins::kIteratorPrototypeIterator, 0, true);
693   iterator_prototype_iterator->shared()->set_native(true);
694 
695   JSObject::AddProperty(iterator_prototype, factory()->iterator_symbol(),
696                         iterator_prototype_iterator, DONT_ENUM);
697   native_context()->set_initial_iterator_prototype(*iterator_prototype);
698 
699   Handle<JSObject> generator_object_prototype =
700       factory()->NewJSObject(isolate()->object_function(), TENURED);
701   native_context()->set_initial_generator_prototype(
702       *generator_object_prototype);
703   JSObject::ForceSetPrototype(generator_object_prototype, iterator_prototype);
704   Handle<JSObject> generator_function_prototype =
705       factory()->NewJSObject(isolate()->object_function(), TENURED);
706   JSObject::ForceSetPrototype(generator_function_prototype, empty);
707 
708   JSObject::AddProperty(
709       generator_function_prototype, factory()->to_string_tag_symbol(),
710       factory()->NewStringFromAsciiChecked("GeneratorFunction"),
711       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
712   JSObject::AddProperty(generator_function_prototype,
713                         factory()->prototype_string(),
714                         generator_object_prototype,
715                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
716 
717   JSObject::AddProperty(generator_object_prototype,
718                         factory()->constructor_string(),
719                         generator_function_prototype,
720                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
721   JSObject::AddProperty(generator_object_prototype,
722                         factory()->to_string_tag_symbol(),
723                         factory()->NewStringFromAsciiChecked("Generator"),
724                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
725   SimpleInstallFunction(generator_object_prototype, "next",
726                         Builtins::kGeneratorPrototypeNext, 1, true);
727   SimpleInstallFunction(generator_object_prototype, "return",
728                         Builtins::kGeneratorPrototypeReturn, 1, true);
729   SimpleInstallFunction(generator_object_prototype, "throw",
730                         Builtins::kGeneratorPrototypeThrow, 1, true);
731 
732   // Internal version of generator_prototype_next, flagged as non-native.
733   Handle<JSFunction> generator_next_internal =
734       SimpleCreateFunction(isolate(), factory()->next_string(),
735                            Builtins::kGeneratorPrototypeNext, 1, true);
736   native_context()->set_generator_next_internal(*generator_next_internal);
737 
738   // Create maps for generator functions and their prototypes.  Store those
739   // maps in the native context. The "prototype" property descriptor is
740   // writable, non-enumerable, and non-configurable (as per ES6 draft
741   // 04-14-15, section 25.2.4.3).
742   Handle<Map> strict_function_map(strict_function_map_writable_prototype_);
743   // Generator functions do not have "caller" or "arguments" accessors.
744   Handle<Map> sloppy_generator_function_map =
745       Map::Copy(strict_function_map, "SloppyGeneratorFunction");
746   sloppy_generator_function_map->set_is_constructor(false);
747   Map::SetPrototype(sloppy_generator_function_map,
748                     generator_function_prototype);
749   native_context()->set_sloppy_generator_function_map(
750       *sloppy_generator_function_map);
751 
752   Handle<Map> strict_generator_function_map =
753       Map::Copy(strict_function_map, "StrictGeneratorFunction");
754   strict_generator_function_map->set_is_constructor(false);
755   Map::SetPrototype(strict_generator_function_map,
756                     generator_function_prototype);
757   native_context()->set_strict_generator_function_map(
758       *strict_generator_function_map);
759 
760   Handle<JSFunction> object_function(native_context()->object_function());
761   Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
762   Map::SetPrototype(generator_object_prototype_map, generator_object_prototype);
763   native_context()->set_generator_object_prototype_map(
764       *generator_object_prototype_map);
765 }
766 
CreateAsyncFunctionMaps(Handle<JSFunction> empty)767 void Genesis::CreateAsyncFunctionMaps(Handle<JSFunction> empty) {
768   // %AsyncFunctionPrototype% intrinsic
769   Handle<JSObject> async_function_prototype =
770       factory()->NewJSObject(isolate()->object_function(), TENURED);
771   JSObject::ForceSetPrototype(async_function_prototype, empty);
772 
773   JSObject::AddProperty(async_function_prototype,
774                         factory()->to_string_tag_symbol(),
775                         factory()->NewStringFromAsciiChecked("AsyncFunction"),
776                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
777 
778   Handle<Map> strict_function_map(
779       native_context()->strict_function_without_prototype_map());
780   Handle<Map> sloppy_async_function_map =
781       Map::Copy(strict_function_map, "SloppyAsyncFunction");
782   sloppy_async_function_map->set_is_constructor(false);
783   Map::SetPrototype(sloppy_async_function_map, async_function_prototype);
784   native_context()->set_sloppy_async_function_map(*sloppy_async_function_map);
785 
786   Handle<Map> strict_async_function_map =
787       Map::Copy(strict_function_map, "StrictAsyncFunction");
788   strict_async_function_map->set_is_constructor(false);
789   Map::SetPrototype(strict_async_function_map, async_function_prototype);
790   native_context()->set_strict_async_function_map(*strict_async_function_map);
791 }
792 
CreateJSProxyMaps()793 void Genesis::CreateJSProxyMaps() {
794   // Allocate the different maps for all Proxy types.
795   // Next to the default proxy, we need maps indicating callable and
796   // constructable proxies.
797   Handle<Map> proxy_function_map =
798       Map::Copy(isolate()->sloppy_function_without_prototype_map(), "Proxy");
799   proxy_function_map->set_is_constructor(true);
800   native_context()->set_proxy_function_map(*proxy_function_map);
801 
802   Handle<Map> proxy_map =
803       factory()->NewMap(JS_PROXY_TYPE, JSProxy::kSize, FAST_ELEMENTS);
804   proxy_map->set_dictionary_map(true);
805   native_context()->set_proxy_map(*proxy_map);
806 
807   Handle<Map> proxy_callable_map = Map::Copy(proxy_map, "callable Proxy");
808   proxy_callable_map->set_is_callable();
809   native_context()->set_proxy_callable_map(*proxy_callable_map);
810   proxy_callable_map->SetConstructor(native_context()->function_function());
811 
812   Handle<Map> proxy_constructor_map =
813       Map::Copy(proxy_callable_map, "constructor Proxy");
814   proxy_constructor_map->set_is_constructor(true);
815   native_context()->set_proxy_constructor_map(*proxy_constructor_map);
816 }
817 
ReplaceAccessors(Handle<Map> map,Handle<String> name,PropertyAttributes attributes,Handle<AccessorPair> accessor_pair)818 static void ReplaceAccessors(Handle<Map> map,
819                              Handle<String> name,
820                              PropertyAttributes attributes,
821                              Handle<AccessorPair> accessor_pair) {
822   DescriptorArray* descriptors = map->instance_descriptors();
823   int idx = descriptors->SearchWithCache(map->GetIsolate(), *name, *map);
824   AccessorConstantDescriptor descriptor(name, accessor_pair, attributes);
825   descriptors->Replace(idx, &descriptor);
826 }
827 
AddRestrictedFunctionProperties(Handle<JSFunction> empty)828 void Genesis::AddRestrictedFunctionProperties(Handle<JSFunction> empty) {
829   PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
830   Handle<JSFunction> thrower = GetRestrictedFunctionPropertiesThrower();
831   Handle<AccessorPair> accessors = factory()->NewAccessorPair();
832   accessors->set_getter(*thrower);
833   accessors->set_setter(*thrower);
834 
835   Handle<Map> map(empty->map());
836   ReplaceAccessors(map, factory()->arguments_string(), rw_attribs, accessors);
837   ReplaceAccessors(map, factory()->caller_string(), rw_attribs, accessors);
838 }
839 
840 
AddToWeakNativeContextList(Context * context)841 static void AddToWeakNativeContextList(Context* context) {
842   DCHECK(context->IsNativeContext());
843   Isolate* isolate = context->GetIsolate();
844   Heap* heap = isolate->heap();
845 #ifdef DEBUG
846   { // NOLINT
847     DCHECK(context->next_context_link()->IsUndefined(isolate));
848     // Check that context is not in the list yet.
849     for (Object* current = heap->native_contexts_list();
850          !current->IsUndefined(isolate);
851          current = Context::cast(current)->next_context_link()) {
852       DCHECK(current != context);
853     }
854   }
855 #endif
856   context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list(),
857                UPDATE_WEAK_WRITE_BARRIER);
858   heap->set_native_contexts_list(context);
859 }
860 
861 
CreateRoots()862 void Genesis::CreateRoots() {
863   // Allocate the native context FixedArray first and then patch the
864   // closure and extension object later (we need the empty function
865   // and the global object, but in order to create those, we need the
866   // native context).
867   native_context_ = factory()->NewNativeContext();
868   AddToWeakNativeContextList(*native_context());
869   isolate()->set_context(*native_context());
870 
871   // Allocate the message listeners object.
872   {
873     Handle<TemplateList> list = TemplateList::New(isolate(), 1);
874     native_context()->set_message_listeners(*list);
875   }
876 }
877 
878 
InstallGlobalThisBinding()879 void Genesis::InstallGlobalThisBinding() {
880   Handle<ScriptContextTable> script_contexts(
881       native_context()->script_context_table());
882   Handle<ScopeInfo> scope_info = ScopeInfo::CreateGlobalThisBinding(isolate());
883   Handle<JSFunction> closure(native_context()->closure());
884   Handle<Context> context = factory()->NewScriptContext(closure, scope_info);
885 
886   // Go ahead and hook it up while we're at it.
887   int slot = scope_info->ReceiverContextSlotIndex();
888   DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
889   context->set(slot, native_context()->global_proxy());
890 
891   Handle<ScriptContextTable> new_script_contexts =
892       ScriptContextTable::Extend(script_contexts, context);
893   native_context()->set_script_context_table(*new_script_contexts);
894 }
895 
896 
CreateNewGlobals(v8::Local<v8::ObjectTemplate> global_proxy_template,Handle<JSGlobalProxy> global_proxy)897 Handle<JSGlobalObject> Genesis::CreateNewGlobals(
898     v8::Local<v8::ObjectTemplate> global_proxy_template,
899     Handle<JSGlobalProxy> global_proxy) {
900   // The argument global_proxy_template aka data is an ObjectTemplateInfo.
901   // It has a constructor pointer that points at global_constructor which is a
902   // FunctionTemplateInfo.
903   // The global_proxy_constructor is used to (re)initialize the
904   // global_proxy. The global_proxy_constructor also has a prototype_template
905   // pointer that points at js_global_object_template which is an
906   // ObjectTemplateInfo.
907   // That in turn has a constructor pointer that points at
908   // js_global_object_constructor which is a FunctionTemplateInfo.
909   // js_global_object_constructor is used to make js_global_object_function
910   // js_global_object_function is used to make the new global_object.
911   //
912   // --- G l o b a l ---
913   // Step 1: Create a fresh JSGlobalObject.
914   Handle<JSFunction> js_global_object_function;
915   Handle<ObjectTemplateInfo> js_global_object_template;
916   if (!global_proxy_template.IsEmpty()) {
917     // Get prototype template of the global_proxy_template.
918     Handle<ObjectTemplateInfo> data =
919         v8::Utils::OpenHandle(*global_proxy_template);
920     Handle<FunctionTemplateInfo> global_constructor =
921         Handle<FunctionTemplateInfo>(
922             FunctionTemplateInfo::cast(data->constructor()));
923     Handle<Object> proto_template(global_constructor->prototype_template(),
924                                   isolate());
925     if (!proto_template->IsUndefined(isolate())) {
926       js_global_object_template =
927           Handle<ObjectTemplateInfo>::cast(proto_template);
928     }
929   }
930 
931   if (js_global_object_template.is_null()) {
932     Handle<String> name = Handle<String>(heap()->empty_string());
933     Handle<Code> code = isolate()->builtins()->Illegal();
934     Handle<JSObject> prototype =
935         factory()->NewFunctionPrototype(isolate()->object_function());
936     js_global_object_function = factory()->NewFunction(
937         name, code, prototype, JS_GLOBAL_OBJECT_TYPE, JSGlobalObject::kSize);
938 #ifdef DEBUG
939     LookupIterator it(prototype, factory()->constructor_string(),
940                       LookupIterator::OWN_SKIP_INTERCEPTOR);
941     Handle<Object> value = Object::GetProperty(&it).ToHandleChecked();
942     DCHECK(it.IsFound());
943     DCHECK_EQ(*isolate()->object_function(), *value);
944 #endif
945   } else {
946     Handle<FunctionTemplateInfo> js_global_object_constructor(
947         FunctionTemplateInfo::cast(js_global_object_template->constructor()));
948     js_global_object_function = ApiNatives::CreateApiFunction(
949         isolate(), js_global_object_constructor, factory()->the_hole_value(),
950         ApiNatives::GlobalObjectType);
951   }
952 
953   js_global_object_function->initial_map()->set_is_prototype_map(true);
954   js_global_object_function->initial_map()->set_dictionary_map(true);
955   Handle<JSGlobalObject> global_object =
956       factory()->NewJSGlobalObject(js_global_object_function);
957 
958   // Step 2: (re)initialize the global proxy object.
959   Handle<JSFunction> global_proxy_function;
960   if (global_proxy_template.IsEmpty()) {
961     Handle<String> name = Handle<String>(heap()->empty_string());
962     Handle<Code> code = isolate()->builtins()->Illegal();
963     global_proxy_function =
964         factory()->NewFunction(name, code, JS_GLOBAL_PROXY_TYPE,
965                                JSGlobalProxy::SizeWithInternalFields(0));
966   } else {
967     Handle<ObjectTemplateInfo> data =
968         v8::Utils::OpenHandle(*global_proxy_template);
969     Handle<FunctionTemplateInfo> global_constructor(
970             FunctionTemplateInfo::cast(data->constructor()));
971     global_proxy_function = ApiNatives::CreateApiFunction(
972         isolate(), global_constructor, factory()->the_hole_value(),
973         ApiNatives::GlobalProxyType);
974   }
975   Handle<String> global_name = factory()->global_string();
976   global_proxy_function->shared()->set_instance_class_name(*global_name);
977   global_proxy_function->initial_map()->set_is_access_check_needed(true);
978   global_proxy_function->initial_map()->set_has_hidden_prototype(true);
979 
980   // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
981   // Return the global proxy.
982 
983   factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
984   return global_object;
985 }
986 
987 
HookUpGlobalProxy(Handle<JSGlobalObject> global_object,Handle<JSGlobalProxy> global_proxy)988 void Genesis::HookUpGlobalProxy(Handle<JSGlobalObject> global_object,
989                                 Handle<JSGlobalProxy> global_proxy) {
990   // Set the native context for the global object.
991   global_object->set_native_context(*native_context());
992   global_object->set_global_proxy(*global_proxy);
993   global_proxy->set_native_context(*native_context());
994   // If we deserialized the context, the global proxy is already
995   // correctly set up. Otherwise it's undefined.
996   DCHECK(native_context()
997              ->get(Context::GLOBAL_PROXY_INDEX)
998              ->IsUndefined(isolate()) ||
999          native_context()->global_proxy() == *global_proxy);
1000   native_context()->set_global_proxy(*global_proxy);
1001 }
1002 
1003 
HookUpGlobalObject(Handle<JSGlobalObject> global_object)1004 void Genesis::HookUpGlobalObject(Handle<JSGlobalObject> global_object) {
1005   Handle<JSGlobalObject> global_object_from_snapshot(
1006       JSGlobalObject::cast(native_context()->extension()));
1007   native_context()->set_extension(*global_object);
1008   native_context()->set_security_token(*global_object);
1009 
1010   TransferNamedProperties(global_object_from_snapshot, global_object);
1011   TransferIndexedProperties(global_object_from_snapshot, global_object);
1012 }
1013 
InstallWithIntrinsicDefaultProto(Isolate * isolate,Handle<JSFunction> function,int context_index)1014 static void InstallWithIntrinsicDefaultProto(Isolate* isolate,
1015                                              Handle<JSFunction> function,
1016                                              int context_index) {
1017   Handle<Smi> index(Smi::FromInt(context_index), isolate);
1018   JSObject::AddProperty(
1019       function, isolate->factory()->native_context_index_symbol(), index, NONE);
1020   isolate->native_context()->set(context_index, *function);
1021 }
1022 
InstallError(Isolate * isolate,Handle<JSObject> global,Handle<String> name,int context_index)1023 static void InstallError(Isolate* isolate, Handle<JSObject> global,
1024                          Handle<String> name, int context_index) {
1025   Factory* factory = isolate->factory();
1026 
1027   Handle<JSFunction> error_fun =
1028       InstallFunction(global, name, JS_ERROR_TYPE, JSObject::kHeaderSize,
1029                       isolate->initial_object_prototype(),
1030                       Builtins::kErrorConstructor, DONT_ENUM);
1031   error_fun->shared()->set_instance_class_name(*factory->Error_string());
1032   error_fun->shared()->DontAdaptArguments();
1033   error_fun->shared()->set_construct_stub(
1034       *isolate->builtins()->ErrorConstructor());
1035   error_fun->shared()->set_length(1);
1036 
1037   if (context_index == Context::ERROR_FUNCTION_INDEX) {
1038     SimpleInstallFunction(error_fun, "captureStackTrace",
1039                           Builtins::kErrorCaptureStackTrace, 2, false);
1040   }
1041 
1042   InstallWithIntrinsicDefaultProto(isolate, error_fun, context_index);
1043 
1044   {
1045     Handle<JSObject> prototype =
1046         factory->NewJSObject(isolate->object_function(), TENURED);
1047 
1048     JSObject::AddProperty(prototype, factory->name_string(), name, DONT_ENUM);
1049     JSObject::AddProperty(prototype, factory->message_string(),
1050                           factory->empty_string(), DONT_ENUM);
1051     JSObject::AddProperty(prototype, factory->constructor_string(), error_fun,
1052                           DONT_ENUM);
1053 
1054     if (context_index == Context::ERROR_FUNCTION_INDEX) {
1055       Handle<JSFunction> to_string_fun =
1056           SimpleInstallFunction(prototype, factory->toString_string(),
1057                                 Builtins::kErrorPrototypeToString, 0, true);
1058       isolate->native_context()->set_error_to_string(*to_string_fun);
1059     } else {
1060       DCHECK(isolate->native_context()->error_to_string()->IsJSFunction());
1061 
1062       InstallFunction(prototype, isolate->error_to_string(),
1063                       factory->toString_string(), DONT_ENUM);
1064 
1065       Handle<JSFunction> global_error = isolate->error_function();
1066       CHECK(JSReceiver::SetPrototype(error_fun, global_error, false,
1067                                      Object::THROW_ON_ERROR)
1068                 .FromMaybe(false));
1069       CHECK(JSReceiver::SetPrototype(prototype,
1070                                      handle(global_error->prototype(), isolate),
1071                                      false, Object::THROW_ON_ERROR)
1072                 .FromMaybe(false));
1073     }
1074 
1075     Accessors::FunctionSetPrototype(error_fun, prototype).Assert();
1076   }
1077 
1078   Handle<Map> initial_map(error_fun->initial_map());
1079   Map::EnsureDescriptorSlack(initial_map, 1);
1080 
1081   PropertyAttributes attribs = DONT_ENUM;
1082   Handle<AccessorInfo> error_stack =
1083       Accessors::ErrorStackInfo(isolate, attribs);
1084   {
1085     AccessorConstantDescriptor d(Handle<Name>(Name::cast(error_stack->name())),
1086                                  error_stack, attribs);
1087     initial_map->AppendDescriptor(&d);
1088   }
1089 }
1090 
InstallMakeError(Isolate * isolate,Handle<Code> code,int context_index)1091 static void InstallMakeError(Isolate* isolate, Handle<Code> code,
1092                              int context_index) {
1093   Handle<JSFunction> function =
1094       isolate->factory()->NewFunction(isolate->factory()->empty_string(), code,
1095                                       JS_OBJECT_TYPE, JSObject::kHeaderSize);
1096   function->shared()->DontAdaptArguments();
1097   isolate->native_context()->set(context_index, *function);
1098 }
1099 
1100 // This is only called if we are not using snapshots.  The equivalent
1101 // work in the snapshot case is done in HookUpGlobalObject.
InitializeGlobal(Handle<JSGlobalObject> global_object,Handle<JSFunction> empty_function,GlobalContextType context_type)1102 void Genesis::InitializeGlobal(Handle<JSGlobalObject> global_object,
1103                                Handle<JSFunction> empty_function,
1104                                GlobalContextType context_type) {
1105   // --- N a t i v e   C o n t e x t ---
1106   // Use the empty function as closure (no scope info).
1107   native_context()->set_closure(*empty_function);
1108   native_context()->set_previous(NULL);
1109   // Set extension and global object.
1110   native_context()->set_extension(*global_object);
1111   // Security setup: Set the security token of the native context to the global
1112   // object. This makes the security check between two different contexts fail
1113   // by default even in case of global object reinitialization.
1114   native_context()->set_security_token(*global_object);
1115 
1116   Isolate* isolate = global_object->GetIsolate();
1117   Factory* factory = isolate->factory();
1118 
1119   Handle<ScriptContextTable> script_context_table =
1120       factory->NewScriptContextTable();
1121   native_context()->set_script_context_table(*script_context_table);
1122   InstallGlobalThisBinding();
1123 
1124   {  // --- O b j e c t ---
1125     Handle<String> object_name = factory->Object_string();
1126     Handle<JSFunction> object_function = isolate->object_function();
1127     JSObject::AddProperty(global_object, object_name, object_function,
1128                           DONT_ENUM);
1129 
1130     SimpleInstallFunction(object_function, factory->assign_string(),
1131                           Builtins::kObjectAssign, 2, false);
1132     SimpleInstallFunction(object_function, factory->create_string(),
1133                           Builtins::kObjectCreate, 2, true);
1134     SimpleInstallFunction(object_function, "getOwnPropertyDescriptor",
1135                           Builtins::kObjectGetOwnPropertyDescriptor, 2, false);
1136     SimpleInstallFunction(object_function,
1137                           factory->getOwnPropertyDescriptors_string(),
1138                           Builtins::kObjectGetOwnPropertyDescriptors, 1, false);
1139     SimpleInstallFunction(object_function, "getOwnPropertyNames",
1140                           Builtins::kObjectGetOwnPropertyNames, 1, false);
1141     SimpleInstallFunction(object_function, "getOwnPropertySymbols",
1142                           Builtins::kObjectGetOwnPropertySymbols, 1, false);
1143     SimpleInstallFunction(object_function, "is",
1144                           Builtins::kObjectIs, 2, true);
1145     SimpleInstallFunction(object_function, "preventExtensions",
1146                           Builtins::kObjectPreventExtensions, 1, false);
1147     SimpleInstallFunction(object_function, "seal",
1148                           Builtins::kObjectSeal, 1, false);
1149 
1150     Handle<JSFunction> object_define_properties = SimpleInstallFunction(
1151         object_function, "defineProperties",
1152         Builtins::kObjectDefineProperties, 2, true);
1153     native_context()->set_object_define_properties(*object_define_properties);
1154 
1155     Handle<JSFunction> object_define_property = SimpleInstallFunction(
1156         object_function, factory->defineProperty_string(),
1157         Builtins::kObjectDefineProperty, 3, true);
1158     native_context()->set_object_define_property(*object_define_property);
1159 
1160     Handle<JSFunction> object_freeze = SimpleInstallFunction(
1161         object_function, "freeze", Builtins::kObjectFreeze, 1, false);
1162     native_context()->set_object_freeze(*object_freeze);
1163 
1164     Handle<JSFunction> object_get_prototype_of = SimpleInstallFunction(
1165         object_function, "getPrototypeOf", Builtins::kObjectGetPrototypeOf,
1166         1, false);
1167     native_context()->set_object_get_prototype_of(*object_get_prototype_of);
1168     SimpleInstallFunction(object_function, "setPrototypeOf",
1169                           Builtins::kObjectSetPrototypeOf, 2, false);
1170 
1171     Handle<JSFunction> object_is_extensible = SimpleInstallFunction(
1172         object_function, "isExtensible", Builtins::kObjectIsExtensible,
1173         1, false);
1174     native_context()->set_object_is_extensible(*object_is_extensible);
1175 
1176     Handle<JSFunction> object_is_frozen = SimpleInstallFunction(
1177         object_function, "isFrozen", Builtins::kObjectIsFrozen, 1, false);
1178     native_context()->set_object_is_frozen(*object_is_frozen);
1179 
1180     Handle<JSFunction> object_is_sealed = SimpleInstallFunction(
1181         object_function, "isSealed", Builtins::kObjectIsSealed, 1, false);
1182     native_context()->set_object_is_sealed(*object_is_sealed);
1183 
1184     Handle<JSFunction> object_keys = SimpleInstallFunction(
1185         object_function, "keys", Builtins::kObjectKeys, 1, false);
1186     native_context()->set_object_keys(*object_keys);
1187     SimpleInstallFunction(object_function, factory->entries_string(),
1188                           Builtins::kObjectEntries, 1, false);
1189     SimpleInstallFunction(object_function, factory->values_string(),
1190                           Builtins::kObjectValues, 1, false);
1191 
1192     SimpleInstallFunction(isolate->initial_object_prototype(),
1193                           "__defineGetter__", Builtins::kObjectDefineGetter, 2,
1194                           true);
1195     SimpleInstallFunction(isolate->initial_object_prototype(),
1196                           "__defineSetter__", Builtins::kObjectDefineSetter, 2,
1197                           true);
1198     SimpleInstallFunction(isolate->initial_object_prototype(), "hasOwnProperty",
1199                           Builtins::kObjectHasOwnProperty, 1, true);
1200     SimpleInstallFunction(isolate->initial_object_prototype(),
1201                           "__lookupGetter__", Builtins::kObjectLookupGetter, 1,
1202                           true);
1203     SimpleInstallFunction(isolate->initial_object_prototype(),
1204                           "__lookupSetter__", Builtins::kObjectLookupSetter, 1,
1205                           true);
1206     SimpleInstallFunction(
1207         isolate->initial_object_prototype(), "propertyIsEnumerable",
1208         Builtins::kObjectPrototypePropertyIsEnumerable, 1, false);
1209 
1210     SimpleInstallGetterSetter(isolate->initial_object_prototype(),
1211                               factory->proto_string(),
1212                               Builtins::kObjectPrototypeGetProto,
1213                               Builtins::kObjectPrototypeSetProto, DONT_ENUM);
1214   }
1215 
1216   Handle<JSObject> global(native_context()->global_object());
1217 
1218   {  // --- F u n c t i o n ---
1219     Handle<JSFunction> prototype = empty_function;
1220     Handle<JSFunction> function_fun =
1221         InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
1222                         prototype, Builtins::kFunctionConstructor);
1223     function_fun->set_prototype_or_initial_map(
1224         *sloppy_function_map_writable_prototype_);
1225     function_fun->shared()->DontAdaptArguments();
1226     function_fun->shared()->SetConstructStub(
1227         *isolate->builtins()->FunctionConstructor());
1228     function_fun->shared()->set_length(1);
1229     InstallWithIntrinsicDefaultProto(isolate, function_fun,
1230                                      Context::FUNCTION_FUNCTION_INDEX);
1231 
1232     // Setup the methods on the %FunctionPrototype%.
1233     SimpleInstallFunction(prototype, factory->apply_string(),
1234                           Builtins::kFunctionPrototypeApply, 2, false);
1235 
1236     if (FLAG_minimal) {
1237       SimpleInstallFunction(prototype, factory->bind_string(),
1238                             Builtins::kFunctionPrototypeBind, 1, false);
1239     } else {
1240       FastFunctionBindStub bind_stub(isolate);
1241       Handle<JSFunction> bind_function = factory->NewFunctionWithoutPrototype(
1242           factory->bind_string(), bind_stub.GetCode(), false);
1243       bind_function->shared()->DontAdaptArguments();
1244       bind_function->shared()->set_length(1);
1245       InstallFunction(prototype, bind_function, factory->bind_string(),
1246                       DONT_ENUM);
1247     }
1248 
1249     SimpleInstallFunction(prototype, factory->call_string(),
1250                           Builtins::kFunctionPrototypeCall, 1, false);
1251     SimpleInstallFunction(prototype, factory->toString_string(),
1252                           Builtins::kFunctionPrototypeToString, 0, false);
1253 
1254     // Install the @@hasInstance function.
1255     Handle<JSFunction> has_instance = InstallFunction(
1256         prototype, factory->has_instance_symbol(), JS_OBJECT_TYPE,
1257         JSObject::kHeaderSize, MaybeHandle<JSObject>(),
1258         Builtins::kFunctionPrototypeHasInstance,
1259         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
1260     has_instance->shared()->set_builtin_function_id(kFunctionHasInstance);
1261     native_context()->set_function_has_instance(*has_instance);
1262 
1263     // Set the expected parameters for @@hasInstance to 1; required by builtin.
1264     has_instance->shared()->set_internal_formal_parameter_count(1);
1265 
1266     // Set the length for the function to satisfy ECMA-262.
1267     has_instance->shared()->set_length(1);
1268 
1269     // Install the "constructor" property on the %FunctionPrototype%.
1270     JSObject::AddProperty(prototype, factory->constructor_string(),
1271                           function_fun, DONT_ENUM);
1272 
1273     sloppy_function_map_writable_prototype_->SetConstructor(*function_fun);
1274     strict_function_map_writable_prototype_->SetConstructor(*function_fun);
1275   }
1276 
1277   {  // --- A r r a y ---
1278     Handle<JSFunction> array_function =
1279         InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
1280                         isolate->initial_object_prototype(),
1281                         Builtins::kArrayCode);
1282     array_function->shared()->DontAdaptArguments();
1283     array_function->shared()->set_builtin_function_id(kArrayCode);
1284 
1285     // This seems a bit hackish, but we need to make sure Array.length
1286     // is 1.
1287     array_function->shared()->set_length(1);
1288 
1289     Handle<Map> initial_map(array_function->initial_map());
1290 
1291     // This assert protects an optimization in
1292     // HGraphBuilder::JSArrayBuilder::EmitMapCode()
1293     DCHECK(initial_map->elements_kind() == GetInitialFastElementsKind());
1294     Map::EnsureDescriptorSlack(initial_map, 1);
1295 
1296     PropertyAttributes attribs = static_cast<PropertyAttributes>(
1297         DONT_ENUM | DONT_DELETE);
1298 
1299     Handle<AccessorInfo> array_length =
1300         Accessors::ArrayLengthInfo(isolate, attribs);
1301     {  // Add length.
1302       AccessorConstantDescriptor d(
1303           Handle<Name>(Name::cast(array_length->name())), array_length,
1304           attribs);
1305       initial_map->AppendDescriptor(&d);
1306     }
1307 
1308     InstallWithIntrinsicDefaultProto(isolate, array_function,
1309                                      Context::ARRAY_FUNCTION_INDEX);
1310 
1311     // Cache the array maps, needed by ArrayConstructorStub
1312     CacheInitialJSArrayMaps(native_context(), initial_map);
1313     ArrayConstructorStub array_constructor_stub(isolate);
1314     Handle<Code> code = array_constructor_stub.GetCode();
1315     array_function->shared()->SetConstructStub(*code);
1316 
1317     Handle<JSFunction> is_arraylike = SimpleInstallFunction(
1318         array_function, isolate->factory()->InternalizeUtf8String("isArray"),
1319         Builtins::kArrayIsArray, 1, true);
1320     native_context()->set_is_arraylike(*is_arraylike);
1321   }
1322 
1323   {  // --- A r r a y I t e r a t o r ---
1324     Handle<JSObject> iterator_prototype(
1325         native_context()->initial_iterator_prototype());
1326 
1327     Handle<JSObject> array_iterator_prototype =
1328         factory->NewJSObject(isolate->object_function(), TENURED);
1329     JSObject::ForceSetPrototype(array_iterator_prototype, iterator_prototype);
1330 
1331     JSObject::AddProperty(
1332         array_iterator_prototype, factory->to_string_tag_symbol(),
1333         factory->ArrayIterator_string(),
1334         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
1335 
1336     Handle<JSFunction> next = InstallFunction(
1337         array_iterator_prototype, "next", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1338         MaybeHandle<JSObject>(), Builtins::kArrayIteratorPrototypeNext);
1339     next->shared()->set_builtin_function_id(kArrayIteratorNext);
1340 
1341     // Set the expected parameters for %ArrayIteratorPrototype%.next to 0 (not
1342     // including the receiver), as required by the builtin.
1343     next->shared()->set_internal_formal_parameter_count(0);
1344 
1345     // Set the length for the function to satisfy ECMA-262.
1346     next->shared()->set_length(0);
1347 
1348     Handle<JSFunction> array_iterator_function = CreateFunction(
1349         isolate, factory->ArrayIterator_string(),
1350         JS_FAST_ARRAY_VALUE_ITERATOR_TYPE, JSArrayIterator::kSize,
1351         array_iterator_prototype, Builtins::kIllegal);
1352     array_iterator_function->shared()->set_instance_class_name(
1353         isolate->heap()->ArrayIterator_string());
1354 
1355     native_context()->set_initial_array_iterator_prototype(
1356         *array_iterator_prototype);
1357     native_context()->set_initial_array_iterator_prototype_map(
1358         array_iterator_prototype->map());
1359 
1360     Handle<Map> initial_map(array_iterator_function->initial_map(), isolate);
1361 
1362 #define ARRAY_ITERATOR_LIST(V)                                              \
1363   V(TYPED_ARRAY, KEY, typed_array, key)                                     \
1364   V(FAST_ARRAY, KEY, fast_array, key)                                       \
1365   V(GENERIC_ARRAY, KEY, array, key)                                         \
1366   V(UINT8_ARRAY, KEY_VALUE, uint8_array, key_value)                         \
1367   V(INT8_ARRAY, KEY_VALUE, int8_array, key_value)                           \
1368   V(UINT16_ARRAY, KEY_VALUE, uint16_array, key_value)                       \
1369   V(INT16_ARRAY, KEY_VALUE, int16_array, key_value)                         \
1370   V(UINT32_ARRAY, KEY_VALUE, uint32_array, key_value)                       \
1371   V(INT32_ARRAY, KEY_VALUE, int32_array, key_value)                         \
1372   V(FLOAT32_ARRAY, KEY_VALUE, float32_array, key_value)                     \
1373   V(FLOAT64_ARRAY, KEY_VALUE, float64_array, key_value)                     \
1374   V(UINT8_CLAMPED_ARRAY, KEY_VALUE, uint8_clamped_array, key_value)         \
1375   V(FAST_SMI_ARRAY, KEY_VALUE, fast_smi_array, key_value)                   \
1376   V(FAST_HOLEY_SMI_ARRAY, KEY_VALUE, fast_holey_smi_array, key_value)       \
1377   V(FAST_ARRAY, KEY_VALUE, fast_array, key_value)                           \
1378   V(FAST_HOLEY_ARRAY, KEY_VALUE, fast_holey_array, key_value)               \
1379   V(FAST_DOUBLE_ARRAY, KEY_VALUE, fast_double_array, key_value)             \
1380   V(FAST_HOLEY_DOUBLE_ARRAY, KEY_VALUE, fast_holey_double_array, key_value) \
1381   V(GENERIC_ARRAY, KEY_VALUE, array, key_value)                             \
1382   V(UINT8_ARRAY, VALUE, uint8_array, value)                                 \
1383   V(INT8_ARRAY, VALUE, int8_array, value)                                   \
1384   V(UINT16_ARRAY, VALUE, uint16_array, value)                               \
1385   V(INT16_ARRAY, VALUE, int16_array, value)                                 \
1386   V(UINT32_ARRAY, VALUE, uint32_array, value)                               \
1387   V(INT32_ARRAY, VALUE, int32_array, value)                                 \
1388   V(FLOAT32_ARRAY, VALUE, float32_array, value)                             \
1389   V(FLOAT64_ARRAY, VALUE, float64_array, value)                             \
1390   V(UINT8_CLAMPED_ARRAY, VALUE, uint8_clamped_array, value)                 \
1391   V(FAST_SMI_ARRAY, VALUE, fast_smi_array, value)                           \
1392   V(FAST_HOLEY_SMI_ARRAY, VALUE, fast_holey_smi_array, value)               \
1393   V(FAST_ARRAY, VALUE, fast_array, value)                                   \
1394   V(FAST_HOLEY_ARRAY, VALUE, fast_holey_array, value)                       \
1395   V(FAST_DOUBLE_ARRAY, VALUE, fast_double_array, value)                     \
1396   V(FAST_HOLEY_DOUBLE_ARRAY, VALUE, fast_holey_double_array, value)         \
1397   V(GENERIC_ARRAY, VALUE, array, value)
1398 
1399 #define CREATE_ARRAY_ITERATOR_MAP(PREFIX, SUFFIX, prefix, suffix)           \
1400   do {                                                                      \
1401     const InstanceType type = JS_##PREFIX##_##SUFFIX##_ITERATOR_TYPE;       \
1402     Handle<Map> map =                                                       \
1403         Map::Copy(initial_map, "JS_" #PREFIX "_" #SUFFIX "_ITERATOR_TYPE"); \
1404     map->set_instance_type(type);                                           \
1405     native_context()->set_##prefix##_##suffix##_iterator_map(*map);         \
1406   } while (0);
1407 
1408     ARRAY_ITERATOR_LIST(CREATE_ARRAY_ITERATOR_MAP)
1409 
1410 #undef CREATE_ARRAY_ITERATOR_MAP
1411 #undef ARRAY_ITERATOR_LIST
1412   }
1413 
1414   {  // --- N u m b e r ---
1415     Handle<JSFunction> number_fun = InstallFunction(
1416         global, "Number", JS_VALUE_TYPE, JSValue::kSize,
1417         isolate->initial_object_prototype(), Builtins::kNumberConstructor);
1418     number_fun->shared()->DontAdaptArguments();
1419     number_fun->shared()->SetConstructStub(
1420         *isolate->builtins()->NumberConstructor_ConstructStub());
1421     number_fun->shared()->set_length(1);
1422     InstallWithIntrinsicDefaultProto(isolate, number_fun,
1423                                      Context::NUMBER_FUNCTION_INDEX);
1424 
1425     // Create the %NumberPrototype%
1426     Handle<JSValue> prototype =
1427         Handle<JSValue>::cast(factory->NewJSObject(number_fun, TENURED));
1428     prototype->set_value(Smi::kZero);
1429     Accessors::FunctionSetPrototype(number_fun, prototype).Assert();
1430 
1431     // Install the "constructor" property on the {prototype}.
1432     JSObject::AddProperty(prototype, factory->constructor_string(), number_fun,
1433                           DONT_ENUM);
1434 
1435     // Install the Number.prototype methods.
1436     SimpleInstallFunction(prototype, "toExponential",
1437                           Builtins::kNumberPrototypeToExponential, 1, false);
1438     SimpleInstallFunction(prototype, "toFixed",
1439                           Builtins::kNumberPrototypeToFixed, 1, false);
1440     SimpleInstallFunction(prototype, "toPrecision",
1441                           Builtins::kNumberPrototypeToPrecision, 1, false);
1442     SimpleInstallFunction(prototype, "toString",
1443                           Builtins::kNumberPrototypeToString, 1, false);
1444     SimpleInstallFunction(prototype, "valueOf",
1445                           Builtins::kNumberPrototypeValueOf, 0, true);
1446 
1447     // Install i18n fallback functions.
1448     SimpleInstallFunction(prototype, "toLocaleString",
1449                           Builtins::kNumberPrototypeToLocaleString, 0, false);
1450 
1451     // Install the Number functions.
1452     SimpleInstallFunction(number_fun, "isFinite", Builtins::kNumberIsFinite, 1,
1453                           true);
1454     SimpleInstallFunction(number_fun, "isInteger", Builtins::kNumberIsInteger,
1455                           1, true);
1456     SimpleInstallFunction(number_fun, "isNaN", Builtins::kNumberIsNaN, 1, true);
1457     SimpleInstallFunction(number_fun, "isSafeInteger",
1458                           Builtins::kNumberIsSafeInteger, 1, true);
1459 
1460     // Install Number.parseFloat and Global.parseFloat.
1461     Handle<JSFunction> parse_float_fun = SimpleInstallFunction(
1462         number_fun, "parseFloat", Builtins::kNumberParseFloat, 1, true);
1463     JSObject::AddProperty(global_object,
1464                           factory->NewStringFromAsciiChecked("parseFloat"),
1465                           parse_float_fun, DONT_ENUM);
1466 
1467     // Install Number.parseInt and Global.parseInt.
1468     Handle<JSFunction> parse_int_fun = SimpleInstallFunction(
1469         number_fun, "parseInt", Builtins::kNumberParseInt, 2, true);
1470     JSObject::AddProperty(global_object,
1471                           factory->NewStringFromAsciiChecked("parseInt"),
1472                           parse_int_fun, DONT_ENUM);
1473   }
1474 
1475   {  // --- B o o l e a n ---
1476     Handle<JSFunction> boolean_fun =
1477         InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
1478                         isolate->initial_object_prototype(),
1479                         Builtins::kBooleanConstructor);
1480     boolean_fun->shared()->DontAdaptArguments();
1481     boolean_fun->shared()->SetConstructStub(
1482         *isolate->builtins()->BooleanConstructor_ConstructStub());
1483     boolean_fun->shared()->set_length(1);
1484     InstallWithIntrinsicDefaultProto(isolate, boolean_fun,
1485                                      Context::BOOLEAN_FUNCTION_INDEX);
1486 
1487     // Create the %BooleanPrototype%
1488     Handle<JSValue> prototype =
1489         Handle<JSValue>::cast(factory->NewJSObject(boolean_fun, TENURED));
1490     prototype->set_value(isolate->heap()->false_value());
1491     Accessors::FunctionSetPrototype(boolean_fun, prototype).Assert();
1492 
1493     // Install the "constructor" property on the {prototype}.
1494     JSObject::AddProperty(prototype, factory->constructor_string(), boolean_fun,
1495                           DONT_ENUM);
1496 
1497     // Install the Boolean.prototype methods.
1498     SimpleInstallFunction(prototype, "toString",
1499                           Builtins::kBooleanPrototypeToString, 0, true);
1500     SimpleInstallFunction(prototype, "valueOf",
1501                           Builtins::kBooleanPrototypeValueOf, 0, true);
1502   }
1503 
1504   {  // --- S t r i n g ---
1505     Handle<JSFunction> string_fun = InstallFunction(
1506         global, "String", JS_VALUE_TYPE, JSValue::kSize,
1507         isolate->initial_object_prototype(), Builtins::kStringConstructor);
1508     string_fun->shared()->SetConstructStub(
1509         *isolate->builtins()->StringConstructor_ConstructStub());
1510     string_fun->shared()->DontAdaptArguments();
1511     string_fun->shared()->set_length(1);
1512     InstallWithIntrinsicDefaultProto(isolate, string_fun,
1513                                      Context::STRING_FUNCTION_INDEX);
1514 
1515     Handle<Map> string_map =
1516         Handle<Map>(native_context()->string_function()->initial_map());
1517     string_map->set_elements_kind(FAST_STRING_WRAPPER_ELEMENTS);
1518     Map::EnsureDescriptorSlack(string_map, 1);
1519 
1520     PropertyAttributes attribs = static_cast<PropertyAttributes>(
1521         DONT_ENUM | DONT_DELETE | READ_ONLY);
1522     Handle<AccessorInfo> string_length(
1523         Accessors::StringLengthInfo(isolate, attribs));
1524 
1525     {  // Add length.
1526       AccessorConstantDescriptor d(factory->length_string(), string_length,
1527                                    attribs);
1528       string_map->AppendDescriptor(&d);
1529     }
1530 
1531     // Install the String.fromCharCode function.
1532     SimpleInstallFunction(string_fun, "fromCharCode",
1533                           Builtins::kStringFromCharCode, 1, false);
1534 
1535     // Install the String.fromCodePoint function.
1536     SimpleInstallFunction(string_fun, "fromCodePoint",
1537                           Builtins::kStringFromCodePoint, 1, false);
1538 
1539     // Create the %StringPrototype%
1540     Handle<JSValue> prototype =
1541         Handle<JSValue>::cast(factory->NewJSObject(string_fun, TENURED));
1542     prototype->set_value(isolate->heap()->empty_string());
1543     Accessors::FunctionSetPrototype(string_fun, prototype).Assert();
1544 
1545     // Install the "constructor" property on the {prototype}.
1546     JSObject::AddProperty(prototype, factory->constructor_string(), string_fun,
1547                           DONT_ENUM);
1548 
1549     // Install the String.prototype methods.
1550     SimpleInstallFunction(prototype, "charAt", Builtins::kStringPrototypeCharAt,
1551                           1, true);
1552     SimpleInstallFunction(prototype, "charCodeAt",
1553                           Builtins::kStringPrototypeCharCodeAt, 1, true);
1554     SimpleInstallFunction(prototype, "endsWith",
1555                           Builtins::kStringPrototypeEndsWith, 1, false);
1556     SimpleInstallFunction(prototype, "includes",
1557                           Builtins::kStringPrototypeIncludes, 1, false);
1558     SimpleInstallFunction(prototype, "indexOf",
1559                           Builtins::kStringPrototypeIndexOf, 1, false);
1560     SimpleInstallFunction(prototype, "lastIndexOf",
1561                           Builtins::kStringPrototypeLastIndexOf, 1, false);
1562     SimpleInstallFunction(prototype, "localeCompare",
1563                           Builtins::kStringPrototypeLocaleCompare, 1, true);
1564     SimpleInstallFunction(prototype, "normalize",
1565                           Builtins::kStringPrototypeNormalize, 0, false);
1566     SimpleInstallFunction(prototype, "substr", Builtins::kStringPrototypeSubstr,
1567                           2, true);
1568     SimpleInstallFunction(prototype, "substring",
1569                           Builtins::kStringPrototypeSubstring, 2, true);
1570     SimpleInstallFunction(prototype, "startsWith",
1571                           Builtins::kStringPrototypeStartsWith, 1, false);
1572     SimpleInstallFunction(prototype, "toString",
1573                           Builtins::kStringPrototypeToString, 0, true);
1574     SimpleInstallFunction(prototype, "trim", Builtins::kStringPrototypeTrim, 0,
1575                           false);
1576     SimpleInstallFunction(prototype, "trimLeft",
1577                           Builtins::kStringPrototypeTrimLeft, 0, false);
1578     SimpleInstallFunction(prototype, "trimRight",
1579                           Builtins::kStringPrototypeTrimRight, 0, false);
1580     SimpleInstallFunction(prototype, "valueOf",
1581                           Builtins::kStringPrototypeValueOf, 0, true);
1582 
1583     Handle<JSFunction> iterator = SimpleCreateFunction(
1584         isolate, factory->NewStringFromAsciiChecked("[Symbol.iterator]"),
1585         Builtins::kStringPrototypeIterator, 0, true);
1586     iterator->shared()->set_native(true);
1587     iterator->shared()->set_builtin_function_id(kStringIterator);
1588     JSObject::AddProperty(prototype, factory->iterator_symbol(), iterator,
1589                           static_cast<PropertyAttributes>(DONT_ENUM));
1590   }
1591 
1592   {  // --- S t r i n g I t e r a t o r ---
1593     Handle<JSObject> iterator_prototype(
1594         native_context()->initial_iterator_prototype());
1595 
1596     Handle<JSObject> string_iterator_prototype =
1597         factory->NewJSObject(isolate->object_function(), TENURED);
1598     JSObject::ForceSetPrototype(string_iterator_prototype, iterator_prototype);
1599 
1600     JSObject::AddProperty(
1601         string_iterator_prototype, factory->to_string_tag_symbol(),
1602         factory->NewStringFromAsciiChecked("String Iterator"),
1603         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
1604 
1605     Handle<JSFunction> next =
1606         InstallFunction(string_iterator_prototype, "next", JS_OBJECT_TYPE,
1607                         JSObject::kHeaderSize, MaybeHandle<JSObject>(),
1608                         Builtins::kStringIteratorPrototypeNext);
1609     next->shared()->set_builtin_function_id(kStringIteratorNext);
1610 
1611     // Set the expected parameters for %StringIteratorPrototype%.next to 0 (not
1612     // including the receiver), as required by the builtin.
1613     next->shared()->set_internal_formal_parameter_count(0);
1614 
1615     // Set the length for the function to satisfy ECMA-262.
1616     next->shared()->set_length(0);
1617 
1618     Handle<JSFunction> string_iterator_function = CreateFunction(
1619         isolate, factory->NewStringFromAsciiChecked("StringIterator"),
1620         JS_STRING_ITERATOR_TYPE, JSStringIterator::kSize,
1621         string_iterator_prototype, Builtins::kIllegal);
1622     native_context()->set_string_iterator_map(
1623         string_iterator_function->initial_map());
1624   }
1625 
1626   {
1627     // --- S y m b o l ---
1628     Handle<JSObject> prototype =
1629         factory->NewJSObject(isolate->object_function(), TENURED);
1630     Handle<JSFunction> symbol_fun =
1631         InstallFunction(global, "Symbol", JS_VALUE_TYPE, JSValue::kSize,
1632                         prototype, Builtins::kSymbolConstructor);
1633     symbol_fun->shared()->SetConstructStub(
1634         *isolate->builtins()->SymbolConstructor_ConstructStub());
1635     symbol_fun->shared()->set_length(0);
1636     symbol_fun->shared()->DontAdaptArguments();
1637     native_context()->set_symbol_function(*symbol_fun);
1638 
1639     // Install the @@toStringTag property on the {prototype}.
1640     JSObject::AddProperty(
1641         prototype, factory->to_string_tag_symbol(),
1642         factory->NewStringFromAsciiChecked("Symbol"),
1643         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
1644 
1645     // Install the "constructor" property on the {prototype}.
1646     JSObject::AddProperty(prototype, factory->constructor_string(), symbol_fun,
1647                           DONT_ENUM);
1648 
1649     // Install the Symbol.prototype methods.
1650     SimpleInstallFunction(prototype, "toString",
1651                           Builtins::kSymbolPrototypeToString, 0, true);
1652     SimpleInstallFunction(prototype, "valueOf",
1653                           Builtins::kSymbolPrototypeValueOf, 0, true);
1654 
1655     // Install the @@toPrimitive function.
1656     Handle<JSFunction> to_primitive = InstallFunction(
1657         prototype, factory->to_primitive_symbol(), JS_OBJECT_TYPE,
1658         JSObject::kHeaderSize, MaybeHandle<JSObject>(),
1659         Builtins::kSymbolPrototypeToPrimitive,
1660         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
1661 
1662     // Set the expected parameters for @@toPrimitive to 1; required by builtin.
1663     to_primitive->shared()->set_internal_formal_parameter_count(1);
1664 
1665     // Set the length for the function to satisfy ECMA-262.
1666     to_primitive->shared()->set_length(1);
1667   }
1668 
1669   {  // --- D a t e ---
1670     // Builtin functions for Date.prototype.
1671     Handle<JSObject> prototype =
1672         factory->NewJSObject(isolate->object_function(), TENURED);
1673     Handle<JSFunction> date_fun =
1674         InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize, prototype,
1675                         Builtins::kDateConstructor);
1676     InstallWithIntrinsicDefaultProto(isolate, date_fun,
1677                                      Context::DATE_FUNCTION_INDEX);
1678     date_fun->shared()->SetConstructStub(
1679         *isolate->builtins()->DateConstructor_ConstructStub());
1680     date_fun->shared()->set_length(7);
1681     date_fun->shared()->DontAdaptArguments();
1682 
1683     // Install the Date.now, Date.parse and Date.UTC functions.
1684     SimpleInstallFunction(date_fun, "now", Builtins::kDateNow, 0, false);
1685     SimpleInstallFunction(date_fun, "parse", Builtins::kDateParse, 1, false);
1686     SimpleInstallFunction(date_fun, "UTC", Builtins::kDateUTC, 7, false);
1687 
1688     // Install the "constructor" property on the {prototype}.
1689     JSObject::AddProperty(prototype, factory->constructor_string(), date_fun,
1690                           DONT_ENUM);
1691 
1692     // Install the Date.prototype methods.
1693     SimpleInstallFunction(prototype, "toString",
1694                           Builtins::kDatePrototypeToString, 0, false);
1695     SimpleInstallFunction(prototype, "toDateString",
1696                           Builtins::kDatePrototypeToDateString, 0, false);
1697     SimpleInstallFunction(prototype, "toTimeString",
1698                           Builtins::kDatePrototypeToTimeString, 0, false);
1699     SimpleInstallFunction(prototype, "toISOString",
1700                           Builtins::kDatePrototypeToISOString, 0, false);
1701     Handle<JSFunction> to_utc_string =
1702         SimpleInstallFunction(prototype, "toUTCString",
1703                               Builtins::kDatePrototypeToUTCString, 0, false);
1704     InstallFunction(prototype, to_utc_string,
1705                     factory->InternalizeUtf8String("toGMTString"), DONT_ENUM);
1706     SimpleInstallFunction(prototype, "getDate", Builtins::kDatePrototypeGetDate,
1707                           0, true);
1708     SimpleInstallFunction(prototype, "setDate", Builtins::kDatePrototypeSetDate,
1709                           1, false);
1710     SimpleInstallFunction(prototype, "getDay", Builtins::kDatePrototypeGetDay,
1711                           0, true);
1712     SimpleInstallFunction(prototype, "getFullYear",
1713                           Builtins::kDatePrototypeGetFullYear, 0, true);
1714     SimpleInstallFunction(prototype, "setFullYear",
1715                           Builtins::kDatePrototypeSetFullYear, 3, false);
1716     SimpleInstallFunction(prototype, "getHours",
1717                           Builtins::kDatePrototypeGetHours, 0, true);
1718     SimpleInstallFunction(prototype, "setHours",
1719                           Builtins::kDatePrototypeSetHours, 4, false);
1720     SimpleInstallFunction(prototype, "getMilliseconds",
1721                           Builtins::kDatePrototypeGetMilliseconds, 0, true);
1722     SimpleInstallFunction(prototype, "setMilliseconds",
1723                           Builtins::kDatePrototypeSetMilliseconds, 1, false);
1724     SimpleInstallFunction(prototype, "getMinutes",
1725                           Builtins::kDatePrototypeGetMinutes, 0, true);
1726     SimpleInstallFunction(prototype, "setMinutes",
1727                           Builtins::kDatePrototypeSetMinutes, 3, false);
1728     SimpleInstallFunction(prototype, "getMonth",
1729                           Builtins::kDatePrototypeGetMonth, 0, true);
1730     SimpleInstallFunction(prototype, "setMonth",
1731                           Builtins::kDatePrototypeSetMonth, 2, false);
1732     SimpleInstallFunction(prototype, "getSeconds",
1733                           Builtins::kDatePrototypeGetSeconds, 0, true);
1734     SimpleInstallFunction(prototype, "setSeconds",
1735                           Builtins::kDatePrototypeSetSeconds, 2, false);
1736     SimpleInstallFunction(prototype, "getTime", Builtins::kDatePrototypeGetTime,
1737                           0, true);
1738     SimpleInstallFunction(prototype, "setTime", Builtins::kDatePrototypeSetTime,
1739                           1, false);
1740     SimpleInstallFunction(prototype, "getTimezoneOffset",
1741                           Builtins::kDatePrototypeGetTimezoneOffset, 0, true);
1742     SimpleInstallFunction(prototype, "getUTCDate",
1743                           Builtins::kDatePrototypeGetUTCDate, 0, true);
1744     SimpleInstallFunction(prototype, "setUTCDate",
1745                           Builtins::kDatePrototypeSetUTCDate, 1, false);
1746     SimpleInstallFunction(prototype, "getUTCDay",
1747                           Builtins::kDatePrototypeGetUTCDay, 0, true);
1748     SimpleInstallFunction(prototype, "getUTCFullYear",
1749                           Builtins::kDatePrototypeGetUTCFullYear, 0, true);
1750     SimpleInstallFunction(prototype, "setUTCFullYear",
1751                           Builtins::kDatePrototypeSetUTCFullYear, 3, false);
1752     SimpleInstallFunction(prototype, "getUTCHours",
1753                           Builtins::kDatePrototypeGetUTCHours, 0, true);
1754     SimpleInstallFunction(prototype, "setUTCHours",
1755                           Builtins::kDatePrototypeSetUTCHours, 4, false);
1756     SimpleInstallFunction(prototype, "getUTCMilliseconds",
1757                           Builtins::kDatePrototypeGetUTCMilliseconds, 0, true);
1758     SimpleInstallFunction(prototype, "setUTCMilliseconds",
1759                           Builtins::kDatePrototypeSetUTCMilliseconds, 1, false);
1760     SimpleInstallFunction(prototype, "getUTCMinutes",
1761                           Builtins::kDatePrototypeGetUTCMinutes, 0, true);
1762     SimpleInstallFunction(prototype, "setUTCMinutes",
1763                           Builtins::kDatePrototypeSetUTCMinutes, 3, false);
1764     SimpleInstallFunction(prototype, "getUTCMonth",
1765                           Builtins::kDatePrototypeGetUTCMonth, 0, true);
1766     SimpleInstallFunction(prototype, "setUTCMonth",
1767                           Builtins::kDatePrototypeSetUTCMonth, 2, false);
1768     SimpleInstallFunction(prototype, "getUTCSeconds",
1769                           Builtins::kDatePrototypeGetUTCSeconds, 0, true);
1770     SimpleInstallFunction(prototype, "setUTCSeconds",
1771                           Builtins::kDatePrototypeSetUTCSeconds, 2, false);
1772     SimpleInstallFunction(prototype, "valueOf", Builtins::kDatePrototypeValueOf,
1773                           0, false);
1774     SimpleInstallFunction(prototype, "getYear", Builtins::kDatePrototypeGetYear,
1775                           0, true);
1776     SimpleInstallFunction(prototype, "setYear", Builtins::kDatePrototypeSetYear,
1777                           1, false);
1778     SimpleInstallFunction(prototype, "toJSON", Builtins::kDatePrototypeToJson,
1779                           1, false);
1780 
1781     // Install i18n fallback functions.
1782     SimpleInstallFunction(prototype, "toLocaleString",
1783                           Builtins::kDatePrototypeToString, 0, false);
1784     SimpleInstallFunction(prototype, "toLocaleDateString",
1785                           Builtins::kDatePrototypeToDateString, 0, false);
1786     SimpleInstallFunction(prototype, "toLocaleTimeString",
1787                           Builtins::kDatePrototypeToTimeString, 0, false);
1788 
1789     // Install the @@toPrimitive function.
1790     Handle<JSFunction> to_primitive = InstallFunction(
1791         prototype, factory->to_primitive_symbol(), JS_OBJECT_TYPE,
1792         JSObject::kHeaderSize, MaybeHandle<JSObject>(),
1793         Builtins::kDatePrototypeToPrimitive,
1794         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
1795 
1796     // Set the expected parameters for @@toPrimitive to 1; required by builtin.
1797     to_primitive->shared()->set_internal_formal_parameter_count(1);
1798 
1799     // Set the length for the function to satisfy ECMA-262.
1800     to_primitive->shared()->set_length(1);
1801   }
1802 
1803   {  // -- R e g E x p
1804     // Builtin functions for RegExp.prototype.
1805     Handle<JSObject> prototype =
1806         factory->NewJSObject(isolate->object_function(), TENURED);
1807     Handle<JSFunction> regexp_fun =
1808         InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
1809                         prototype, Builtins::kRegExpConstructor);
1810     InstallWithIntrinsicDefaultProto(isolate, regexp_fun,
1811                                      Context::REGEXP_FUNCTION_INDEX);
1812 
1813     Handle<SharedFunctionInfo> shared(regexp_fun->shared(), isolate);
1814     shared->SetConstructStub(*isolate->builtins()->RegExpConstructor());
1815     shared->set_instance_class_name(isolate->heap()->RegExp_string());
1816     shared->DontAdaptArguments();
1817     shared->set_length(2);
1818 
1819     {
1820       // RegExp.prototype setup.
1821 
1822       // Install the "constructor" property on the {prototype}.
1823       JSObject::AddProperty(prototype, factory->constructor_string(),
1824                             regexp_fun, DONT_ENUM);
1825 
1826       {
1827         Handle<JSFunction> fun = SimpleInstallFunction(
1828             prototype, factory->exec_string(), Builtins::kRegExpPrototypeExec,
1829             1, true, DONT_ENUM);
1830         native_context()->set_regexp_exec_function(*fun);
1831       }
1832 
1833       SimpleInstallGetter(prototype, factory->flags_string(),
1834                           Builtins::kRegExpPrototypeFlagsGetter, true);
1835       SimpleInstallGetter(prototype, factory->global_string(),
1836                           Builtins::kRegExpPrototypeGlobalGetter, true);
1837       SimpleInstallGetter(prototype, factory->ignoreCase_string(),
1838                           Builtins::kRegExpPrototypeIgnoreCaseGetter, true);
1839       SimpleInstallGetter(prototype, factory->multiline_string(),
1840                           Builtins::kRegExpPrototypeMultilineGetter, true);
1841       SimpleInstallGetter(prototype, factory->source_string(),
1842                           Builtins::kRegExpPrototypeSourceGetter, false);
1843       SimpleInstallGetter(prototype, factory->sticky_string(),
1844                           Builtins::kRegExpPrototypeStickyGetter, true);
1845       SimpleInstallGetter(prototype, factory->unicode_string(),
1846                           Builtins::kRegExpPrototypeUnicodeGetter, true);
1847 
1848       SimpleInstallFunction(prototype, "compile",
1849                             Builtins::kRegExpPrototypeCompile, 2, false,
1850                             DONT_ENUM);
1851       SimpleInstallFunction(prototype, factory->toString_string(),
1852                             Builtins::kRegExpPrototypeToString, 0, false,
1853                             DONT_ENUM);
1854       SimpleInstallFunction(prototype, "test", Builtins::kRegExpPrototypeTest,
1855                             1, true, DONT_ENUM);
1856 
1857       {
1858         Handle<JSFunction> fun = SimpleCreateFunction(
1859             isolate, factory->InternalizeUtf8String("[Symbol.match]"),
1860             Builtins::kRegExpPrototypeMatch, 1, false);
1861         InstallFunction(prototype, fun, factory->match_symbol(), DONT_ENUM);
1862       }
1863 
1864       {
1865         Handle<JSFunction> fun = SimpleCreateFunction(
1866             isolate, factory->InternalizeUtf8String("[Symbol.replace]"),
1867             Builtins::kRegExpPrototypeReplace, 2, true);
1868         InstallFunction(prototype, fun, factory->replace_symbol(), DONT_ENUM);
1869       }
1870 
1871       {
1872         Handle<JSFunction> fun = SimpleCreateFunction(
1873             isolate, factory->InternalizeUtf8String("[Symbol.search]"),
1874             Builtins::kRegExpPrototypeSearch, 1, true);
1875         InstallFunction(prototype, fun, factory->search_symbol(), DONT_ENUM);
1876       }
1877 
1878       {
1879         Handle<JSFunction> fun = SimpleCreateFunction(
1880             isolate, factory->InternalizeUtf8String("[Symbol.split]"),
1881             Builtins::kRegExpPrototypeSplit, 2, false);
1882         InstallFunction(prototype, fun, factory->split_symbol(), DONT_ENUM);
1883       }
1884 
1885       // Store the initial RegExp.prototype map. This is used in fast-path
1886       // checks. Do not alter the prototype after this point.
1887       native_context()->set_regexp_prototype_map(prototype->map());
1888     }
1889 
1890     {
1891       // RegExp getters and setters.
1892 
1893       SimpleInstallGetter(regexp_fun,
1894                           factory->InternalizeUtf8String("[Symbol.species]"),
1895                           factory->species_symbol(),
1896                           Builtins::kRegExpPrototypeSpeciesGetter, false);
1897 
1898       // Static properties set by a successful match.
1899 
1900       const PropertyAttributes no_enum = DONT_ENUM;
1901       SimpleInstallGetterSetter(regexp_fun, factory->input_string(),
1902                                 Builtins::kRegExpInputGetter,
1903                                 Builtins::kRegExpInputSetter, no_enum);
1904       SimpleInstallGetterSetter(
1905           regexp_fun, factory->InternalizeUtf8String("$_"),
1906           Builtins::kRegExpInputGetter, Builtins::kRegExpInputSetter, no_enum);
1907 
1908       SimpleInstallGetterSetter(
1909           regexp_fun, factory->InternalizeUtf8String("lastMatch"),
1910           Builtins::kRegExpLastMatchGetter, Builtins::kEmptyFunction, no_enum);
1911       SimpleInstallGetterSetter(
1912           regexp_fun, factory->InternalizeUtf8String("$&"),
1913           Builtins::kRegExpLastMatchGetter, Builtins::kEmptyFunction, no_enum);
1914 
1915       SimpleInstallGetterSetter(
1916           regexp_fun, factory->InternalizeUtf8String("lastParen"),
1917           Builtins::kRegExpLastParenGetter, Builtins::kEmptyFunction, no_enum);
1918       SimpleInstallGetterSetter(
1919           regexp_fun, factory->InternalizeUtf8String("$+"),
1920           Builtins::kRegExpLastParenGetter, Builtins::kEmptyFunction, no_enum);
1921 
1922       SimpleInstallGetterSetter(regexp_fun,
1923                                 factory->InternalizeUtf8String("leftContext"),
1924                                 Builtins::kRegExpLeftContextGetter,
1925                                 Builtins::kEmptyFunction, no_enum);
1926       SimpleInstallGetterSetter(regexp_fun,
1927                                 factory->InternalizeUtf8String("$`"),
1928                                 Builtins::kRegExpLeftContextGetter,
1929                                 Builtins::kEmptyFunction, no_enum);
1930 
1931       SimpleInstallGetterSetter(regexp_fun,
1932                                 factory->InternalizeUtf8String("rightContext"),
1933                                 Builtins::kRegExpRightContextGetter,
1934                                 Builtins::kEmptyFunction, no_enum);
1935       SimpleInstallGetterSetter(regexp_fun,
1936                                 factory->InternalizeUtf8String("$'"),
1937                                 Builtins::kRegExpRightContextGetter,
1938                                 Builtins::kEmptyFunction, no_enum);
1939 
1940 #define INSTALL_CAPTURE_GETTER(i)                         \
1941   SimpleInstallGetterSetter(                              \
1942       regexp_fun, factory->InternalizeUtf8String("$" #i), \
1943       Builtins::kRegExpCapture##i##Getter, Builtins::kEmptyFunction, no_enum)
1944       INSTALL_CAPTURE_GETTER(1);
1945       INSTALL_CAPTURE_GETTER(2);
1946       INSTALL_CAPTURE_GETTER(3);
1947       INSTALL_CAPTURE_GETTER(4);
1948       INSTALL_CAPTURE_GETTER(5);
1949       INSTALL_CAPTURE_GETTER(6);
1950       INSTALL_CAPTURE_GETTER(7);
1951       INSTALL_CAPTURE_GETTER(8);
1952       INSTALL_CAPTURE_GETTER(9);
1953 #undef INSTALL_CAPTURE_GETTER
1954     }
1955 
1956     DCHECK(regexp_fun->has_initial_map());
1957     Handle<Map> initial_map(regexp_fun->initial_map());
1958 
1959     DCHECK_EQ(0, initial_map->GetInObjectProperties());
1960 
1961     Map::EnsureDescriptorSlack(initial_map, 1);
1962 
1963     // ECMA-262, section 15.10.7.5.
1964     PropertyAttributes writable =
1965         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
1966     DataDescriptor field(factory->lastIndex_string(),
1967                          JSRegExp::kLastIndexFieldIndex, writable,
1968                          Representation::Tagged());
1969     initial_map->AppendDescriptor(&field);
1970 
1971     static const int num_fields = JSRegExp::kInObjectFieldCount;
1972     initial_map->SetInObjectProperties(num_fields);
1973     initial_map->set_unused_property_fields(0);
1974     initial_map->set_instance_size(initial_map->instance_size() +
1975                                    num_fields * kPointerSize);
1976 
1977     {  // Internal: RegExpInternalMatch
1978       Handle<JSFunction> function =
1979           factory->NewFunction(isolate->factory()->empty_string(),
1980                                isolate->builtins()->RegExpInternalMatch(),
1981                                JS_OBJECT_TYPE, JSObject::kHeaderSize);
1982       function->shared()->set_internal_formal_parameter_count(2);
1983       function->shared()->set_length(2);
1984       function->shared()->set_native(true);
1985       native_context()->set(Context::REGEXP_INTERNAL_MATCH, *function);
1986     }
1987 
1988     // Create the last match info. One for external use, and one for internal
1989     // use when we don't want to modify the externally visible match info.
1990     Handle<RegExpMatchInfo> last_match_info = factory->NewRegExpMatchInfo();
1991     native_context()->set_regexp_last_match_info(*last_match_info);
1992     Handle<RegExpMatchInfo> internal_match_info = factory->NewRegExpMatchInfo();
1993     native_context()->set_regexp_internal_match_info(*internal_match_info);
1994   }
1995 
1996   {  // -- E r r o r
1997     InstallError(isolate, global, factory->Error_string(),
1998                  Context::ERROR_FUNCTION_INDEX);
1999     InstallMakeError(isolate, isolate->builtins()->MakeError(),
2000                      Context::MAKE_ERROR_INDEX);
2001   }
2002 
2003   {  // -- E v a l E r r o r
2004     InstallError(isolate, global, factory->EvalError_string(),
2005                  Context::EVAL_ERROR_FUNCTION_INDEX);
2006   }
2007 
2008   {  // -- R a n g e E r r o r
2009     InstallError(isolate, global, factory->RangeError_string(),
2010                  Context::RANGE_ERROR_FUNCTION_INDEX);
2011     InstallMakeError(isolate, isolate->builtins()->MakeRangeError(),
2012                      Context::MAKE_RANGE_ERROR_INDEX);
2013   }
2014 
2015   {  // -- R e f e r e n c e E r r o r
2016     InstallError(isolate, global, factory->ReferenceError_string(),
2017                  Context::REFERENCE_ERROR_FUNCTION_INDEX);
2018   }
2019 
2020   {  // -- S y n t a x E r r o r
2021     InstallError(isolate, global, factory->SyntaxError_string(),
2022                  Context::SYNTAX_ERROR_FUNCTION_INDEX);
2023     InstallMakeError(isolate, isolate->builtins()->MakeSyntaxError(),
2024                      Context::MAKE_SYNTAX_ERROR_INDEX);
2025   }
2026 
2027   {  // -- T y p e E r r o r
2028     InstallError(isolate, global, factory->TypeError_string(),
2029                  Context::TYPE_ERROR_FUNCTION_INDEX);
2030     InstallMakeError(isolate, isolate->builtins()->MakeTypeError(),
2031                      Context::MAKE_TYPE_ERROR_INDEX);
2032   }
2033 
2034   {  // -- U R I E r r o r
2035     InstallError(isolate, global, factory->URIError_string(),
2036                  Context::URI_ERROR_FUNCTION_INDEX);
2037     InstallMakeError(isolate, isolate->builtins()->MakeURIError(),
2038                      Context::MAKE_URI_ERROR_INDEX);
2039   }
2040 
2041   {  // -- C o m p i l e E r r o r
2042     Handle<JSObject> dummy = factory->NewJSObject(isolate->object_function());
2043     InstallError(isolate, dummy, factory->CompileError_string(),
2044                  Context::WASM_COMPILE_ERROR_FUNCTION_INDEX);
2045 
2046     // -- R u n t i m e E r r o r
2047     InstallError(isolate, dummy, factory->RuntimeError_string(),
2048                  Context::WASM_RUNTIME_ERROR_FUNCTION_INDEX);
2049   }
2050 
2051   // Initialize the embedder data slot.
2052   Handle<FixedArray> embedder_data = factory->NewFixedArray(3);
2053   native_context()->set_embedder_data(*embedder_data);
2054 
2055   {  // -- J S O N
2056     Handle<String> name = factory->InternalizeUtf8String("JSON");
2057     Handle<JSFunction> cons = factory->NewFunction(name);
2058     JSFunction::SetInstancePrototype(cons,
2059         Handle<Object>(native_context()->initial_object_prototype(), isolate));
2060     Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
2061     DCHECK(json_object->IsJSObject());
2062     JSObject::AddProperty(global, name, json_object, DONT_ENUM);
2063     SimpleInstallFunction(json_object, "parse", Builtins::kJsonParse, 2, false);
2064     SimpleInstallFunction(json_object, "stringify", Builtins::kJsonStringify, 3,
2065                           true);
2066     JSObject::AddProperty(
2067         json_object, factory->to_string_tag_symbol(),
2068         factory->NewStringFromAsciiChecked("JSON"),
2069         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2070   }
2071 
2072   {  // -- M a t h
2073     Handle<String> name = factory->InternalizeUtf8String("Math");
2074     Handle<JSFunction> cons = factory->NewFunction(name);
2075     JSFunction::SetInstancePrototype(
2076         cons,
2077         Handle<Object>(native_context()->initial_object_prototype(), isolate));
2078     Handle<JSObject> math = factory->NewJSObject(cons, TENURED);
2079     DCHECK(math->IsJSObject());
2080     JSObject::AddProperty(global, name, math, DONT_ENUM);
2081     SimpleInstallFunction(math, "abs", Builtins::kMathAbs, 1, true);
2082     SimpleInstallFunction(math, "acos", Builtins::kMathAcos, 1, true);
2083     SimpleInstallFunction(math, "acosh", Builtins::kMathAcosh, 1, true);
2084     SimpleInstallFunction(math, "asin", Builtins::kMathAsin, 1, true);
2085     SimpleInstallFunction(math, "asinh", Builtins::kMathAsinh, 1, true);
2086     SimpleInstallFunction(math, "atan", Builtins::kMathAtan, 1, true);
2087     SimpleInstallFunction(math, "atanh", Builtins::kMathAtanh, 1, true);
2088     SimpleInstallFunction(math, "atan2", Builtins::kMathAtan2, 2, true);
2089     SimpleInstallFunction(math, "ceil", Builtins::kMathCeil, 1, true);
2090     SimpleInstallFunction(math, "cbrt", Builtins::kMathCbrt, 1, true);
2091     SimpleInstallFunction(math, "expm1", Builtins::kMathExpm1, 1, true);
2092     SimpleInstallFunction(math, "clz32", Builtins::kMathClz32, 1, true);
2093     SimpleInstallFunction(math, "cos", Builtins::kMathCos, 1, true);
2094     SimpleInstallFunction(math, "cosh", Builtins::kMathCosh, 1, true);
2095     SimpleInstallFunction(math, "exp", Builtins::kMathExp, 1, true);
2096     Handle<JSFunction> math_floor =
2097         SimpleInstallFunction(math, "floor", Builtins::kMathFloor, 1, true);
2098     native_context()->set_math_floor(*math_floor);
2099     SimpleInstallFunction(math, "fround", Builtins::kMathFround, 1, true);
2100     SimpleInstallFunction(math, "hypot", Builtins::kMathHypot, 2, false);
2101     SimpleInstallFunction(math, "imul", Builtins::kMathImul, 2, true);
2102     SimpleInstallFunction(math, "log", Builtins::kMathLog, 1, true);
2103     SimpleInstallFunction(math, "log1p", Builtins::kMathLog1p, 1, true);
2104     SimpleInstallFunction(math, "log2", Builtins::kMathLog2, 1, true);
2105     SimpleInstallFunction(math, "log10", Builtins::kMathLog10, 1, true);
2106     SimpleInstallFunction(math, "max", Builtins::kMathMax, 2, false);
2107     SimpleInstallFunction(math, "min", Builtins::kMathMin, 2, false);
2108     Handle<JSFunction> math_pow =
2109         SimpleInstallFunction(math, "pow", Builtins::kMathPow, 2, true);
2110     native_context()->set_math_pow(*math_pow);
2111     SimpleInstallFunction(math, "random", Builtins::kMathRandom, 0, true);
2112     SimpleInstallFunction(math, "round", Builtins::kMathRound, 1, true);
2113     SimpleInstallFunction(math, "sign", Builtins::kMathSign, 1, true);
2114     SimpleInstallFunction(math, "sin", Builtins::kMathSin, 1, true);
2115     SimpleInstallFunction(math, "sinh", Builtins::kMathSinh, 1, true);
2116     SimpleInstallFunction(math, "sqrt", Builtins::kMathSqrt, 1, true);
2117     SimpleInstallFunction(math, "tan", Builtins::kMathTan, 1, true);
2118     SimpleInstallFunction(math, "tanh", Builtins::kMathTanh, 1, true);
2119     SimpleInstallFunction(math, "trunc", Builtins::kMathTrunc, 1, true);
2120 
2121     // Install math constants.
2122     double const kE = base::ieee754::exp(1.0);
2123     double const kPI = 3.1415926535897932;
2124     JSObject::AddProperty(
2125         math, factory->NewStringFromAsciiChecked("E"), factory->NewNumber(kE),
2126         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2127     JSObject::AddProperty(
2128         math, factory->NewStringFromAsciiChecked("LN10"),
2129         factory->NewNumber(base::ieee754::log(10.0)),
2130         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2131     JSObject::AddProperty(
2132         math, factory->NewStringFromAsciiChecked("LN2"),
2133         factory->NewNumber(base::ieee754::log(2.0)),
2134         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2135     JSObject::AddProperty(
2136         math, factory->NewStringFromAsciiChecked("LOG10E"),
2137         factory->NewNumber(base::ieee754::log10(kE)),
2138         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2139     JSObject::AddProperty(
2140         math, factory->NewStringFromAsciiChecked("LOG2E"),
2141         factory->NewNumber(base::ieee754::log2(kE)),
2142         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2143     JSObject::AddProperty(
2144         math, factory->NewStringFromAsciiChecked("PI"), factory->NewNumber(kPI),
2145         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2146     JSObject::AddProperty(
2147         math, factory->NewStringFromAsciiChecked("SQRT1_2"),
2148         factory->NewNumber(std::sqrt(0.5)),
2149         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2150     JSObject::AddProperty(
2151         math, factory->NewStringFromAsciiChecked("SQRT2"),
2152         factory->NewNumber(std::sqrt(2.0)),
2153         static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY));
2154     JSObject::AddProperty(
2155         math, factory->to_string_tag_symbol(),
2156         factory->NewStringFromAsciiChecked("Math"),
2157         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2158   }
2159 
2160   {  // -- A r r a y B u f f e r
2161     Handle<JSFunction> array_buffer_fun = InstallArrayBuffer(
2162         global, "ArrayBuffer", Builtins::kArrayBufferPrototypeGetByteLength,
2163         BuiltinFunctionId::kArrayBufferByteLength);
2164     InstallWithIntrinsicDefaultProto(isolate, array_buffer_fun,
2165                                      Context::ARRAY_BUFFER_FUN_INDEX);
2166   }
2167 
2168   {  // -- T y p e d A r r a y
2169     Handle<JSObject> prototype =
2170         factory->NewJSObject(isolate->object_function(), TENURED);
2171     native_context()->set_typed_array_prototype(*prototype);
2172 
2173     Handle<JSFunction> typed_array_fun =
2174         CreateFunction(isolate, factory->InternalizeUtf8String("TypedArray"),
2175                        JS_TYPED_ARRAY_TYPE, JSTypedArray::kSize, prototype,
2176                        Builtins::kIllegal);
2177 
2178     // Install the "constructor" property on the {prototype}.
2179     JSObject::AddProperty(prototype, factory->constructor_string(),
2180                           typed_array_fun, DONT_ENUM);
2181     native_context()->set_typed_array_function(*typed_array_fun);
2182 
2183     // Install the "buffer", "byteOffset", "byteLength" and "length"
2184     // getters on the {prototype}.
2185     SimpleInstallGetter(prototype, factory->buffer_string(),
2186                         Builtins::kTypedArrayPrototypeBuffer, false);
2187     SimpleInstallGetter(prototype, factory->byte_length_string(),
2188                         Builtins::kTypedArrayPrototypeByteLength, true,
2189                         kTypedArrayByteLength);
2190     SimpleInstallGetter(prototype, factory->byte_offset_string(),
2191                         Builtins::kTypedArrayPrototypeByteOffset, true,
2192                         kTypedArrayByteOffset);
2193     SimpleInstallGetter(prototype, factory->length_string(),
2194                         Builtins::kTypedArrayPrototypeLength, true,
2195                         kTypedArrayLength);
2196 
2197     // Install "keys", "values" and "entries" methods on the {prototype}.
2198     Handle<JSFunction> entries =
2199         SimpleInstallFunction(prototype, factory->entries_string(),
2200                               Builtins::kTypedArrayPrototypeEntries, 0, true);
2201     entries->shared()->set_builtin_function_id(kTypedArrayEntries);
2202 
2203     Handle<JSFunction> keys =
2204         SimpleInstallFunction(prototype, factory->keys_string(),
2205                               Builtins::kTypedArrayPrototypeKeys, 0, true);
2206     keys->shared()->set_builtin_function_id(kTypedArrayKeys);
2207 
2208     Handle<JSFunction> values =
2209         SimpleInstallFunction(prototype, factory->values_string(),
2210                               Builtins::kTypedArrayPrototypeValues, 0, true);
2211     values->shared()->set_builtin_function_id(kTypedArrayValues);
2212     JSObject::AddProperty(prototype, factory->iterator_symbol(), values,
2213                           DONT_ENUM);
2214   }
2215 
2216   {  // -- T y p e d A r r a y s
2217 #define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype, size)             \
2218   {                                                                    \
2219     Handle<JSFunction> fun;                                            \
2220     InstallTypedArray(#Type "Array", TYPE##_ELEMENTS, &fun);           \
2221     InstallWithIntrinsicDefaultProto(isolate, fun,                     \
2222                                      Context::TYPE##_ARRAY_FUN_INDEX); \
2223   }
2224     TYPED_ARRAYS(INSTALL_TYPED_ARRAY)
2225 #undef INSTALL_TYPED_ARRAY
2226   }
2227 
2228   {  // -- D a t a V i e w
2229     Handle<JSObject> prototype =
2230         factory->NewJSObject(isolate->object_function(), TENURED);
2231     Handle<JSFunction> data_view_fun =
2232         InstallFunction(global, "DataView", JS_DATA_VIEW_TYPE,
2233                         JSDataView::kSizeWithInternalFields, prototype,
2234                         Builtins::kDataViewConstructor);
2235     InstallWithIntrinsicDefaultProto(isolate, data_view_fun,
2236                                      Context::DATA_VIEW_FUN_INDEX);
2237     data_view_fun->shared()->SetConstructStub(
2238         *isolate->builtins()->DataViewConstructor_ConstructStub());
2239     data_view_fun->shared()->set_length(3);
2240     data_view_fun->shared()->DontAdaptArguments();
2241 
2242     // Install the @@toStringTag property on the {prototype}.
2243     JSObject::AddProperty(
2244         prototype, factory->to_string_tag_symbol(),
2245         factory->NewStringFromAsciiChecked("DataView"),
2246         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2247 
2248     // Install the "constructor" property on the {prototype}.
2249     JSObject::AddProperty(prototype, factory->constructor_string(),
2250                           data_view_fun, DONT_ENUM);
2251 
2252     // Install the "buffer", "byteOffset" and "byteLength" getters
2253     // on the {prototype}.
2254     SimpleInstallGetter(prototype, factory->buffer_string(),
2255                         Builtins::kDataViewPrototypeGetBuffer, false,
2256                         kDataViewBuffer);
2257     SimpleInstallGetter(prototype, factory->byte_length_string(),
2258                         Builtins::kDataViewPrototypeGetByteLength, false,
2259                         kDataViewByteLength);
2260     SimpleInstallGetter(prototype, factory->byte_offset_string(),
2261                         Builtins::kDataViewPrototypeGetByteOffset, false,
2262                         kDataViewByteOffset);
2263 
2264     SimpleInstallFunction(prototype, "getInt8",
2265                           Builtins::kDataViewPrototypeGetInt8, 1, false);
2266     SimpleInstallFunction(prototype, "setInt8",
2267                           Builtins::kDataViewPrototypeSetInt8, 2, false);
2268     SimpleInstallFunction(prototype, "getUint8",
2269                           Builtins::kDataViewPrototypeGetUint8, 1, false);
2270     SimpleInstallFunction(prototype, "setUint8",
2271                           Builtins::kDataViewPrototypeSetUint8, 2, false);
2272     SimpleInstallFunction(prototype, "getInt16",
2273                           Builtins::kDataViewPrototypeGetInt16, 1, false);
2274     SimpleInstallFunction(prototype, "setInt16",
2275                           Builtins::kDataViewPrototypeSetInt16, 2, false);
2276     SimpleInstallFunction(prototype, "getUint16",
2277                           Builtins::kDataViewPrototypeGetUint16, 1, false);
2278     SimpleInstallFunction(prototype, "setUint16",
2279                           Builtins::kDataViewPrototypeSetUint16, 2, false);
2280     SimpleInstallFunction(prototype, "getInt32",
2281                           Builtins::kDataViewPrototypeGetInt32, 1, false);
2282     SimpleInstallFunction(prototype, "setInt32",
2283                           Builtins::kDataViewPrototypeSetInt32, 2, false);
2284     SimpleInstallFunction(prototype, "getUint32",
2285                           Builtins::kDataViewPrototypeGetUint32, 1, false);
2286     SimpleInstallFunction(prototype, "setUint32",
2287                           Builtins::kDataViewPrototypeSetUint32, 2, false);
2288     SimpleInstallFunction(prototype, "getFloat32",
2289                           Builtins::kDataViewPrototypeGetFloat32, 1, false);
2290     SimpleInstallFunction(prototype, "setFloat32",
2291                           Builtins::kDataViewPrototypeSetFloat32, 2, false);
2292     SimpleInstallFunction(prototype, "getFloat64",
2293                           Builtins::kDataViewPrototypeGetFloat64, 1, false);
2294     SimpleInstallFunction(prototype, "setFloat64",
2295                           Builtins::kDataViewPrototypeSetFloat64, 2, false);
2296   }
2297 
2298   {  // -- M a p
2299     Handle<JSFunction> js_map_fun = InstallFunction(
2300         global, "Map", JS_MAP_TYPE, JSMap::kSize,
2301         isolate->initial_object_prototype(), Builtins::kIllegal);
2302     InstallWithIntrinsicDefaultProto(isolate, js_map_fun,
2303                                      Context::JS_MAP_FUN_INDEX);
2304   }
2305 
2306   {  // -- S e t
2307     Handle<JSFunction> js_set_fun = InstallFunction(
2308         global, "Set", JS_SET_TYPE, JSSet::kSize,
2309         isolate->initial_object_prototype(), Builtins::kIllegal);
2310     InstallWithIntrinsicDefaultProto(isolate, js_set_fun,
2311                                      Context::JS_SET_FUN_INDEX);
2312   }
2313 
2314   {  // -- J S M o d u l e N a m e s p a c e
2315     Handle<Map> map =
2316         factory->NewMap(JS_MODULE_NAMESPACE_TYPE, JSModuleNamespace::kSize);
2317     Map::SetPrototype(map, isolate->factory()->null_value());
2318     Map::EnsureDescriptorSlack(map, 2);
2319     native_context()->set_js_module_namespace_map(*map);
2320 
2321     {  // Install @@toStringTag.
2322       PropertyAttributes attribs =
2323           static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
2324       DataConstantDescriptor d(factory->to_string_tag_symbol(),
2325                                factory->NewStringFromAsciiChecked("Module"),
2326                                attribs);
2327       map->AppendDescriptor(&d);
2328     }
2329 
2330     {  // Install @@iterator.
2331       Handle<JSFunction> iterator = SimpleCreateFunction(
2332           isolate, factory->NewStringFromAsciiChecked("[Symbol.iterator]"),
2333           Builtins::kModuleNamespaceIterator, 0, true);
2334       iterator->shared()->set_native(true);
2335       // TODO(neis): Is this really supposed to be writable?
2336       DataConstantDescriptor d(factory->iterator_symbol(), iterator, DONT_ENUM);
2337       map->AppendDescriptor(&d);
2338     }
2339   }
2340 
2341   {  // -- I t e r a t o r R e s u l t
2342     Handle<Map> map =
2343         factory->NewMap(JS_OBJECT_TYPE, JSIteratorResult::kSize);
2344     Map::SetPrototype(map, isolate->initial_object_prototype());
2345     Map::EnsureDescriptorSlack(map, 2);
2346 
2347     {  // value
2348       DataDescriptor d(factory->value_string(), JSIteratorResult::kValueIndex,
2349                        NONE, Representation::Tagged());
2350       map->AppendDescriptor(&d);
2351     }
2352 
2353     {  // done
2354       DataDescriptor d(factory->done_string(), JSIteratorResult::kDoneIndex,
2355                        NONE, Representation::Tagged());
2356       map->AppendDescriptor(&d);
2357     }
2358 
2359     map->SetConstructor(native_context()->object_function());
2360     map->SetInObjectProperties(2);
2361     native_context()->set_iterator_result_map(*map);
2362   }
2363 
2364   {  // -- W e a k M a p
2365     Handle<JSFunction> js_weak_map_fun = InstallFunction(
2366         global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
2367         isolate->initial_object_prototype(), Builtins::kIllegal);
2368     InstallWithIntrinsicDefaultProto(isolate, js_weak_map_fun,
2369                                      Context::JS_WEAK_MAP_FUN_INDEX);
2370   }
2371 
2372   {  // -- W e a k S e t
2373     Handle<JSFunction> js_weak_set_fun = InstallFunction(
2374         global, "WeakSet", JS_WEAK_SET_TYPE, JSWeakSet::kSize,
2375         isolate->initial_object_prototype(), Builtins::kIllegal);
2376     InstallWithIntrinsicDefaultProto(isolate, js_weak_set_fun,
2377                                      Context::JS_WEAK_SET_FUN_INDEX);
2378   }
2379 
2380   {  // -- P r o x y
2381     CreateJSProxyMaps();
2382 
2383     Handle<String> name = factory->Proxy_string();
2384     Handle<Code> code(isolate->builtins()->ProxyConstructor());
2385 
2386     Handle<JSFunction> proxy_function =
2387         factory->NewFunction(isolate->proxy_function_map(),
2388                              factory->Proxy_string(), MaybeHandle<Code>(code));
2389 
2390     JSFunction::SetInitialMap(
2391         proxy_function, Handle<Map>(native_context()->proxy_map(), isolate),
2392         factory->null_value());
2393 
2394     proxy_function->shared()->SetConstructStub(
2395         *isolate->builtins()->ProxyConstructor_ConstructStub());
2396     proxy_function->shared()->set_internal_formal_parameter_count(2);
2397     proxy_function->shared()->set_length(2);
2398 
2399     native_context()->set_proxy_function(*proxy_function);
2400     InstallFunction(global, name, proxy_function, factory->Object_string());
2401   }
2402 
2403   {  // -- R e f l e c t
2404     Handle<String> reflect_string = factory->InternalizeUtf8String("Reflect");
2405     Handle<JSObject> reflect =
2406         factory->NewJSObject(isolate->object_function(), TENURED);
2407     JSObject::AddProperty(global, reflect_string, reflect, DONT_ENUM);
2408 
2409     Handle<JSFunction> define_property =
2410         SimpleInstallFunction(reflect, factory->defineProperty_string(),
2411                               Builtins::kReflectDefineProperty, 3, true);
2412     native_context()->set_reflect_define_property(*define_property);
2413 
2414     Handle<JSFunction> delete_property =
2415         SimpleInstallFunction(reflect, factory->deleteProperty_string(),
2416                               Builtins::kReflectDeleteProperty, 2, true);
2417     native_context()->set_reflect_delete_property(*delete_property);
2418 
2419     Handle<JSFunction> apply = SimpleInstallFunction(
2420         reflect, factory->apply_string(), Builtins::kReflectApply, 3, false);
2421     native_context()->set_reflect_apply(*apply);
2422 
2423     Handle<JSFunction> construct =
2424         SimpleInstallFunction(reflect, factory->construct_string(),
2425                               Builtins::kReflectConstruct, 2, false);
2426     native_context()->set_reflect_construct(*construct);
2427 
2428     SimpleInstallFunction(reflect, factory->get_string(), Builtins::kReflectGet,
2429                           2, false);
2430     SimpleInstallFunction(reflect, factory->getOwnPropertyDescriptor_string(),
2431                           Builtins::kReflectGetOwnPropertyDescriptor, 2, true);
2432     SimpleInstallFunction(reflect, factory->getPrototypeOf_string(),
2433                           Builtins::kReflectGetPrototypeOf, 1, true);
2434     SimpleInstallFunction(reflect, factory->has_string(), Builtins::kReflectHas,
2435                           2, true);
2436     SimpleInstallFunction(reflect, factory->isExtensible_string(),
2437                           Builtins::kReflectIsExtensible, 1, true);
2438     SimpleInstallFunction(reflect, factory->ownKeys_string(),
2439                           Builtins::kReflectOwnKeys, 1, true);
2440     SimpleInstallFunction(reflect, factory->preventExtensions_string(),
2441                           Builtins::kReflectPreventExtensions, 1, true);
2442     SimpleInstallFunction(reflect, factory->set_string(), Builtins::kReflectSet,
2443                           3, false);
2444     SimpleInstallFunction(reflect, factory->setPrototypeOf_string(),
2445                           Builtins::kReflectSetPrototypeOf, 2, true);
2446   }
2447 
2448   {  // --- B o u n d F u n c t i o n
2449     Handle<Map> map =
2450         factory->NewMap(JS_BOUND_FUNCTION_TYPE, JSBoundFunction::kSize);
2451     map->set_is_callable();
2452     Map::SetPrototype(map, empty_function);
2453 
2454     PropertyAttributes roc_attribs =
2455         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
2456     Map::EnsureDescriptorSlack(map, 2);
2457 
2458     Handle<AccessorInfo> bound_length =
2459         Accessors::BoundFunctionLengthInfo(isolate, roc_attribs);
2460     {  // length
2461       AccessorConstantDescriptor d(factory->length_string(), bound_length,
2462                                    roc_attribs);
2463       map->AppendDescriptor(&d);
2464     }
2465     Handle<AccessorInfo> bound_name =
2466         Accessors::BoundFunctionNameInfo(isolate, roc_attribs);
2467     {  // length
2468       AccessorConstantDescriptor d(factory->name_string(), bound_name,
2469                                    roc_attribs);
2470       map->AppendDescriptor(&d);
2471     }
2472     map->SetInObjectProperties(0);
2473     native_context()->set_bound_function_without_constructor_map(*map);
2474 
2475     map = Map::Copy(map, "IsConstructor");
2476     map->set_is_constructor(true);
2477     native_context()->set_bound_function_with_constructor_map(*map);
2478   }
2479 
2480   {  // --- sloppy arguments map
2481     // Make sure we can recognize argument objects at runtime.
2482     // This is done by introducing an anonymous function with
2483     // class_name equals 'Arguments'.
2484     Handle<String> arguments_string = factory->Arguments_string();
2485     Handle<Code> code = isolate->builtins()->Illegal();
2486     Handle<JSFunction> function = factory->NewFunctionWithoutPrototype(
2487         arguments_string, code);
2488     function->shared()->set_instance_class_name(*arguments_string);
2489 
2490     Handle<Map> map = factory->NewMap(
2491         JS_ARGUMENTS_TYPE, JSSloppyArgumentsObject::kSize, FAST_ELEMENTS);
2492     // Create the descriptor array for the arguments object.
2493     Map::EnsureDescriptorSlack(map, 2);
2494 
2495     {  // length
2496       DataDescriptor d(factory->length_string(),
2497                        JSSloppyArgumentsObject::kLengthIndex, DONT_ENUM,
2498                        Representation::Tagged());
2499       map->AppendDescriptor(&d);
2500     }
2501     {  // callee
2502       DataDescriptor d(factory->callee_string(),
2503                        JSSloppyArgumentsObject::kCalleeIndex, DONT_ENUM,
2504                        Representation::Tagged());
2505       map->AppendDescriptor(&d);
2506     }
2507     // @@iterator method is added later.
2508 
2509     map->SetInObjectProperties(2);
2510     native_context()->set_sloppy_arguments_map(*map);
2511 
2512     DCHECK(!function->has_initial_map());
2513     JSFunction::SetInitialMap(function, map,
2514                               isolate->initial_object_prototype());
2515 
2516     DCHECK(!map->is_dictionary_map());
2517     DCHECK(IsFastObjectElementsKind(map->elements_kind()));
2518   }
2519 
2520   {  // --- fast and slow aliased arguments map
2521     Handle<Map> map = isolate->sloppy_arguments_map();
2522     map = Map::Copy(map, "FastAliasedArguments");
2523     map->set_elements_kind(FAST_SLOPPY_ARGUMENTS_ELEMENTS);
2524     DCHECK_EQ(2, map->GetInObjectProperties());
2525     native_context()->set_fast_aliased_arguments_map(*map);
2526 
2527     map = Map::Copy(map, "SlowAliasedArguments");
2528     map->set_elements_kind(SLOW_SLOPPY_ARGUMENTS_ELEMENTS);
2529     DCHECK_EQ(2, map->GetInObjectProperties());
2530     native_context()->set_slow_aliased_arguments_map(*map);
2531   }
2532 
2533   {  // --- strict mode arguments map
2534     const PropertyAttributes attributes =
2535       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2536 
2537     // Create the ThrowTypeError function.
2538     Handle<AccessorPair> callee = factory->NewAccessorPair();
2539 
2540     Handle<JSFunction> poison = GetStrictArgumentsPoisonFunction();
2541 
2542     // Install the ThrowTypeError function.
2543     callee->set_getter(*poison);
2544     callee->set_setter(*poison);
2545 
2546     // Create the map. Allocate one in-object field for length.
2547     Handle<Map> map = factory->NewMap(
2548         JS_ARGUMENTS_TYPE, JSStrictArgumentsObject::kSize, FAST_ELEMENTS);
2549     // Create the descriptor array for the arguments object.
2550     Map::EnsureDescriptorSlack(map, 2);
2551 
2552     {  // length
2553       DataDescriptor d(factory->length_string(),
2554                        JSStrictArgumentsObject::kLengthIndex, DONT_ENUM,
2555                        Representation::Tagged());
2556       map->AppendDescriptor(&d);
2557     }
2558     {  // callee
2559       AccessorConstantDescriptor d(factory->callee_string(), callee,
2560                                    attributes);
2561       map->AppendDescriptor(&d);
2562     }
2563     // @@iterator method is added later.
2564 
2565     DCHECK_EQ(native_context()->object_function()->prototype(),
2566               *isolate->initial_object_prototype());
2567     Map::SetPrototype(map, isolate->initial_object_prototype());
2568     map->SetInObjectProperties(1);
2569 
2570     // Copy constructor from the sloppy arguments boilerplate.
2571     map->SetConstructor(
2572         native_context()->sloppy_arguments_map()->GetConstructor());
2573 
2574     native_context()->set_strict_arguments_map(*map);
2575 
2576     DCHECK(!map->is_dictionary_map());
2577     DCHECK(IsFastObjectElementsKind(map->elements_kind()));
2578   }
2579 
2580   {  // --- context extension
2581     // Create a function for the context extension objects.
2582     Handle<Code> code = isolate->builtins()->Illegal();
2583     Handle<JSFunction> context_extension_fun = factory->NewFunction(
2584         factory->empty_string(), code, JS_CONTEXT_EXTENSION_OBJECT_TYPE,
2585         JSObject::kHeaderSize);
2586 
2587     Handle<String> name = factory->InternalizeOneByteString(
2588         STATIC_CHAR_VECTOR("context_extension"));
2589     context_extension_fun->shared()->set_instance_class_name(*name);
2590     native_context()->set_context_extension_function(*context_extension_fun);
2591   }
2592 
2593 
2594   {
2595     // Set up the call-as-function delegate.
2596     Handle<Code> code = isolate->builtins()->HandleApiCallAsFunction();
2597     Handle<JSFunction> delegate = factory->NewFunction(
2598         factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
2599     native_context()->set_call_as_function_delegate(*delegate);
2600     delegate->shared()->DontAdaptArguments();
2601   }
2602 
2603   {
2604     // Set up the call-as-constructor delegate.
2605     Handle<Code> code = isolate->builtins()->HandleApiCallAsConstructor();
2606     Handle<JSFunction> delegate = factory->NewFunction(
2607         factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
2608     native_context()->set_call_as_constructor_delegate(*delegate);
2609     delegate->shared()->DontAdaptArguments();
2610   }
2611 }  // NOLINT(readability/fn_size)
2612 
InstallTypedArray(const char * name,ElementsKind elements_kind,Handle<JSFunction> * fun)2613 void Genesis::InstallTypedArray(const char* name, ElementsKind elements_kind,
2614                                 Handle<JSFunction>* fun) {
2615   Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
2616 
2617   Handle<JSObject> typed_array_prototype =
2618       Handle<JSObject>(isolate()->typed_array_prototype());
2619   Handle<JSFunction> typed_array_function =
2620       Handle<JSFunction>(isolate()->typed_array_function());
2621 
2622   Handle<JSObject> prototype =
2623       factory()->NewJSObject(isolate()->object_function(), TENURED);
2624   Handle<JSFunction> result = InstallFunction(
2625       global, name, JS_TYPED_ARRAY_TYPE, JSTypedArray::kSizeWithInternalFields,
2626       prototype, Builtins::kIllegal);
2627   result->initial_map()->set_elements_kind(elements_kind);
2628 
2629   CHECK(JSObject::SetPrototype(result, typed_array_function, false,
2630                                Object::DONT_THROW)
2631             .FromJust());
2632 
2633   CHECK(JSObject::SetPrototype(prototype, typed_array_prototype, false,
2634                                Object::DONT_THROW)
2635             .FromJust());
2636   *fun = result;
2637 }
2638 
2639 
InitializeExperimentalGlobal()2640 void Genesis::InitializeExperimentalGlobal() {
2641 #define FEATURE_INITIALIZE_GLOBAL(id, descr) InitializeGlobal_##id();
2642 
2643   HARMONY_INPROGRESS(FEATURE_INITIALIZE_GLOBAL)
2644   HARMONY_STAGED(FEATURE_INITIALIZE_GLOBAL)
2645   HARMONY_SHIPPING(FEATURE_INITIALIZE_GLOBAL)
2646 #undef FEATURE_INITIALIZE_GLOBAL
2647 }
2648 
2649 
CompileBuiltin(Isolate * isolate,int index)2650 bool Bootstrapper::CompileBuiltin(Isolate* isolate, int index) {
2651   Vector<const char> name = Natives::GetScriptName(index);
2652   Handle<String> source_code =
2653       isolate->bootstrapper()->SourceLookup<Natives>(index);
2654 
2655   // We pass in extras_utils so that builtin code can set it up for later use
2656   // by actual extras code, compiled with CompileExtraBuiltin.
2657   Handle<Object> global = isolate->global_object();
2658   Handle<Object> utils = isolate->natives_utils_object();
2659   Handle<Object> extras_utils = isolate->extras_utils_object();
2660   Handle<Object> args[] = {global, utils, extras_utils};
2661 
2662   return Bootstrapper::CompileNative(isolate, name, source_code,
2663                                      arraysize(args), args, NATIVES_CODE);
2664 }
2665 
2666 
CompileExperimentalBuiltin(Isolate * isolate,int index)2667 bool Bootstrapper::CompileExperimentalBuiltin(Isolate* isolate, int index) {
2668   HandleScope scope(isolate);
2669   Vector<const char> name = ExperimentalNatives::GetScriptName(index);
2670   Handle<String> source_code =
2671       isolate->bootstrapper()->SourceLookup<ExperimentalNatives>(index);
2672   Handle<Object> global = isolate->global_object();
2673   Handle<Object> utils = isolate->natives_utils_object();
2674   Handle<Object> args[] = {global, utils};
2675   return Bootstrapper::CompileNative(isolate, name, source_code,
2676                                      arraysize(args), args, NATIVES_CODE);
2677 }
2678 
2679 
CompileExtraBuiltin(Isolate * isolate,int index)2680 bool Bootstrapper::CompileExtraBuiltin(Isolate* isolate, int index) {
2681   HandleScope scope(isolate);
2682   Vector<const char> name = ExtraNatives::GetScriptName(index);
2683   Handle<String> source_code =
2684       isolate->bootstrapper()->SourceLookup<ExtraNatives>(index);
2685   Handle<Object> global = isolate->global_object();
2686   Handle<Object> binding = isolate->extras_binding_object();
2687   Handle<Object> extras_utils = isolate->extras_utils_object();
2688   Handle<Object> args[] = {global, binding, extras_utils};
2689   return Bootstrapper::CompileNative(isolate, name, source_code,
2690                                      arraysize(args), args, EXTENSION_CODE);
2691 }
2692 
2693 
CompileExperimentalExtraBuiltin(Isolate * isolate,int index)2694 bool Bootstrapper::CompileExperimentalExtraBuiltin(Isolate* isolate,
2695                                                    int index) {
2696   HandleScope scope(isolate);
2697   Vector<const char> name = ExperimentalExtraNatives::GetScriptName(index);
2698   Handle<String> source_code =
2699       isolate->bootstrapper()->SourceLookup<ExperimentalExtraNatives>(index);
2700   Handle<Object> global = isolate->global_object();
2701   Handle<Object> binding = isolate->extras_binding_object();
2702   Handle<Object> extras_utils = isolate->extras_utils_object();
2703   Handle<Object> args[] = {global, binding, extras_utils};
2704   return Bootstrapper::CompileNative(isolate, name, source_code,
2705                                      arraysize(args), args, EXTENSION_CODE);
2706 }
2707 
CompileNative(Isolate * isolate,Vector<const char> name,Handle<String> source,int argc,Handle<Object> argv[],NativesFlag natives_flag)2708 bool Bootstrapper::CompileNative(Isolate* isolate, Vector<const char> name,
2709                                  Handle<String> source, int argc,
2710                                  Handle<Object> argv[],
2711                                  NativesFlag natives_flag) {
2712   SuppressDebug compiling_natives(isolate->debug());
2713   // During genesis, the boilerplate for stack overflow won't work until the
2714   // environment has been at least partially initialized. Add a stack check
2715   // before entering JS code to catch overflow early.
2716   StackLimitCheck check(isolate);
2717   if (check.JsHasOverflowed(1 * KB)) {
2718     isolate->StackOverflow();
2719     return false;
2720   }
2721 
2722   Handle<Context> context(isolate->context());
2723 
2724   Handle<String> script_name =
2725       isolate->factory()->NewStringFromUtf8(name).ToHandleChecked();
2726   Handle<SharedFunctionInfo> function_info =
2727       Compiler::GetSharedFunctionInfoForScript(
2728           source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
2729           context, NULL, NULL, ScriptCompiler::kNoCompileOptions, natives_flag,
2730           false);
2731   if (function_info.is_null()) return false;
2732 
2733   DCHECK(context->IsNativeContext());
2734 
2735   Handle<JSFunction> fun =
2736       isolate->factory()->NewFunctionFromSharedFunctionInfo(function_info,
2737                                                             context);
2738   Handle<Object> receiver = isolate->factory()->undefined_value();
2739 
2740   // For non-extension scripts, run script to get the function wrapper.
2741   Handle<Object> wrapper;
2742   if (!Execution::Call(isolate, fun, receiver, 0, NULL).ToHandle(&wrapper)) {
2743     return false;
2744   }
2745   // Then run the function wrapper.
2746   return !Execution::Call(isolate, Handle<JSFunction>::cast(wrapper), receiver,
2747                           argc, argv).is_null();
2748 }
2749 
2750 
CallUtilsFunction(Isolate * isolate,const char * name)2751 bool Genesis::CallUtilsFunction(Isolate* isolate, const char* name) {
2752   Handle<JSObject> utils =
2753       Handle<JSObject>::cast(isolate->natives_utils_object());
2754   Handle<String> name_string =
2755       isolate->factory()->NewStringFromAsciiChecked(name);
2756   Handle<Object> fun = JSObject::GetDataProperty(utils, name_string);
2757   Handle<Object> receiver = isolate->factory()->undefined_value();
2758   Handle<Object> args[] = {utils};
2759   return !Execution::Call(isolate, fun, receiver, 1, args).is_null();
2760 }
2761 
2762 
CompileExtension(Isolate * isolate,v8::Extension * extension)2763 bool Genesis::CompileExtension(Isolate* isolate, v8::Extension* extension) {
2764   Factory* factory = isolate->factory();
2765   HandleScope scope(isolate);
2766   Handle<SharedFunctionInfo> function_info;
2767 
2768   Handle<String> source =
2769       isolate->factory()
2770           ->NewExternalStringFromOneByte(extension->source())
2771           .ToHandleChecked();
2772   DCHECK(source->IsOneByteRepresentation());
2773 
2774   // If we can't find the function in the cache, we compile a new
2775   // function and insert it into the cache.
2776   Vector<const char> name = CStrVector(extension->name());
2777   SourceCodeCache* cache = isolate->bootstrapper()->extensions_cache();
2778   Handle<Context> context(isolate->context());
2779   DCHECK(context->IsNativeContext());
2780 
2781   if (!cache->Lookup(name, &function_info)) {
2782     Handle<String> script_name =
2783         factory->NewStringFromUtf8(name).ToHandleChecked();
2784     function_info = Compiler::GetSharedFunctionInfoForScript(
2785         source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
2786         context, extension, NULL, ScriptCompiler::kNoCompileOptions,
2787         EXTENSION_CODE, false);
2788     if (function_info.is_null()) return false;
2789     cache->Add(name, function_info);
2790   }
2791 
2792   // Set up the function context. Conceptually, we should clone the
2793   // function before overwriting the context but since we're in a
2794   // single-threaded environment it is not strictly necessary.
2795   Handle<JSFunction> fun =
2796       factory->NewFunctionFromSharedFunctionInfo(function_info, context);
2797 
2798   // Call function using either the runtime object or the global
2799   // object as the receiver. Provide no parameters.
2800   Handle<Object> receiver = isolate->global_object();
2801   return !Execution::Call(isolate, fun, receiver, 0, NULL).is_null();
2802 }
2803 
2804 
ResolveBuiltinIdHolder(Handle<Context> native_context,const char * holder_expr)2805 static Handle<JSObject> ResolveBuiltinIdHolder(Handle<Context> native_context,
2806                                                const char* holder_expr) {
2807   Isolate* isolate = native_context->GetIsolate();
2808   Factory* factory = isolate->factory();
2809   Handle<JSGlobalObject> global(native_context->global_object());
2810   const char* period_pos = strchr(holder_expr, '.');
2811   if (period_pos == NULL) {
2812     return Handle<JSObject>::cast(
2813         Object::GetPropertyOrElement(
2814             global, factory->InternalizeUtf8String(holder_expr))
2815             .ToHandleChecked());
2816   }
2817   const char* inner = period_pos + 1;
2818   DCHECK(!strchr(inner, '.'));
2819   Vector<const char> property(holder_expr,
2820                               static_cast<int>(period_pos - holder_expr));
2821   Handle<String> property_string = factory->InternalizeUtf8String(property);
2822   DCHECK(!property_string.is_null());
2823   Handle<JSObject> object = Handle<JSObject>::cast(
2824       JSReceiver::GetProperty(global, property_string).ToHandleChecked());
2825   if (strcmp("prototype", inner) == 0) {
2826     Handle<JSFunction> function = Handle<JSFunction>::cast(object);
2827     return Handle<JSObject>(JSObject::cast(function->prototype()));
2828   }
2829   Handle<String> inner_string = factory->InternalizeUtf8String(inner);
2830   DCHECK(!inner_string.is_null());
2831   Handle<Object> value =
2832       JSReceiver::GetProperty(object, inner_string).ToHandleChecked();
2833   return Handle<JSObject>::cast(value);
2834 }
2835 
ConfigureUtilsObject(GlobalContextType context_type)2836 void Genesis::ConfigureUtilsObject(GlobalContextType context_type) {
2837   switch (context_type) {
2838     // We still need the utils object to find debug functions.
2839     case DEBUG_CONTEXT:
2840       return;
2841     // Expose the natives in global if a valid name for it is specified.
2842     case FULL_CONTEXT: {
2843       // We still need the utils object after deserialization.
2844       if (isolate()->serializer_enabled()) return;
2845       if (FLAG_expose_natives_as == NULL) break;
2846       if (strlen(FLAG_expose_natives_as) == 0) break;
2847       HandleScope scope(isolate());
2848       Handle<String> natives_key =
2849           factory()->InternalizeUtf8String(FLAG_expose_natives_as);
2850       uint32_t dummy_index;
2851       if (natives_key->AsArrayIndex(&dummy_index)) break;
2852       Handle<Object> utils = isolate()->natives_utils_object();
2853       Handle<JSObject> global = isolate()->global_object();
2854       JSObject::AddProperty(global, natives_key, utils, DONT_ENUM);
2855       break;
2856     }
2857   }
2858 
2859   // The utils object can be removed for cases that reach this point.
2860   native_context()->set_natives_utils_object(heap()->undefined_value());
2861 }
2862 
2863 
ExportFromRuntime(Isolate * isolate,Handle<JSObject> container)2864 void Bootstrapper::ExportFromRuntime(Isolate* isolate,
2865                                      Handle<JSObject> container) {
2866   Factory* factory = isolate->factory();
2867   HandleScope scope(isolate);
2868   Handle<Context> native_context = isolate->native_context();
2869 #define EXPORT_PRIVATE_SYMBOL(NAME)                                       \
2870   Handle<String> NAME##_name = factory->NewStringFromAsciiChecked(#NAME); \
2871   JSObject::AddProperty(container, NAME##_name, factory->NAME(), NONE);
2872   PRIVATE_SYMBOL_LIST(EXPORT_PRIVATE_SYMBOL)
2873 #undef EXPORT_PRIVATE_SYMBOL
2874 
2875 #define EXPORT_PUBLIC_SYMBOL(NAME, DESCRIPTION)                           \
2876   Handle<String> NAME##_name = factory->NewStringFromAsciiChecked(#NAME); \
2877   JSObject::AddProperty(container, NAME##_name, factory->NAME(), NONE);
2878   PUBLIC_SYMBOL_LIST(EXPORT_PUBLIC_SYMBOL)
2879   WELL_KNOWN_SYMBOL_LIST(EXPORT_PUBLIC_SYMBOL)
2880 #undef EXPORT_PUBLIC_SYMBOL
2881 
2882   {
2883     Handle<JSFunction> to_string = InstallFunction(
2884         container, "object_to_string", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2885         MaybeHandle<JSObject>(), Builtins::kObjectProtoToString);
2886     to_string->shared()->set_internal_formal_parameter_count(0);
2887     to_string->shared()->set_length(0);
2888     native_context->set_object_to_string(*to_string);
2889   }
2890 
2891   Handle<JSObject> iterator_prototype(
2892       native_context->initial_iterator_prototype());
2893 
2894   JSObject::AddProperty(container,
2895                         factory->InternalizeUtf8String("IteratorPrototype"),
2896                         iterator_prototype, NONE);
2897 
2898   {
2899     PrototypeIterator iter(native_context->sloppy_generator_function_map());
2900     Handle<JSObject> generator_function_prototype(iter.GetCurrent<JSObject>());
2901 
2902     JSObject::AddProperty(
2903         container, factory->InternalizeUtf8String("GeneratorFunctionPrototype"),
2904         generator_function_prototype, NONE);
2905 
2906     static const bool kUseStrictFunctionMap = true;
2907     Handle<JSFunction> generator_function_function = InstallFunction(
2908         container, "GeneratorFunction", JS_FUNCTION_TYPE, JSFunction::kSize,
2909         generator_function_prototype, Builtins::kGeneratorFunctionConstructor,
2910         kUseStrictFunctionMap);
2911     generator_function_function->set_prototype_or_initial_map(
2912         native_context->sloppy_generator_function_map());
2913     generator_function_function->shared()->DontAdaptArguments();
2914     generator_function_function->shared()->SetConstructStub(
2915         *isolate->builtins()->GeneratorFunctionConstructor());
2916     generator_function_function->shared()->set_length(1);
2917     InstallWithIntrinsicDefaultProto(
2918         isolate, generator_function_function,
2919         Context::GENERATOR_FUNCTION_FUNCTION_INDEX);
2920 
2921     JSObject::ForceSetPrototype(generator_function_function,
2922                                 isolate->function_function());
2923     JSObject::AddProperty(
2924         generator_function_prototype, factory->constructor_string(),
2925         generator_function_function,
2926         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2927 
2928     native_context->sloppy_generator_function_map()->SetConstructor(
2929         *generator_function_function);
2930     native_context->strict_generator_function_map()->SetConstructor(
2931         *generator_function_function);
2932   }
2933 
2934   {  // -- F i x e d A r r a y I t e r a t o r
2935     int size = JSFixedArrayIterator::kHeaderSize +
2936                JSFixedArrayIterator::kInObjectPropertyCount * kPointerSize;
2937     Handle<Map> map = factory->NewMap(JS_FIXED_ARRAY_ITERATOR_TYPE, size);
2938     Map::SetPrototype(map, iterator_prototype);
2939     Map::EnsureDescriptorSlack(map,
2940                                JSFixedArrayIterator::kInObjectPropertyCount);
2941     map->SetInObjectProperties(JSFixedArrayIterator::kInObjectPropertyCount);
2942     map->SetConstructor(native_context->object_function());
2943 
2944     {  // next
2945       DataDescriptor d(factory->next_string(), JSFixedArrayIterator::kNextIndex,
2946                        DONT_ENUM, Representation::Tagged());
2947       map->AppendDescriptor(&d);
2948     }
2949 
2950     native_context->set_fixed_array_iterator_map(*map);
2951   }
2952 
2953   {  // -- S e t I t e r a t o r
2954     Handle<JSObject> set_iterator_prototype =
2955         isolate->factory()->NewJSObject(isolate->object_function(), TENURED);
2956     JSObject::ForceSetPrototype(set_iterator_prototype, iterator_prototype);
2957     Handle<JSFunction> set_iterator_function = InstallFunction(
2958         container, "SetIterator", JS_SET_ITERATOR_TYPE, JSSetIterator::kSize,
2959         set_iterator_prototype, Builtins::kIllegal);
2960     native_context->set_set_iterator_map(set_iterator_function->initial_map());
2961   }
2962 
2963   {  // -- M a p I t e r a t o r
2964     Handle<JSObject> map_iterator_prototype =
2965         isolate->factory()->NewJSObject(isolate->object_function(), TENURED);
2966     JSObject::ForceSetPrototype(map_iterator_prototype, iterator_prototype);
2967     Handle<JSFunction> map_iterator_function = InstallFunction(
2968         container, "MapIterator", JS_MAP_ITERATOR_TYPE, JSMapIterator::kSize,
2969         map_iterator_prototype, Builtins::kIllegal);
2970     native_context->set_map_iterator_map(map_iterator_function->initial_map());
2971   }
2972 
2973   {  // -- S c r i p t
2974     // Builtin functions for Script.
2975     Handle<JSFunction> script_fun = InstallFunction(
2976         container, "Script", JS_VALUE_TYPE, JSValue::kSize,
2977         isolate->initial_object_prototype(), Builtins::kUnsupportedThrower);
2978     Handle<JSObject> prototype =
2979         factory->NewJSObject(isolate->object_function(), TENURED);
2980     Accessors::FunctionSetPrototype(script_fun, prototype).Assert();
2981     native_context->set_script_function(*script_fun);
2982 
2983     Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
2984     Map::EnsureDescriptorSlack(script_map, 15);
2985 
2986     PropertyAttributes attribs =
2987         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2988 
2989     Handle<AccessorInfo> script_column =
2990         Accessors::ScriptColumnOffsetInfo(isolate, attribs);
2991     {
2992       AccessorConstantDescriptor d(
2993           Handle<Name>(Name::cast(script_column->name())), script_column,
2994           attribs);
2995       script_map->AppendDescriptor(&d);
2996     }
2997 
2998     Handle<AccessorInfo> script_id = Accessors::ScriptIdInfo(isolate, attribs);
2999     {
3000       AccessorConstantDescriptor d(Handle<Name>(Name::cast(script_id->name())),
3001                                    script_id, attribs);
3002       script_map->AppendDescriptor(&d);
3003     }
3004 
3005 
3006     Handle<AccessorInfo> script_name =
3007         Accessors::ScriptNameInfo(isolate, attribs);
3008     {
3009       AccessorConstantDescriptor d(
3010           Handle<Name>(Name::cast(script_name->name())), script_name, attribs);
3011       script_map->AppendDescriptor(&d);
3012     }
3013 
3014     Handle<AccessorInfo> script_line =
3015         Accessors::ScriptLineOffsetInfo(isolate, attribs);
3016     {
3017       AccessorConstantDescriptor d(
3018           Handle<Name>(Name::cast(script_line->name())), script_line, attribs);
3019       script_map->AppendDescriptor(&d);
3020     }
3021 
3022     Handle<AccessorInfo> script_source =
3023         Accessors::ScriptSourceInfo(isolate, attribs);
3024     {
3025       AccessorConstantDescriptor d(
3026           Handle<Name>(Name::cast(script_source->name())), script_source,
3027           attribs);
3028       script_map->AppendDescriptor(&d);
3029     }
3030 
3031     Handle<AccessorInfo> script_type =
3032         Accessors::ScriptTypeInfo(isolate, attribs);
3033     {
3034       AccessorConstantDescriptor d(
3035           Handle<Name>(Name::cast(script_type->name())), script_type, attribs);
3036       script_map->AppendDescriptor(&d);
3037     }
3038 
3039     Handle<AccessorInfo> script_compilation_type =
3040         Accessors::ScriptCompilationTypeInfo(isolate, attribs);
3041     {
3042       AccessorConstantDescriptor d(
3043           Handle<Name>(Name::cast(script_compilation_type->name())),
3044           script_compilation_type, attribs);
3045       script_map->AppendDescriptor(&d);
3046     }
3047 
3048     Handle<AccessorInfo> script_context_data =
3049         Accessors::ScriptContextDataInfo(isolate, attribs);
3050     {
3051       AccessorConstantDescriptor d(
3052           Handle<Name>(Name::cast(script_context_data->name())),
3053           script_context_data, attribs);
3054       script_map->AppendDescriptor(&d);
3055     }
3056 
3057     Handle<AccessorInfo> script_eval_from_script =
3058         Accessors::ScriptEvalFromScriptInfo(isolate, attribs);
3059     {
3060       AccessorConstantDescriptor d(
3061           Handle<Name>(Name::cast(script_eval_from_script->name())),
3062           script_eval_from_script, attribs);
3063       script_map->AppendDescriptor(&d);
3064     }
3065 
3066     Handle<AccessorInfo> script_eval_from_script_position =
3067         Accessors::ScriptEvalFromScriptPositionInfo(isolate, attribs);
3068     {
3069       AccessorConstantDescriptor d(
3070           Handle<Name>(Name::cast(script_eval_from_script_position->name())),
3071           script_eval_from_script_position, attribs);
3072       script_map->AppendDescriptor(&d);
3073     }
3074 
3075     Handle<AccessorInfo> script_eval_from_function_name =
3076         Accessors::ScriptEvalFromFunctionNameInfo(isolate, attribs);
3077     {
3078       AccessorConstantDescriptor d(
3079           Handle<Name>(Name::cast(script_eval_from_function_name->name())),
3080           script_eval_from_function_name, attribs);
3081       script_map->AppendDescriptor(&d);
3082     }
3083 
3084     Handle<AccessorInfo> script_source_url =
3085         Accessors::ScriptSourceUrlInfo(isolate, attribs);
3086     {
3087       AccessorConstantDescriptor d(
3088           Handle<Name>(Name::cast(script_source_url->name())),
3089           script_source_url, attribs);
3090       script_map->AppendDescriptor(&d);
3091     }
3092 
3093     Handle<AccessorInfo> script_source_mapping_url =
3094         Accessors::ScriptSourceMappingUrlInfo(isolate, attribs);
3095     {
3096       AccessorConstantDescriptor d(
3097           Handle<Name>(Name::cast(script_source_mapping_url->name())),
3098           script_source_mapping_url, attribs);
3099       script_map->AppendDescriptor(&d);
3100     }
3101 
3102     Handle<AccessorInfo> script_is_embedder_debug_script =
3103         Accessors::ScriptIsEmbedderDebugScriptInfo(isolate, attribs);
3104     {
3105       AccessorConstantDescriptor d(
3106           Handle<Name>(Name::cast(script_is_embedder_debug_script->name())),
3107           script_is_embedder_debug_script, attribs);
3108       script_map->AppendDescriptor(&d);
3109     }
3110 
3111     {
3112       PrototypeIterator iter(native_context->sloppy_async_function_map());
3113       Handle<JSObject> async_function_prototype(iter.GetCurrent<JSObject>());
3114 
3115       static const bool kUseStrictFunctionMap = true;
3116       Handle<JSFunction> async_function_constructor = InstallFunction(
3117           container, "AsyncFunction", JS_FUNCTION_TYPE, JSFunction::kSize,
3118           async_function_prototype, Builtins::kAsyncFunctionConstructor,
3119           kUseStrictFunctionMap);
3120       async_function_constructor->shared()->DontAdaptArguments();
3121       async_function_constructor->shared()->SetConstructStub(
3122           *isolate->builtins()->AsyncFunctionConstructor());
3123       async_function_constructor->shared()->set_length(1);
3124       InstallWithIntrinsicDefaultProto(isolate, async_function_constructor,
3125                                        Context::ASYNC_FUNCTION_FUNCTION_INDEX);
3126       JSObject::ForceSetPrototype(async_function_constructor,
3127                                   isolate->function_function());
3128 
3129       JSObject::AddProperty(
3130           async_function_prototype, factory->constructor_string(),
3131           async_function_constructor,
3132           static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
3133 
3134       JSFunction::SetPrototype(async_function_constructor,
3135                                async_function_prototype);
3136 
3137       Handle<JSFunction> async_function_next =
3138           SimpleInstallFunction(container, "AsyncFunctionNext",
3139                                 Builtins::kGeneratorPrototypeNext, 1, true);
3140       Handle<JSFunction> async_function_throw =
3141           SimpleInstallFunction(container, "AsyncFunctionThrow",
3142                                 Builtins::kGeneratorPrototypeThrow, 1, true);
3143       async_function_next->shared()->set_native(false);
3144       async_function_throw->shared()->set_native(false);
3145     }
3146   }
3147 
3148   {  // -- C a l l S i t e
3149     // Builtin functions for CallSite.
3150 
3151     // CallSites are a special case; the constructor is for our private use
3152     // only, therefore we set it up as a builtin that throws. Internally, we use
3153     // CallSiteUtils::Construct to create CallSite objects.
3154 
3155     Handle<JSFunction> callsite_fun = InstallFunction(
3156         container, "CallSite", JS_OBJECT_TYPE, JSObject::kHeaderSize,
3157         isolate->initial_object_prototype(), Builtins::kUnsupportedThrower);
3158     callsite_fun->shared()->DontAdaptArguments();
3159     isolate->native_context()->set_callsite_function(*callsite_fun);
3160 
3161     {
3162       Handle<JSObject> proto =
3163           factory->NewJSObject(isolate->object_function(), TENURED);
3164       JSObject::AddProperty(proto, factory->constructor_string(), callsite_fun,
3165                             DONT_ENUM);
3166 
3167       struct FunctionInfo {
3168         const char* name;
3169         Builtins::Name id;
3170       };
3171 
3172       FunctionInfo infos[] = {
3173           {"getColumnNumber", Builtins::kCallSitePrototypeGetColumnNumber},
3174           {"getEvalOrigin", Builtins::kCallSitePrototypeGetEvalOrigin},
3175           {"getFileName", Builtins::kCallSitePrototypeGetFileName},
3176           {"getFunction", Builtins::kCallSitePrototypeGetFunction},
3177           {"getFunctionName", Builtins::kCallSitePrototypeGetFunctionName},
3178           {"getLineNumber", Builtins::kCallSitePrototypeGetLineNumber},
3179           {"getMethodName", Builtins::kCallSitePrototypeGetMethodName},
3180           {"getPosition", Builtins::kCallSitePrototypeGetPosition},
3181           {"getScriptNameOrSourceURL",
3182            Builtins::kCallSitePrototypeGetScriptNameOrSourceURL},
3183           {"getThis", Builtins::kCallSitePrototypeGetThis},
3184           {"getTypeName", Builtins::kCallSitePrototypeGetTypeName},
3185           {"isConstructor", Builtins::kCallSitePrototypeIsConstructor},
3186           {"isEval", Builtins::kCallSitePrototypeIsEval},
3187           {"isNative", Builtins::kCallSitePrototypeIsNative},
3188           {"isToplevel", Builtins::kCallSitePrototypeIsToplevel},
3189           {"toString", Builtins::kCallSitePrototypeToString}};
3190 
3191       PropertyAttributes attrs =
3192           static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
3193 
3194       Handle<JSFunction> fun;
3195       for (const FunctionInfo& info : infos) {
3196         SimpleInstallFunction(proto, info.name, info.id, 0, true, attrs);
3197       }
3198 
3199       Accessors::FunctionSetPrototype(callsite_fun, proto).Assert();
3200     }
3201   }
3202 }
3203 
3204 
ExportExperimentalFromRuntime(Isolate * isolate,Handle<JSObject> container)3205 void Bootstrapper::ExportExperimentalFromRuntime(Isolate* isolate,
3206                                                  Handle<JSObject> container) {
3207   HandleScope scope(isolate);
3208 
3209 #ifdef V8_I18N_SUPPORT
3210 #define INITIALIZE_FLAG(FLAG)                                         \
3211   {                                                                   \
3212     Handle<String> name =                                             \
3213         isolate->factory()->NewStringFromAsciiChecked(#FLAG);         \
3214     JSObject::AddProperty(container, name,                            \
3215                           isolate->factory()->ToBoolean(FLAG), NONE); \
3216   }
3217 
3218 #undef INITIALIZE_FLAG
3219 #endif
3220 }
3221 
3222 
3223 #define EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(id) \
3224   void Genesis::InitializeGlobal_##id() {}
3225 
3226 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_do_expressions)
EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_regexp_lookbehind)3227 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_regexp_lookbehind)
3228 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_regexp_named_captures)
3229 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_regexp_property)
3230 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_function_sent)
3231 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_tailcalls)
3232 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_string_padding)
3233 #ifdef V8_I18N_SUPPORT
3234 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(datetime_format_to_parts)
3235 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(icu_case_mapping)
3236 #endif
3237 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_async_await)
3238 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_restrictive_generators)
3239 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_trailing_commas)
3240 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_class_fields)
3241 
3242 void InstallPublicSymbol(Factory* factory, Handle<Context> native_context,
3243                          const char* name, Handle<Symbol> value) {
3244   Handle<JSGlobalObject> global(
3245       JSGlobalObject::cast(native_context->global_object()));
3246   Handle<String> symbol_string = factory->InternalizeUtf8String("Symbol");
3247   Handle<JSObject> symbol = Handle<JSObject>::cast(
3248       JSObject::GetProperty(global, symbol_string).ToHandleChecked());
3249   Handle<String> name_string = factory->InternalizeUtf8String(name);
3250   PropertyAttributes attributes =
3251       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
3252   JSObject::AddProperty(symbol, name_string, value, attributes);
3253 }
3254 
3255 
InitializeGlobal_harmony_sharedarraybuffer()3256 void Genesis::InitializeGlobal_harmony_sharedarraybuffer() {
3257   if (!FLAG_harmony_sharedarraybuffer) return;
3258 
3259   Handle<JSGlobalObject> global(native_context()->global_object());
3260   Isolate* isolate = global->GetIsolate();
3261   Factory* factory = isolate->factory();
3262 
3263   Handle<JSFunction> shared_array_buffer_fun =
3264       InstallArrayBuffer(global, "SharedArrayBuffer",
3265                          Builtins::kSharedArrayBufferPrototypeGetByteLength,
3266                          BuiltinFunctionId::kSharedArrayBufferByteLength);
3267   native_context()->set_shared_array_buffer_fun(*shared_array_buffer_fun);
3268 
3269   Handle<String> name = factory->InternalizeUtf8String("Atomics");
3270   Handle<JSFunction> cons = factory->NewFunction(name);
3271   JSFunction::SetInstancePrototype(
3272       cons,
3273       Handle<Object>(native_context()->initial_object_prototype(), isolate));
3274   Handle<JSObject> atomics_object = factory->NewJSObject(cons, TENURED);
3275   DCHECK(atomics_object->IsJSObject());
3276   JSObject::AddProperty(global, name, atomics_object, DONT_ENUM);
3277 
3278   SimpleInstallFunction(atomics_object, factory->InternalizeUtf8String("load"),
3279                         Builtins::kAtomicsLoad, 2, true);
3280   SimpleInstallFunction(atomics_object, factory->InternalizeUtf8String("store"),
3281                         Builtins::kAtomicsStore, 3, true);
3282 }
3283 
3284 
InitializeGlobal_harmony_simd()3285 void Genesis::InitializeGlobal_harmony_simd() {
3286   if (!FLAG_harmony_simd) return;
3287 
3288   Handle<JSGlobalObject> global(
3289       JSGlobalObject::cast(native_context()->global_object()));
3290   Isolate* isolate = global->GetIsolate();
3291   Factory* factory = isolate->factory();
3292 
3293   Handle<String> name = factory->InternalizeUtf8String("SIMD");
3294   Handle<JSFunction> cons = factory->NewFunction(name);
3295   JSFunction::SetInstancePrototype(
3296       cons,
3297       Handle<Object>(native_context()->initial_object_prototype(), isolate));
3298   cons->shared()->set_instance_class_name(*name);
3299   Handle<JSObject> simd_object = factory->NewJSObject(cons, TENURED);
3300   DCHECK(simd_object->IsJSObject());
3301   JSObject::AddProperty(global, name, simd_object, DONT_ENUM);
3302 
3303 // Install SIMD type functions. Set the instance class names since
3304 // InstallFunction only does this when we install on the JSGlobalObject.
3305 #define SIMD128_INSTALL_FUNCTION(TYPE, Type, type, lane_count, lane_type) \
3306   Handle<JSFunction> type##_function = InstallFunction(                   \
3307       simd_object, #Type, JS_VALUE_TYPE, JSValue::kSize,                  \
3308       isolate->initial_object_prototype(), Builtins::kIllegal);           \
3309   native_context()->set_##type##_function(*type##_function);              \
3310   type##_function->shared()->set_instance_class_name(*factory->Type##_string());
3311   SIMD128_TYPES(SIMD128_INSTALL_FUNCTION)
3312 #undef SIMD128_INSTALL_FUNCTION
3313 }
3314 
3315 
InitializeGlobal_harmony_array_prototype_values()3316 void Genesis::InitializeGlobal_harmony_array_prototype_values() {
3317   if (!FLAG_harmony_array_prototype_values) return;
3318   Handle<JSFunction> array_constructor(native_context()->array_function());
3319   Handle<JSObject> array_prototype(
3320       JSObject::cast(array_constructor->instance_prototype()));
3321   Handle<Object> values_iterator =
3322       JSObject::GetProperty(array_prototype, factory()->iterator_symbol())
3323           .ToHandleChecked();
3324   DCHECK(values_iterator->IsJSFunction());
3325   JSObject::AddProperty(array_prototype, factory()->values_string(),
3326                         values_iterator, DONT_ENUM);
3327 
3328   Handle<Object> unscopables =
3329       JSObject::GetProperty(array_prototype, factory()->unscopables_symbol())
3330           .ToHandleChecked();
3331   DCHECK(unscopables->IsJSObject());
3332   JSObject::AddProperty(Handle<JSObject>::cast(unscopables),
3333                         factory()->values_string(), factory()->true_value(),
3334                         NONE);
3335 }
3336 
InstallArrayBuffer(Handle<JSObject> target,const char * name,Builtins::Name call,BuiltinFunctionId id)3337 Handle<JSFunction> Genesis::InstallArrayBuffer(Handle<JSObject> target,
3338                                                const char* name,
3339                                                Builtins::Name call,
3340                                                BuiltinFunctionId id) {
3341   // Create the %ArrayBufferPrototype%
3342   // Setup the {prototype} with the given {name} for @@toStringTag.
3343   Handle<JSObject> prototype =
3344       factory()->NewJSObject(isolate()->object_function(), TENURED);
3345   JSObject::AddProperty(prototype, factory()->to_string_tag_symbol(),
3346                         factory()->NewStringFromAsciiChecked(name),
3347                         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
3348 
3349   // Allocate the constructor with the given {prototype}.
3350   Handle<JSFunction> array_buffer_fun =
3351       InstallFunction(target, name, JS_ARRAY_BUFFER_TYPE,
3352                       JSArrayBuffer::kSizeWithInternalFields, prototype,
3353                       Builtins::kArrayBufferConstructor);
3354   array_buffer_fun->shared()->SetConstructStub(
3355       *isolate()->builtins()->ArrayBufferConstructor_ConstructStub());
3356   array_buffer_fun->shared()->DontAdaptArguments();
3357   array_buffer_fun->shared()->set_length(1);
3358 
3359   // Install the "constructor" property on the {prototype}.
3360   JSObject::AddProperty(prototype, factory()->constructor_string(),
3361                         array_buffer_fun, DONT_ENUM);
3362 
3363   SimpleInstallFunction(array_buffer_fun, factory()->isView_string(),
3364                         Builtins::kArrayBufferIsView, 1, true);
3365 
3366   // Install the "byteLength" getter on the {prototype}.
3367   SimpleInstallGetter(prototype, factory()->byte_length_string(), call, false,
3368                       id);
3369 
3370   return array_buffer_fun;
3371 }
3372 
3373 
InstallInternalArray(Handle<JSObject> target,const char * name,ElementsKind elements_kind)3374 Handle<JSFunction> Genesis::InstallInternalArray(Handle<JSObject> target,
3375                                                  const char* name,
3376                                                  ElementsKind elements_kind) {
3377   // --- I n t e r n a l   A r r a y ---
3378   // An array constructor on the builtins object that works like
3379   // the public Array constructor, except that its prototype
3380   // doesn't inherit from Object.prototype.
3381   // To be used only for internal work by builtins. Instances
3382   // must not be leaked to user code.
3383   Handle<JSObject> prototype =
3384       factory()->NewJSObject(isolate()->object_function(), TENURED);
3385   Handle<JSFunction> array_function =
3386       InstallFunction(target, name, JS_ARRAY_TYPE, JSArray::kSize, prototype,
3387                       Builtins::kInternalArrayCode);
3388 
3389   InternalArrayConstructorStub internal_array_constructor_stub(isolate());
3390   Handle<Code> code = internal_array_constructor_stub.GetCode();
3391   array_function->shared()->SetConstructStub(*code);
3392   array_function->shared()->DontAdaptArguments();
3393 
3394   Handle<Map> original_map(array_function->initial_map());
3395   Handle<Map> initial_map = Map::Copy(original_map, "InternalArray");
3396   initial_map->set_elements_kind(elements_kind);
3397   JSFunction::SetInitialMap(array_function, initial_map, prototype);
3398 
3399   // Make "length" magic on instances.
3400   Map::EnsureDescriptorSlack(initial_map, 1);
3401 
3402   PropertyAttributes attribs = static_cast<PropertyAttributes>(
3403       DONT_ENUM | DONT_DELETE);
3404 
3405   Handle<AccessorInfo> array_length =
3406       Accessors::ArrayLengthInfo(isolate(), attribs);
3407   {  // Add length.
3408     AccessorConstantDescriptor d(Handle<Name>(Name::cast(array_length->name())),
3409                                  array_length, attribs);
3410     initial_map->AppendDescriptor(&d);
3411   }
3412 
3413   return array_function;
3414 }
3415 
InstallNatives(GlobalContextType context_type)3416 bool Genesis::InstallNatives(GlobalContextType context_type) {
3417   HandleScope scope(isolate());
3418 
3419   // Set up the utils object as shared container between native scripts.
3420   Handle<JSObject> utils = factory()->NewJSObject(isolate()->object_function());
3421   JSObject::NormalizeProperties(utils, CLEAR_INOBJECT_PROPERTIES, 16,
3422                                 "utils container for native scripts");
3423   native_context()->set_natives_utils_object(*utils);
3424 
3425   // Set up the extras utils object as a shared container between native
3426   // scripts and extras. (Extras consume things added there by native scripts.)
3427   Handle<JSObject> extras_utils =
3428       factory()->NewJSObject(isolate()->object_function());
3429   native_context()->set_extras_utils_object(*extras_utils);
3430 
3431   InstallInternalArray(extras_utils, "InternalPackedArray", FAST_ELEMENTS);
3432 
3433   int builtin_index = Natives::GetDebuggerCount();
3434   // Only run prologue.js and runtime.js at this point.
3435   DCHECK_EQ(builtin_index, Natives::GetIndex("prologue"));
3436   if (!Bootstrapper::CompileBuiltin(isolate(), builtin_index++)) return false;
3437   DCHECK_EQ(builtin_index, Natives::GetIndex("runtime"));
3438   if (!Bootstrapper::CompileBuiltin(isolate(), builtin_index++)) return false;
3439 
3440   {
3441     // Builtin function for OpaqueReference -- a JSValue-based object,
3442     // that keeps its field isolated from JavaScript code. It may store
3443     // objects, that JavaScript code may not access.
3444     Handle<JSFunction> opaque_reference_fun = factory()->NewFunction(
3445         factory()->empty_string(), isolate()->builtins()->Illegal(),
3446         isolate()->initial_object_prototype(), JS_VALUE_TYPE, JSValue::kSize);
3447     Handle<JSObject> prototype =
3448         factory()->NewJSObject(isolate()->object_function(), TENURED);
3449     Accessors::FunctionSetPrototype(opaque_reference_fun, prototype).Assert();
3450     native_context()->set_opaque_reference_function(*opaque_reference_fun);
3451   }
3452 
3453   // InternalArrays should not use Smi-Only array optimizations. There are too
3454   // many places in the C++ runtime code (e.g. RegEx) that assume that
3455   // elements in InternalArrays can be set to non-Smi values without going
3456   // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
3457   // transition easy to trap. Moreover, they rarely are smi-only.
3458   {
3459     HandleScope scope(isolate());
3460     Handle<JSObject> utils =
3461         Handle<JSObject>::cast(isolate()->natives_utils_object());
3462     Handle<JSFunction> array_function =
3463         InstallInternalArray(utils, "InternalArray", FAST_HOLEY_ELEMENTS);
3464     native_context()->set_internal_array_function(*array_function);
3465     InstallInternalArray(utils, "InternalPackedArray", FAST_ELEMENTS);
3466   }
3467 
3468   // Run the rest of the native scripts.
3469   while (builtin_index < Natives::GetBuiltinsCount()) {
3470     if (!Bootstrapper::CompileBuiltin(isolate(), builtin_index++)) return false;
3471   }
3472 
3473   if (!CallUtilsFunction(isolate(), "PostNatives")) return false;
3474   auto fast_template_instantiations_cache = isolate()->factory()->NewFixedArray(
3475       TemplateInfo::kFastTemplateInstantiationsCacheSize);
3476   native_context()->set_fast_template_instantiations_cache(
3477       *fast_template_instantiations_cache);
3478 
3479   auto slow_template_instantiations_cache = UnseededNumberDictionary::New(
3480       isolate(), ApiNatives::kInitialFunctionCacheSize);
3481   native_context()->set_slow_template_instantiations_cache(
3482       *slow_template_instantiations_cache);
3483 
3484   // Store the map for the %ObjectPrototype% after the natives has been compiled
3485   // and the Object function has been set up.
3486   Handle<JSFunction> object_function(native_context()->object_function());
3487   DCHECK(JSObject::cast(object_function->initial_map()->prototype())
3488              ->HasFastProperties());
3489   native_context()->set_object_function_prototype_map(
3490       HeapObject::cast(object_function->initial_map()->prototype())->map());
3491 
3492   // Set up the map for Object.create(null) instances.
3493   Handle<Map> slow_object_with_null_prototype_map =
3494       Map::CopyInitialMap(handle(object_function->initial_map(), isolate()));
3495   slow_object_with_null_prototype_map->set_dictionary_map(true);
3496   Map::SetPrototype(slow_object_with_null_prototype_map,
3497                     isolate()->factory()->null_value());
3498   native_context()->set_slow_object_with_null_prototype_map(
3499       *slow_object_with_null_prototype_map);
3500 
3501   // Store the map for the %StringPrototype% after the natives has been compiled
3502   // and the String function has been set up.
3503   Handle<JSFunction> string_function(native_context()->string_function());
3504   DCHECK(JSObject::cast(
3505       string_function->initial_map()->prototype())->HasFastProperties());
3506   native_context()->set_string_function_prototype_map(
3507       HeapObject::cast(string_function->initial_map()->prototype())->map());
3508 
3509   Handle<JSGlobalObject> global_object =
3510       handle(native_context()->global_object());
3511 
3512   // Install Global.decodeURI.
3513   SimpleInstallFunction(global_object, "decodeURI", Builtins::kGlobalDecodeURI,
3514                         1, false, kGlobalDecodeURI);
3515 
3516   // Install Global.decodeURIComponent.
3517   SimpleInstallFunction(global_object, "decodeURIComponent",
3518                         Builtins::kGlobalDecodeURIComponent, 1, false,
3519                         kGlobalDecodeURIComponent);
3520 
3521   // Install Global.encodeURI.
3522   SimpleInstallFunction(global_object, "encodeURI", Builtins::kGlobalEncodeURI,
3523                         1, false, kGlobalEncodeURI);
3524 
3525   // Install Global.encodeURIComponent.
3526   SimpleInstallFunction(global_object, "encodeURIComponent",
3527                         Builtins::kGlobalEncodeURIComponent, 1, false,
3528                         kGlobalEncodeURIComponent);
3529 
3530   // Install Global.escape.
3531   SimpleInstallFunction(global_object, "escape", Builtins::kGlobalEscape, 1,
3532                         false, kGlobalEscape);
3533 
3534   // Install Global.unescape.
3535   SimpleInstallFunction(global_object, "unescape", Builtins::kGlobalUnescape, 1,
3536                         false, kGlobalUnescape);
3537 
3538   // Install Global.eval.
3539   {
3540     Handle<JSFunction> eval =
3541         SimpleInstallFunction(global_object, factory()->eval_string(),
3542                               Builtins::kGlobalEval, 1, false);
3543     native_context()->set_global_eval_fun(*eval);
3544   }
3545 
3546   // Install Global.isFinite
3547   SimpleInstallFunction(global_object, "isFinite", Builtins::kGlobalIsFinite, 1,
3548                         true, kGlobalIsFinite);
3549 
3550   // Install Global.isNaN
3551   SimpleInstallFunction(global_object, "isNaN", Builtins::kGlobalIsNaN, 1, true,
3552                         kGlobalIsNaN);
3553 
3554   // Install Array.prototype.concat
3555   {
3556     Handle<JSFunction> array_constructor(native_context()->array_function());
3557     Handle<JSObject> proto(JSObject::cast(array_constructor->prototype()));
3558     Handle<JSFunction> concat =
3559         InstallFunction(proto, "concat", JS_OBJECT_TYPE, JSObject::kHeaderSize,
3560                         MaybeHandle<JSObject>(), Builtins::kArrayConcat);
3561 
3562     // Make sure that Array.prototype.concat appears to be compiled.
3563     // The code will never be called, but inline caching for call will
3564     // only work if it appears to be compiled.
3565     concat->shared()->DontAdaptArguments();
3566     DCHECK(concat->is_compiled());
3567     // Set the lengths for the functions to satisfy ECMA-262.
3568     concat->shared()->set_length(1);
3569   }
3570 
3571   // Install InternalArray.prototype.concat
3572   {
3573     Handle<JSFunction> array_constructor(
3574         native_context()->internal_array_function());
3575     Handle<JSObject> proto(JSObject::cast(array_constructor->prototype()));
3576     Handle<JSFunction> concat =
3577         InstallFunction(proto, "concat", JS_OBJECT_TYPE, JSObject::kHeaderSize,
3578                         MaybeHandle<JSObject>(), Builtins::kArrayConcat);
3579 
3580     // Make sure that InternalArray.prototype.concat appears to be compiled.
3581     // The code will never be called, but inline caching for call will
3582     // only work if it appears to be compiled.
3583     concat->shared()->DontAdaptArguments();
3584     DCHECK(concat->is_compiled());
3585     // Set the lengths for the functions to satisfy ECMA-262.
3586     concat->shared()->set_length(1);
3587   }
3588 
3589   // Set up the Promise constructor.
3590   {
3591     Handle<String> key = factory()->Promise_string();
3592     Handle<JSFunction> function = Handle<JSFunction>::cast(
3593         JSReceiver::GetProperty(global_object, key).ToHandleChecked());
3594     JSFunction::EnsureHasInitialMap(function);
3595     function->initial_map()->set_instance_type(JS_PROMISE_TYPE);
3596     function->shared()->SetConstructStub(
3597         *isolate()->builtins()->JSBuiltinsConstructStub());
3598     InstallWithIntrinsicDefaultProto(isolate(), function,
3599                                      Context::PROMISE_FUNCTION_INDEX);
3600 
3601     {
3602       Handle<Code> code = handle(
3603           isolate()->builtins()->builtin(Builtins::kPromiseResolveClosure),
3604           isolate());
3605       Handle<SharedFunctionInfo> info =
3606           isolate()->factory()->NewSharedFunctionInfo(factory()->empty_string(),
3607                                                       code, false);
3608       info->set_internal_formal_parameter_count(1);
3609       info->set_length(1);
3610       native_context()->set_promise_resolve_shared_fun(*info);
3611 
3612       code = handle(
3613           isolate()->builtins()->builtin(Builtins::kPromiseRejectClosure),
3614           isolate());
3615       info = isolate()->factory()->NewSharedFunctionInfo(
3616           factory()->empty_string(), code, false);
3617       info->set_internal_formal_parameter_count(2);
3618       info->set_length(1);
3619       native_context()->set_promise_reject_shared_fun(*info);
3620     }
3621 
3622     Handle<JSFunction> create_resolving_functions =
3623         SimpleCreateFunction(isolate(), factory()->empty_string(),
3624                              Builtins::kCreateResolvingFunctions, 2, false);
3625     native_context()->set_create_resolving_functions(
3626         *create_resolving_functions);
3627   }
3628 
3629   InstallBuiltinFunctionIds();
3630 
3631   // Create a map for accessor property descriptors (a variant of JSObject
3632   // that predefines four properties get, set, configurable and enumerable).
3633   {
3634     // AccessorPropertyDescriptor initial map.
3635     Handle<Map> map =
3636         factory()->NewMap(JS_OBJECT_TYPE, JSAccessorPropertyDescriptor::kSize);
3637     // Create the descriptor array for the property descriptor object.
3638     Map::EnsureDescriptorSlack(map, 4);
3639 
3640     {  // get
3641       DataDescriptor d(factory()->get_string(),
3642                        JSAccessorPropertyDescriptor::kGetIndex, NONE,
3643                        Representation::Tagged());
3644       map->AppendDescriptor(&d);
3645     }
3646     {  // set
3647       DataDescriptor d(factory()->set_string(),
3648                        JSAccessorPropertyDescriptor::kSetIndex, NONE,
3649                        Representation::Tagged());
3650       map->AppendDescriptor(&d);
3651     }
3652     {  // enumerable
3653       DataDescriptor d(factory()->enumerable_string(),
3654                        JSAccessorPropertyDescriptor::kEnumerableIndex, NONE,
3655                        Representation::Tagged());
3656       map->AppendDescriptor(&d);
3657     }
3658     {  // configurable
3659       DataDescriptor d(factory()->configurable_string(),
3660                        JSAccessorPropertyDescriptor::kConfigurableIndex, NONE,
3661                        Representation::Tagged());
3662       map->AppendDescriptor(&d);
3663     }
3664 
3665     Map::SetPrototype(map, isolate()->initial_object_prototype());
3666     map->SetConstructor(native_context()->object_function());
3667     map->SetInObjectProperties(4);
3668     map->set_unused_property_fields(0);
3669 
3670     native_context()->set_accessor_property_descriptor_map(*map);
3671   }
3672 
3673   // Create a map for data property descriptors (a variant of JSObject
3674   // that predefines four properties value, writable, configurable and
3675   // enumerable).
3676   {
3677     // DataPropertyDescriptor initial map.
3678     Handle<Map> map =
3679         factory()->NewMap(JS_OBJECT_TYPE, JSDataPropertyDescriptor::kSize);
3680     // Create the descriptor array for the property descriptor object.
3681     Map::EnsureDescriptorSlack(map, 4);
3682 
3683     {  // value
3684       DataDescriptor d(factory()->value_string(),
3685                        JSDataPropertyDescriptor::kValueIndex, NONE,
3686                        Representation::Tagged());
3687       map->AppendDescriptor(&d);
3688     }
3689     {  // writable
3690       DataDescriptor d(factory()->writable_string(),
3691                        JSDataPropertyDescriptor::kWritableIndex, NONE,
3692                        Representation::Tagged());
3693       map->AppendDescriptor(&d);
3694     }
3695     {  // enumerable
3696       DataDescriptor d(factory()->enumerable_string(),
3697                        JSDataPropertyDescriptor::kEnumerableIndex, NONE,
3698                        Representation::Tagged());
3699       map->AppendDescriptor(&d);
3700     }
3701     {  // configurable
3702       DataDescriptor d(factory()->configurable_string(),
3703                        JSDataPropertyDescriptor::kConfigurableIndex, NONE,
3704                        Representation::Tagged());
3705       map->AppendDescriptor(&d);
3706     }
3707 
3708     Map::SetPrototype(map, isolate()->initial_object_prototype());
3709     map->SetConstructor(native_context()->object_function());
3710     map->SetInObjectProperties(4);
3711     map->set_unused_property_fields(0);
3712 
3713     native_context()->set_data_property_descriptor_map(*map);
3714   }
3715 
3716   // Create a constructor for RegExp results (a variant of Array that
3717   // predefines the two properties index and match).
3718   {
3719     // RegExpResult initial map.
3720 
3721     // Find global.Array.prototype to inherit from.
3722     Handle<JSFunction> array_constructor(native_context()->array_function());
3723     Handle<JSObject> array_prototype(
3724         JSObject::cast(array_constructor->instance_prototype()));
3725 
3726     // Add initial map.
3727     Handle<Map> initial_map =
3728         factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
3729     initial_map->SetConstructor(*array_constructor);
3730 
3731     // Set prototype on map.
3732     initial_map->set_non_instance_prototype(false);
3733     Map::SetPrototype(initial_map, array_prototype);
3734 
3735     // Update map with length accessor from Array and add "index" and "input".
3736     Map::EnsureDescriptorSlack(initial_map, 3);
3737 
3738     {
3739       JSFunction* array_function = native_context()->array_function();
3740       Handle<DescriptorArray> array_descriptors(
3741           array_function->initial_map()->instance_descriptors());
3742       Handle<String> length = factory()->length_string();
3743       int old = array_descriptors->SearchWithCache(
3744           isolate(), *length, array_function->initial_map());
3745       DCHECK(old != DescriptorArray::kNotFound);
3746       AccessorConstantDescriptor desc(
3747           length, handle(array_descriptors->GetValue(old), isolate()),
3748           array_descriptors->GetDetails(old).attributes());
3749       initial_map->AppendDescriptor(&desc);
3750     }
3751     {
3752       DataDescriptor index_field(factory()->index_string(),
3753                                  JSRegExpResult::kIndexIndex, NONE,
3754                                  Representation::Tagged());
3755       initial_map->AppendDescriptor(&index_field);
3756     }
3757 
3758     {
3759       DataDescriptor input_field(factory()->input_string(),
3760                                  JSRegExpResult::kInputIndex, NONE,
3761                                  Representation::Tagged());
3762       initial_map->AppendDescriptor(&input_field);
3763     }
3764 
3765     initial_map->SetInObjectProperties(2);
3766     initial_map->set_unused_property_fields(0);
3767 
3768     native_context()->set_regexp_result_map(*initial_map);
3769   }
3770 
3771   // Add @@iterator method to the arguments object maps.
3772   {
3773     PropertyAttributes attribs = DONT_ENUM;
3774     Handle<AccessorInfo> arguments_iterator =
3775         Accessors::ArgumentsIteratorInfo(isolate(), attribs);
3776     {
3777       AccessorConstantDescriptor d(factory()->iterator_symbol(),
3778                                    arguments_iterator, attribs);
3779       Handle<Map> map(native_context()->sloppy_arguments_map());
3780       Map::EnsureDescriptorSlack(map, 1);
3781       map->AppendDescriptor(&d);
3782     }
3783     {
3784       AccessorConstantDescriptor d(factory()->iterator_symbol(),
3785                                    arguments_iterator, attribs);
3786       Handle<Map> map(native_context()->fast_aliased_arguments_map());
3787       Map::EnsureDescriptorSlack(map, 1);
3788       map->AppendDescriptor(&d);
3789     }
3790     {
3791       AccessorConstantDescriptor d(factory()->iterator_symbol(),
3792                                    arguments_iterator, attribs);
3793       Handle<Map> map(native_context()->slow_aliased_arguments_map());
3794       Map::EnsureDescriptorSlack(map, 1);
3795       map->AppendDescriptor(&d);
3796     }
3797     {
3798       AccessorConstantDescriptor d(factory()->iterator_symbol(),
3799                                    arguments_iterator, attribs);
3800       Handle<Map> map(native_context()->strict_arguments_map());
3801       Map::EnsureDescriptorSlack(map, 1);
3802       map->AppendDescriptor(&d);
3803     }
3804   }
3805 
3806   return true;
3807 }
3808 
3809 
InstallExperimentalNatives()3810 bool Genesis::InstallExperimentalNatives() {
3811   static const char* harmony_tailcalls_natives[] = {nullptr};
3812   static const char* harmony_sharedarraybuffer_natives[] = {
3813       "native harmony-atomics.js", NULL};
3814   static const char* harmony_simd_natives[] = {"native harmony-simd.js",
3815                                                nullptr};
3816   static const char* harmony_do_expressions_natives[] = {nullptr};
3817   static const char* harmony_regexp_lookbehind_natives[] = {nullptr};
3818   static const char* harmony_regexp_named_captures_natives[] = {nullptr};
3819   static const char* harmony_regexp_property_natives[] = {nullptr};
3820   static const char* harmony_function_sent_natives[] = {nullptr};
3821   static const char* harmony_array_prototype_values_natives[] = {nullptr};
3822   static const char* harmony_string_padding_natives[] = {
3823       "native harmony-string-padding.js", nullptr};
3824 #ifdef V8_I18N_SUPPORT
3825   static const char* icu_case_mapping_natives[] = {"native icu-case-mapping.js",
3826                                                    nullptr};
3827   static const char* datetime_format_to_parts_natives[] = {
3828       "native datetime-format-to-parts.js", nullptr};
3829 #endif
3830   static const char* harmony_async_await_natives[] = {nullptr};
3831   static const char* harmony_restrictive_generators_natives[] = {nullptr};
3832   static const char* harmony_trailing_commas_natives[] = {nullptr};
3833   static const char* harmony_class_fields_natives[] = {nullptr};
3834 
3835   for (int i = ExperimentalNatives::GetDebuggerCount();
3836        i < ExperimentalNatives::GetBuiltinsCount(); i++) {
3837 #define INSTALL_EXPERIMENTAL_NATIVES(id, desc)                                \
3838   if (FLAG_##id) {                                                            \
3839     for (size_t j = 0; id##_natives[j] != NULL; j++) {                        \
3840       Vector<const char> script_name = ExperimentalNatives::GetScriptName(i); \
3841       if (strncmp(script_name.start(), id##_natives[j],                       \
3842                   script_name.length()) == 0) {                               \
3843         if (!Bootstrapper::CompileExperimentalBuiltin(isolate(), i)) {        \
3844           return false;                                                       \
3845         }                                                                     \
3846       }                                                                       \
3847     }                                                                         \
3848   }
3849     HARMONY_INPROGRESS(INSTALL_EXPERIMENTAL_NATIVES);
3850     HARMONY_STAGED(INSTALL_EXPERIMENTAL_NATIVES);
3851     HARMONY_SHIPPING(INSTALL_EXPERIMENTAL_NATIVES);
3852 #undef INSTALL_EXPERIMENTAL_NATIVES
3853   }
3854 
3855   if (!CallUtilsFunction(isolate(), "PostExperimentals")) return false;
3856 
3857   InstallExperimentalBuiltinFunctionIds();
3858   return true;
3859 }
3860 
3861 
InstallExtraNatives()3862 bool Genesis::InstallExtraNatives() {
3863   HandleScope scope(isolate());
3864 
3865   Handle<JSObject> extras_binding =
3866       factory()->NewJSObject(isolate()->object_function());
3867   native_context()->set_extras_binding_object(*extras_binding);
3868 
3869   for (int i = ExtraNatives::GetDebuggerCount();
3870        i < ExtraNatives::GetBuiltinsCount(); i++) {
3871     if (!Bootstrapper::CompileExtraBuiltin(isolate(), i)) return false;
3872   }
3873 
3874   return true;
3875 }
3876 
3877 
InstallExperimentalExtraNatives()3878 bool Genesis::InstallExperimentalExtraNatives() {
3879   for (int i = ExperimentalExtraNatives::GetDebuggerCount();
3880        i < ExperimentalExtraNatives::GetBuiltinsCount(); i++) {
3881     if (!Bootstrapper::CompileExperimentalExtraBuiltin(isolate(), i))
3882       return false;
3883   }
3884 
3885   return true;
3886 }
3887 
3888 
InstallDebuggerNatives()3889 bool Genesis::InstallDebuggerNatives() {
3890   for (int i = 0; i < Natives::GetDebuggerCount(); ++i) {
3891     if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
3892   }
3893   return CallUtilsFunction(isolate(), "PostDebug");
3894 }
3895 
3896 
InstallBuiltinFunctionId(Handle<JSObject> holder,const char * function_name,BuiltinFunctionId id)3897 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
3898                                      const char* function_name,
3899                                      BuiltinFunctionId id) {
3900   Isolate* isolate = holder->GetIsolate();
3901   Handle<Object> function_object =
3902       JSReceiver::GetProperty(isolate, holder, function_name).ToHandleChecked();
3903   Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
3904   function->shared()->set_builtin_function_id(id);
3905 }
3906 
3907 
3908 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
3909   { #holder_expr, #fun_name, k##name }                  \
3910   ,
3911 
3912 
InstallBuiltinFunctionIds()3913 void Genesis::InstallBuiltinFunctionIds() {
3914   HandleScope scope(isolate());
3915   struct BuiltinFunctionIds {
3916     const char* holder_expr;
3917     const char* fun_name;
3918     BuiltinFunctionId id;
3919   };
3920 
3921   const BuiltinFunctionIds builtins[] = {
3922       FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
3923 
3924   for (const BuiltinFunctionIds& builtin : builtins) {
3925     Handle<JSObject> holder =
3926         ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
3927     InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
3928   }
3929 }
3930 
3931 
InstallExperimentalBuiltinFunctionIds()3932 void Genesis::InstallExperimentalBuiltinFunctionIds() {
3933   if (FLAG_harmony_sharedarraybuffer) {
3934     struct BuiltinFunctionIds {
3935       const char* holder_expr;
3936       const char* fun_name;
3937       BuiltinFunctionId id;
3938     };
3939 
3940     const BuiltinFunctionIds atomic_builtins[] = {
3941         ATOMIC_FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
3942 
3943     for (const BuiltinFunctionIds& builtin : atomic_builtins) {
3944       Handle<JSObject> holder =
3945           ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
3946       InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
3947     }
3948   }
3949 }
3950 
3951 
3952 #undef INSTALL_BUILTIN_ID
3953 
3954 
InitializeNormalizedMapCaches()3955 void Genesis::InitializeNormalizedMapCaches() {
3956   Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
3957   native_context()->set_normalized_map_cache(*cache);
3958 }
3959 
3960 
InstallExtensions(Handle<Context> native_context,v8::ExtensionConfiguration * extensions)3961 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
3962                                      v8::ExtensionConfiguration* extensions) {
3963   BootstrapperActive active(this);
3964   SaveContext saved_context(isolate_);
3965   isolate_->set_context(*native_context);
3966   return Genesis::InstallExtensions(native_context, extensions) &&
3967       Genesis::InstallSpecialObjects(native_context);
3968 }
3969 
3970 
InstallSpecialObjects(Handle<Context> native_context)3971 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
3972   Isolate* isolate = native_context->GetIsolate();
3973   // Don't install extensions into the snapshot.
3974   if (isolate->serializer_enabled()) return true;
3975 
3976   Factory* factory = isolate->factory();
3977   HandleScope scope(isolate);
3978   Handle<JSGlobalObject> global(JSGlobalObject::cast(
3979       native_context->global_object()));
3980 
3981   Handle<JSObject> Error = isolate->error_function();
3982   Handle<String> name =
3983       factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("stackTraceLimit"));
3984   Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit), isolate);
3985   JSObject::AddProperty(Error, name, stack_trace_limit, NONE);
3986 
3987   // Expose the debug global object in global if a name for it is specified.
3988   if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
3989     // If loading fails we just bail out without installing the
3990     // debugger but without tanking the whole context.
3991     Debug* debug = isolate->debug();
3992     if (!debug->Load()) return true;
3993     Handle<Context> debug_context = debug->debug_context();
3994     // Set the security token for the debugger context to the same as
3995     // the shell native context to allow calling between these (otherwise
3996     // exposing debug global object doesn't make much sense).
3997     debug_context->set_security_token(native_context->security_token());
3998     Handle<String> debug_string =
3999         factory->InternalizeUtf8String(FLAG_expose_debug_as);
4000     uint32_t index;
4001     if (debug_string->AsArrayIndex(&index)) return true;
4002     Handle<Object> global_proxy(debug_context->global_proxy(), isolate);
4003     JSObject::AddProperty(global, debug_string, global_proxy, DONT_ENUM);
4004   }
4005 
4006   WasmJs::Install(isolate, global);
4007 
4008   return true;
4009 }
4010 
4011 
Hash(RegisteredExtension * extension)4012 static uint32_t Hash(RegisteredExtension* extension) {
4013   return v8::internal::ComputePointerHash(extension);
4014 }
4015 
ExtensionStates()4016 Genesis::ExtensionStates::ExtensionStates() : map_(8) {}
4017 
get_state(RegisteredExtension * extension)4018 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
4019     RegisteredExtension* extension) {
4020   base::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension));
4021   if (entry == NULL) {
4022     return UNVISITED;
4023   }
4024   return static_cast<ExtensionTraversalState>(
4025       reinterpret_cast<intptr_t>(entry->value));
4026 }
4027 
set_state(RegisteredExtension * extension,ExtensionTraversalState state)4028 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
4029                                          ExtensionTraversalState state) {
4030   map_.LookupOrInsert(extension, Hash(extension))->value =
4031       reinterpret_cast<void*>(static_cast<intptr_t>(state));
4032 }
4033 
4034 
InstallExtensions(Handle<Context> native_context,v8::ExtensionConfiguration * extensions)4035 bool Genesis::InstallExtensions(Handle<Context> native_context,
4036                                 v8::ExtensionConfiguration* extensions) {
4037   Isolate* isolate = native_context->GetIsolate();
4038   ExtensionStates extension_states;  // All extensions have state UNVISITED.
4039   return InstallAutoExtensions(isolate, &extension_states) &&
4040          (!FLAG_expose_free_buffer ||
4041           InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
4042          (!FLAG_expose_gc ||
4043           InstallExtension(isolate, "v8/gc", &extension_states)) &&
4044          (!FLAG_expose_externalize_string ||
4045           InstallExtension(isolate, "v8/externalize", &extension_states)) &&
4046          (!FLAG_gc_stats ||
4047           InstallExtension(isolate, "v8/statistics", &extension_states)) &&
4048          (!FLAG_expose_trigger_failure ||
4049           InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
4050          (!FLAG_trace_ignition_dispatches ||
4051           InstallExtension(isolate, "v8/ignition-statistics",
4052                            &extension_states)) &&
4053          InstallRequestedExtensions(isolate, extensions, &extension_states);
4054 }
4055 
4056 
InstallAutoExtensions(Isolate * isolate,ExtensionStates * extension_states)4057 bool Genesis::InstallAutoExtensions(Isolate* isolate,
4058                                     ExtensionStates* extension_states) {
4059   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
4060        it != NULL;
4061        it = it->next()) {
4062     if (it->extension()->auto_enable() &&
4063         !InstallExtension(isolate, it, extension_states)) {
4064       return false;
4065     }
4066   }
4067   return true;
4068 }
4069 
4070 
InstallRequestedExtensions(Isolate * isolate,v8::ExtensionConfiguration * extensions,ExtensionStates * extension_states)4071 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
4072                                          v8::ExtensionConfiguration* extensions,
4073                                          ExtensionStates* extension_states) {
4074   for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
4075     if (!InstallExtension(isolate, *it, extension_states)) return false;
4076   }
4077   return true;
4078 }
4079 
4080 
4081 // Installs a named extension.  This methods is unoptimized and does
4082 // not scale well if we want to support a large number of extensions.
InstallExtension(Isolate * isolate,const char * name,ExtensionStates * extension_states)4083 bool Genesis::InstallExtension(Isolate* isolate,
4084                                const char* name,
4085                                ExtensionStates* extension_states) {
4086   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
4087        it != NULL;
4088        it = it->next()) {
4089     if (strcmp(name, it->extension()->name()) == 0) {
4090       return InstallExtension(isolate, it, extension_states);
4091     }
4092   }
4093   return Utils::ApiCheck(false,
4094                          "v8::Context::New()",
4095                          "Cannot find required extension");
4096 }
4097 
4098 
InstallExtension(Isolate * isolate,v8::RegisteredExtension * current,ExtensionStates * extension_states)4099 bool Genesis::InstallExtension(Isolate* isolate,
4100                                v8::RegisteredExtension* current,
4101                                ExtensionStates* extension_states) {
4102   HandleScope scope(isolate);
4103 
4104   if (extension_states->get_state(current) == INSTALLED) return true;
4105   // The current node has already been visited so there must be a
4106   // cycle in the dependency graph; fail.
4107   if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
4108                        "v8::Context::New()",
4109                        "Circular extension dependency")) {
4110     return false;
4111   }
4112   DCHECK(extension_states->get_state(current) == UNVISITED);
4113   extension_states->set_state(current, VISITED);
4114   v8::Extension* extension = current->extension();
4115   // Install the extension's dependencies
4116   for (int i = 0; i < extension->dependency_count(); i++) {
4117     if (!InstallExtension(isolate,
4118                           extension->dependencies()[i],
4119                           extension_states)) {
4120       return false;
4121     }
4122   }
4123   // We do not expect this to throw an exception. Change this if it does.
4124   bool result = CompileExtension(isolate, extension);
4125   DCHECK(isolate->has_pending_exception() != result);
4126   if (!result) {
4127     // We print out the name of the extension that fail to install.
4128     // When an error is thrown during bootstrapping we automatically print
4129     // the line number at which this happened to the console in the isolate
4130     // error throwing functionality.
4131     base::OS::PrintError("Error installing extension '%s'.\n",
4132                          current->extension()->name());
4133     isolate->clear_pending_exception();
4134   }
4135   extension_states->set_state(current, INSTALLED);
4136   isolate->NotifyExtensionInstalled();
4137   return result;
4138 }
4139 
4140 
ConfigureGlobalObjects(v8::Local<v8::ObjectTemplate> global_proxy_template)4141 bool Genesis::ConfigureGlobalObjects(
4142     v8::Local<v8::ObjectTemplate> global_proxy_template) {
4143   Handle<JSObject> global_proxy(
4144       JSObject::cast(native_context()->global_proxy()));
4145   Handle<JSObject> global_object(
4146       JSObject::cast(native_context()->global_object()));
4147 
4148   if (!global_proxy_template.IsEmpty()) {
4149     // Configure the global proxy object.
4150     Handle<ObjectTemplateInfo> global_proxy_data =
4151         v8::Utils::OpenHandle(*global_proxy_template);
4152     if (!ConfigureApiObject(global_proxy, global_proxy_data)) return false;
4153 
4154     // Configure the global object.
4155     Handle<FunctionTemplateInfo> proxy_constructor(
4156         FunctionTemplateInfo::cast(global_proxy_data->constructor()));
4157     if (!proxy_constructor->prototype_template()->IsUndefined(isolate())) {
4158       Handle<ObjectTemplateInfo> global_object_data(
4159           ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
4160       if (!ConfigureApiObject(global_object, global_object_data)) return false;
4161     }
4162   }
4163 
4164   JSObject::ForceSetPrototype(global_proxy, global_object);
4165 
4166   native_context()->set_initial_array_prototype(
4167       JSArray::cast(native_context()->array_function()->prototype()));
4168   native_context()->set_array_buffer_map(
4169       native_context()->array_buffer_fun()->initial_map());
4170   native_context()->set_js_map_map(
4171       native_context()->js_map_fun()->initial_map());
4172   native_context()->set_js_set_map(
4173       native_context()->js_set_fun()->initial_map());
4174 
4175   return true;
4176 }
4177 
4178 
ConfigureApiObject(Handle<JSObject> object,Handle<ObjectTemplateInfo> object_template)4179 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
4180                                  Handle<ObjectTemplateInfo> object_template) {
4181   DCHECK(!object_template.is_null());
4182   DCHECK(FunctionTemplateInfo::cast(object_template->constructor())
4183              ->IsTemplateFor(object->map()));;
4184 
4185   MaybeHandle<JSObject> maybe_obj =
4186       ApiNatives::InstantiateObject(object_template);
4187   Handle<JSObject> obj;
4188   if (!maybe_obj.ToHandle(&obj)) {
4189     DCHECK(isolate()->has_pending_exception());
4190     isolate()->clear_pending_exception();
4191     return false;
4192   }
4193   TransferObject(obj, object);
4194   return true;
4195 }
4196 
4197 
TransferNamedProperties(Handle<JSObject> from,Handle<JSObject> to)4198 void Genesis::TransferNamedProperties(Handle<JSObject> from,
4199                                       Handle<JSObject> to) {
4200   // If JSObject::AddProperty asserts due to already existing property,
4201   // it is likely due to both global objects sharing property name(s).
4202   // Merging those two global objects is impossible.
4203   // The global template must not create properties that already exist
4204   // in the snapshotted global object.
4205   if (from->HasFastProperties()) {
4206     Handle<DescriptorArray> descs =
4207         Handle<DescriptorArray>(from->map()->instance_descriptors());
4208     for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
4209       PropertyDetails details = descs->GetDetails(i);
4210       switch (details.type()) {
4211         case DATA: {
4212           HandleScope inner(isolate());
4213           Handle<Name> key = Handle<Name>(descs->GetKey(i));
4214           FieldIndex index = FieldIndex::ForDescriptor(from->map(), i);
4215           DCHECK(!descs->GetDetails(i).representation().IsDouble());
4216           Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
4217                                                 isolate());
4218           JSObject::AddProperty(to, key, value, details.attributes());
4219           break;
4220         }
4221         case DATA_CONSTANT: {
4222           HandleScope inner(isolate());
4223           Handle<Name> key = Handle<Name>(descs->GetKey(i));
4224           Handle<Object> constant(descs->GetConstant(i), isolate());
4225           JSObject::AddProperty(to, key, constant, details.attributes());
4226           break;
4227         }
4228         case ACCESSOR:
4229           UNREACHABLE();
4230         case ACCESSOR_CONSTANT: {
4231           Handle<Name> key(descs->GetKey(i));
4232           LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
4233           CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
4234           // If the property is already there we skip it
4235           if (it.IsFound()) continue;
4236           HandleScope inner(isolate());
4237           DCHECK(!to->HasFastProperties());
4238           // Add to dictionary.
4239           Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
4240           PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
4241                             PropertyCellType::kMutable);
4242           JSObject::SetNormalizedProperty(to, key, callbacks, d);
4243           break;
4244         }
4245       }
4246     }
4247   } else if (from->IsJSGlobalObject()) {
4248     Handle<GlobalDictionary> properties =
4249         Handle<GlobalDictionary>(from->global_dictionary());
4250     int capacity = properties->Capacity();
4251     for (int i = 0; i < capacity; i++) {
4252       Object* raw_key(properties->KeyAt(i));
4253       if (properties->IsKey(isolate(), raw_key)) {
4254         DCHECK(raw_key->IsName());
4255         // If the property is already there we skip it.
4256         Handle<Name> key(Name::cast(raw_key));
4257         LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
4258         CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
4259         if (it.IsFound()) continue;
4260         // Set the property.
4261         DCHECK(properties->ValueAt(i)->IsPropertyCell());
4262         Handle<PropertyCell> cell(PropertyCell::cast(properties->ValueAt(i)));
4263         Handle<Object> value(cell->value(), isolate());
4264         if (value->IsTheHole(isolate())) continue;
4265         PropertyDetails details = cell->property_details();
4266         DCHECK_EQ(kData, details.kind());
4267         JSObject::AddProperty(to, key, value, details.attributes());
4268       }
4269     }
4270   } else {
4271     Handle<NameDictionary> properties =
4272         Handle<NameDictionary>(from->property_dictionary());
4273     int capacity = properties->Capacity();
4274     for (int i = 0; i < capacity; i++) {
4275       Object* raw_key(properties->KeyAt(i));
4276       if (properties->IsKey(isolate(), raw_key)) {
4277         DCHECK(raw_key->IsName());
4278         // If the property is already there we skip it.
4279         Handle<Name> key(Name::cast(raw_key));
4280         LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
4281         CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
4282         if (it.IsFound()) continue;
4283         // Set the property.
4284         Handle<Object> value = Handle<Object>(properties->ValueAt(i),
4285                                               isolate());
4286         DCHECK(!value->IsCell());
4287         DCHECK(!value->IsTheHole(isolate()));
4288         PropertyDetails details = properties->DetailsAt(i);
4289         DCHECK_EQ(kData, details.kind());
4290         JSObject::AddProperty(to, key, value, details.attributes());
4291       }
4292     }
4293   }
4294 }
4295 
4296 
TransferIndexedProperties(Handle<JSObject> from,Handle<JSObject> to)4297 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
4298                                         Handle<JSObject> to) {
4299   // Cloning the elements array is sufficient.
4300   Handle<FixedArray> from_elements =
4301       Handle<FixedArray>(FixedArray::cast(from->elements()));
4302   Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
4303   to->set_elements(*to_elements);
4304 }
4305 
4306 
TransferObject(Handle<JSObject> from,Handle<JSObject> to)4307 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
4308   HandleScope outer(isolate());
4309 
4310   DCHECK(!from->IsJSArray());
4311   DCHECK(!to->IsJSArray());
4312 
4313   TransferNamedProperties(from, to);
4314   TransferIndexedProperties(from, to);
4315 
4316   // Transfer the prototype (new map is needed).
4317   Handle<Object> proto(from->map()->prototype(), isolate());
4318   JSObject::ForceSetPrototype(to, proto);
4319 }
4320 
4321 
MakeFunctionInstancePrototypeWritable()4322 void Genesis::MakeFunctionInstancePrototypeWritable() {
4323   // The maps with writable prototype are created in CreateEmptyFunction
4324   // and CreateStrictModeFunctionMaps respectively. Initially the maps are
4325   // created with read-only prototype for JS builtins processing.
4326   DCHECK(!sloppy_function_map_writable_prototype_.is_null());
4327   DCHECK(!strict_function_map_writable_prototype_.is_null());
4328 
4329   // Replace function instance maps to make prototype writable.
4330   native_context()->set_sloppy_function_map(
4331       *sloppy_function_map_writable_prototype_);
4332   native_context()->set_strict_function_map(
4333       *strict_function_map_writable_prototype_);
4334 }
4335 
4336 
4337 class NoTrackDoubleFieldsForSerializerScope {
4338  public:
NoTrackDoubleFieldsForSerializerScope(Isolate * isolate)4339   explicit NoTrackDoubleFieldsForSerializerScope(Isolate* isolate)
4340       : flag_(FLAG_track_double_fields), enabled_(false) {
4341     if (isolate->serializer_enabled()) {
4342       // Disable tracking double fields because heap numbers treated as
4343       // immutable by the serializer.
4344       FLAG_track_double_fields = false;
4345       enabled_ = true;
4346     }
4347   }
4348 
~NoTrackDoubleFieldsForSerializerScope()4349   ~NoTrackDoubleFieldsForSerializerScope() {
4350     if (enabled_) {
4351       FLAG_track_double_fields = flag_;
4352     }
4353   }
4354 
4355  private:
4356   bool flag_;
4357   bool enabled_;
4358 };
4359 
Genesis(Isolate * isolate,MaybeHandle<JSGlobalProxy> maybe_global_proxy,v8::Local<v8::ObjectTemplate> global_proxy_template,v8::ExtensionConfiguration * extensions,size_t context_snapshot_index,GlobalContextType context_type)4360 Genesis::Genesis(Isolate* isolate,
4361                  MaybeHandle<JSGlobalProxy> maybe_global_proxy,
4362                  v8::Local<v8::ObjectTemplate> global_proxy_template,
4363                  v8::ExtensionConfiguration* extensions,
4364                  size_t context_snapshot_index, GlobalContextType context_type)
4365     : isolate_(isolate), active_(isolate->bootstrapper()) {
4366   NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
4367   result_ = Handle<Context>::null();
4368   global_proxy_ = Handle<JSGlobalProxy>::null();
4369 
4370   // Before creating the roots we must save the context and restore it
4371   // on all function exits.
4372   SaveContext saved_context(isolate);
4373 
4374   // During genesis, the boilerplate for stack overflow won't work until the
4375   // environment has been at least partially initialized. Add a stack check
4376   // before entering JS code to catch overflow early.
4377   StackLimitCheck check(isolate);
4378   if (check.HasOverflowed()) {
4379     isolate->StackOverflow();
4380     return;
4381   }
4382 
4383   // The deserializer needs to hook up references to the global proxy.
4384   // Create an uninitialized global proxy now if we don't have one
4385   // and initialize it later in CreateNewGlobals.
4386   Handle<JSGlobalProxy> global_proxy;
4387   if (!maybe_global_proxy.ToHandle(&global_proxy)) {
4388     const int internal_field_count =
4389         !global_proxy_template.IsEmpty()
4390             ? global_proxy_template->InternalFieldCount()
4391             : 0;
4392     global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy(
4393         JSGlobalProxy::SizeWithInternalFields(internal_field_count));
4394   }
4395 
4396   // We can only de-serialize a context if the isolate was initialized from
4397   // a snapshot. Otherwise we have to build the context from scratch.
4398   // Also create a context from scratch to expose natives, if required by flag.
4399   if (!isolate->initialized_from_snapshot() ||
4400       !Snapshot::NewContextFromSnapshot(isolate, global_proxy,
4401                                         context_snapshot_index)
4402            .ToHandle(&native_context_)) {
4403     native_context_ = Handle<Context>();
4404   }
4405 
4406   if (!native_context().is_null()) {
4407     AddToWeakNativeContextList(*native_context());
4408     isolate->set_context(*native_context());
4409     isolate->counters()->contexts_created_by_snapshot()->Increment();
4410 #if TRACE_MAPS
4411     if (FLAG_trace_maps) {
4412       Handle<JSFunction> object_fun = isolate->object_function();
4413       PrintF("[TraceMap: InitialMap map= %p SFI= %d_Object ]\n",
4414              reinterpret_cast<void*>(object_fun->initial_map()),
4415              object_fun->shared()->unique_id());
4416       Map::TraceAllTransitions(object_fun->initial_map());
4417     }
4418 #endif
4419     Handle<JSGlobalObject> global_object =
4420         CreateNewGlobals(global_proxy_template, global_proxy);
4421 
4422     HookUpGlobalProxy(global_object, global_proxy);
4423     HookUpGlobalObject(global_object);
4424 
4425     if (!ConfigureGlobalObjects(global_proxy_template)) return;
4426   } else {
4427     // We get here if there was no context snapshot.
4428     CreateRoots();
4429     Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
4430     CreateStrictModeFunctionMaps(empty_function);
4431     CreateIteratorMaps(empty_function);
4432     CreateAsyncFunctionMaps(empty_function);
4433     Handle<JSGlobalObject> global_object =
4434         CreateNewGlobals(global_proxy_template, global_proxy);
4435     HookUpGlobalProxy(global_object, global_proxy);
4436     InitializeGlobal(global_object, empty_function, context_type);
4437     InitializeNormalizedMapCaches();
4438 
4439     if (!InstallNatives(context_type)) return;
4440 
4441     MakeFunctionInstancePrototypeWritable();
4442 
4443     if (!InstallExtraNatives()) return;
4444     if (!ConfigureGlobalObjects(global_proxy_template)) return;
4445 
4446     isolate->counters()->contexts_created_from_scratch()->Increment();
4447     // Re-initialize the counter because it got incremented during snapshot
4448     // creation.
4449     isolate->native_context()->set_errors_thrown(Smi::kZero);
4450   }
4451 
4452   // Install experimental natives. Do not include them into the
4453   // snapshot as we should be able to turn them off at runtime. Re-installing
4454   // them after they have already been deserialized would also fail.
4455   if (context_type == FULL_CONTEXT) {
4456     if (!isolate->serializer_enabled()) {
4457       InitializeExperimentalGlobal();
4458       if (!InstallExperimentalNatives()) return;
4459 
4460       if (FLAG_experimental_extras) {
4461         if (!InstallExperimentalExtraNatives()) return;
4462       }
4463     }
4464     // The serializer cannot serialize typed arrays. Reset those typed arrays
4465     // for each new context.
4466   } else if (context_type == DEBUG_CONTEXT) {
4467     DCHECK(!isolate->serializer_enabled());
4468     InitializeExperimentalGlobal();
4469     if (!InstallDebuggerNatives()) return;
4470   }
4471 
4472   ConfigureUtilsObject(context_type);
4473 
4474   // Check that the script context table is empty except for the 'this' binding.
4475   // We do not need script contexts for native scripts.
4476   DCHECK_EQ(1, native_context()->script_context_table()->used());
4477 
4478   result_ = native_context();
4479 }
4480 
Genesis(Isolate * isolate,MaybeHandle<JSGlobalProxy> maybe_global_proxy,v8::Local<v8::ObjectTemplate> global_proxy_template)4481 Genesis::Genesis(Isolate* isolate,
4482                  MaybeHandle<JSGlobalProxy> maybe_global_proxy,
4483                  v8::Local<v8::ObjectTemplate> global_proxy_template)
4484     : isolate_(isolate), active_(isolate->bootstrapper()) {
4485   NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
4486   result_ = Handle<Context>::null();
4487   global_proxy_ = Handle<JSGlobalProxy>::null();
4488 
4489   // Before creating the roots we must save the context and restore it
4490   // on all function exits.
4491   SaveContext saved_context(isolate);
4492 
4493   // During genesis, the boilerplate for stack overflow won't work until the
4494   // environment has been at least partially initialized. Add a stack check
4495   // before entering JS code to catch overflow early.
4496   StackLimitCheck check(isolate);
4497   if (check.HasOverflowed()) {
4498     isolate->StackOverflow();
4499     return;
4500   }
4501 
4502   const int proxy_size = JSGlobalProxy::SizeWithInternalFields(
4503       global_proxy_template->InternalFieldCount());
4504 
4505   Handle<JSGlobalProxy> global_proxy;
4506   if (!maybe_global_proxy.ToHandle(&global_proxy)) {
4507     global_proxy = factory()->NewUninitializedJSGlobalProxy(proxy_size);
4508   }
4509 
4510   // CreateNewGlobals.
4511   Handle<ObjectTemplateInfo> global_proxy_data =
4512       v8::Utils::OpenHandle(*global_proxy_template);
4513   Handle<FunctionTemplateInfo> global_constructor(
4514       FunctionTemplateInfo::cast(global_proxy_data->constructor()));
4515   Handle<SharedFunctionInfo> shared =
4516       FunctionTemplateInfo::GetOrCreateSharedFunctionInfo(isolate,
4517                                                           global_constructor);
4518   Handle<Map> initial_map =
4519       factory()->CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE);
4520   Handle<JSFunction> global_proxy_function =
4521       isolate->factory()->NewFunctionFromSharedFunctionInfo(
4522           initial_map, shared, factory()->undefined_value());
4523   DCHECK_EQ(global_proxy_data->internal_field_count(),
4524             global_proxy_template->InternalFieldCount());
4525   Handle<Map> global_proxy_map = isolate->factory()->NewMap(
4526       JS_GLOBAL_PROXY_TYPE, proxy_size, FAST_HOLEY_SMI_ELEMENTS);
4527   JSFunction::SetInitialMap(global_proxy_function, global_proxy_map,
4528                             factory()->null_value());
4529   global_proxy_map->set_is_access_check_needed(true);
4530   global_proxy_map->set_is_callable();
4531   global_proxy_map->set_is_constructor(true);
4532   global_proxy_map->set_has_hidden_prototype(true);
4533 
4534   Handle<String> global_name = factory()->global_string();
4535   global_proxy_function->shared()->set_instance_class_name(*global_name);
4536   factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
4537 
4538   // HookUpGlobalProxy.
4539   global_proxy->set_native_context(heap()->null_value());
4540 
4541   // DetachGlobal.
4542   JSObject::ForceSetPrototype(global_proxy, factory()->null_value());
4543 
4544   global_proxy_ = global_proxy;
4545 }
4546 
4547 // Support for thread preemption.
4548 
4549 // Reserve space for statics needing saving and restoring.
ArchiveSpacePerThread()4550 int Bootstrapper::ArchiveSpacePerThread() {
4551   return sizeof(NestingCounterType);
4552 }
4553 
4554 
4555 // Archive statics that are thread-local.
ArchiveState(char * to)4556 char* Bootstrapper::ArchiveState(char* to) {
4557   *reinterpret_cast<NestingCounterType*>(to) = nesting_;
4558   nesting_ = 0;
4559   return to + sizeof(NestingCounterType);
4560 }
4561 
4562 
4563 // Restore statics that are thread-local.
RestoreState(char * from)4564 char* Bootstrapper::RestoreState(char* from) {
4565   nesting_ = *reinterpret_cast<NestingCounterType*>(from);
4566   return from + sizeof(NestingCounterType);
4567 }
4568 
4569 
4570 // Called when the top-level V8 mutex is destroyed.
FreeThreadResources()4571 void Bootstrapper::FreeThreadResources() {
4572   DCHECK(!IsActive());
4573 }
4574 
4575 }  // namespace internal
4576 }  // namespace v8
4577