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