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.
5 #include "bootstrapper.h"
8 #include "isolate-inl.h"
11 #include "trig-table.h"
12 #include "extensions/externalize-string-extension.h"
13 #include "extensions/free-buffer-extension.h"
14 #include "extensions/gc-extension.h"
15 #include "extensions/statistics-extension.h"
16 #include "extensions/trigger-failure-extension.h"
17 #include "code-stubs.h"
22 NativesExternalStringResource::NativesExternalStringResource(
23 Bootstrapper* bootstrapper,
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);
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));
37 Bootstrapper::Bootstrapper(Isolate* isolate)
40 extensions_cache_(Script::TYPE_EXTENSION),
41 delete_these_non_arrays_on_tear_down_(NULL),
42 delete_these_arrays_on_tear_down_(NULL) {
46 Handle<String> Bootstrapper::NativesSourceLookup(int index) {
47 ASSERT(0 <= index && index < Natives::GetBuiltinsCount());
48 Heap* heap = isolate_->heap();
49 if (heap->natives_source_cache()->get(index)->IsUndefined()) {
50 // We can use external strings for the natives.
51 Vector<const char> source = Natives::GetRawScriptSource(index);
52 NativesExternalStringResource* resource =
53 new NativesExternalStringResource(this,
56 // We do not expect this to throw an exception. Change this if it does.
57 Handle<String> source_code =
58 isolate_->factory()->NewExternalStringFromAscii(
59 resource).ToHandleChecked();
60 heap->natives_source_cache()->set(index, *source_code);
62 Handle<Object> cached_source(heap->natives_source_cache()->get(index),
64 return Handle<String>::cast(cached_source);
68 void Bootstrapper::Initialize(bool create_heap_objects) {
69 extensions_cache_.Initialize(isolate_, create_heap_objects);
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";
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;
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_);
100 void Bootstrapper::TearDownExtensions() {
101 delete free_buffer_extension_;
102 delete gc_extension_;
103 delete externalize_string_extension_;
104 delete statistics_extension_;
105 delete trigger_failure_extension_;
109 char* Bootstrapper::AllocateAutoDeletedArray(int bytes) {
110 char* memory = new char[bytes];
111 if (memory != NULL) {
112 if (delete_these_arrays_on_tear_down_ == NULL) {
113 delete_these_arrays_on_tear_down_ = new List<char*>(2);
115 delete_these_arrays_on_tear_down_->Add(memory);
121 void Bootstrapper::TearDown() {
122 if (delete_these_non_arrays_on_tear_down_ != NULL) {
123 int len = delete_these_non_arrays_on_tear_down_->length();
124 ASSERT(len < 20); // Don't use this mechanism for unbounded allocations.
125 for (int i = 0; i < len; i++) {
126 delete delete_these_non_arrays_on_tear_down_->at(i);
127 delete_these_non_arrays_on_tear_down_->at(i) = NULL;
129 delete delete_these_non_arrays_on_tear_down_;
130 delete_these_non_arrays_on_tear_down_ = NULL;
133 if (delete_these_arrays_on_tear_down_ != NULL) {
134 int len = delete_these_arrays_on_tear_down_->length();
135 ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations.
136 for (int i = 0; i < len; i++) {
137 delete[] delete_these_arrays_on_tear_down_->at(i);
138 delete_these_arrays_on_tear_down_->at(i) = NULL;
140 delete delete_these_arrays_on_tear_down_;
141 delete_these_arrays_on_tear_down_ = NULL;
144 extensions_cache_.Initialize(isolate_, false); // Yes, symmetrical
148 class Genesis BASE_EMBEDDED {
150 Genesis(Isolate* isolate,
151 Handle<Object> global_object,
152 v8::Handle<v8::ObjectTemplate> global_template,
153 v8::ExtensionConfiguration* extensions);
156 Isolate* isolate() const { return isolate_; }
157 Factory* factory() const { return isolate_->factory(); }
158 Heap* heap() const { return isolate_->heap(); }
160 Handle<Context> result() { return result_; }
163 Handle<Context> native_context() { return native_context_; }
165 // Creates some basic objects. Used for creating a context from scratch.
167 // Creates the empty function. Used for creating a context from scratch.
168 Handle<JSFunction> CreateEmptyFunction(Isolate* isolate);
169 // Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
170 Handle<JSFunction> GetThrowTypeErrorFunction();
172 void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
174 // Make the "arguments" and "caller" properties throw a TypeError on access.
175 void PoisonArgumentsAndCaller(Handle<Map> map);
177 // Creates the global objects using the global and the template passed in
178 // through the API. We call this regardless of whether we are building a
179 // context from scratch or using a deserialized one from the partial snapshot
180 // but in the latter case we don't use the objects it produces directly, as
181 // we have to used the deserialized ones that are linked together with the
182 // rest of the context snapshot.
183 Handle<JSGlobalProxy> CreateNewGlobals(
184 v8::Handle<v8::ObjectTemplate> global_template,
185 Handle<Object> global_object,
186 Handle<GlobalObject>* global_proxy_out);
187 // Hooks the given global proxy into the context. If the context was created
188 // by deserialization then this will unhook the global proxy that was
189 // deserialized, leaving the GC to pick it up.
190 void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
191 Handle<JSGlobalProxy> global_proxy);
192 // Similarly, we want to use the inner global that has been created by the
193 // templates passed through the API. The inner global from the snapshot is
194 // detached from the other objects in the snapshot.
195 void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
196 // New context initialization. Used for creating a context from scratch.
197 void InitializeGlobal(Handle<GlobalObject> inner_global,
198 Handle<JSFunction> empty_function);
199 void InitializeExperimentalGlobal();
200 // Installs the contents of the native .js files on the global objects.
201 // Used for creating a context from scratch.
202 void InstallNativeFunctions();
203 void InstallExperimentalBuiltinFunctionIds();
204 void InstallExperimentalNativeFunctions();
205 Handle<JSFunction> InstallInternalArray(Handle<JSBuiltinsObject> builtins,
207 ElementsKind elements_kind);
208 bool InstallNatives();
210 void InstallTypedArray(
212 ElementsKind elements_kind,
213 Handle<JSFunction>* fun,
214 Handle<Map>* external_map);
215 bool InstallExperimentalNatives();
216 void InstallBuiltinFunctionIds();
217 void InstallExperimentalSIMDBuiltinFunctionIds();
218 void InstallJSFunctionResultCaches();
219 void InitializeNormalizedMapCaches();
221 enum ExtensionTraversalState {
222 UNVISITED, VISITED, INSTALLED
225 class ExtensionStates {
228 ExtensionTraversalState get_state(RegisteredExtension* extension);
229 void set_state(RegisteredExtension* extension,
230 ExtensionTraversalState state);
233 DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
236 // Used both for deserialized and from-scratch contexts to add the extensions
238 static bool InstallExtensions(Handle<Context> native_context,
239 v8::ExtensionConfiguration* extensions);
240 static bool InstallAutoExtensions(Isolate* isolate,
241 ExtensionStates* extension_states);
242 static bool InstallRequestedExtensions(Isolate* isolate,
243 v8::ExtensionConfiguration* extensions,
244 ExtensionStates* extension_states);
245 static bool InstallExtension(Isolate* isolate,
247 ExtensionStates* extension_states);
248 static bool InstallExtension(Isolate* isolate,
249 v8::RegisteredExtension* current,
250 ExtensionStates* extension_states);
251 static bool InstallSpecialObjects(Handle<Context> native_context);
252 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
253 bool ConfigureApiObject(Handle<JSObject> object,
254 Handle<ObjectTemplateInfo> object_template);
255 bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
257 // Migrates all properties from the 'from' object to the 'to'
258 // object and overrides the prototype in 'to' with the one from
260 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
261 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
262 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
264 enum PrototypePropertyMode {
266 ADD_READONLY_PROTOTYPE,
267 ADD_WRITEABLE_PROTOTYPE
270 Handle<Map> CreateFunctionMap(PrototypePropertyMode prototype_mode);
272 void SetFunctionInstanceDescriptor(Handle<Map> map,
273 PrototypePropertyMode prototypeMode);
274 void MakeFunctionInstancePrototypeWritable();
276 Handle<Map> CreateStrictFunctionMap(
277 PrototypePropertyMode prototype_mode,
278 Handle<JSFunction> empty_function);
280 void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
281 PrototypePropertyMode propertyMode);
283 static bool CompileBuiltin(Isolate* isolate, int index);
284 static bool CompileExperimentalBuiltin(Isolate* isolate, int index);
285 static bool CompileNative(Isolate* isolate,
286 Vector<const char> name,
287 Handle<String> source);
288 static bool CompileScriptCached(Isolate* isolate,
289 Vector<const char> name,
290 Handle<String> source,
291 SourceCodeCache* cache,
292 v8::Extension* extension,
293 Handle<Context> top_context,
294 bool use_runtime_context);
297 Handle<Context> result_;
298 Handle<Context> native_context_;
300 // Function maps. Function maps are created initially with a read only
301 // prototype for the processing of JS builtins. Later the function maps are
302 // replaced in order to make prototype writable. These are the final, writable
304 Handle<Map> sloppy_function_map_writable_prototype_;
305 Handle<Map> strict_function_map_writable_prototype_;
306 Handle<JSFunction> throw_type_error_function;
308 BootstrapperActive active_;
309 friend class Bootstrapper;
313 void Bootstrapper::Iterate(ObjectVisitor* v) {
314 extensions_cache_.Iterate(v);
315 v->Synchronize(VisitorSynchronization::kExtensions);
319 Handle<Context> Bootstrapper::CreateEnvironment(
320 Handle<Object> global_object,
321 v8::Handle<v8::ObjectTemplate> global_template,
322 v8::ExtensionConfiguration* extensions) {
323 HandleScope scope(isolate_);
324 Genesis genesis(isolate_, global_object, global_template, extensions);
325 Handle<Context> env = genesis.result();
326 if (env.is_null() || !InstallExtensions(env, extensions)) {
327 return Handle<Context>();
329 return scope.CloseAndEscape(env);
333 static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
334 // object.__proto__ = proto;
335 Handle<Map> old_to_map = Handle<Map>(object->map());
336 Handle<Map> new_to_map = Map::Copy(old_to_map);
337 new_to_map->set_prototype(*proto);
338 object->set_map(*new_to_map);
342 void Bootstrapper::DetachGlobal(Handle<Context> env) {
343 Factory* factory = env->GetIsolate()->factory();
344 Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
345 global_proxy->set_native_context(*factory->null_value());
346 SetObjectPrototype(global_proxy, factory->null_value());
350 static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
354 Handle<JSObject> prototype,
356 bool install_initial_map,
357 bool set_instance_class_name) {
358 Isolate* isolate = target->GetIsolate();
359 Factory* factory = isolate->factory();
360 Handle<String> internalized_name = factory->InternalizeUtf8String(name);
361 Handle<Code> call_code = Handle<Code>(isolate->builtins()->builtin(call));
362 Handle<JSFunction> function = prototype.is_null()
363 ? factory->NewFunction(internalized_name, call_code)
364 : factory->NewFunctionWithPrototype(internalized_name,
369 install_initial_map);
370 PropertyAttributes attributes;
371 if (target->IsJSBuiltinsObject()) {
373 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
375 attributes = DONT_ENUM;
377 JSObject::SetLocalPropertyIgnoreAttributes(
378 target, internalized_name, function, attributes).Check();
379 if (set_instance_class_name) {
380 function->shared()->set_instance_class_name(*internalized_name);
382 function->shared()->set_native(true);
387 void Genesis::SetFunctionInstanceDescriptor(
388 Handle<Map> map, PrototypePropertyMode prototypeMode) {
389 int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
390 Map::EnsureDescriptorSlack(map, size);
392 PropertyAttributes attribs = static_cast<PropertyAttributes>(
393 DONT_ENUM | DONT_DELETE | READ_ONLY);
395 Handle<AccessorInfo> length =
396 Accessors::FunctionLengthInfo(isolate(), attribs);
398 CallbacksDescriptor d(Handle<Name>(Name::cast(length->name())),
400 map->AppendDescriptor(&d);
402 Handle<AccessorInfo> name =
403 Accessors::FunctionNameInfo(isolate(), attribs);
405 CallbacksDescriptor d(Handle<Name>(Name::cast(name->name())),
407 map->AppendDescriptor(&d);
409 Handle<AccessorInfo> args =
410 Accessors::FunctionArgumentsInfo(isolate(), attribs);
412 CallbacksDescriptor d(Handle<Name>(Name::cast(args->name())),
414 map->AppendDescriptor(&d);
416 Handle<AccessorInfo> caller =
417 Accessors::FunctionCallerInfo(isolate(), attribs);
419 CallbacksDescriptor d(Handle<Name>(Name::cast(caller->name())),
421 map->AppendDescriptor(&d);
423 if (prototypeMode != DONT_ADD_PROTOTYPE) {
424 if (prototypeMode == ADD_WRITEABLE_PROTOTYPE) {
425 attribs = static_cast<PropertyAttributes>(attribs & ~READ_ONLY);
427 Handle<AccessorInfo> prototype =
428 Accessors::FunctionPrototypeInfo(isolate(), attribs);
429 CallbacksDescriptor d(Handle<Name>(Name::cast(prototype->name())),
431 map->AppendDescriptor(&d);
436 Handle<Map> Genesis::CreateFunctionMap(PrototypePropertyMode prototype_mode) {
437 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
438 SetFunctionInstanceDescriptor(map, prototype_mode);
439 map->set_function_with_prototype(prototype_mode != DONT_ADD_PROTOTYPE);
444 Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
445 // Allocate the map for function instances. Maps are allocated first and their
446 // prototypes patched later, once empty function is created.
448 // Functions with this map will not have a 'prototype' property, and
449 // can not be used as constructors.
450 Handle<Map> function_without_prototype_map =
451 CreateFunctionMap(DONT_ADD_PROTOTYPE);
452 native_context()->set_sloppy_function_without_prototype_map(
453 *function_without_prototype_map);
455 // Allocate the function map. This map is temporary, used only for processing
457 // Later the map is replaced with writable prototype map, allocated below.
458 Handle<Map> function_map = CreateFunctionMap(ADD_READONLY_PROTOTYPE);
459 native_context()->set_sloppy_function_map(*function_map);
461 // The final map for functions. Writeable prototype.
462 // This map is installed in MakeFunctionInstancePrototypeWritable.
463 sloppy_function_map_writable_prototype_ =
464 CreateFunctionMap(ADD_WRITEABLE_PROTOTYPE);
466 Factory* factory = isolate->factory();
468 Handle<String> object_name = factory->Object_string();
470 { // --- O b j e c t ---
471 Handle<JSFunction> object_fun = factory->NewFunctionWithPrototype(
472 object_name, factory->null_value());
473 Handle<Map> object_function_map =
474 factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
475 object_fun->set_initial_map(*object_function_map);
476 object_function_map->set_constructor(*object_fun);
478 native_context()->set_object_function(*object_fun);
480 // Allocate a new prototype for the object function.
481 Handle<JSObject> prototype = factory->NewJSObject(
482 isolate->object_function(),
485 native_context()->set_initial_object_prototype(*prototype);
486 // For bootstrapping set the array prototype to be the same as the object
487 // prototype, otherwise the missing initial_array_prototype will cause
488 // assertions during startup.
489 native_context()->set_initial_array_prototype(*prototype);
490 Accessors::FunctionSetPrototype(object_fun, prototype);
493 // Allocate the empty function as the prototype for function ECMAScript
495 Handle<String> empty_string =
496 factory->InternalizeOneByteString(STATIC_ASCII_VECTOR("Empty"));
497 Handle<Code> code(isolate->builtins()->builtin(Builtins::kEmptyFunction));
498 Handle<JSFunction> empty_function = factory->NewFunction(empty_string, code);
501 Handle<String> source = factory->NewStringFromStaticAscii("() {}");
502 Handle<Script> script = factory->NewScript(source);
503 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
504 empty_function->shared()->set_script(*script);
505 empty_function->shared()->set_start_position(0);
506 empty_function->shared()->set_end_position(source->length());
507 empty_function->shared()->DontAdaptArguments();
509 // Set prototypes for the function maps.
510 native_context()->sloppy_function_map()->set_prototype(*empty_function);
511 native_context()->sloppy_function_without_prototype_map()->
512 set_prototype(*empty_function);
513 sloppy_function_map_writable_prototype_->set_prototype(*empty_function);
515 // Allocate the function map first and then patch the prototype later
516 Handle<Map> empty_function_map = CreateFunctionMap(DONT_ADD_PROTOTYPE);
517 empty_function_map->set_prototype(
518 native_context()->object_function()->prototype());
519 empty_function->set_map(*empty_function_map);
520 return empty_function;
524 void Genesis::SetStrictFunctionInstanceDescriptor(
525 Handle<Map> map, PrototypePropertyMode prototypeMode) {
526 int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
527 Map::EnsureDescriptorSlack(map, size);
529 Handle<AccessorPair> arguments(factory()->NewAccessorPair());
530 Handle<AccessorPair> caller(factory()->NewAccessorPair());
531 PropertyAttributes rw_attribs =
532 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
533 PropertyAttributes ro_attribs =
534 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
536 Handle<AccessorInfo> length =
537 Accessors::FunctionLengthInfo(isolate(), ro_attribs);
539 CallbacksDescriptor d(Handle<Name>(Name::cast(length->name())),
541 map->AppendDescriptor(&d);
543 Handle<AccessorInfo> name =
544 Accessors::FunctionNameInfo(isolate(), ro_attribs);
546 CallbacksDescriptor d(Handle<Name>(Name::cast(name->name())),
548 map->AppendDescriptor(&d);
551 CallbacksDescriptor d(factory()->arguments_string(), arguments,
553 map->AppendDescriptor(&d);
556 CallbacksDescriptor d(factory()->caller_string(), caller, rw_attribs);
557 map->AppendDescriptor(&d);
559 if (prototypeMode != DONT_ADD_PROTOTYPE) {
561 PropertyAttributes attribs =
562 prototypeMode == ADD_WRITEABLE_PROTOTYPE ? rw_attribs : ro_attribs;
563 Handle<AccessorInfo> prototype =
564 Accessors::FunctionPrototypeInfo(isolate(), attribs);
565 CallbacksDescriptor d(Handle<Name>(Name::cast(prototype->name())),
567 map->AppendDescriptor(&d);
572 // ECMAScript 5th Edition, 13.2.3
573 Handle<JSFunction> Genesis::GetThrowTypeErrorFunction() {
574 if (throw_type_error_function.is_null()) {
575 Handle<String> name = factory()->InternalizeOneByteString(
576 STATIC_ASCII_VECTOR("ThrowTypeError"));
577 Handle<Code> code(isolate()->builtins()->builtin(
578 Builtins::kStrictModePoisonPill));
579 throw_type_error_function = factory()->NewFunction(name, code);
580 throw_type_error_function->set_map(native_context()->sloppy_function_map());
581 throw_type_error_function->shared()->DontAdaptArguments();
583 JSObject::PreventExtensions(throw_type_error_function).Assert();
585 return throw_type_error_function;
589 Handle<Map> Genesis::CreateStrictFunctionMap(
590 PrototypePropertyMode prototype_mode,
591 Handle<JSFunction> empty_function) {
592 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
593 SetStrictFunctionInstanceDescriptor(map, prototype_mode);
594 map->set_function_with_prototype(prototype_mode != DONT_ADD_PROTOTYPE);
595 map->set_prototype(*empty_function);
600 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
601 // Allocate map for the prototype-less strict mode instances.
602 Handle<Map> strict_function_without_prototype_map =
603 CreateStrictFunctionMap(DONT_ADD_PROTOTYPE, empty);
604 native_context()->set_strict_function_without_prototype_map(
605 *strict_function_without_prototype_map);
607 // Allocate map for the strict mode functions. This map is temporary, used
608 // only for processing of builtins.
609 // Later the map is replaced with writable prototype map, allocated below.
610 Handle<Map> strict_function_map =
611 CreateStrictFunctionMap(ADD_READONLY_PROTOTYPE, empty);
612 native_context()->set_strict_function_map(*strict_function_map);
614 // The final map for the strict mode functions. Writeable prototype.
615 // This map is installed in MakeFunctionInstancePrototypeWritable.
616 strict_function_map_writable_prototype_ =
617 CreateStrictFunctionMap(ADD_WRITEABLE_PROTOTYPE, empty);
619 // Complete the callbacks.
620 PoisonArgumentsAndCaller(strict_function_without_prototype_map);
621 PoisonArgumentsAndCaller(strict_function_map);
622 PoisonArgumentsAndCaller(strict_function_map_writable_prototype_);
626 static void SetAccessors(Handle<Map> map,
628 Handle<JSFunction> func) {
629 DescriptorArray* descs = map->instance_descriptors();
630 int number = descs->SearchWithCache(*name, *map);
631 AccessorPair* accessors = AccessorPair::cast(descs->GetValue(number));
632 accessors->set_getter(*func);
633 accessors->set_setter(*func);
637 void Genesis::PoisonArgumentsAndCaller(Handle<Map> map) {
638 SetAccessors(map, factory()->arguments_string(), GetThrowTypeErrorFunction());
639 SetAccessors(map, factory()->caller_string(), GetThrowTypeErrorFunction());
643 static void AddToWeakNativeContextList(Context* context) {
644 ASSERT(context->IsNativeContext());
645 Heap* heap = context->GetIsolate()->heap();
648 ASSERT(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
649 // Check that context is not in the list yet.
650 for (Object* current = heap->native_contexts_list();
651 !current->IsUndefined();
652 current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
653 ASSERT(current != context);
657 context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list());
658 heap->set_native_contexts_list(context);
662 void Genesis::CreateRoots() {
663 // Allocate the native context FixedArray first and then patch the
664 // closure and extension object later (we need the empty function
665 // and the global object, but in order to create those, we need the
667 native_context_ = factory()->NewNativeContext();
668 AddToWeakNativeContextList(*native_context());
669 isolate()->set_context(*native_context());
671 // Allocate the message listeners object.
673 v8::NeanderArray listeners(isolate());
674 native_context()->set_message_listeners(*listeners.value());
679 Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
680 v8::Handle<v8::ObjectTemplate> global_template,
681 Handle<Object> global_object,
682 Handle<GlobalObject>* inner_global_out) {
683 // The argument global_template aka data is an ObjectTemplateInfo.
684 // It has a constructor pointer that points at global_constructor which is a
685 // FunctionTemplateInfo.
686 // The global_constructor is used to create or reinitialize the global_proxy.
687 // The global_constructor also has a prototype_template pointer that points at
688 // js_global_template which is an ObjectTemplateInfo.
689 // That in turn has a constructor pointer that points at
690 // js_global_constructor which is a FunctionTemplateInfo.
691 // js_global_constructor is used to make js_global_function
692 // js_global_function is used to make the new inner_global.
694 // --- G l o b a l ---
695 // Step 1: Create a fresh inner JSGlobalObject.
696 Handle<JSFunction> js_global_function;
697 Handle<ObjectTemplateInfo> js_global_template;
698 if (!global_template.IsEmpty()) {
699 // Get prototype template of the global_template.
700 Handle<ObjectTemplateInfo> data =
701 v8::Utils::OpenHandle(*global_template);
702 Handle<FunctionTemplateInfo> global_constructor =
703 Handle<FunctionTemplateInfo>(
704 FunctionTemplateInfo::cast(data->constructor()));
705 Handle<Object> proto_template(global_constructor->prototype_template(),
707 if (!proto_template->IsUndefined()) {
709 Handle<ObjectTemplateInfo>::cast(proto_template);
713 if (js_global_template.is_null()) {
714 Handle<String> name = Handle<String>(heap()->empty_string());
715 Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
716 Builtins::kIllegal));
718 factory()->NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
719 JSGlobalObject::kSize, code, true);
720 // Change the constructor property of the prototype of the
721 // hidden global function to refer to the Object function.
722 Handle<JSObject> prototype =
724 JSObject::cast(js_global_function->instance_prototype()));
725 JSObject::SetLocalPropertyIgnoreAttributes(
726 prototype, factory()->constructor_string(),
727 isolate()->object_function(), NONE).Check();
729 Handle<FunctionTemplateInfo> js_global_constructor(
730 FunctionTemplateInfo::cast(js_global_template->constructor()));
732 factory()->CreateApiFunction(js_global_constructor,
733 factory()->the_hole_value(),
734 factory()->InnerGlobalObject);
737 js_global_function->initial_map()->set_is_hidden_prototype();
738 js_global_function->initial_map()->set_dictionary_map(true);
739 Handle<GlobalObject> inner_global =
740 factory()->NewGlobalObject(js_global_function);
741 if (inner_global_out != NULL) {
742 *inner_global_out = inner_global;
745 // Step 2: create or re-initialize the global proxy object.
746 Handle<JSFunction> global_proxy_function;
747 if (global_template.IsEmpty()) {
748 Handle<String> name = Handle<String>(heap()->empty_string());
749 Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
750 Builtins::kIllegal));
751 global_proxy_function =
752 factory()->NewFunction(name, JS_GLOBAL_PROXY_TYPE,
753 JSGlobalProxy::kSize, code, true);
755 Handle<ObjectTemplateInfo> data =
756 v8::Utils::OpenHandle(*global_template);
757 Handle<FunctionTemplateInfo> global_constructor(
758 FunctionTemplateInfo::cast(data->constructor()));
759 global_proxy_function =
760 factory()->CreateApiFunction(global_constructor,
761 factory()->the_hole_value(),
762 factory()->OuterGlobalObject);
765 Handle<String> global_name = factory()->InternalizeOneByteString(
766 STATIC_ASCII_VECTOR("global"));
767 global_proxy_function->shared()->set_instance_class_name(*global_name);
768 global_proxy_function->initial_map()->set_is_access_check_needed(true);
770 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
771 // Return the global proxy.
773 if (global_object.location() != NULL) {
774 ASSERT(global_object->IsJSGlobalProxy());
775 Handle<JSGlobalProxy> global_proxy =
776 Handle<JSGlobalProxy>::cast(global_object);
777 factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
780 return Handle<JSGlobalProxy>::cast(
781 factory()->NewJSObject(global_proxy_function, TENURED));
786 void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
787 Handle<JSGlobalProxy> global_proxy) {
788 // Set the native context for the global object.
789 inner_global->set_native_context(*native_context());
790 inner_global->set_global_context(*native_context());
791 inner_global->set_global_receiver(*global_proxy);
792 global_proxy->set_native_context(*native_context());
793 native_context()->set_global_proxy(*global_proxy);
797 void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
798 Handle<GlobalObject> inner_global_from_snapshot(
799 GlobalObject::cast(native_context()->extension()));
800 Handle<JSBuiltinsObject> builtins_global(native_context()->builtins());
801 native_context()->set_extension(*inner_global);
802 native_context()->set_global_object(*inner_global);
803 native_context()->set_security_token(*inner_global);
804 static const PropertyAttributes attributes =
805 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
806 Runtime::ForceSetObjectProperty(builtins_global,
807 factory()->InternalizeOneByteString(
808 STATIC_ASCII_VECTOR("global")),
810 attributes).Assert();
811 // Set up the reference from the global object to the builtins object.
812 JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
813 TransferNamedProperties(inner_global_from_snapshot, inner_global);
814 TransferIndexedProperties(inner_global_from_snapshot, inner_global);
818 // This is only called if we are not using snapshots. The equivalent
819 // work in the snapshot case is done in HookUpInnerGlobal.
820 void Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
821 Handle<JSFunction> empty_function) {
822 // --- N a t i v e C o n t e x t ---
823 // Use the empty function as closure (no scope info).
824 native_context()->set_closure(*empty_function);
825 native_context()->set_previous(NULL);
826 // Set extension and global object.
827 native_context()->set_extension(*inner_global);
828 native_context()->set_global_object(*inner_global);
829 // Security setup: Set the security token of the global object to
830 // its the inner global. This makes the security check between two
831 // different contexts fail by default even in case of global
832 // object reinitialization.
833 native_context()->set_security_token(*inner_global);
835 Isolate* isolate = inner_global->GetIsolate();
836 Factory* factory = isolate->factory();
837 Heap* heap = isolate->heap();
839 Handle<String> object_name = factory->Object_string();
840 JSObject::SetLocalPropertyIgnoreAttributes(
841 inner_global, object_name,
842 isolate->object_function(), DONT_ENUM).Check();
844 Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
846 // Install global Function object
847 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
848 empty_function, Builtins::kIllegal, true, true);
850 { // --- A r r a y ---
851 Handle<JSFunction> array_function =
852 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
853 isolate->initial_object_prototype(),
854 Builtins::kArrayCode, true, true);
855 array_function->shared()->DontAdaptArguments();
856 array_function->shared()->set_function_data(Smi::FromInt(kArrayCode));
858 // This seems a bit hackish, but we need to make sure Array.length
860 array_function->shared()->set_length(1);
862 Handle<Map> initial_map(array_function->initial_map());
864 // This assert protects an optimization in
865 // HGraphBuilder::JSArrayBuilder::EmitMapCode()
866 ASSERT(initial_map->elements_kind() == GetInitialFastElementsKind());
867 Map::EnsureDescriptorSlack(initial_map, 1);
869 PropertyAttributes attribs = static_cast<PropertyAttributes>(
870 DONT_ENUM | DONT_DELETE);
872 Handle<AccessorInfo> array_length =
873 Accessors::ArrayLengthInfo(isolate, attribs);
875 CallbacksDescriptor d(
876 Handle<Name>(Name::cast(array_length->name())),
877 array_length, attribs);
878 array_function->initial_map()->AppendDescriptor(&d);
881 // array_function is used internally. JS code creating array object should
882 // search for the 'Array' property on the global object and use that one
883 // as the constructor. 'Array' property on a global object can be
884 // overwritten by JS code.
885 native_context()->set_array_function(*array_function);
887 // Cache the array maps, needed by ArrayConstructorStub
888 CacheInitialJSArrayMaps(native_context(), initial_map);
889 ArrayConstructorStub array_constructor_stub(isolate);
890 Handle<Code> code = array_constructor_stub.GetCode();
891 array_function->shared()->set_construct_stub(*code);
894 { // --- N u m b e r ---
895 Handle<JSFunction> number_fun =
896 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
897 isolate->initial_object_prototype(),
898 Builtins::kIllegal, true, true);
899 native_context()->set_number_function(*number_fun);
902 { // --- B o o l e a n ---
903 Handle<JSFunction> boolean_fun =
904 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
905 isolate->initial_object_prototype(),
906 Builtins::kIllegal, true, true);
907 native_context()->set_boolean_function(*boolean_fun);
910 { // --- S t r i n g ---
911 Handle<JSFunction> string_fun =
912 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
913 isolate->initial_object_prototype(),
914 Builtins::kIllegal, true, true);
915 string_fun->shared()->set_construct_stub(
916 isolate->builtins()->builtin(Builtins::kStringConstructCode));
917 native_context()->set_string_function(*string_fun);
919 Handle<Map> string_map =
920 Handle<Map>(native_context()->string_function()->initial_map());
921 Map::EnsureDescriptorSlack(string_map, 1);
923 PropertyAttributes attribs = static_cast<PropertyAttributes>(
924 DONT_ENUM | DONT_DELETE | READ_ONLY);
925 Handle<AccessorInfo> string_length(
926 Accessors::StringLengthInfo(isolate, attribs));
929 CallbacksDescriptor d(factory->length_string(), string_length, attribs);
930 string_map->AppendDescriptor(&d);
935 // Builtin functions for Date.prototype.
936 Handle<JSFunction> date_fun =
937 InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize,
938 isolate->initial_object_prototype(),
939 Builtins::kIllegal, true, true);
941 native_context()->set_date_function(*date_fun);
946 // Builtin functions for RegExp.prototype.
947 Handle<JSFunction> regexp_fun =
948 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
949 isolate->initial_object_prototype(),
950 Builtins::kIllegal, true, true);
951 native_context()->set_regexp_function(*regexp_fun);
953 ASSERT(regexp_fun->has_initial_map());
954 Handle<Map> initial_map(regexp_fun->initial_map());
956 ASSERT_EQ(0, initial_map->inobject_properties());
958 PropertyAttributes final =
959 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
960 Map::EnsureDescriptorSlack(initial_map, 5);
963 // ECMA-262, section 15.10.7.1.
964 FieldDescriptor field(factory->source_string(),
965 JSRegExp::kSourceFieldIndex,
967 Representation::Tagged());
968 initial_map->AppendDescriptor(&field);
971 // ECMA-262, section 15.10.7.2.
972 FieldDescriptor field(factory->global_string(),
973 JSRegExp::kGlobalFieldIndex,
975 Representation::Tagged());
976 initial_map->AppendDescriptor(&field);
979 // ECMA-262, section 15.10.7.3.
980 FieldDescriptor field(factory->ignore_case_string(),
981 JSRegExp::kIgnoreCaseFieldIndex,
983 Representation::Tagged());
984 initial_map->AppendDescriptor(&field);
987 // ECMA-262, section 15.10.7.4.
988 FieldDescriptor field(factory->multiline_string(),
989 JSRegExp::kMultilineFieldIndex,
991 Representation::Tagged());
992 initial_map->AppendDescriptor(&field);
995 // ECMA-262, section 15.10.7.5.
996 PropertyAttributes writable =
997 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
998 FieldDescriptor field(factory->last_index_string(),
999 JSRegExp::kLastIndexFieldIndex,
1001 Representation::Tagged());
1002 initial_map->AppendDescriptor(&field);
1005 initial_map->set_inobject_properties(5);
1006 initial_map->set_pre_allocated_property_fields(5);
1007 initial_map->set_unused_property_fields(0);
1008 initial_map->set_instance_size(
1009 initial_map->instance_size() + 5 * kPointerSize);
1010 initial_map->set_visitor_id(StaticVisitorBase::GetVisitorId(*initial_map));
1012 // RegExp prototype object is itself a RegExp.
1013 Handle<Map> proto_map = Map::Copy(initial_map);
1014 proto_map->set_prototype(native_context()->initial_object_prototype());
1015 Handle<JSObject> proto = factory->NewJSObjectFromMap(proto_map);
1016 proto->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex,
1017 heap->query_colon_string());
1018 proto->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex,
1019 heap->false_value());
1020 proto->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex,
1021 heap->false_value());
1022 proto->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex,
1023 heap->false_value());
1024 proto->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
1026 SKIP_WRITE_BARRIER); // It's a Smi.
1027 initial_map->set_prototype(*proto);
1028 factory->SetRegExpIrregexpData(Handle<JSRegExp>::cast(proto),
1029 JSRegExp::IRREGEXP, factory->empty_string(),
1030 JSRegExp::Flags(0), 0);
1034 Handle<String> name = factory->InternalizeUtf8String("JSON");
1035 Handle<JSFunction> cons = factory->NewFunctionWithPrototype(
1036 name, factory->the_hole_value());
1037 JSFunction::SetInstancePrototype(cons,
1038 Handle<Object>(native_context()->initial_object_prototype(), isolate));
1039 cons->SetInstanceClassName(*name);
1040 Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1041 ASSERT(json_object->IsJSObject());
1042 JSObject::SetLocalPropertyIgnoreAttributes(
1043 global, name, json_object, DONT_ENUM).Check();
1044 native_context()->set_json_object(*json_object);
1047 { // -- A r r a y B u f f e r
1048 Handle<JSFunction> array_buffer_fun =
1050 global, "ArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1051 JSArrayBuffer::kSizeWithInternalFields,
1052 isolate->initial_object_prototype(),
1053 Builtins::kIllegal, true, true);
1054 native_context()->set_array_buffer_fun(*array_buffer_fun);
1057 { // -- T y p e d A r r a y s
1058 #define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype, size) \
1060 Handle<JSFunction> fun; \
1061 Handle<Map> external_map; \
1062 InstallTypedArray(#Type "Array", \
1066 native_context()->set_##type##_array_fun(*fun); \
1067 native_context()->set_##type##_array_external_map(*external_map); \
1069 BUILTIN_TYPED_ARRAY(INSTALL_TYPED_ARRAY)
1070 #undef INSTALL_TYPED_ARRAY
1072 Handle<JSFunction> data_view_fun =
1074 global, "DataView", JS_DATA_VIEW_TYPE,
1075 JSDataView::kSizeWithInternalFields,
1076 isolate->initial_object_prototype(),
1077 Builtins::kIllegal, true, true);
1078 native_context()->set_data_view_fun(*data_view_fun);
1081 { // --- arguments_boilerplate_
1082 // Make sure we can recognize argument objects at runtime.
1083 // This is done by introducing an anonymous function with
1084 // class_name equals 'Arguments'.
1085 Handle<String> arguments_string = factory->InternalizeOneByteString(
1086 STATIC_ASCII_VECTOR("Arguments"));
1087 Handle<Code> code(isolate->builtins()->builtin(Builtins::kIllegal));
1088 Handle<JSObject> prototype(
1089 JSObject::cast(native_context()->object_function()->prototype()));
1091 Handle<JSFunction> function =
1092 factory->NewFunctionWithPrototype(arguments_string,
1094 JSObject::kHeaderSize,
1098 ASSERT(!function->has_initial_map());
1099 function->shared()->set_instance_class_name(*arguments_string);
1100 function->shared()->set_expected_nof_properties(2);
1101 Handle<JSObject> result = factory->NewJSObject(function);
1103 native_context()->set_sloppy_arguments_boilerplate(*result);
1104 // Note: length must be added as the first property and
1105 // callee must be added as the second property.
1106 JSObject::SetLocalPropertyIgnoreAttributes(
1107 result, factory->length_string(),
1108 factory->undefined_value(), DONT_ENUM,
1109 Object::FORCE_TAGGED, FORCE_FIELD).Check();
1110 JSObject::SetLocalPropertyIgnoreAttributes(
1111 result, factory->callee_string(),
1112 factory->undefined_value(), DONT_ENUM,
1113 Object::FORCE_TAGGED, FORCE_FIELD).Check();
1116 LookupResult lookup(isolate);
1117 result->LocalLookup(factory->callee_string(), &lookup);
1118 ASSERT(lookup.IsField());
1119 ASSERT(lookup.GetFieldIndex().field_index() == Heap::kArgumentsCalleeIndex);
1121 result->LocalLookup(factory->length_string(), &lookup);
1122 ASSERT(lookup.IsField());
1123 ASSERT(lookup.GetFieldIndex().field_index() == Heap::kArgumentsLengthIndex);
1125 ASSERT(result->map()->inobject_properties() > Heap::kArgumentsCalleeIndex);
1126 ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1128 // Check the state of the object.
1129 ASSERT(result->HasFastProperties());
1130 ASSERT(result->HasFastObjectElements());
1134 { // --- aliased_arguments_boilerplate_
1135 // Set up a well-formed parameter map to make assertions happy.
1136 Handle<FixedArray> elements = factory->NewFixedArray(2);
1137 elements->set_map(heap->sloppy_arguments_elements_map());
1138 Handle<FixedArray> array;
1139 array = factory->NewFixedArray(0);
1140 elements->set(0, *array);
1141 array = factory->NewFixedArray(0);
1142 elements->set(1, *array);
1144 Handle<Map> old_map(
1145 native_context()->sloppy_arguments_boilerplate()->map());
1146 Handle<Map> new_map = Map::Copy(old_map);
1147 new_map->set_pre_allocated_property_fields(2);
1148 Handle<JSObject> result = factory->NewJSObjectFromMap(new_map);
1149 // Set elements kind after allocating the object because
1150 // NewJSObjectFromMap assumes a fast elements map.
1151 new_map->set_elements_kind(SLOPPY_ARGUMENTS_ELEMENTS);
1152 result->set_elements(*elements);
1153 ASSERT(result->HasSloppyArgumentsElements());
1154 native_context()->set_aliased_arguments_boilerplate(*result);
1157 { // --- strict mode arguments boilerplate
1158 const PropertyAttributes attributes =
1159 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1161 // Create the ThrowTypeError functions.
1162 Handle<AccessorPair> callee = factory->NewAccessorPair();
1163 Handle<AccessorPair> caller = factory->NewAccessorPair();
1165 Handle<JSFunction> throw_function =
1166 GetThrowTypeErrorFunction();
1168 // Install the ThrowTypeError functions.
1169 callee->set_getter(*throw_function);
1170 callee->set_setter(*throw_function);
1171 caller->set_getter(*throw_function);
1172 caller->set_setter(*throw_function);
1174 // Create the map. Allocate one in-object field for length.
1175 Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE,
1176 Heap::kStrictArgumentsObjectSize);
1177 // Create the descriptor array for the arguments object.
1178 Map::EnsureDescriptorSlack(map, 3);
1182 factory->length_string(), 0, DONT_ENUM, Representation::Tagged());
1183 map->AppendDescriptor(&d);
1186 CallbacksDescriptor d(factory->callee_string(),
1189 map->AppendDescriptor(&d);
1192 CallbacksDescriptor d(factory->caller_string(),
1195 map->AppendDescriptor(&d);
1198 map->set_function_with_prototype(true);
1199 map->set_prototype(native_context()->object_function()->prototype());
1200 map->set_pre_allocated_property_fields(1);
1201 map->set_inobject_properties(1);
1203 // Copy constructor from the sloppy arguments boilerplate.
1204 map->set_constructor(
1205 native_context()->sloppy_arguments_boilerplate()->map()->constructor());
1207 // Allocate the arguments boilerplate object.
1208 Handle<JSObject> result = factory->NewJSObjectFromMap(map);
1209 native_context()->set_strict_arguments_boilerplate(*result);
1211 // Add length property only for strict mode boilerplate.
1212 JSObject::SetLocalPropertyIgnoreAttributes(
1213 result, factory->length_string(),
1214 factory->undefined_value(), DONT_ENUM).Check();
1217 LookupResult lookup(isolate);
1218 result->LocalLookup(factory->length_string(), &lookup);
1219 ASSERT(lookup.IsField());
1220 ASSERT(lookup.GetFieldIndex().field_index() == Heap::kArgumentsLengthIndex);
1222 ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1224 // Check the state of the object.
1225 ASSERT(result->HasFastProperties());
1226 ASSERT(result->HasFastObjectElements());
1230 { // --- context extension
1231 // Create a function for the context extension objects.
1232 Handle<Code> code = Handle<Code>(
1233 isolate->builtins()->builtin(Builtins::kIllegal));
1234 Handle<JSFunction> context_extension_fun =
1235 factory->NewFunction(factory->empty_string(),
1236 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
1237 JSObject::kHeaderSize,
1241 Handle<String> name = factory->InternalizeOneByteString(
1242 STATIC_ASCII_VECTOR("context_extension"));
1243 context_extension_fun->shared()->set_instance_class_name(*name);
1244 native_context()->set_context_extension_function(*context_extension_fun);
1249 // Set up the call-as-function delegate.
1251 Handle<Code>(isolate->builtins()->builtin(
1252 Builtins::kHandleApiCallAsFunction));
1253 Handle<JSFunction> delegate =
1254 factory->NewFunction(factory->empty_string(), JS_OBJECT_TYPE,
1255 JSObject::kHeaderSize, code, true);
1256 native_context()->set_call_as_function_delegate(*delegate);
1257 delegate->shared()->DontAdaptArguments();
1261 // Set up the call-as-constructor delegate.
1263 Handle<Code>(isolate->builtins()->builtin(
1264 Builtins::kHandleApiCallAsConstructor));
1265 Handle<JSFunction> delegate =
1266 factory->NewFunction(factory->empty_string(), JS_OBJECT_TYPE,
1267 JSObject::kHeaderSize, code, true);
1268 native_context()->set_call_as_constructor_delegate(*delegate);
1269 delegate->shared()->DontAdaptArguments();
1272 // Initialize the embedder data slot.
1273 Handle<FixedArray> embedder_data = factory->NewFixedArray(3);
1274 native_context()->set_embedder_data(*embedder_data);
1278 void Genesis::InstallTypedArray(
1280 ElementsKind elements_kind,
1281 Handle<JSFunction>* fun,
1282 Handle<Map>* external_map) {
1283 Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1284 Handle<JSFunction> result = InstallFunction(global, name, JS_TYPED_ARRAY_TYPE,
1285 JSTypedArray::kSize, isolate()->initial_object_prototype(),
1286 Builtins::kIllegal, false, true);
1288 Handle<Map> initial_map = isolate()->factory()->NewMap(
1289 JS_TYPED_ARRAY_TYPE,
1290 JSTypedArray::kSizeWithInternalFields,
1292 result->set_initial_map(*initial_map);
1293 initial_map->set_constructor(*result);
1296 ElementsKind external_kind = GetNextTransitionElementsKind(elements_kind);
1297 *external_map = Map::AsElementsKind(initial_map, external_kind);
1301 void Genesis::InitializeExperimentalGlobal() {
1302 Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1304 // TODO(mstarzinger): Move this into Genesis::InitializeGlobal once we no
1305 // longer need to live behind flags, so functions get added to the snapshot.
1307 if (FLAG_harmony_symbols) {
1308 // --- S y m b o l ---
1309 Handle<JSFunction> symbol_fun =
1310 InstallFunction(global, "Symbol", JS_VALUE_TYPE, JSValue::kSize,
1311 isolate()->initial_object_prototype(),
1312 Builtins::kIllegal, true, true);
1313 native_context()->set_symbol_function(*symbol_fun);
1316 if (FLAG_harmony_collections) {
1318 InstallFunction(global, "Map", JS_MAP_TYPE, JSMap::kSize,
1319 isolate()->initial_object_prototype(),
1320 Builtins::kIllegal, true, true);
1323 InstallFunction(global, "Set", JS_SET_TYPE, JSSet::kSize,
1324 isolate()->initial_object_prototype(),
1325 Builtins::kIllegal, true, true);
1327 { // -- S e t I t e r a t o r
1328 Handle<Map> map = isolate()->factory()->NewMap(
1329 JS_SET_ITERATOR_TYPE, JSSetIterator::kSize);
1330 native_context()->set_set_iterator_map(*map);
1332 { // -- M a p I t e r a t o r
1333 Handle<Map> map = isolate()->factory()->NewMap(
1334 JS_MAP_ITERATOR_TYPE, JSMapIterator::kSize);
1335 native_context()->set_map_iterator_map(*map);
1339 if (FLAG_harmony_weak_collections) {
1340 { // -- W e a k M a p
1341 InstallFunction(global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
1342 isolate()->initial_object_prototype(),
1343 Builtins::kIllegal, true, true);
1345 { // -- W e a k S e t
1346 InstallFunction(global, "WeakSet", JS_WEAK_SET_TYPE, JSWeakSet::kSize,
1347 isolate()->initial_object_prototype(),
1348 Builtins::kIllegal, true, true);
1352 if (FLAG_harmony_generators) {
1353 // Create generator meta-objects and install them on the builtins object.
1354 Handle<JSObject> builtins(native_context()->builtins());
1355 Handle<JSObject> generator_object_prototype =
1356 factory()->NewJSObject(isolate()->object_function(), TENURED);
1357 Handle<JSFunction> generator_function_prototype =
1358 InstallFunction(builtins, "GeneratorFunctionPrototype",
1359 JS_FUNCTION_TYPE, JSFunction::kHeaderSize,
1360 generator_object_prototype, Builtins::kIllegal,
1362 InstallFunction(builtins, "GeneratorFunction",
1363 JS_FUNCTION_TYPE, JSFunction::kSize,
1364 generator_function_prototype, Builtins::kIllegal,
1367 // Create maps for generator functions and their prototypes. Store those
1368 // maps in the native context.
1369 Handle<Map> function_map(native_context()->sloppy_function_map());
1370 Handle<Map> generator_function_map = Map::Copy(function_map);
1371 generator_function_map->set_prototype(*generator_function_prototype);
1372 native_context()->set_sloppy_generator_function_map(
1373 *generator_function_map);
1375 Handle<Map> strict_mode_function_map(
1376 native_context()->strict_function_map());
1377 Handle<Map> strict_mode_generator_function_map =
1378 Map::Copy(strict_mode_function_map);
1379 strict_mode_generator_function_map->set_prototype(
1380 *generator_function_prototype);
1381 native_context()->set_strict_generator_function_map(
1382 *strict_mode_generator_function_map);
1384 Handle<JSFunction> object_function(native_context()->object_function());
1385 Handle<Map> generator_object_prototype_map = Map::Create(
1386 object_function, 0);
1387 generator_object_prototype_map->set_prototype(
1388 *generator_object_prototype);
1389 native_context()->set_generator_object_prototype_map(
1390 *generator_object_prototype_map);
1393 if (FLAG_harmony_collections || FLAG_harmony_generators) {
1394 // Collection forEach uses an iterator result object.
1395 // Generators return iteraror result objects.
1397 STATIC_ASSERT(JSGeneratorObject::kResultPropertyCount == 2);
1398 Handle<JSFunction> object_function(native_context()->object_function());
1399 ASSERT(object_function->initial_map()->inobject_properties() == 0);
1400 Handle<Map> iterator_result_map = Map::Create(
1401 object_function, JSGeneratorObject::kResultPropertyCount);
1402 ASSERT(iterator_result_map->inobject_properties() ==
1403 JSGeneratorObject::kResultPropertyCount);
1404 Map::EnsureDescriptorSlack(
1405 iterator_result_map, JSGeneratorObject::kResultPropertyCount);
1407 FieldDescriptor value_descr(isolate()->factory()->value_string(),
1408 JSGeneratorObject::kResultValuePropertyIndex,
1410 Representation::Tagged());
1411 iterator_result_map->AppendDescriptor(&value_descr);
1413 FieldDescriptor done_descr(isolate()->factory()->done_string(),
1414 JSGeneratorObject::kResultDonePropertyIndex,
1416 Representation::Tagged());
1417 iterator_result_map->AppendDescriptor(&done_descr);
1419 iterator_result_map->set_unused_property_fields(0);
1420 ASSERT_EQ(JSGeneratorObject::kResultSize,
1421 iterator_result_map->instance_size());
1422 native_context()->set_iterator_result_map(*iterator_result_map);
1425 if (FLAG_simd_object) {
1427 Handle<String> name = factory()->InternalizeUtf8String("SIMD");
1428 Handle<Code> code(isolate()->builtins()->builtin(Builtins::kEmptyFunction));
1429 Handle<JSFunction> cons =
1430 factory()->NewFunction(name, code);
1431 JSFunction::SetInstancePrototype(cons,
1432 Handle<Object>(native_context()->initial_object_prototype(),
1434 cons->SetInstanceClassName(*name);
1435 Handle<JSObject> simd_object = factory()->NewJSObject(cons, TENURED);
1436 ASSERT(simd_object->IsJSObject());
1437 JSObject::SetLocalPropertyIgnoreAttributes(
1438 global, name, simd_object, DONT_ENUM).Check();
1439 native_context()->set_simd_object(*simd_object);
1440 // --- f l o a t 3 2 x 4 ---
1441 Handle<JSFunction> float32x4_fun =
1442 InstallFunction(simd_object, "float32x4", JS_VALUE_TYPE, JSValue::kSize,
1443 isolate()->initial_object_prototype(),
1444 Builtins::kIllegal, true, true);
1445 native_context()->set_float32x4_function(*float32x4_fun);
1447 // --- f l o a t 6 4 x 2 ---
1448 Handle<JSFunction> float64x2_fun =
1449 InstallFunction(simd_object, "float64x2", JS_VALUE_TYPE, JSValue::kSize,
1450 isolate()->initial_object_prototype(),
1451 Builtins::kIllegal, true, true);
1452 native_context()->set_float64x2_function(*float64x2_fun);
1454 // --- i n t 3 2 x 4 ---
1455 Handle<JSFunction> int32x4_fun =
1456 InstallFunction(simd_object, "int32x4", JS_VALUE_TYPE, JSValue::kSize,
1457 isolate()->initial_object_prototype(),
1458 Builtins::kIllegal, true, true);
1459 native_context()->set_int32x4_function(*int32x4_fun);
1461 // --- F l o a t 3 2 x 4 A r r a y---
1462 Handle<JSFunction> fun;
1463 Handle<Map> external_map;
1465 "Float32x4Array", FLOAT32x4_ELEMENTS, &fun, &external_map);
1466 native_context()->set_float32x4_array_fun(*fun);
1467 native_context()->set_float32x4_array_external_map(*external_map);
1469 // --- F l o a t 6 4 x 2 A r r a y---
1471 "Float64x2Array", FLOAT64x2_ELEMENTS, &fun, &external_map);
1472 native_context()->set_float64x2_array_fun(*fun);
1473 native_context()->set_float64x2_array_external_map(*external_map);
1475 // --- I n t 3 2 x 4 A r r a y---
1477 "Int32x4Array", INT32x4_ELEMENTS, &fun, &external_map);
1478 native_context()->set_int32x4_array_fun(*fun);
1479 native_context()->set_int32x4_array_external_map(*external_map);
1484 bool Genesis::CompileBuiltin(Isolate* isolate, int index) {
1485 Vector<const char> name = Natives::GetScriptName(index);
1486 Handle<String> source_code =
1487 isolate->bootstrapper()->NativesSourceLookup(index);
1488 return CompileNative(isolate, name, source_code);
1492 bool Genesis::CompileExperimentalBuiltin(Isolate* isolate, int index) {
1493 Vector<const char> name = ExperimentalNatives::GetScriptName(index);
1494 Factory* factory = isolate->factory();
1495 Handle<String> source_code;
1496 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
1497 isolate, source_code,
1498 factory->NewStringFromAscii(
1499 ExperimentalNatives::GetRawScriptSource(index)),
1501 return CompileNative(isolate, name, source_code);
1505 bool Genesis::CompileNative(Isolate* isolate,
1506 Vector<const char> name,
1507 Handle<String> source) {
1508 HandleScope scope(isolate);
1509 isolate->debugger()->set_compiling_natives(true);
1510 // During genesis, the boilerplate for stack overflow won't work until the
1511 // environment has been at least partially initialized. Add a stack check
1512 // before entering JS code to catch overflow early.
1513 StackLimitCheck check(isolate);
1514 if (check.HasOverflowed()) return false;
1516 bool result = CompileScriptCached(isolate,
1521 Handle<Context>(isolate->context()),
1523 ASSERT(isolate->has_pending_exception() != result);
1524 if (!result) isolate->clear_pending_exception();
1525 isolate->debugger()->set_compiling_natives(false);
1530 bool Genesis::CompileScriptCached(Isolate* isolate,
1531 Vector<const char> name,
1532 Handle<String> source,
1533 SourceCodeCache* cache,
1534 v8::Extension* extension,
1535 Handle<Context> top_context,
1536 bool use_runtime_context) {
1537 Factory* factory = isolate->factory();
1538 HandleScope scope(isolate);
1539 Handle<SharedFunctionInfo> function_info;
1541 // If we can't find the function in the cache, we compile a new
1542 // function and insert it into the cache.
1543 if (cache == NULL || !cache->Lookup(name, &function_info)) {
1544 ASSERT(source->IsOneByteRepresentation());
1545 Handle<String> script_name =
1546 factory->NewStringFromUtf8(name).ToHandleChecked();
1547 function_info = Compiler::CompileScript(
1557 use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
1558 if (function_info.is_null()) return false;
1559 if (cache != NULL) cache->Add(name, function_info);
1562 // Set up the function context. Conceptually, we should clone the
1563 // function before overwriting the context but since we're in a
1564 // single-threaded environment it is not strictly necessary.
1565 ASSERT(top_context->IsNativeContext());
1566 Handle<Context> context =
1567 Handle<Context>(use_runtime_context
1568 ? Handle<Context>(top_context->runtime_context())
1570 Handle<JSFunction> fun =
1571 factory->NewFunctionFromSharedFunctionInfo(function_info, context);
1573 // Call function using either the runtime object or the global
1574 // object as the receiver. Provide no parameters.
1575 Handle<Object> receiver =
1576 Handle<Object>(use_runtime_context
1577 ? top_context->builtins()
1578 : top_context->global_object(),
1580 return !Execution::Call(
1581 isolate, fun, receiver, 0, NULL).is_null();
1585 #define INSTALL_NATIVE(Type, name, var) \
1586 Handle<String> var##_name = \
1587 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR(name)); \
1588 Handle<Object> var##_native = Object::GetProperty( \
1589 handle(native_context()->builtins()), var##_name).ToHandleChecked(); \
1590 native_context()->set_##var(Type::cast(*var##_native));
1593 void Genesis::InstallNativeFunctions() {
1594 HandleScope scope(isolate());
1595 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1596 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1597 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1598 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1599 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1600 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1601 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1602 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
1603 INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
1604 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1605 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1606 configure_instance_fun);
1607 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1608 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1609 INSTALL_NATIVE(JSFunction, "ToCompletePropertyDescriptor",
1610 to_complete_property_descriptor);
1611 INSTALL_NATIVE(JSFunction, "NotifyChange", observers_notify_change);
1612 INSTALL_NATIVE(JSFunction, "EnqueueSpliceRecord", observers_enqueue_splice);
1613 INSTALL_NATIVE(JSFunction, "BeginPerformSplice",
1614 observers_begin_perform_splice);
1615 INSTALL_NATIVE(JSFunction, "EndPerformSplice",
1616 observers_end_perform_splice);
1617 INSTALL_NATIVE(JSFunction, "NativeObjectObserve",
1618 native_object_observe);
1619 INSTALL_NATIVE(JSFunction, "NativeObjectGetNotifier",
1620 native_object_get_notifier);
1621 INSTALL_NATIVE(JSFunction, "NativeObjectNotifierPerformChange",
1622 native_object_notifier_perform_change);
1626 void Genesis::InstallExperimentalNativeFunctions() {
1627 INSTALL_NATIVE(JSFunction, "RunMicrotasks", run_microtasks);
1628 INSTALL_NATIVE(JSFunction, "EnqueueMicrotask", enqueue_microtask);
1630 if (FLAG_harmony_promises) {
1631 INSTALL_NATIVE(JSFunction, "IsPromise", is_promise);
1632 INSTALL_NATIVE(JSFunction, "PromiseCreate", promise_create);
1633 INSTALL_NATIVE(JSFunction, "PromiseResolve", promise_resolve);
1634 INSTALL_NATIVE(JSFunction, "PromiseReject", promise_reject);
1635 INSTALL_NATIVE(JSFunction, "PromiseChain", promise_chain);
1636 INSTALL_NATIVE(JSFunction, "PromiseCatch", promise_catch);
1639 if (FLAG_harmony_proxies) {
1640 INSTALL_NATIVE(JSFunction, "DerivedHasTrap", derived_has_trap);
1641 INSTALL_NATIVE(JSFunction, "DerivedGetTrap", derived_get_trap);
1642 INSTALL_NATIVE(JSFunction, "DerivedSetTrap", derived_set_trap);
1643 INSTALL_NATIVE(JSFunction, "ProxyEnumerate", proxy_enumerate);
1647 #undef INSTALL_NATIVE
1650 Handle<JSFunction> Genesis::InstallInternalArray(
1651 Handle<JSBuiltinsObject> builtins,
1653 ElementsKind elements_kind) {
1654 // --- I n t e r n a l A r r a y ---
1655 // An array constructor on the builtins object that works like
1656 // the public Array constructor, except that its prototype
1657 // doesn't inherit from Object.prototype.
1658 // To be used only for internal work by builtins. Instances
1659 // must not be leaked to user code.
1660 Handle<JSFunction> array_function =
1661 InstallFunction(builtins,
1665 isolate()->initial_object_prototype(),
1666 Builtins::kInternalArrayCode,
1668 Handle<JSObject> prototype =
1669 factory()->NewJSObject(isolate()->object_function(), TENURED);
1670 Accessors::FunctionSetPrototype(array_function, prototype);
1672 InternalArrayConstructorStub internal_array_constructor_stub(isolate());
1673 Handle<Code> code = internal_array_constructor_stub.GetCode();
1674 array_function->shared()->set_construct_stub(*code);
1675 array_function->shared()->DontAdaptArguments();
1677 Handle<Map> original_map(array_function->initial_map());
1678 Handle<Map> initial_map = Map::Copy(original_map);
1679 initial_map->set_elements_kind(elements_kind);
1680 array_function->set_initial_map(*initial_map);
1682 // Make "length" magic on instances.
1683 Map::EnsureDescriptorSlack(initial_map, 1);
1685 PropertyAttributes attribs = static_cast<PropertyAttributes>(
1686 DONT_ENUM | DONT_DELETE);
1688 Handle<AccessorInfo> array_length =
1689 Accessors::ArrayLengthInfo(isolate(), attribs);
1691 CallbacksDescriptor d(
1692 Handle<Name>(Name::cast(array_length->name())), array_length, attribs);
1693 array_function->initial_map()->AppendDescriptor(&d);
1696 return array_function;
1700 bool Genesis::InstallNatives() {
1701 HandleScope scope(isolate());
1703 // Create a function for the builtins object. Allocate space for the
1704 // JavaScript builtins, a reference to the builtins object
1705 // (itself) and a reference to the native_context directly in the object.
1706 Handle<Code> code = Handle<Code>(
1707 isolate()->builtins()->builtin(Builtins::kIllegal));
1708 Handle<JSFunction> builtins_fun =
1709 factory()->NewFunction(factory()->empty_string(),
1710 JS_BUILTINS_OBJECT_TYPE,
1711 JSBuiltinsObject::kSize, code, true);
1713 Handle<String> name =
1714 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("builtins"));
1715 builtins_fun->shared()->set_instance_class_name(*name);
1716 builtins_fun->initial_map()->set_dictionary_map(true);
1717 builtins_fun->initial_map()->set_prototype(heap()->null_value());
1719 // Allocate the builtins object.
1720 Handle<JSBuiltinsObject> builtins =
1721 Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
1722 builtins->set_builtins(*builtins);
1723 builtins->set_native_context(*native_context());
1724 builtins->set_global_context(*native_context());
1725 builtins->set_global_receiver(*builtins);
1726 builtins->set_global_receiver(native_context()->global_proxy());
1729 // Set up the 'global' properties of the builtins object. The
1730 // 'global' property that refers to the global object is the only
1731 // way to get from code running in the builtins context to the
1733 static const PropertyAttributes attributes =
1734 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1735 Handle<String> global_string =
1736 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("global"));
1737 Handle<Object> global_obj(native_context()->global_object(), isolate());
1738 JSObject::SetLocalPropertyIgnoreAttributes(
1739 builtins, global_string, global_obj, attributes).Check();
1740 Handle<String> builtins_string =
1741 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("builtins"));
1742 JSObject::SetLocalPropertyIgnoreAttributes(
1743 builtins, builtins_string, builtins, attributes).Check();
1745 // Set up the reference from the global object to the builtins object.
1746 JSGlobalObject::cast(native_context()->global_object())->
1747 set_builtins(*builtins);
1749 // Create a bridge function that has context in the native context.
1750 Handle<JSFunction> bridge = factory()->NewFunctionWithPrototype(
1751 factory()->empty_string(), factory()->undefined_value());
1752 ASSERT(bridge->context() == *isolate()->native_context());
1754 // Allocate the builtins context.
1755 Handle<Context> context =
1756 factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1757 context->set_global_object(*builtins); // override builtins global object
1759 native_context()->set_runtime_context(*context);
1762 // Builtin functions for Script.
1763 Handle<JSFunction> script_fun =
1764 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1765 isolate()->initial_object_prototype(),
1766 Builtins::kIllegal, false, false);
1767 Handle<JSObject> prototype =
1768 factory()->NewJSObject(isolate()->object_function(), TENURED);
1769 Accessors::FunctionSetPrototype(script_fun, prototype);
1770 native_context()->set_script_function(*script_fun);
1772 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1773 Map::EnsureDescriptorSlack(script_map, 13);
1775 PropertyAttributes attribs =
1776 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1778 Handle<AccessorInfo> script_column =
1779 Accessors::ScriptColumnOffsetInfo(isolate(), attribs);
1781 CallbacksDescriptor d(Handle<Name>(Name::cast(script_column->name())),
1782 script_column, attribs);
1783 script_map->AppendDescriptor(&d);
1786 Handle<AccessorInfo> script_id =
1787 Accessors::ScriptIdInfo(isolate(), attribs);
1789 CallbacksDescriptor d(Handle<Name>(Name::cast(script_id->name())),
1790 script_id, attribs);
1791 script_map->AppendDescriptor(&d);
1795 Handle<AccessorInfo> script_name =
1796 Accessors::ScriptNameInfo(isolate(), attribs);
1798 CallbacksDescriptor d(Handle<Name>(Name::cast(script_name->name())),
1799 script_name, attribs);
1800 script_map->AppendDescriptor(&d);
1803 Handle<AccessorInfo> script_line =
1804 Accessors::ScriptLineOffsetInfo(isolate(), attribs);
1806 CallbacksDescriptor d(Handle<Name>(Name::cast(script_line->name())),
1807 script_line, attribs);
1808 script_map->AppendDescriptor(&d);
1811 Handle<AccessorInfo> script_source =
1812 Accessors::ScriptSourceInfo(isolate(), attribs);
1814 CallbacksDescriptor d(Handle<Name>(Name::cast(script_source->name())),
1815 script_source, attribs);
1816 script_map->AppendDescriptor(&d);
1819 Handle<AccessorInfo> script_type =
1820 Accessors::ScriptTypeInfo(isolate(), attribs);
1822 CallbacksDescriptor d(Handle<Name>(Name::cast(script_type->name())),
1823 script_type, attribs);
1824 script_map->AppendDescriptor(&d);
1827 Handle<AccessorInfo> script_compilation_type =
1828 Accessors::ScriptCompilationTypeInfo(isolate(), attribs);
1830 CallbacksDescriptor d(
1831 Handle<Name>(Name::cast(script_compilation_type->name())),
1832 script_compilation_type, attribs);
1833 script_map->AppendDescriptor(&d);
1836 Handle<AccessorInfo> script_line_ends =
1837 Accessors::ScriptLineEndsInfo(isolate(), attribs);
1839 CallbacksDescriptor d(Handle<Name>(Name::cast(script_line_ends->name())),
1840 script_line_ends, attribs);
1841 script_map->AppendDescriptor(&d);
1844 Handle<AccessorInfo> script_context_data =
1845 Accessors::ScriptContextDataInfo(isolate(), attribs);
1847 CallbacksDescriptor d(
1848 Handle<Name>(Name::cast(script_context_data->name())),
1849 script_context_data, attribs);
1850 script_map->AppendDescriptor(&d);
1853 Handle<AccessorInfo> script_eval_from_script =
1854 Accessors::ScriptEvalFromScriptInfo(isolate(), attribs);
1856 CallbacksDescriptor d(
1857 Handle<Name>(Name::cast(script_eval_from_script->name())),
1858 script_eval_from_script, attribs);
1859 script_map->AppendDescriptor(&d);
1862 Handle<AccessorInfo> script_eval_from_script_position =
1863 Accessors::ScriptEvalFromScriptPositionInfo(isolate(), attribs);
1865 CallbacksDescriptor d(
1866 Handle<Name>(Name::cast(script_eval_from_script_position->name())),
1867 script_eval_from_script_position, attribs);
1868 script_map->AppendDescriptor(&d);
1871 Handle<AccessorInfo> script_eval_from_function_name =
1872 Accessors::ScriptEvalFromFunctionNameInfo(isolate(), attribs);
1874 CallbacksDescriptor d(
1875 Handle<Name>(Name::cast(script_eval_from_function_name->name())),
1876 script_eval_from_function_name, attribs);
1877 script_map->AppendDescriptor(&d);
1880 // Allocate the empty script.
1881 Handle<Script> script = factory()->NewScript(factory()->empty_string());
1882 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
1883 heap()->public_set_empty_script(*script);
1886 // Builtin function for OpaqueReference -- a JSValue-based object,
1887 // that keeps its field isolated from JavaScript code. It may store
1888 // objects, that JavaScript code may not access.
1889 Handle<JSFunction> opaque_reference_fun =
1890 InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1892 isolate()->initial_object_prototype(),
1893 Builtins::kIllegal, false, false);
1894 Handle<JSObject> prototype =
1895 factory()->NewJSObject(isolate()->object_function(), TENURED);
1896 Accessors::FunctionSetPrototype(opaque_reference_fun, prototype);
1897 native_context()->set_opaque_reference_function(*opaque_reference_fun);
1900 // InternalArrays should not use Smi-Only array optimizations. There are too
1901 // many places in the C++ runtime code (e.g. RegEx) that assume that
1902 // elements in InternalArrays can be set to non-Smi values without going
1903 // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
1904 // transition easy to trap. Moreover, they rarely are smi-only.
1906 Handle<JSFunction> array_function =
1907 InstallInternalArray(builtins, "InternalArray", FAST_HOLEY_ELEMENTS);
1908 native_context()->set_internal_array_function(*array_function);
1912 InstallInternalArray(builtins, "InternalPackedArray", FAST_ELEMENTS);
1915 if (FLAG_disable_native_files) {
1916 PrintF("Warning: Running without installed natives!\n");
1921 for (int i = Natives::GetDebuggerCount();
1922 i < Natives::GetBuiltinsCount();
1924 if (!CompileBuiltin(isolate(), i)) return false;
1925 // TODO(ager): We really only need to install the JS builtin
1926 // functions on the builtins object after compiling and running
1928 if (!InstallJSBuiltins(builtins)) return false;
1931 InstallNativeFunctions();
1933 // Store the map for the string prototype after the natives has been compiled
1934 // and the String function has been set up.
1935 Handle<JSFunction> string_function(native_context()->string_function());
1936 ASSERT(JSObject::cast(
1937 string_function->initial_map()->prototype())->HasFastProperties());
1938 native_context()->set_string_function_prototype_map(
1939 HeapObject::cast(string_function->initial_map()->prototype())->map());
1941 // Install Function.prototype.call and apply.
1942 { Handle<String> key = factory()->function_class_string();
1943 Handle<JSFunction> function =
1944 Handle<JSFunction>::cast(Object::GetProperty(
1945 isolate()->global_object(), key).ToHandleChecked());
1946 Handle<JSObject> proto =
1947 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1949 // Install the call and the apply functions.
1950 Handle<JSFunction> call =
1951 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1952 Handle<JSObject>::null(),
1953 Builtins::kFunctionCall,
1955 Handle<JSFunction> apply =
1956 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1957 Handle<JSObject>::null(),
1958 Builtins::kFunctionApply,
1961 // Make sure that Function.prototype.call appears to be compiled.
1962 // The code will never be called, but inline caching for call will
1963 // only work if it appears to be compiled.
1964 call->shared()->DontAdaptArguments();
1965 ASSERT(call->is_compiled());
1967 // Set the expected parameters for apply to 2; required by builtin.
1968 apply->shared()->set_formal_parameter_count(2);
1970 // Set the lengths for the functions to satisfy ECMA-262.
1971 call->shared()->set_length(1);
1972 apply->shared()->set_length(2);
1975 InstallBuiltinFunctionIds();
1977 // Create a constructor for RegExp results (a variant of Array that
1978 // predefines the two properties index and match).
1980 // RegExpResult initial map.
1982 // Find global.Array.prototype to inherit from.
1983 Handle<JSFunction> array_constructor(native_context()->array_function());
1984 Handle<JSObject> array_prototype(
1985 JSObject::cast(array_constructor->instance_prototype()));
1988 Handle<Map> initial_map =
1989 factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1990 initial_map->set_constructor(*array_constructor);
1992 // Set prototype on map.
1993 initial_map->set_non_instance_prototype(false);
1994 initial_map->set_prototype(*array_prototype);
1996 // Update map with length accessor from Array and add "index" and "input".
1997 Map::EnsureDescriptorSlack(initial_map, 3);
2000 JSFunction* array_function = native_context()->array_function();
2001 Handle<DescriptorArray> array_descriptors(
2002 array_function->initial_map()->instance_descriptors());
2003 Handle<String> length = factory()->length_string();
2004 int old = array_descriptors->SearchWithCache(
2005 *length, array_function->initial_map());
2006 ASSERT(old != DescriptorArray::kNotFound);
2007 CallbacksDescriptor desc(length,
2008 handle(array_descriptors->GetValue(old),
2010 array_descriptors->GetDetails(old).attributes());
2011 initial_map->AppendDescriptor(&desc);
2014 FieldDescriptor index_field(factory()->index_string(),
2015 JSRegExpResult::kIndexIndex,
2017 Representation::Tagged());
2018 initial_map->AppendDescriptor(&index_field);
2022 FieldDescriptor input_field(factory()->input_string(),
2023 JSRegExpResult::kInputIndex,
2025 Representation::Tagged());
2026 initial_map->AppendDescriptor(&input_field);
2029 initial_map->set_inobject_properties(2);
2030 initial_map->set_pre_allocated_property_fields(2);
2031 initial_map->set_unused_property_fields(0);
2033 native_context()->set_regexp_result_map(*initial_map);
2037 builtins->ObjectVerify();
2044 #define INSTALL_EXPERIMENTAL_NATIVE(i, flag, file) \
2045 if (FLAG_harmony_##flag && \
2046 strcmp(ExperimentalNatives::GetScriptName(i).start(), \
2047 "native " file) == 0) { \
2048 if (!CompileExperimentalBuiltin(isolate(), i)) return false; \
2052 bool Genesis::InstallExperimentalNatives() {
2053 for (int i = ExperimentalNatives::GetDebuggerCount();
2054 i < ExperimentalNatives::GetBuiltinsCount();
2056 INSTALL_EXPERIMENTAL_NATIVE(i, symbols, "symbol.js")
2057 INSTALL_EXPERIMENTAL_NATIVE(i, proxies, "proxy.js")
2058 INSTALL_EXPERIMENTAL_NATIVE(i, collections, "collection.js")
2059 INSTALL_EXPERIMENTAL_NATIVE(i, weak_collections, "weak_collection.js")
2060 INSTALL_EXPERIMENTAL_NATIVE(i, promises, "promise.js")
2061 INSTALL_EXPERIMENTAL_NATIVE(i, generators, "generator.js")
2062 INSTALL_EXPERIMENTAL_NATIVE(i, iteration, "array-iterator.js")
2063 INSTALL_EXPERIMENTAL_NATIVE(i, strings, "harmony-string.js")
2064 INSTALL_EXPERIMENTAL_NATIVE(i, arrays, "harmony-array.js")
2065 INSTALL_EXPERIMENTAL_NATIVE(i, maths, "harmony-math.js")
2066 if (FLAG_simd_object &&
2067 strcmp(ExperimentalNatives::GetScriptName(i).start(),
2068 "native simd128.js") == 0) {
2069 if (!CompileExperimentalBuiltin(isolate(), i)) return false;
2070 // Store the map for the float32x4, float64x2 and int32x4 function
2071 // prototype after the float32x4 and int32x4 function has been set up.
2072 InstallExperimentalSIMDBuiltinFunctionIds();
2073 JSObject* float32x4_function_prototype = JSObject::cast(
2074 native_context()->float32x4_function()->instance_prototype());
2075 native_context()->set_float32x4_function_prototype_map(
2076 float32x4_function_prototype->map());
2077 JSObject* float64x2_function_prototype = JSObject::cast(
2078 native_context()->float64x2_function()->instance_prototype());
2079 native_context()->set_float64x2_function_prototype_map(
2080 float64x2_function_prototype->map());
2081 JSObject* int32x4_function_prototype = JSObject::cast(
2082 native_context()->int32x4_function()->instance_prototype());
2083 native_context()->set_int32x4_function_prototype_map(
2084 int32x4_function_prototype->map());
2088 InstallExperimentalNativeFunctions();
2089 InstallExperimentalBuiltinFunctionIds();
2094 static Handle<JSObject> ResolveBuiltinIdHolder(
2095 Handle<Context> native_context,
2096 const char* holder_expr) {
2097 Isolate* isolate = native_context->GetIsolate();
2098 Factory* factory = isolate->factory();
2099 Handle<GlobalObject> global(native_context->global_object());
2100 const char* period_pos = strchr(holder_expr, '.');
2101 if (period_pos == NULL) {
2102 return Handle<JSObject>::cast(Object::GetPropertyOrElement(
2103 global, factory->InternalizeUtf8String(holder_expr)).ToHandleChecked());
2105 ASSERT_EQ(".prototype", period_pos);
2106 Vector<const char> property(holder_expr,
2107 static_cast<int>(period_pos - holder_expr));
2108 Handle<String> property_string = factory->InternalizeUtf8String(property);
2109 ASSERT(!property_string.is_null());
2110 Handle<JSFunction> function = Handle<JSFunction>::cast(
2111 Object::GetProperty(global, property_string).ToHandleChecked());
2112 return Handle<JSObject>(JSObject::cast(function->prototype()));
2116 static Handle<JSObject> ResolveBuiltinSIMDIdHolder(
2117 Handle<Context> native_context,
2118 const char* holder_expr) {
2119 Isolate* isolate = native_context->GetIsolate();
2120 Factory* factory = isolate->factory();
2121 Handle<GlobalObject> global(native_context->global_object());
2122 Handle<Object> holder = global;
2123 char* name = const_cast<char*>(holder_expr);
2124 char* period_pos = strchr(name, '.');
2125 while (period_pos != NULL) {
2126 Vector<const char> property(name,
2127 static_cast<int>(period_pos - name));
2128 Handle<String> property_string = factory->InternalizeUtf8String(property);
2129 ASSERT(!property_string.is_null());
2130 holder = Object::GetProperty(holder, property_string).ToHandleChecked();
2131 if (strcmp(".prototype", period_pos) == 0) {
2132 Handle<JSFunction> function = Handle<JSFunction>::cast(holder);
2133 return Handle<JSObject>(JSObject::cast(function->prototype()));
2135 name = period_pos + 1;
2136 period_pos = strchr(name, '.');
2140 return Handle<JSObject>::cast(Object::GetPropertyOrElement(
2141 holder, factory->InternalizeUtf8String(name)).ToHandleChecked());
2145 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
2146 const char* function_name,
2147 BuiltinFunctionId id) {
2148 Isolate* isolate = holder->GetIsolate();
2149 Handle<Object> function_object =
2150 Object::GetProperty(isolate, holder, function_name).ToHandleChecked();
2151 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2152 function->shared()->set_function_data(Smi::FromInt(id));
2156 void Genesis::InstallBuiltinFunctionIds() {
2157 HandleScope scope(isolate());
2158 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2160 Handle<JSObject> holder = ResolveBuiltinIdHolder( \
2161 native_context(), #holder_expr); \
2162 BuiltinFunctionId id = k##name; \
2163 InstallBuiltinFunctionId(holder, #fun_name, id); \
2165 FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)
2166 #undef INSTALL_BUILTIN_ID
2170 void Genesis::InstallExperimentalBuiltinFunctionIds() {
2171 HandleScope scope(isolate());
2172 if (FLAG_harmony_maths) {
2173 Handle<JSObject> holder = ResolveBuiltinIdHolder(native_context(), "Math");
2174 InstallBuiltinFunctionId(holder, "clz32", kMathClz32);
2179 void Genesis::InstallExperimentalSIMDBuiltinFunctionIds() {
2180 HandleScope scope(isolate());
2181 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2183 Handle<JSObject> holder = ResolveBuiltinSIMDIdHolder( \
2184 native_context(), #holder_expr); \
2185 BuiltinFunctionId id = k##name; \
2186 InstallBuiltinFunctionId(holder, #fun_name, id); \
2188 SIMD_ARRAY_OPERATIONS(INSTALL_BUILTIN_ID)
2189 #define INSTALL_SIMD_NULLARY_FUNCTION_ID(p1, p2, p3, p4) \
2190 INSTALL_BUILTIN_ID(p1, p2, p3)
2191 SIMD_NULLARY_OPERATIONS(INSTALL_SIMD_NULLARY_FUNCTION_ID)
2192 #undef INSTALL_SIMD_NULLARY_FUNCTION_ID
2193 #define INSTALL_SIMD_UNARY_FUNCTION_ID(p1, p2, p3, p4, p5) \
2194 INSTALL_BUILTIN_ID(p1, p2, p3)
2195 SIMD_UNARY_OPERATIONS(INSTALL_SIMD_UNARY_FUNCTION_ID)
2196 #undef INSTALL_SIMD_UNARY_FUNCTION_ID
2197 #define INSTALL_SIMD_BINARY_FUNCTION_ID(p1, p2, p3, p4, p5, p6) \
2198 INSTALL_BUILTIN_ID(p1, p2, p3)
2199 SIMD_BINARY_OPERATIONS(INSTALL_SIMD_BINARY_FUNCTION_ID)
2200 #undef INSTALL_SIMD_BINARY_FUNCTION_ID
2201 #define INSTALL_SIMD_TERNARY_FUNCTION_ID(p1, p2, p3, p4, p5, p6, p7) \
2202 INSTALL_BUILTIN_ID(p1, p2, p3)
2203 SIMD_TERNARY_OPERATIONS(INSTALL_SIMD_TERNARY_FUNCTION_ID)
2204 #undef INSTALL_SIMD_TERNARY_FUNCTION_ID
2205 #define INSTALL_SIMD_QUARTERNARY_FUNCTION_ID(p1, p2, p3, p4, p5, p6, p7, p8) \
2206 INSTALL_BUILTIN_ID(p1, p2, p3)
2207 SIMD_QUARTERNARY_OPERATIONS(INSTALL_SIMD_QUARTERNARY_FUNCTION_ID)
2208 #undef INSTALL_SIMD_QUARTERNARY_FUNCTION_ID
2209 #undef INSTALL_BUILTIN_ID
2213 // Do not forget to update macros.py with named constant
2215 #define JSFUNCTION_RESULT_CACHE_LIST(F) \
2216 F(16, native_context()->regexp_function())
2219 static FixedArray* CreateCache(int size, Handle<JSFunction> factory_function) {
2220 Factory* factory = factory_function->GetIsolate()->factory();
2221 // Caches are supposed to live for a long time, allocate in old space.
2222 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
2223 // Cannot use cast as object is not fully initialized yet.
2224 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
2225 *factory->NewFixedArrayWithHoles(array_size, TENURED));
2226 cache->set(JSFunctionResultCache::kFactoryIndex, *factory_function);
2227 cache->MakeZeroSize();
2232 void Genesis::InstallJSFunctionResultCaches() {
2233 const int kNumberOfCaches = 0 +
2234 #define F(size, func) + 1
2235 JSFUNCTION_RESULT_CACHE_LIST(F)
2239 Handle<FixedArray> caches =
2240 factory()->NewFixedArray(kNumberOfCaches, TENURED);
2244 #define F(size, func) do { \
2245 FixedArray* cache = CreateCache((size), Handle<JSFunction>(func)); \
2246 caches->set(index++, cache); \
2249 JSFUNCTION_RESULT_CACHE_LIST(F);
2253 native_context()->set_jsfunction_result_caches(*caches);
2257 void Genesis::InitializeNormalizedMapCaches() {
2258 Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
2259 native_context()->set_normalized_map_cache(*cache);
2263 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
2264 v8::ExtensionConfiguration* extensions) {
2265 BootstrapperActive active(this);
2266 SaveContext saved_context(isolate_);
2267 isolate_->set_context(*native_context);
2268 return Genesis::InstallExtensions(native_context, extensions) &&
2269 Genesis::InstallSpecialObjects(native_context);
2273 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
2274 Isolate* isolate = native_context->GetIsolate();
2275 Factory* factory = isolate->factory();
2276 HandleScope scope(isolate);
2277 Handle<JSGlobalObject> global(JSGlobalObject::cast(
2278 native_context->global_object()));
2279 // Expose the natives in global if a name for it is specified.
2280 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
2281 Handle<String> natives =
2282 factory->InternalizeUtf8String(FLAG_expose_natives_as);
2283 RETURN_ON_EXCEPTION_VALUE(
2285 JSObject::SetLocalPropertyIgnoreAttributes(
2286 global, natives, Handle<JSObject>(global->builtins()), DONT_ENUM),
2290 Handle<Object> Error = Object::GetProperty(
2291 isolate, global, "Error").ToHandleChecked();
2292 if (Error->IsJSObject()) {
2293 Handle<String> name = factory->InternalizeOneByteString(
2294 STATIC_ASCII_VECTOR("stackTraceLimit"));
2295 Handle<Smi> stack_trace_limit(
2296 Smi::FromInt(FLAG_stack_trace_limit), isolate);
2297 RETURN_ON_EXCEPTION_VALUE(
2299 JSObject::SetLocalPropertyIgnoreAttributes(
2300 Handle<JSObject>::cast(Error), name, stack_trace_limit, NONE),
2304 // Expose the debug global object in global if a name for it is specified.
2305 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
2306 Debug* debug = isolate->debug();
2307 // If loading fails we just bail out without installing the
2308 // debugger but without tanking the whole context.
2309 if (!debug->Load()) return true;
2310 // Set the security token for the debugger context to the same as
2311 // the shell native context to allow calling between these (otherwise
2312 // exposing debug global object doesn't make much sense).
2313 debug->debug_context()->set_security_token(
2314 native_context->security_token());
2316 Handle<String> debug_string =
2317 factory->InternalizeUtf8String(FLAG_expose_debug_as);
2318 Handle<Object> global_proxy(
2319 debug->debug_context()->global_proxy(), isolate);
2320 RETURN_ON_EXCEPTION_VALUE(
2322 JSObject::SetLocalPropertyIgnoreAttributes(
2323 global, debug_string, global_proxy, DONT_ENUM),
2330 static uint32_t Hash(RegisteredExtension* extension) {
2331 return v8::internal::ComputePointerHash(extension);
2335 Genesis::ExtensionStates::ExtensionStates() : map_(HashMap::PointersMatch, 8) {}
2337 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2338 RegisteredExtension* extension) {
2339 i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension), false);
2340 if (entry == NULL) {
2343 return static_cast<ExtensionTraversalState>(
2344 reinterpret_cast<intptr_t>(entry->value));
2347 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2348 ExtensionTraversalState state) {
2349 map_.Lookup(extension, Hash(extension), true)->value =
2350 reinterpret_cast<void*>(static_cast<intptr_t>(state));
2354 bool Genesis::InstallExtensions(Handle<Context> native_context,
2355 v8::ExtensionConfiguration* extensions) {
2356 Isolate* isolate = native_context->GetIsolate();
2357 ExtensionStates extension_states; // All extensions have state UNVISITED.
2358 return InstallAutoExtensions(isolate, &extension_states) &&
2359 (!FLAG_expose_free_buffer ||
2360 InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
2362 InstallExtension(isolate, "v8/gc", &extension_states)) &&
2363 (!FLAG_expose_externalize_string ||
2364 InstallExtension(isolate, "v8/externalize", &extension_states)) &&
2365 (!FLAG_track_gc_object_stats ||
2366 InstallExtension(isolate, "v8/statistics", &extension_states)) &&
2367 (!FLAG_expose_trigger_failure ||
2368 InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
2369 InstallRequestedExtensions(isolate, extensions, &extension_states);
2373 bool Genesis::InstallAutoExtensions(Isolate* isolate,
2374 ExtensionStates* extension_states) {
2375 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2378 if (it->extension()->auto_enable() &&
2379 !InstallExtension(isolate, it, extension_states)) {
2387 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
2388 v8::ExtensionConfiguration* extensions,
2389 ExtensionStates* extension_states) {
2390 for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
2391 if (!InstallExtension(isolate, *it, extension_states)) return false;
2397 // Installs a named extension. This methods is unoptimized and does
2398 // not scale well if we want to support a large number of extensions.
2399 bool Genesis::InstallExtension(Isolate* isolate,
2401 ExtensionStates* extension_states) {
2402 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2405 if (strcmp(name, it->extension()->name()) == 0) {
2406 return InstallExtension(isolate, it, extension_states);
2409 return Utils::ApiCheck(false,
2410 "v8::Context::New()",
2411 "Cannot find required extension");
2415 bool Genesis::InstallExtension(Isolate* isolate,
2416 v8::RegisteredExtension* current,
2417 ExtensionStates* extension_states) {
2418 HandleScope scope(isolate);
2420 if (extension_states->get_state(current) == INSTALLED) return true;
2421 // The current node has already been visited so there must be a
2422 // cycle in the dependency graph; fail.
2423 if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
2424 "v8::Context::New()",
2425 "Circular extension dependency")) {
2428 ASSERT(extension_states->get_state(current) == UNVISITED);
2429 extension_states->set_state(current, VISITED);
2430 v8::Extension* extension = current->extension();
2431 // Install the extension's dependencies
2432 for (int i = 0; i < extension->dependency_count(); i++) {
2433 if (!InstallExtension(isolate,
2434 extension->dependencies()[i],
2435 extension_states)) {
2439 // We do not expect this to throw an exception. Change this if it does.
2440 Handle<String> source_code =
2441 isolate->factory()->NewExternalStringFromAscii(
2442 extension->source()).ToHandleChecked();
2443 bool result = CompileScriptCached(isolate,
2444 CStrVector(extension->name()),
2446 isolate->bootstrapper()->extensions_cache(),
2448 Handle<Context>(isolate->context()),
2450 ASSERT(isolate->has_pending_exception() != result);
2452 // We print out the name of the extension that fail to install.
2453 // When an error is thrown during bootstrapping we automatically print
2454 // the line number at which this happened to the console in the isolate
2455 // error throwing functionality.
2456 OS::PrintError("Error installing extension '%s'.\n",
2457 current->extension()->name());
2458 isolate->clear_pending_exception();
2460 extension_states->set_state(current, INSTALLED);
2461 isolate->NotifyExtensionInstalled();
2466 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2467 HandleScope scope(isolate());
2468 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2469 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2470 Handle<Object> function_object = Object::GetProperty(
2471 isolate(), builtins, Builtins::GetName(id)).ToHandleChecked();
2472 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2473 builtins->set_javascript_builtin(id, *function);
2474 if (!Compiler::EnsureCompiled(function, CLEAR_EXCEPTION)) {
2477 builtins->set_javascript_builtin_code(id, function->shared()->code());
2483 bool Genesis::ConfigureGlobalObjects(
2484 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
2485 Handle<JSObject> global_proxy(
2486 JSObject::cast(native_context()->global_proxy()));
2487 Handle<JSObject> inner_global(
2488 JSObject::cast(native_context()->global_object()));
2490 if (!global_proxy_template.IsEmpty()) {
2491 // Configure the global proxy object.
2492 Handle<ObjectTemplateInfo> proxy_data =
2493 v8::Utils::OpenHandle(*global_proxy_template);
2494 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
2496 // Configure the inner global object.
2497 Handle<FunctionTemplateInfo> proxy_constructor(
2498 FunctionTemplateInfo::cast(proxy_data->constructor()));
2499 if (!proxy_constructor->prototype_template()->IsUndefined()) {
2500 Handle<ObjectTemplateInfo> inner_data(
2501 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2502 if (!ConfigureApiObject(inner_global, inner_data)) return false;
2506 SetObjectPrototype(global_proxy, inner_global);
2508 native_context()->set_initial_array_prototype(
2509 JSArray::cast(native_context()->array_function()->prototype()));
2515 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
2516 Handle<ObjectTemplateInfo> object_template) {
2517 ASSERT(!object_template.is_null());
2518 ASSERT(FunctionTemplateInfo::cast(object_template->constructor())
2519 ->IsTemplateFor(object->map()));;
2521 MaybeHandle<JSObject> maybe_obj =
2522 Execution::InstantiateObject(object_template);
2523 Handle<JSObject> obj;
2524 if (!maybe_obj.ToHandle(&obj)) {
2525 ASSERT(isolate()->has_pending_exception());
2526 isolate()->clear_pending_exception();
2529 TransferObject(obj, object);
2534 void Genesis::TransferNamedProperties(Handle<JSObject> from,
2535 Handle<JSObject> to) {
2536 if (from->HasFastProperties()) {
2537 Handle<DescriptorArray> descs =
2538 Handle<DescriptorArray>(from->map()->instance_descriptors());
2539 for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
2540 PropertyDetails details = descs->GetDetails(i);
2541 switch (details.type()) {
2543 HandleScope inner(isolate());
2544 Handle<Name> key = Handle<Name>(descs->GetKey(i));
2545 int index = descs->GetFieldIndex(i);
2546 ASSERT(!descs->GetDetails(i).representation().IsDouble());
2547 Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
2549 JSObject::SetLocalPropertyIgnoreAttributes(
2550 to, key, value, details.attributes()).Check();
2554 HandleScope inner(isolate());
2555 Handle<Name> key = Handle<Name>(descs->GetKey(i));
2556 Handle<Object> constant(descs->GetConstant(i), isolate());
2557 JSObject::SetLocalPropertyIgnoreAttributes(
2558 to, key, constant, details.attributes()).Check();
2562 LookupResult result(isolate());
2563 Handle<Name> key(Name::cast(descs->GetKey(i)), isolate());
2564 to->LocalLookup(key, &result);
2565 // If the property is already there we skip it
2566 if (result.IsFound()) continue;
2567 HandleScope inner(isolate());
2568 ASSERT(!to->HasFastProperties());
2569 // Add to dictionary.
2570 Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
2571 PropertyDetails d = PropertyDetails(
2572 details.attributes(), CALLBACKS, i + 1);
2573 JSObject::SetNormalizedProperty(to, key, callbacks, d);
2577 // Do not occur since the from object has fast properties.
2581 // No element in instance descriptors have proxy or interceptor type.
2587 Handle<NameDictionary> properties =
2588 Handle<NameDictionary>(from->property_dictionary());
2589 int capacity = properties->Capacity();
2590 for (int i = 0; i < capacity; i++) {
2591 Object* raw_key(properties->KeyAt(i));
2592 if (properties->IsKey(raw_key)) {
2593 ASSERT(raw_key->IsName());
2594 // If the property is already there we skip it.
2595 LookupResult result(isolate());
2596 Handle<Name> key(Name::cast(raw_key));
2597 to->LocalLookup(key, &result);
2598 if (result.IsFound()) continue;
2599 // Set the property.
2600 Handle<Object> value = Handle<Object>(properties->ValueAt(i),
2602 ASSERT(!value->IsCell());
2603 if (value->IsPropertyCell()) {
2604 value = Handle<Object>(PropertyCell::cast(*value)->value(),
2607 PropertyDetails details = properties->DetailsAt(i);
2608 JSObject::SetLocalPropertyIgnoreAttributes(
2609 to, key, value, details.attributes()).Check();
2616 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
2617 Handle<JSObject> to) {
2618 // Cloning the elements array is sufficient.
2619 Handle<FixedArray> from_elements =
2620 Handle<FixedArray>(FixedArray::cast(from->elements()));
2621 Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
2622 to->set_elements(*to_elements);
2626 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
2627 HandleScope outer(isolate());
2629 ASSERT(!from->IsJSArray());
2630 ASSERT(!to->IsJSArray());
2632 TransferNamedProperties(from, to);
2633 TransferIndexedProperties(from, to);
2635 // Transfer the prototype (new map is needed).
2636 Handle<Map> old_to_map = Handle<Map>(to->map());
2637 Handle<Map> new_to_map = Map::Copy(old_to_map);
2638 new_to_map->set_prototype(from->map()->prototype());
2639 to->set_map(*new_to_map);
2643 void Genesis::MakeFunctionInstancePrototypeWritable() {
2644 // The maps with writable prototype are created in CreateEmptyFunction
2645 // and CreateStrictModeFunctionMaps respectively. Initially the maps are
2646 // created with read-only prototype for JS builtins processing.
2647 ASSERT(!sloppy_function_map_writable_prototype_.is_null());
2648 ASSERT(!strict_function_map_writable_prototype_.is_null());
2650 // Replace function instance maps to make prototype writable.
2651 native_context()->set_sloppy_function_map(
2652 *sloppy_function_map_writable_prototype_);
2653 native_context()->set_strict_function_map(
2654 *strict_function_map_writable_prototype_);
2658 class NoTrackDoubleFieldsForSerializerScope {
2660 explicit NoTrackDoubleFieldsForSerializerScope(Isolate* isolate)
2661 : isolate_(isolate), flag_(FLAG_track_double_fields) {
2662 if (Serializer::enabled(isolate)) {
2663 // Disable tracking double fields because heap numbers treated as
2664 // immutable by the serializer.
2665 FLAG_track_double_fields = false;
2669 ~NoTrackDoubleFieldsForSerializerScope() {
2670 if (Serializer::enabled(isolate_)) {
2671 FLAG_track_double_fields = flag_;
2681 Genesis::Genesis(Isolate* isolate,
2682 Handle<Object> global_object,
2683 v8::Handle<v8::ObjectTemplate> global_template,
2684 v8::ExtensionConfiguration* extensions)
2685 : isolate_(isolate),
2686 active_(isolate->bootstrapper()) {
2687 NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
2688 result_ = Handle<Context>::null();
2689 // If V8 cannot be initialized, just return.
2690 if (!V8::Initialize(NULL)) return;
2692 // Before creating the roots we must save the context and restore it
2693 // on all function exits.
2694 SaveContext saved_context(isolate);
2696 // During genesis, the boilerplate for stack overflow won't work until the
2697 // environment has been at least partially initialized. Add a stack check
2698 // before entering JS code to catch overflow early.
2699 StackLimitCheck check(isolate);
2700 if (check.HasOverflowed()) return;
2702 // We can only de-serialize a context if the isolate was initialized from
2703 // a snapshot. Otherwise we have to build the context from scratch.
2704 if (isolate->initialized_from_snapshot()) {
2705 native_context_ = Snapshot::NewContextFromSnapshot(isolate);
2707 native_context_ = Handle<Context>();
2710 if (!native_context().is_null()) {
2711 AddToWeakNativeContextList(*native_context());
2712 isolate->set_context(*native_context());
2713 isolate->counters()->contexts_created_by_snapshot()->Increment();
2714 Handle<GlobalObject> inner_global;
2715 Handle<JSGlobalProxy> global_proxy =
2716 CreateNewGlobals(global_template,
2720 HookUpGlobalProxy(inner_global, global_proxy);
2721 HookUpInnerGlobal(inner_global);
2722 native_context()->builtins()->set_global_receiver(
2723 native_context()->global_proxy());
2725 if (!ConfigureGlobalObjects(global_template)) return;
2727 // We get here if there was no context snapshot.
2729 Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
2730 CreateStrictModeFunctionMaps(empty_function);
2731 Handle<GlobalObject> inner_global;
2732 Handle<JSGlobalProxy> global_proxy =
2733 CreateNewGlobals(global_template, global_object, &inner_global);
2734 HookUpGlobalProxy(inner_global, global_proxy);
2735 InitializeGlobal(inner_global, empty_function);
2736 InstallJSFunctionResultCaches();
2737 InitializeNormalizedMapCaches();
2738 if (!InstallNatives()) return;
2740 MakeFunctionInstancePrototypeWritable();
2742 if (!ConfigureGlobalObjects(global_template)) return;
2743 isolate->counters()->contexts_created_from_scratch()->Increment();
2746 // Initialize experimental globals and install experimental natives.
2747 InitializeExperimentalGlobal();
2748 if (!InstallExperimentalNatives()) return;
2750 // We can't (de-)serialize typed arrays currently, but we are lucky: The state
2751 // of the random number generator needs no initialization during snapshot
2752 // creation time and we don't need trigonometric functions then.
2753 if (!Serializer::enabled(isolate)) {
2754 // Initially seed the per-context random number generator using the
2755 // per-isolate random number generator.
2756 const int num_elems = 2;
2757 const int num_bytes = num_elems * sizeof(uint32_t);
2758 uint32_t* state = reinterpret_cast<uint32_t*>(malloc(num_bytes));
2761 isolate->random_number_generator()->NextBytes(state, num_bytes);
2762 } while (state[0] == 0 || state[1] == 0);
2764 v8::Local<v8::ArrayBuffer> buffer = v8::ArrayBuffer::New(
2765 reinterpret_cast<v8::Isolate*>(isolate), state, num_bytes);
2766 Utils::OpenHandle(*buffer)->set_should_be_freed(true);
2767 v8::Local<v8::Uint32Array> ta = v8::Uint32Array::New(buffer, 0, num_elems);
2768 Handle<JSBuiltinsObject> builtins(native_context()->builtins());
2769 Runtime::ForceSetObjectProperty(builtins,
2770 factory()->InternalizeOneByteString(
2771 STATIC_ASCII_VECTOR("rngstate")),
2772 Utils::OpenHandle(*ta),
2775 // Initialize trigonometric lookup tables and constants.
2776 const int table_num_bytes = TrigonometricLookupTable::table_num_bytes();
2777 v8::Local<v8::ArrayBuffer> sin_buffer = v8::ArrayBuffer::New(
2778 reinterpret_cast<v8::Isolate*>(isolate),
2779 TrigonometricLookupTable::sin_table(), table_num_bytes);
2780 v8::Local<v8::ArrayBuffer> cos_buffer = v8::ArrayBuffer::New(
2781 reinterpret_cast<v8::Isolate*>(isolate),
2782 TrigonometricLookupTable::cos_x_interval_table(), table_num_bytes);
2783 v8::Local<v8::Float64Array> sin_table = v8::Float64Array::New(
2784 sin_buffer, 0, TrigonometricLookupTable::table_size());
2785 v8::Local<v8::Float64Array> cos_table = v8::Float64Array::New(
2786 cos_buffer, 0, TrigonometricLookupTable::table_size());
2788 Runtime::ForceSetObjectProperty(builtins,
2789 factory()->InternalizeOneByteString(
2790 STATIC_ASCII_VECTOR("kSinTable")),
2791 Utils::OpenHandle(*sin_table),
2793 Runtime::ForceSetObjectProperty(
2795 factory()->InternalizeOneByteString(
2796 STATIC_ASCII_VECTOR("kCosXIntervalTable")),
2797 Utils::OpenHandle(*cos_table),
2799 Runtime::ForceSetObjectProperty(
2801 factory()->InternalizeOneByteString(
2802 STATIC_ASCII_VECTOR("kSamples")),
2803 factory()->NewHeapNumber(
2804 TrigonometricLookupTable::samples()),
2806 Runtime::ForceSetObjectProperty(
2808 factory()->InternalizeOneByteString(
2809 STATIC_ASCII_VECTOR("kIndexConvert")),
2810 factory()->NewHeapNumber(
2811 TrigonometricLookupTable::samples_over_pi_half()),
2815 result_ = native_context();
2819 // Support for thread preemption.
2821 // Reserve space for statics needing saving and restoring.
2822 int Bootstrapper::ArchiveSpacePerThread() {
2823 return sizeof(NestingCounterType);
2827 // Archive statics that are thread local.
2828 char* Bootstrapper::ArchiveState(char* to) {
2829 *reinterpret_cast<NestingCounterType*>(to) = nesting_;
2831 return to + sizeof(NestingCounterType);
2835 // Restore statics that are thread local.
2836 char* Bootstrapper::RestoreState(char* from) {
2837 nesting_ = *reinterpret_cast<NestingCounterType*>(from);
2838 return from + sizeof(NestingCounterType);
2842 // Called when the top-level V8 mutex is destroyed.
2843 void Bootstrapper::FreeThreadResources() {
2844 ASSERT(!IsActive());
2847 } } // namespace v8::internal