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