Revert of Remove property loads from js builtins objects from runtime. (patchset...
[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, "JsonSerializeAdapter", json_serialize_adapter);
1758
1759   INSTALL_NATIVE(JSFunction, "Error", error_function);
1760   INSTALL_NATIVE(JSFunction, "EvalError", eval_error_function);
1761   INSTALL_NATIVE(JSFunction, "RangeError", range_error_function);
1762   INSTALL_NATIVE(JSFunction, "ReferenceError", reference_error_function);
1763   INSTALL_NATIVE(JSFunction, "SyntaxError", syntax_error_function);
1764   INSTALL_NATIVE(JSFunction, "TypeError", type_error_function);
1765   INSTALL_NATIVE(JSFunction, "URIError", uri_error_function);
1766   INSTALL_NATIVE(JSFunction, "MakeError", make_error_function);
1767
1768   INSTALL_NATIVE(Symbol, "promiseStatus", promise_status);
1769   INSTALL_NATIVE(Symbol, "promiseValue", promise_value);
1770   INSTALL_NATIVE(JSFunction, "PromiseCreate", promise_create);
1771   INSTALL_NATIVE(JSFunction, "PromiseResolve", promise_resolve);
1772   INSTALL_NATIVE(JSFunction, "PromiseReject", promise_reject);
1773   INSTALL_NATIVE(JSFunction, "PromiseChain", promise_chain);
1774   INSTALL_NATIVE(JSFunction, "PromiseCatch", promise_catch);
1775   INSTALL_NATIVE(JSFunction, "PromiseThen", promise_then);
1776   INSTALL_NATIVE(JSFunction, "PromiseHasUserDefinedRejectHandler",
1777                  promise_has_user_defined_reject_handler);
1778
1779   INSTALL_NATIVE(JSFunction, "ObserveNotifyChange", observers_notify_change);
1780   INSTALL_NATIVE(JSFunction, "ObserveEnqueueSpliceRecord",
1781                  observers_enqueue_splice);
1782   INSTALL_NATIVE(JSFunction, "ObserveBeginPerformSplice",
1783                  observers_begin_perform_splice);
1784   INSTALL_NATIVE(JSFunction, "ObserveEndPerformSplice",
1785                  observers_end_perform_splice);
1786   INSTALL_NATIVE(JSFunction, "ObserveNativeObjectObserve",
1787                  native_object_observe);
1788   INSTALL_NATIVE(JSFunction, "ObserveNativeObjectGetNotifier",
1789                  native_object_get_notifier);
1790   INSTALL_NATIVE(JSFunction, "ObserveNativeObjectNotifierPerformChange",
1791                  native_object_notifier_perform_change);
1792
1793   INSTALL_NATIVE(JSFunction, "ArrayValues", array_values_iterator);
1794   INSTALL_NATIVE(JSFunction, "MapGet", map_get);
1795   INSTALL_NATIVE(JSFunction, "MapSet", map_set);
1796   INSTALL_NATIVE(JSFunction, "MapHas", map_has);
1797   INSTALL_NATIVE(JSFunction, "MapDelete", map_delete);
1798   INSTALL_NATIVE(JSFunction, "SetAdd", set_add);
1799   INSTALL_NATIVE(JSFunction, "SetHas", set_has);
1800   INSTALL_NATIVE(JSFunction, "SetDelete", set_delete);
1801   INSTALL_NATIVE(JSFunction, "MapFromArray", map_from_array);
1802   INSTALL_NATIVE(JSFunction, "SetFromArray", set_from_array);
1803 }
1804
1805
1806 #define EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(id)                                \
1807   static void InstallExperimentalNatives_##id(Isolate* isolate,               \
1808                                               Handle<Context> native_context, \
1809                                               Handle<JSObject> container) {}
1810
1811 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_modules)
1812 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_array_includes)
1813 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_regexps)
1814 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_arrow_functions)
1815 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_tostring)
1816 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy)
1817 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy_function)
1818 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy_let)
1819 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_unicode_regexps)
1820 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_rest_parameters)
1821 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_default_parameters)
1822 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_reflect)
1823 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spreadcalls)
1824 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_destructuring)
1825 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_object)
1826 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_object_observe)
1827 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spread_arrays)
1828 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sharedarraybuffer)
1829 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_atomics)
1830 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_new_target)
1831 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_concat_spreadable)
1832 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_simd)
1833
1834
1835 static void InstallExperimentalNatives_harmony_proxies(
1836     Isolate* isolate, Handle<Context> native_context,
1837     Handle<JSObject> container) {
1838   if (FLAG_harmony_proxies) {
1839     INSTALL_NATIVE(JSFunction, "ProxyDerivedGetTrap", derived_get_trap);
1840     INSTALL_NATIVE(JSFunction, "ProxyDerivedHasTrap", derived_has_trap);
1841     INSTALL_NATIVE(JSFunction, "ProxyDerivedSetTrap", derived_set_trap);
1842     INSTALL_NATIVE(JSFunction, "ProxyEnumerate", proxy_enumerate);
1843   }
1844 }
1845
1846
1847 void Bootstrapper::ImportExperimentalNatives(Isolate* isolate,
1848                                              Handle<JSObject> container) {
1849   HandleScope scope(isolate);
1850   Handle<Context> native_context = isolate->native_context();
1851 #define INSTALL_NATIVE_FUNCTIONS_FOR(id, descr) \
1852   InstallExperimentalNatives_##id(isolate, native_context, container);
1853
1854   HARMONY_INPROGRESS(INSTALL_NATIVE_FUNCTIONS_FOR)
1855   HARMONY_STAGED(INSTALL_NATIVE_FUNCTIONS_FOR)
1856   HARMONY_SHIPPING(INSTALL_NATIVE_FUNCTIONS_FOR)
1857 #undef INSTALL_NATIVE_FUNCTIONS_FOR
1858 }
1859
1860 #undef INSTALL_NATIVE
1861
1862 #define EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(id) \
1863   void Genesis::InitializeGlobal_##id() {}
1864
1865 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_modules)
1866 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_array_includes)
1867 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_arrow_functions)
1868 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_proxies)
1869 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy)
1870 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy_function)
1871 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy_let)
1872 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_rest_parameters)
1873 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_default_parameters)
1874 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spreadcalls)
1875 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_destructuring)
1876 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_object)
1877 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_object_observe)
1878 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spread_arrays)
1879 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_atomics)
1880 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_new_target)
1881 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_concat_spreadable)
1882
1883 void Genesis::InitializeGlobal_harmony_regexps() {
1884   Handle<JSObject> builtins(native_context()->builtins());
1885
1886   Handle<HeapObject> flag(FLAG_harmony_regexps ? heap()->true_value()
1887                                                : heap()->false_value());
1888   Runtime::SetObjectProperty(isolate(), builtins,
1889                              factory()->harmony_regexps_string(), flag,
1890                              STRICT).Assert();
1891 }
1892
1893
1894 void Genesis::InitializeGlobal_harmony_unicode_regexps() {
1895   Handle<JSObject> builtins(native_context()->builtins());
1896
1897   Handle<HeapObject> flag(FLAG_harmony_unicode_regexps ? heap()->true_value()
1898                                                        : heap()->false_value());
1899   Runtime::SetObjectProperty(isolate(), builtins,
1900                              factory()->harmony_unicode_regexps_string(), flag,
1901                              STRICT).Assert();
1902 }
1903
1904
1905 void Genesis::InitializeGlobal_harmony_reflect() {
1906   Handle<JSObject> builtins(native_context()->builtins());
1907
1908   Handle<JSFunction> apply = InstallFunction(
1909       builtins, "$reflectApply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1910       MaybeHandle<JSObject>(), Builtins::kReflectApply);
1911   apply->shared()->set_internal_formal_parameter_count(3);
1912   apply->shared()->set_length(3);
1913
1914   Handle<JSFunction> construct = InstallFunction(
1915       builtins, "$reflectConstruct", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1916       MaybeHandle<JSObject>(), Builtins::kReflectConstruct);
1917   construct->shared()->set_internal_formal_parameter_count(3);
1918   construct->shared()->set_length(2);
1919
1920   if (!FLAG_harmony_reflect) return;
1921
1922   Handle<JSGlobalObject> global(JSGlobalObject::cast(
1923       native_context()->global_object()));
1924   Handle<String> reflect_string =
1925       factory()->NewStringFromStaticChars("Reflect");
1926   Handle<Object> reflect =
1927       factory()->NewJSObject(isolate()->object_function(), TENURED);
1928   JSObject::AddProperty(global, reflect_string, reflect, DONT_ENUM);
1929 }
1930
1931
1932 void Genesis::InitializeGlobal_harmony_tostring() {
1933   Handle<JSObject> builtins(native_context()->builtins());
1934
1935   Handle<HeapObject> flag(FLAG_harmony_tostring ? heap()->true_value()
1936                                                 : heap()->false_value());
1937   Runtime::SetObjectProperty(isolate(), builtins,
1938                              factory()->harmony_tostring_string(), flag,
1939                              STRICT).Assert();
1940 }
1941
1942
1943 void Genesis::InitializeGlobal_harmony_sharedarraybuffer() {
1944   if (!FLAG_harmony_sharedarraybuffer) return;
1945
1946   Handle<JSGlobalObject> global(
1947       JSGlobalObject::cast(native_context()->global_object()));
1948
1949   Handle<JSFunction> shared_array_buffer_fun = InstallFunction(
1950       global, "SharedArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1951       JSArrayBuffer::kSizeWithInternalFields,
1952       isolate()->initial_object_prototype(), Builtins::kIllegal);
1953   native_context()->set_shared_array_buffer_fun(*shared_array_buffer_fun);
1954 }
1955
1956
1957 void Genesis::InitializeGlobal_harmony_simd() {
1958   if (!FLAG_harmony_simd) return;
1959
1960   Handle<JSGlobalObject> global(
1961       JSGlobalObject::cast(native_context()->global_object()));
1962   Isolate* isolate = global->GetIsolate();
1963   Factory* factory = isolate->factory();
1964
1965   Handle<String> name = factory->InternalizeUtf8String("SIMD");
1966   Handle<JSFunction> cons = factory->NewFunction(name);
1967   JSFunction::SetInstancePrototype(
1968       cons,
1969       Handle<Object>(native_context()->initial_object_prototype(), isolate));
1970   cons->SetInstanceClassName(*name);
1971   Handle<JSObject> simd_object = factory->NewJSObject(cons, TENURED);
1972   DCHECK(simd_object->IsJSObject());
1973   JSObject::AddProperty(global, name, simd_object, DONT_ENUM);
1974
1975 // Install SIMD type functions. Set the instance class names since
1976 // InstallFunction only does this when we install on the GlobalObject.
1977 #define SIMD128_INSTALL_FUNCTION(TYPE, Type, type, lane_count, lane_type) \
1978   Handle<JSFunction> type##_function = InstallFunction(                   \
1979       simd_object, #Type, JS_VALUE_TYPE, JSValue::kSize,                  \
1980       isolate->initial_object_prototype(), Builtins::kIllegal);           \
1981   native_context()->set_##type##_function(*type##_function);              \
1982   type##_function->SetInstanceClassName(*factory->Type##_string());
1983   SIMD128_TYPES(SIMD128_INSTALL_FUNCTION)
1984 #undef SIMD128_INSTALL_FUNCTION
1985 }
1986
1987
1988 Handle<JSFunction> Genesis::InstallInternalArray(Handle<JSObject> target,
1989                                                  const char* name,
1990                                                  ElementsKind elements_kind) {
1991   // --- I n t e r n a l   A r r a y ---
1992   // An array constructor on the builtins object that works like
1993   // the public Array constructor, except that its prototype
1994   // doesn't inherit from Object.prototype.
1995   // To be used only for internal work by builtins. Instances
1996   // must not be leaked to user code.
1997   Handle<JSObject> prototype =
1998       factory()->NewJSObject(isolate()->object_function(), TENURED);
1999   Handle<JSFunction> array_function =
2000       InstallFunction(target, name, JS_ARRAY_TYPE, JSArray::kSize, prototype,
2001                       Builtins::kInternalArrayCode);
2002
2003   InternalArrayConstructorStub internal_array_constructor_stub(isolate());
2004   Handle<Code> code = internal_array_constructor_stub.GetCode();
2005   array_function->shared()->set_construct_stub(*code);
2006   array_function->shared()->DontAdaptArguments();
2007
2008   Handle<Map> original_map(array_function->initial_map());
2009   Handle<Map> initial_map = Map::Copy(original_map, "InternalArray");
2010   initial_map->set_elements_kind(elements_kind);
2011   JSFunction::SetInitialMap(array_function, initial_map, prototype);
2012
2013   // Make "length" magic on instances.
2014   Map::EnsureDescriptorSlack(initial_map, 1);
2015
2016   PropertyAttributes attribs = static_cast<PropertyAttributes>(
2017       DONT_ENUM | DONT_DELETE);
2018
2019   Handle<AccessorInfo> array_length =
2020       Accessors::ArrayLengthInfo(isolate(), attribs);
2021   {  // Add length.
2022     AccessorConstantDescriptor d(Handle<Name>(Name::cast(array_length->name())),
2023                                  array_length, attribs);
2024     initial_map->AppendDescriptor(&d);
2025   }
2026
2027   return array_function;
2028 }
2029
2030
2031 bool Genesis::InstallNatives(ContextType context_type) {
2032   HandleScope scope(isolate());
2033
2034   // Create a function for the builtins object. Allocate space for the
2035   // JavaScript builtins, a reference to the builtins object
2036   // (itself) and a reference to the native_context directly in the object.
2037   Handle<Code> code = Handle<Code>(
2038       isolate()->builtins()->builtin(Builtins::kIllegal));
2039   Handle<JSFunction> builtins_fun = factory()->NewFunction(
2040       factory()->empty_string(), code, JS_BUILTINS_OBJECT_TYPE,
2041       JSBuiltinsObject::kSize);
2042
2043   Handle<String> name =
2044       factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2045   builtins_fun->shared()->set_instance_class_name(*name);
2046   builtins_fun->initial_map()->set_dictionary_map(true);
2047   builtins_fun->initial_map()->set_prototype(heap()->null_value());
2048
2049   // Allocate the builtins object.
2050   Handle<JSBuiltinsObject> builtins =
2051       Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
2052   builtins->set_builtins(*builtins);
2053   builtins->set_native_context(*native_context());
2054   builtins->set_global_proxy(native_context()->global_proxy());
2055
2056
2057   // Set up the 'builtin' property, which refers to the js builtins object.
2058   static const PropertyAttributes attributes =
2059       static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2060   Handle<String> builtins_string =
2061       factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2062   JSObject::AddProperty(builtins, builtins_string, builtins, attributes);
2063
2064   // Set up the reference from the global object to the builtins object.
2065   JSGlobalObject::cast(native_context()->global_object())->
2066       set_builtins(*builtins);
2067
2068   // Create a bridge function that has context in the native context.
2069   Handle<JSFunction> bridge = factory()->NewFunction(factory()->empty_string());
2070   DCHECK(bridge->context() == *isolate()->native_context());
2071
2072   // Allocate the builtins context.
2073   Handle<Context> context =
2074     factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
2075   context->set_global_object(*builtins);  // override builtins global object
2076
2077   native_context()->set_runtime_context(*context);
2078
2079   if (context_type == THIN_CONTEXT) {
2080     int js_builtins_script_index = Natives::GetDebuggerCount();
2081     if (!Bootstrapper::CompileBuiltin(isolate(), js_builtins_script_index))
2082       return false;
2083     if (!InstallJSBuiltins(builtins)) return false;
2084     return true;
2085   }
2086
2087   // Set up the utils object as shared container between native scripts.
2088   Handle<JSObject> utils = factory()->NewJSObject(isolate()->object_function());
2089   JSObject::NormalizeProperties(utils, CLEAR_INOBJECT_PROPERTIES, 16,
2090                                 "utils container for native scripts");
2091   native_context()->set_natives_utils_object(*utils);
2092
2093   if (FLAG_expose_natives_as != NULL) {
2094     Handle<String> utils_key = factory()->NewStringFromAsciiChecked("utils");
2095     JSObject::AddProperty(builtins, utils_key, utils, NONE);
2096   }
2097
2098   {  // -- S c r i p t
2099     // Builtin functions for Script.
2100     Handle<JSFunction> script_fun = InstallFunction(
2101         builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
2102         isolate()->initial_object_prototype(), Builtins::kIllegal);
2103     Handle<JSObject> prototype =
2104         factory()->NewJSObject(isolate()->object_function(), TENURED);
2105     Accessors::FunctionSetPrototype(script_fun, prototype).Assert();
2106     native_context()->set_script_function(*script_fun);
2107
2108     Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
2109     Map::EnsureDescriptorSlack(script_map, 15);
2110
2111     PropertyAttributes attribs =
2112         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2113
2114     Handle<AccessorInfo> script_column =
2115         Accessors::ScriptColumnOffsetInfo(isolate(), attribs);
2116     {
2117       AccessorConstantDescriptor d(
2118           Handle<Name>(Name::cast(script_column->name())), script_column,
2119           attribs);
2120       script_map->AppendDescriptor(&d);
2121     }
2122
2123     Handle<AccessorInfo> script_id =
2124         Accessors::ScriptIdInfo(isolate(), attribs);
2125     {
2126       AccessorConstantDescriptor d(Handle<Name>(Name::cast(script_id->name())),
2127                                    script_id, attribs);
2128       script_map->AppendDescriptor(&d);
2129     }
2130
2131
2132     Handle<AccessorInfo> script_name =
2133         Accessors::ScriptNameInfo(isolate(), attribs);
2134     {
2135       AccessorConstantDescriptor d(
2136           Handle<Name>(Name::cast(script_name->name())), script_name, attribs);
2137       script_map->AppendDescriptor(&d);
2138     }
2139
2140     Handle<AccessorInfo> script_line =
2141         Accessors::ScriptLineOffsetInfo(isolate(), attribs);
2142     {
2143       AccessorConstantDescriptor d(
2144           Handle<Name>(Name::cast(script_line->name())), script_line, attribs);
2145       script_map->AppendDescriptor(&d);
2146     }
2147
2148     Handle<AccessorInfo> script_source =
2149         Accessors::ScriptSourceInfo(isolate(), attribs);
2150     {
2151       AccessorConstantDescriptor d(
2152           Handle<Name>(Name::cast(script_source->name())), script_source,
2153           attribs);
2154       script_map->AppendDescriptor(&d);
2155     }
2156
2157     Handle<AccessorInfo> script_type =
2158         Accessors::ScriptTypeInfo(isolate(), attribs);
2159     {
2160       AccessorConstantDescriptor d(
2161           Handle<Name>(Name::cast(script_type->name())), script_type, attribs);
2162       script_map->AppendDescriptor(&d);
2163     }
2164
2165     Handle<AccessorInfo> script_compilation_type =
2166         Accessors::ScriptCompilationTypeInfo(isolate(), attribs);
2167     {
2168       AccessorConstantDescriptor d(
2169           Handle<Name>(Name::cast(script_compilation_type->name())),
2170           script_compilation_type, attribs);
2171       script_map->AppendDescriptor(&d);
2172     }
2173
2174     Handle<AccessorInfo> script_line_ends =
2175         Accessors::ScriptLineEndsInfo(isolate(), attribs);
2176     {
2177       AccessorConstantDescriptor d(
2178           Handle<Name>(Name::cast(script_line_ends->name())), script_line_ends,
2179           attribs);
2180       script_map->AppendDescriptor(&d);
2181     }
2182
2183     Handle<AccessorInfo> script_context_data =
2184         Accessors::ScriptContextDataInfo(isolate(), attribs);
2185     {
2186       AccessorConstantDescriptor d(
2187           Handle<Name>(Name::cast(script_context_data->name())),
2188           script_context_data, attribs);
2189       script_map->AppendDescriptor(&d);
2190     }
2191
2192     Handle<AccessorInfo> script_eval_from_script =
2193         Accessors::ScriptEvalFromScriptInfo(isolate(), attribs);
2194     {
2195       AccessorConstantDescriptor d(
2196           Handle<Name>(Name::cast(script_eval_from_script->name())),
2197           script_eval_from_script, attribs);
2198       script_map->AppendDescriptor(&d);
2199     }
2200
2201     Handle<AccessorInfo> script_eval_from_script_position =
2202         Accessors::ScriptEvalFromScriptPositionInfo(isolate(), attribs);
2203     {
2204       AccessorConstantDescriptor d(
2205           Handle<Name>(Name::cast(script_eval_from_script_position->name())),
2206           script_eval_from_script_position, attribs);
2207       script_map->AppendDescriptor(&d);
2208     }
2209
2210     Handle<AccessorInfo> script_eval_from_function_name =
2211         Accessors::ScriptEvalFromFunctionNameInfo(isolate(), attribs);
2212     {
2213       AccessorConstantDescriptor d(
2214           Handle<Name>(Name::cast(script_eval_from_function_name->name())),
2215           script_eval_from_function_name, attribs);
2216       script_map->AppendDescriptor(&d);
2217     }
2218
2219     Handle<AccessorInfo> script_source_url =
2220         Accessors::ScriptSourceUrlInfo(isolate(), attribs);
2221     {
2222       AccessorConstantDescriptor d(
2223           Handle<Name>(Name::cast(script_source_url->name())),
2224           script_source_url, attribs);
2225       script_map->AppendDescriptor(&d);
2226     }
2227
2228     Handle<AccessorInfo> script_source_mapping_url =
2229         Accessors::ScriptSourceMappingUrlInfo(isolate(), attribs);
2230     {
2231       AccessorConstantDescriptor d(
2232           Handle<Name>(Name::cast(script_source_mapping_url->name())),
2233           script_source_mapping_url, attribs);
2234       script_map->AppendDescriptor(&d);
2235     }
2236
2237     Handle<AccessorInfo> script_is_embedder_debug_script =
2238         Accessors::ScriptIsEmbedderDebugScriptInfo(isolate(), attribs);
2239     {
2240       AccessorConstantDescriptor d(
2241           Handle<Name>(Name::cast(script_is_embedder_debug_script->name())),
2242           script_is_embedder_debug_script, attribs);
2243       script_map->AppendDescriptor(&d);
2244     }
2245
2246     // Allocate the empty script.
2247     Handle<Script> script = factory()->NewScript(factory()->empty_string());
2248     script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
2249     heap()->public_set_empty_script(*script);
2250   }
2251   {
2252     // Builtin function for OpaqueReference -- a JSValue-based object,
2253     // that keeps its field isolated from JavaScript code. It may store
2254     // objects, that JavaScript code may not access.
2255     Handle<JSFunction> opaque_reference_fun = InstallFunction(
2256         builtins, "OpaqueReference", JS_VALUE_TYPE, JSValue::kSize,
2257         isolate()->initial_object_prototype(), Builtins::kIllegal);
2258     Handle<JSObject> prototype =
2259         factory()->NewJSObject(isolate()->object_function(), TENURED);
2260     Accessors::FunctionSetPrototype(opaque_reference_fun, prototype).Assert();
2261     native_context()->set_opaque_reference_function(*opaque_reference_fun);
2262   }
2263
2264   // InternalArrays should not use Smi-Only array optimizations. There are too
2265   // many places in the C++ runtime code (e.g. RegEx) that assume that
2266   // elements in InternalArrays can be set to non-Smi values without going
2267   // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
2268   // transition easy to trap. Moreover, they rarely are smi-only.
2269   {
2270     HandleScope scope(isolate());
2271     Handle<JSObject> utils =
2272         Handle<JSObject>::cast(isolate()->natives_utils_object());
2273     Handle<JSFunction> array_function =
2274         InstallInternalArray(utils, "InternalArray", FAST_HOLEY_ELEMENTS);
2275     native_context()->set_internal_array_function(*array_function);
2276     InstallInternalArray(utils, "InternalPackedArray", FAST_ELEMENTS);
2277   }
2278
2279   {  // -- S e t I t e r a t o r
2280     Handle<JSFunction> set_iterator_function = InstallFunction(
2281         builtins, "SetIterator", JS_SET_ITERATOR_TYPE, JSSetIterator::kSize,
2282         isolate()->initial_object_prototype(), Builtins::kIllegal);
2283     native_context()->set_set_iterator_map(
2284         set_iterator_function->initial_map());
2285   }
2286
2287   {  // -- M a p I t e r a t o r
2288     Handle<JSFunction> map_iterator_function = InstallFunction(
2289         builtins, "MapIterator", JS_MAP_ITERATOR_TYPE, JSMapIterator::kSize,
2290         isolate()->initial_object_prototype(), Builtins::kIllegal);
2291     native_context()->set_map_iterator_map(
2292         map_iterator_function->initial_map());
2293   }
2294
2295   {
2296     // Create generator meta-objects and install them on the builtins object.
2297     Handle<JSObject> builtins(native_context()->builtins());
2298     Handle<JSObject> iterator_prototype =
2299         factory()->NewJSObject(isolate()->object_function(), TENURED);
2300     Handle<JSObject> generator_object_prototype =
2301         factory()->NewJSObject(isolate()->object_function(), TENURED);
2302     Handle<JSObject> generator_function_prototype =
2303         factory()->NewJSObject(isolate()->object_function(), TENURED);
2304     SetObjectPrototype(generator_object_prototype, iterator_prototype);
2305     JSObject::AddProperty(
2306         builtins, factory()->InternalizeUtf8String("$iteratorPrototype"),
2307         iterator_prototype,
2308         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2309     JSObject::AddProperty(
2310         builtins,
2311         factory()->InternalizeUtf8String("GeneratorFunctionPrototype"),
2312         generator_function_prototype,
2313         static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2314
2315     JSObject::AddProperty(
2316         generator_function_prototype,
2317         factory()->InternalizeUtf8String("prototype"),
2318         generator_object_prototype,
2319         static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2320
2321     static const bool kUseStrictFunctionMap = true;
2322     InstallFunction(builtins, "GeneratorFunction", JS_FUNCTION_TYPE,
2323                     JSFunction::kSize, generator_function_prototype,
2324                     Builtins::kIllegal, kUseStrictFunctionMap);
2325
2326     // Create maps for generator functions and their prototypes.  Store those
2327     // maps in the native context. The "prototype" property descriptor is
2328     // writable, non-enumerable, and non-configurable (as per ES6 draft
2329     // 04-14-15, section 25.2.4.3).
2330     Handle<Map> strict_function_map(strict_function_map_writable_prototype_);
2331     // Generator functions do not have "caller" or "arguments" accessors.
2332     Handle<Map> sloppy_generator_function_map =
2333         Map::Copy(strict_function_map, "SloppyGeneratorFunction");
2334     Map::SetPrototype(sloppy_generator_function_map,
2335                       generator_function_prototype);
2336     native_context()->set_sloppy_generator_function_map(
2337         *sloppy_generator_function_map);
2338
2339     Handle<Map> strict_generator_function_map =
2340         Map::Copy(strict_function_map, "StrictGeneratorFunction");
2341     Map::SetPrototype(strict_generator_function_map,
2342                       generator_function_prototype);
2343     native_context()->set_strict_generator_function_map(
2344         *strict_generator_function_map);
2345
2346     Handle<Map> strong_function_map(native_context()->strong_function_map());
2347     Handle<Map> strong_generator_function_map =
2348         Map::Copy(strong_function_map, "StrongGeneratorFunction");
2349     Map::SetPrototype(strong_generator_function_map,
2350                       generator_function_prototype);
2351     native_context()->set_strong_generator_function_map(
2352         *strong_generator_function_map);
2353
2354     Handle<JSFunction> object_function(native_context()->object_function());
2355     Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
2356     Map::SetPrototype(generator_object_prototype_map,
2357                       generator_object_prototype);
2358     native_context()->set_generator_object_prototype_map(
2359         *generator_object_prototype_map);
2360   }
2361
2362   if (FLAG_disable_native_files) {
2363     PrintF("Warning: Running without installed natives!\n");
2364     return true;
2365   }
2366
2367   // Install public symbols.
2368   {
2369     static const PropertyAttributes attributes =
2370         static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2371 #define INSTALL_PUBLIC_SYMBOL(name, varname, description)                 \
2372   Handle<String> varname = factory()->NewStringFromStaticChars(#varname); \
2373   JSObject::AddProperty(builtins, varname, factory()->name(), attributes);
2374     PUBLIC_SYMBOL_LIST(INSTALL_PUBLIC_SYMBOL)
2375 #undef INSTALL_PUBLIC_SYMBOL
2376   }
2377
2378   int i = Natives::GetDebuggerCount();
2379   if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2380
2381   if (!InstallJSBuiltins(builtins)) return false;
2382
2383   for (++i; i < Natives::GetBuiltinsCount(); ++i) {
2384     if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2385   }
2386
2387   if (!CallUtilsFunction(isolate(), "PostNatives")) return false;
2388
2389   auto function_cache =
2390       ObjectHashTable::New(isolate(), ApiNatives::kInitialFunctionCacheSize,
2391                            USE_CUSTOM_MINIMUM_CAPACITY);
2392   native_context()->set_function_cache(*function_cache);
2393
2394   // Store the map for the string prototype after the natives has been compiled
2395   // and the String function has been set up.
2396   Handle<JSFunction> string_function(native_context()->string_function());
2397   DCHECK(JSObject::cast(
2398       string_function->initial_map()->prototype())->HasFastProperties());
2399   native_context()->set_string_function_prototype_map(
2400       HeapObject::cast(string_function->initial_map()->prototype())->map());
2401
2402   // Install Function.prototype.call and apply.
2403   {
2404     Handle<String> key = factory()->Function_string();
2405     Handle<JSFunction> function =
2406         Handle<JSFunction>::cast(Object::GetProperty(
2407             handle(native_context()->global_object()), key).ToHandleChecked());
2408     Handle<JSObject> proto =
2409         Handle<JSObject>(JSObject::cast(function->instance_prototype()));
2410
2411     // Install the call and the apply functions.
2412     Handle<JSFunction> call =
2413         InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2414                         MaybeHandle<JSObject>(), Builtins::kFunctionCall);
2415     Handle<JSFunction> apply =
2416         InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2417                         MaybeHandle<JSObject>(), Builtins::kFunctionApply);
2418
2419     // Make sure that Function.prototype.call appears to be compiled.
2420     // The code will never be called, but inline caching for call will
2421     // only work if it appears to be compiled.
2422     call->shared()->DontAdaptArguments();
2423     DCHECK(call->is_compiled());
2424
2425     // Set the expected parameters for apply to 2; required by builtin.
2426     apply->shared()->set_internal_formal_parameter_count(2);
2427
2428     // Set the lengths for the functions to satisfy ECMA-262.
2429     call->shared()->set_length(1);
2430     apply->shared()->set_length(2);
2431   }
2432
2433   InstallBuiltinFunctionIds();
2434
2435   // Create a constructor for RegExp results (a variant of Array that
2436   // predefines the two properties index and match).
2437   {
2438     // RegExpResult initial map.
2439
2440     // Find global.Array.prototype to inherit from.
2441     Handle<JSFunction> array_constructor(native_context()->array_function());
2442     Handle<JSObject> array_prototype(
2443         JSObject::cast(array_constructor->instance_prototype()));
2444
2445     // Add initial map.
2446     Handle<Map> initial_map =
2447         factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
2448     initial_map->SetConstructor(*array_constructor);
2449
2450     // Set prototype on map.
2451     initial_map->set_non_instance_prototype(false);
2452     Map::SetPrototype(initial_map, array_prototype);
2453
2454     // Update map with length accessor from Array and add "index" and "input".
2455     Map::EnsureDescriptorSlack(initial_map, 3);
2456
2457     {
2458       JSFunction* array_function = native_context()->array_function();
2459       Handle<DescriptorArray> array_descriptors(
2460           array_function->initial_map()->instance_descriptors());
2461       Handle<String> length = factory()->length_string();
2462       int old = array_descriptors->SearchWithCache(
2463           *length, array_function->initial_map());
2464       DCHECK(old != DescriptorArray::kNotFound);
2465       AccessorConstantDescriptor desc(
2466           length, handle(array_descriptors->GetValue(old), isolate()),
2467           array_descriptors->GetDetails(old).attributes());
2468       initial_map->AppendDescriptor(&desc);
2469     }
2470     {
2471       DataDescriptor index_field(factory()->index_string(),
2472                                  JSRegExpResult::kIndexIndex, NONE,
2473                                  Representation::Tagged());
2474       initial_map->AppendDescriptor(&index_field);
2475     }
2476
2477     {
2478       DataDescriptor input_field(factory()->input_string(),
2479                                  JSRegExpResult::kInputIndex, NONE,
2480                                  Representation::Tagged());
2481       initial_map->AppendDescriptor(&input_field);
2482     }
2483
2484     initial_map->SetInObjectProperties(2);
2485     initial_map->set_unused_property_fields(0);
2486
2487     native_context()->set_regexp_result_map(*initial_map);
2488   }
2489
2490   // Add @@iterator method to the arguments object maps.
2491   {
2492     PropertyAttributes attribs = DONT_ENUM;
2493     Handle<AccessorInfo> arguments_iterator =
2494         Accessors::ArgumentsIteratorInfo(isolate(), attribs);
2495     {
2496       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2497                                    arguments_iterator, attribs);
2498       Handle<Map> map(native_context()->sloppy_arguments_map());
2499       Map::EnsureDescriptorSlack(map, 1);
2500       map->AppendDescriptor(&d);
2501     }
2502     {
2503       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2504                                    arguments_iterator, attribs);
2505       Handle<Map> map(native_context()->fast_aliased_arguments_map());
2506       Map::EnsureDescriptorSlack(map, 1);
2507       map->AppendDescriptor(&d);
2508     }
2509     {
2510       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2511                                    arguments_iterator, attribs);
2512       Handle<Map> map(native_context()->slow_aliased_arguments_map());
2513       Map::EnsureDescriptorSlack(map, 1);
2514       map->AppendDescriptor(&d);
2515     }
2516     {
2517       AccessorConstantDescriptor d(factory()->iterator_symbol(),
2518                                    arguments_iterator, attribs);
2519       Handle<Map> map(native_context()->strict_arguments_map());
2520       Map::EnsureDescriptorSlack(map, 1);
2521       map->AppendDescriptor(&d);
2522     }
2523   }
2524
2525 #ifdef VERIFY_HEAP
2526   if (FLAG_verify_heap) {
2527     builtins->ObjectVerify();
2528   }
2529 #endif
2530
2531   return true;
2532 }
2533
2534
2535 bool Genesis::InstallExperimentalNatives() {
2536   static const char* harmony_array_includes_natives[] = {
2537       "native harmony-array-includes.js", nullptr};
2538   static const char* harmony_proxies_natives[] = {"native proxy.js", nullptr};
2539   static const char* harmony_modules_natives[] = {nullptr};
2540   static const char* harmony_regexps_natives[] = {"native harmony-regexp.js",
2541                                                   nullptr};
2542   static const char* harmony_arrow_functions_natives[] = {nullptr};
2543   static const char* harmony_tostring_natives[] = {"native harmony-tostring.js",
2544                                                    nullptr};
2545   static const char* harmony_sloppy_natives[] = {nullptr};
2546   static const char* harmony_sloppy_function_natives[] = {nullptr};
2547   static const char* harmony_sloppy_let_natives[] = {nullptr};
2548   static const char* harmony_unicode_regexps_natives[] = {nullptr};
2549   static const char* harmony_rest_parameters_natives[] = {nullptr};
2550   static const char* harmony_default_parameters_natives[] = {nullptr};
2551   static const char* harmony_reflect_natives[] = {"native harmony-reflect.js",
2552                                                   nullptr};
2553   static const char* harmony_spreadcalls_natives[] = {
2554       "native harmony-spread.js", nullptr};
2555   static const char* harmony_destructuring_natives[] = {nullptr};
2556   static const char* harmony_object_natives[] = {"native harmony-object.js",
2557                                                  NULL};
2558   static const char* harmony_object_observe_natives[] = {
2559       "native harmony-object-observe.js", nullptr};
2560   static const char* harmony_spread_arrays_natives[] = {nullptr};
2561   static const char* harmony_sharedarraybuffer_natives[] = {
2562       "native harmony-sharedarraybuffer.js", NULL};
2563   static const char* harmony_atomics_natives[] = {"native harmony-atomics.js",
2564                                                   nullptr};
2565   static const char* harmony_new_target_natives[] = {nullptr};
2566   static const char* harmony_concat_spreadable_natives[] = {
2567       "native harmony-concat-spreadable.js", nullptr};
2568   static const char* harmony_simd_natives[] = {"native harmony-simd.js",
2569                                                nullptr};
2570
2571   for (int i = ExperimentalNatives::GetDebuggerCount();
2572        i < ExperimentalNatives::GetBuiltinsCount(); i++) {
2573 #define INSTALL_EXPERIMENTAL_NATIVES(id, desc)                                \
2574   if (FLAG_##id) {                                                            \
2575     for (size_t j = 0; id##_natives[j] != NULL; j++) {                        \
2576       Vector<const char> script_name = ExperimentalNatives::GetScriptName(i); \
2577       if (strncmp(script_name.start(), id##_natives[j],                       \
2578                   script_name.length()) == 0) {                               \
2579         if (!Bootstrapper::CompileExperimentalBuiltin(isolate(), i)) {        \
2580           return false;                                                       \
2581         }                                                                     \
2582       }                                                                       \
2583     }                                                                         \
2584   }
2585     HARMONY_INPROGRESS(INSTALL_EXPERIMENTAL_NATIVES);
2586     HARMONY_STAGED(INSTALL_EXPERIMENTAL_NATIVES);
2587     HARMONY_SHIPPING(INSTALL_EXPERIMENTAL_NATIVES);
2588 #undef INSTALL_EXPERIMENTAL_NATIVES
2589   }
2590
2591   if (!CallUtilsFunction(isolate(), "PostExperimentals")) return false;
2592
2593   InstallExperimentalBuiltinFunctionIds();
2594   return true;
2595 }
2596
2597
2598 bool Genesis::InstallExtraNatives() {
2599   HandleScope scope(isolate());
2600
2601   Handle<JSObject> extras_binding =
2602       factory()->NewJSObject(isolate()->object_function());
2603   JSObject::NormalizeProperties(extras_binding, CLEAR_INOBJECT_PROPERTIES, 2,
2604                                 "container for binding to/from extra natives");
2605   native_context()->set_extras_binding_object(*extras_binding);
2606
2607   for (int i = ExtraNatives::GetDebuggerCount();
2608        i < ExtraNatives::GetBuiltinsCount(); i++) {
2609     if (!Bootstrapper::CompileExtraBuiltin(isolate(), i)) return false;
2610   }
2611
2612   return true;
2613 }
2614
2615
2616 bool Genesis::InstallDebuggerNatives() {
2617   for (int i = 0; i < Natives::GetDebuggerCount(); ++i) {
2618     if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2619   }
2620   return CallUtilsFunction(isolate(), "PostDebug");
2621 }
2622
2623
2624 bool Bootstrapper::InstallCodeStubNatives(Isolate* isolate) {
2625   for (int i = CodeStubNatives::GetDebuggerCount();
2626        i < CodeStubNatives::GetBuiltinsCount(); i++) {
2627     if (!CompileCodeStubBuiltin(isolate, i)) return false;
2628   }
2629
2630   return true;
2631 }
2632
2633
2634 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
2635                                      const char* function_name,
2636                                      BuiltinFunctionId id) {
2637   Isolate* isolate = holder->GetIsolate();
2638   Handle<Object> function_object =
2639       Object::GetProperty(isolate, holder, function_name).ToHandleChecked();
2640   Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2641   function->shared()->set_function_data(Smi::FromInt(id));
2642 }
2643
2644
2645 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2646   { #holder_expr, #fun_name, k##name }                  \
2647   ,
2648
2649
2650 void Genesis::InstallBuiltinFunctionIds() {
2651   HandleScope scope(isolate());
2652   struct BuiltinFunctionIds {
2653     const char* holder_expr;
2654     const char* fun_name;
2655     BuiltinFunctionId id;
2656   };
2657
2658   const BuiltinFunctionIds builtins[] = {
2659       FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2660
2661   for (const BuiltinFunctionIds& builtin : builtins) {
2662     Handle<JSObject> holder =
2663         ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2664     InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2665   }
2666 }
2667
2668
2669 void Genesis::InstallExperimentalBuiltinFunctionIds() {
2670   if (FLAG_harmony_atomics) {
2671     struct BuiltinFunctionIds {
2672       const char* holder_expr;
2673       const char* fun_name;
2674       BuiltinFunctionId id;
2675     };
2676
2677     const BuiltinFunctionIds atomic_builtins[] = {
2678         ATOMIC_FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2679
2680     for (const BuiltinFunctionIds& builtin : atomic_builtins) {
2681       Handle<JSObject> holder =
2682           ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2683       InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2684     }
2685   }
2686 }
2687
2688
2689 #undef INSTALL_BUILTIN_ID
2690
2691
2692 void Genesis::InitializeNormalizedMapCaches() {
2693   Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
2694   native_context()->set_normalized_map_cache(*cache);
2695 }
2696
2697
2698 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
2699                                      v8::ExtensionConfiguration* extensions) {
2700   BootstrapperActive active(this);
2701   SaveContext saved_context(isolate_);
2702   isolate_->set_context(*native_context);
2703   return Genesis::InstallExtensions(native_context, extensions) &&
2704       Genesis::InstallSpecialObjects(native_context);
2705 }
2706
2707
2708 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
2709   Isolate* isolate = native_context->GetIsolate();
2710   // Don't install extensions into the snapshot.
2711   if (isolate->serializer_enabled()) return true;
2712
2713   Factory* factory = isolate->factory();
2714   HandleScope scope(isolate);
2715   Handle<JSGlobalObject> global(JSGlobalObject::cast(
2716       native_context->global_object()));
2717
2718   Handle<JSObject> Error = Handle<JSObject>::cast(
2719       Object::GetProperty(isolate, global, "Error").ToHandleChecked());
2720   Handle<String> name =
2721       factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("stackTraceLimit"));
2722   Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit), isolate);
2723   JSObject::AddProperty(Error, name, stack_trace_limit, NONE);
2724
2725   // Expose the natives in global if a name for it is specified.
2726   if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
2727     Handle<String> natives_key =
2728         factory->InternalizeUtf8String(FLAG_expose_natives_as);
2729     uint32_t dummy_index;
2730     if (natives_key->AsArrayIndex(&dummy_index)) return true;
2731     Handle<JSBuiltinsObject> natives(global->builtins());
2732     JSObject::AddProperty(global, natives_key, natives, DONT_ENUM);
2733   }
2734
2735   // Expose the stack trace symbol to native JS.
2736   RETURN_ON_EXCEPTION_VALUE(isolate,
2737                             JSObject::SetOwnPropertyIgnoreAttributes(
2738                                 handle(native_context->builtins(), isolate),
2739                                 factory->InternalizeOneByteString(
2740                                     STATIC_CHAR_VECTOR("$stackTraceSymbol")),
2741                                 factory->stack_trace_symbol(), NONE),
2742                             false);
2743
2744   // Expose the internal error symbol to native JS
2745   RETURN_ON_EXCEPTION_VALUE(isolate,
2746                             JSObject::SetOwnPropertyIgnoreAttributes(
2747                                 handle(native_context->builtins(), isolate),
2748                                 factory->InternalizeOneByteString(
2749                                     STATIC_CHAR_VECTOR("$internalErrorSymbol")),
2750                                 factory->internal_error_symbol(), NONE),
2751                             false);
2752
2753   // Expose the debug global object in global if a name for it is specified.
2754   if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
2755     // If loading fails we just bail out without installing the
2756     // debugger but without tanking the whole context.
2757     Debug* debug = isolate->debug();
2758     if (!debug->Load()) return true;
2759     Handle<Context> debug_context = debug->debug_context();
2760     // Set the security token for the debugger context to the same as
2761     // the shell native context to allow calling between these (otherwise
2762     // exposing debug global object doesn't make much sense).
2763     debug_context->set_security_token(native_context->security_token());
2764     Handle<String> debug_string =
2765         factory->InternalizeUtf8String(FLAG_expose_debug_as);
2766     uint32_t index;
2767     if (debug_string->AsArrayIndex(&index)) return true;
2768     Handle<Object> global_proxy(debug_context->global_proxy(), isolate);
2769     JSObject::AddProperty(global, debug_string, global_proxy, DONT_ENUM);
2770   }
2771   return true;
2772 }
2773
2774
2775 static uint32_t Hash(RegisteredExtension* extension) {
2776   return v8::internal::ComputePointerHash(extension);
2777 }
2778
2779
2780 Genesis::ExtensionStates::ExtensionStates() : map_(HashMap::PointersMatch, 8) {}
2781
2782 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2783     RegisteredExtension* extension) {
2784   i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension));
2785   if (entry == NULL) {
2786     return UNVISITED;
2787   }
2788   return static_cast<ExtensionTraversalState>(
2789       reinterpret_cast<intptr_t>(entry->value));
2790 }
2791
2792 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2793                                          ExtensionTraversalState state) {
2794   map_.LookupOrInsert(extension, Hash(extension))->value =
2795       reinterpret_cast<void*>(static_cast<intptr_t>(state));
2796 }
2797
2798
2799 bool Genesis::InstallExtensions(Handle<Context> native_context,
2800                                 v8::ExtensionConfiguration* extensions) {
2801   Isolate* isolate = native_context->GetIsolate();
2802   ExtensionStates extension_states;  // All extensions have state UNVISITED.
2803   return InstallAutoExtensions(isolate, &extension_states) &&
2804       (!FLAG_expose_free_buffer ||
2805        InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
2806       (!FLAG_expose_gc ||
2807        InstallExtension(isolate, "v8/gc", &extension_states)) &&
2808       (!FLAG_expose_externalize_string ||
2809        InstallExtension(isolate, "v8/externalize", &extension_states)) &&
2810       (!FLAG_track_gc_object_stats ||
2811        InstallExtension(isolate, "v8/statistics", &extension_states)) &&
2812       (!FLAG_expose_trigger_failure ||
2813        InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
2814       InstallRequestedExtensions(isolate, extensions, &extension_states);
2815 }
2816
2817
2818 bool Genesis::InstallAutoExtensions(Isolate* isolate,
2819                                     ExtensionStates* extension_states) {
2820   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2821        it != NULL;
2822        it = it->next()) {
2823     if (it->extension()->auto_enable() &&
2824         !InstallExtension(isolate, it, extension_states)) {
2825       return false;
2826     }
2827   }
2828   return true;
2829 }
2830
2831
2832 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
2833                                          v8::ExtensionConfiguration* extensions,
2834                                          ExtensionStates* extension_states) {
2835   for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
2836     if (!InstallExtension(isolate, *it, extension_states)) return false;
2837   }
2838   return true;
2839 }
2840
2841
2842 // Installs a named extension.  This methods is unoptimized and does
2843 // not scale well if we want to support a large number of extensions.
2844 bool Genesis::InstallExtension(Isolate* isolate,
2845                                const char* name,
2846                                ExtensionStates* extension_states) {
2847   for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2848        it != NULL;
2849        it = it->next()) {
2850     if (strcmp(name, it->extension()->name()) == 0) {
2851       return InstallExtension(isolate, it, extension_states);
2852     }
2853   }
2854   return Utils::ApiCheck(false,
2855                          "v8::Context::New()",
2856                          "Cannot find required extension");
2857 }
2858
2859
2860 bool Genesis::InstallExtension(Isolate* isolate,
2861                                v8::RegisteredExtension* current,
2862                                ExtensionStates* extension_states) {
2863   HandleScope scope(isolate);
2864
2865   if (extension_states->get_state(current) == INSTALLED) return true;
2866   // The current node has already been visited so there must be a
2867   // cycle in the dependency graph; fail.
2868   if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
2869                        "v8::Context::New()",
2870                        "Circular extension dependency")) {
2871     return false;
2872   }
2873   DCHECK(extension_states->get_state(current) == UNVISITED);
2874   extension_states->set_state(current, VISITED);
2875   v8::Extension* extension = current->extension();
2876   // Install the extension's dependencies
2877   for (int i = 0; i < extension->dependency_count(); i++) {
2878     if (!InstallExtension(isolate,
2879                           extension->dependencies()[i],
2880                           extension_states)) {
2881       return false;
2882     }
2883   }
2884   // We do not expect this to throw an exception. Change this if it does.
2885   bool result = CompileExtension(isolate, extension);
2886   DCHECK(isolate->has_pending_exception() != result);
2887   if (!result) {
2888     // We print out the name of the extension that fail to install.
2889     // When an error is thrown during bootstrapping we automatically print
2890     // the line number at which this happened to the console in the isolate
2891     // error throwing functionality.
2892     base::OS::PrintError("Error installing extension '%s'.\n",
2893                          current->extension()->name());
2894     isolate->clear_pending_exception();
2895   }
2896   extension_states->set_state(current, INSTALLED);
2897   isolate->NotifyExtensionInstalled();
2898   return result;
2899 }
2900
2901
2902 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2903   HandleScope scope(isolate());
2904   for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2905     Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2906     Handle<Object> function_object = Object::GetProperty(
2907         isolate(), builtins, Builtins::GetName(id)).ToHandleChecked();
2908     Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2909     builtins->set_javascript_builtin(id, *function);
2910   }
2911   return true;
2912 }
2913
2914
2915 bool Genesis::ConfigureGlobalObjects(
2916     v8::Local<v8::ObjectTemplate> global_proxy_template) {
2917   Handle<JSObject> global_proxy(
2918       JSObject::cast(native_context()->global_proxy()));
2919   Handle<JSObject> global_object(
2920       JSObject::cast(native_context()->global_object()));
2921
2922   if (!global_proxy_template.IsEmpty()) {
2923     // Configure the global proxy object.
2924     Handle<ObjectTemplateInfo> global_proxy_data =
2925         v8::Utils::OpenHandle(*global_proxy_template);
2926     if (!ConfigureApiObject(global_proxy, global_proxy_data)) return false;
2927
2928     // Configure the global object.
2929     Handle<FunctionTemplateInfo> proxy_constructor(
2930         FunctionTemplateInfo::cast(global_proxy_data->constructor()));
2931     if (!proxy_constructor->prototype_template()->IsUndefined()) {
2932       Handle<ObjectTemplateInfo> global_object_data(
2933           ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2934       if (!ConfigureApiObject(global_object, global_object_data)) return false;
2935     }
2936   }
2937
2938   SetObjectPrototype(global_proxy, global_object);
2939
2940   native_context()->set_initial_array_prototype(
2941       JSArray::cast(native_context()->array_function()->prototype()));
2942   native_context()->set_array_buffer_map(
2943       native_context()->array_buffer_fun()->initial_map());
2944   native_context()->set_js_map_map(
2945       native_context()->js_map_fun()->initial_map());
2946   native_context()->set_js_set_map(
2947       native_context()->js_set_fun()->initial_map());
2948
2949   return true;
2950 }
2951
2952
2953 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
2954                                  Handle<ObjectTemplateInfo> object_template) {
2955   DCHECK(!object_template.is_null());
2956   DCHECK(FunctionTemplateInfo::cast(object_template->constructor())
2957              ->IsTemplateFor(object->map()));;
2958
2959   MaybeHandle<JSObject> maybe_obj =
2960       ApiNatives::InstantiateObject(object_template);
2961   Handle<JSObject> obj;
2962   if (!maybe_obj.ToHandle(&obj)) {
2963     DCHECK(isolate()->has_pending_exception());
2964     isolate()->clear_pending_exception();
2965     return false;
2966   }
2967   TransferObject(obj, object);
2968   return true;
2969 }
2970
2971
2972 void Genesis::TransferNamedProperties(Handle<JSObject> from,
2973                                       Handle<JSObject> to) {
2974   // If JSObject::AddProperty asserts due to already existing property,
2975   // it is likely due to both global objects sharing property name(s).
2976   // Merging those two global objects is impossible.
2977   // The global template must not create properties that already exist
2978   // in the snapshotted global object.
2979   if (from->HasFastProperties()) {
2980     Handle<DescriptorArray> descs =
2981         Handle<DescriptorArray>(from->map()->instance_descriptors());
2982     for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
2983       PropertyDetails details = descs->GetDetails(i);
2984       switch (details.type()) {
2985         case DATA: {
2986           HandleScope inner(isolate());
2987           Handle<Name> key = Handle<Name>(descs->GetKey(i));
2988           FieldIndex index = FieldIndex::ForDescriptor(from->map(), i);
2989           DCHECK(!descs->GetDetails(i).representation().IsDouble());
2990           Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
2991                                                 isolate());
2992           JSObject::AddProperty(to, key, value, details.attributes());
2993           break;
2994         }
2995         case DATA_CONSTANT: {
2996           HandleScope inner(isolate());
2997           Handle<Name> key = Handle<Name>(descs->GetKey(i));
2998           Handle<Object> constant(descs->GetConstant(i), isolate());
2999           JSObject::AddProperty(to, key, constant, details.attributes());
3000           break;
3001         }
3002         case ACCESSOR:
3003           UNREACHABLE();
3004         case ACCESSOR_CONSTANT: {
3005           Handle<Name> key(descs->GetKey(i));
3006           LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3007           CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3008           // If the property is already there we skip it
3009           if (it.IsFound()) continue;
3010           HandleScope inner(isolate());
3011           DCHECK(!to->HasFastProperties());
3012           // Add to dictionary.
3013           Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
3014           PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
3015                             PropertyCellType::kMutable);
3016           JSObject::SetNormalizedProperty(to, key, callbacks, d);
3017           break;
3018         }
3019       }
3020     }
3021   } else if (from->IsGlobalObject()) {
3022     Handle<GlobalDictionary> properties =
3023         Handle<GlobalDictionary>(from->global_dictionary());
3024     int capacity = properties->Capacity();
3025     for (int i = 0; i < capacity; i++) {
3026       Object* raw_key(properties->KeyAt(i));
3027       if (properties->IsKey(raw_key)) {
3028         DCHECK(raw_key->IsName());
3029         // If the property is already there we skip it.
3030         Handle<Name> key(Name::cast(raw_key));
3031         LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3032         CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3033         if (it.IsFound()) continue;
3034         // Set the property.
3035         DCHECK(properties->ValueAt(i)->IsPropertyCell());
3036         Handle<PropertyCell> cell(PropertyCell::cast(properties->ValueAt(i)));
3037         Handle<Object> value(cell->value(), isolate());
3038         if (value->IsTheHole()) continue;
3039         PropertyDetails details = cell->property_details();
3040         DCHECK_EQ(kData, details.kind());
3041         JSObject::AddProperty(to, key, value, details.attributes());
3042       }
3043     }
3044   } else {
3045     Handle<NameDictionary> properties =
3046         Handle<NameDictionary>(from->property_dictionary());
3047     int capacity = properties->Capacity();
3048     for (int i = 0; i < capacity; i++) {
3049       Object* raw_key(properties->KeyAt(i));
3050       if (properties->IsKey(raw_key)) {
3051         DCHECK(raw_key->IsName());
3052         // If the property is already there we skip it.
3053         Handle<Name> key(Name::cast(raw_key));
3054         LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3055         CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3056         if (it.IsFound()) continue;
3057         // Set the property.
3058         Handle<Object> value = Handle<Object>(properties->ValueAt(i),
3059                                               isolate());
3060         DCHECK(!value->IsCell());
3061         DCHECK(!value->IsTheHole());
3062         PropertyDetails details = properties->DetailsAt(i);
3063         DCHECK_EQ(kData, details.kind());
3064         JSObject::AddProperty(to, key, value, details.attributes());
3065       }
3066     }
3067   }
3068 }
3069
3070
3071 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
3072                                         Handle<JSObject> to) {
3073   // Cloning the elements array is sufficient.
3074   Handle<FixedArray> from_elements =
3075       Handle<FixedArray>(FixedArray::cast(from->elements()));
3076   Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
3077   to->set_elements(*to_elements);
3078 }
3079
3080
3081 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
3082   HandleScope outer(isolate());
3083
3084   DCHECK(!from->IsJSArray());
3085   DCHECK(!to->IsJSArray());
3086
3087   TransferNamedProperties(from, to);
3088   TransferIndexedProperties(from, to);
3089
3090   // Transfer the prototype (new map is needed).
3091   Handle<Object> proto(from->map()->prototype(), isolate());
3092   SetObjectPrototype(to, proto);
3093 }
3094
3095
3096 void Genesis::MakeFunctionInstancePrototypeWritable() {
3097   // The maps with writable prototype are created in CreateEmptyFunction
3098   // and CreateStrictModeFunctionMaps respectively. Initially the maps are
3099   // created with read-only prototype for JS builtins processing.
3100   DCHECK(!sloppy_function_map_writable_prototype_.is_null());
3101   DCHECK(!strict_function_map_writable_prototype_.is_null());
3102
3103   // Replace function instance maps to make prototype writable.
3104   native_context()->set_sloppy_function_map(
3105       *sloppy_function_map_writable_prototype_);
3106   native_context()->set_strict_function_map(
3107       *strict_function_map_writable_prototype_);
3108 }
3109
3110
3111 class NoTrackDoubleFieldsForSerializerScope {
3112  public:
3113   explicit NoTrackDoubleFieldsForSerializerScope(Isolate* isolate)
3114       : flag_(FLAG_track_double_fields), enabled_(false) {
3115     if (isolate->serializer_enabled()) {
3116       // Disable tracking double fields because heap numbers treated as
3117       // immutable by the serializer.
3118       FLAG_track_double_fields = false;
3119       enabled_ = true;
3120     }
3121   }
3122
3123   ~NoTrackDoubleFieldsForSerializerScope() {
3124     if (enabled_) {
3125       FLAG_track_double_fields = flag_;
3126     }
3127   }
3128
3129  private:
3130   bool flag_;
3131   bool enabled_;
3132 };
3133
3134
3135 Genesis::Genesis(Isolate* isolate,
3136                  MaybeHandle<JSGlobalProxy> maybe_global_proxy,
3137                  v8::Local<v8::ObjectTemplate> global_proxy_template,
3138                  v8::ExtensionConfiguration* extensions,
3139                  ContextType context_type)
3140     : isolate_(isolate), active_(isolate->bootstrapper()) {
3141   NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
3142   result_ = Handle<Context>::null();
3143   // Before creating the roots we must save the context and restore it
3144   // on all function exits.
3145   SaveContext saved_context(isolate);
3146
3147   // During genesis, the boilerplate for stack overflow won't work until the
3148   // environment has been at least partially initialized. Add a stack check
3149   // before entering JS code to catch overflow early.
3150   StackLimitCheck check(isolate);
3151   if (check.HasOverflowed()) {
3152     isolate->StackOverflow();
3153     return;
3154   }
3155
3156   // The deserializer needs to hook up references to the global proxy.
3157   // Create an uninitialized global proxy now if we don't have one
3158   // and initialize it later in CreateNewGlobals.
3159   Handle<JSGlobalProxy> global_proxy;
3160   if (!maybe_global_proxy.ToHandle(&global_proxy)) {
3161     global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy();
3162   }
3163
3164   // We can only de-serialize a context if the isolate was initialized from
3165   // a snapshot. Otherwise we have to build the context from scratch.
3166   // Also create a context from scratch to expose natives, if required by flag.
3167   Handle<FixedArray> outdated_contexts;
3168   if (!isolate->initialized_from_snapshot() ||
3169       !Snapshot::NewContextFromSnapshot(isolate, global_proxy,
3170                                         &outdated_contexts)
3171            .ToHandle(&native_context_)) {
3172     native_context_ = Handle<Context>();
3173   }
3174
3175   if (!native_context().is_null()) {
3176     AddToWeakNativeContextList(*native_context());
3177     isolate->set_context(*native_context());
3178     isolate->counters()->contexts_created_by_snapshot()->Increment();
3179 #if TRACE_MAPS
3180     if (FLAG_trace_maps) {
3181       Handle<JSFunction> object_fun = isolate->object_function();
3182       PrintF("[TraceMap: InitialMap map= %p SFI= %d_Object ]\n",
3183              reinterpret_cast<void*>(object_fun->initial_map()),
3184              object_fun->shared()->unique_id());
3185       Map::TraceAllTransitions(object_fun->initial_map());
3186     }
3187 #endif
3188     Handle<GlobalObject> global_object =
3189         CreateNewGlobals(global_proxy_template, global_proxy);
3190
3191     HookUpGlobalProxy(global_object, global_proxy);
3192     HookUpGlobalObject(global_object, outdated_contexts);
3193     native_context()->builtins()->set_global_proxy(
3194         native_context()->global_proxy());
3195     HookUpGlobalThisBinding(outdated_contexts);
3196
3197     if (!ConfigureGlobalObjects(global_proxy_template)) return;
3198   } else {
3199     // We get here if there was no context snapshot.
3200     CreateRoots();
3201     Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
3202     CreateStrictModeFunctionMaps(empty_function);
3203     CreateStrongModeFunctionMaps(empty_function);
3204     Handle<GlobalObject> global_object =
3205         CreateNewGlobals(global_proxy_template, global_proxy);
3206     HookUpGlobalProxy(global_object, global_proxy);
3207     InitializeGlobal(global_object, empty_function, context_type);
3208     InitializeNormalizedMapCaches();
3209
3210     if (!InstallNatives(context_type)) return;
3211
3212     MakeFunctionInstancePrototypeWritable();
3213
3214     if (context_type != THIN_CONTEXT) {
3215       if (!InstallExtraNatives()) return;
3216       if (!ConfigureGlobalObjects(global_proxy_template)) return;
3217     }
3218     isolate->counters()->contexts_created_from_scratch()->Increment();
3219   }
3220
3221   // Install experimental natives. Do not include them into the
3222   // snapshot as we should be able to turn them off at runtime. Re-installing
3223   // them after they have already been deserialized would also fail.
3224   if (context_type == FULL_CONTEXT) {
3225     if (!isolate->serializer_enabled()) {
3226       InitializeExperimentalGlobal();
3227       if (!InstallExperimentalNatives()) return;
3228       // By now the utils object is useless and can be removed.
3229       native_context()->set_natives_utils_object(
3230           isolate->heap()->undefined_value());
3231     }
3232     // The serializer cannot serialize typed arrays. Reset those typed arrays
3233     // for each new context.
3234     InitializeBuiltinTypedArrays();
3235   } else if (context_type == DEBUG_CONTEXT) {
3236     DCHECK(!isolate->serializer_enabled());
3237     InitializeExperimentalGlobal();
3238     if (!InstallDebuggerNatives()) return;
3239   }
3240
3241   // Check that the script context table is empty except for the 'this' binding.
3242   // We do not need script contexts for native scripts.
3243   DCHECK_EQ(1, native_context()->script_context_table()->used());
3244
3245   result_ = native_context();
3246 }
3247
3248
3249 // Support for thread preemption.
3250
3251 // Reserve space for statics needing saving and restoring.
3252 int Bootstrapper::ArchiveSpacePerThread() {
3253   return sizeof(NestingCounterType);
3254 }
3255
3256
3257 // Archive statics that are thread-local.
3258 char* Bootstrapper::ArchiveState(char* to) {
3259   *reinterpret_cast<NestingCounterType*>(to) = nesting_;
3260   nesting_ = 0;
3261   return to + sizeof(NestingCounterType);
3262 }
3263
3264
3265 // Restore statics that are thread-local.
3266 char* Bootstrapper::RestoreState(char* from) {
3267   nesting_ = *reinterpret_cast<NestingCounterType*>(from);
3268   return from + sizeof(NestingCounterType);
3269 }
3270
3271
3272 // Called when the top-level V8 mutex is destroyed.
3273 void Bootstrapper::FreeThreadResources() {
3274   DCHECK(!IsActive());
3275 }
3276
3277 }  // namespace internal
3278 }  // namespace v8