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