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/api-natives.h"
9 #include "src/base/utils/random-number-generator.h"
10 #include "src/code-stubs.h"
11 #include "src/extensions/externalize-string-extension.h"
12 #include "src/extensions/free-buffer-extension.h"
13 #include "src/extensions/gc-extension.h"
14 #include "src/extensions/statistics-extension.h"
15 #include "src/extensions/trigger-failure-extension.h"
16 #include "src/snapshot/natives.h"
17 #include "src/snapshot/snapshot.h"
18 #include "third_party/fdlibm/fdlibm.h"
23 Bootstrapper::Bootstrapper(Isolate* isolate)
26 extensions_cache_(Script::TYPE_EXTENSION) {}
29 template <class Source>
30 inline FixedArray* GetCache(Heap* heap);
34 FixedArray* GetCache<Natives>(Heap* heap) {
35 return heap->natives_source_cache();
40 FixedArray* GetCache<ExperimentalNatives>(Heap* heap) {
41 return heap->experimental_natives_source_cache();
46 FixedArray* GetCache<ExtraNatives>(Heap* heap) {
47 return heap->extra_natives_source_cache();
52 FixedArray* GetCache<CodeStubNatives>(Heap* heap) {
53 return heap->code_stub_natives_source_cache();
57 template <class Source>
58 Handle<String> Bootstrapper::SourceLookup(int index) {
59 DCHECK(0 <= index && index < Source::GetBuiltinsCount());
60 Heap* heap = isolate_->heap();
61 if (GetCache<Source>(heap)->get(index)->IsUndefined()) {
62 // We can use external strings for the natives.
63 Vector<const char> source = Source::GetScriptSource(index);
64 NativesExternalStringResource* resource =
65 new NativesExternalStringResource(source.start(), source.length());
66 // We do not expect this to throw an exception. Change this if it does.
67 Handle<String> source_code = isolate_->factory()
68 ->NewExternalStringFromOneByte(resource)
70 // Mark this external string with a special map.
71 source_code->set_map(isolate_->heap()->native_source_string_map());
72 GetCache<Source>(heap)->set(index, *source_code);
74 Handle<Object> cached_source(GetCache<Source>(heap)->get(index), isolate_);
75 return Handle<String>::cast(cached_source);
79 template Handle<String> Bootstrapper::SourceLookup<Natives>(int index);
80 template Handle<String> Bootstrapper::SourceLookup<ExperimentalNatives>(
82 template Handle<String> Bootstrapper::SourceLookup<ExtraNatives>(int index);
83 template Handle<String> Bootstrapper::SourceLookup<CodeStubNatives>(int index);
86 void Bootstrapper::Initialize(bool create_heap_objects) {
87 extensions_cache_.Initialize(isolate_, create_heap_objects);
91 static const char* GCFunctionName() {
92 bool flag_given = FLAG_expose_gc_as != NULL && strlen(FLAG_expose_gc_as) != 0;
93 return flag_given ? FLAG_expose_gc_as : "gc";
97 v8::Extension* Bootstrapper::free_buffer_extension_ = NULL;
98 v8::Extension* Bootstrapper::gc_extension_ = NULL;
99 v8::Extension* Bootstrapper::externalize_string_extension_ = NULL;
100 v8::Extension* Bootstrapper::statistics_extension_ = NULL;
101 v8::Extension* Bootstrapper::trigger_failure_extension_ = NULL;
104 void Bootstrapper::InitializeOncePerProcess() {
105 free_buffer_extension_ = new FreeBufferExtension;
106 v8::RegisterExtension(free_buffer_extension_);
107 gc_extension_ = new GCExtension(GCFunctionName());
108 v8::RegisterExtension(gc_extension_);
109 externalize_string_extension_ = new ExternalizeStringExtension;
110 v8::RegisterExtension(externalize_string_extension_);
111 statistics_extension_ = new StatisticsExtension;
112 v8::RegisterExtension(statistics_extension_);
113 trigger_failure_extension_ = new TriggerFailureExtension;
114 v8::RegisterExtension(trigger_failure_extension_);
118 void Bootstrapper::TearDownExtensions() {
119 delete free_buffer_extension_;
120 free_buffer_extension_ = NULL;
121 delete gc_extension_;
122 gc_extension_ = NULL;
123 delete externalize_string_extension_;
124 externalize_string_extension_ = NULL;
125 delete statistics_extension_;
126 statistics_extension_ = NULL;
127 delete trigger_failure_extension_;
128 trigger_failure_extension_ = NULL;
132 void DeleteNativeSources(Object* maybe_array) {
133 if (maybe_array->IsFixedArray()) {
134 FixedArray* array = FixedArray::cast(maybe_array);
135 for (int i = 0; i < array->length(); i++) {
136 Object* natives_source = array->get(i);
137 if (!natives_source->IsUndefined()) {
138 const NativesExternalStringResource* resource =
139 reinterpret_cast<const NativesExternalStringResource*>(
140 ExternalOneByteString::cast(natives_source)->resource());
148 void Bootstrapper::TearDown() {
149 DeleteNativeSources(isolate_->heap()->natives_source_cache());
150 DeleteNativeSources(isolate_->heap()->experimental_natives_source_cache());
151 DeleteNativeSources(isolate_->heap()->extra_natives_source_cache());
152 DeleteNativeSources(isolate_->heap()->code_stub_natives_source_cache());
153 extensions_cache_.Initialize(isolate_, false); // Yes, symmetrical
157 class Genesis BASE_EMBEDDED {
159 Genesis(Isolate* isolate, MaybeHandle<JSGlobalProxy> maybe_global_proxy,
160 v8::Local<v8::ObjectTemplate> global_proxy_template,
161 v8::ExtensionConfiguration* extensions, ContextType context_type);
164 Isolate* isolate() const { return isolate_; }
165 Factory* factory() const { return isolate_->factory(); }
166 Heap* heap() const { return isolate_->heap(); }
168 Handle<Context> result() { return result_; }
171 Handle<Context> native_context() { return native_context_; }
173 // Creates some basic objects. Used for creating a context from scratch.
175 // Creates the empty function. Used for creating a context from scratch.
176 Handle<JSFunction> CreateEmptyFunction(Isolate* isolate);
177 // Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
178 Handle<JSFunction> GetRestrictedFunctionPropertiesThrower();
179 Handle<JSFunction> GetStrictArgumentsPoisonFunction();
180 Handle<JSFunction> GetThrowTypeErrorIntrinsic(Builtins::Name builtin_name);
182 void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
183 void CreateStrongModeFunctionMaps(Handle<JSFunction> empty);
185 // Make the "arguments" and "caller" properties throw a TypeError on access.
186 void AddRestrictedFunctionProperties(Handle<Map> map);
188 // Creates the global objects using the global proxy and the template passed
189 // in through the API. We call this regardless of whether we are building a
190 // context from scratch or using a deserialized one from the partial snapshot
191 // but in the latter case we don't use the objects it produces directly, as
192 // we have to used the deserialized ones that are linked together with the
193 // rest of the context snapshot.
194 Handle<GlobalObject> CreateNewGlobals(
195 v8::Local<v8::ObjectTemplate> global_proxy_template,
196 Handle<JSGlobalProxy> global_proxy);
197 // Hooks the given global proxy into the context. If the context was created
198 // by deserialization then this will unhook the global proxy that was
199 // deserialized, leaving the GC to pick it up.
200 void HookUpGlobalProxy(Handle<GlobalObject> global_object,
201 Handle<JSGlobalProxy> global_proxy);
202 // Similarly, we want to use the global that has been created by the templates
203 // passed through the API. The global from the snapshot is detached from the
204 // other objects in the snapshot.
205 void HookUpGlobalObject(Handle<GlobalObject> global_object,
206 Handle<FixedArray> outdated_contexts);
207 // The native context has a ScriptContextTable that store declarative bindings
208 // made in script scopes. Add a "this" binding to that table pointing to the
210 void InstallGlobalThisBinding();
211 void HookUpGlobalThisBinding(Handle<FixedArray> outdated_contexts);
212 // New context initialization. Used for creating a context from scratch.
213 void InitializeGlobal(Handle<GlobalObject> global_object,
214 Handle<JSFunction> empty_function,
215 ContextType context_type);
216 void InitializeExperimentalGlobal();
217 // Installs the contents of the native .js files on the global objects.
218 // Used for creating a context from scratch.
219 void InstallNativeFunctions();
220 void InstallExperimentalNativeFunctions();
221 // Typed arrays are not serializable and have to initialized afterwards.
222 void InitializeBuiltinTypedArrays();
224 #define DECLARE_FEATURE_INITIALIZATION(id, descr) \
225 void InstallNativeFunctions_##id(); \
226 void InitializeGlobal_##id();
228 HARMONY_INPROGRESS(DECLARE_FEATURE_INITIALIZATION)
229 HARMONY_STAGED(DECLARE_FEATURE_INITIALIZATION)
230 HARMONY_SHIPPING(DECLARE_FEATURE_INITIALIZATION)
231 #undef DECLARE_FEATURE_INITIALIZATION
233 Handle<JSFunction> InstallInternalArray(Handle<JSObject> target,
235 ElementsKind elements_kind);
236 bool InstallNatives(ContextType context_type);
238 void InstallTypedArray(const char* name, ElementsKind elements_kind,
239 Handle<JSFunction>* fun);
240 bool InstallExperimentalNatives();
241 bool InstallExtraNatives();
242 void InstallBuiltinFunctionIds();
243 void InstallExperimentalBuiltinFunctionIds();
244 void InstallJSFunctionResultCaches();
245 void InitializeNormalizedMapCaches();
247 enum ExtensionTraversalState {
248 UNVISITED, VISITED, INSTALLED
251 class ExtensionStates {
254 ExtensionTraversalState get_state(RegisteredExtension* extension);
255 void set_state(RegisteredExtension* extension,
256 ExtensionTraversalState state);
259 DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
262 // Used both for deserialized and from-scratch contexts to add the extensions
264 static bool InstallExtensions(Handle<Context> native_context,
265 v8::ExtensionConfiguration* extensions);
266 static bool InstallAutoExtensions(Isolate* isolate,
267 ExtensionStates* extension_states);
268 static bool InstallRequestedExtensions(Isolate* isolate,
269 v8::ExtensionConfiguration* extensions,
270 ExtensionStates* extension_states);
271 static bool InstallExtension(Isolate* isolate,
273 ExtensionStates* extension_states);
274 static bool InstallExtension(Isolate* isolate,
275 v8::RegisteredExtension* current,
276 ExtensionStates* extension_states);
277 static bool InstallSpecialObjects(Handle<Context> native_context);
278 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
279 bool ConfigureApiObject(Handle<JSObject> object,
280 Handle<ObjectTemplateInfo> object_template);
281 bool ConfigureGlobalObjects(
282 v8::Local<v8::ObjectTemplate> global_proxy_template);
284 // Migrates all properties from the 'from' object to the 'to'
285 // object and overrides the prototype in 'to' with the one from
287 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
288 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
289 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
293 FUNCTION_WITH_WRITEABLE_PROTOTYPE,
294 FUNCTION_WITH_READONLY_PROTOTYPE,
295 // Without prototype.
296 FUNCTION_WITHOUT_PROTOTYPE,
300 static bool IsFunctionModeWithPrototype(FunctionMode function_mode) {
301 return (function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ||
302 function_mode == FUNCTION_WITH_READONLY_PROTOTYPE);
305 Handle<Map> CreateSloppyFunctionMap(FunctionMode function_mode);
307 void SetFunctionInstanceDescriptor(Handle<Map> map,
308 FunctionMode function_mode);
309 void MakeFunctionInstancePrototypeWritable();
311 Handle<Map> CreateStrictFunctionMap(FunctionMode function_mode,
312 Handle<JSFunction> empty_function);
313 Handle<Map> CreateStrongFunctionMap(Handle<JSFunction> empty_function,
314 bool is_constructor);
317 void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
318 FunctionMode function_mode);
319 void SetStrongFunctionInstanceDescriptor(Handle<Map> map);
321 static bool CompileBuiltin(Isolate* isolate, int index);
322 static bool CompileExperimentalBuiltin(Isolate* isolate, int index);
323 static bool CompileExtraBuiltin(Isolate* isolate, int index);
324 static bool CompileNative(Isolate* isolate, Vector<const char> name,
325 Handle<String> source, int argc,
326 Handle<Object> argv[]);
328 static bool CallUtilsFunction(Isolate* isolate, const char* name);
330 static bool CompileExtension(Isolate* isolate, v8::Extension* extension);
333 Handle<Context> result_;
334 Handle<Context> native_context_;
336 // Function maps. Function maps are created initially with a read only
337 // prototype for the processing of JS builtins. Later the function maps are
338 // replaced in order to make prototype writable. These are the final, writable
340 Handle<Map> sloppy_function_map_writable_prototype_;
341 Handle<Map> strict_function_map_writable_prototype_;
342 Handle<JSFunction> strict_poison_function_;
343 Handle<JSFunction> restricted_function_properties_thrower_;
345 BootstrapperActive active_;
346 friend class Bootstrapper;
350 void Bootstrapper::Iterate(ObjectVisitor* v) {
351 extensions_cache_.Iterate(v);
352 v->Synchronize(VisitorSynchronization::kExtensions);
356 Handle<Context> Bootstrapper::CreateEnvironment(
357 MaybeHandle<JSGlobalProxy> maybe_global_proxy,
358 v8::Local<v8::ObjectTemplate> global_proxy_template,
359 v8::ExtensionConfiguration* extensions, ContextType context_type) {
360 HandleScope scope(isolate_);
361 Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template,
362 extensions, context_type);
363 Handle<Context> env = genesis.result();
365 (context_type == FULL_CONTEXT && !InstallExtensions(env, extensions))) {
366 return Handle<Context>();
368 return scope.CloseAndEscape(env);
372 bool Bootstrapper::CreateCodeStubContext(Isolate* isolate) {
373 HandleScope scope(isolate);
374 SaveContext save_context(isolate);
375 BootstrapperActive active(this);
377 v8::ExtensionConfiguration no_extensions;
378 Handle<Context> native_context = CreateEnvironment(
379 MaybeHandle<JSGlobalProxy>(), v8::Local<v8::ObjectTemplate>(),
380 &no_extensions, THIN_CONTEXT);
381 isolate->heap()->set_code_stub_context(*native_context);
382 isolate->set_context(*native_context);
383 Handle<JSObject> code_stub_exports =
384 isolate->factory()->NewJSObject(isolate->object_function());
385 JSObject::NormalizeProperties(code_stub_exports, CLEAR_INOBJECT_PROPERTIES, 2,
386 "container to export to extra natives");
387 isolate->heap()->set_code_stub_exports_object(*code_stub_exports);
388 return InstallCodeStubNatives(isolate);
392 static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
393 // object.__proto__ = proto;
394 Handle<Map> old_map = Handle<Map>(object->map());
395 Handle<Map> new_map = Map::Copy(old_map, "SetObjectPrototype");
396 Map::SetPrototype(new_map, proto, FAST_PROTOTYPE);
397 JSObject::MigrateToMap(object, new_map);
401 void Bootstrapper::DetachGlobal(Handle<Context> env) {
402 Factory* factory = env->GetIsolate()->factory();
403 Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
404 global_proxy->set_native_context(*factory->null_value());
405 SetObjectPrototype(global_proxy, factory->null_value());
406 global_proxy->map()->SetConstructor(*factory->null_value());
407 if (FLAG_track_detached_contexts) {
408 env->GetIsolate()->AddDetachedContext(env);
413 static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
414 const char* name, InstanceType type,
416 MaybeHandle<JSObject> maybe_prototype,
418 bool strict_function_map = false) {
419 Isolate* isolate = target->GetIsolate();
420 Factory* factory = isolate->factory();
421 Handle<String> internalized_name = factory->InternalizeUtf8String(name);
422 Handle<Code> call_code = Handle<Code>(isolate->builtins()->builtin(call));
423 Handle<JSObject> prototype;
424 static const bool kReadOnlyPrototype = false;
425 static const bool kInstallConstructor = false;
426 Handle<JSFunction> function =
427 maybe_prototype.ToHandle(&prototype)
428 ? factory->NewFunction(internalized_name, call_code, prototype, type,
429 instance_size, kReadOnlyPrototype,
430 kInstallConstructor, strict_function_map)
431 : factory->NewFunctionWithoutPrototype(internalized_name, call_code,
432 strict_function_map);
433 PropertyAttributes attributes;
434 if (target->IsJSBuiltinsObject()) {
436 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
438 attributes = DONT_ENUM;
440 JSObject::AddProperty(target, internalized_name, function, attributes);
441 if (target->IsJSGlobalObject()) {
442 function->shared()->set_instance_class_name(*internalized_name);
444 function->shared()->set_native(true);
449 void Genesis::SetFunctionInstanceDescriptor(Handle<Map> map,
450 FunctionMode function_mode) {
451 int size = IsFunctionModeWithPrototype(function_mode) ? 5 : 4;
452 Map::EnsureDescriptorSlack(map, size);
454 PropertyAttributes ro_attribs =
455 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
456 PropertyAttributes roc_attribs =
457 static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
459 Handle<AccessorInfo> length =
460 Accessors::FunctionLengthInfo(isolate(), roc_attribs);
462 AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
463 length, roc_attribs);
464 map->AppendDescriptor(&d);
466 Handle<AccessorInfo> name =
467 Accessors::FunctionNameInfo(isolate(), ro_attribs);
469 AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
471 map->AppendDescriptor(&d);
473 Handle<AccessorInfo> args =
474 Accessors::FunctionArgumentsInfo(isolate(), ro_attribs);
476 AccessorConstantDescriptor d(Handle<Name>(Name::cast(args->name())), args,
478 map->AppendDescriptor(&d);
480 Handle<AccessorInfo> caller =
481 Accessors::FunctionCallerInfo(isolate(), ro_attribs);
483 AccessorConstantDescriptor d(Handle<Name>(Name::cast(caller->name())),
485 map->AppendDescriptor(&d);
487 if (IsFunctionModeWithPrototype(function_mode)) {
488 if (function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE) {
489 ro_attribs = static_cast<PropertyAttributes>(ro_attribs & ~READ_ONLY);
491 Handle<AccessorInfo> prototype =
492 Accessors::FunctionPrototypeInfo(isolate(), ro_attribs);
493 AccessorConstantDescriptor d(Handle<Name>(Name::cast(prototype->name())),
494 prototype, ro_attribs);
495 map->AppendDescriptor(&d);
500 Handle<Map> Genesis::CreateSloppyFunctionMap(FunctionMode function_mode) {
501 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
502 SetFunctionInstanceDescriptor(map, function_mode);
503 map->set_function_with_prototype(IsFunctionModeWithPrototype(function_mode));
508 Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
509 // Allocate the map for function instances. Maps are allocated first and their
510 // prototypes patched later, once empty function is created.
512 // Functions with this map will not have a 'prototype' property, and
513 // can not be used as constructors.
514 Handle<Map> function_without_prototype_map =
515 CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
516 native_context()->set_sloppy_function_without_prototype_map(
517 *function_without_prototype_map);
519 // Allocate the function map. This map is temporary, used only for processing
521 // Later the map is replaced with writable prototype map, allocated below.
522 Handle<Map> function_map =
523 CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE);
524 native_context()->set_sloppy_function_map(*function_map);
525 native_context()->set_sloppy_function_with_readonly_prototype_map(
528 // The final map for functions. Writeable prototype.
529 // This map is installed in MakeFunctionInstancePrototypeWritable.
530 sloppy_function_map_writable_prototype_ =
531 CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE);
532 Factory* factory = isolate->factory();
534 Handle<String> object_name = factory->Object_string();
536 Handle<JSObject> object_function_prototype;
538 { // --- O b j e c t ---
539 Handle<JSFunction> object_fun = factory->NewFunction(object_name);
540 int unused = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
541 int instance_size = JSObject::kHeaderSize + kPointerSize * unused;
542 Handle<Map> object_function_map =
543 factory->NewMap(JS_OBJECT_TYPE, instance_size);
544 object_function_map->set_inobject_properties(unused);
545 JSFunction::SetInitialMap(object_fun, object_function_map,
546 isolate->factory()->null_value());
547 object_function_map->set_unused_property_fields(unused);
549 native_context()->set_object_function(*object_fun);
551 // Allocate a new prototype for the object function.
552 object_function_prototype =
553 factory->NewJSObject(isolate->object_function(), TENURED);
554 Handle<Map> map = Map::Copy(handle(object_function_prototype->map()),
555 "EmptyObjectPrototype");
556 map->set_is_prototype_map(true);
557 object_function_prototype->set_map(*map);
559 native_context()->set_initial_object_prototype(*object_function_prototype);
560 // For bootstrapping set the array prototype to be the same as the object
561 // prototype, otherwise the missing initial_array_prototype will cause
562 // assertions during startup.
563 native_context()->set_initial_array_prototype(*object_function_prototype);
564 Accessors::FunctionSetPrototype(object_fun, object_function_prototype)
567 // Allocate initial strong object map.
568 Handle<Map> strong_object_map =
569 Map::Copy(Handle<Map>(object_fun->initial_map()), "EmptyStrongObject");
570 strong_object_map->set_is_strong();
571 native_context()->set_js_object_strong_map(*strong_object_map);
574 // Allocate the empty function as the prototype for function - ES6 19.2.3
575 Handle<Code> code(isolate->builtins()->builtin(Builtins::kEmptyFunction));
576 Handle<JSFunction> empty_function =
577 factory->NewFunctionWithoutPrototype(factory->empty_string(), code);
579 // Allocate the function map first and then patch the prototype later
580 Handle<Map> empty_function_map =
581 CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
582 DCHECK(!empty_function_map->is_dictionary_map());
583 Map::SetPrototype(empty_function_map, object_function_prototype);
584 empty_function_map->set_is_prototype_map(true);
586 empty_function->set_map(*empty_function_map);
589 Handle<String> source = factory->NewStringFromStaticChars("() {}");
590 Handle<Script> script = factory->NewScript(source);
591 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
592 empty_function->shared()->set_start_position(0);
593 empty_function->shared()->set_end_position(source->length());
594 empty_function->shared()->DontAdaptArguments();
595 SharedFunctionInfo::SetScript(handle(empty_function->shared()), script);
597 // Set prototypes for the function maps.
598 Handle<Map> sloppy_function_map(native_context()->sloppy_function_map(),
600 Handle<Map> sloppy_function_without_prototype_map(
601 native_context()->sloppy_function_without_prototype_map(), isolate);
602 Map::SetPrototype(sloppy_function_map, empty_function);
603 Map::SetPrototype(sloppy_function_without_prototype_map, empty_function);
604 Map::SetPrototype(sloppy_function_map_writable_prototype_, empty_function);
606 // ES6 draft 03-17-2015, section 8.2.2 step 12
607 AddRestrictedFunctionProperties(empty_function_map);
609 return empty_function;
613 void Genesis::SetStrictFunctionInstanceDescriptor(Handle<Map> map,
614 FunctionMode function_mode) {
615 int size = IsFunctionModeWithPrototype(function_mode) ? 5 : 4;
616 Map::EnsureDescriptorSlack(map, size);
618 PropertyAttributes rw_attribs =
619 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
620 PropertyAttributes ro_attribs =
621 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
622 PropertyAttributes roc_attribs =
623 static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
625 if (function_mode == BOUND_FUNCTION) {
627 Handle<String> length_string = isolate()->factory()->length_string();
628 DataDescriptor d(length_string, 0, roc_attribs, Representation::Tagged());
629 map->AppendDescriptor(&d);
632 Handle<String> name_string = isolate()->factory()->name_string();
633 DataDescriptor d(name_string, 1, roc_attribs, Representation::Tagged());
634 map->AppendDescriptor(&d);
637 DCHECK(function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ||
638 function_mode == FUNCTION_WITH_READONLY_PROTOTYPE ||
639 function_mode == FUNCTION_WITHOUT_PROTOTYPE);
641 Handle<AccessorInfo> length =
642 Accessors::FunctionLengthInfo(isolate(), roc_attribs);
643 AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
644 length, roc_attribs);
645 map->AppendDescriptor(&d);
648 Handle<AccessorInfo> name =
649 Accessors::FunctionNameInfo(isolate(), roc_attribs);
650 AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
652 map->AppendDescriptor(&d);
655 if (IsFunctionModeWithPrototype(function_mode)) {
657 PropertyAttributes attribs =
658 function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ? rw_attribs
660 Handle<AccessorInfo> prototype =
661 Accessors::FunctionPrototypeInfo(isolate(), attribs);
662 AccessorConstantDescriptor d(Handle<Name>(Name::cast(prototype->name())),
664 map->AppendDescriptor(&d);
669 void Genesis::SetStrongFunctionInstanceDescriptor(Handle<Map> map) {
670 Map::EnsureDescriptorSlack(map, 2);
672 PropertyAttributes ro_attribs =
673 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
675 Handle<AccessorInfo> length =
676 Accessors::FunctionLengthInfo(isolate(), ro_attribs);
678 AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
680 map->AppendDescriptor(&d);
682 Handle<AccessorInfo> name =
683 Accessors::FunctionNameInfo(isolate(), ro_attribs);
685 AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
687 map->AppendDescriptor(&d);
692 // Creates the %ThrowTypeError% function.
693 Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic(
694 Builtins::Name builtin_name) {
695 Handle<String> name =
696 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("ThrowTypeError"));
697 Handle<Code> code(isolate()->builtins()->builtin(builtin_name));
698 Handle<JSFunction> function =
699 factory()->NewFunctionWithoutPrototype(name, code);
700 function->set_map(native_context()->sloppy_function_map());
701 function->shared()->DontAdaptArguments();
703 // %ThrowTypeError% must not have a name property.
704 JSReceiver::DeleteProperty(function, factory()->name_string()).Assert();
706 // length needs to be non configurable.
707 Handle<Object> value(Smi::FromInt(function->shared()->length()), isolate());
708 JSObject::SetOwnPropertyIgnoreAttributes(
709 function, factory()->length_string(), value,
710 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
713 JSObject::PreventExtensions(function).Assert();
719 // ECMAScript 5th Edition, 13.2.3
720 Handle<JSFunction> Genesis::GetRestrictedFunctionPropertiesThrower() {
721 if (restricted_function_properties_thrower_.is_null()) {
722 restricted_function_properties_thrower_ = GetThrowTypeErrorIntrinsic(
723 Builtins::kRestrictedFunctionPropertiesThrower);
725 return restricted_function_properties_thrower_;
729 Handle<JSFunction> Genesis::GetStrictArgumentsPoisonFunction() {
730 if (strict_poison_function_.is_null()) {
731 strict_poison_function_ = GetThrowTypeErrorIntrinsic(
732 Builtins::kRestrictedStrictArgumentsPropertiesThrower);
734 return strict_poison_function_;
738 Handle<Map> Genesis::CreateStrictFunctionMap(
739 FunctionMode function_mode, Handle<JSFunction> empty_function) {
740 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
741 SetStrictFunctionInstanceDescriptor(map, function_mode);
742 map->set_function_with_prototype(IsFunctionModeWithPrototype(function_mode));
743 Map::SetPrototype(map, empty_function);
748 Handle<Map> Genesis::CreateStrongFunctionMap(
749 Handle<JSFunction> empty_function, bool is_constructor) {
750 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
751 SetStrongFunctionInstanceDescriptor(map);
752 map->set_function_with_prototype(is_constructor);
753 Map::SetPrototype(map, empty_function);
754 map->set_is_extensible(is_constructor);
755 map->set_is_strong();
760 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
761 // Allocate map for the prototype-less strict mode instances.
762 Handle<Map> strict_function_without_prototype_map =
763 CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
764 native_context()->set_strict_function_without_prototype_map(
765 *strict_function_without_prototype_map);
767 // Allocate map for the strict mode functions. This map is temporary, used
768 // only for processing of builtins.
769 // Later the map is replaced with writable prototype map, allocated below.
770 Handle<Map> strict_function_map =
771 CreateStrictFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
772 native_context()->set_strict_function_map(*strict_function_map);
774 // The final map for the strict mode functions. Writeable prototype.
775 // This map is installed in MakeFunctionInstancePrototypeWritable.
776 strict_function_map_writable_prototype_ =
777 CreateStrictFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE, empty);
779 // Special map for bound functions.
780 Handle<Map> bound_function_map =
781 CreateStrictFunctionMap(BOUND_FUNCTION, empty);
782 native_context()->set_bound_function_map(*bound_function_map);
786 void Genesis::CreateStrongModeFunctionMaps(Handle<JSFunction> empty) {
787 // Allocate map for strong mode instances, which never have prototypes.
788 Handle<Map> strong_function_map = CreateStrongFunctionMap(empty, false);
789 native_context()->set_strong_function_map(*strong_function_map);
790 // Constructors do, though.
791 Handle<Map> strong_constructor_map = CreateStrongFunctionMap(empty, true);
792 native_context()->set_strong_constructor_map(*strong_constructor_map);
796 static void ReplaceAccessors(Handle<Map> map,
798 PropertyAttributes attributes,
799 Handle<AccessorPair> accessor_pair) {
800 DescriptorArray* descriptors = map->instance_descriptors();
801 int idx = descriptors->SearchWithCache(*name, *map);
802 AccessorConstantDescriptor descriptor(name, accessor_pair, attributes);
803 descriptors->Replace(idx, &descriptor);
807 void Genesis::AddRestrictedFunctionProperties(Handle<Map> map) {
808 PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
809 Handle<JSFunction> thrower = GetRestrictedFunctionPropertiesThrower();
810 Handle<AccessorPair> accessors = factory()->NewAccessorPair();
811 accessors->set_getter(*thrower);
812 accessors->set_setter(*thrower);
814 ReplaceAccessors(map, factory()->arguments_string(), rw_attribs, accessors);
815 ReplaceAccessors(map, factory()->caller_string(), rw_attribs, accessors);
819 static void AddToWeakNativeContextList(Context* context) {
820 DCHECK(context->IsNativeContext());
821 Heap* heap = context->GetIsolate()->heap();
824 DCHECK(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
825 // Check that context is not in the list yet.
826 for (Object* current = heap->native_contexts_list();
827 !current->IsUndefined();
828 current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
829 DCHECK(current != context);
833 context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list(),
834 UPDATE_WEAK_WRITE_BARRIER);
835 heap->set_native_contexts_list(context);
839 void Genesis::CreateRoots() {
840 // Allocate the native context FixedArray first and then patch the
841 // closure and extension object later (we need the empty function
842 // and the global object, but in order to create those, we need the
844 native_context_ = factory()->NewNativeContext();
845 AddToWeakNativeContextList(*native_context());
846 isolate()->set_context(*native_context());
848 // Allocate the message listeners object.
850 v8::NeanderArray listeners(isolate());
851 native_context()->set_message_listeners(*listeners.value());
856 void Genesis::InstallGlobalThisBinding() {
857 Handle<ScriptContextTable> script_contexts(
858 native_context()->script_context_table());
859 Handle<ScopeInfo> scope_info = ScopeInfo::CreateGlobalThisBinding(isolate());
860 Handle<JSFunction> closure(native_context()->closure());
861 Handle<Context> context = factory()->NewScriptContext(closure, scope_info);
863 // Go ahead and hook it up while we're at it.
864 int slot = scope_info->ReceiverContextSlotIndex();
865 DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
866 context->set(slot, native_context()->global_proxy());
868 Handle<ScriptContextTable> new_script_contexts =
869 ScriptContextTable::Extend(script_contexts, context);
870 native_context()->set_script_context_table(*new_script_contexts);
874 void Genesis::HookUpGlobalThisBinding(Handle<FixedArray> outdated_contexts) {
875 // One of these contexts should be the one that declares the global "this"
877 for (int i = 0; i < outdated_contexts->length(); ++i) {
878 Context* context = Context::cast(outdated_contexts->get(i));
879 if (context->IsScriptContext()) {
880 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
881 int slot = scope_info->ReceiverContextSlotIndex();
883 DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
884 context->set(slot, native_context()->global_proxy());
891 Handle<GlobalObject> Genesis::CreateNewGlobals(
892 v8::Local<v8::ObjectTemplate> global_proxy_template,
893 Handle<JSGlobalProxy> global_proxy) {
894 // The argument global_proxy_template aka data is an ObjectTemplateInfo.
895 // It has a constructor pointer that points at global_constructor which is a
896 // FunctionTemplateInfo.
897 // The global_proxy_constructor is used to (re)initialize the
898 // global_proxy. The global_proxy_constructor also has a prototype_template
899 // pointer that points at js_global_object_template which is an
900 // ObjectTemplateInfo.
901 // That in turn has a constructor pointer that points at
902 // js_global_object_constructor which is a FunctionTemplateInfo.
903 // js_global_object_constructor is used to make js_global_object_function
904 // js_global_object_function is used to make the new global_object.
906 // --- G l o b a l ---
907 // Step 1: Create a fresh JSGlobalObject.
908 Handle<JSFunction> js_global_object_function;
909 Handle<ObjectTemplateInfo> js_global_object_template;
910 if (!global_proxy_template.IsEmpty()) {
911 // Get prototype template of the global_proxy_template.
912 Handle<ObjectTemplateInfo> data =
913 v8::Utils::OpenHandle(*global_proxy_template);
914 Handle<FunctionTemplateInfo> global_constructor =
915 Handle<FunctionTemplateInfo>(
916 FunctionTemplateInfo::cast(data->constructor()));
917 Handle<Object> proto_template(global_constructor->prototype_template(),
919 if (!proto_template->IsUndefined()) {
920 js_global_object_template =
921 Handle<ObjectTemplateInfo>::cast(proto_template);
925 if (js_global_object_template.is_null()) {
926 Handle<String> name = Handle<String>(heap()->empty_string());
927 Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
928 Builtins::kIllegal));
929 Handle<JSObject> prototype =
930 factory()->NewFunctionPrototype(isolate()->object_function());
931 js_global_object_function = factory()->NewFunction(
932 name, code, prototype, JS_GLOBAL_OBJECT_TYPE, JSGlobalObject::kSize);
934 LookupIterator it(prototype, factory()->constructor_string(),
935 LookupIterator::OWN_SKIP_INTERCEPTOR);
936 Handle<Object> value = JSReceiver::GetProperty(&it).ToHandleChecked();
937 DCHECK(it.IsFound());
938 DCHECK_EQ(*isolate()->object_function(), *value);
941 Handle<FunctionTemplateInfo> js_global_object_constructor(
942 FunctionTemplateInfo::cast(js_global_object_template->constructor()));
943 js_global_object_function = ApiNatives::CreateApiFunction(
944 isolate(), js_global_object_constructor, factory()->the_hole_value(),
945 ApiNatives::GlobalObjectType);
948 js_global_object_function->initial_map()->set_is_prototype_map(true);
949 js_global_object_function->initial_map()->set_is_hidden_prototype();
950 js_global_object_function->initial_map()->set_dictionary_map(true);
951 Handle<GlobalObject> global_object =
952 factory()->NewGlobalObject(js_global_object_function);
954 // Step 2: (re)initialize the global proxy object.
955 Handle<JSFunction> global_proxy_function;
956 if (global_proxy_template.IsEmpty()) {
957 Handle<String> name = Handle<String>(heap()->empty_string());
958 Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
959 Builtins::kIllegal));
960 global_proxy_function = factory()->NewFunction(
961 name, code, JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
963 Handle<ObjectTemplateInfo> data =
964 v8::Utils::OpenHandle(*global_proxy_template);
965 Handle<FunctionTemplateInfo> global_constructor(
966 FunctionTemplateInfo::cast(data->constructor()));
967 global_proxy_function = ApiNatives::CreateApiFunction(
968 isolate(), global_constructor, factory()->the_hole_value(),
969 ApiNatives::GlobalProxyType);
972 Handle<String> global_name = factory()->global_string();
973 global_proxy_function->shared()->set_instance_class_name(*global_name);
974 global_proxy_function->initial_map()->set_is_access_check_needed(true);
976 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
977 // Return the global proxy.
979 factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
980 return global_object;
984 void Genesis::HookUpGlobalProxy(Handle<GlobalObject> global_object,
985 Handle<JSGlobalProxy> global_proxy) {
986 // Set the native context for the global object.
987 global_object->set_native_context(*native_context());
988 global_object->set_global_proxy(*global_proxy);
989 global_proxy->set_native_context(*native_context());
990 // If we deserialized the context, the global proxy is already
991 // correctly set up. Otherwise it's undefined.
992 DCHECK(native_context()->get(Context::GLOBAL_PROXY_INDEX)->IsUndefined() ||
993 native_context()->global_proxy() == *global_proxy);
994 native_context()->set_global_proxy(*global_proxy);
998 void Genesis::HookUpGlobalObject(Handle<GlobalObject> global_object,
999 Handle<FixedArray> outdated_contexts) {
1000 Handle<GlobalObject> global_object_from_snapshot(
1001 GlobalObject::cast(native_context()->extension()));
1002 Handle<JSBuiltinsObject> builtins_global(native_context()->builtins());
1003 native_context()->set_extension(*global_object);
1004 native_context()->set_security_token(*global_object);
1006 // Replace outdated global objects in deserialized contexts.
1007 for (int i = 0; i < outdated_contexts->length(); ++i) {
1008 Context* context = Context::cast(outdated_contexts->get(i));
1009 // Assert that there is only one native context.
1010 DCHECK(!context->IsNativeContext() || context == *native_context());
1011 DCHECK_EQ(context->global_object(), *global_object_from_snapshot);
1012 context->set_global_object(*global_object);
1015 static const PropertyAttributes attributes =
1016 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1017 JSObject::SetOwnPropertyIgnoreAttributes(builtins_global,
1018 factory()->global_string(),
1019 global_object, attributes).Assert();
1020 // Set up the reference from the global object to the builtins object.
1021 JSGlobalObject::cast(*global_object)->set_builtins(*builtins_global);
1022 TransferNamedProperties(global_object_from_snapshot, global_object);
1023 TransferIndexedProperties(global_object_from_snapshot, global_object);
1027 // This is only called if we are not using snapshots. The equivalent
1028 // work in the snapshot case is done in HookUpGlobalObject.
1029 void Genesis::InitializeGlobal(Handle<GlobalObject> global_object,
1030 Handle<JSFunction> empty_function,
1031 ContextType context_type) {
1032 // --- N a t i v e C o n t e x t ---
1033 // Use the empty function as closure (no scope info).
1034 native_context()->set_closure(*empty_function);
1035 native_context()->set_previous(NULL);
1036 // Set extension and global object.
1037 native_context()->set_extension(*global_object);
1038 native_context()->set_global_object(*global_object);
1039 // Security setup: Set the security token of the native context to the global
1040 // object. This makes the security check between two different contexts fail
1041 // by default even in case of global object reinitialization.
1042 native_context()->set_security_token(*global_object);
1044 Isolate* isolate = global_object->GetIsolate();
1045 Factory* factory = isolate->factory();
1046 Heap* heap = isolate->heap();
1048 Handle<ScriptContextTable> script_context_table =
1049 factory->NewScriptContextTable();
1050 native_context()->set_script_context_table(*script_context_table);
1051 InstallGlobalThisBinding();
1053 Handle<String> object_name = factory->Object_string();
1054 JSObject::AddProperty(
1055 global_object, object_name, isolate->object_function(), DONT_ENUM);
1057 Handle<JSObject> global(native_context()->global_object());
1059 // Install global Function object
1060 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
1061 empty_function, Builtins::kIllegal);
1063 { // --- A r r a y ---
1064 Handle<JSFunction> array_function =
1065 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
1066 isolate->initial_object_prototype(),
1067 Builtins::kArrayCode);
1068 array_function->shared()->DontAdaptArguments();
1069 array_function->shared()->set_function_data(Smi::FromInt(kArrayCode));
1071 // This seems a bit hackish, but we need to make sure Array.length
1073 array_function->shared()->set_length(1);
1075 Handle<Map> initial_map(array_function->initial_map());
1077 // This assert protects an optimization in
1078 // HGraphBuilder::JSArrayBuilder::EmitMapCode()
1079 DCHECK(initial_map->elements_kind() == GetInitialFastElementsKind());
1080 Map::EnsureDescriptorSlack(initial_map, 1);
1082 PropertyAttributes attribs = static_cast<PropertyAttributes>(
1083 DONT_ENUM | DONT_DELETE);
1085 Handle<AccessorInfo> array_length =
1086 Accessors::ArrayLengthInfo(isolate, attribs);
1088 AccessorConstantDescriptor d(
1089 Handle<Name>(Name::cast(array_length->name())), array_length,
1091 initial_map->AppendDescriptor(&d);
1094 // array_function is used internally. JS code creating array object should
1095 // search for the 'Array' property on the global object and use that one
1096 // as the constructor. 'Array' property on a global object can be
1097 // overwritten by JS code.
1098 native_context()->set_array_function(*array_function);
1100 // Cache the array maps, needed by ArrayConstructorStub
1101 CacheInitialJSArrayMaps(native_context(), initial_map);
1102 ArrayConstructorStub array_constructor_stub(isolate);
1103 Handle<Code> code = array_constructor_stub.GetCode();
1104 array_function->shared()->set_construct_stub(*code);
1106 Handle<Map> initial_strong_map =
1107 Map::Copy(initial_map, "SetInstancePrototype");
1108 initial_strong_map->set_is_strong();
1109 CacheInitialJSArrayMaps(native_context(), initial_strong_map);
1112 { // --- N u m b e r ---
1113 Handle<JSFunction> number_fun =
1114 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
1115 isolate->initial_object_prototype(),
1116 Builtins::kIllegal);
1117 native_context()->set_number_function(*number_fun);
1120 { // --- B o o l e a n ---
1121 Handle<JSFunction> boolean_fun =
1122 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
1123 isolate->initial_object_prototype(),
1124 Builtins::kIllegal);
1125 native_context()->set_boolean_function(*boolean_fun);
1128 { // --- S t r i n g ---
1129 Handle<JSFunction> string_fun =
1130 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
1131 isolate->initial_object_prototype(),
1132 Builtins::kIllegal);
1133 string_fun->shared()->set_construct_stub(
1134 isolate->builtins()->builtin(Builtins::kStringConstructCode));
1135 native_context()->set_string_function(*string_fun);
1137 Handle<Map> string_map =
1138 Handle<Map>(native_context()->string_function()->initial_map());
1139 Map::EnsureDescriptorSlack(string_map, 1);
1141 PropertyAttributes attribs = static_cast<PropertyAttributes>(
1142 DONT_ENUM | DONT_DELETE | READ_ONLY);
1143 Handle<AccessorInfo> string_length(
1144 Accessors::StringLengthInfo(isolate, attribs));
1147 AccessorConstantDescriptor d(factory->length_string(), string_length,
1149 string_map->AppendDescriptor(&d);
1154 // --- S y m b o l ---
1155 Handle<JSFunction> symbol_fun = InstallFunction(
1156 global, "Symbol", JS_VALUE_TYPE, JSValue::kSize,
1157 isolate->initial_object_prototype(), Builtins::kIllegal);
1158 native_context()->set_symbol_function(*symbol_fun);
1161 { // --- D a t e ---
1162 // Builtin functions for Date.prototype.
1163 Handle<JSFunction> date_fun =
1164 InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize,
1165 isolate->initial_object_prototype(),
1166 Builtins::kIllegal);
1168 native_context()->set_date_function(*date_fun);
1173 // Builtin functions for RegExp.prototype.
1174 Handle<JSFunction> regexp_fun =
1175 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
1176 isolate->initial_object_prototype(),
1177 Builtins::kIllegal);
1178 native_context()->set_regexp_function(*regexp_fun);
1180 DCHECK(regexp_fun->has_initial_map());
1181 Handle<Map> initial_map(regexp_fun->initial_map());
1183 DCHECK_EQ(0, initial_map->inobject_properties());
1185 PropertyAttributes final =
1186 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1187 Map::EnsureDescriptorSlack(initial_map, 5);
1190 // ECMA-262, section 15.10.7.1.
1191 DataDescriptor field(factory->source_string(),
1192 JSRegExp::kSourceFieldIndex, final,
1193 Representation::Tagged());
1194 initial_map->AppendDescriptor(&field);
1197 // ECMA-262, section 15.10.7.2.
1198 DataDescriptor field(factory->global_string(),
1199 JSRegExp::kGlobalFieldIndex, final,
1200 Representation::Tagged());
1201 initial_map->AppendDescriptor(&field);
1204 // ECMA-262, section 15.10.7.3.
1205 DataDescriptor field(factory->ignore_case_string(),
1206 JSRegExp::kIgnoreCaseFieldIndex, final,
1207 Representation::Tagged());
1208 initial_map->AppendDescriptor(&field);
1211 // ECMA-262, section 15.10.7.4.
1212 DataDescriptor field(factory->multiline_string(),
1213 JSRegExp::kMultilineFieldIndex, final,
1214 Representation::Tagged());
1215 initial_map->AppendDescriptor(&field);
1218 // ECMA-262, section 15.10.7.5.
1219 PropertyAttributes writable =
1220 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
1221 DataDescriptor field(factory->last_index_string(),
1222 JSRegExp::kLastIndexFieldIndex, writable,
1223 Representation::Tagged());
1224 initial_map->AppendDescriptor(&field);
1227 static const int num_fields = JSRegExp::kInObjectFieldCount;
1228 initial_map->set_inobject_properties(num_fields);
1229 initial_map->set_unused_property_fields(0);
1230 initial_map->set_instance_size(initial_map->instance_size() +
1231 num_fields * kPointerSize);
1233 // RegExp prototype object is itself a RegExp.
1234 Handle<Map> proto_map = Map::Copy(initial_map, "RegExpPrototype");
1235 DCHECK(proto_map->prototype() == *isolate->initial_object_prototype());
1236 Handle<JSObject> proto = factory->NewJSObjectFromMap(proto_map);
1237 proto->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex,
1238 heap->query_colon_string());
1239 proto->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex,
1240 heap->false_value());
1241 proto->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex,
1242 heap->false_value());
1243 proto->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex,
1244 heap->false_value());
1245 proto->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
1247 SKIP_WRITE_BARRIER); // It's a Smi.
1248 proto_map->set_is_prototype_map(true);
1249 Map::SetPrototype(initial_map, proto);
1250 factory->SetRegExpIrregexpData(Handle<JSRegExp>::cast(proto),
1251 JSRegExp::IRREGEXP, factory->empty_string(),
1252 JSRegExp::Flags(0), 0);
1255 // Initialize the embedder data slot.
1256 Handle<FixedArray> embedder_data = factory->NewFixedArray(3);
1257 native_context()->set_embedder_data(*embedder_data);
1259 if (context_type == THIN_CONTEXT) return;
1262 Handle<String> name = factory->InternalizeUtf8String("JSON");
1263 Handle<JSFunction> cons = factory->NewFunction(name);
1264 JSFunction::SetInstancePrototype(cons,
1265 Handle<Object>(native_context()->initial_object_prototype(), isolate));
1266 cons->SetInstanceClassName(*name);
1267 Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1268 DCHECK(json_object->IsJSObject());
1269 JSObject::AddProperty(global, name, json_object, DONT_ENUM);
1270 native_context()->set_json_object(*json_object);
1273 { // -- A r r a y B u f f e r
1274 Handle<JSFunction> array_buffer_fun =
1276 global, "ArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1277 JSArrayBuffer::kSizeWithInternalFields,
1278 isolate->initial_object_prototype(),
1279 Builtins::kIllegal);
1280 native_context()->set_array_buffer_fun(*array_buffer_fun);
1283 { // -- T y p e d A r r a y s
1284 #define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype, size) \
1286 Handle<JSFunction> fun; \
1287 InstallTypedArray(#Type "Array", TYPE##_ELEMENTS, &fun); \
1288 native_context()->set_##type##_array_fun(*fun); \
1290 TYPED_ARRAYS(INSTALL_TYPED_ARRAY)
1291 #undef INSTALL_TYPED_ARRAY
1293 Handle<JSFunction> data_view_fun =
1295 global, "DataView", JS_DATA_VIEW_TYPE,
1296 JSDataView::kSizeWithInternalFields,
1297 isolate->initial_object_prototype(),
1298 Builtins::kIllegal);
1299 native_context()->set_data_view_fun(*data_view_fun);
1303 Handle<JSFunction> js_map_fun = InstallFunction(
1304 global, "Map", JS_MAP_TYPE, JSMap::kSize,
1305 isolate->initial_object_prototype(), Builtins::kIllegal);
1306 native_context()->set_js_map_fun(*js_map_fun);
1310 Handle<JSFunction> js_set_fun = InstallFunction(
1311 global, "Set", JS_SET_TYPE, JSSet::kSize,
1312 isolate->initial_object_prototype(), Builtins::kIllegal);
1313 native_context()->set_js_set_fun(*js_set_fun);
1316 { // Set up the iterator result object
1317 STATIC_ASSERT(JSGeneratorObject::kResultPropertyCount == 2);
1318 Handle<JSFunction> object_function(native_context()->object_function());
1319 Handle<Map> iterator_result_map =
1320 Map::Create(isolate, JSGeneratorObject::kResultPropertyCount);
1321 DCHECK_EQ(JSGeneratorObject::kResultSize,
1322 iterator_result_map->instance_size());
1323 DCHECK_EQ(JSGeneratorObject::kResultPropertyCount,
1324 iterator_result_map->inobject_properties());
1325 Map::EnsureDescriptorSlack(iterator_result_map,
1326 JSGeneratorObject::kResultPropertyCount);
1328 DataDescriptor value_descr(factory->value_string(),
1329 JSGeneratorObject::kResultValuePropertyIndex,
1330 NONE, Representation::Tagged());
1331 iterator_result_map->AppendDescriptor(&value_descr);
1333 DataDescriptor done_descr(factory->done_string(),
1334 JSGeneratorObject::kResultDonePropertyIndex, NONE,
1335 Representation::Tagged());
1336 iterator_result_map->AppendDescriptor(&done_descr);
1338 iterator_result_map->set_unused_property_fields(0);
1339 DCHECK_EQ(JSGeneratorObject::kResultSize,
1340 iterator_result_map->instance_size());
1341 native_context()->set_iterator_result_map(*iterator_result_map);
1345 InstallFunction(global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
1346 isolate->initial_object_prototype(), Builtins::kIllegal);
1348 InstallFunction(global, "WeakSet", JS_WEAK_SET_TYPE, JSWeakSet::kSize,
1349 isolate->initial_object_prototype(), Builtins::kIllegal);
1351 { // --- sloppy arguments map
1352 // Make sure we can recognize argument objects at runtime.
1353 // This is done by introducing an anonymous function with
1354 // class_name equals 'Arguments'.
1355 Handle<String> arguments_string = factory->Arguments_string();
1356 Handle<Code> code(isolate->builtins()->builtin(Builtins::kIllegal));
1357 Handle<JSFunction> function = factory->NewFunctionWithoutPrototype(
1358 arguments_string, code);
1359 function->shared()->set_instance_class_name(*arguments_string);
1362 factory->NewMap(JS_OBJECT_TYPE, Heap::kSloppyArgumentsObjectSize);
1363 // Create the descriptor array for the arguments object.
1364 Map::EnsureDescriptorSlack(map, 2);
1367 DataDescriptor d(factory->length_string(), Heap::kArgumentsLengthIndex,
1368 DONT_ENUM, Representation::Tagged());
1369 map->AppendDescriptor(&d);
1372 DataDescriptor d(factory->callee_string(), Heap::kArgumentsCalleeIndex,
1373 DONT_ENUM, Representation::Tagged());
1374 map->AppendDescriptor(&d);
1376 // @@iterator method is added later.
1378 map->set_function_with_prototype(true);
1379 map->set_inobject_properties(2);
1380 native_context()->set_sloppy_arguments_map(*map);
1382 DCHECK(!function->has_initial_map());
1383 JSFunction::SetInitialMap(function, map,
1384 isolate->initial_object_prototype());
1386 DCHECK(map->inobject_properties() > Heap::kArgumentsCalleeIndex);
1387 DCHECK(map->inobject_properties() > Heap::kArgumentsLengthIndex);
1388 DCHECK(!map->is_dictionary_map());
1389 DCHECK(IsFastObjectElementsKind(map->elements_kind()));
1392 { // --- fast and slow aliased arguments map
1393 Handle<Map> map = isolate->sloppy_arguments_map();
1394 map = Map::Copy(map, "FastAliasedArguments");
1395 map->set_elements_kind(FAST_SLOPPY_ARGUMENTS_ELEMENTS);
1396 DCHECK_EQ(2, map->inobject_properties());
1397 native_context()->set_fast_aliased_arguments_map(*map);
1399 map = Map::Copy(map, "SlowAliasedArguments");
1400 map->set_elements_kind(SLOW_SLOPPY_ARGUMENTS_ELEMENTS);
1401 DCHECK_EQ(2, map->inobject_properties());
1402 native_context()->set_slow_aliased_arguments_map(*map);
1405 { // --- strict mode arguments map
1406 const PropertyAttributes attributes =
1407 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1409 // Create the ThrowTypeError functions.
1410 Handle<AccessorPair> callee = factory->NewAccessorPair();
1411 Handle<AccessorPair> caller = factory->NewAccessorPair();
1413 Handle<JSFunction> poison = GetStrictArgumentsPoisonFunction();
1415 // Install the ThrowTypeError functions.
1416 callee->set_getter(*poison);
1417 callee->set_setter(*poison);
1418 caller->set_getter(*poison);
1419 caller->set_setter(*poison);
1421 // Create the map. Allocate one in-object field for length.
1422 Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE,
1423 Heap::kStrictArgumentsObjectSize);
1424 // Create the descriptor array for the arguments object.
1425 Map::EnsureDescriptorSlack(map, 3);
1428 DataDescriptor d(factory->length_string(), Heap::kArgumentsLengthIndex,
1429 DONT_ENUM, Representation::Tagged());
1430 map->AppendDescriptor(&d);
1433 AccessorConstantDescriptor d(factory->callee_string(), callee,
1435 map->AppendDescriptor(&d);
1438 AccessorConstantDescriptor d(factory->caller_string(), caller,
1440 map->AppendDescriptor(&d);
1442 // @@iterator method is added later.
1444 map->set_function_with_prototype(true);
1445 DCHECK_EQ(native_context()->object_function()->prototype(),
1446 *isolate->initial_object_prototype());
1447 Map::SetPrototype(map, isolate->initial_object_prototype());
1448 map->set_inobject_properties(1);
1450 // Copy constructor from the sloppy arguments boilerplate.
1451 map->SetConstructor(
1452 native_context()->sloppy_arguments_map()->GetConstructor());
1454 native_context()->set_strict_arguments_map(*map);
1456 DCHECK(map->inobject_properties() > Heap::kArgumentsLengthIndex);
1457 DCHECK(!map->is_dictionary_map());
1458 DCHECK(IsFastObjectElementsKind(map->elements_kind()));
1461 { // --- context extension
1462 // Create a function for the context extension objects.
1463 Handle<Code> code = Handle<Code>(
1464 isolate->builtins()->builtin(Builtins::kIllegal));
1465 Handle<JSFunction> context_extension_fun = factory->NewFunction(
1466 factory->empty_string(), code, JS_CONTEXT_EXTENSION_OBJECT_TYPE,
1467 JSObject::kHeaderSize);
1469 Handle<String> name = factory->InternalizeOneByteString(
1470 STATIC_CHAR_VECTOR("context_extension"));
1471 context_extension_fun->shared()->set_instance_class_name(*name);
1472 native_context()->set_context_extension_function(*context_extension_fun);
1477 // Set up the call-as-function delegate.
1479 Handle<Code>(isolate->builtins()->builtin(
1480 Builtins::kHandleApiCallAsFunction));
1481 Handle<JSFunction> delegate = factory->NewFunction(
1482 factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1483 native_context()->set_call_as_function_delegate(*delegate);
1484 delegate->shared()->DontAdaptArguments();
1488 // Set up the call-as-constructor delegate.
1490 Handle<Code>(isolate->builtins()->builtin(
1491 Builtins::kHandleApiCallAsConstructor));
1492 Handle<JSFunction> delegate = factory->NewFunction(
1493 factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1494 native_context()->set_call_as_constructor_delegate(*delegate);
1495 delegate->shared()->DontAdaptArguments();
1500 void Genesis::InstallTypedArray(const char* name, ElementsKind elements_kind,
1501 Handle<JSFunction>* fun) {
1502 Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1503 Handle<JSFunction> result = InstallFunction(
1504 global, name, JS_TYPED_ARRAY_TYPE, JSTypedArray::kSize,
1505 isolate()->initial_object_prototype(), Builtins::kIllegal);
1507 Handle<Map> initial_map = isolate()->factory()->NewMap(
1508 JS_TYPED_ARRAY_TYPE,
1509 JSTypedArray::kSizeWithInternalFields,
1511 JSFunction::SetInitialMap(result, initial_map,
1512 handle(initial_map->prototype(), isolate()));
1517 void Genesis::InitializeExperimentalGlobal() {
1518 #define FEATURE_INITIALIZE_GLOBAL(id, descr) InitializeGlobal_##id();
1520 HARMONY_INPROGRESS(FEATURE_INITIALIZE_GLOBAL)
1521 HARMONY_STAGED(FEATURE_INITIALIZE_GLOBAL)
1522 HARMONY_SHIPPING(FEATURE_INITIALIZE_GLOBAL)
1523 #undef FEATURE_INITIALIZE_GLOBAL
1527 bool Bootstrapper::CompileBuiltin(Isolate* isolate, int index) {
1528 Vector<const char> name = Natives::GetScriptName(index);
1529 Handle<String> source_code =
1530 isolate->bootstrapper()->SourceLookup<Natives>(index);
1531 Handle<Object> global = isolate->global_object();
1532 Handle<Object> utils = isolate->natives_utils_object();
1533 Handle<Object> args[] = {global, utils};
1535 return Bootstrapper::CompileNative(
1536 isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1537 source_code, arraysize(args), args);
1541 bool Bootstrapper::CompileExperimentalBuiltin(Isolate* isolate, int index) {
1542 HandleScope scope(isolate);
1543 Vector<const char> name = ExperimentalNatives::GetScriptName(index);
1544 Handle<String> source_code =
1545 isolate->bootstrapper()->SourceLookup<ExperimentalNatives>(index);
1546 Handle<Object> global = isolate->global_object();
1547 Handle<Object> utils = isolate->natives_utils_object();
1548 Handle<Object> args[] = {global, utils};
1549 return Bootstrapper::CompileNative(
1550 isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1551 source_code, arraysize(args), args);
1555 bool Bootstrapper::CompileExtraBuiltin(Isolate* isolate, int index) {
1556 HandleScope scope(isolate);
1557 Vector<const char> name = ExtraNatives::GetScriptName(index);
1558 Handle<String> source_code =
1559 isolate->bootstrapper()->SourceLookup<ExtraNatives>(index);
1560 Handle<Object> global = isolate->global_object();
1561 Handle<Object> exports = isolate->extras_exports_object();
1562 Handle<Object> args[] = {global, exports};
1563 return Bootstrapper::CompileNative(
1564 isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1565 source_code, arraysize(args), args);
1569 bool Bootstrapper::CompileCodeStubBuiltin(Isolate* isolate, int index) {
1570 HandleScope scope(isolate);
1571 Vector<const char> name = CodeStubNatives::GetScriptName(index);
1572 Handle<String> source_code =
1573 isolate->bootstrapper()->SourceLookup<CodeStubNatives>(index);
1574 Handle<JSObject> global(isolate->global_object());
1575 Handle<JSObject> exports(isolate->heap()->code_stub_exports_object());
1576 Handle<Object> args[] = {global, exports};
1578 CompileNative(isolate, name, global, source_code, arraysize(args), args);
1583 bool Bootstrapper::CompileNative(Isolate* isolate, Vector<const char> name,
1584 Handle<JSObject> receiver,
1585 Handle<String> source, int argc,
1586 Handle<Object> argv[]) {
1587 SuppressDebug compiling_natives(isolate->debug());
1588 // During genesis, the boilerplate for stack overflow won't work until the
1589 // environment has been at least partially initialized. Add a stack check
1590 // before entering JS code to catch overflow early.
1591 StackLimitCheck check(isolate);
1592 if (check.JsHasOverflowed(1 * KB)) {
1593 isolate->StackOverflow();
1597 Handle<Context> context(isolate->context());
1599 Handle<String> script_name =
1600 isolate->factory()->NewStringFromUtf8(name).ToHandleChecked();
1601 Handle<SharedFunctionInfo> function_info = Compiler::CompileScript(
1602 source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
1603 context, NULL, NULL, ScriptCompiler::kNoCompileOptions, NATIVES_CODE,
1605 if (function_info.is_null()) return false;
1607 DCHECK(context->IsNativeContext());
1609 Handle<Context> runtime_context(context->runtime_context());
1610 Handle<JSFunction> fun =
1611 isolate->factory()->NewFunctionFromSharedFunctionInfo(function_info,
1614 // For non-extension scripts, run script to get the function wrapper.
1615 Handle<Object> wrapper;
1616 if (!Execution::Call(isolate, fun, receiver, 0, NULL).ToHandle(&wrapper)) {
1619 // Then run the function wrapper.
1620 return !Execution::Call(isolate, Handle<JSFunction>::cast(wrapper), receiver,
1621 argc, argv).is_null();
1625 bool Genesis::CallUtilsFunction(Isolate* isolate, const char* name) {
1626 Handle<JSObject> utils =
1627 Handle<JSObject>::cast(isolate->natives_utils_object());
1628 Handle<String> name_string =
1629 isolate->factory()->NewStringFromAsciiChecked(name);
1630 Handle<Object> fun = JSObject::GetDataProperty(utils, name_string);
1631 Handle<Object> receiver = isolate->factory()->undefined_value();
1632 Handle<Object> args[] = {utils};
1633 return !Execution::Call(isolate, fun, receiver, 1, args).is_null();
1637 bool Genesis::CompileExtension(Isolate* isolate, v8::Extension* extension) {
1638 Factory* factory = isolate->factory();
1639 HandleScope scope(isolate);
1640 Handle<SharedFunctionInfo> function_info;
1642 Handle<String> source =
1644 ->NewExternalStringFromOneByte(extension->source())
1646 DCHECK(source->IsOneByteRepresentation());
1648 // If we can't find the function in the cache, we compile a new
1649 // function and insert it into the cache.
1650 Vector<const char> name = CStrVector(extension->name());
1651 SourceCodeCache* cache = isolate->bootstrapper()->extensions_cache();
1652 Handle<Context> context(isolate->context());
1653 DCHECK(context->IsNativeContext());
1655 if (!cache->Lookup(name, &function_info)) {
1656 Handle<String> script_name =
1657 factory->NewStringFromUtf8(name).ToHandleChecked();
1658 function_info = Compiler::CompileScript(
1659 source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
1660 context, extension, NULL, ScriptCompiler::kNoCompileOptions,
1661 NOT_NATIVES_CODE, false);
1662 if (function_info.is_null()) return false;
1663 cache->Add(name, function_info);
1666 // Set up the function context. Conceptually, we should clone the
1667 // function before overwriting the context but since we're in a
1668 // single-threaded environment it is not strictly necessary.
1669 Handle<JSFunction> fun =
1670 factory->NewFunctionFromSharedFunctionInfo(function_info, context);
1672 // Call function using either the runtime object or the global
1673 // object as the receiver. Provide no parameters.
1674 Handle<Object> receiver = isolate->global_object();
1675 return !Execution::Call(isolate, fun, receiver, 0, NULL).is_null();
1679 static Handle<JSObject> ResolveBuiltinIdHolder(Handle<Context> native_context,
1680 const char* holder_expr) {
1681 Isolate* isolate = native_context->GetIsolate();
1682 Factory* factory = isolate->factory();
1683 Handle<GlobalObject> global(native_context->global_object());
1684 const char* period_pos = strchr(holder_expr, '.');
1685 if (period_pos == NULL) {
1686 return Handle<JSObject>::cast(
1687 Object::GetPropertyOrElement(
1688 global, factory->InternalizeUtf8String(holder_expr))
1689 .ToHandleChecked());
1691 const char* inner = period_pos + 1;
1692 DCHECK(!strchr(inner, '.'));
1693 Vector<const char> property(holder_expr,
1694 static_cast<int>(period_pos - holder_expr));
1695 Handle<String> property_string = factory->InternalizeUtf8String(property);
1696 DCHECK(!property_string.is_null());
1697 Handle<JSObject> object = Handle<JSObject>::cast(
1698 Object::GetProperty(global, property_string).ToHandleChecked());
1699 if (strcmp("prototype", inner) == 0) {
1700 Handle<JSFunction> function = Handle<JSFunction>::cast(object);
1701 return Handle<JSObject>(JSObject::cast(function->prototype()));
1703 Handle<String> inner_string = factory->InternalizeUtf8String(inner);
1704 DCHECK(!inner_string.is_null());
1705 Handle<Object> value =
1706 Object::GetProperty(object, inner_string).ToHandleChecked();
1707 return Handle<JSObject>::cast(value);
1711 #define INSTALL_NATIVE(Type, name, var) \
1712 Handle<String> var##_name = \
1713 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR(name)); \
1714 Handle<Object> var##_native = \
1715 Object::GetProperty(handle(native_context()->builtins()), var##_name) \
1716 .ToHandleChecked(); \
1717 native_context()->set_##var(Type::cast(*var##_native));
1720 void Genesis::InstallNativeFunctions() {
1721 HandleScope scope(isolate());
1722 INSTALL_NATIVE(JSFunction, "$createDate", create_date_fun);
1724 INSTALL_NATIVE(JSFunction, "$toNumber", to_number_fun);
1725 INSTALL_NATIVE(JSFunction, "$toString", to_string_fun);
1726 INSTALL_NATIVE(JSFunction, "$toDetailString", to_detail_string_fun);
1727 INSTALL_NATIVE(JSFunction, "$toInteger", to_integer_fun);
1728 INSTALL_NATIVE(JSFunction, "$toUint32", to_uint32_fun);
1729 INSTALL_NATIVE(JSFunction, "$toInt32", to_int32_fun);
1730 INSTALL_NATIVE(JSFunction, "$toLength", to_length_fun);
1732 INSTALL_NATIVE(JSFunction, "$globalEval", global_eval_fun);
1733 INSTALL_NATIVE(JSFunction, "$getStackTraceLine", get_stack_trace_line_fun);
1734 INSTALL_NATIVE(JSFunction, "$toCompletePropertyDescriptor",
1735 to_complete_property_descriptor);
1737 INSTALL_NATIVE(Symbol, "$promiseStatus", promise_status);
1738 INSTALL_NATIVE(Symbol, "$promiseValue", promise_value);
1739 INSTALL_NATIVE(JSFunction, "$promiseCreate", promise_create);
1740 INSTALL_NATIVE(JSFunction, "$promiseResolve", promise_resolve);
1741 INSTALL_NATIVE(JSFunction, "$promiseReject", promise_reject);
1742 INSTALL_NATIVE(JSFunction, "$promiseChain", promise_chain);
1743 INSTALL_NATIVE(JSFunction, "$promiseCatch", promise_catch);
1744 INSTALL_NATIVE(JSFunction, "$promiseThen", promise_then);
1746 INSTALL_NATIVE(JSFunction, "$observeNotifyChange", observers_notify_change);
1747 INSTALL_NATIVE(JSFunction, "$observeEnqueueSpliceRecord",
1748 observers_enqueue_splice);
1749 INSTALL_NATIVE(JSFunction, "$observeBeginPerformSplice",
1750 observers_begin_perform_splice);
1751 INSTALL_NATIVE(JSFunction, "$observeEndPerformSplice",
1752 observers_end_perform_splice);
1753 INSTALL_NATIVE(JSFunction, "$observeNativeObjectObserve",
1754 native_object_observe);
1755 INSTALL_NATIVE(JSFunction, "$observeNativeObjectGetNotifier",
1756 native_object_get_notifier);
1757 INSTALL_NATIVE(JSFunction, "$observeNativeObjectNotifierPerformChange",
1758 native_object_notifier_perform_change);
1759 INSTALL_NATIVE(JSFunction, "$arrayValues", array_values_iterator);
1760 INSTALL_NATIVE(JSFunction, "$mapGet", map_get);
1761 INSTALL_NATIVE(JSFunction, "$mapSet", map_set);
1762 INSTALL_NATIVE(JSFunction, "$mapHas", map_has);
1763 INSTALL_NATIVE(JSFunction, "$mapDelete", map_delete);
1764 INSTALL_NATIVE(JSFunction, "$setAdd", set_add);
1765 INSTALL_NATIVE(JSFunction, "$setHas", set_has);
1766 INSTALL_NATIVE(JSFunction, "$setDelete", set_delete);
1767 INSTALL_NATIVE(JSFunction, "$mapFromArray", map_from_array);
1768 INSTALL_NATIVE(JSFunction, "$setFromArray", set_from_array);
1772 void Genesis::InstallExperimentalNativeFunctions() {
1773 if (FLAG_harmony_proxies) {
1774 INSTALL_NATIVE(JSFunction, "$proxyDerivedHasTrap", derived_has_trap);
1775 INSTALL_NATIVE(JSFunction, "$proxyDerivedGetTrap", derived_get_trap);
1776 INSTALL_NATIVE(JSFunction, "$proxyDerivedSetTrap", derived_set_trap);
1777 INSTALL_NATIVE(JSFunction, "$proxyEnumerate", proxy_enumerate);
1780 #define INSTALL_NATIVE_FUNCTIONS_FOR(id, descr) InstallNativeFunctions_##id();
1781 HARMONY_INPROGRESS(INSTALL_NATIVE_FUNCTIONS_FOR)
1782 HARMONY_STAGED(INSTALL_NATIVE_FUNCTIONS_FOR)
1783 HARMONY_SHIPPING(INSTALL_NATIVE_FUNCTIONS_FOR)
1784 #undef INSTALL_NATIVE_FUNCTIONS_FOR
1788 template <typename Data>
1789 Data* SetBuiltinTypedArray(Isolate* isolate, Handle<JSBuiltinsObject> builtins,
1790 ExternalArrayType type, Data* data,
1791 size_t num_elements, const char* name) {
1792 size_t byte_length = num_elements * sizeof(*data);
1793 Handle<JSArrayBuffer> buffer = isolate->factory()->NewJSArrayBuffer();
1794 bool is_external = data != nullptr;
1796 data = reinterpret_cast<Data*>(
1797 isolate->array_buffer_allocator()->Allocate(byte_length));
1799 Runtime::SetupArrayBuffer(isolate, buffer, is_external, data, byte_length);
1801 Handle<JSTypedArray> typed_array =
1802 isolate->factory()->NewJSTypedArray(type, buffer, 0, num_elements);
1803 Handle<String> name_string = isolate->factory()->InternalizeUtf8String(name);
1804 // Reset property cell type before (re)initializing.
1805 JSBuiltinsObject::InvalidatePropertyCell(builtins, name_string);
1806 JSObject::SetOwnPropertyIgnoreAttributes(builtins, name_string, typed_array,
1813 void Genesis::InitializeBuiltinTypedArrays() {
1814 Handle<JSBuiltinsObject> builtins(native_context()->builtins());
1815 { // Initially seed the per-context random number generator using the
1816 // per-isolate random number generator.
1817 const size_t num_elements = 2;
1818 const size_t num_bytes = num_elements * sizeof(uint32_t);
1819 uint32_t* state = SetBuiltinTypedArray<uint32_t>(isolate(), builtins,
1820 kExternalUint32Array, NULL,
1821 num_elements, "rngstate");
1823 isolate()->random_number_generator()->NextBytes(state, num_bytes);
1824 } while (state[0] == 0 || state[1] == 0);
1827 { // Initialize trigonometric lookup tables and constants.
1828 const size_t num_elements = arraysize(fdlibm::MathConstants::constants);
1829 double* data = const_cast<double*>(fdlibm::MathConstants::constants);
1830 SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1831 data, num_elements, "kMath");
1834 { // Initialize a result array for rempio2 calculation
1835 const size_t num_elements = 2;
1837 SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1838 NULL, num_elements, "rempio2result");
1839 for (size_t i = 0; i < num_elements; i++) data[i] = 0;
1844 #define EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(id) \
1845 void Genesis::InstallNativeFunctions_##id() {}
1847 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_modules)
1848 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_array_includes)
1849 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_regexps)
1850 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_arrow_functions)
1851 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_tostring)
1852 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy)
1853 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy_let)
1854 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_unicode)
1855 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_unicode_regexps)
1856 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_computed_property_names)
1857 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_rest_parameters)
1858 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_reflect)
1859 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spreadcalls)
1860 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_destructuring)
1861 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_object)
1862 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spread_arrays)
1863 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sharedarraybuffer)
1864 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_atomics)
1865 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_new_target)
1866 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_concat_spreadable)
1867 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_simd)
1870 void Genesis::InstallNativeFunctions_harmony_proxies() {
1871 if (FLAG_harmony_proxies) {
1872 INSTALL_NATIVE(JSFunction, "$proxyDerivedHasTrap", derived_has_trap);
1873 INSTALL_NATIVE(JSFunction, "$proxyDerivedGetTrap", derived_get_trap);
1874 INSTALL_NATIVE(JSFunction, "$proxyDerivedSetTrap", derived_set_trap);
1875 INSTALL_NATIVE(JSFunction, "$proxyEnumerate", proxy_enumerate);
1880 #undef INSTALL_NATIVE
1882 #define EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(id) \
1883 void Genesis::InitializeGlobal_##id() {}
1885 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_modules)
1886 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_array_includes)
1887 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_arrow_functions)
1888 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_proxies)
1889 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy)
1890 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy_let)
1891 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_unicode)
1892 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_computed_property_names)
1893 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_rest_parameters)
1894 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spreadcalls)
1895 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_destructuring)
1896 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_object)
1897 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spread_arrays)
1898 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_atomics)
1899 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_new_target)
1900 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_concat_spreadable)
1902 void Genesis::InitializeGlobal_harmony_regexps() {
1903 Handle<JSObject> builtins(native_context()->builtins());
1905 Handle<HeapObject> flag(FLAG_harmony_regexps ? heap()->true_value()
1906 : heap()->false_value());
1907 Runtime::SetObjectProperty(isolate(), builtins,
1908 factory()->harmony_regexps_string(), flag,
1913 void Genesis::InitializeGlobal_harmony_unicode_regexps() {
1914 Handle<JSObject> builtins(native_context()->builtins());
1916 Handle<HeapObject> flag(FLAG_harmony_unicode_regexps ? heap()->true_value()
1917 : heap()->false_value());
1918 Runtime::SetObjectProperty(isolate(), builtins,
1919 factory()->harmony_unicode_regexps_string(), flag,
1924 void Genesis::InitializeGlobal_harmony_reflect() {
1925 Handle<JSObject> builtins(native_context()->builtins());
1927 Handle<JSFunction> apply = InstallFunction(
1928 builtins, "$reflectApply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1929 MaybeHandle<JSObject>(), Builtins::kReflectApply);
1930 apply->shared()->set_internal_formal_parameter_count(3);
1931 apply->shared()->set_length(3);
1933 Handle<JSFunction> construct = InstallFunction(
1934 builtins, "$reflectConstruct", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1935 MaybeHandle<JSObject>(), Builtins::kReflectConstruct);
1936 construct->shared()->set_internal_formal_parameter_count(3);
1937 construct->shared()->set_length(2);
1939 if (!FLAG_harmony_reflect) return;
1941 Handle<JSGlobalObject> global(JSGlobalObject::cast(
1942 native_context()->global_object()));
1943 Handle<String> reflect_string =
1944 factory()->NewStringFromStaticChars("Reflect");
1945 Handle<Object> reflect =
1946 factory()->NewJSObject(isolate()->object_function(), TENURED);
1947 JSObject::AddProperty(global, reflect_string, reflect, DONT_ENUM);
1951 void Genesis::InitializeGlobal_harmony_tostring() {
1952 Handle<JSObject> builtins(native_context()->builtins());
1954 Handle<HeapObject> flag(FLAG_harmony_tostring ? heap()->true_value()
1955 : heap()->false_value());
1956 Runtime::SetObjectProperty(isolate(), builtins,
1957 factory()->harmony_tostring_string(), flag,
1962 void Genesis::InitializeGlobal_harmony_sharedarraybuffer() {
1963 if (!FLAG_harmony_sharedarraybuffer) return;
1965 Handle<JSGlobalObject> global(
1966 JSGlobalObject::cast(native_context()->global_object()));
1968 Handle<JSFunction> shared_array_buffer_fun = InstallFunction(
1969 global, "SharedArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1970 JSArrayBuffer::kSizeWithInternalFields,
1971 isolate()->initial_object_prototype(), Builtins::kIllegal);
1972 native_context()->set_shared_array_buffer_fun(*shared_array_buffer_fun);
1976 void Genesis::InitializeGlobal_harmony_simd() {
1977 if (!FLAG_harmony_simd) return;
1979 Handle<JSGlobalObject> global(
1980 JSGlobalObject::cast(native_context()->global_object()));
1981 Isolate* isolate = global->GetIsolate();
1982 Factory* factory = isolate->factory();
1984 Handle<String> name = factory->InternalizeUtf8String("SIMD");
1985 Handle<JSFunction> cons = factory->NewFunction(name);
1986 JSFunction::SetInstancePrototype(
1988 Handle<Object>(native_context()->initial_object_prototype(), isolate));
1989 cons->SetInstanceClassName(*name);
1990 Handle<JSObject> simd_object = factory->NewJSObject(cons, TENURED);
1991 DCHECK(simd_object->IsJSObject());
1992 JSObject::AddProperty(global, name, simd_object, DONT_ENUM);
1994 Handle<JSFunction> float32x4_function =
1995 InstallFunction(simd_object, "Float32x4", JS_VALUE_TYPE, JSValue::kSize,
1996 isolate->initial_object_prototype(), Builtins::kIllegal);
1997 // Set the instance class name since InstallFunction only does this when
1998 // we install on the GlobalObject.
1999 float32x4_function->SetInstanceClassName(*factory->Float32x4_string());
2000 native_context()->set_float32x4_function(*float32x4_function);
2004 Handle<JSFunction> Genesis::InstallInternalArray(Handle<JSObject> target,
2006 ElementsKind elements_kind) {
2007 // --- I n t e r n a l A r r a y ---
2008 // An array constructor on the builtins object that works like
2009 // the public Array constructor, except that its prototype
2010 // doesn't inherit from Object.prototype.
2011 // To be used only for internal work by builtins. Instances
2012 // must not be leaked to user code.
2013 Handle<JSObject> prototype =
2014 factory()->NewJSObject(isolate()->object_function(), TENURED);
2015 Handle<JSFunction> array_function =
2016 InstallFunction(target, name, JS_ARRAY_TYPE, JSArray::kSize, prototype,
2017 Builtins::kInternalArrayCode);
2019 InternalArrayConstructorStub internal_array_constructor_stub(isolate());
2020 Handle<Code> code = internal_array_constructor_stub.GetCode();
2021 array_function->shared()->set_construct_stub(*code);
2022 array_function->shared()->DontAdaptArguments();
2024 Handle<Map> original_map(array_function->initial_map());
2025 Handle<Map> initial_map = Map::Copy(original_map, "InternalArray");
2026 initial_map->set_elements_kind(elements_kind);
2027 JSFunction::SetInitialMap(array_function, initial_map, prototype);
2029 // Make "length" magic on instances.
2030 Map::EnsureDescriptorSlack(initial_map, 1);
2032 PropertyAttributes attribs = static_cast<PropertyAttributes>(
2033 DONT_ENUM | DONT_DELETE);
2035 Handle<AccessorInfo> array_length =
2036 Accessors::ArrayLengthInfo(isolate(), attribs);
2038 AccessorConstantDescriptor d(Handle<Name>(Name::cast(array_length->name())),
2039 array_length, attribs);
2040 initial_map->AppendDescriptor(&d);
2043 return array_function;
2047 bool Genesis::InstallNatives(ContextType context_type) {
2048 HandleScope scope(isolate());
2050 // Create a function for the builtins object. Allocate space for the
2051 // JavaScript builtins, a reference to the builtins object
2052 // (itself) and a reference to the native_context directly in the object.
2053 Handle<Code> code = Handle<Code>(
2054 isolate()->builtins()->builtin(Builtins::kIllegal));
2055 Handle<JSFunction> builtins_fun = factory()->NewFunction(
2056 factory()->empty_string(), code, JS_BUILTINS_OBJECT_TYPE,
2057 JSBuiltinsObject::kSize);
2059 Handle<String> name =
2060 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2061 builtins_fun->shared()->set_instance_class_name(*name);
2062 builtins_fun->initial_map()->set_dictionary_map(true);
2063 builtins_fun->initial_map()->set_prototype(heap()->null_value());
2065 // Allocate the builtins object.
2066 Handle<JSBuiltinsObject> builtins =
2067 Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
2068 builtins->set_builtins(*builtins);
2069 builtins->set_native_context(*native_context());
2070 builtins->set_global_proxy(native_context()->global_proxy());
2073 // Set up the 'builtin' property, which refers to the js builtins object.
2074 static const PropertyAttributes attributes =
2075 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2076 Handle<String> builtins_string =
2077 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2078 JSObject::AddProperty(builtins, builtins_string, builtins, attributes);
2080 // Set up the reference from the global object to the builtins object.
2081 JSGlobalObject::cast(native_context()->global_object())->
2082 set_builtins(*builtins);
2084 // Create a bridge function that has context in the native context.
2085 Handle<JSFunction> bridge = factory()->NewFunction(factory()->empty_string());
2086 DCHECK(bridge->context() == *isolate()->native_context());
2088 // Allocate the builtins context.
2089 Handle<Context> context =
2090 factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
2091 context->set_global_object(*builtins); // override builtins global object
2093 native_context()->set_runtime_context(*context);
2095 if (context_type == THIN_CONTEXT) {
2096 int js_builtins_script_index = Natives::GetDebuggerCount();
2097 if (!Bootstrapper::CompileBuiltin(isolate(), js_builtins_script_index))
2099 if (!InstallJSBuiltins(builtins)) return false;
2103 // Set up the utils object as shared container between native scripts.
2104 Handle<JSObject> utils = factory()->NewJSObject(isolate()->object_function());
2105 JSObject::NormalizeProperties(utils, CLEAR_INOBJECT_PROPERTIES, 16,
2106 "utils container for native scripts");
2107 native_context()->set_natives_utils_object(*utils);
2109 Handle<JSObject> extras_exports =
2110 factory()->NewJSObject(isolate()->object_function());
2111 JSObject::NormalizeProperties(extras_exports, CLEAR_INOBJECT_PROPERTIES, 2,
2112 "container to export to extra natives");
2113 native_context()->set_extras_exports_object(*extras_exports);
2115 if (FLAG_expose_natives_as != NULL) {
2116 Handle<String> utils_key = factory()->NewStringFromAsciiChecked("utils");
2117 JSObject::AddProperty(builtins, utils_key, utils, NONE);
2121 // Builtin functions for Script.
2122 Handle<JSFunction> script_fun = InstallFunction(
2123 builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
2124 isolate()->initial_object_prototype(), Builtins::kIllegal);
2125 Handle<JSObject> prototype =
2126 factory()->NewJSObject(isolate()->object_function(), TENURED);
2127 Accessors::FunctionSetPrototype(script_fun, prototype).Assert();
2128 native_context()->set_script_function(*script_fun);
2130 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
2131 Map::EnsureDescriptorSlack(script_map, 15);
2133 PropertyAttributes attribs =
2134 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2136 Handle<AccessorInfo> script_column =
2137 Accessors::ScriptColumnOffsetInfo(isolate(), attribs);
2139 AccessorConstantDescriptor d(
2140 Handle<Name>(Name::cast(script_column->name())), script_column,
2142 script_map->AppendDescriptor(&d);
2145 Handle<AccessorInfo> script_id =
2146 Accessors::ScriptIdInfo(isolate(), attribs);
2148 AccessorConstantDescriptor d(Handle<Name>(Name::cast(script_id->name())),
2149 script_id, attribs);
2150 script_map->AppendDescriptor(&d);
2154 Handle<AccessorInfo> script_name =
2155 Accessors::ScriptNameInfo(isolate(), attribs);
2157 AccessorConstantDescriptor d(
2158 Handle<Name>(Name::cast(script_name->name())), script_name, attribs);
2159 script_map->AppendDescriptor(&d);
2162 Handle<AccessorInfo> script_line =
2163 Accessors::ScriptLineOffsetInfo(isolate(), attribs);
2165 AccessorConstantDescriptor d(
2166 Handle<Name>(Name::cast(script_line->name())), script_line, attribs);
2167 script_map->AppendDescriptor(&d);
2170 Handle<AccessorInfo> script_source =
2171 Accessors::ScriptSourceInfo(isolate(), attribs);
2173 AccessorConstantDescriptor d(
2174 Handle<Name>(Name::cast(script_source->name())), script_source,
2176 script_map->AppendDescriptor(&d);
2179 Handle<AccessorInfo> script_type =
2180 Accessors::ScriptTypeInfo(isolate(), attribs);
2182 AccessorConstantDescriptor d(
2183 Handle<Name>(Name::cast(script_type->name())), script_type, attribs);
2184 script_map->AppendDescriptor(&d);
2187 Handle<AccessorInfo> script_compilation_type =
2188 Accessors::ScriptCompilationTypeInfo(isolate(), attribs);
2190 AccessorConstantDescriptor d(
2191 Handle<Name>(Name::cast(script_compilation_type->name())),
2192 script_compilation_type, attribs);
2193 script_map->AppendDescriptor(&d);
2196 Handle<AccessorInfo> script_line_ends =
2197 Accessors::ScriptLineEndsInfo(isolate(), attribs);
2199 AccessorConstantDescriptor d(
2200 Handle<Name>(Name::cast(script_line_ends->name())), script_line_ends,
2202 script_map->AppendDescriptor(&d);
2205 Handle<AccessorInfo> script_context_data =
2206 Accessors::ScriptContextDataInfo(isolate(), attribs);
2208 AccessorConstantDescriptor d(
2209 Handle<Name>(Name::cast(script_context_data->name())),
2210 script_context_data, attribs);
2211 script_map->AppendDescriptor(&d);
2214 Handle<AccessorInfo> script_eval_from_script =
2215 Accessors::ScriptEvalFromScriptInfo(isolate(), attribs);
2217 AccessorConstantDescriptor d(
2218 Handle<Name>(Name::cast(script_eval_from_script->name())),
2219 script_eval_from_script, attribs);
2220 script_map->AppendDescriptor(&d);
2223 Handle<AccessorInfo> script_eval_from_script_position =
2224 Accessors::ScriptEvalFromScriptPositionInfo(isolate(), attribs);
2226 AccessorConstantDescriptor d(
2227 Handle<Name>(Name::cast(script_eval_from_script_position->name())),
2228 script_eval_from_script_position, attribs);
2229 script_map->AppendDescriptor(&d);
2232 Handle<AccessorInfo> script_eval_from_function_name =
2233 Accessors::ScriptEvalFromFunctionNameInfo(isolate(), attribs);
2235 AccessorConstantDescriptor d(
2236 Handle<Name>(Name::cast(script_eval_from_function_name->name())),
2237 script_eval_from_function_name, attribs);
2238 script_map->AppendDescriptor(&d);
2241 Handle<AccessorInfo> script_source_url =
2242 Accessors::ScriptSourceUrlInfo(isolate(), attribs);
2244 AccessorConstantDescriptor d(
2245 Handle<Name>(Name::cast(script_source_url->name())),
2246 script_source_url, attribs);
2247 script_map->AppendDescriptor(&d);
2250 Handle<AccessorInfo> script_source_mapping_url =
2251 Accessors::ScriptSourceMappingUrlInfo(isolate(), attribs);
2253 AccessorConstantDescriptor d(
2254 Handle<Name>(Name::cast(script_source_mapping_url->name())),
2255 script_source_mapping_url, attribs);
2256 script_map->AppendDescriptor(&d);
2259 Handle<AccessorInfo> script_is_embedder_debug_script =
2260 Accessors::ScriptIsEmbedderDebugScriptInfo(isolate(), attribs);
2262 AccessorConstantDescriptor d(
2263 Handle<Name>(Name::cast(script_is_embedder_debug_script->name())),
2264 script_is_embedder_debug_script, attribs);
2265 script_map->AppendDescriptor(&d);
2268 // Allocate the empty script.
2269 Handle<Script> script = factory()->NewScript(factory()->empty_string());
2270 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
2271 heap()->public_set_empty_script(*script);
2274 // Builtin function for OpaqueReference -- a JSValue-based object,
2275 // that keeps its field isolated from JavaScript code. It may store
2276 // objects, that JavaScript code may not access.
2277 Handle<JSFunction> opaque_reference_fun = InstallFunction(
2278 builtins, "OpaqueReference", JS_VALUE_TYPE, JSValue::kSize,
2279 isolate()->initial_object_prototype(), Builtins::kIllegal);
2280 Handle<JSObject> prototype =
2281 factory()->NewJSObject(isolate()->object_function(), TENURED);
2282 Accessors::FunctionSetPrototype(opaque_reference_fun, prototype).Assert();
2283 native_context()->set_opaque_reference_function(*opaque_reference_fun);
2286 // InternalArrays should not use Smi-Only array optimizations. There are too
2287 // many places in the C++ runtime code (e.g. RegEx) that assume that
2288 // elements in InternalArrays can be set to non-Smi values without going
2289 // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
2290 // transition easy to trap. Moreover, they rarely are smi-only.
2292 HandleScope scope(isolate());
2293 Handle<JSObject> utils =
2294 Handle<JSObject>::cast(isolate()->natives_utils_object());
2295 Handle<JSFunction> array_function =
2296 InstallInternalArray(utils, "InternalArray", FAST_HOLEY_ELEMENTS);
2297 native_context()->set_internal_array_function(*array_function);
2298 InstallInternalArray(utils, "InternalPackedArray", FAST_ELEMENTS);
2301 { // -- S e t I t e r a t o r
2302 Handle<JSFunction> set_iterator_function = InstallFunction(
2303 builtins, "SetIterator", JS_SET_ITERATOR_TYPE, JSSetIterator::kSize,
2304 isolate()->initial_object_prototype(), Builtins::kIllegal);
2305 native_context()->set_set_iterator_map(
2306 set_iterator_function->initial_map());
2309 { // -- M a p I t e r a t o r
2310 Handle<JSFunction> map_iterator_function = InstallFunction(
2311 builtins, "MapIterator", JS_MAP_ITERATOR_TYPE, JSMapIterator::kSize,
2312 isolate()->initial_object_prototype(), Builtins::kIllegal);
2313 native_context()->set_map_iterator_map(
2314 map_iterator_function->initial_map());
2318 // Create generator meta-objects and install them on the builtins object.
2319 Handle<JSObject> builtins(native_context()->builtins());
2320 Handle<JSObject> iterator_prototype =
2321 factory()->NewJSObject(isolate()->object_function(), TENURED);
2322 Handle<JSObject> generator_object_prototype =
2323 factory()->NewJSObject(isolate()->object_function(), TENURED);
2324 Handle<JSObject> generator_function_prototype =
2325 factory()->NewJSObject(isolate()->object_function(), TENURED);
2326 SetObjectPrototype(generator_object_prototype, iterator_prototype);
2327 JSObject::AddProperty(
2328 builtins, factory()->InternalizeUtf8String("$iteratorPrototype"),
2330 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2331 JSObject::AddProperty(
2333 factory()->InternalizeUtf8String("GeneratorFunctionPrototype"),
2334 generator_function_prototype,
2335 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2337 JSObject::AddProperty(
2338 generator_function_prototype,
2339 factory()->InternalizeUtf8String("prototype"),
2340 generator_object_prototype,
2341 static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2343 static const bool kUseStrictFunctionMap = true;
2344 InstallFunction(builtins, "GeneratorFunction", JS_FUNCTION_TYPE,
2345 JSFunction::kSize, generator_function_prototype,
2346 Builtins::kIllegal, kUseStrictFunctionMap);
2348 // Create maps for generator functions and their prototypes. Store those
2349 // maps in the native context. The "prototype" property descriptor is
2350 // writable, non-enumerable, and non-configurable (as per ES6 draft
2351 // 04-14-15, section 25.2.4.3).
2352 Handle<Map> strict_function_map(strict_function_map_writable_prototype_);
2353 // Generator functions do not have "caller" or "arguments" accessors.
2354 Handle<Map> sloppy_generator_function_map =
2355 Map::Copy(strict_function_map, "SloppyGeneratorFunction");
2356 Map::SetPrototype(sloppy_generator_function_map,
2357 generator_function_prototype);
2358 native_context()->set_sloppy_generator_function_map(
2359 *sloppy_generator_function_map);
2361 Handle<Map> strict_generator_function_map =
2362 Map::Copy(strict_function_map, "StrictGeneratorFunction");
2363 Map::SetPrototype(strict_generator_function_map,
2364 generator_function_prototype);
2365 native_context()->set_strict_generator_function_map(
2366 *strict_generator_function_map);
2368 Handle<Map> strong_function_map(native_context()->strong_function_map());
2369 Handle<Map> strong_generator_function_map =
2370 Map::Copy(strong_function_map, "StrongGeneratorFunction");
2371 Map::SetPrototype(strong_generator_function_map,
2372 generator_function_prototype);
2373 native_context()->set_strong_generator_function_map(
2374 *strong_generator_function_map);
2376 Handle<JSFunction> object_function(native_context()->object_function());
2377 Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
2378 Map::SetPrototype(generator_object_prototype_map,
2379 generator_object_prototype);
2380 native_context()->set_generator_object_prototype_map(
2381 *generator_object_prototype_map);
2384 if (FLAG_disable_native_files) {
2385 PrintF("Warning: Running without installed natives!\n");
2389 // Install public symbols.
2391 static const PropertyAttributes attributes =
2392 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2393 #define INSTALL_PUBLIC_SYMBOL(name, varname, description) \
2394 Handle<String> varname = factory()->NewStringFromStaticChars(#varname); \
2395 JSObject::AddProperty(builtins, varname, factory()->name(), attributes);
2396 PUBLIC_SYMBOL_LIST(INSTALL_PUBLIC_SYMBOL)
2397 #undef INSTALL_PUBLIC_SYMBOL
2400 int i = Natives::GetDebuggerCount();
2401 if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2403 if (!InstallJSBuiltins(builtins)) return false;
2405 for (++i; i < Natives::GetBuiltinsCount(); ++i) {
2406 if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2409 if (!CallUtilsFunction(isolate(), "PostNatives")) return false;
2411 InstallNativeFunctions();
2413 auto function_cache =
2414 ObjectHashTable::New(isolate(), ApiNatives::kInitialFunctionCacheSize);
2415 native_context()->set_function_cache(*function_cache);
2417 // Store the map for the string prototype after the natives has been compiled
2418 // and the String function has been set up.
2419 Handle<JSFunction> string_function(native_context()->string_function());
2420 DCHECK(JSObject::cast(
2421 string_function->initial_map()->prototype())->HasFastProperties());
2422 native_context()->set_string_function_prototype_map(
2423 HeapObject::cast(string_function->initial_map()->prototype())->map());
2425 // Install Function.prototype.call and apply.
2427 Handle<String> key = factory()->Function_string();
2428 Handle<JSFunction> function =
2429 Handle<JSFunction>::cast(Object::GetProperty(
2430 handle(native_context()->global_object()), key).ToHandleChecked());
2431 Handle<JSObject> proto =
2432 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
2434 // Install the call and the apply functions.
2435 Handle<JSFunction> call =
2436 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2437 MaybeHandle<JSObject>(), Builtins::kFunctionCall);
2438 Handle<JSFunction> apply =
2439 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2440 MaybeHandle<JSObject>(), Builtins::kFunctionApply);
2442 // Make sure that Function.prototype.call appears to be compiled.
2443 // The code will never be called, but inline caching for call will
2444 // only work if it appears to be compiled.
2445 call->shared()->DontAdaptArguments();
2446 DCHECK(call->is_compiled());
2448 // Set the expected parameters for apply to 2; required by builtin.
2449 apply->shared()->set_internal_formal_parameter_count(2);
2451 // Set the lengths for the functions to satisfy ECMA-262.
2452 call->shared()->set_length(1);
2453 apply->shared()->set_length(2);
2456 InstallBuiltinFunctionIds();
2458 // Create a constructor for RegExp results (a variant of Array that
2459 // predefines the two properties index and match).
2461 // RegExpResult initial map.
2463 // Find global.Array.prototype to inherit from.
2464 Handle<JSFunction> array_constructor(native_context()->array_function());
2465 Handle<JSObject> array_prototype(
2466 JSObject::cast(array_constructor->instance_prototype()));
2469 Handle<Map> initial_map =
2470 factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
2471 initial_map->SetConstructor(*array_constructor);
2473 // Set prototype on map.
2474 initial_map->set_non_instance_prototype(false);
2475 Map::SetPrototype(initial_map, array_prototype);
2477 // Update map with length accessor from Array and add "index" and "input".
2478 Map::EnsureDescriptorSlack(initial_map, 3);
2481 JSFunction* array_function = native_context()->array_function();
2482 Handle<DescriptorArray> array_descriptors(
2483 array_function->initial_map()->instance_descriptors());
2484 Handle<String> length = factory()->length_string();
2485 int old = array_descriptors->SearchWithCache(
2486 *length, array_function->initial_map());
2487 DCHECK(old != DescriptorArray::kNotFound);
2488 AccessorConstantDescriptor desc(
2489 length, handle(array_descriptors->GetValue(old), isolate()),
2490 array_descriptors->GetDetails(old).attributes());
2491 initial_map->AppendDescriptor(&desc);
2494 DataDescriptor index_field(factory()->index_string(),
2495 JSRegExpResult::kIndexIndex, NONE,
2496 Representation::Tagged());
2497 initial_map->AppendDescriptor(&index_field);
2501 DataDescriptor input_field(factory()->input_string(),
2502 JSRegExpResult::kInputIndex, NONE,
2503 Representation::Tagged());
2504 initial_map->AppendDescriptor(&input_field);
2507 initial_map->set_inobject_properties(2);
2508 initial_map->set_unused_property_fields(0);
2510 native_context()->set_regexp_result_map(*initial_map);
2513 // Add @@iterator method to the arguments object maps.
2515 PropertyAttributes attribs = DONT_ENUM;
2516 Handle<AccessorInfo> arguments_iterator =
2517 Accessors::ArgumentsIteratorInfo(isolate(), attribs);
2519 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2520 arguments_iterator, attribs);
2521 Handle<Map> map(native_context()->sloppy_arguments_map());
2522 Map::EnsureDescriptorSlack(map, 1);
2523 map->AppendDescriptor(&d);
2526 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2527 arguments_iterator, attribs);
2528 Handle<Map> map(native_context()->fast_aliased_arguments_map());
2529 Map::EnsureDescriptorSlack(map, 1);
2530 map->AppendDescriptor(&d);
2533 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2534 arguments_iterator, attribs);
2535 Handle<Map> map(native_context()->slow_aliased_arguments_map());
2536 Map::EnsureDescriptorSlack(map, 1);
2537 map->AppendDescriptor(&d);
2540 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2541 arguments_iterator, attribs);
2542 Handle<Map> map(native_context()->strict_arguments_map());
2543 Map::EnsureDescriptorSlack(map, 1);
2544 map->AppendDescriptor(&d);
2549 if (FLAG_verify_heap) {
2550 builtins->ObjectVerify();
2558 bool Genesis::InstallExperimentalNatives() {
2559 static const char* harmony_array_includes_natives[] = {
2560 "native harmony-array-includes.js", nullptr};
2561 static const char* harmony_proxies_natives[] = {"native proxy.js", nullptr};
2562 static const char* harmony_modules_natives[] = {nullptr};
2563 static const char* harmony_regexps_natives[] = {"native harmony-regexp.js",
2565 static const char* harmony_arrow_functions_natives[] = {nullptr};
2566 static const char* harmony_tostring_natives[] = {"native harmony-tostring.js",
2568 static const char* harmony_sloppy_natives[] = {nullptr};
2569 static const char* harmony_sloppy_let_natives[] = {nullptr};
2570 static const char* harmony_unicode_natives[] = {nullptr};
2571 static const char* harmony_unicode_regexps_natives[] = {nullptr};
2572 static const char* harmony_computed_property_names_natives[] = {nullptr};
2573 static const char* harmony_rest_parameters_natives[] = {nullptr};
2574 static const char* harmony_reflect_natives[] = {"native harmony-reflect.js",
2576 static const char* harmony_spreadcalls_natives[] = {
2577 "native harmony-spread.js", nullptr};
2578 static const char* harmony_destructuring_natives[] = {nullptr};
2579 static const char* harmony_object_natives[] = {"native harmony-object.js",
2581 static const char* harmony_spread_arrays_natives[] = {nullptr};
2582 static const char* harmony_sharedarraybuffer_natives[] = {
2583 "native harmony-sharedarraybuffer.js", NULL};
2584 static const char* harmony_atomics_natives[] = {"native harmony-atomics.js",
2586 static const char* harmony_new_target_natives[] = {nullptr};
2587 static const char* harmony_concat_spreadable_natives[] = {
2588 "native harmony-concat-spreadable.js", nullptr};
2589 static const char* harmony_simd_natives[] = {"native harmony-simd.js",
2592 for (int i = ExperimentalNatives::GetDebuggerCount();
2593 i < ExperimentalNatives::GetBuiltinsCount(); i++) {
2594 #define INSTALL_EXPERIMENTAL_NATIVES(id, desc) \
2596 for (size_t j = 0; id##_natives[j] != NULL; j++) { \
2597 Vector<const char> script_name = ExperimentalNatives::GetScriptName(i); \
2598 if (strncmp(script_name.start(), id##_natives[j], \
2599 script_name.length()) == 0) { \
2600 if (!Bootstrapper::CompileExperimentalBuiltin(isolate(), i)) { \
2606 HARMONY_INPROGRESS(INSTALL_EXPERIMENTAL_NATIVES);
2607 HARMONY_STAGED(INSTALL_EXPERIMENTAL_NATIVES);
2608 HARMONY_SHIPPING(INSTALL_EXPERIMENTAL_NATIVES);
2609 #undef INSTALL_EXPERIMENTAL_NATIVES
2612 if (!CallUtilsFunction(isolate(), "PostExperimentals")) return false;
2614 InstallExperimentalNativeFunctions();
2615 InstallExperimentalBuiltinFunctionIds();
2620 bool Genesis::InstallExtraNatives() {
2621 for (int i = ExtraNatives::GetDebuggerCount();
2622 i < ExtraNatives::GetBuiltinsCount(); i++) {
2623 if (!Bootstrapper::CompileExtraBuiltin(isolate(), i)) return false;
2630 bool Bootstrapper::InstallCodeStubNatives(Isolate* isolate) {
2631 for (int i = CodeStubNatives::GetDebuggerCount();
2632 i < CodeStubNatives::GetBuiltinsCount(); i++) {
2633 if (!CompileCodeStubBuiltin(isolate, i)) return false;
2640 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
2641 const char* function_name,
2642 BuiltinFunctionId id) {
2643 Isolate* isolate = holder->GetIsolate();
2644 Handle<Object> function_object =
2645 Object::GetProperty(isolate, holder, function_name).ToHandleChecked();
2646 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2647 function->shared()->set_function_data(Smi::FromInt(id));
2651 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2652 { #holder_expr, #fun_name, k##name } \
2656 void Genesis::InstallBuiltinFunctionIds() {
2657 HandleScope scope(isolate());
2658 struct BuiltinFunctionIds {
2659 const char* holder_expr;
2660 const char* fun_name;
2661 BuiltinFunctionId id;
2664 const BuiltinFunctionIds builtins[] = {
2665 FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2667 for (const BuiltinFunctionIds& builtin : builtins) {
2668 Handle<JSObject> holder =
2669 ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2670 InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2675 void Genesis::InstallExperimentalBuiltinFunctionIds() {
2676 if (FLAG_harmony_atomics) {
2677 struct BuiltinFunctionIds {
2678 const char* holder_expr;
2679 const char* fun_name;
2680 BuiltinFunctionId id;
2683 const BuiltinFunctionIds atomic_builtins[] = {
2684 ATOMIC_FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2686 for (const BuiltinFunctionIds& builtin : atomic_builtins) {
2687 Handle<JSObject> holder =
2688 ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2689 InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2695 #undef INSTALL_BUILTIN_ID
2698 // Do not forget to update macros.py with named constant
2700 #define JSFUNCTION_RESULT_CACHE_LIST(F) \
2701 F(16, native_context()->regexp_function())
2704 static FixedArray* CreateCache(int size, Handle<JSFunction> factory_function) {
2705 Factory* factory = factory_function->GetIsolate()->factory();
2706 // Caches are supposed to live for a long time, allocate in old space.
2707 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
2708 // Cannot use cast as object is not fully initialized yet.
2709 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
2710 *factory->NewFixedArrayWithHoles(array_size, TENURED));
2711 cache->set(JSFunctionResultCache::kFactoryIndex, *factory_function);
2712 cache->MakeZeroSize();
2717 void Genesis::InstallJSFunctionResultCaches() {
2718 const int kNumberOfCaches = 0 +
2719 #define F(size, func) + 1
2720 JSFUNCTION_RESULT_CACHE_LIST(F)
2724 Handle<FixedArray> caches =
2725 factory()->NewFixedArray(kNumberOfCaches, TENURED);
2729 #define F(size, func) do { \
2730 FixedArray* cache = CreateCache((size), Handle<JSFunction>(func)); \
2731 caches->set(index++, cache); \
2734 JSFUNCTION_RESULT_CACHE_LIST(F);
2738 native_context()->set_jsfunction_result_caches(*caches);
2742 void Genesis::InitializeNormalizedMapCaches() {
2743 Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
2744 native_context()->set_normalized_map_cache(*cache);
2748 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
2749 v8::ExtensionConfiguration* extensions) {
2750 BootstrapperActive active(this);
2751 SaveContext saved_context(isolate_);
2752 isolate_->set_context(*native_context);
2753 return Genesis::InstallExtensions(native_context, extensions) &&
2754 Genesis::InstallSpecialObjects(native_context);
2758 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
2759 Isolate* isolate = native_context->GetIsolate();
2760 // Don't install extensions into the snapshot.
2761 if (isolate->serializer_enabled()) return true;
2763 Factory* factory = isolate->factory();
2764 HandleScope scope(isolate);
2765 Handle<JSGlobalObject> global(JSGlobalObject::cast(
2766 native_context->global_object()));
2768 Handle<JSObject> Error = Handle<JSObject>::cast(
2769 Object::GetProperty(isolate, global, "Error").ToHandleChecked());
2770 Handle<String> name =
2771 factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("stackTraceLimit"));
2772 Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit), isolate);
2773 JSObject::AddProperty(Error, name, stack_trace_limit, NONE);
2775 // By now the utils object is useless and can be removed.
2776 native_context->set_natives_utils_object(*factory->undefined_value());
2778 // Expose the natives in global if a name for it is specified.
2779 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
2780 Handle<String> natives_key =
2781 factory->InternalizeUtf8String(FLAG_expose_natives_as);
2782 uint32_t dummy_index;
2783 if (natives_key->AsArrayIndex(&dummy_index)) return true;
2784 Handle<JSBuiltinsObject> natives(global->builtins());
2785 JSObject::AddProperty(global, natives_key, natives, DONT_ENUM);
2788 // Expose the stack trace symbol to native JS.
2789 RETURN_ON_EXCEPTION_VALUE(isolate,
2790 JSObject::SetOwnPropertyIgnoreAttributes(
2791 handle(native_context->builtins(), isolate),
2792 factory->InternalizeOneByteString(
2793 STATIC_CHAR_VECTOR("$stackTraceSymbol")),
2794 factory->stack_trace_symbol(), NONE),
2797 // Expose the debug global object in global if a name for it is specified.
2798 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
2799 // If loading fails we just bail out without installing the
2800 // debugger but without tanking the whole context.
2801 Debug* debug = isolate->debug();
2802 if (!debug->Load()) return true;
2803 Handle<Context> debug_context = debug->debug_context();
2804 // Set the security token for the debugger context to the same as
2805 // the shell native context to allow calling between these (otherwise
2806 // exposing debug global object doesn't make much sense).
2807 debug_context->set_security_token(native_context->security_token());
2808 Handle<String> debug_string =
2809 factory->InternalizeUtf8String(FLAG_expose_debug_as);
2811 if (debug_string->AsArrayIndex(&index)) return true;
2812 Handle<Object> global_proxy(debug_context->global_proxy(), isolate);
2813 JSObject::AddProperty(global, debug_string, global_proxy, DONT_ENUM);
2819 static uint32_t Hash(RegisteredExtension* extension) {
2820 return v8::internal::ComputePointerHash(extension);
2824 Genesis::ExtensionStates::ExtensionStates() : map_(HashMap::PointersMatch, 8) {}
2826 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2827 RegisteredExtension* extension) {
2828 i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension));
2829 if (entry == NULL) {
2832 return static_cast<ExtensionTraversalState>(
2833 reinterpret_cast<intptr_t>(entry->value));
2836 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2837 ExtensionTraversalState state) {
2838 map_.LookupOrInsert(extension, Hash(extension))->value =
2839 reinterpret_cast<void*>(static_cast<intptr_t>(state));
2843 bool Genesis::InstallExtensions(Handle<Context> native_context,
2844 v8::ExtensionConfiguration* extensions) {
2845 Isolate* isolate = native_context->GetIsolate();
2846 ExtensionStates extension_states; // All extensions have state UNVISITED.
2847 return InstallAutoExtensions(isolate, &extension_states) &&
2848 (!FLAG_expose_free_buffer ||
2849 InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
2851 InstallExtension(isolate, "v8/gc", &extension_states)) &&
2852 (!FLAG_expose_externalize_string ||
2853 InstallExtension(isolate, "v8/externalize", &extension_states)) &&
2854 (!FLAG_track_gc_object_stats ||
2855 InstallExtension(isolate, "v8/statistics", &extension_states)) &&
2856 (!FLAG_expose_trigger_failure ||
2857 InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
2858 InstallRequestedExtensions(isolate, extensions, &extension_states);
2862 bool Genesis::InstallAutoExtensions(Isolate* isolate,
2863 ExtensionStates* extension_states) {
2864 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2867 if (it->extension()->auto_enable() &&
2868 !InstallExtension(isolate, it, extension_states)) {
2876 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
2877 v8::ExtensionConfiguration* extensions,
2878 ExtensionStates* extension_states) {
2879 for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
2880 if (!InstallExtension(isolate, *it, extension_states)) return false;
2886 // Installs a named extension. This methods is unoptimized and does
2887 // not scale well if we want to support a large number of extensions.
2888 bool Genesis::InstallExtension(Isolate* isolate,
2890 ExtensionStates* extension_states) {
2891 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2894 if (strcmp(name, it->extension()->name()) == 0) {
2895 return InstallExtension(isolate, it, extension_states);
2898 return Utils::ApiCheck(false,
2899 "v8::Context::New()",
2900 "Cannot find required extension");
2904 bool Genesis::InstallExtension(Isolate* isolate,
2905 v8::RegisteredExtension* current,
2906 ExtensionStates* extension_states) {
2907 HandleScope scope(isolate);
2909 if (extension_states->get_state(current) == INSTALLED) return true;
2910 // The current node has already been visited so there must be a
2911 // cycle in the dependency graph; fail.
2912 if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
2913 "v8::Context::New()",
2914 "Circular extension dependency")) {
2917 DCHECK(extension_states->get_state(current) == UNVISITED);
2918 extension_states->set_state(current, VISITED);
2919 v8::Extension* extension = current->extension();
2920 // Install the extension's dependencies
2921 for (int i = 0; i < extension->dependency_count(); i++) {
2922 if (!InstallExtension(isolate,
2923 extension->dependencies()[i],
2924 extension_states)) {
2928 // We do not expect this to throw an exception. Change this if it does.
2929 bool result = CompileExtension(isolate, extension);
2930 DCHECK(isolate->has_pending_exception() != result);
2932 // We print out the name of the extension that fail to install.
2933 // When an error is thrown during bootstrapping we automatically print
2934 // the line number at which this happened to the console in the isolate
2935 // error throwing functionality.
2936 base::OS::PrintError("Error installing extension '%s'.\n",
2937 current->extension()->name());
2938 isolate->clear_pending_exception();
2940 extension_states->set_state(current, INSTALLED);
2941 isolate->NotifyExtensionInstalled();
2946 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2947 HandleScope scope(isolate());
2948 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2949 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2950 Handle<Object> function_object = Object::GetProperty(
2951 isolate(), builtins, Builtins::GetName(id)).ToHandleChecked();
2952 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2953 builtins->set_javascript_builtin(id, *function);
2959 bool Genesis::ConfigureGlobalObjects(
2960 v8::Local<v8::ObjectTemplate> global_proxy_template) {
2961 Handle<JSObject> global_proxy(
2962 JSObject::cast(native_context()->global_proxy()));
2963 Handle<JSObject> global_object(
2964 JSObject::cast(native_context()->global_object()));
2966 if (!global_proxy_template.IsEmpty()) {
2967 // Configure the global proxy object.
2968 Handle<ObjectTemplateInfo> global_proxy_data =
2969 v8::Utils::OpenHandle(*global_proxy_template);
2970 if (!ConfigureApiObject(global_proxy, global_proxy_data)) return false;
2972 // Configure the global object.
2973 Handle<FunctionTemplateInfo> proxy_constructor(
2974 FunctionTemplateInfo::cast(global_proxy_data->constructor()));
2975 if (!proxy_constructor->prototype_template()->IsUndefined()) {
2976 Handle<ObjectTemplateInfo> global_object_data(
2977 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2978 if (!ConfigureApiObject(global_object, global_object_data)) return false;
2982 SetObjectPrototype(global_proxy, global_object);
2984 native_context()->set_initial_array_prototype(
2985 JSArray::cast(native_context()->array_function()->prototype()));
2986 native_context()->set_array_buffer_map(
2987 native_context()->array_buffer_fun()->initial_map());
2988 native_context()->set_js_map_map(
2989 native_context()->js_map_fun()->initial_map());
2990 native_context()->set_js_set_map(
2991 native_context()->js_set_fun()->initial_map());
2997 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
2998 Handle<ObjectTemplateInfo> object_template) {
2999 DCHECK(!object_template.is_null());
3000 DCHECK(FunctionTemplateInfo::cast(object_template->constructor())
3001 ->IsTemplateFor(object->map()));;
3003 MaybeHandle<JSObject> maybe_obj =
3004 ApiNatives::InstantiateObject(object_template);
3005 Handle<JSObject> obj;
3006 if (!maybe_obj.ToHandle(&obj)) {
3007 DCHECK(isolate()->has_pending_exception());
3008 isolate()->clear_pending_exception();
3011 TransferObject(obj, object);
3016 void Genesis::TransferNamedProperties(Handle<JSObject> from,
3017 Handle<JSObject> to) {
3018 // If JSObject::AddProperty asserts due to already existing property,
3019 // it is likely due to both global objects sharing property name(s).
3020 // Merging those two global objects is impossible.
3021 // The global template must not create properties that already exist
3022 // in the snapshotted global object.
3023 if (from->HasFastProperties()) {
3024 Handle<DescriptorArray> descs =
3025 Handle<DescriptorArray>(from->map()->instance_descriptors());
3026 for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
3027 PropertyDetails details = descs->GetDetails(i);
3028 switch (details.type()) {
3030 HandleScope inner(isolate());
3031 Handle<Name> key = Handle<Name>(descs->GetKey(i));
3032 FieldIndex index = FieldIndex::ForDescriptor(from->map(), i);
3033 DCHECK(!descs->GetDetails(i).representation().IsDouble());
3034 Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
3036 JSObject::AddProperty(to, key, value, details.attributes());
3039 case DATA_CONSTANT: {
3040 HandleScope inner(isolate());
3041 Handle<Name> key = Handle<Name>(descs->GetKey(i));
3042 Handle<Object> constant(descs->GetConstant(i), isolate());
3043 JSObject::AddProperty(to, key, constant, details.attributes());
3048 case ACCESSOR_CONSTANT: {
3049 Handle<Name> key(descs->GetKey(i));
3050 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3051 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3052 // If the property is already there we skip it
3053 if (it.IsFound()) continue;
3054 HandleScope inner(isolate());
3055 DCHECK(!to->HasFastProperties());
3056 // Add to dictionary.
3057 Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
3058 PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
3059 PropertyCellType::kMutable);
3060 JSObject::SetNormalizedProperty(to, key, callbacks, d);
3065 } else if (from->IsGlobalObject()) {
3066 Handle<GlobalDictionary> properties =
3067 Handle<GlobalDictionary>(from->global_dictionary());
3068 int capacity = properties->Capacity();
3069 for (int i = 0; i < capacity; i++) {
3070 Object* raw_key(properties->KeyAt(i));
3071 if (properties->IsKey(raw_key)) {
3072 DCHECK(raw_key->IsName());
3073 // If the property is already there we skip it.
3074 Handle<Name> key(Name::cast(raw_key));
3075 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3076 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3077 if (it.IsFound()) continue;
3078 // Set the property.
3079 DCHECK(properties->ValueAt(i)->IsPropertyCell());
3080 Handle<PropertyCell> cell(PropertyCell::cast(properties->ValueAt(i)));
3081 Handle<Object> value(cell->value(), isolate());
3082 if (value->IsTheHole()) continue;
3083 PropertyDetails details = cell->property_details();
3084 DCHECK_EQ(kData, details.kind());
3085 JSObject::AddProperty(to, key, value, details.attributes());
3089 Handle<NameDictionary> properties =
3090 Handle<NameDictionary>(from->property_dictionary());
3091 int capacity = properties->Capacity();
3092 for (int i = 0; i < capacity; i++) {
3093 Object* raw_key(properties->KeyAt(i));
3094 if (properties->IsKey(raw_key)) {
3095 DCHECK(raw_key->IsName());
3096 // If the property is already there we skip it.
3097 Handle<Name> key(Name::cast(raw_key));
3098 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3099 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3100 if (it.IsFound()) continue;
3101 // Set the property.
3102 Handle<Object> value = Handle<Object>(properties->ValueAt(i),
3104 DCHECK(!value->IsCell());
3105 DCHECK(!value->IsTheHole());
3106 PropertyDetails details = properties->DetailsAt(i);
3107 DCHECK_EQ(kData, details.kind());
3108 JSObject::AddProperty(to, key, value, details.attributes());
3115 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
3116 Handle<JSObject> to) {
3117 // Cloning the elements array is sufficient.
3118 Handle<FixedArray> from_elements =
3119 Handle<FixedArray>(FixedArray::cast(from->elements()));
3120 Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
3121 to->set_elements(*to_elements);
3125 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
3126 HandleScope outer(isolate());
3128 DCHECK(!from->IsJSArray());
3129 DCHECK(!to->IsJSArray());
3131 TransferNamedProperties(from, to);
3132 TransferIndexedProperties(from, to);
3134 // Transfer the prototype (new map is needed).
3135 Handle<Object> proto(from->map()->prototype(), isolate());
3136 SetObjectPrototype(to, proto);
3140 void Genesis::MakeFunctionInstancePrototypeWritable() {
3141 // The maps with writable prototype are created in CreateEmptyFunction
3142 // and CreateStrictModeFunctionMaps respectively. Initially the maps are
3143 // created with read-only prototype for JS builtins processing.
3144 DCHECK(!sloppy_function_map_writable_prototype_.is_null());
3145 DCHECK(!strict_function_map_writable_prototype_.is_null());
3147 // Replace function instance maps to make prototype writable.
3148 native_context()->set_sloppy_function_map(
3149 *sloppy_function_map_writable_prototype_);
3150 native_context()->set_strict_function_map(
3151 *strict_function_map_writable_prototype_);
3155 class NoTrackDoubleFieldsForSerializerScope {
3157 explicit NoTrackDoubleFieldsForSerializerScope(Isolate* isolate)
3158 : flag_(FLAG_track_double_fields), enabled_(false) {
3159 if (isolate->serializer_enabled()) {
3160 // Disable tracking double fields because heap numbers treated as
3161 // immutable by the serializer.
3162 FLAG_track_double_fields = false;
3167 ~NoTrackDoubleFieldsForSerializerScope() {
3169 FLAG_track_double_fields = flag_;
3179 Genesis::Genesis(Isolate* isolate,
3180 MaybeHandle<JSGlobalProxy> maybe_global_proxy,
3181 v8::Local<v8::ObjectTemplate> global_proxy_template,
3182 v8::ExtensionConfiguration* extensions,
3183 ContextType context_type)
3184 : isolate_(isolate), active_(isolate->bootstrapper()) {
3185 NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
3186 result_ = Handle<Context>::null();
3187 // Before creating the roots we must save the context and restore it
3188 // on all function exits.
3189 SaveContext saved_context(isolate);
3191 // During genesis, the boilerplate for stack overflow won't work until the
3192 // environment has been at least partially initialized. Add a stack check
3193 // before entering JS code to catch overflow early.
3194 StackLimitCheck check(isolate);
3195 if (check.HasOverflowed()) {
3196 isolate->StackOverflow();
3200 // The deserializer needs to hook up references to the global proxy.
3201 // Create an uninitialized global proxy now if we don't have one
3202 // and initialize it later in CreateNewGlobals.
3203 Handle<JSGlobalProxy> global_proxy;
3204 if (!maybe_global_proxy.ToHandle(&global_proxy)) {
3205 global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy();
3208 // We can only de-serialize a context if the isolate was initialized from
3209 // a snapshot. Otherwise we have to build the context from scratch.
3210 // Also create a context from scratch to expose natives, if required by flag.
3211 Handle<FixedArray> outdated_contexts;
3212 if (!isolate->initialized_from_snapshot() ||
3213 !Snapshot::NewContextFromSnapshot(isolate, global_proxy,
3215 .ToHandle(&native_context_)) {
3216 native_context_ = Handle<Context>();
3219 if (!native_context().is_null()) {
3220 AddToWeakNativeContextList(*native_context());
3221 isolate->set_context(*native_context());
3222 isolate->counters()->contexts_created_by_snapshot()->Increment();
3224 if (FLAG_trace_maps) {
3225 Handle<JSFunction> object_fun = isolate->object_function();
3226 PrintF("[TraceMap: InitialMap map= %p SFI= %d_Object ]\n",
3227 reinterpret_cast<void*>(object_fun->initial_map()),
3228 object_fun->shared()->unique_id());
3229 Map::TraceAllTransitions(object_fun->initial_map());
3232 Handle<GlobalObject> global_object =
3233 CreateNewGlobals(global_proxy_template, global_proxy);
3235 HookUpGlobalProxy(global_object, global_proxy);
3236 HookUpGlobalObject(global_object, outdated_contexts);
3237 native_context()->builtins()->set_global_proxy(
3238 native_context()->global_proxy());
3239 HookUpGlobalThisBinding(outdated_contexts);
3241 if (!ConfigureGlobalObjects(global_proxy_template)) return;
3243 // We get here if there was no context snapshot.
3245 Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
3246 CreateStrictModeFunctionMaps(empty_function);
3247 CreateStrongModeFunctionMaps(empty_function);
3248 Handle<GlobalObject> global_object =
3249 CreateNewGlobals(global_proxy_template, global_proxy);
3250 HookUpGlobalProxy(global_object, global_proxy);
3251 InitializeGlobal(global_object, empty_function, context_type);
3252 InstallJSFunctionResultCaches();
3253 InitializeNormalizedMapCaches();
3255 if (!InstallNatives(context_type)) return;
3257 MakeFunctionInstancePrototypeWritable();
3259 if (context_type == FULL_CONTEXT) {
3260 if (!ConfigureGlobalObjects(global_proxy_template)) return;
3262 isolate->counters()->contexts_created_from_scratch()->Increment();
3265 // Install experimental and extra natives. Do not include them into the
3266 // snapshot as we should be able to turn them off at runtime. Re-installing
3267 // them after they have already been deserialized would also fail.
3268 if (context_type == FULL_CONTEXT) {
3269 if (!isolate->serializer_enabled()) {
3270 InitializeExperimentalGlobal();
3271 if (!InstallExperimentalNatives()) return;
3272 if (!InstallExtraNatives()) return;
3275 // The serializer cannot serialize typed arrays. Reset those typed arrays
3276 // for each new context.
3277 InitializeBuiltinTypedArrays();
3280 result_ = native_context();
3284 // Support for thread preemption.
3286 // Reserve space for statics needing saving and restoring.
3287 int Bootstrapper::ArchiveSpacePerThread() {
3288 return sizeof(NestingCounterType);
3292 // Archive statics that are thread-local.
3293 char* Bootstrapper::ArchiveState(char* to) {
3294 *reinterpret_cast<NestingCounterType*>(to) = nesting_;
3296 return to + sizeof(NestingCounterType);
3300 // Restore statics that are thread-local.
3301 char* Bootstrapper::RestoreState(char* from) {
3302 nesting_ = *reinterpret_cast<NestingCounterType*>(from);
3303 return from + sizeof(NestingCounterType);
3307 // Called when the top-level V8 mutex is destroyed.
3308 void Bootstrapper::FreeThreadResources() {
3309 DCHECK(!IsActive());
3312 } // namespace internal