93f9151117605b757bbf6ef8db6d32942bd4c9bc
[platform/upstream/v8.git] / src / bootstrapper.cc
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/utils/random-number-generator.h"
10 #include "src/code-stubs.h"
11 #include "src/extensions/externalize-string-extension.h"
12 #include "src/extensions/free-buffer-extension.h"
13 #include "src/extensions/gc-extension.h"
14 #include "src/extensions/statistics-extension.h"
15 #include "src/extensions/trigger-failure-extension.h"
16 #include "src/heap/heap.h"
17 #include "src/snapshot/natives.h"
18 #include "src/snapshot/snapshot.h"
19 #include "third_party/fdlibm/fdlibm.h"
20
21 #if defined(V8_WASM)
22 #include "src/wasm/wasm-js.h"
23 #endif
24
25 namespace v8 {
26 namespace internal {
27
28 Bootstrapper::Bootstrapper(Isolate* isolate)
29     : isolate_(isolate),
30       nesting_(0),
31       extensions_cache_(Script::TYPE_EXTENSION) {}
32
33 template <class Source>
34 Handle<String> Bootstrapper::SourceLookup(int index) {
35   DCHECK(0 <= index && index < Source::GetBuiltinsCount());
36   Heap* heap = isolate_->heap();
37   if (Source::GetSourceCache(heap)->get(index)->IsUndefined()) {
38     // We can use external strings for the natives.
39     Vector<const char> source = Source::GetScriptSource(index);
40     NativesExternalStringResource* resource =
41         new NativesExternalStringResource(source.start(), source.length());
42     // We do not expect this to throw an exception. Change this if it does.
43     Handle<String> source_code = isolate_->factory()
44                                      ->NewExternalStringFromOneByte(resource)
45                                      .ToHandleChecked();
46     // Mark this external string with a special map.
47     source_code->set_map(isolate_->heap()->native_source_string_map());
48     Source::GetSourceCache(heap)->set(index, *source_code);
49   }
50   Handle<Object> cached_source(Source::GetSourceCache(heap)->get(index),
51                                isolate_);
52   return Handle<String>::cast(cached_source);
53 }
54
55
56 template Handle<String> Bootstrapper::SourceLookup<Natives>(int index);
57 template Handle<String> Bootstrapper::SourceLookup<ExperimentalNatives>(
58     int index);
59 template Handle<String> Bootstrapper::SourceLookup<ExperimentalExtraNatives>(
60     int index);
61 template Handle<String> Bootstrapper::SourceLookup<ExtraNatives>(int index);
62 template Handle<String> Bootstrapper::SourceLookup<CodeStubNatives>(int index);
63
64
65 void Bootstrapper::Initialize(bool create_heap_objects) {
66   extensions_cache_.Initialize(isolate_, create_heap_objects);
67 }
68
69
70 static const char* GCFunctionName() {
71   bool flag_given = FLAG_expose_gc_as != NULL && strlen(FLAG_expose_gc_as) != 0;
72   return flag_given ? FLAG_expose_gc_as : "gc";
73 }
74
75
76 v8::Extension* Bootstrapper::free_buffer_extension_ = NULL;
77 v8::Extension* Bootstrapper::gc_extension_ = NULL;
78 v8::Extension* Bootstrapper::externalize_string_extension_ = NULL;
79 v8::Extension* Bootstrapper::statistics_extension_ = NULL;
80 v8::Extension* Bootstrapper::trigger_failure_extension_ = NULL;
81
82
83 void Bootstrapper::InitializeOncePerProcess() {
84   free_buffer_extension_ = new FreeBufferExtension;
85   v8::RegisterExtension(free_buffer_extension_);
86   gc_extension_ = new GCExtension(GCFunctionName());
87   v8::RegisterExtension(gc_extension_);
88   externalize_string_extension_ = new ExternalizeStringExtension;
89   v8::RegisterExtension(externalize_string_extension_);
90   statistics_extension_ = new StatisticsExtension;
91   v8::RegisterExtension(statistics_extension_);
92   trigger_failure_extension_ = new TriggerFailureExtension;
93   v8::RegisterExtension(trigger_failure_extension_);
94 }
95
96
97 void Bootstrapper::TearDownExtensions() {
98   delete free_buffer_extension_;
99   free_buffer_extension_ = NULL;
100   delete gc_extension_;
101   gc_extension_ = NULL;
102   delete externalize_string_extension_;
103   externalize_string_extension_ = NULL;
104   delete statistics_extension_;
105   statistics_extension_ = NULL;
106   delete trigger_failure_extension_;
107   trigger_failure_extension_ = NULL;
108 }
109
110
111 void DeleteNativeSources(Object* maybe_array) {
112   if (maybe_array->IsFixedArray()) {
113     FixedArray* array = FixedArray::cast(maybe_array);
114     for (int i = 0; i < array->length(); i++) {
115       Object* natives_source = array->get(i);
116       if (!natives_source->IsUndefined()) {
117         const NativesExternalStringResource* resource =
118             reinterpret_cast<const NativesExternalStringResource*>(
119                 ExternalOneByteString::cast(natives_source)->resource());
120         delete resource;
121       }
122     }
123   }
124 }
125
126
127 void Bootstrapper::TearDown() {
128   DeleteNativeSources(Natives::GetSourceCache(isolate_->heap()));
129   DeleteNativeSources(ExperimentalNatives::GetSourceCache(isolate_->heap()));
130   DeleteNativeSources(ExtraNatives::GetSourceCache(isolate_->heap()));
131   DeleteNativeSources(
132       ExperimentalExtraNatives::GetSourceCache(isolate_->heap()));
133   DeleteNativeSources(CodeStubNatives::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, ContextType context_type);
144   ~Genesis() { }
145
146   Isolate* isolate() const { return isolate_; }
147   Factory* factory() const { return isolate_->factory(); }
148   Heap* heap() const { return isolate_->heap(); }
149
150   Handle<Context> result() { return result_; }
151
152  private:
153   Handle<Context> native_context() { return native_context_; }
154
155   // Creates some basic objects. Used for creating a context from scratch.
156   void CreateRoots();
157   // Creates the empty function.  Used for creating a context from scratch.
158   Handle<JSFunction> CreateEmptyFunction(Isolate* isolate);
159   // Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
160   Handle<JSFunction> GetRestrictedFunctionPropertiesThrower();
161   Handle<JSFunction> GetStrictArgumentsPoisonFunction();
162   Handle<JSFunction> GetThrowTypeErrorIntrinsic(Builtins::Name builtin_name);
163
164   void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
165   void CreateStrongModeFunctionMaps(Handle<JSFunction> empty);
166
167   // Make the "arguments" and "caller" properties throw a TypeError on access.
168   void AddRestrictedFunctionProperties(Handle<Map> map);
169
170   // Creates the global objects using the global proxy and the template passed
171   // in through the API.  We call this regardless of whether we are building a
172   // context from scratch or using a deserialized one from the partial snapshot
173   // but in the latter case we don't use the objects it produces directly, as
174   // we have to used the deserialized ones that are linked together with the
175   // rest of the context snapshot.
176   Handle<GlobalObject> CreateNewGlobals(
177       v8::Local<v8::ObjectTemplate> global_proxy_template,
178       Handle<JSGlobalProxy> global_proxy);
179   // Hooks the given global proxy into the context.  If the context was created
180   // by deserialization then this will unhook the global proxy that was
181   // deserialized, leaving the GC to pick it up.
182   void HookUpGlobalProxy(Handle<GlobalObject> global_object,
183                          Handle<JSGlobalProxy> global_proxy);
184   // Similarly, we want to use the global that has been created by the templates
185   // passed through the API.  The global from the snapshot is detached from the
186   // other objects in the snapshot.
187   void HookUpGlobalObject(Handle<GlobalObject> global_object,
188                           Handle<FixedArray> outdated_contexts);
189   // The native context has a ScriptContextTable that store declarative bindings
190   // made in script scopes.  Add a "this" binding to that table pointing to the
191   // global proxy.
192   void InstallGlobalThisBinding();
193   void HookUpGlobalThisBinding(Handle<FixedArray> outdated_contexts);
194   // New context initialization.  Used for creating a context from scratch.
195   void InitializeGlobal(Handle<GlobalObject> global_object,
196                         Handle<JSFunction> empty_function,
197                         ContextType context_type);
198   void InitializeExperimentalGlobal();
199   // Typed arrays are not serializable and have to initialized afterwards.
200   void InitializeBuiltinTypedArrays();
201
202 #define DECLARE_FEATURE_INITIALIZATION(id, descr) \
203   void InitializeGlobal_##id();
204
205   HARMONY_INPROGRESS(DECLARE_FEATURE_INITIALIZATION)
206   HARMONY_STAGED(DECLARE_FEATURE_INITIALIZATION)
207   HARMONY_SHIPPING(DECLARE_FEATURE_INITIALIZATION)
208 #undef DECLARE_FEATURE_INITIALIZATION
209
210   Handle<JSFunction> InstallInternalArray(Handle<JSObject> target,
211                                           const char* name,
212                                           ElementsKind elements_kind);
213   bool InstallNatives(ContextType context_type);
214
215   void InstallTypedArray(const char* name, ElementsKind elements_kind,
216                          Handle<JSFunction>* fun);
217   bool InstallExperimentalNatives();
218   bool InstallExtraNatives();
219   bool InstallExperimentalExtraNatives();
220   bool InstallDebuggerNatives();
221   void InstallBuiltinFunctionIds();
222   void InstallExperimentalBuiltinFunctionIds();
223   void InitializeNormalizedMapCaches();
224
225   enum ExtensionTraversalState {
226     UNVISITED, VISITED, INSTALLED
227   };
228
229   class ExtensionStates {
230    public:
231     ExtensionStates();
232     ExtensionTraversalState get_state(RegisteredExtension* extension);
233     void set_state(RegisteredExtension* extension,
234                    ExtensionTraversalState state);
235    private:
236     HashMap map_;
237     DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
238   };
239
240   // Used both for deserialized and from-scratch contexts to add the extensions
241   // provided.
242   static bool InstallExtensions(Handle<Context> native_context,
243                                 v8::ExtensionConfiguration* extensions);
244   static bool InstallAutoExtensions(Isolate* isolate,
245                                     ExtensionStates* extension_states);
246   static bool InstallRequestedExtensions(Isolate* isolate,
247                                          v8::ExtensionConfiguration* extensions,
248                                          ExtensionStates* extension_states);
249   static bool InstallExtension(Isolate* isolate,
250                                const char* name,
251                                ExtensionStates* extension_states);
252   static bool InstallExtension(Isolate* isolate,
253                                v8::RegisteredExtension* current,
254                                ExtensionStates* extension_states);
255   static bool InstallSpecialObjects(Handle<Context> native_context);
256   bool ConfigureApiObject(Handle<JSObject> object,
257                           Handle<ObjectTemplateInfo> object_template);
258   bool ConfigureGlobalObjects(
259       v8::Local<v8::ObjectTemplate> global_proxy_template);
260
261   // Migrates all properties from the 'from' object to the 'to'
262   // object and overrides the prototype in 'to' with the one from
263   // 'from'.
264   void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
265   void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
266   void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
267
268   enum FunctionMode {
269     // With prototype.
270     FUNCTION_WITH_WRITEABLE_PROTOTYPE,
271     FUNCTION_WITH_READONLY_PROTOTYPE,
272     // Without prototype.
273     FUNCTION_WITHOUT_PROTOTYPE,
274     BOUND_FUNCTION
275   };
276
277   static bool IsFunctionModeWithPrototype(FunctionMode function_mode) {
278     return (function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ||
279             function_mode == FUNCTION_WITH_READONLY_PROTOTYPE);
280   }
281
282   Handle<Map> CreateSloppyFunctionMap(FunctionMode function_mode);
283
284   void SetFunctionInstanceDescriptor(Handle<Map> map,
285                                      FunctionMode function_mode);
286   void MakeFunctionInstancePrototypeWritable();
287
288   Handle<Map> CreateStrictFunctionMap(FunctionMode function_mode,
289                                       Handle<JSFunction> empty_function);
290   Handle<Map> CreateStrongFunctionMap(Handle<JSFunction> empty_function,
291                                       bool is_constructor);
292
293
294   void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
295                                            FunctionMode function_mode);
296   void SetStrongFunctionInstanceDescriptor(Handle<Map> map);
297
298   static bool CallUtilsFunction(Isolate* isolate, const char* name);
299
300   static bool CompileExtension(Isolate* isolate, v8::Extension* extension);
301
302   Isolate* isolate_;
303   Handle<Context> result_;
304   Handle<Context> native_context_;
305
306   // Function maps. Function maps are created initially with a read only
307   // prototype for the processing of JS builtins. Later the function maps are
308   // replaced in order to make prototype writable. These are the final, writable
309   // prototype, maps.
310   Handle<Map> sloppy_function_map_writable_prototype_;
311   Handle<Map> strict_function_map_writable_prototype_;
312   Handle<JSFunction> strict_poison_function_;
313   Handle<JSFunction> restricted_function_properties_thrower_;
314
315   BootstrapperActive active_;
316   friend class Bootstrapper;
317 };
318
319
320 void Bootstrapper::Iterate(ObjectVisitor* v) {
321   extensions_cache_.Iterate(v);
322   v->Synchronize(VisitorSynchronization::kExtensions);
323 }
324
325
326 Handle<Context> Bootstrapper::CreateEnvironment(
327     MaybeHandle<JSGlobalProxy> maybe_global_proxy,
328     v8::Local<v8::ObjectTemplate> global_proxy_template,
329     v8::ExtensionConfiguration* extensions, ContextType context_type) {
330   HandleScope scope(isolate_);
331   Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template,
332                   extensions, context_type);
333   Handle<Context> env = genesis.result();
334   if (env.is_null() ||
335       (context_type != THIN_CONTEXT && !InstallExtensions(env, extensions))) {
336     return Handle<Context>();
337   }
338   return scope.CloseAndEscape(env);
339 }
340
341
342 bool Bootstrapper::CreateCodeStubContext(Isolate* isolate) {
343   HandleScope scope(isolate);
344   SaveContext save_context(isolate);
345   BootstrapperActive active(this);
346
347   v8::ExtensionConfiguration no_extensions;
348   Handle<Context> native_context = CreateEnvironment(
349       MaybeHandle<JSGlobalProxy>(), v8::Local<v8::ObjectTemplate>(),
350       &no_extensions, THIN_CONTEXT);
351   isolate->heap()->SetRootCodeStubContext(*native_context);
352   isolate->set_context(*native_context);
353   Handle<JSObject> code_stub_exports =
354       isolate->factory()->NewJSObject(isolate->object_function());
355   JSObject::NormalizeProperties(code_stub_exports, CLEAR_INOBJECT_PROPERTIES, 2,
356                                 "container to export to extra natives");
357   isolate->heap()->SetRootCodeStubExportsObject(*code_stub_exports);
358   return InstallCodeStubNatives(isolate);
359 }
360
361
362 static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
363   // object.__proto__ = proto;
364   Handle<Map> old_map = Handle<Map>(object->map());
365   Handle<Map> new_map = Map::Copy(old_map, "SetObjectPrototype");
366   Map::SetPrototype(new_map, proto, FAST_PROTOTYPE);
367   JSObject::MigrateToMap(object, new_map);
368 }
369
370
371 void Bootstrapper::DetachGlobal(Handle<Context> env) {
372   Factory* factory = env->GetIsolate()->factory();
373   Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
374   global_proxy->set_native_context(*factory->null_value());
375   SetObjectPrototype(global_proxy, factory->null_value());
376   global_proxy->map()->SetConstructor(*factory->null_value());
377   if (FLAG_track_detached_contexts) {
378     env->GetIsolate()->AddDetachedContext(env);
379   }
380 }
381
382
383 static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
384                                           const char* name, InstanceType type,
385                                           int instance_size,
386                                           MaybeHandle<JSObject> maybe_prototype,
387                                           Builtins::Name call,
388                                           bool strict_function_map = false) {
389   Isolate* isolate = target->GetIsolate();
390   Factory* factory = isolate->factory();
391   Handle<String> internalized_name = factory->InternalizeUtf8String(name);
392   Handle<Code> call_code = Handle<Code>(isolate->builtins()->builtin(call));
393   Handle<JSObject> prototype;
394   static const bool kReadOnlyPrototype = false;
395   static const bool kInstallConstructor = false;
396   Handle<JSFunction> function =
397       maybe_prototype.ToHandle(&prototype)
398           ? factory->NewFunction(internalized_name, call_code, prototype, type,
399                                  instance_size, kReadOnlyPrototype,
400                                  kInstallConstructor, strict_function_map)
401           : factory->NewFunctionWithoutPrototype(internalized_name, call_code,
402                                                  strict_function_map);
403   PropertyAttributes attributes;
404   if (target->IsJSBuiltinsObject()) {
405     attributes =
406         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
407   } else {
408     attributes = DONT_ENUM;
409   }
410   JSObject::AddProperty(target, internalized_name, function, attributes);
411   if (target->IsJSGlobalObject()) {
412     function->shared()->set_instance_class_name(*internalized_name);
413   }
414   function->shared()->set_native(true);
415   return function;
416 }
417
418
419 void Genesis::SetFunctionInstanceDescriptor(Handle<Map> map,
420                                             FunctionMode function_mode) {
421   int size = IsFunctionModeWithPrototype(function_mode) ? 5 : 4;
422   Map::EnsureDescriptorSlack(map, size);
423
424   PropertyAttributes ro_attribs =
425       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
426   PropertyAttributes roc_attribs =
427       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
428
429   Handle<AccessorInfo> length =
430       Accessors::FunctionLengthInfo(isolate(), roc_attribs);
431   {  // Add length.
432     AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
433                                  length, roc_attribs);
434     map->AppendDescriptor(&d);
435   }
436   Handle<AccessorInfo> name =
437       Accessors::FunctionNameInfo(isolate(), ro_attribs);
438   {  // Add name.
439     AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
440                                  roc_attribs);
441     map->AppendDescriptor(&d);
442   }
443   Handle<AccessorInfo> args =
444       Accessors::FunctionArgumentsInfo(isolate(), ro_attribs);
445   {  // Add arguments.
446     AccessorConstantDescriptor d(Handle<Name>(Name::cast(args->name())), args,
447                                  ro_attribs);
448     map->AppendDescriptor(&d);
449   }
450   Handle<AccessorInfo> caller =
451       Accessors::FunctionCallerInfo(isolate(), ro_attribs);
452   {  // Add caller.
453     AccessorConstantDescriptor d(Handle<Name>(Name::cast(caller->name())),
454                                  caller, ro_attribs);
455     map->AppendDescriptor(&d);
456   }
457   if (IsFunctionModeWithPrototype(function_mode)) {
458     if (function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE) {
459       ro_attribs = static_cast<PropertyAttributes>(ro_attribs & ~READ_ONLY);
460     }
461     Handle<AccessorInfo> prototype =
462         Accessors::FunctionPrototypeInfo(isolate(), ro_attribs);
463     AccessorConstantDescriptor d(Handle<Name>(Name::cast(prototype->name())),
464                                  prototype, ro_attribs);
465     map->AppendDescriptor(&d);
466   }
467 }
468
469
470 Handle<Map> Genesis::CreateSloppyFunctionMap(FunctionMode function_mode) {
471   Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
472   SetFunctionInstanceDescriptor(map, function_mode);
473   map->set_function_with_prototype(IsFunctionModeWithPrototype(function_mode));
474   return map;
475 }
476
477
478 Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
479   // Allocate the map for function instances. Maps are allocated first and their
480   // prototypes patched later, once empty function is created.
481
482   // Functions with this map will not have a 'prototype' property, and
483   // can not be used as constructors.
484   Handle<Map> function_without_prototype_map =
485       CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
486   native_context()->set_sloppy_function_without_prototype_map(
487       *function_without_prototype_map);
488
489   // Allocate the function map. This map is temporary, used only for processing
490   // of builtins.
491   // Later the map is replaced with writable prototype map, allocated below.
492   Handle<Map> function_map =
493       CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE);
494   native_context()->set_sloppy_function_map(*function_map);
495   native_context()->set_sloppy_function_with_readonly_prototype_map(
496       *function_map);
497
498   // The final map for functions. Writeable prototype.
499   // This map is installed in MakeFunctionInstancePrototypeWritable.
500   sloppy_function_map_writable_prototype_ =
501       CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE);
502   Factory* factory = isolate->factory();
503
504   Handle<String> object_name = factory->Object_string();
505
506   Handle<JSObject> object_function_prototype;
507
508   {  // --- O b j e c t ---
509     Handle<JSFunction> object_fun = factory->NewFunction(object_name);
510     int unused = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
511     int instance_size = JSObject::kHeaderSize + kPointerSize * unused;
512     Handle<Map> object_function_map =
513         factory->NewMap(JS_OBJECT_TYPE, instance_size);
514     object_function_map->SetInObjectProperties(unused);
515     JSFunction::SetInitialMap(object_fun, object_function_map,
516                               isolate->factory()->null_value());
517     object_function_map->set_unused_property_fields(unused);
518
519     native_context()->set_object_function(*object_fun);
520
521     // Allocate a new prototype for the object function.
522     object_function_prototype =
523         factory->NewJSObject(isolate->object_function(), TENURED);
524     Handle<Map> map = Map::Copy(handle(object_function_prototype->map()),
525                                 "EmptyObjectPrototype");
526     map->set_is_prototype_map(true);
527     object_function_prototype->set_map(*map);
528
529     native_context()->set_initial_object_prototype(*object_function_prototype);
530     // For bootstrapping set the array prototype to be the same as the object
531     // prototype, otherwise the missing initial_array_prototype will cause
532     // assertions during startup.
533     native_context()->set_initial_array_prototype(*object_function_prototype);
534     Accessors::FunctionSetPrototype(object_fun, object_function_prototype)
535         .Assert();
536
537     // Allocate initial strong object map.
538     Handle<Map> strong_object_map =
539         Map::Copy(Handle<Map>(object_fun->initial_map()), "EmptyStrongObject");
540     strong_object_map->set_is_strong();
541     native_context()->set_js_object_strong_map(*strong_object_map);
542   }
543
544   // Allocate the empty function as the prototype for function - ES6 19.2.3
545   Handle<Code> code(isolate->builtins()->builtin(Builtins::kEmptyFunction));
546   Handle<JSFunction> empty_function =
547       factory->NewFunctionWithoutPrototype(factory->empty_string(), code);
548
549   // Allocate the function map first and then patch the prototype later
550   Handle<Map> empty_function_map =
551       CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
552   DCHECK(!empty_function_map->is_dictionary_map());
553   Map::SetPrototype(empty_function_map, object_function_prototype);
554   empty_function_map->set_is_prototype_map(true);
555
556   empty_function->set_map(*empty_function_map);
557
558   // --- E m p t y ---
559   Handle<String> source = factory->NewStringFromStaticChars("() {}");
560   Handle<Script> script = factory->NewScript(source);
561   script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
562   empty_function->shared()->set_start_position(0);
563   empty_function->shared()->set_end_position(source->length());
564   empty_function->shared()->DontAdaptArguments();
565   SharedFunctionInfo::SetScript(handle(empty_function->shared()), script);
566
567   // Set prototypes for the function maps.
568   Handle<Map> sloppy_function_map(native_context()->sloppy_function_map(),
569                                   isolate);
570   Handle<Map> sloppy_function_without_prototype_map(
571       native_context()->sloppy_function_without_prototype_map(), isolate);
572   Map::SetPrototype(sloppy_function_map, empty_function);
573   Map::SetPrototype(sloppy_function_without_prototype_map, empty_function);
574   Map::SetPrototype(sloppy_function_map_writable_prototype_, empty_function);
575
576   // ES6 draft 03-17-2015, section 8.2.2 step 12
577   AddRestrictedFunctionProperties(empty_function_map);
578
579   return empty_function;
580 }
581
582
583 void Genesis::SetStrictFunctionInstanceDescriptor(Handle<Map> map,
584                                                   FunctionMode function_mode) {
585   int size = IsFunctionModeWithPrototype(function_mode) ? 5 : 4;
586   Map::EnsureDescriptorSlack(map, size);
587
588   PropertyAttributes rw_attribs =
589       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
590   PropertyAttributes ro_attribs =
591       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
592   PropertyAttributes roc_attribs =
593       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
594
595   if (function_mode == BOUND_FUNCTION) {
596     {  // Add length.
597       Handle<String> length_string = isolate()->factory()->length_string();
598       DataDescriptor d(length_string, 0, roc_attribs, Representation::Tagged());
599       map->AppendDescriptor(&d);
600     }
601     {  // Add name.
602       Handle<String> name_string = isolate()->factory()->name_string();
603       DataDescriptor d(name_string, 1, roc_attribs, Representation::Tagged());
604       map->AppendDescriptor(&d);
605     }
606   } else {
607     DCHECK(function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ||
608            function_mode == FUNCTION_WITH_READONLY_PROTOTYPE ||
609            function_mode == FUNCTION_WITHOUT_PROTOTYPE);
610     {  // Add length.
611       Handle<AccessorInfo> length =
612           Accessors::FunctionLengthInfo(isolate(), roc_attribs);
613       AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
614                                    length, roc_attribs);
615       map->AppendDescriptor(&d);
616     }
617     {  // Add name.
618       Handle<AccessorInfo> name =
619           Accessors::FunctionNameInfo(isolate(), roc_attribs);
620       AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
621                                    roc_attribs);
622       map->AppendDescriptor(&d);
623     }
624   }
625   if (IsFunctionModeWithPrototype(function_mode)) {
626     // Add prototype.
627     PropertyAttributes attribs =
628         function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ? rw_attribs
629                                                            : ro_attribs;
630     Handle<AccessorInfo> prototype =
631         Accessors::FunctionPrototypeInfo(isolate(), attribs);
632     AccessorConstantDescriptor d(Handle<Name>(Name::cast(prototype->name())),
633                                  prototype, attribs);
634     map->AppendDescriptor(&d);
635   }
636 }
637
638
639 void Genesis::SetStrongFunctionInstanceDescriptor(Handle<Map> map) {
640   Map::EnsureDescriptorSlack(map, 2);
641
642   PropertyAttributes ro_attribs =
643       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
644
645   Handle<AccessorInfo> length =
646       Accessors::FunctionLengthInfo(isolate(), ro_attribs);
647   {  // Add length.
648     AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
649                                  length, ro_attribs);
650     map->AppendDescriptor(&d);
651   }
652   Handle<AccessorInfo> name =
653       Accessors::FunctionNameInfo(isolate(), ro_attribs);
654   {  // Add name.
655     AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
656                                  ro_attribs);
657     map->AppendDescriptor(&d);
658   }
659 }
660
661
662 // Creates the %ThrowTypeError% function.
663 Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic(
664     Builtins::Name builtin_name) {
665   Handle<String> name =
666       factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("ThrowTypeError"));
667   Handle<Code> code(isolate()->builtins()->builtin(builtin_name));
668   Handle<JSFunction> function =
669       factory()->NewFunctionWithoutPrototype(name, code);
670   function->set_map(native_context()->sloppy_function_map());
671   function->shared()->DontAdaptArguments();
672
673   // %ThrowTypeError% must not have a name property.
674   JSReceiver::DeleteProperty(function, factory()->name_string()).Assert();
675
676   // length needs to be non configurable.
677   Handle<Object> value(Smi::FromInt(function->shared()->length()), isolate());
678   JSObject::SetOwnPropertyIgnoreAttributes(
679       function, factory()->length_string(), value,
680       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
681       .Assert();
682
683   JSObject::PreventExtensions(function).Assert();
684
685   return function;
686 }
687
688
689 // ECMAScript 5th Edition, 13.2.3
690 Handle<JSFunction> Genesis::GetRestrictedFunctionPropertiesThrower() {
691   if (restricted_function_properties_thrower_.is_null()) {
692     restricted_function_properties_thrower_ = GetThrowTypeErrorIntrinsic(
693         Builtins::kRestrictedFunctionPropertiesThrower);
694   }
695   return restricted_function_properties_thrower_;
696 }
697
698
699 Handle<JSFunction> Genesis::GetStrictArgumentsPoisonFunction() {
700   if (strict_poison_function_.is_null()) {
701     strict_poison_function_ = GetThrowTypeErrorIntrinsic(
702         Builtins::kRestrictedStrictArgumentsPropertiesThrower);
703   }
704   return strict_poison_function_;
705 }
706
707
708 Handle<Map> Genesis::CreateStrictFunctionMap(
709     FunctionMode function_mode, Handle<JSFunction> empty_function) {
710   Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
711   SetStrictFunctionInstanceDescriptor(map, function_mode);
712   map->set_function_with_prototype(IsFunctionModeWithPrototype(function_mode));
713   Map::SetPrototype(map, empty_function);
714   return map;
715 }
716
717
718 Handle<Map> Genesis::CreateStrongFunctionMap(
719     Handle<JSFunction> empty_function, bool is_constructor) {
720   Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
721   SetStrongFunctionInstanceDescriptor(map);
722   map->set_function_with_prototype(is_constructor);
723   Map::SetPrototype(map, empty_function);
724   map->set_is_extensible(is_constructor);
725   map->set_is_strong();
726   return map;
727 }
728
729
730 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
731   // Allocate map for the prototype-less strict mode instances.
732   Handle<Map> strict_function_without_prototype_map =
733       CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
734   native_context()->set_strict_function_without_prototype_map(
735       *strict_function_without_prototype_map);
736
737   // Allocate map for the strict mode functions. This map is temporary, used
738   // only for processing of builtins.
739   // Later the map is replaced with writable prototype map, allocated below.
740   Handle<Map> strict_function_map =
741       CreateStrictFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
742   native_context()->set_strict_function_map(*strict_function_map);
743
744   // The final map for the strict mode functions. Writeable prototype.
745   // This map is installed in MakeFunctionInstancePrototypeWritable.
746   strict_function_map_writable_prototype_ =
747       CreateStrictFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE, empty);
748
749   // Special map for bound functions.
750   Handle<Map> bound_function_map =
751       CreateStrictFunctionMap(BOUND_FUNCTION, empty);
752   native_context()->set_bound_function_map(*bound_function_map);
753 }
754
755
756 void Genesis::CreateStrongModeFunctionMaps(Handle<JSFunction> empty) {
757   // Allocate map for strong mode instances, which never have prototypes.
758   Handle<Map> strong_function_map = CreateStrongFunctionMap(empty, false);
759   native_context()->set_strong_function_map(*strong_function_map);
760   // Constructors do, though.
761   Handle<Map> strong_constructor_map = CreateStrongFunctionMap(empty, true);
762   native_context()->set_strong_constructor_map(*strong_constructor_map);
763 }
764
765
766 static void ReplaceAccessors(Handle<Map> map,
767                              Handle<String> name,
768                              PropertyAttributes attributes,
769                              Handle<AccessorPair> accessor_pair) {
770   DescriptorArray* descriptors = map->instance_descriptors();
771   int idx = descriptors->SearchWithCache(*name, *map);
772   AccessorConstantDescriptor descriptor(name, accessor_pair, attributes);
773   descriptors->Replace(idx, &descriptor);
774 }
775
776
777 void Genesis::AddRestrictedFunctionProperties(Handle<Map> map) {
778   PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
779   Handle<JSFunction> thrower = GetRestrictedFunctionPropertiesThrower();
780   Handle<AccessorPair> accessors = factory()->NewAccessorPair();
781   accessors->set_getter(*thrower);
782   accessors->set_setter(*thrower);
783
784   ReplaceAccessors(map, factory()->arguments_string(), rw_attribs, accessors);
785   ReplaceAccessors(map, factory()->caller_string(), rw_attribs, accessors);
786 }
787
788
789 static void AddToWeakNativeContextList(Context* context) {
790   DCHECK(context->IsNativeContext());
791   Heap* heap = context->GetIsolate()->heap();
792 #ifdef DEBUG
793   { // NOLINT
794     DCHECK(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
795     // Check that context is not in the list yet.
796     for (Object* current = heap->native_contexts_list();
797          !current->IsUndefined();
798          current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
799       DCHECK(current != context);
800     }
801   }
802 #endif
803   context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list(),
804                UPDATE_WEAK_WRITE_BARRIER);
805   heap->set_native_contexts_list(context);
806 }
807
808
809 void Genesis::CreateRoots() {
810   // Allocate the native context FixedArray first and then patch the
811   // closure and extension object later (we need the empty function
812   // and the global object, but in order to create those, we need the
813   // native context).
814   native_context_ = factory()->NewNativeContext();
815   AddToWeakNativeContextList(*native_context());
816   isolate()->set_context(*native_context());
817
818   // Allocate the message listeners object.
819   {
820     v8::NeanderArray listeners(isolate());
821     native_context()->set_message_listeners(*listeners.value());
822   }
823 }
824
825
826 void Genesis::InstallGlobalThisBinding() {
827   Handle<ScriptContextTable> script_contexts(
828       native_context()->script_context_table());
829   Handle<ScopeInfo> scope_info = ScopeInfo::CreateGlobalThisBinding(isolate());
830   Handle<JSFunction> closure(native_context()->closure());
831   Handle<Context> context = factory()->NewScriptContext(closure, scope_info);
832
833   // Go ahead and hook it up while we're at it.
834   int slot = scope_info->ReceiverContextSlotIndex();
835   DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
836   context->set(slot, native_context()->global_proxy());
837
838   Handle<ScriptContextTable> new_script_contexts =
839       ScriptContextTable::Extend(script_contexts, context);
840   native_context()->set_script_context_table(*new_script_contexts);
841 }
842
843
844 void Genesis::HookUpGlobalThisBinding(Handle<FixedArray> outdated_contexts) {
845   // One of these contexts should be the one that declares the global "this"
846   // binding.
847   for (int i = 0; i < outdated_contexts->length(); ++i) {
848     Context* context = Context::cast(outdated_contexts->get(i));
849     if (context->IsScriptContext()) {
850       ScopeInfo* scope_info = context->scope_info();
851       int slot = scope_info->ReceiverContextSlotIndex();
852       if (slot >= 0) {
853         DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
854         context->set(slot, native_context()->global_proxy());
855       }
856     }
857   }
858 }
859
860
861 Handle<GlobalObject> Genesis::CreateNewGlobals(
862     v8::Local<v8::ObjectTemplate> global_proxy_template,
863     Handle<JSGlobalProxy> global_proxy) {
864   // The argument global_proxy_template aka data is an ObjectTemplateInfo.
865   // It has a constructor pointer that points at global_constructor which is a
866   // FunctionTemplateInfo.
867   // The global_proxy_constructor is used to (re)initialize the
868   // global_proxy. The global_proxy_constructor also has a prototype_template
869   // pointer that points at js_global_object_template which is an
870   // ObjectTemplateInfo.
871   // That in turn has a constructor pointer that points at
872   // js_global_object_constructor which is a FunctionTemplateInfo.
873   // js_global_object_constructor is used to make js_global_object_function
874   // js_global_object_function is used to make the new global_object.
875   //
876   // --- G l o b a l ---
877   // Step 1: Create a fresh JSGlobalObject.
878   Handle<JSFunction> js_global_object_function;
879   Handle<ObjectTemplateInfo> js_global_object_template;
880   if (!global_proxy_template.IsEmpty()) {
881     // Get prototype template of the global_proxy_template.
882     Handle<ObjectTemplateInfo> data =
883         v8::Utils::OpenHandle(*global_proxy_template);
884     Handle<FunctionTemplateInfo> global_constructor =
885         Handle<FunctionTemplateInfo>(
886             FunctionTemplateInfo::cast(data->constructor()));
887     Handle<Object> proto_template(global_constructor->prototype_template(),
888                                   isolate());
889     if (!proto_template->IsUndefined()) {
890       js_global_object_template =
891           Handle<ObjectTemplateInfo>::cast(proto_template);
892     }
893   }
894
895   if (js_global_object_template.is_null()) {
896     Handle<String> name = Handle<String>(heap()->empty_string());
897     Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
898         Builtins::kIllegal));
899     Handle<JSObject> prototype =
900         factory()->NewFunctionPrototype(isolate()->object_function());
901     js_global_object_function = factory()->NewFunction(
902         name, code, prototype, JS_GLOBAL_OBJECT_TYPE, JSGlobalObject::kSize);
903 #ifdef DEBUG
904     LookupIterator it(prototype, factory()->constructor_string(),
905                       LookupIterator::OWN_SKIP_INTERCEPTOR);
906     Handle<Object> value = JSReceiver::GetProperty(&it).ToHandleChecked();
907     DCHECK(it.IsFound());
908     DCHECK_EQ(*isolate()->object_function(), *value);
909 #endif
910   } else {
911     Handle<FunctionTemplateInfo> js_global_object_constructor(
912         FunctionTemplateInfo::cast(js_global_object_template->constructor()));
913     js_global_object_function = ApiNatives::CreateApiFunction(
914         isolate(), js_global_object_constructor, factory()->the_hole_value(),
915         ApiNatives::GlobalObjectType);
916   }
917
918   js_global_object_function->initial_map()->set_is_prototype_map(true);
919   js_global_object_function->initial_map()->set_is_hidden_prototype();
920   js_global_object_function->initial_map()->set_dictionary_map(true);
921   Handle<GlobalObject> global_object =
922       factory()->NewGlobalObject(js_global_object_function);
923
924   // Step 2: (re)initialize the global proxy object.
925   Handle<JSFunction> global_proxy_function;
926   if (global_proxy_template.IsEmpty()) {
927     Handle<String> name = Handle<String>(heap()->empty_string());
928     Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
929         Builtins::kIllegal));
930     global_proxy_function = factory()->NewFunction(
931         name, code, JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
932   } else {
933     Handle<ObjectTemplateInfo> data =
934         v8::Utils::OpenHandle(*global_proxy_template);
935     Handle<FunctionTemplateInfo> global_constructor(
936             FunctionTemplateInfo::cast(data->constructor()));
937     global_proxy_function = ApiNatives::CreateApiFunction(
938         isolate(), global_constructor, factory()->the_hole_value(),
939         ApiNatives::GlobalProxyType);
940   }
941
942   Handle<String> global_name = factory()->global_string();
943   global_proxy_function->shared()->set_instance_class_name(*global_name);
944   global_proxy_function->initial_map()->set_is_access_check_needed(true);
945
946   // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
947   // Return the global proxy.
948
949   factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
950   return global_object;
951 }
952
953
954 void Genesis::HookUpGlobalProxy(Handle<GlobalObject> global_object,
955                                 Handle<JSGlobalProxy> global_proxy) {
956   // Set the native context for the global object.
957   global_object->set_native_context(*native_context());
958   global_object->set_global_proxy(*global_proxy);
959   global_proxy->set_native_context(*native_context());
960   // If we deserialized the context, the global proxy is already
961   // correctly set up. Otherwise it's undefined.
962   DCHECK(native_context()->get(Context::GLOBAL_PROXY_INDEX)->IsUndefined() ||
963          native_context()->global_proxy() == *global_proxy);
964   native_context()->set_global_proxy(*global_proxy);
965 }
966
967
968 void Genesis::HookUpGlobalObject(Handle<GlobalObject> global_object,
969                                  Handle<FixedArray> outdated_contexts) {
970   Handle<GlobalObject> global_object_from_snapshot(
971       GlobalObject::cast(native_context()->extension()));
972   Handle<JSBuiltinsObject> builtins_global(native_context()->builtins());
973   native_context()->set_extension(*global_object);
974   native_context()->set_security_token(*global_object);
975
976   // Replace outdated global objects in deserialized contexts.
977   for (int i = 0; i < outdated_contexts->length(); ++i) {
978     Context* context = Context::cast(outdated_contexts->get(i));
979     // Assert that there is only one native context.
980     DCHECK(!context->IsNativeContext() || context == *native_context());
981     DCHECK_EQ(context->global_object(), *global_object_from_snapshot);
982     context->set_global_object(*global_object);
983   }
984
985   static const PropertyAttributes attributes =
986       static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
987   JSObject::SetOwnPropertyIgnoreAttributes(builtins_global,
988                                            factory()->global_string(),
989                                            global_object, attributes).Assert();
990   // Set up the reference from the global object to the builtins object.
991   JSGlobalObject::cast(*global_object)->set_builtins(*builtins_global);
992   TransferNamedProperties(global_object_from_snapshot, global_object);
993   TransferIndexedProperties(global_object_from_snapshot, global_object);
994 }
995
996
997 // This is only called if we are not using snapshots.  The equivalent
998 // work in the snapshot case is done in HookUpGlobalObject.
999 void Genesis::InitializeGlobal(Handle<GlobalObject> global_object,
1000                                Handle<JSFunction> empty_function,
1001                                ContextType context_type) {
1002   // --- N a t i v e   C o n t e x t ---
1003   // Use the empty function as closure (no scope info).
1004   native_context()->set_closure(*empty_function);
1005   native_context()->set_previous(NULL);
1006   // Set extension and global object.
1007   native_context()->set_extension(*global_object);
1008   native_context()->set_global_object(*global_object);
1009   // Security setup: Set the security token of the native context to the global
1010   // object. This makes the security check between two different contexts fail
1011   // by default even in case of global object reinitialization.
1012   native_context()->set_security_token(*global_object);
1013
1014   Isolate* isolate = global_object->GetIsolate();
1015   Factory* factory = isolate->factory();
1016   Heap* heap = isolate->heap();
1017
1018   Handle<ScriptContextTable> script_context_table =
1019       factory->NewScriptContextTable();
1020   native_context()->set_script_context_table(*script_context_table);
1021   InstallGlobalThisBinding();
1022
1023   Handle<String> object_name = factory->Object_string();
1024   JSObject::AddProperty(
1025       global_object, object_name, isolate->object_function(), DONT_ENUM);
1026
1027   Handle<JSObject> global(native_context()->global_object());
1028
1029   // Install global Function object
1030   InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
1031                   empty_function, Builtins::kIllegal);
1032
1033   {  // --- A r r a y ---
1034     Handle<JSFunction> array_function =
1035         InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
1036                         isolate->initial_object_prototype(),
1037                         Builtins::kArrayCode);
1038     array_function->shared()->DontAdaptArguments();
1039     array_function->shared()->set_function_data(Smi::FromInt(kArrayCode));
1040
1041     // This seems a bit hackish, but we need to make sure Array.length
1042     // is 1.
1043     array_function->shared()->set_length(1);
1044
1045     Handle<Map> initial_map(array_function->initial_map());
1046
1047     // This assert protects an optimization in
1048     // HGraphBuilder::JSArrayBuilder::EmitMapCode()
1049     DCHECK(initial_map->elements_kind() == GetInitialFastElementsKind());
1050     Map::EnsureDescriptorSlack(initial_map, 1);
1051
1052     PropertyAttributes attribs = static_cast<PropertyAttributes>(
1053         DONT_ENUM | DONT_DELETE);
1054
1055     Handle<AccessorInfo> array_length =
1056         Accessors::ArrayLengthInfo(isolate, attribs);
1057     {  // Add length.
1058       AccessorConstantDescriptor d(
1059           Handle<Name>(Name::cast(array_length->name())), array_length,
1060           attribs);
1061       initial_map->AppendDescriptor(&d);
1062     }
1063
1064     // array_function is used internally. JS code creating array object should
1065     // search for the 'Array' property on the global object and use that one
1066     // as the constructor. 'Array' property on a global object can be
1067     // overwritten by JS code.
1068     native_context()->set_array_function(*array_function);
1069
1070     // Cache the array maps, needed by ArrayConstructorStub
1071     CacheInitialJSArrayMaps(native_context(), initial_map);
1072     ArrayConstructorStub array_constructor_stub(isolate);
1073     Handle<Code> code = array_constructor_stub.GetCode();
1074     array_function->shared()->set_construct_stub(*code);
1075
1076     Handle<Map> initial_strong_map =
1077         Map::Copy(initial_map, "SetInstancePrototype");
1078     initial_strong_map->set_is_strong();
1079     CacheInitialJSArrayMaps(native_context(), initial_strong_map);
1080   }
1081
1082   {  // --- N u m b e r ---
1083     Handle<JSFunction> number_fun =
1084         InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
1085                         isolate->initial_object_prototype(),
1086                         Builtins::kIllegal);
1087     native_context()->set_number_function(*number_fun);
1088   }
1089
1090   {  // --- B o o l e a n ---
1091     Handle<JSFunction> boolean_fun =
1092         InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
1093                         isolate->initial_object_prototype(),
1094                         Builtins::kIllegal);
1095     native_context()->set_boolean_function(*boolean_fun);
1096   }
1097
1098   {  // --- S t r i n g ---
1099     Handle<JSFunction> string_fun =
1100         InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
1101                         isolate->initial_object_prototype(),
1102                         Builtins::kIllegal);
1103     string_fun->shared()->set_construct_stub(
1104         isolate->builtins()->builtin(Builtins::kStringConstructCode));
1105     native_context()->set_string_function(*string_fun);
1106
1107     Handle<Map> string_map =
1108         Handle<Map>(native_context()->string_function()->initial_map());
1109     Map::EnsureDescriptorSlack(string_map, 1);
1110
1111     PropertyAttributes attribs = static_cast<PropertyAttributes>(
1112         DONT_ENUM | DONT_DELETE | READ_ONLY);
1113     Handle<AccessorInfo> string_length(
1114         Accessors::StringLengthInfo(isolate, attribs));
1115
1116     {  // Add length.
1117       AccessorConstantDescriptor d(factory->length_string(), string_length,
1118                                    attribs);
1119       string_map->AppendDescriptor(&d);
1120     }
1121   }
1122
1123   {
1124     // --- S y m b o l ---
1125     Handle<JSFunction> symbol_fun = InstallFunction(
1126         global, "Symbol", JS_VALUE_TYPE, JSValue::kSize,
1127         isolate->initial_object_prototype(), Builtins::kIllegal);
1128     native_context()->set_symbol_function(*symbol_fun);
1129   }
1130
1131   {  // --- D a t e ---
1132     // Builtin functions for Date.prototype.
1133     InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize,
1134                     isolate->initial_object_prototype(), Builtins::kIllegal);
1135   }
1136
1137
1138   {  // -- R e g E x p
1139     // Builtin functions for RegExp.prototype.
1140     Handle<JSFunction> regexp_fun =
1141         InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
1142                         isolate->initial_object_prototype(),
1143                         Builtins::kIllegal);
1144     native_context()->set_regexp_function(*regexp_fun);
1145
1146     DCHECK(regexp_fun->has_initial_map());
1147     Handle<Map> initial_map(regexp_fun->initial_map());
1148
1149     DCHECK_EQ(0, initial_map->GetInObjectProperties());
1150
1151     PropertyAttributes final =
1152         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1153     Map::EnsureDescriptorSlack(initial_map, 5);
1154
1155     {
1156       // ECMA-262, section 15.10.7.1.
1157       DataDescriptor field(factory->source_string(),
1158                            JSRegExp::kSourceFieldIndex, final,
1159                            Representation::Tagged());
1160       initial_map->AppendDescriptor(&field);
1161     }
1162     {
1163       // ECMA-262, section 15.10.7.2.
1164       DataDescriptor field(factory->global_string(),
1165                            JSRegExp::kGlobalFieldIndex, final,
1166                            Representation::Tagged());
1167       initial_map->AppendDescriptor(&field);
1168     }
1169     {
1170       // ECMA-262, section 15.10.7.3.
1171       DataDescriptor field(factory->ignore_case_string(),
1172                            JSRegExp::kIgnoreCaseFieldIndex, final,
1173                            Representation::Tagged());
1174       initial_map->AppendDescriptor(&field);
1175     }
1176     {
1177       // ECMA-262, section 15.10.7.4.
1178       DataDescriptor field(factory->multiline_string(),
1179                            JSRegExp::kMultilineFieldIndex, final,
1180                            Representation::Tagged());
1181       initial_map->AppendDescriptor(&field);
1182     }
1183     {
1184       // ECMA-262, section 15.10.7.5.
1185       PropertyAttributes writable =
1186           static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
1187       DataDescriptor field(factory->last_index_string(),
1188                            JSRegExp::kLastIndexFieldIndex, writable,
1189                            Representation::Tagged());
1190       initial_map->AppendDescriptor(&field);
1191     }
1192
1193     static const int num_fields = JSRegExp::kInObjectFieldCount;
1194     initial_map->SetInObjectProperties(num_fields);
1195     initial_map->set_unused_property_fields(0);
1196     initial_map->set_instance_size(initial_map->instance_size() +
1197                                    num_fields * kPointerSize);
1198
1199     // RegExp prototype object is itself a RegExp.
1200     Handle<Map> proto_map = Map::Copy(initial_map, "RegExpPrototype");
1201     DCHECK(proto_map->prototype() == *isolate->initial_object_prototype());
1202     Handle<JSObject> proto = factory->NewJSObjectFromMap(proto_map);
1203     proto->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex,
1204                                  heap->query_colon_string());
1205     proto->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex,
1206                                  heap->false_value());
1207     proto->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex,
1208                                  heap->false_value());
1209     proto->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex,
1210                                  heap->false_value());
1211     proto->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
1212                                  Smi::FromInt(0),
1213                                  SKIP_WRITE_BARRIER);  // It's a Smi.
1214     proto_map->set_is_prototype_map(true);
1215     Map::SetPrototype(initial_map, proto);
1216     factory->SetRegExpIrregexpData(Handle<JSRegExp>::cast(proto),
1217                                    JSRegExp::IRREGEXP, factory->empty_string(),
1218                                    JSRegExp::Flags(0), 0);
1219   }
1220
1221   // Initialize the embedder data slot.
1222   Handle<FixedArray> embedder_data = factory->NewFixedArray(3);
1223   native_context()->set_embedder_data(*embedder_data);
1224
1225   if (context_type == THIN_CONTEXT) return;
1226
1227   {  // -- J S O N
1228     Handle<String> name = factory->InternalizeUtf8String("JSON");
1229     Handle<JSFunction> cons = factory->NewFunction(name);
1230     JSFunction::SetInstancePrototype(cons,
1231         Handle<Object>(native_context()->initial_object_prototype(), isolate));
1232     cons->SetInstanceClassName(*name);
1233     Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1234     DCHECK(json_object->IsJSObject());
1235     JSObject::AddProperty(global, name, json_object, DONT_ENUM);
1236   }
1237
1238   {  // -- M a t h
1239     Handle<String> name = factory->InternalizeUtf8String("Math");
1240     Handle<JSFunction> cons = factory->NewFunction(name);
1241     JSFunction::SetInstancePrototype(
1242         cons,
1243         Handle<Object>(native_context()->initial_object_prototype(), isolate));
1244     cons->SetInstanceClassName(*name);
1245     Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1246     DCHECK(json_object->IsJSObject());
1247     JSObject::AddProperty(global, name, json_object, DONT_ENUM);
1248   }
1249
1250   {  // -- A r r a y B u f f e r
1251     Handle<JSFunction> array_buffer_fun =
1252         InstallFunction(
1253             global, "ArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1254             JSArrayBuffer::kSizeWithInternalFields,
1255             isolate->initial_object_prototype(),
1256             Builtins::kIllegal);
1257     native_context()->set_array_buffer_fun(*array_buffer_fun);
1258   }
1259
1260   {  // -- T y p e d A r r a y s
1261 #define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype, size)   \
1262   {                                                          \
1263     Handle<JSFunction> fun;                                  \
1264     InstallTypedArray(#Type "Array", TYPE##_ELEMENTS, &fun); \
1265     native_context()->set_##type##_array_fun(*fun);          \
1266   }
1267     TYPED_ARRAYS(INSTALL_TYPED_ARRAY)
1268 #undef INSTALL_TYPED_ARRAY
1269
1270     Handle<JSFunction> data_view_fun =
1271         InstallFunction(
1272             global, "DataView", JS_DATA_VIEW_TYPE,
1273             JSDataView::kSizeWithInternalFields,
1274             isolate->initial_object_prototype(),
1275             Builtins::kIllegal);
1276     native_context()->set_data_view_fun(*data_view_fun);
1277   }
1278
1279   {  // -- M a p
1280     Handle<JSFunction> js_map_fun = InstallFunction(
1281         global, "Map", JS_MAP_TYPE, JSMap::kSize,
1282         isolate->initial_object_prototype(), Builtins::kIllegal);
1283     native_context()->set_js_map_fun(*js_map_fun);
1284   }
1285
1286   {  // -- S e t
1287     Handle<JSFunction> js_set_fun = InstallFunction(
1288         global, "Set", JS_SET_TYPE, JSSet::kSize,
1289         isolate->initial_object_prototype(), Builtins::kIllegal);
1290     native_context()->set_js_set_fun(*js_set_fun);
1291   }
1292
1293   {  // Set up the iterator result object
1294     STATIC_ASSERT(JSGeneratorObject::kResultPropertyCount == 2);
1295     Handle<JSFunction> object_function(native_context()->object_function());
1296     Handle<Map> iterator_result_map =
1297         Map::Create(isolate, JSGeneratorObject::kResultPropertyCount);
1298     DCHECK_EQ(JSGeneratorObject::kResultSize,
1299               iterator_result_map->instance_size());
1300     DCHECK_EQ(JSGeneratorObject::kResultPropertyCount,
1301               iterator_result_map->GetInObjectProperties());
1302     Map::EnsureDescriptorSlack(iterator_result_map,
1303                                JSGeneratorObject::kResultPropertyCount);
1304
1305     DataDescriptor value_descr(factory->value_string(),
1306                                JSGeneratorObject::kResultValuePropertyIndex,
1307                                NONE, Representation::Tagged());
1308     iterator_result_map->AppendDescriptor(&value_descr);
1309
1310     DataDescriptor done_descr(factory->done_string(),
1311                               JSGeneratorObject::kResultDonePropertyIndex, NONE,
1312                               Representation::Tagged());
1313     iterator_result_map->AppendDescriptor(&done_descr);
1314
1315     iterator_result_map->set_unused_property_fields(0);
1316     DCHECK_EQ(JSGeneratorObject::kResultSize,
1317               iterator_result_map->instance_size());
1318     native_context()->set_iterator_result_map(*iterator_result_map);
1319   }
1320
1321   // -- W e a k M a p
1322   InstallFunction(global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
1323                   isolate->initial_object_prototype(), Builtins::kIllegal);
1324   // -- W e a k S e t
1325   InstallFunction(global, "WeakSet", JS_WEAK_SET_TYPE, JSWeakSet::kSize,
1326                   isolate->initial_object_prototype(), Builtins::kIllegal);
1327
1328   {  // --- sloppy arguments map
1329     // Make sure we can recognize argument objects at runtime.
1330     // This is done by introducing an anonymous function with
1331     // class_name equals 'Arguments'.
1332     Handle<String> arguments_string = factory->Arguments_string();
1333     Handle<Code> code(isolate->builtins()->builtin(Builtins::kIllegal));
1334     Handle<JSFunction> function = factory->NewFunctionWithoutPrototype(
1335         arguments_string, code);
1336     function->shared()->set_instance_class_name(*arguments_string);
1337
1338     Handle<Map> map =
1339         factory->NewMap(JS_OBJECT_TYPE, Heap::kSloppyArgumentsObjectSize);
1340     // Create the descriptor array for the arguments object.
1341     Map::EnsureDescriptorSlack(map, 2);
1342
1343     {  // length
1344       DataDescriptor d(factory->length_string(), Heap::kArgumentsLengthIndex,
1345                        DONT_ENUM, Representation::Tagged());
1346       map->AppendDescriptor(&d);
1347     }
1348     {  // callee
1349       DataDescriptor d(factory->callee_string(), Heap::kArgumentsCalleeIndex,
1350                        DONT_ENUM, Representation::Tagged());
1351       map->AppendDescriptor(&d);
1352     }
1353     // @@iterator method is added later.
1354
1355     map->set_function_with_prototype(true);
1356     map->SetInObjectProperties(2);
1357     native_context()->set_sloppy_arguments_map(*map);
1358
1359     DCHECK(!function->has_initial_map());
1360     JSFunction::SetInitialMap(function, map,
1361                               isolate->initial_object_prototype());
1362
1363     DCHECK(map->GetInObjectProperties() > Heap::kArgumentsCalleeIndex);
1364     DCHECK(map->GetInObjectProperties() > Heap::kArgumentsLengthIndex);
1365     DCHECK(!map->is_dictionary_map());
1366     DCHECK(IsFastObjectElementsKind(map->elements_kind()));
1367   }
1368
1369   {  // --- fast and slow aliased arguments map
1370     Handle<Map> map = isolate->sloppy_arguments_map();
1371     map = Map::Copy(map, "FastAliasedArguments");
1372     map->set_elements_kind(FAST_SLOPPY_ARGUMENTS_ELEMENTS);
1373     DCHECK_EQ(2, map->GetInObjectProperties());
1374     native_context()->set_fast_aliased_arguments_map(*map);
1375
1376     map = Map::Copy(map, "SlowAliasedArguments");
1377     map->set_elements_kind(SLOW_SLOPPY_ARGUMENTS_ELEMENTS);
1378     DCHECK_EQ(2, map->GetInObjectProperties());
1379     native_context()->set_slow_aliased_arguments_map(*map);
1380   }
1381
1382   {  // --- strict mode arguments map
1383     const PropertyAttributes attributes =
1384       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1385
1386     // Create the ThrowTypeError functions.
1387     Handle<AccessorPair> callee = factory->NewAccessorPair();
1388     Handle<AccessorPair> caller = factory->NewAccessorPair();
1389
1390     Handle<JSFunction> poison = GetStrictArgumentsPoisonFunction();
1391
1392     // Install the ThrowTypeError functions.
1393     callee->set_getter(*poison);
1394     callee->set_setter(*poison);
1395     caller->set_getter(*poison);
1396     caller->set_setter(*poison);
1397
1398     // Create the map. Allocate one in-object field for length.
1399     Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE,
1400                                       Heap::kStrictArgumentsObjectSize);
1401     // Create the descriptor array for the arguments object.
1402     Map::EnsureDescriptorSlack(map, 3);
1403
1404     {  // length
1405       DataDescriptor d(factory->length_string(), Heap::kArgumentsLengthIndex,
1406                        DONT_ENUM, Representation::Tagged());
1407       map->AppendDescriptor(&d);
1408     }
1409     {  // callee
1410       AccessorConstantDescriptor d(factory->callee_string(), callee,
1411                                    attributes);
1412       map->AppendDescriptor(&d);
1413     }
1414     {  // caller
1415       AccessorConstantDescriptor d(factory->caller_string(), caller,
1416                                    attributes);
1417       map->AppendDescriptor(&d);
1418     }
1419     // @@iterator method is added later.
1420
1421     map->set_function_with_prototype(true);
1422     DCHECK_EQ(native_context()->object_function()->prototype(),
1423               *isolate->initial_object_prototype());
1424     Map::SetPrototype(map, isolate->initial_object_prototype());
1425     map->SetInObjectProperties(1);
1426
1427     // Copy constructor from the sloppy arguments boilerplate.
1428     map->SetConstructor(
1429         native_context()->sloppy_arguments_map()->GetConstructor());
1430
1431     native_context()->set_strict_arguments_map(*map);
1432
1433     DCHECK(map->GetInObjectProperties() > Heap::kArgumentsLengthIndex);
1434     DCHECK(!map->is_dictionary_map());
1435     DCHECK(IsFastObjectElementsKind(map->elements_kind()));
1436   }
1437
1438   {  // --- context extension
1439     // Create a function for the context extension objects.
1440     Handle<Code> code = Handle<Code>(
1441         isolate->builtins()->builtin(Builtins::kIllegal));
1442     Handle<JSFunction> context_extension_fun = factory->NewFunction(
1443         factory->empty_string(), code, JS_CONTEXT_EXTENSION_OBJECT_TYPE,
1444         JSObject::kHeaderSize);
1445
1446     Handle<String> name = factory->InternalizeOneByteString(
1447         STATIC_CHAR_VECTOR("context_extension"));
1448     context_extension_fun->shared()->set_instance_class_name(*name);
1449     native_context()->set_context_extension_function(*context_extension_fun);
1450   }
1451
1452
1453   {
1454     // Set up the call-as-function delegate.
1455     Handle<Code> code =
1456         Handle<Code>(isolate->builtins()->builtin(
1457             Builtins::kHandleApiCallAsFunction));
1458     Handle<JSFunction> delegate = factory->NewFunction(
1459         factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1460     native_context()->set_call_as_function_delegate(*delegate);
1461     delegate->shared()->DontAdaptArguments();
1462   }
1463
1464   {
1465     // Set up the call-as-constructor delegate.
1466     Handle<Code> code =
1467         Handle<Code>(isolate->builtins()->builtin(
1468             Builtins::kHandleApiCallAsConstructor));
1469     Handle<JSFunction> delegate = factory->NewFunction(
1470         factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1471     native_context()->set_call_as_constructor_delegate(*delegate);
1472     delegate->shared()->DontAdaptArguments();
1473   }
1474 }
1475
1476
1477 void Genesis::InstallTypedArray(const char* name, ElementsKind elements_kind,
1478                                 Handle<JSFunction>* fun) {
1479   Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1480   Handle<JSFunction> result = InstallFunction(
1481       global, name, JS_TYPED_ARRAY_TYPE, JSTypedArray::kSize,
1482       isolate()->initial_object_prototype(), Builtins::kIllegal);
1483
1484   Handle<Map> initial_map = isolate()->factory()->NewMap(
1485       JS_TYPED_ARRAY_TYPE,
1486       JSTypedArray::kSizeWithInternalFields,
1487       elements_kind);
1488   JSFunction::SetInitialMap(result, initial_map,
1489                             handle(initial_map->prototype(), isolate()));
1490   *fun = result;
1491 }
1492
1493
1494 void Genesis::InitializeExperimentalGlobal() {
1495 #define FEATURE_INITIALIZE_GLOBAL(id, descr) InitializeGlobal_##id();
1496
1497   HARMONY_INPROGRESS(FEATURE_INITIALIZE_GLOBAL)
1498   HARMONY_STAGED(FEATURE_INITIALIZE_GLOBAL)
1499   HARMONY_SHIPPING(FEATURE_INITIALIZE_GLOBAL)
1500 #undef FEATURE_INITIALIZE_GLOBAL
1501 }
1502
1503
1504 bool Bootstrapper::CompileBuiltin(Isolate* isolate, int index) {
1505   Vector<const char> name = Natives::GetScriptName(index);
1506   Handle<String> source_code =
1507       isolate->bootstrapper()->SourceLookup<Natives>(index);
1508   Handle<Object> global = isolate->global_object();
1509   Handle<Object> utils = isolate->natives_utils_object();
1510   Handle<Object> args[] = {global, utils};
1511
1512   return Bootstrapper::CompileNative(
1513       isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1514       source_code, arraysize(args), args);
1515 }
1516
1517
1518 bool Bootstrapper::CompileExperimentalBuiltin(Isolate* isolate, int index) {
1519   HandleScope scope(isolate);
1520   Vector<const char> name = ExperimentalNatives::GetScriptName(index);
1521   Handle<String> source_code =
1522       isolate->bootstrapper()->SourceLookup<ExperimentalNatives>(index);
1523   Handle<Object> global = isolate->global_object();
1524   Handle<Object> utils = isolate->natives_utils_object();
1525   Handle<Object> args[] = {global, utils};
1526   return Bootstrapper::CompileNative(
1527       isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1528       source_code, arraysize(args), args);
1529 }
1530
1531
1532 bool Bootstrapper::CompileExtraBuiltin(Isolate* isolate, int index) {
1533   HandleScope scope(isolate);
1534   Vector<const char> name = ExtraNatives::GetScriptName(index);
1535   Handle<String> source_code =
1536       isolate->bootstrapper()->SourceLookup<ExtraNatives>(index);
1537   Handle<Object> global = isolate->global_object();
1538   Handle<Object> binding = isolate->extras_binding_object();
1539   Handle<Object> args[] = {global, binding};
1540   return Bootstrapper::CompileNative(
1541       isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1542       source_code, arraysize(args), args);
1543 }
1544
1545
1546 bool Bootstrapper::CompileExperimentalExtraBuiltin(Isolate* isolate,
1547                                                    int index) {
1548   HandleScope scope(isolate);
1549   Vector<const char> name = ExperimentalExtraNatives::GetScriptName(index);
1550   Handle<String> source_code =
1551       isolate->bootstrapper()->SourceLookup<ExperimentalExtraNatives>(index);
1552   Handle<Object> global = isolate->global_object();
1553   Handle<Object> binding = isolate->extras_binding_object();
1554   Handle<Object> args[] = {global, binding};
1555   return Bootstrapper::CompileNative(
1556       isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1557       source_code, arraysize(args), args);
1558 }
1559
1560
1561 bool Bootstrapper::CompileCodeStubBuiltin(Isolate* isolate, int index) {
1562   HandleScope scope(isolate);
1563   Vector<const char> name = CodeStubNatives::GetScriptName(index);
1564   Handle<String> source_code =
1565       isolate->bootstrapper()->SourceLookup<CodeStubNatives>(index);
1566   Handle<JSObject> global(isolate->global_object());
1567   Handle<JSObject> exports(isolate->heap()->code_stub_exports_object());
1568   Handle<Object> args[] = {global, exports};
1569   bool result =
1570       CompileNative(isolate, name, global, source_code, arraysize(args), args);
1571   return result;
1572 }
1573
1574
1575 bool Bootstrapper::CompileNative(Isolate* isolate, Vector<const char> name,
1576                                  Handle<JSObject> receiver,
1577                                  Handle<String> source, int argc,
1578                                  Handle<Object> argv[]) {
1579   SuppressDebug compiling_natives(isolate->debug());
1580   // During genesis, the boilerplate for stack overflow won't work until the
1581   // environment has been at least partially initialized. Add a stack check
1582   // before entering JS code to catch overflow early.
1583   StackLimitCheck check(isolate);
1584   if (check.JsHasOverflowed(1 * KB)) {
1585     isolate->StackOverflow();
1586     return false;
1587   }
1588
1589   Handle<Context> context(isolate->context());
1590
1591   Handle<String> script_name =
1592       isolate->factory()->NewStringFromUtf8(name).ToHandleChecked();
1593   Handle<SharedFunctionInfo> function_info = Compiler::CompileScript(
1594       source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
1595       context, NULL, NULL, ScriptCompiler::kNoCompileOptions, NATIVES_CODE,
1596       false);
1597   if (function_info.is_null()) return false;
1598
1599   DCHECK(context->IsNativeContext());
1600
1601   Handle<Context> runtime_context(context->runtime_context());
1602   Handle<JSFunction> fun =
1603       isolate->factory()->NewFunctionFromSharedFunctionInfo(function_info,
1604                                                             runtime_context);
1605
1606   // For non-extension scripts, run script to get the function wrapper.
1607   Handle<Object> wrapper;
1608   if (!Execution::Call(isolate, fun, receiver, 0, NULL).ToHandle(&wrapper)) {
1609     return false;
1610   }
1611   // Then run the function wrapper.
1612   return !Execution::Call(isolate, Handle<JSFunction>::cast(wrapper), receiver,
1613                           argc, argv).is_null();
1614 }
1615
1616
1617 bool Genesis::CallUtilsFunction(Isolate* isolate, const char* name) {
1618   Handle<JSObject> utils =
1619       Handle<JSObject>::cast(isolate->natives_utils_object());
1620   Handle<String> name_string =
1621       isolate->factory()->NewStringFromAsciiChecked(name);
1622   Handle<Object> fun = JSObject::GetDataProperty(utils, name_string);
1623   Handle<Object> receiver = isolate->factory()->undefined_value();
1624   Handle<Object> args[] = {utils};
1625   return !Execution::Call(isolate, fun, receiver, 1, args).is_null();
1626 }
1627
1628
1629 bool Genesis::CompileExtension(Isolate* isolate, v8::Extension* extension) {
1630   Factory* factory = isolate->factory();
1631   HandleScope scope(isolate);
1632   Handle<SharedFunctionInfo> function_info;
1633
1634   Handle<String> source =
1635       isolate->factory()
1636           ->NewExternalStringFromOneByte(extension->source())
1637           .ToHandleChecked();
1638   DCHECK(source->IsOneByteRepresentation());
1639
1640   // If we can't find the function in the cache, we compile a new
1641   // function and insert it into the cache.
1642   Vector<const char> name = CStrVector(extension->name());
1643   SourceCodeCache* cache = isolate->bootstrapper()->extensions_cache();
1644   Handle<Context> context(isolate->context());
1645   DCHECK(context->IsNativeContext());
1646
1647   if (!cache->Lookup(name, &function_info)) {
1648     Handle<String> script_name =
1649         factory->NewStringFromUtf8(name).ToHandleChecked();
1650     function_info = Compiler::CompileScript(
1651         source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
1652         context, extension, NULL, ScriptCompiler::kNoCompileOptions,
1653         NOT_NATIVES_CODE, false);
1654     if (function_info.is_null()) return false;
1655     cache->Add(name, function_info);
1656   }
1657
1658   // Set up the function context. Conceptually, we should clone the
1659   // function before overwriting the context but since we're in a
1660   // single-threaded environment it is not strictly necessary.
1661   Handle<JSFunction> fun =
1662       factory->NewFunctionFromSharedFunctionInfo(function_info, context);
1663
1664   // Call function using either the runtime object or the global
1665   // object as the receiver. Provide no parameters.
1666   Handle<Object> receiver = isolate->global_object();
1667   return !Execution::Call(isolate, fun, receiver, 0, NULL).is_null();
1668 }
1669
1670
1671 static Handle<JSObject> ResolveBuiltinIdHolder(Handle<Context> native_context,
1672                                                const char* holder_expr) {
1673   Isolate* isolate = native_context->GetIsolate();
1674   Factory* factory = isolate->factory();
1675   Handle<GlobalObject> global(native_context->global_object());
1676   const char* period_pos = strchr(holder_expr, '.');
1677   if (period_pos == NULL) {
1678     return Handle<JSObject>::cast(
1679         Object::GetPropertyOrElement(
1680             global, factory->InternalizeUtf8String(holder_expr))
1681             .ToHandleChecked());
1682   }
1683   const char* inner = period_pos + 1;
1684   DCHECK(!strchr(inner, '.'));
1685   Vector<const char> property(holder_expr,
1686                               static_cast<int>(period_pos - holder_expr));
1687   Handle<String> property_string = factory->InternalizeUtf8String(property);
1688   DCHECK(!property_string.is_null());
1689   Handle<JSObject> object = Handle<JSObject>::cast(
1690       Object::GetProperty(global, property_string).ToHandleChecked());
1691   if (strcmp("prototype", inner) == 0) {
1692     Handle<JSFunction> function = Handle<JSFunction>::cast(object);
1693     return Handle<JSObject>(JSObject::cast(function->prototype()));
1694   }
1695   Handle<String> inner_string = factory->InternalizeUtf8String(inner);
1696   DCHECK(!inner_string.is_null());
1697   Handle<Object> value =
1698       Object::GetProperty(object, inner_string).ToHandleChecked();
1699   return Handle<JSObject>::cast(value);
1700 }
1701
1702
1703 template <typename Data>
1704 Data* SetBuiltinTypedArray(Isolate* isolate, Handle<JSBuiltinsObject> builtins,
1705                            ExternalArrayType type, Data* data,
1706                            size_t num_elements, const char* name) {
1707   size_t byte_length = num_elements * sizeof(*data);
1708   Handle<JSArrayBuffer> buffer = isolate->factory()->NewJSArrayBuffer();
1709   bool is_external = data != nullptr;
1710   if (!is_external) {
1711     data = reinterpret_cast<Data*>(
1712         isolate->array_buffer_allocator()->Allocate(byte_length));
1713   }
1714   JSArrayBuffer::Setup(buffer, isolate, is_external, data, byte_length);
1715
1716   Handle<JSTypedArray> typed_array =
1717       isolate->factory()->NewJSTypedArray(type, buffer, 0, num_elements);
1718   Handle<String> name_string = isolate->factory()->InternalizeUtf8String(name);
1719   // Reset property cell type before (re)initializing.
1720   JSBuiltinsObject::InvalidatePropertyCell(builtins, name_string);
1721   JSObject::SetOwnPropertyIgnoreAttributes(builtins, name_string, typed_array,
1722                                            FROZEN)
1723       .Assert();
1724   return data;
1725 }
1726
1727
1728 void Genesis::InitializeBuiltinTypedArrays() {
1729   Handle<JSBuiltinsObject> builtins(native_context()->builtins());
1730   {  // Initially seed the per-context random number generator using the
1731     // per-isolate random number generator.
1732     const size_t num_elements = 2;
1733     const size_t num_bytes = num_elements * sizeof(uint32_t);
1734     uint32_t* state = SetBuiltinTypedArray<uint32_t>(isolate(), builtins,
1735                                                      kExternalUint32Array, NULL,
1736                                                      num_elements, "rngstate");
1737     do {
1738       isolate()->random_number_generator()->NextBytes(state, num_bytes);
1739     } while (state[0] == 0 || state[1] == 0);
1740   }
1741
1742   {  // Initialize trigonometric lookup tables and constants.
1743     const size_t num_elements = arraysize(fdlibm::MathConstants::constants);
1744     double* data = const_cast<double*>(fdlibm::MathConstants::constants);
1745     SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1746                                  data, num_elements, "kMath");
1747   }
1748
1749   {  // Initialize a result array for rempio2 calculation
1750     const size_t num_elements = 2;
1751     double* data =
1752         SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1753                                      NULL, num_elements, "rempio2result");
1754     for (size_t i = 0; i < num_elements; i++) data[i] = 0;
1755   }
1756 }
1757
1758
1759 void Bootstrapper::ExportFromRuntime(Isolate* isolate,
1760                                      Handle<JSObject> container) {
1761   HandleScope scope(isolate);
1762 #define EXPORT_PRIVATE_SYMBOL(NAME)                                         \
1763   Handle<String> NAME##_name =                                              \
1764       isolate->factory()->NewStringFromAsciiChecked(#NAME);                 \
1765   JSObject::AddProperty(container, NAME##_name, isolate->factory()->NAME(), \
1766                         NONE);
1767   PRIVATE_SYMBOL_LIST(EXPORT_PRIVATE_SYMBOL)
1768 #undef EXPORT_PRIVATE_SYMBOL
1769
1770 #define EXPORT_PUBLIC_SYMBOL(NAME, DESCRIPTION)                             \
1771   Handle<String> NAME##_name =                                              \
1772       isolate->factory()->NewStringFromAsciiChecked(#NAME);                 \
1773   JSObject::AddProperty(container, NAME##_name, isolate->factory()->NAME(), \
1774                         NONE);
1775   PUBLIC_SYMBOL_LIST(EXPORT_PUBLIC_SYMBOL)
1776 #undef EXPORT_PUBLIC_SYMBOL
1777
1778   Handle<JSFunction> apply = InstallFunction(
1779       container, "reflect_apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1780       MaybeHandle<JSObject>(), Builtins::kReflectApply);
1781   apply->shared()->set_internal_formal_parameter_count(3);
1782   apply->shared()->set_length(3);
1783   isolate->native_context()->set_reflect_apply(*apply);
1784
1785   Handle<JSFunction> construct = InstallFunction(
1786       container, "reflect_construct", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1787       MaybeHandle<JSObject>(), Builtins::kReflectConstruct);
1788   construct->shared()->set_internal_formal_parameter_count(3);
1789   construct->shared()->set_length(2);
1790   isolate->native_context()->set_reflect_construct(*construct);
1791 }
1792
1793
1794 void Bootstrapper::ExportExperimentalFromRuntime(Isolate* isolate,
1795                                                  Handle<JSObject> container) {
1796   HandleScope scope(isolate);
1797
1798 #define INITIALIZE_FLAG(FLAG)                                         \
1799   {                                                                   \
1800     Handle<String> name =                                             \
1801         isolate->factory()->NewStringFromAsciiChecked(#FLAG);         \
1802     JSObject::AddProperty(container, name,                            \
1803                           isolate->factory()->ToBoolean(FLAG), NONE); \
1804   }
1805
1806   INITIALIZE_FLAG(FLAG_harmony_regexps)
1807   INITIALIZE_FLAG(FLAG_harmony_unicode_regexps)
1808   INITIALIZE_FLAG(FLAG_harmony_tostring)
1809
1810 #undef INITIALIZE_FLAG
1811 }
1812
1813
1814 #define EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(id) \
1815   void Genesis::InitializeGlobal_##id() {}
1816
1817 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_modules)
1818 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_array_includes)
1819 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_arrow_functions)
1820 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_proxies)
1821 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy)
1822 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy_function)
1823 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy_let)
1824 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_rest_parameters)
1825 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_default_parameters)
1826 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spreadcalls)
1827 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_destructuring)
1828 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_object)
1829 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_object_observe)
1830 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spread_arrays)
1831 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_atomics)
1832 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_new_target)
1833 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_concat_spreadable)
1834 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_regexps)
1835 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_unicode_regexps)
1836 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_tostring)
1837
1838
1839 void Genesis::InitializeGlobal_harmony_reflect() {
1840   if (!FLAG_harmony_reflect) return;
1841
1842   Handle<JSGlobalObject> global(JSGlobalObject::cast(
1843       native_context()->global_object()));
1844   Handle<String> reflect_string =
1845       factory()->NewStringFromStaticChars("Reflect");
1846   Handle<Object> reflect =
1847       factory()->NewJSObject(isolate()->object_function(), TENURED);
1848   JSObject::AddProperty(global, reflect_string, reflect, DONT_ENUM);
1849 }
1850
1851
1852
1853 void Genesis::InitializeGlobal_harmony_sharedarraybuffer() {
1854   if (!FLAG_harmony_sharedarraybuffer) return;
1855
1856   Handle<JSGlobalObject> global(
1857       JSGlobalObject::cast(native_context()->global_object()));
1858
1859   Handle<JSFunction> shared_array_buffer_fun = InstallFunction(
1860       global, "SharedArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1861       JSArrayBuffer::kSizeWithInternalFields,
1862       isolate()->initial_object_prototype(), Builtins::kIllegal);
1863   native_context()->set_shared_array_buffer_fun(*shared_array_buffer_fun);
1864 }
1865
1866
1867 void Genesis::InitializeGlobal_harmony_simd() {
1868   if (!FLAG_harmony_simd) return;
1869
1870   Handle<JSGlobalObject> global(
1871       JSGlobalObject::cast(native_context()->global_object()));
1872   Isolate* isolate = global->GetIsolate();
1873   Factory* factory = isolate->factory();
1874
1875   Handle<String> name = factory->InternalizeUtf8String("SIMD");
1876   Handle<JSFunction> cons = factory->NewFunction(name);
1877   JSFunction::SetInstancePrototype(
1878       cons,
1879       Handle<Object>(native_context()->initial_object_prototype(), isolate));
1880   cons->SetInstanceClassName(*name);
1881   Handle<JSObject> simd_object = factory->NewJSObject(cons, TENURED);
1882   DCHECK(simd_object->IsJSObject());
1883   JSObject::AddProperty(global, name, simd_object, DONT_ENUM);
1884
1885 // Install SIMD type functions. Set the instance class names since
1886 // InstallFunction only does this when we install on the GlobalObject.
1887 #define SIMD128_INSTALL_FUNCTION(TYPE, Type, type, lane_count, lane_type) \
1888   Handle<JSFunction> type##_function = InstallFunction(                   \
1889       simd_object, #Type, JS_VALUE_TYPE, JSValue::kSize,                  \
1890       isolate->initial_object_prototype(), Builtins::kIllegal);           \
1891   native_context()->set_##type##_function(*type##_function);              \
1892   type##_function->SetInstanceClassName(*factory->Type##_string());
1893   SIMD128_TYPES(SIMD128_INSTALL_FUNCTION)
1894 #undef SIMD128_INSTALL_FUNCTION
1895 }
1896
1897
1898 Handle<JSFunction> Genesis::InstallInternalArray(Handle<JSObject> target,
1899                                                  const char* name,
1900                                                  ElementsKind elements_kind) {
1901   // --- I n t e r n a l   A r r a y ---
1902   // An array constructor on the builtins object that works like
1903   // the public Array constructor, except that its prototype
1904   // doesn't inherit from Object.prototype.
1905   // To be used only for internal work by builtins. Instances
1906   // must not be leaked to user code.
1907   Handle<JSObject> prototype =
1908       factory()->NewJSObject(isolate()->object_function(), TENURED);
1909   Handle<JSFunction> array_function =
1910       InstallFunction(target, name, JS_ARRAY_TYPE, JSArray::kSize, prototype,
1911                       Builtins::kInternalArrayCode);
1912
1913   InternalArrayConstructorStub internal_array_constructor_stub(isolate());
1914   Handle<Code> code = internal_array_constructor_stub.GetCode();
1915   array_function->shared()->set_construct_stub(*code);
1916   array_function->shared()->DontAdaptArguments();
1917
1918   Handle<Map> original_map(array_function->initial_map());
1919   Handle<Map> initial_map = Map::Copy(original_map, "InternalArray");
1920   initial_map->set_elements_kind(elements_kind);
1921   JSFunction::SetInitialMap(array_function, initial_map, prototype);
1922
1923   // Make "length" magic on instances.
1924   Map::EnsureDescriptorSlack(initial_map, 1);
1925
1926   PropertyAttributes attribs = static_cast<PropertyAttributes>(
1927       DONT_ENUM | DONT_DELETE);
1928
1929   Handle<AccessorInfo> array_length =
1930       Accessors::ArrayLengthInfo(isolate(), attribs);
1931   {  // Add length.
1932     AccessorConstantDescriptor d(Handle<Name>(Name::cast(array_length->name())),
1933                                  array_length, attribs);
1934     initial_map->AppendDescriptor(&d);
1935   }
1936
1937   return array_function;
1938 }
1939
1940
1941 bool Genesis::InstallNatives(ContextType context_type) {
1942   HandleScope scope(isolate());
1943
1944   // Create a function for the builtins object. Allocate space for the
1945   // JavaScript builtins, a reference to the builtins object
1946   // (itself) and a reference to the native_context directly in the object.
1947   Handle<Code> code = Handle<Code>(
1948       isolate()->builtins()->builtin(Builtins::kIllegal));
1949   Handle<JSFunction> builtins_fun = factory()->NewFunction(
1950       factory()->empty_string(), code, JS_BUILTINS_OBJECT_TYPE,
1951       JSBuiltinsObject::kSize);
1952
1953   Handle<String> name =
1954       factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
1955   builtins_fun->shared()->set_instance_class_name(*name);
1956   builtins_fun->initial_map()->set_dictionary_map(true);
1957   builtins_fun->initial_map()->set_prototype(heap()->null_value());
1958
1959   // Allocate the builtins object.
1960   Handle<JSBuiltinsObject> builtins =
1961       Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
1962   builtins->set_builtins(*builtins);
1963   builtins->set_native_context(*native_context());
1964   builtins->set_global_proxy(native_context()->global_proxy());
1965
1966
1967   // Set up the 'builtin' property, which refers to the js builtins object.
1968   static const PropertyAttributes attributes =
1969       static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1970   Handle<String> builtins_string =
1971       factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
1972   JSObject::AddProperty(builtins, builtins_string, builtins, attributes);
1973
1974   // Set up the reference from the global object to the builtins object.
1975   JSGlobalObject::cast(native_context()->global_object())->
1976       set_builtins(*builtins);
1977
1978   // Create a bridge function that has context in the native context.
1979   Handle<JSFunction> bridge = factory()->NewFunction(factory()->empty_string());
1980   DCHECK(bridge->context() == *isolate()->native_context());
1981
1982   // Allocate the builtins context.
1983   Handle<Context> context =
1984     factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1985   context->set_global_object(*builtins);  // override builtins global object
1986
1987   native_context()->set_runtime_context(*context);
1988
1989   // Set up the utils object as shared container between native scripts.
1990   Handle<JSObject> utils = factory()->NewJSObject(isolate()->object_function());
1991   JSObject::NormalizeProperties(utils, CLEAR_INOBJECT_PROPERTIES, 16,
1992                                 "utils container for native scripts");
1993   native_context()->set_natives_utils_object(*utils);
1994
1995   int builtin_index = Natives::GetDebuggerCount();
1996   // Only run prologue.js and runtime.js at this point.
1997   DCHECK_EQ(builtin_index, Natives::GetIndex("prologue"));
1998   if (!Bootstrapper::CompileBuiltin(isolate(), builtin_index++)) return false;
1999   DCHECK_EQ(builtin_index, Natives::GetIndex("runtime"));
2000   if (!Bootstrapper::CompileBuiltin(isolate(), builtin_index++)) return false;
2001
2002   // A thin context is ready at this point.
2003   if (context_type == THIN_CONTEXT) return true;
2004
2005   if (FLAG_expose_natives_as != NULL) {
2006     Handle<String> utils_key = factory()->NewStringFromAsciiChecked("utils");
2007     JSObject::AddProperty(builtins, utils_key, utils, NONE);
2008   }
2009
2010   {  // -- S c r i p t
2011     // Builtin functions for Script.
2012     Handle<JSFunction> script_fun = InstallFunction(
2013         builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
2014         isolate()->initial_object_prototype(), Builtins::kIllegal);
2015     Handle<JSObject> prototype =
2016         factory()->NewJSObject(isolate()->object_function(), TENURED);
2017     Accessors::FunctionSetPrototype(script_fun, prototype).Assert();
2018     native_context()->set_script_function(*script_fun);
2019
2020     Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
2021     Map::EnsureDescriptorSlack(script_map, 15);
2022
2023     PropertyAttributes attribs =
2024         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2025
2026     Handle<AccessorInfo> script_column =
2027         Accessors::ScriptColumnOffsetInfo(isolate(), attribs);
2028     {
2029       AccessorConstantDescriptor d(
2030           Handle<Name>(Name::cast(script_column->name())), script_column,
2031           attribs);
2032       script_map->AppendDescriptor(&d);
2033     }
2034
2035     Handle<AccessorInfo> script_id =
2036         Accessors::ScriptIdInfo(isolate(), attribs);
2037     {
2038       AccessorConstantDescriptor d(Handle<Name>(Name::cast(script_id->name())),
2039                                    script_id, attribs);
2040       script_map->AppendDescriptor(&d);
2041     }
2042
2043
2044     Handle<AccessorInfo> script_name =
2045         Accessors::ScriptNameInfo(isolate(), attribs);
2046     {
2047       AccessorConstantDescriptor d(
2048           Handle<Name>(Name::cast(script_name->name())), script_name, attribs);
2049       script_map->AppendDescriptor(&d);
2050     }
2051
2052     Handle<AccessorInfo> script_line =
2053         Accessors::ScriptLineOffsetInfo(isolate(), attribs);
2054     {
2055       AccessorConstantDescriptor d(
2056           Handle<Name>(Name::cast(script_line->name())), script_line, attribs);
2057       script_map->AppendDescriptor(&d);
2058     }
2059
2060     Handle<AccessorInfo> script_source =
2061         Accessors::ScriptSourceInfo(isolate(), attribs);
2062     {
2063       AccessorConstantDescriptor d(
2064           Handle<Name>(Name::cast(script_source->name())), script_source,
2065           attribs);
2066       script_map->AppendDescriptor(&d);
2067     }
2068
2069     Handle<AccessorInfo> script_type =
2070         Accessors::ScriptTypeInfo(isolate(), attribs);
2071     {
2072       AccessorConstantDescriptor d(
2073           Handle<Name>(Name::cast(script_type->name())), script_type, attribs);
2074       script_map->AppendDescriptor(&d);
2075     }
2076
2077     Handle<AccessorInfo> script_compilation_type =
2078         Accessors::ScriptCompilationTypeInfo(isolate(), attribs);
2079     {
2080       AccessorConstantDescriptor d(
2081           Handle<Name>(Name::cast(script_compilation_type->name())),
2082           script_compilation_type, attribs);
2083       script_map->AppendDescriptor(&d);
2084     }
2085
2086     Handle<AccessorInfo> script_line_ends =
2087         Accessors::ScriptLineEndsInfo(isolate(), attribs);
2088     {
2089       AccessorConstantDescriptor d(
2090           Handle<Name>(Name::cast(script_line_ends->name())), script_line_ends,
2091           attribs);
2092       script_map->AppendDescriptor(&d);
2093     }
2094
2095     Handle<AccessorInfo> script_context_data =
2096         Accessors::ScriptContextDataInfo(isolate(), attribs);
2097     {
2098       AccessorConstantDescriptor d(
2099           Handle<Name>(Name::cast(script_context_data->name())),
2100           script_context_data, attribs);
2101       script_map->AppendDescriptor(&d);
2102     }
2103
2104     Handle<AccessorInfo> script_eval_from_script =
2105         Accessors::ScriptEvalFromScriptInfo(isolate(), attribs);
2106     {
2107       AccessorConstantDescriptor d(
2108           Handle<Name>(Name::cast(script_eval_from_script->name())),
2109           script_eval_from_script, attribs);
2110       script_map->AppendDescriptor(&d);
2111     }
2112
2113     Handle<AccessorInfo> script_eval_from_script_position =
2114         Accessors::ScriptEvalFromScriptPositionInfo(isolate(), attribs);
2115     {
2116       AccessorConstantDescriptor d(
2117           Handle<Name>(Name::cast(script_eval_from_script_position->name())),
2118           script_eval_from_script_position, attribs);
2119       script_map->AppendDescriptor(&d);
2120     }
2121
2122     Handle<AccessorInfo> script_eval_from_function_name =
2123         Accessors::ScriptEvalFromFunctionNameInfo(isolate(), attribs);
2124     {
2125       AccessorConstantDescriptor d(
2126           Handle<Name>(Name::cast(script_eval_from_function_name->name())),
2127           script_eval_from_function_name, attribs);
2128       script_map->AppendDescriptor(&d);
2129     }
2130
2131     Handle<AccessorInfo> script_source_url =
2132         Accessors::ScriptSourceUrlInfo(isolate(), attribs);
2133     {
2134       AccessorConstantDescriptor d(
2135           Handle<Name>(Name::cast(script_source_url->name())),
2136           script_source_url, attribs);
2137       script_map->AppendDescriptor(&d);
2138     }
2139
2140     Handle<AccessorInfo> script_source_mapping_url =
2141         Accessors::ScriptSourceMappingUrlInfo(isolate(), attribs);
2142     {
2143       AccessorConstantDescriptor d(
2144           Handle<Name>(Name::cast(script_source_mapping_url->name())),
2145           script_source_mapping_url, attribs);
2146       script_map->AppendDescriptor(&d);
2147     }
2148
2149     Handle<AccessorInfo> script_is_embedder_debug_script =
2150         Accessors::ScriptIsEmbedderDebugScriptInfo(isolate(), attribs);
2151     {
2152       AccessorConstantDescriptor d(
2153           Handle<Name>(Name::cast(script_is_embedder_debug_script->name())),
2154           script_is_embedder_debug_script, attribs);
2155       script_map->AppendDescriptor(&d);
2156     }
2157   }
2158   {
2159     // Builtin function for OpaqueReference -- a JSValue-based object,
2160     // that keeps its field isolated from JavaScript code. It may store
2161     // objects, that JavaScript code may not access.
2162     Handle<JSFunction> opaque_reference_fun = InstallFunction(
2163         builtins, "OpaqueReference", JS_VALUE_TYPE, JSValue::kSize,
2164         isolate()->initial_object_prototype(), Builtins::kIllegal);
2165     Handle<JSObject> prototype =
2166         factory()->NewJSObject(isolate()->object_function(), TENURED);
2167     Accessors::FunctionSetPrototype(opaque_reference_fun, prototype).Assert();
2168     native_context()->set_opaque_reference_function(*opaque_reference_fun);
2169   }
2170
2171   // InternalArrays should not use Smi-Only array optimizations. There are too
2172   // many places in the C++ runtime code (e.g. RegEx) that assume that
2173   // elements in InternalArrays can be set to non-Smi values without going
2174   // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
2175   // transition easy to trap. Moreover, they rarely are smi-only.
2176   {
2177     HandleScope scope(isolate());
2178     Handle<JSObject> utils =
2179         Handle<JSObject>::cast(isolate()->natives_utils_object());
2180     Handle<JSFunction> array_function =
2181         InstallInternalArray(utils, "InternalArray", FAST_HOLEY_ELEMENTS);
2182     native_context()->set_internal_array_function(*array_function);
2183     InstallInternalArray(utils, "InternalPackedArray", FAST_ELEMENTS);
2184   }
2185
2186   {  // -- S e t I t e r a t o r
2187     Handle<JSFunction> set_iterator_function = InstallFunction(
2188         builtins, "SetIterator", JS_SET_ITERATOR_TYPE, JSSetIterator::kSize,
2189         isolate()->initial_object_prototype(), Builtins::kIllegal);
2190     native_context()->set_set_iterator_map(
2191         set_iterator_function->initial_map());
2192   }
2193
2194   {  // -- M a p I t e r a t o r
2195     Handle<JSFunction> map_iterator_function = InstallFunction(
2196         builtins, "MapIterator", JS_MAP_ITERATOR_TYPE, JSMapIterator::kSize,
2197         isolate()->initial_object_prototype(), Builtins::kIllegal);
2198     native_context()->set_map_iterator_map(
2199         map_iterator_function->initial_map());
2200   }
2201
2202   {
2203     // Create generator meta-objects and install them on the builtins object.
2204     Handle<JSObject> builtins(native_context()->builtins());
2205     Handle<JSObject> iterator_prototype =
2206         factory()->NewJSObject(isolate()->object_function(), TENURED);
2207     Handle<JSObject> generator_object_prototype =
2208         factory()->NewJSObject(isolate()->object_function(), TENURED);
2209     Handle<JSObject> generator_function_prototype =
2210         factory()->NewJSObject(isolate()->object_function(), TENURED);
2211     SetObjectPrototype(generator_object_prototype, iterator_prototype);
2212     JSObject::AddProperty(
2213         builtins, factory()->InternalizeUtf8String("$iteratorPrototype"),
2214         iterator_prototype,
2215         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2216     JSObject::AddProperty(
2217         builtins,
2218         factory()->InternalizeUtf8String("GeneratorFunctionPrototype"),
2219         generator_function_prototype,
2220         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2221
2222     JSObject::AddProperty(
2223         generator_function_prototype,
2224         factory()->InternalizeUtf8String("prototype"),
2225         generator_object_prototype,
2226         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2227
2228     static const bool kUseStrictFunctionMap = true;
2229     InstallFunction(builtins, "GeneratorFunction", JS_FUNCTION_TYPE,
2230                     JSFunction::kSize, generator_function_prototype,
2231                     Builtins::kIllegal, kUseStrictFunctionMap);
2232
2233     // Create maps for generator functions and their prototypes.  Store those
2234     // maps in the native context. The "prototype" property descriptor is
2235     // writable, non-enumerable, and non-configurable (as per ES6 draft
2236     // 04-14-15, section 25.2.4.3).
2237     Handle<Map> strict_function_map(strict_function_map_writable_prototype_);
2238     // Generator functions do not have "caller" or "arguments" accessors.
2239     Handle<Map> sloppy_generator_function_map =
2240         Map::Copy(strict_function_map, "SloppyGeneratorFunction");
2241     Map::SetPrototype(sloppy_generator_function_map,
2242                       generator_function_prototype);
2243     native_context()->set_sloppy_generator_function_map(
2244         *sloppy_generator_function_map);
2245
2246     Handle<Map> strict_generator_function_map =
2247         Map::Copy(strict_function_map, "StrictGeneratorFunction");
2248     Map::SetPrototype(strict_generator_function_map,
2249                       generator_function_prototype);
2250     native_context()->set_strict_generator_function_map(
2251         *strict_generator_function_map);
2252
2253     Handle<Map> strong_function_map(native_context()->strong_function_map());
2254     Handle<Map> strong_generator_function_map =
2255         Map::Copy(strong_function_map, "StrongGeneratorFunction");
2256     Map::SetPrototype(strong_generator_function_map,
2257                       generator_function_prototype);
2258     native_context()->set_strong_generator_function_map(
2259         *strong_generator_function_map);
2260
2261     Handle<JSFunction> object_function(native_context()->object_function());
2262     Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
2263     Map::SetPrototype(generator_object_prototype_map,
2264                       generator_object_prototype);
2265     native_context()->set_generator_object_prototype_map(
2266         *generator_object_prototype_map);
2267   }
2268
2269   if (FLAG_disable_native_files) {
2270     PrintF("Warning: Running without installed natives!\n");
2271     return true;
2272   }
2273
2274   // Run the rest of the native scripts.
2275   while (builtin_index < Natives::GetBuiltinsCount()) {
2276     if (!Bootstrapper::CompileBuiltin(isolate(), builtin_index++)) return false;
2277   }
2278
2279   if (!CallUtilsFunction(isolate(), "PostNatives")) return false;
2280
2281   auto function_cache =
2282       ObjectHashTable::New(isolate(), ApiNatives::kInitialFunctionCacheSize,
2283                            USE_CUSTOM_MINIMUM_CAPACITY);
2284   native_context()->set_function_cache(*function_cache);
2285
2286   // Store the map for the string prototype after the natives has been compiled
2287   // and the String function has been set up.
2288   Handle<JSFunction> string_function(native_context()->string_function());
2289   DCHECK(JSObject::cast(
2290       string_function->initial_map()->prototype())->HasFastProperties());
2291   native_context()->set_string_function_prototype_map(
2292       HeapObject::cast(string_function->initial_map()->prototype())->map());
2293
2294   // Install Function.prototype.call and apply.
2295   {
2296     Handle<String> key = factory()->Function_string();
2297     Handle<JSFunction> function =
2298         Handle<JSFunction>::cast(Object::GetProperty(
2299             handle(native_context()->global_object()), key).ToHandleChecked());
2300     Handle<JSObject> proto =
2301         Handle<JSObject>(JSObject::cast(function->instance_prototype()));
2302
2303     // Install the call and the apply functions.
2304     Handle<JSFunction> call =
2305         InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2306                         MaybeHandle<JSObject>(), Builtins::kFunctionCall);
2307     Handle<JSFunction> apply =
2308         InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2309                         MaybeHandle<JSObject>(), Builtins::kFunctionApply);
2310
2311     // Make sure that Function.prototype.call appears to be compiled.
2312     // The code will never be called, but inline caching for call will
2313     // only work if it appears to be compiled.
2314     call->shared()->DontAdaptArguments();
2315     DCHECK(call->is_compiled());
2316
2317     // Set the expected parameters for apply to 2; required by builtin.
2318     apply->shared()->set_internal_formal_parameter_count(2);
2319
2320     // Set the lengths for the functions to satisfy ECMA-262.
2321     call->shared()->set_length(1);
2322     apply->shared()->set_length(2);
2323   }
2324
2325   InstallBuiltinFunctionIds();
2326
2327   // Create a constructor for RegExp results (a variant of Array that
2328   // predefines the two properties index and match).
2329   {
2330     // RegExpResult initial map.
2331
2332     // Find global.Array.prototype to inherit from.
2333     Handle<JSFunction> array_constructor(native_context()->array_function());
2334     Handle<JSObject> array_prototype(
2335         JSObject::cast(array_constructor->instance_prototype()));
2336
2337     // Add initial map.
2338     Handle<Map> initial_map =
2339         factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
2340     initial_map->SetConstructor(*array_constructor);
2341
2342     // Set prototype on map.
2343     initial_map->set_non_instance_prototype(false);
2344     Map::SetPrototype(initial_map, array_prototype);
2345
2346     // Update map with length accessor from Array and add "index" and "input".
2347     Map::EnsureDescriptorSlack(initial_map, 3);
2348
2349     {
2350       JSFunction* array_function = native_context()->array_function();
2351       Handle<DescriptorArray> array_descriptors(
2352           array_function->initial_map()->instance_descriptors());
2353       Handle<String> length = factory()->length_string();
2354       int old = array_descriptors->SearchWithCache(
2355           *length, array_function->initial_map());
2356       DCHECK(old != DescriptorArray::kNotFound);
2357       AccessorConstantDescriptor desc(
2358           length, handle(array_descriptors->GetValue(old), isolate()),
2359           array_descriptors->GetDetails(old).attributes());
2360       initial_map->AppendDescriptor(&desc);
2361     }
2362     {
2363       DataDescriptor index_field(factory()->index_string(),
2364                                  JSRegExpResult::kIndexIndex, NONE,
2365                                  Representation::Tagged());
2366       initial_map->AppendDescriptor(&index_field);
2367     }
2368
2369     {
2370       DataDescriptor input_field(factory()->input_string(),
2371                                  JSRegExpResult::kInputIndex, NONE,
2372                                  Representation::Tagged());
2373       initial_map->AppendDescriptor(&input_field);
2374     }
2375
2376     initial_map->SetInObjectProperties(2);
2377     initial_map->set_unused_property_fields(0);
2378
2379     native_context()->set_regexp_result_map(*initial_map);
2380   }
2381
2382   // Add @@iterator method to the arguments object maps.
2383   {
2384     PropertyAttributes attribs = DONT_ENUM;
2385     Handle<AccessorInfo> arguments_iterator =
2386         Accessors::ArgumentsIteratorInfo(isolate(), attribs);
2387     {
2388       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2389                                    arguments_iterator, attribs);
2390       Handle<Map> map(native_context()->sloppy_arguments_map());
2391       Map::EnsureDescriptorSlack(map, 1);
2392       map->AppendDescriptor(&d);
2393     }
2394     {
2395       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2396                                    arguments_iterator, attribs);
2397       Handle<Map> map(native_context()->fast_aliased_arguments_map());
2398       Map::EnsureDescriptorSlack(map, 1);
2399       map->AppendDescriptor(&d);
2400     }
2401     {
2402       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2403                                    arguments_iterator, attribs);
2404       Handle<Map> map(native_context()->slow_aliased_arguments_map());
2405       Map::EnsureDescriptorSlack(map, 1);
2406       map->AppendDescriptor(&d);
2407     }
2408     {
2409       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2410                                    arguments_iterator, attribs);
2411       Handle<Map> map(native_context()->strict_arguments_map());
2412       Map::EnsureDescriptorSlack(map, 1);
2413       map->AppendDescriptor(&d);
2414     }
2415   }
2416
2417 #ifdef VERIFY_HEAP
2418   if (FLAG_verify_heap) {
2419     builtins->ObjectVerify();
2420   }
2421 #endif
2422
2423   return true;
2424 }
2425
2426
2427 bool Genesis::InstallExperimentalNatives() {
2428   static const char* harmony_array_includes_natives[] = {
2429       "native harmony-array-includes.js", nullptr};
2430   static const char* harmony_proxies_natives[] = {"native proxy.js", nullptr};
2431   static const char* harmony_modules_natives[] = {nullptr};
2432   static const char* harmony_regexps_natives[] = {"native harmony-regexp.js",
2433                                                   nullptr};
2434   static const char* harmony_arrow_functions_natives[] = {nullptr};
2435   static const char* harmony_tostring_natives[] = {"native harmony-tostring.js",
2436                                                    nullptr};
2437   static const char* harmony_sloppy_natives[] = {nullptr};
2438   static const char* harmony_sloppy_function_natives[] = {nullptr};
2439   static const char* harmony_sloppy_let_natives[] = {nullptr};
2440   static const char* harmony_unicode_regexps_natives[] = {nullptr};
2441   static const char* harmony_rest_parameters_natives[] = {nullptr};
2442   static const char* harmony_default_parameters_natives[] = {nullptr};
2443   static const char* harmony_reflect_natives[] = {"native harmony-reflect.js",
2444                                                   nullptr};
2445   static const char* harmony_spreadcalls_natives[] = {
2446       "native harmony-spread.js", nullptr};
2447   static const char* harmony_destructuring_natives[] = {nullptr};
2448   static const char* harmony_object_natives[] = {"native harmony-object.js",
2449                                                  NULL};
2450   static const char* harmony_object_observe_natives[] = {
2451       "native harmony-object-observe.js", nullptr};
2452   static const char* harmony_spread_arrays_natives[] = {nullptr};
2453   static const char* harmony_sharedarraybuffer_natives[] = {
2454       "native harmony-sharedarraybuffer.js", NULL};
2455   static const char* harmony_atomics_natives[] = {"native harmony-atomics.js",
2456                                                   nullptr};
2457   static const char* harmony_new_target_natives[] = {nullptr};
2458   static const char* harmony_concat_spreadable_natives[] = {
2459       "native harmony-concat-spreadable.js", nullptr};
2460   static const char* harmony_simd_natives[] = {"native harmony-simd.js",
2461                                                nullptr};
2462
2463   for (int i = ExperimentalNatives::GetDebuggerCount();
2464        i < ExperimentalNatives::GetBuiltinsCount(); i++) {
2465 #define INSTALL_EXPERIMENTAL_NATIVES(id, desc)                                \
2466   if (FLAG_##id) {                                                            \
2467     for (size_t j = 0; id##_natives[j] != NULL; j++) {                        \
2468       Vector<const char> script_name = ExperimentalNatives::GetScriptName(i); \
2469       if (strncmp(script_name.start(), id##_natives[j],                       \
2470                   script_name.length()) == 0) {                               \
2471         if (!Bootstrapper::CompileExperimentalBuiltin(isolate(), i)) {        \
2472           return false;                                                       \
2473         }                                                                     \
2474       }                                                                       \
2475     }                                                                         \
2476   }
2477     HARMONY_INPROGRESS(INSTALL_EXPERIMENTAL_NATIVES);
2478     HARMONY_STAGED(INSTALL_EXPERIMENTAL_NATIVES);
2479     HARMONY_SHIPPING(INSTALL_EXPERIMENTAL_NATIVES);
2480 #undef INSTALL_EXPERIMENTAL_NATIVES
2481   }
2482
2483   if (!CallUtilsFunction(isolate(), "PostExperimentals")) return false;
2484
2485   InstallExperimentalBuiltinFunctionIds();
2486   return true;
2487 }
2488
2489
2490 bool Genesis::InstallExtraNatives() {
2491   HandleScope scope(isolate());
2492
2493   Handle<JSObject> extras_binding =
2494       factory()->NewJSObject(isolate()->object_function());
2495   JSObject::NormalizeProperties(extras_binding, CLEAR_INOBJECT_PROPERTIES, 2,
2496                                 "container for binding to/from extra natives");
2497   native_context()->set_extras_binding_object(*extras_binding);
2498
2499   for (int i = ExtraNatives::GetDebuggerCount();
2500        i < ExtraNatives::GetBuiltinsCount(); i++) {
2501     if (!Bootstrapper::CompileExtraBuiltin(isolate(), i)) return false;
2502   }
2503
2504   return true;
2505 }
2506
2507
2508 bool Genesis::InstallExperimentalExtraNatives() {
2509   for (int i = ExperimentalExtraNatives::GetDebuggerCount();
2510        i < ExperimentalExtraNatives::GetBuiltinsCount(); i++) {
2511     if (!Bootstrapper::CompileExperimentalExtraBuiltin(isolate(), i))
2512       return false;
2513   }
2514
2515   return true;
2516 }
2517
2518
2519 bool Genesis::InstallDebuggerNatives() {
2520   for (int i = 0; i < Natives::GetDebuggerCount(); ++i) {
2521     if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2522   }
2523   return CallUtilsFunction(isolate(), "PostDebug");
2524 }
2525
2526
2527 bool Bootstrapper::InstallCodeStubNatives(Isolate* isolate) {
2528   for (int i = CodeStubNatives::GetDebuggerCount();
2529        i < CodeStubNatives::GetBuiltinsCount(); i++) {
2530     if (!CompileCodeStubBuiltin(isolate, i)) return false;
2531   }
2532
2533   return true;
2534 }
2535
2536
2537 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
2538                                      const char* function_name,
2539                                      BuiltinFunctionId id) {
2540   Isolate* isolate = holder->GetIsolate();
2541   Handle<Object> function_object =
2542       Object::GetProperty(isolate, holder, function_name).ToHandleChecked();
2543   Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2544   function->shared()->set_function_data(Smi::FromInt(id));
2545 }
2546
2547
2548 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2549   { #holder_expr, #fun_name, k##name }                  \
2550   ,
2551
2552
2553 void Genesis::InstallBuiltinFunctionIds() {
2554   HandleScope scope(isolate());
2555   struct BuiltinFunctionIds {
2556     const char* holder_expr;
2557     const char* fun_name;
2558     BuiltinFunctionId id;
2559   };
2560
2561   const BuiltinFunctionIds builtins[] = {
2562       FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2563
2564   for (const BuiltinFunctionIds& builtin : builtins) {
2565     Handle<JSObject> holder =
2566         ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2567     InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2568   }
2569 }
2570
2571
2572 void Genesis::InstallExperimentalBuiltinFunctionIds() {
2573   if (FLAG_harmony_atomics) {
2574     struct BuiltinFunctionIds {
2575       const char* holder_expr;
2576       const char* fun_name;
2577       BuiltinFunctionId id;
2578     };
2579
2580     const BuiltinFunctionIds atomic_builtins[] = {
2581         ATOMIC_FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2582
2583     for (const BuiltinFunctionIds& builtin : atomic_builtins) {
2584       Handle<JSObject> holder =
2585           ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2586       InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2587     }
2588   }
2589 }
2590
2591
2592 #undef INSTALL_BUILTIN_ID
2593
2594
2595 void Genesis::InitializeNormalizedMapCaches() {
2596   Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
2597   native_context()->set_normalized_map_cache(*cache);
2598 }
2599
2600
2601 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
2602                                      v8::ExtensionConfiguration* extensions) {
2603   BootstrapperActive active(this);
2604   SaveContext saved_context(isolate_);
2605   isolate_->set_context(*native_context);
2606   return Genesis::InstallExtensions(native_context, extensions) &&
2607       Genesis::InstallSpecialObjects(native_context);
2608 }
2609
2610
2611 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
2612   Isolate* isolate = native_context->GetIsolate();
2613   // Don't install extensions into the snapshot.
2614   if (isolate->serializer_enabled()) return true;
2615
2616   Factory* factory = isolate->factory();
2617   HandleScope scope(isolate);
2618   Handle<JSGlobalObject> global(JSGlobalObject::cast(
2619       native_context->global_object()));
2620
2621   Handle<JSObject> Error = Handle<JSObject>::cast(
2622       Object::GetProperty(isolate, global, "Error").ToHandleChecked());
2623   Handle<String> name =
2624       factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("stackTraceLimit"));
2625   Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit), isolate);
2626   JSObject::AddProperty(Error, name, stack_trace_limit, NONE);
2627
2628   // Expose the natives in global if a name for it is specified.
2629   if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
2630     Handle<String> natives_key =
2631         factory->InternalizeUtf8String(FLAG_expose_natives_as);
2632     uint32_t dummy_index;
2633     if (natives_key->AsArrayIndex(&dummy_index)) return true;
2634     Handle<JSBuiltinsObject> natives(global->builtins());
2635     JSObject::AddProperty(global, natives_key, natives, DONT_ENUM);
2636   }
2637
2638   // Expose the debug global object in global if a name for it is specified.
2639   if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
2640     // If loading fails we just bail out without installing the
2641     // debugger but without tanking the whole context.
2642     Debug* debug = isolate->debug();
2643     if (!debug->Load()) return true;
2644     Handle<Context> debug_context = debug->debug_context();
2645     // Set the security token for the debugger context to the same as
2646     // the shell native context to allow calling between these (otherwise
2647     // exposing debug global object doesn't make much sense).
2648     debug_context->set_security_token(native_context->security_token());
2649     Handle<String> debug_string =
2650         factory->InternalizeUtf8String(FLAG_expose_debug_as);
2651     uint32_t index;
2652     if (debug_string->AsArrayIndex(&index)) return true;
2653     Handle<Object> global_proxy(debug_context->global_proxy(), isolate);
2654     JSObject::AddProperty(global, debug_string, global_proxy, DONT_ENUM);
2655   }
2656
2657 #if defined(V8_WASM)
2658   WasmJs::Install(isolate, global);
2659 #endif
2660
2661   return true;
2662 }
2663
2664
2665 static uint32_t Hash(RegisteredExtension* extension) {
2666   return v8::internal::ComputePointerHash(extension);
2667 }
2668
2669
2670 Genesis::ExtensionStates::ExtensionStates() : map_(HashMap::PointersMatch, 8) {}
2671
2672 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2673     RegisteredExtension* extension) {
2674   i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension));
2675   if (entry == NULL) {
2676     return UNVISITED;
2677   }
2678   return static_cast<ExtensionTraversalState>(
2679       reinterpret_cast<intptr_t>(entry->value));
2680 }
2681
2682 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2683                                          ExtensionTraversalState state) {
2684   map_.LookupOrInsert(extension, Hash(extension))->value =
2685       reinterpret_cast<void*>(static_cast<intptr_t>(state));
2686 }
2687
2688
2689 bool Genesis::InstallExtensions(Handle<Context> native_context,
2690                                 v8::ExtensionConfiguration* extensions) {
2691   Isolate* isolate = native_context->GetIsolate();
2692   ExtensionStates extension_states;  // All extensions have state UNVISITED.
2693   return InstallAutoExtensions(isolate, &extension_states) &&
2694       (!FLAG_expose_free_buffer ||
2695        InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
2696       (!FLAG_expose_gc ||
2697        InstallExtension(isolate, "v8/gc", &extension_states)) &&
2698       (!FLAG_expose_externalize_string ||
2699        InstallExtension(isolate, "v8/externalize", &extension_states)) &&
2700       (!FLAG_track_gc_object_stats ||
2701        InstallExtension(isolate, "v8/statistics", &extension_states)) &&
2702       (!FLAG_expose_trigger_failure ||
2703        InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
2704       InstallRequestedExtensions(isolate, extensions, &extension_states);
2705 }
2706
2707
2708 bool Genesis::InstallAutoExtensions(Isolate* isolate,
2709                                     ExtensionStates* extension_states) {
2710   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2711        it != NULL;
2712        it = it->next()) {
2713     if (it->extension()->auto_enable() &&
2714         !InstallExtension(isolate, it, extension_states)) {
2715       return false;
2716     }
2717   }
2718   return true;
2719 }
2720
2721
2722 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
2723                                          v8::ExtensionConfiguration* extensions,
2724                                          ExtensionStates* extension_states) {
2725   for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
2726     if (!InstallExtension(isolate, *it, extension_states)) return false;
2727   }
2728   return true;
2729 }
2730
2731
2732 // Installs a named extension.  This methods is unoptimized and does
2733 // not scale well if we want to support a large number of extensions.
2734 bool Genesis::InstallExtension(Isolate* isolate,
2735                                const char* name,
2736                                ExtensionStates* extension_states) {
2737   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2738        it != NULL;
2739        it = it->next()) {
2740     if (strcmp(name, it->extension()->name()) == 0) {
2741       return InstallExtension(isolate, it, extension_states);
2742     }
2743   }
2744   return Utils::ApiCheck(false,
2745                          "v8::Context::New()",
2746                          "Cannot find required extension");
2747 }
2748
2749
2750 bool Genesis::InstallExtension(Isolate* isolate,
2751                                v8::RegisteredExtension* current,
2752                                ExtensionStates* extension_states) {
2753   HandleScope scope(isolate);
2754
2755   if (extension_states->get_state(current) == INSTALLED) return true;
2756   // The current node has already been visited so there must be a
2757   // cycle in the dependency graph; fail.
2758   if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
2759                        "v8::Context::New()",
2760                        "Circular extension dependency")) {
2761     return false;
2762   }
2763   DCHECK(extension_states->get_state(current) == UNVISITED);
2764   extension_states->set_state(current, VISITED);
2765   v8::Extension* extension = current->extension();
2766   // Install the extension's dependencies
2767   for (int i = 0; i < extension->dependency_count(); i++) {
2768     if (!InstallExtension(isolate,
2769                           extension->dependencies()[i],
2770                           extension_states)) {
2771       return false;
2772     }
2773   }
2774   // We do not expect this to throw an exception. Change this if it does.
2775   bool result = CompileExtension(isolate, extension);
2776   DCHECK(isolate->has_pending_exception() != result);
2777   if (!result) {
2778     // We print out the name of the extension that fail to install.
2779     // When an error is thrown during bootstrapping we automatically print
2780     // the line number at which this happened to the console in the isolate
2781     // error throwing functionality.
2782     base::OS::PrintError("Error installing extension '%s'.\n",
2783                          current->extension()->name());
2784     isolate->clear_pending_exception();
2785   }
2786   extension_states->set_state(current, INSTALLED);
2787   isolate->NotifyExtensionInstalled();
2788   return result;
2789 }
2790
2791
2792 bool Genesis::ConfigureGlobalObjects(
2793     v8::Local<v8::ObjectTemplate> global_proxy_template) {
2794   Handle<JSObject> global_proxy(
2795       JSObject::cast(native_context()->global_proxy()));
2796   Handle<JSObject> global_object(
2797       JSObject::cast(native_context()->global_object()));
2798
2799   if (!global_proxy_template.IsEmpty()) {
2800     // Configure the global proxy object.
2801     Handle<ObjectTemplateInfo> global_proxy_data =
2802         v8::Utils::OpenHandle(*global_proxy_template);
2803     if (!ConfigureApiObject(global_proxy, global_proxy_data)) return false;
2804
2805     // Configure the global object.
2806     Handle<FunctionTemplateInfo> proxy_constructor(
2807         FunctionTemplateInfo::cast(global_proxy_data->constructor()));
2808     if (!proxy_constructor->prototype_template()->IsUndefined()) {
2809       Handle<ObjectTemplateInfo> global_object_data(
2810           ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2811       if (!ConfigureApiObject(global_object, global_object_data)) return false;
2812     }
2813   }
2814
2815   SetObjectPrototype(global_proxy, global_object);
2816
2817   native_context()->set_initial_array_prototype(
2818       JSArray::cast(native_context()->array_function()->prototype()));
2819   native_context()->set_array_buffer_map(
2820       native_context()->array_buffer_fun()->initial_map());
2821   native_context()->set_js_map_map(
2822       native_context()->js_map_fun()->initial_map());
2823   native_context()->set_js_set_map(
2824       native_context()->js_set_fun()->initial_map());
2825
2826   return true;
2827 }
2828
2829
2830 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
2831                                  Handle<ObjectTemplateInfo> object_template) {
2832   DCHECK(!object_template.is_null());
2833   DCHECK(FunctionTemplateInfo::cast(object_template->constructor())
2834              ->IsTemplateFor(object->map()));;
2835
2836   MaybeHandle<JSObject> maybe_obj =
2837       ApiNatives::InstantiateObject(object_template);
2838   Handle<JSObject> obj;
2839   if (!maybe_obj.ToHandle(&obj)) {
2840     DCHECK(isolate()->has_pending_exception());
2841     isolate()->clear_pending_exception();
2842     return false;
2843   }
2844   TransferObject(obj, object);
2845   return true;
2846 }
2847
2848
2849 void Genesis::TransferNamedProperties(Handle<JSObject> from,
2850                                       Handle<JSObject> to) {
2851   // If JSObject::AddProperty asserts due to already existing property,
2852   // it is likely due to both global objects sharing property name(s).
2853   // Merging those two global objects is impossible.
2854   // The global template must not create properties that already exist
2855   // in the snapshotted global object.
2856   if (from->HasFastProperties()) {
2857     Handle<DescriptorArray> descs =
2858         Handle<DescriptorArray>(from->map()->instance_descriptors());
2859     for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
2860       PropertyDetails details = descs->GetDetails(i);
2861       switch (details.type()) {
2862         case DATA: {
2863           HandleScope inner(isolate());
2864           Handle<Name> key = Handle<Name>(descs->GetKey(i));
2865           FieldIndex index = FieldIndex::ForDescriptor(from->map(), i);
2866           DCHECK(!descs->GetDetails(i).representation().IsDouble());
2867           Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
2868                                                 isolate());
2869           JSObject::AddProperty(to, key, value, details.attributes());
2870           break;
2871         }
2872         case DATA_CONSTANT: {
2873           HandleScope inner(isolate());
2874           Handle<Name> key = Handle<Name>(descs->GetKey(i));
2875           Handle<Object> constant(descs->GetConstant(i), isolate());
2876           JSObject::AddProperty(to, key, constant, details.attributes());
2877           break;
2878         }
2879         case ACCESSOR:
2880           UNREACHABLE();
2881         case ACCESSOR_CONSTANT: {
2882           Handle<Name> key(descs->GetKey(i));
2883           LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
2884           CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
2885           // If the property is already there we skip it
2886           if (it.IsFound()) continue;
2887           HandleScope inner(isolate());
2888           DCHECK(!to->HasFastProperties());
2889           // Add to dictionary.
2890           Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
2891           PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
2892                             PropertyCellType::kMutable);
2893           JSObject::SetNormalizedProperty(to, key, callbacks, d);
2894           break;
2895         }
2896       }
2897     }
2898   } else if (from->IsGlobalObject()) {
2899     Handle<GlobalDictionary> properties =
2900         Handle<GlobalDictionary>(from->global_dictionary());
2901     int capacity = properties->Capacity();
2902     for (int i = 0; i < capacity; i++) {
2903       Object* raw_key(properties->KeyAt(i));
2904       if (properties->IsKey(raw_key)) {
2905         DCHECK(raw_key->IsName());
2906         // If the property is already there we skip it.
2907         Handle<Name> key(Name::cast(raw_key));
2908         LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
2909         CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
2910         if (it.IsFound()) continue;
2911         // Set the property.
2912         DCHECK(properties->ValueAt(i)->IsPropertyCell());
2913         Handle<PropertyCell> cell(PropertyCell::cast(properties->ValueAt(i)));
2914         Handle<Object> value(cell->value(), isolate());
2915         if (value->IsTheHole()) continue;
2916         PropertyDetails details = cell->property_details();
2917         DCHECK_EQ(kData, details.kind());
2918         JSObject::AddProperty(to, key, value, details.attributes());
2919       }
2920     }
2921   } else {
2922     Handle<NameDictionary> properties =
2923         Handle<NameDictionary>(from->property_dictionary());
2924     int capacity = properties->Capacity();
2925     for (int i = 0; i < capacity; i++) {
2926       Object* raw_key(properties->KeyAt(i));
2927       if (properties->IsKey(raw_key)) {
2928         DCHECK(raw_key->IsName());
2929         // If the property is already there we skip it.
2930         Handle<Name> key(Name::cast(raw_key));
2931         LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
2932         CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
2933         if (it.IsFound()) continue;
2934         // Set the property.
2935         Handle<Object> value = Handle<Object>(properties->ValueAt(i),
2936                                               isolate());
2937         DCHECK(!value->IsCell());
2938         DCHECK(!value->IsTheHole());
2939         PropertyDetails details = properties->DetailsAt(i);
2940         DCHECK_EQ(kData, details.kind());
2941         JSObject::AddProperty(to, key, value, details.attributes());
2942       }
2943     }
2944   }
2945 }
2946
2947
2948 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
2949                                         Handle<JSObject> to) {
2950   // Cloning the elements array is sufficient.
2951   Handle<FixedArray> from_elements =
2952       Handle<FixedArray>(FixedArray::cast(from->elements()));
2953   Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
2954   to->set_elements(*to_elements);
2955 }
2956
2957
2958 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
2959   HandleScope outer(isolate());
2960
2961   DCHECK(!from->IsJSArray());
2962   DCHECK(!to->IsJSArray());
2963
2964   TransferNamedProperties(from, to);
2965   TransferIndexedProperties(from, to);
2966
2967   // Transfer the prototype (new map is needed).
2968   Handle<Object> proto(from->map()->prototype(), isolate());
2969   SetObjectPrototype(to, proto);
2970 }
2971
2972
2973 void Genesis::MakeFunctionInstancePrototypeWritable() {
2974   // The maps with writable prototype are created in CreateEmptyFunction
2975   // and CreateStrictModeFunctionMaps respectively. Initially the maps are
2976   // created with read-only prototype for JS builtins processing.
2977   DCHECK(!sloppy_function_map_writable_prototype_.is_null());
2978   DCHECK(!strict_function_map_writable_prototype_.is_null());
2979
2980   // Replace function instance maps to make prototype writable.
2981   native_context()->set_sloppy_function_map(
2982       *sloppy_function_map_writable_prototype_);
2983   native_context()->set_strict_function_map(
2984       *strict_function_map_writable_prototype_);
2985 }
2986
2987
2988 class NoTrackDoubleFieldsForSerializerScope {
2989  public:
2990   explicit NoTrackDoubleFieldsForSerializerScope(Isolate* isolate)
2991       : flag_(FLAG_track_double_fields), enabled_(false) {
2992     if (isolate->serializer_enabled()) {
2993       // Disable tracking double fields because heap numbers treated as
2994       // immutable by the serializer.
2995       FLAG_track_double_fields = false;
2996       enabled_ = true;
2997     }
2998   }
2999
3000   ~NoTrackDoubleFieldsForSerializerScope() {
3001     if (enabled_) {
3002       FLAG_track_double_fields = flag_;
3003     }
3004   }
3005
3006  private:
3007   bool flag_;
3008   bool enabled_;
3009 };
3010
3011
3012 Genesis::Genesis(Isolate* isolate,
3013                  MaybeHandle<JSGlobalProxy> maybe_global_proxy,
3014                  v8::Local<v8::ObjectTemplate> global_proxy_template,
3015                  v8::ExtensionConfiguration* extensions,
3016                  ContextType context_type)
3017     : isolate_(isolate), active_(isolate->bootstrapper()) {
3018   NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
3019   result_ = Handle<Context>::null();
3020   // Before creating the roots we must save the context and restore it
3021   // on all function exits.
3022   SaveContext saved_context(isolate);
3023
3024   // During genesis, the boilerplate for stack overflow won't work until the
3025   // environment has been at least partially initialized. Add a stack check
3026   // before entering JS code to catch overflow early.
3027   StackLimitCheck check(isolate);
3028   if (check.HasOverflowed()) {
3029     isolate->StackOverflow();
3030     return;
3031   }
3032
3033   // The deserializer needs to hook up references to the global proxy.
3034   // Create an uninitialized global proxy now if we don't have one
3035   // and initialize it later in CreateNewGlobals.
3036   Handle<JSGlobalProxy> global_proxy;
3037   if (!maybe_global_proxy.ToHandle(&global_proxy)) {
3038     global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy();
3039   }
3040
3041   // We can only de-serialize a context if the isolate was initialized from
3042   // a snapshot. Otherwise we have to build the context from scratch.
3043   // Also create a context from scratch to expose natives, if required by flag.
3044   Handle<FixedArray> outdated_contexts;
3045   if (!isolate->initialized_from_snapshot() ||
3046       !Snapshot::NewContextFromSnapshot(isolate, global_proxy,
3047                                         &outdated_contexts)
3048            .ToHandle(&native_context_)) {
3049     native_context_ = Handle<Context>();
3050   }
3051
3052   if (!native_context().is_null()) {
3053     AddToWeakNativeContextList(*native_context());
3054     isolate->set_context(*native_context());
3055     isolate->counters()->contexts_created_by_snapshot()->Increment();
3056 #if TRACE_MAPS
3057     if (FLAG_trace_maps) {
3058       Handle<JSFunction> object_fun = isolate->object_function();
3059       PrintF("[TraceMap: InitialMap map= %p SFI= %d_Object ]\n",
3060              reinterpret_cast<void*>(object_fun->initial_map()),
3061              object_fun->shared()->unique_id());
3062       Map::TraceAllTransitions(object_fun->initial_map());
3063     }
3064 #endif
3065     Handle<GlobalObject> global_object =
3066         CreateNewGlobals(global_proxy_template, global_proxy);
3067
3068     HookUpGlobalProxy(global_object, global_proxy);
3069     HookUpGlobalObject(global_object, outdated_contexts);
3070     native_context()->builtins()->set_global_proxy(
3071         native_context()->global_proxy());
3072     HookUpGlobalThisBinding(outdated_contexts);
3073
3074     if (!ConfigureGlobalObjects(global_proxy_template)) return;
3075   } else {
3076     // We get here if there was no context snapshot.
3077     CreateRoots();
3078     Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
3079     CreateStrictModeFunctionMaps(empty_function);
3080     CreateStrongModeFunctionMaps(empty_function);
3081     Handle<GlobalObject> global_object =
3082         CreateNewGlobals(global_proxy_template, global_proxy);
3083     HookUpGlobalProxy(global_object, global_proxy);
3084     InitializeGlobal(global_object, empty_function, context_type);
3085     InitializeNormalizedMapCaches();
3086
3087     if (!InstallNatives(context_type)) return;
3088
3089     MakeFunctionInstancePrototypeWritable();
3090
3091     if (context_type != THIN_CONTEXT) {
3092       if (!InstallExtraNatives()) return;
3093       if (!ConfigureGlobalObjects(global_proxy_template)) return;
3094     }
3095     isolate->counters()->contexts_created_from_scratch()->Increment();
3096   }
3097
3098   // Install experimental natives. Do not include them into the
3099   // snapshot as we should be able to turn them off at runtime. Re-installing
3100   // them after they have already been deserialized would also fail.
3101   if (context_type == FULL_CONTEXT) {
3102     if (!isolate->serializer_enabled()) {
3103       InitializeExperimentalGlobal();
3104       if (!InstallExperimentalNatives()) return;
3105
3106       if (FLAG_experimental_extras) {
3107         if (!InstallExperimentalExtraNatives()) return;
3108       }
3109
3110       // By now the utils object is useless and can be removed.
3111       native_context()->set_natives_utils_object(
3112           isolate->heap()->undefined_value());
3113     }
3114     // The serializer cannot serialize typed arrays. Reset those typed arrays
3115     // for each new context.
3116     InitializeBuiltinTypedArrays();
3117   } else if (context_type == DEBUG_CONTEXT) {
3118     DCHECK(!isolate->serializer_enabled());
3119     InitializeExperimentalGlobal();
3120     if (!InstallDebuggerNatives()) return;
3121   }
3122
3123   // Check that the script context table is empty except for the 'this' binding.
3124   // We do not need script contexts for native scripts.
3125   DCHECK_EQ(1, native_context()->script_context_table()->used());
3126
3127   result_ = native_context();
3128 }
3129
3130
3131 // Support for thread preemption.
3132
3133 // Reserve space for statics needing saving and restoring.
3134 int Bootstrapper::ArchiveSpacePerThread() {
3135   return sizeof(NestingCounterType);
3136 }
3137
3138
3139 // Archive statics that are thread-local.
3140 char* Bootstrapper::ArchiveState(char* to) {
3141   *reinterpret_cast<NestingCounterType*>(to) = nesting_;
3142   nesting_ = 0;
3143   return to + sizeof(NestingCounterType);
3144 }
3145
3146
3147 // Restore statics that are thread-local.
3148 char* Bootstrapper::RestoreState(char* from) {
3149   nesting_ = *reinterpret_cast<NestingCounterType*>(from);
3150   return from + sizeof(NestingCounterType);
3151 }
3152
3153
3154 // Called when the top-level V8 mutex is destroyed.
3155 void Bootstrapper::FreeThreadResources() {
3156   DCHECK(!IsActive());
3157 }
3158
3159 }  // namespace internal
3160 }  // namespace v8