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