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