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