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