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(
240 ElementsKind elements_kind,
241 Handle<JSFunction>* fun,
242 Handle<Map>* external_map);
243 bool InstallExperimentalNatives();
244 bool InstallExtraNatives();
245 void InstallBuiltinFunctionIds();
246 void InstallExperimentalBuiltinFunctionIds();
247 void InstallJSFunctionResultCaches();
248 void InitializeNormalizedMapCaches();
250 enum ExtensionTraversalState {
251 UNVISITED, VISITED, INSTALLED
254 class ExtensionStates {
257 ExtensionTraversalState get_state(RegisteredExtension* extension);
258 void set_state(RegisteredExtension* extension,
259 ExtensionTraversalState state);
262 DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
265 // Used both for deserialized and from-scratch contexts to add the extensions
267 static bool InstallExtensions(Handle<Context> native_context,
268 v8::ExtensionConfiguration* extensions);
269 static bool InstallAutoExtensions(Isolate* isolate,
270 ExtensionStates* extension_states);
271 static bool InstallRequestedExtensions(Isolate* isolate,
272 v8::ExtensionConfiguration* extensions,
273 ExtensionStates* extension_states);
274 static bool InstallExtension(Isolate* isolate,
276 ExtensionStates* extension_states);
277 static bool InstallExtension(Isolate* isolate,
278 v8::RegisteredExtension* current,
279 ExtensionStates* extension_states);
280 static bool InstallSpecialObjects(Handle<Context> native_context);
281 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
282 bool ConfigureApiObject(Handle<JSObject> object,
283 Handle<ObjectTemplateInfo> object_template);
284 bool ConfigureGlobalObjects(
285 v8::Local<v8::ObjectTemplate> global_proxy_template);
287 // Migrates all properties from the 'from' object to the 'to'
288 // object and overrides the prototype in 'to' with the one from
290 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
291 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
292 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
296 FUNCTION_WITH_WRITEABLE_PROTOTYPE,
297 FUNCTION_WITH_READONLY_PROTOTYPE,
298 // Without prototype.
299 FUNCTION_WITHOUT_PROTOTYPE,
303 static bool IsFunctionModeWithPrototype(FunctionMode function_mode) {
304 return (function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ||
305 function_mode == FUNCTION_WITH_READONLY_PROTOTYPE);
308 Handle<Map> CreateSloppyFunctionMap(FunctionMode function_mode);
310 void SetFunctionInstanceDescriptor(Handle<Map> map,
311 FunctionMode function_mode);
312 void MakeFunctionInstancePrototypeWritable();
314 Handle<Map> CreateStrictFunctionMap(FunctionMode function_mode,
315 Handle<JSFunction> empty_function);
316 Handle<Map> CreateStrongFunctionMap(Handle<JSFunction> empty_function,
317 bool is_constructor);
320 void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
321 FunctionMode function_mode);
322 void SetStrongFunctionInstanceDescriptor(Handle<Map> map);
324 static bool CompileBuiltin(Isolate* isolate, int index);
325 static bool CompileExperimentalBuiltin(Isolate* isolate, int index);
326 static bool CompileExtraBuiltin(Isolate* isolate, int index);
327 static bool CompileNative(Isolate* isolate, Vector<const char> name,
328 Handle<String> source, int argc,
329 Handle<Object> argv[]);
331 static bool CallUtilsFunction(Isolate* isolate, const char* name);
333 static bool CompileExtension(Isolate* isolate, v8::Extension* extension);
336 Handle<Context> result_;
337 Handle<Context> native_context_;
339 // Function maps. Function maps are created initially with a read only
340 // prototype for the processing of JS builtins. Later the function maps are
341 // replaced in order to make prototype writable. These are the final, writable
343 Handle<Map> sloppy_function_map_writable_prototype_;
344 Handle<Map> strict_function_map_writable_prototype_;
345 Handle<JSFunction> strict_poison_function_;
346 Handle<JSFunction> restricted_function_properties_thrower_;
348 BootstrapperActive active_;
349 friend class Bootstrapper;
353 void Bootstrapper::Iterate(ObjectVisitor* v) {
354 extensions_cache_.Iterate(v);
355 v->Synchronize(VisitorSynchronization::kExtensions);
359 Handle<Context> Bootstrapper::CreateEnvironment(
360 MaybeHandle<JSGlobalProxy> maybe_global_proxy,
361 v8::Local<v8::ObjectTemplate> global_proxy_template,
362 v8::ExtensionConfiguration* extensions, ContextType context_type) {
363 HandleScope scope(isolate_);
364 Genesis genesis(isolate_, maybe_global_proxy, global_proxy_template,
365 extensions, context_type);
366 Handle<Context> env = genesis.result();
368 (context_type == FULL_CONTEXT && !InstallExtensions(env, extensions))) {
369 return Handle<Context>();
371 return scope.CloseAndEscape(env);
375 bool Bootstrapper::CreateCodeStubContext(Isolate* isolate) {
376 HandleScope scope(isolate);
377 SaveContext save_context(isolate);
378 BootstrapperActive active(this);
380 v8::ExtensionConfiguration no_extensions;
381 Handle<Context> native_context = CreateEnvironment(
382 MaybeHandle<JSGlobalProxy>(), v8::Local<v8::ObjectTemplate>(),
383 &no_extensions, THIN_CONTEXT);
384 isolate->heap()->set_code_stub_context(*native_context);
385 isolate->set_context(*native_context);
386 Handle<JSObject> code_stub_exports =
387 isolate->factory()->NewJSObject(isolate->object_function());
388 JSObject::NormalizeProperties(code_stub_exports, CLEAR_INOBJECT_PROPERTIES, 2,
389 "container to export to extra natives");
390 isolate->heap()->set_code_stub_exports_object(*code_stub_exports);
391 return InstallCodeStubNatives(isolate);
395 static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
396 // object.__proto__ = proto;
397 Handle<Map> old_map = Handle<Map>(object->map());
398 Handle<Map> new_map = Map::Copy(old_map, "SetObjectPrototype");
399 Map::SetPrototype(new_map, proto, FAST_PROTOTYPE);
400 JSObject::MigrateToMap(object, new_map);
404 void Bootstrapper::DetachGlobal(Handle<Context> env) {
405 Factory* factory = env->GetIsolate()->factory();
406 Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
407 global_proxy->set_native_context(*factory->null_value());
408 SetObjectPrototype(global_proxy, factory->null_value());
409 global_proxy->map()->SetConstructor(*factory->null_value());
410 if (FLAG_track_detached_contexts) {
411 env->GetIsolate()->AddDetachedContext(env);
416 static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
417 const char* name, InstanceType type,
419 MaybeHandle<JSObject> maybe_prototype,
421 bool strict_function_map = false) {
422 Isolate* isolate = target->GetIsolate();
423 Factory* factory = isolate->factory();
424 Handle<String> internalized_name = factory->InternalizeUtf8String(name);
425 Handle<Code> call_code = Handle<Code>(isolate->builtins()->builtin(call));
426 Handle<JSObject> prototype;
427 static const bool kReadOnlyPrototype = false;
428 static const bool kInstallConstructor = false;
429 Handle<JSFunction> function =
430 maybe_prototype.ToHandle(&prototype)
431 ? factory->NewFunction(internalized_name, call_code, prototype, type,
432 instance_size, kReadOnlyPrototype,
433 kInstallConstructor, strict_function_map)
434 : factory->NewFunctionWithoutPrototype(internalized_name, call_code,
435 strict_function_map);
436 PropertyAttributes attributes;
437 if (target->IsJSBuiltinsObject()) {
439 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
441 attributes = DONT_ENUM;
443 JSObject::AddProperty(target, internalized_name, function, attributes);
444 if (target->IsJSGlobalObject()) {
445 function->shared()->set_instance_class_name(*internalized_name);
447 function->shared()->set_native(true);
452 void Genesis::SetFunctionInstanceDescriptor(Handle<Map> map,
453 FunctionMode function_mode) {
454 int size = IsFunctionModeWithPrototype(function_mode) ? 5 : 4;
455 Map::EnsureDescriptorSlack(map, size);
457 PropertyAttributes ro_attribs =
458 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
459 PropertyAttributes roc_attribs =
460 static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
462 Handle<AccessorInfo> length =
463 Accessors::FunctionLengthInfo(isolate(), roc_attribs);
465 AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
466 length, roc_attribs);
467 map->AppendDescriptor(&d);
469 Handle<AccessorInfo> name =
470 Accessors::FunctionNameInfo(isolate(), ro_attribs);
472 AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
474 map->AppendDescriptor(&d);
476 Handle<AccessorInfo> args =
477 Accessors::FunctionArgumentsInfo(isolate(), ro_attribs);
479 AccessorConstantDescriptor d(Handle<Name>(Name::cast(args->name())), args,
481 map->AppendDescriptor(&d);
483 Handle<AccessorInfo> caller =
484 Accessors::FunctionCallerInfo(isolate(), ro_attribs);
486 AccessorConstantDescriptor d(Handle<Name>(Name::cast(caller->name())),
488 map->AppendDescriptor(&d);
490 if (IsFunctionModeWithPrototype(function_mode)) {
491 if (function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE) {
492 ro_attribs = static_cast<PropertyAttributes>(ro_attribs & ~READ_ONLY);
494 Handle<AccessorInfo> prototype =
495 Accessors::FunctionPrototypeInfo(isolate(), ro_attribs);
496 AccessorConstantDescriptor d(Handle<Name>(Name::cast(prototype->name())),
497 prototype, ro_attribs);
498 map->AppendDescriptor(&d);
503 Handle<Map> Genesis::CreateSloppyFunctionMap(FunctionMode function_mode) {
504 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
505 SetFunctionInstanceDescriptor(map, function_mode);
506 map->set_function_with_prototype(IsFunctionModeWithPrototype(function_mode));
511 Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
512 // Allocate the map for function instances. Maps are allocated first and their
513 // prototypes patched later, once empty function is created.
515 // Functions with this map will not have a 'prototype' property, and
516 // can not be used as constructors.
517 Handle<Map> function_without_prototype_map =
518 CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
519 native_context()->set_sloppy_function_without_prototype_map(
520 *function_without_prototype_map);
522 // Allocate the function map. This map is temporary, used only for processing
524 // Later the map is replaced with writable prototype map, allocated below.
525 Handle<Map> function_map =
526 CreateSloppyFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE);
527 native_context()->set_sloppy_function_map(*function_map);
528 native_context()->set_sloppy_function_with_readonly_prototype_map(
531 // The final map for functions. Writeable prototype.
532 // This map is installed in MakeFunctionInstancePrototypeWritable.
533 sloppy_function_map_writable_prototype_ =
534 CreateSloppyFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE);
535 Factory* factory = isolate->factory();
537 Handle<String> object_name = factory->Object_string();
539 Handle<JSObject> object_function_prototype;
541 { // --- O b j e c t ---
542 Handle<JSFunction> object_fun = factory->NewFunction(object_name);
543 int unused = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
544 int instance_size = JSObject::kHeaderSize + kPointerSize * unused;
545 Handle<Map> object_function_map =
546 factory->NewMap(JS_OBJECT_TYPE, instance_size);
547 object_function_map->set_inobject_properties(unused);
548 JSFunction::SetInitialMap(object_fun, object_function_map,
549 isolate->factory()->null_value());
550 object_function_map->set_unused_property_fields(unused);
552 native_context()->set_object_function(*object_fun);
554 // Allocate a new prototype for the object function.
555 object_function_prototype =
556 factory->NewJSObject(isolate->object_function(), TENURED);
557 Handle<Map> map = Map::Copy(handle(object_function_prototype->map()),
558 "EmptyObjectPrototype");
559 map->set_is_prototype_map(true);
560 object_function_prototype->set_map(*map);
562 native_context()->set_initial_object_prototype(*object_function_prototype);
563 // For bootstrapping set the array prototype to be the same as the object
564 // prototype, otherwise the missing initial_array_prototype will cause
565 // assertions during startup.
566 native_context()->set_initial_array_prototype(*object_function_prototype);
567 Accessors::FunctionSetPrototype(object_fun, object_function_prototype)
570 // Allocate initial strong object map.
571 Handle<Map> strong_object_map =
572 Map::Copy(Handle<Map>(object_fun->initial_map()), "EmptyStrongObject");
573 strong_object_map->set_is_strong();
574 native_context()->set_js_object_strong_map(*strong_object_map);
577 // Allocate the empty function as the prototype for function - ES6 19.2.3
578 Handle<Code> code(isolate->builtins()->builtin(Builtins::kEmptyFunction));
579 Handle<JSFunction> empty_function =
580 factory->NewFunctionWithoutPrototype(factory->empty_string(), code);
582 // Allocate the function map first and then patch the prototype later
583 Handle<Map> empty_function_map =
584 CreateSloppyFunctionMap(FUNCTION_WITHOUT_PROTOTYPE);
585 DCHECK(!empty_function_map->is_dictionary_map());
586 Map::SetPrototype(empty_function_map, object_function_prototype);
587 empty_function_map->set_is_prototype_map(true);
589 empty_function->set_map(*empty_function_map);
592 Handle<String> source = factory->NewStringFromStaticChars("() {}");
593 Handle<Script> script = factory->NewScript(source);
594 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
595 empty_function->shared()->set_start_position(0);
596 empty_function->shared()->set_end_position(source->length());
597 empty_function->shared()->DontAdaptArguments();
598 SharedFunctionInfo::SetScript(handle(empty_function->shared()), script);
600 // Set prototypes for the function maps.
601 Handle<Map> sloppy_function_map(native_context()->sloppy_function_map(),
603 Handle<Map> sloppy_function_without_prototype_map(
604 native_context()->sloppy_function_without_prototype_map(), isolate);
605 Map::SetPrototype(sloppy_function_map, empty_function);
606 Map::SetPrototype(sloppy_function_without_prototype_map, empty_function);
607 Map::SetPrototype(sloppy_function_map_writable_prototype_, empty_function);
609 // ES6 draft 03-17-2015, section 8.2.2 step 12
610 AddRestrictedFunctionProperties(empty_function_map);
612 return empty_function;
616 void Genesis::SetStrictFunctionInstanceDescriptor(Handle<Map> map,
617 FunctionMode function_mode) {
618 int size = IsFunctionModeWithPrototype(function_mode) ? 5 : 4;
619 Map::EnsureDescriptorSlack(map, size);
621 PropertyAttributes rw_attribs =
622 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
623 PropertyAttributes ro_attribs =
624 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
625 PropertyAttributes roc_attribs =
626 static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
628 if (function_mode == BOUND_FUNCTION) {
630 Handle<String> length_string = isolate()->factory()->length_string();
631 DataDescriptor d(length_string, 0, roc_attribs, Representation::Tagged());
632 map->AppendDescriptor(&d);
635 Handle<String> name_string = isolate()->factory()->name_string();
636 DataDescriptor d(name_string, 1, roc_attribs, Representation::Tagged());
637 map->AppendDescriptor(&d);
640 DCHECK(function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ||
641 function_mode == FUNCTION_WITH_READONLY_PROTOTYPE ||
642 function_mode == FUNCTION_WITHOUT_PROTOTYPE);
644 Handle<AccessorInfo> length =
645 Accessors::FunctionLengthInfo(isolate(), roc_attribs);
646 AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
647 length, roc_attribs);
648 map->AppendDescriptor(&d);
651 Handle<AccessorInfo> name =
652 Accessors::FunctionNameInfo(isolate(), roc_attribs);
653 AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
655 map->AppendDescriptor(&d);
658 if (IsFunctionModeWithPrototype(function_mode)) {
660 PropertyAttributes attribs =
661 function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ? rw_attribs
663 Handle<AccessorInfo> prototype =
664 Accessors::FunctionPrototypeInfo(isolate(), attribs);
665 AccessorConstantDescriptor d(Handle<Name>(Name::cast(prototype->name())),
667 map->AppendDescriptor(&d);
672 void Genesis::SetStrongFunctionInstanceDescriptor(Handle<Map> map) {
673 Map::EnsureDescriptorSlack(map, 2);
675 PropertyAttributes ro_attribs =
676 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
678 Handle<AccessorInfo> length =
679 Accessors::FunctionLengthInfo(isolate(), ro_attribs);
681 AccessorConstantDescriptor d(Handle<Name>(Name::cast(length->name())),
683 map->AppendDescriptor(&d);
685 Handle<AccessorInfo> name =
686 Accessors::FunctionNameInfo(isolate(), ro_attribs);
688 AccessorConstantDescriptor d(Handle<Name>(Name::cast(name->name())), name,
690 map->AppendDescriptor(&d);
695 // Creates the %ThrowTypeError% function.
696 Handle<JSFunction> Genesis::GetThrowTypeErrorIntrinsic(
697 Builtins::Name builtin_name) {
698 Handle<String> name =
699 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("ThrowTypeError"));
700 Handle<Code> code(isolate()->builtins()->builtin(builtin_name));
701 Handle<JSFunction> function =
702 factory()->NewFunctionWithoutPrototype(name, code);
703 function->set_map(native_context()->sloppy_function_map());
704 function->shared()->DontAdaptArguments();
706 // %ThrowTypeError% must not have a name property.
707 JSReceiver::DeleteProperty(function, factory()->name_string()).Assert();
709 // length needs to be non configurable.
710 Handle<Object> value(Smi::FromInt(function->shared()->length()), isolate());
711 JSObject::SetOwnPropertyIgnoreAttributes(
712 function, factory()->length_string(), value,
713 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY))
716 JSObject::PreventExtensions(function).Assert();
722 // ECMAScript 5th Edition, 13.2.3
723 Handle<JSFunction> Genesis::GetRestrictedFunctionPropertiesThrower() {
724 if (restricted_function_properties_thrower_.is_null()) {
725 restricted_function_properties_thrower_ = GetThrowTypeErrorIntrinsic(
726 Builtins::kRestrictedFunctionPropertiesThrower);
728 return restricted_function_properties_thrower_;
732 Handle<JSFunction> Genesis::GetStrictArgumentsPoisonFunction() {
733 if (strict_poison_function_.is_null()) {
734 strict_poison_function_ = GetThrowTypeErrorIntrinsic(
735 Builtins::kRestrictedStrictArgumentsPropertiesThrower);
737 return strict_poison_function_;
741 Handle<Map> Genesis::CreateStrictFunctionMap(
742 FunctionMode function_mode, Handle<JSFunction> empty_function) {
743 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
744 SetStrictFunctionInstanceDescriptor(map, function_mode);
745 map->set_function_with_prototype(IsFunctionModeWithPrototype(function_mode));
746 Map::SetPrototype(map, empty_function);
751 Handle<Map> Genesis::CreateStrongFunctionMap(
752 Handle<JSFunction> empty_function, bool is_constructor) {
753 Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
754 SetStrongFunctionInstanceDescriptor(map);
755 map->set_function_with_prototype(is_constructor);
756 Map::SetPrototype(map, empty_function);
757 map->set_is_extensible(is_constructor);
758 map->set_is_strong();
763 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
764 // Allocate map for the prototype-less strict mode instances.
765 Handle<Map> strict_function_without_prototype_map =
766 CreateStrictFunctionMap(FUNCTION_WITHOUT_PROTOTYPE, empty);
767 native_context()->set_strict_function_without_prototype_map(
768 *strict_function_without_prototype_map);
770 // Allocate map for the strict mode functions. This map is temporary, used
771 // only for processing of builtins.
772 // Later the map is replaced with writable prototype map, allocated below.
773 Handle<Map> strict_function_map =
774 CreateStrictFunctionMap(FUNCTION_WITH_READONLY_PROTOTYPE, empty);
775 native_context()->set_strict_function_map(*strict_function_map);
777 // The final map for the strict mode functions. Writeable prototype.
778 // This map is installed in MakeFunctionInstancePrototypeWritable.
779 strict_function_map_writable_prototype_ =
780 CreateStrictFunctionMap(FUNCTION_WITH_WRITEABLE_PROTOTYPE, empty);
782 // Special map for bound functions.
783 Handle<Map> bound_function_map =
784 CreateStrictFunctionMap(BOUND_FUNCTION, empty);
785 native_context()->set_bound_function_map(*bound_function_map);
789 void Genesis::CreateStrongModeFunctionMaps(Handle<JSFunction> empty) {
790 // Allocate map for strong mode instances, which never have prototypes.
791 Handle<Map> strong_function_map = CreateStrongFunctionMap(empty, false);
792 native_context()->set_strong_function_map(*strong_function_map);
793 // Constructors do, though.
794 Handle<Map> strong_constructor_map = CreateStrongFunctionMap(empty, true);
795 native_context()->set_strong_constructor_map(*strong_constructor_map);
799 static void ReplaceAccessors(Handle<Map> map,
801 PropertyAttributes attributes,
802 Handle<AccessorPair> accessor_pair) {
803 DescriptorArray* descriptors = map->instance_descriptors();
804 int idx = descriptors->SearchWithCache(*name, *map);
805 AccessorConstantDescriptor descriptor(name, accessor_pair, attributes);
806 descriptors->Replace(idx, &descriptor);
810 void Genesis::AddRestrictedFunctionProperties(Handle<Map> map) {
811 PropertyAttributes rw_attribs = static_cast<PropertyAttributes>(DONT_ENUM);
812 Handle<JSFunction> thrower = GetRestrictedFunctionPropertiesThrower();
813 Handle<AccessorPair> accessors = factory()->NewAccessorPair();
814 accessors->set_getter(*thrower);
815 accessors->set_setter(*thrower);
817 ReplaceAccessors(map, factory()->arguments_string(), rw_attribs, accessors);
818 ReplaceAccessors(map, factory()->caller_string(), rw_attribs, accessors);
822 static void AddToWeakNativeContextList(Context* context) {
823 DCHECK(context->IsNativeContext());
824 Heap* heap = context->GetIsolate()->heap();
827 DCHECK(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
828 // Check that context is not in the list yet.
829 for (Object* current = heap->native_contexts_list();
830 !current->IsUndefined();
831 current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
832 DCHECK(current != context);
836 context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list(),
837 UPDATE_WEAK_WRITE_BARRIER);
838 heap->set_native_contexts_list(context);
842 void Genesis::CreateRoots() {
843 // Allocate the native context FixedArray first and then patch the
844 // closure and extension object later (we need the empty function
845 // and the global object, but in order to create those, we need the
847 native_context_ = factory()->NewNativeContext();
848 AddToWeakNativeContextList(*native_context());
849 isolate()->set_context(*native_context());
851 // Allocate the message listeners object.
853 v8::NeanderArray listeners(isolate());
854 native_context()->set_message_listeners(*listeners.value());
859 void Genesis::InstallGlobalThisBinding() {
860 Handle<ScriptContextTable> script_contexts(
861 native_context()->script_context_table());
862 Handle<ScopeInfo> scope_info = ScopeInfo::CreateGlobalThisBinding(isolate());
863 Handle<JSFunction> closure(native_context()->closure());
864 Handle<Context> context = factory()->NewScriptContext(closure, scope_info);
866 // Go ahead and hook it up while we're at it.
867 int slot = scope_info->ReceiverContextSlotIndex();
868 DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
869 context->set(slot, native_context()->global_proxy());
871 Handle<ScriptContextTable> new_script_contexts =
872 ScriptContextTable::Extend(script_contexts, context);
873 native_context()->set_script_context_table(*new_script_contexts);
877 void Genesis::HookUpGlobalThisBinding(Handle<FixedArray> outdated_contexts) {
878 // One of these contexts should be the one that declares the global "this"
880 for (int i = 0; i < outdated_contexts->length(); ++i) {
881 Context* context = Context::cast(outdated_contexts->get(i));
882 if (context->IsScriptContext()) {
883 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
884 int slot = scope_info->ReceiverContextSlotIndex();
886 DCHECK_EQ(slot, Context::MIN_CONTEXT_SLOTS);
887 context->set(slot, native_context()->global_proxy());
894 Handle<GlobalObject> Genesis::CreateNewGlobals(
895 v8::Local<v8::ObjectTemplate> global_proxy_template,
896 Handle<JSGlobalProxy> global_proxy) {
897 // The argument global_proxy_template aka data is an ObjectTemplateInfo.
898 // It has a constructor pointer that points at global_constructor which is a
899 // FunctionTemplateInfo.
900 // The global_proxy_constructor is used to (re)initialize the
901 // global_proxy. The global_proxy_constructor also has a prototype_template
902 // pointer that points at js_global_object_template which is an
903 // ObjectTemplateInfo.
904 // That in turn has a constructor pointer that points at
905 // js_global_object_constructor which is a FunctionTemplateInfo.
906 // js_global_object_constructor is used to make js_global_object_function
907 // js_global_object_function is used to make the new global_object.
909 // --- G l o b a l ---
910 // Step 1: Create a fresh JSGlobalObject.
911 Handle<JSFunction> js_global_object_function;
912 Handle<ObjectTemplateInfo> js_global_object_template;
913 if (!global_proxy_template.IsEmpty()) {
914 // Get prototype template of the global_proxy_template.
915 Handle<ObjectTemplateInfo> data =
916 v8::Utils::OpenHandle(*global_proxy_template);
917 Handle<FunctionTemplateInfo> global_constructor =
918 Handle<FunctionTemplateInfo>(
919 FunctionTemplateInfo::cast(data->constructor()));
920 Handle<Object> proto_template(global_constructor->prototype_template(),
922 if (!proto_template->IsUndefined()) {
923 js_global_object_template =
924 Handle<ObjectTemplateInfo>::cast(proto_template);
928 if (js_global_object_template.is_null()) {
929 Handle<String> name = Handle<String>(heap()->empty_string());
930 Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
931 Builtins::kIllegal));
932 Handle<JSObject> prototype =
933 factory()->NewFunctionPrototype(isolate()->object_function());
934 js_global_object_function = factory()->NewFunction(
935 name, code, prototype, JS_GLOBAL_OBJECT_TYPE, JSGlobalObject::kSize);
937 LookupIterator it(prototype, factory()->constructor_string(),
938 LookupIterator::OWN_SKIP_INTERCEPTOR);
939 Handle<Object> value = JSReceiver::GetProperty(&it).ToHandleChecked();
940 DCHECK(it.IsFound());
941 DCHECK_EQ(*isolate()->object_function(), *value);
944 Handle<FunctionTemplateInfo> js_global_object_constructor(
945 FunctionTemplateInfo::cast(js_global_object_template->constructor()));
946 js_global_object_function = ApiNatives::CreateApiFunction(
947 isolate(), js_global_object_constructor, factory()->the_hole_value(),
948 ApiNatives::GlobalObjectType);
951 js_global_object_function->initial_map()->set_is_prototype_map(true);
952 js_global_object_function->initial_map()->set_is_hidden_prototype();
953 js_global_object_function->initial_map()->set_dictionary_map(true);
954 Handle<GlobalObject> global_object =
955 factory()->NewGlobalObject(js_global_object_function);
957 // Step 2: (re)initialize the global proxy object.
958 Handle<JSFunction> global_proxy_function;
959 if (global_proxy_template.IsEmpty()) {
960 Handle<String> name = Handle<String>(heap()->empty_string());
961 Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
962 Builtins::kIllegal));
963 global_proxy_function = factory()->NewFunction(
964 name, code, JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
966 Handle<ObjectTemplateInfo> data =
967 v8::Utils::OpenHandle(*global_proxy_template);
968 Handle<FunctionTemplateInfo> global_constructor(
969 FunctionTemplateInfo::cast(data->constructor()));
970 global_proxy_function = ApiNatives::CreateApiFunction(
971 isolate(), global_constructor, factory()->the_hole_value(),
972 ApiNatives::GlobalProxyType);
975 Handle<String> global_name = factory()->global_string();
976 global_proxy_function->shared()->set_instance_class_name(*global_name);
977 global_proxy_function->initial_map()->set_is_access_check_needed(true);
979 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
980 // Return the global proxy.
982 factory()->ReinitializeJSGlobalProxy(global_proxy, global_proxy_function);
983 return global_object;
987 void Genesis::HookUpGlobalProxy(Handle<GlobalObject> global_object,
988 Handle<JSGlobalProxy> global_proxy) {
989 // Set the native context for the global object.
990 global_object->set_native_context(*native_context());
991 global_object->set_global_proxy(*global_proxy);
992 global_proxy->set_native_context(*native_context());
993 // If we deserialized the context, the global proxy is already
994 // correctly set up. Otherwise it's undefined.
995 DCHECK(native_context()->get(Context::GLOBAL_PROXY_INDEX)->IsUndefined() ||
996 native_context()->global_proxy() == *global_proxy);
997 native_context()->set_global_proxy(*global_proxy);
1001 void Genesis::HookUpGlobalObject(Handle<GlobalObject> global_object,
1002 Handle<FixedArray> outdated_contexts) {
1003 Handle<GlobalObject> global_object_from_snapshot(
1004 GlobalObject::cast(native_context()->extension()));
1005 Handle<JSBuiltinsObject> builtins_global(native_context()->builtins());
1006 native_context()->set_extension(*global_object);
1007 native_context()->set_security_token(*global_object);
1009 // Replace outdated global objects in deserialized contexts.
1010 for (int i = 0; i < outdated_contexts->length(); ++i) {
1011 Context* context = Context::cast(outdated_contexts->get(i));
1012 // Assert that there is only one native context.
1013 DCHECK(!context->IsNativeContext() || context == *native_context());
1014 DCHECK_EQ(context->global_object(), *global_object_from_snapshot);
1015 context->set_global_object(*global_object);
1018 static const PropertyAttributes attributes =
1019 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1020 JSObject::SetOwnPropertyIgnoreAttributes(builtins_global,
1021 factory()->global_string(),
1022 global_object, attributes).Assert();
1023 // Set up the reference from the global object to the builtins object.
1024 JSGlobalObject::cast(*global_object)->set_builtins(*builtins_global);
1025 TransferNamedProperties(global_object_from_snapshot, global_object);
1026 TransferIndexedProperties(global_object_from_snapshot, global_object);
1030 // This is only called if we are not using snapshots. The equivalent
1031 // work in the snapshot case is done in HookUpGlobalObject.
1032 void Genesis::InitializeGlobal(Handle<GlobalObject> global_object,
1033 Handle<JSFunction> empty_function,
1034 ContextType context_type) {
1035 // --- N a t i v e C o n t e x t ---
1036 // Use the empty function as closure (no scope info).
1037 native_context()->set_closure(*empty_function);
1038 native_context()->set_previous(NULL);
1039 // Set extension and global object.
1040 native_context()->set_extension(*global_object);
1041 native_context()->set_global_object(*global_object);
1042 // Security setup: Set the security token of the native context to the global
1043 // object. This makes the security check between two different contexts fail
1044 // by default even in case of global object reinitialization.
1045 native_context()->set_security_token(*global_object);
1047 Isolate* isolate = global_object->GetIsolate();
1048 Factory* factory = isolate->factory();
1049 Heap* heap = isolate->heap();
1051 Handle<ScriptContextTable> script_context_table =
1052 factory->NewScriptContextTable();
1053 native_context()->set_script_context_table(*script_context_table);
1054 InstallGlobalThisBinding();
1056 Handle<String> object_name = factory->Object_string();
1057 JSObject::AddProperty(
1058 global_object, object_name, isolate->object_function(), DONT_ENUM);
1060 Handle<JSObject> global(native_context()->global_object());
1062 // Install global Function object
1063 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
1064 empty_function, Builtins::kIllegal);
1066 { // --- A r r a y ---
1067 Handle<JSFunction> array_function =
1068 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
1069 isolate->initial_object_prototype(),
1070 Builtins::kArrayCode);
1071 array_function->shared()->DontAdaptArguments();
1072 array_function->shared()->set_function_data(Smi::FromInt(kArrayCode));
1074 // This seems a bit hackish, but we need to make sure Array.length
1076 array_function->shared()->set_length(1);
1078 Handle<Map> initial_map(array_function->initial_map());
1080 // This assert protects an optimization in
1081 // HGraphBuilder::JSArrayBuilder::EmitMapCode()
1082 DCHECK(initial_map->elements_kind() == GetInitialFastElementsKind());
1083 Map::EnsureDescriptorSlack(initial_map, 1);
1085 PropertyAttributes attribs = static_cast<PropertyAttributes>(
1086 DONT_ENUM | DONT_DELETE);
1088 Handle<AccessorInfo> array_length =
1089 Accessors::ArrayLengthInfo(isolate, attribs);
1091 AccessorConstantDescriptor d(
1092 Handle<Name>(Name::cast(array_length->name())), array_length,
1094 initial_map->AppendDescriptor(&d);
1097 // array_function is used internally. JS code creating array object should
1098 // search for the 'Array' property on the global object and use that one
1099 // as the constructor. 'Array' property on a global object can be
1100 // overwritten by JS code.
1101 native_context()->set_array_function(*array_function);
1103 // Cache the array maps, needed by ArrayConstructorStub
1104 CacheInitialJSArrayMaps(native_context(), initial_map);
1105 ArrayConstructorStub array_constructor_stub(isolate);
1106 Handle<Code> code = array_constructor_stub.GetCode();
1107 array_function->shared()->set_construct_stub(*code);
1109 Handle<Map> initial_strong_map =
1110 Map::Copy(initial_map, "SetInstancePrototype");
1111 initial_strong_map->set_is_strong();
1112 CacheInitialJSArrayMaps(native_context(), initial_strong_map);
1115 { // --- N u m b e r ---
1116 Handle<JSFunction> number_fun =
1117 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
1118 isolate->initial_object_prototype(),
1119 Builtins::kIllegal);
1120 native_context()->set_number_function(*number_fun);
1123 { // --- B o o l e a n ---
1124 Handle<JSFunction> boolean_fun =
1125 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
1126 isolate->initial_object_prototype(),
1127 Builtins::kIllegal);
1128 native_context()->set_boolean_function(*boolean_fun);
1131 { // --- S t r i n g ---
1132 Handle<JSFunction> string_fun =
1133 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
1134 isolate->initial_object_prototype(),
1135 Builtins::kIllegal);
1136 string_fun->shared()->set_construct_stub(
1137 isolate->builtins()->builtin(Builtins::kStringConstructCode));
1138 native_context()->set_string_function(*string_fun);
1140 Handle<Map> string_map =
1141 Handle<Map>(native_context()->string_function()->initial_map());
1142 Map::EnsureDescriptorSlack(string_map, 1);
1144 PropertyAttributes attribs = static_cast<PropertyAttributes>(
1145 DONT_ENUM | DONT_DELETE | READ_ONLY);
1146 Handle<AccessorInfo> string_length(
1147 Accessors::StringLengthInfo(isolate, attribs));
1150 AccessorConstantDescriptor d(factory->length_string(), string_length,
1152 string_map->AppendDescriptor(&d);
1157 // --- S y m b o l ---
1158 Handle<JSFunction> symbol_fun = InstallFunction(
1159 global, "Symbol", JS_VALUE_TYPE, JSValue::kSize,
1160 isolate->initial_object_prototype(), Builtins::kIllegal);
1161 native_context()->set_symbol_function(*symbol_fun);
1164 { // --- D a t e ---
1165 // Builtin functions for Date.prototype.
1166 Handle<JSFunction> date_fun =
1167 InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize,
1168 isolate->initial_object_prototype(),
1169 Builtins::kIllegal);
1171 native_context()->set_date_function(*date_fun);
1176 // Builtin functions for RegExp.prototype.
1177 Handle<JSFunction> regexp_fun =
1178 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
1179 isolate->initial_object_prototype(),
1180 Builtins::kIllegal);
1181 native_context()->set_regexp_function(*regexp_fun);
1183 DCHECK(regexp_fun->has_initial_map());
1184 Handle<Map> initial_map(regexp_fun->initial_map());
1186 DCHECK_EQ(0, initial_map->inobject_properties());
1188 PropertyAttributes final =
1189 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1190 Map::EnsureDescriptorSlack(initial_map, 5);
1193 // ECMA-262, section 15.10.7.1.
1194 DataDescriptor field(factory->source_string(),
1195 JSRegExp::kSourceFieldIndex, final,
1196 Representation::Tagged());
1197 initial_map->AppendDescriptor(&field);
1200 // ECMA-262, section 15.10.7.2.
1201 DataDescriptor field(factory->global_string(),
1202 JSRegExp::kGlobalFieldIndex, final,
1203 Representation::Tagged());
1204 initial_map->AppendDescriptor(&field);
1207 // ECMA-262, section 15.10.7.3.
1208 DataDescriptor field(factory->ignore_case_string(),
1209 JSRegExp::kIgnoreCaseFieldIndex, final,
1210 Representation::Tagged());
1211 initial_map->AppendDescriptor(&field);
1214 // ECMA-262, section 15.10.7.4.
1215 DataDescriptor field(factory->multiline_string(),
1216 JSRegExp::kMultilineFieldIndex, final,
1217 Representation::Tagged());
1218 initial_map->AppendDescriptor(&field);
1221 // ECMA-262, section 15.10.7.5.
1222 PropertyAttributes writable =
1223 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
1224 DataDescriptor field(factory->last_index_string(),
1225 JSRegExp::kLastIndexFieldIndex, writable,
1226 Representation::Tagged());
1227 initial_map->AppendDescriptor(&field);
1230 static const int num_fields = JSRegExp::kInObjectFieldCount;
1231 initial_map->set_inobject_properties(num_fields);
1232 initial_map->set_unused_property_fields(0);
1233 initial_map->set_instance_size(initial_map->instance_size() +
1234 num_fields * kPointerSize);
1236 // RegExp prototype object is itself a RegExp.
1237 Handle<Map> proto_map = Map::Copy(initial_map, "RegExpPrototype");
1238 DCHECK(proto_map->prototype() == *isolate->initial_object_prototype());
1239 Handle<JSObject> proto = factory->NewJSObjectFromMap(proto_map);
1240 proto->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex,
1241 heap->query_colon_string());
1242 proto->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex,
1243 heap->false_value());
1244 proto->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex,
1245 heap->false_value());
1246 proto->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex,
1247 heap->false_value());
1248 proto->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
1250 SKIP_WRITE_BARRIER); // It's a Smi.
1251 proto_map->set_is_prototype_map(true);
1252 Map::SetPrototype(initial_map, proto);
1253 factory->SetRegExpIrregexpData(Handle<JSRegExp>::cast(proto),
1254 JSRegExp::IRREGEXP, factory->empty_string(),
1255 JSRegExp::Flags(0), 0);
1258 // Initialize the embedder data slot.
1259 Handle<FixedArray> embedder_data = factory->NewFixedArray(3);
1260 native_context()->set_embedder_data(*embedder_data);
1262 if (context_type == THIN_CONTEXT) return;
1265 Handle<String> name = factory->InternalizeUtf8String("JSON");
1266 Handle<JSFunction> cons = factory->NewFunction(name);
1267 JSFunction::SetInstancePrototype(cons,
1268 Handle<Object>(native_context()->initial_object_prototype(), isolate));
1269 cons->SetInstanceClassName(*name);
1270 Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1271 DCHECK(json_object->IsJSObject());
1272 JSObject::AddProperty(global, name, json_object, DONT_ENUM);
1273 native_context()->set_json_object(*json_object);
1276 { // -- A r r a y B u f f e r
1277 Handle<JSFunction> array_buffer_fun =
1279 global, "ArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1280 JSArrayBuffer::kSizeWithInternalFields,
1281 isolate->initial_object_prototype(),
1282 Builtins::kIllegal);
1283 native_context()->set_array_buffer_fun(*array_buffer_fun);
1286 { // -- T y p e d A r r a y s
1287 #define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype, size) \
1289 Handle<JSFunction> fun; \
1290 Handle<Map> external_map; \
1291 InstallTypedArray(#Type "Array", \
1295 native_context()->set_##type##_array_fun(*fun); \
1296 native_context()->set_##type##_array_external_map(*external_map); \
1298 TYPED_ARRAYS(INSTALL_TYPED_ARRAY)
1299 #undef INSTALL_TYPED_ARRAY
1301 Handle<JSFunction> data_view_fun =
1303 global, "DataView", JS_DATA_VIEW_TYPE,
1304 JSDataView::kSizeWithInternalFields,
1305 isolate->initial_object_prototype(),
1306 Builtins::kIllegal);
1307 native_context()->set_data_view_fun(*data_view_fun);
1311 Handle<JSFunction> js_map_fun = InstallFunction(
1312 global, "Map", JS_MAP_TYPE, JSMap::kSize,
1313 isolate->initial_object_prototype(), Builtins::kIllegal);
1314 native_context()->set_js_map_fun(*js_map_fun);
1318 Handle<JSFunction> js_set_fun = InstallFunction(
1319 global, "Set", JS_SET_TYPE, JSSet::kSize,
1320 isolate->initial_object_prototype(), Builtins::kIllegal);
1321 native_context()->set_js_set_fun(*js_set_fun);
1324 { // Set up the iterator result object
1325 STATIC_ASSERT(JSGeneratorObject::kResultPropertyCount == 2);
1326 Handle<JSFunction> object_function(native_context()->object_function());
1327 Handle<Map> iterator_result_map =
1328 Map::Create(isolate, JSGeneratorObject::kResultPropertyCount);
1329 DCHECK_EQ(JSGeneratorObject::kResultSize,
1330 iterator_result_map->instance_size());
1331 DCHECK_EQ(JSGeneratorObject::kResultPropertyCount,
1332 iterator_result_map->inobject_properties());
1333 Map::EnsureDescriptorSlack(iterator_result_map,
1334 JSGeneratorObject::kResultPropertyCount);
1336 DataDescriptor value_descr(factory->value_string(),
1337 JSGeneratorObject::kResultValuePropertyIndex,
1338 NONE, Representation::Tagged());
1339 iterator_result_map->AppendDescriptor(&value_descr);
1341 DataDescriptor done_descr(factory->done_string(),
1342 JSGeneratorObject::kResultDonePropertyIndex, NONE,
1343 Representation::Tagged());
1344 iterator_result_map->AppendDescriptor(&done_descr);
1346 iterator_result_map->set_unused_property_fields(0);
1347 DCHECK_EQ(JSGeneratorObject::kResultSize,
1348 iterator_result_map->instance_size());
1349 native_context()->set_iterator_result_map(*iterator_result_map);
1353 InstallFunction(global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
1354 isolate->initial_object_prototype(), Builtins::kIllegal);
1356 InstallFunction(global, "WeakSet", JS_WEAK_SET_TYPE, JSWeakSet::kSize,
1357 isolate->initial_object_prototype(), Builtins::kIllegal);
1359 { // --- sloppy arguments map
1360 // Make sure we can recognize argument objects at runtime.
1361 // This is done by introducing an anonymous function with
1362 // class_name equals 'Arguments'.
1363 Handle<String> arguments_string = factory->Arguments_string();
1364 Handle<Code> code(isolate->builtins()->builtin(Builtins::kIllegal));
1365 Handle<JSFunction> function = factory->NewFunctionWithoutPrototype(
1366 arguments_string, code);
1367 function->shared()->set_instance_class_name(*arguments_string);
1370 factory->NewMap(JS_OBJECT_TYPE, Heap::kSloppyArgumentsObjectSize);
1371 // Create the descriptor array for the arguments object.
1372 Map::EnsureDescriptorSlack(map, 2);
1375 DataDescriptor d(factory->length_string(), Heap::kArgumentsLengthIndex,
1376 DONT_ENUM, Representation::Tagged());
1377 map->AppendDescriptor(&d);
1380 DataDescriptor d(factory->callee_string(), Heap::kArgumentsCalleeIndex,
1381 DONT_ENUM, Representation::Tagged());
1382 map->AppendDescriptor(&d);
1384 // @@iterator method is added later.
1386 map->set_function_with_prototype(true);
1387 map->set_inobject_properties(2);
1388 native_context()->set_sloppy_arguments_map(*map);
1390 DCHECK(!function->has_initial_map());
1391 JSFunction::SetInitialMap(function, map,
1392 isolate->initial_object_prototype());
1394 DCHECK(map->inobject_properties() > Heap::kArgumentsCalleeIndex);
1395 DCHECK(map->inobject_properties() > Heap::kArgumentsLengthIndex);
1396 DCHECK(!map->is_dictionary_map());
1397 DCHECK(IsFastObjectElementsKind(map->elements_kind()));
1400 { // --- fast and slow aliased arguments map
1401 Handle<Map> map = isolate->sloppy_arguments_map();
1402 map = Map::Copy(map, "FastAliasedArguments");
1403 map->set_elements_kind(FAST_SLOPPY_ARGUMENTS_ELEMENTS);
1404 DCHECK_EQ(2, map->inobject_properties());
1405 native_context()->set_fast_aliased_arguments_map(*map);
1407 map = Map::Copy(map, "SlowAliasedArguments");
1408 map->set_elements_kind(SLOW_SLOPPY_ARGUMENTS_ELEMENTS);
1409 DCHECK_EQ(2, map->inobject_properties());
1410 native_context()->set_slow_aliased_arguments_map(*map);
1413 { // --- strict mode arguments map
1414 const PropertyAttributes attributes =
1415 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1417 // Create the ThrowTypeError functions.
1418 Handle<AccessorPair> callee = factory->NewAccessorPair();
1419 Handle<AccessorPair> caller = factory->NewAccessorPair();
1421 Handle<JSFunction> poison = GetStrictArgumentsPoisonFunction();
1423 // Install the ThrowTypeError functions.
1424 callee->set_getter(*poison);
1425 callee->set_setter(*poison);
1426 caller->set_getter(*poison);
1427 caller->set_setter(*poison);
1429 // Create the map. Allocate one in-object field for length.
1430 Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE,
1431 Heap::kStrictArgumentsObjectSize);
1432 // Create the descriptor array for the arguments object.
1433 Map::EnsureDescriptorSlack(map, 3);
1436 DataDescriptor d(factory->length_string(), Heap::kArgumentsLengthIndex,
1437 DONT_ENUM, Representation::Tagged());
1438 map->AppendDescriptor(&d);
1441 AccessorConstantDescriptor d(factory->callee_string(), callee,
1443 map->AppendDescriptor(&d);
1446 AccessorConstantDescriptor d(factory->caller_string(), caller,
1448 map->AppendDescriptor(&d);
1450 // @@iterator method is added later.
1452 map->set_function_with_prototype(true);
1453 DCHECK_EQ(native_context()->object_function()->prototype(),
1454 *isolate->initial_object_prototype());
1455 Map::SetPrototype(map, isolate->initial_object_prototype());
1456 map->set_inobject_properties(1);
1458 // Copy constructor from the sloppy arguments boilerplate.
1459 map->SetConstructor(
1460 native_context()->sloppy_arguments_map()->GetConstructor());
1462 native_context()->set_strict_arguments_map(*map);
1464 DCHECK(map->inobject_properties() > Heap::kArgumentsLengthIndex);
1465 DCHECK(!map->is_dictionary_map());
1466 DCHECK(IsFastObjectElementsKind(map->elements_kind()));
1469 { // --- context extension
1470 // Create a function for the context extension objects.
1471 Handle<Code> code = Handle<Code>(
1472 isolate->builtins()->builtin(Builtins::kIllegal));
1473 Handle<JSFunction> context_extension_fun = factory->NewFunction(
1474 factory->empty_string(), code, JS_CONTEXT_EXTENSION_OBJECT_TYPE,
1475 JSObject::kHeaderSize);
1477 Handle<String> name = factory->InternalizeOneByteString(
1478 STATIC_CHAR_VECTOR("context_extension"));
1479 context_extension_fun->shared()->set_instance_class_name(*name);
1480 native_context()->set_context_extension_function(*context_extension_fun);
1485 // Set up the call-as-function delegate.
1487 Handle<Code>(isolate->builtins()->builtin(
1488 Builtins::kHandleApiCallAsFunction));
1489 Handle<JSFunction> delegate = factory->NewFunction(
1490 factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1491 native_context()->set_call_as_function_delegate(*delegate);
1492 delegate->shared()->DontAdaptArguments();
1496 // Set up the call-as-constructor delegate.
1498 Handle<Code>(isolate->builtins()->builtin(
1499 Builtins::kHandleApiCallAsConstructor));
1500 Handle<JSFunction> delegate = factory->NewFunction(
1501 factory->empty_string(), code, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1502 native_context()->set_call_as_constructor_delegate(*delegate);
1503 delegate->shared()->DontAdaptArguments();
1508 void Genesis::InstallTypedArray(
1510 ElementsKind elements_kind,
1511 Handle<JSFunction>* fun,
1512 Handle<Map>* external_map) {
1513 Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1514 Handle<JSFunction> result = InstallFunction(
1515 global, name, JS_TYPED_ARRAY_TYPE, JSTypedArray::kSize,
1516 isolate()->initial_object_prototype(), Builtins::kIllegal);
1518 Handle<Map> initial_map = isolate()->factory()->NewMap(
1519 JS_TYPED_ARRAY_TYPE,
1520 JSTypedArray::kSizeWithInternalFields,
1522 JSFunction::SetInitialMap(result, initial_map,
1523 handle(initial_map->prototype(), isolate()));
1526 ElementsKind external_kind = GetNextTransitionElementsKind(elements_kind);
1527 *external_map = Map::AsElementsKind(initial_map, external_kind);
1531 void Genesis::InitializeExperimentalGlobal() {
1532 #define FEATURE_INITIALIZE_GLOBAL(id, descr) InitializeGlobal_##id();
1534 HARMONY_INPROGRESS(FEATURE_INITIALIZE_GLOBAL)
1535 HARMONY_STAGED(FEATURE_INITIALIZE_GLOBAL)
1536 HARMONY_SHIPPING(FEATURE_INITIALIZE_GLOBAL)
1537 #undef FEATURE_INITIALIZE_GLOBAL
1541 bool Bootstrapper::CompileBuiltin(Isolate* isolate, int index) {
1542 Vector<const char> name = Natives::GetScriptName(index);
1543 Handle<String> source_code =
1544 isolate->bootstrapper()->SourceLookup<Natives>(index);
1545 Handle<Object> global = isolate->global_object();
1546 Handle<Object> utils = isolate->natives_utils_object();
1547 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::CompileExperimentalBuiltin(Isolate* isolate, int index) {
1556 HandleScope scope(isolate);
1557 Vector<const char> name = ExperimentalNatives::GetScriptName(index);
1558 Handle<String> source_code =
1559 isolate->bootstrapper()->SourceLookup<ExperimentalNatives>(index);
1560 Handle<Object> global = isolate->global_object();
1561 Handle<Object> utils = isolate->natives_utils_object();
1562 Handle<Object> args[] = {global, utils};
1563 return Bootstrapper::CompileNative(
1564 isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1565 source_code, arraysize(args), args);
1569 bool Bootstrapper::CompileExtraBuiltin(Isolate* isolate, int index) {
1570 HandleScope scope(isolate);
1571 Vector<const char> name = ExtraNatives::GetScriptName(index);
1572 Handle<String> source_code =
1573 isolate->bootstrapper()->SourceLookup<ExtraNatives>(index);
1574 Handle<Object> global = isolate->global_object();
1575 Handle<Object> exports = isolate->extras_exports_object();
1576 Handle<Object> args[] = {global, exports};
1577 return Bootstrapper::CompileNative(
1578 isolate, name, Handle<JSObject>(isolate->native_context()->builtins()),
1579 source_code, arraysize(args), args);
1583 bool Bootstrapper::CompileCodeStubBuiltin(Isolate* isolate, int index) {
1584 HandleScope scope(isolate);
1585 Vector<const char> name = CodeStubNatives::GetScriptName(index);
1586 Handle<String> source_code =
1587 isolate->bootstrapper()->SourceLookup<CodeStubNatives>(index);
1588 Handle<JSObject> global(isolate->global_object());
1589 Handle<JSObject> exports(isolate->heap()->code_stub_exports_object());
1590 Handle<Object> args[] = {global, exports};
1592 CompileNative(isolate, name, global, source_code, arraysize(args), args);
1597 bool Bootstrapper::CompileNative(Isolate* isolate, Vector<const char> name,
1598 Handle<JSObject> receiver,
1599 Handle<String> source, int argc,
1600 Handle<Object> argv[]) {
1601 SuppressDebug compiling_natives(isolate->debug());
1602 // During genesis, the boilerplate for stack overflow won't work until the
1603 // environment has been at least partially initialized. Add a stack check
1604 // before entering JS code to catch overflow early.
1605 StackLimitCheck check(isolate);
1606 if (check.JsHasOverflowed(1 * KB)) {
1607 isolate->StackOverflow();
1611 Handle<Context> context(isolate->context());
1613 Handle<String> script_name =
1614 isolate->factory()->NewStringFromUtf8(name).ToHandleChecked();
1615 Handle<SharedFunctionInfo> function_info = Compiler::CompileScript(
1616 source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
1617 context, NULL, NULL, ScriptCompiler::kNoCompileOptions, NATIVES_CODE,
1619 if (function_info.is_null()) return false;
1621 DCHECK(context->IsNativeContext());
1623 Handle<Context> runtime_context(context->runtime_context());
1624 Handle<JSFunction> fun =
1625 isolate->factory()->NewFunctionFromSharedFunctionInfo(function_info,
1628 // For non-extension scripts, run script to get the function wrapper.
1629 Handle<Object> wrapper;
1630 if (!Execution::Call(isolate, fun, receiver, 0, NULL).ToHandle(&wrapper)) {
1633 // Then run the function wrapper.
1634 return !Execution::Call(isolate, Handle<JSFunction>::cast(wrapper), receiver,
1635 argc, argv).is_null();
1639 bool Genesis::CallUtilsFunction(Isolate* isolate, const char* name) {
1640 Handle<JSObject> utils =
1641 Handle<JSObject>::cast(isolate->natives_utils_object());
1642 Handle<String> name_string =
1643 isolate->factory()->NewStringFromAsciiChecked(name);
1644 Handle<Object> fun = JSObject::GetDataProperty(utils, name_string);
1645 Handle<Object> receiver = isolate->factory()->undefined_value();
1646 Handle<Object> args[] = {utils};
1647 return !Execution::Call(isolate, fun, receiver, 1, args).is_null();
1651 bool Genesis::CompileExtension(Isolate* isolate, v8::Extension* extension) {
1652 Factory* factory = isolate->factory();
1653 HandleScope scope(isolate);
1654 Handle<SharedFunctionInfo> function_info;
1656 Handle<String> source =
1658 ->NewExternalStringFromOneByte(extension->source())
1660 DCHECK(source->IsOneByteRepresentation());
1662 // If we can't find the function in the cache, we compile a new
1663 // function and insert it into the cache.
1664 Vector<const char> name = CStrVector(extension->name());
1665 SourceCodeCache* cache = isolate->bootstrapper()->extensions_cache();
1666 Handle<Context> context(isolate->context());
1667 DCHECK(context->IsNativeContext());
1669 if (!cache->Lookup(name, &function_info)) {
1670 Handle<String> script_name =
1671 factory->NewStringFromUtf8(name).ToHandleChecked();
1672 function_info = Compiler::CompileScript(
1673 source, script_name, 0, 0, ScriptOriginOptions(), Handle<Object>(),
1674 context, extension, NULL, ScriptCompiler::kNoCompileOptions,
1675 NOT_NATIVES_CODE, false);
1676 if (function_info.is_null()) return false;
1677 cache->Add(name, function_info);
1680 // Set up the function context. Conceptually, we should clone the
1681 // function before overwriting the context but since we're in a
1682 // single-threaded environment it is not strictly necessary.
1683 Handle<JSFunction> fun =
1684 factory->NewFunctionFromSharedFunctionInfo(function_info, context);
1686 // Call function using either the runtime object or the global
1687 // object as the receiver. Provide no parameters.
1688 Handle<Object> receiver = isolate->global_object();
1689 return !Execution::Call(isolate, fun, receiver, 0, NULL).is_null();
1693 static Handle<JSObject> ResolveBuiltinIdHolder(Handle<Context> native_context,
1694 const char* holder_expr) {
1695 Isolate* isolate = native_context->GetIsolate();
1696 Factory* factory = isolate->factory();
1697 Handle<GlobalObject> global(native_context->global_object());
1698 const char* period_pos = strchr(holder_expr, '.');
1699 if (period_pos == NULL) {
1700 return Handle<JSObject>::cast(
1701 Object::GetPropertyOrElement(
1702 global, factory->InternalizeUtf8String(holder_expr))
1703 .ToHandleChecked());
1705 const char* inner = period_pos + 1;
1706 DCHECK(!strchr(inner, '.'));
1707 Vector<const char> property(holder_expr,
1708 static_cast<int>(period_pos - holder_expr));
1709 Handle<String> property_string = factory->InternalizeUtf8String(property);
1710 DCHECK(!property_string.is_null());
1711 Handle<JSObject> object = Handle<JSObject>::cast(
1712 Object::GetProperty(global, property_string).ToHandleChecked());
1713 if (strcmp("prototype", inner) == 0) {
1714 Handle<JSFunction> function = Handle<JSFunction>::cast(object);
1715 return Handle<JSObject>(JSObject::cast(function->prototype()));
1717 Handle<String> inner_string = factory->InternalizeUtf8String(inner);
1718 DCHECK(!inner_string.is_null());
1719 Handle<Object> value =
1720 Object::GetProperty(object, inner_string).ToHandleChecked();
1721 return Handle<JSObject>::cast(value);
1725 #define INSTALL_NATIVE(Type, name, var) \
1726 Handle<String> var##_name = \
1727 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR(name)); \
1728 Handle<Object> var##_native = \
1729 Object::GetProperty(handle(native_context()->builtins()), var##_name) \
1730 .ToHandleChecked(); \
1731 native_context()->set_##var(Type::cast(*var##_native));
1734 void Genesis::InstallNativeFunctions() {
1735 HandleScope scope(isolate());
1736 INSTALL_NATIVE(JSFunction, "$createDate", create_date_fun);
1738 INSTALL_NATIVE(JSFunction, "$toNumber", to_number_fun);
1739 INSTALL_NATIVE(JSFunction, "$toString", to_string_fun);
1740 INSTALL_NATIVE(JSFunction, "$toDetailString", to_detail_string_fun);
1741 INSTALL_NATIVE(JSFunction, "$toObject", to_object_fun);
1742 INSTALL_NATIVE(JSFunction, "$toInteger", to_integer_fun);
1743 INSTALL_NATIVE(JSFunction, "$toUint32", to_uint32_fun);
1744 INSTALL_NATIVE(JSFunction, "$toInt32", to_int32_fun);
1745 INSTALL_NATIVE(JSFunction, "$toLength", to_length_fun);
1747 INSTALL_NATIVE(JSFunction, "$globalEval", global_eval_fun);
1748 INSTALL_NATIVE(JSFunction, "$getStackTraceLine", get_stack_trace_line_fun);
1749 INSTALL_NATIVE(JSFunction, "$toCompletePropertyDescriptor",
1750 to_complete_property_descriptor);
1752 INSTALL_NATIVE(Symbol, "$promiseStatus", promise_status);
1753 INSTALL_NATIVE(Symbol, "$promiseValue", promise_value);
1754 INSTALL_NATIVE(JSFunction, "$promiseCreate", promise_create);
1755 INSTALL_NATIVE(JSFunction, "$promiseResolve", promise_resolve);
1756 INSTALL_NATIVE(JSFunction, "$promiseReject", promise_reject);
1757 INSTALL_NATIVE(JSFunction, "$promiseChain", promise_chain);
1758 INSTALL_NATIVE(JSFunction, "$promiseCatch", promise_catch);
1759 INSTALL_NATIVE(JSFunction, "$promiseThen", promise_then);
1761 INSTALL_NATIVE(JSFunction, "$observeNotifyChange", observers_notify_change);
1762 INSTALL_NATIVE(JSFunction, "$observeEnqueueSpliceRecord",
1763 observers_enqueue_splice);
1764 INSTALL_NATIVE(JSFunction, "$observeBeginPerformSplice",
1765 observers_begin_perform_splice);
1766 INSTALL_NATIVE(JSFunction, "$observeEndPerformSplice",
1767 observers_end_perform_splice);
1768 INSTALL_NATIVE(JSFunction, "$observeNativeObjectObserve",
1769 native_object_observe);
1770 INSTALL_NATIVE(JSFunction, "$observeNativeObjectGetNotifier",
1771 native_object_get_notifier);
1772 INSTALL_NATIVE(JSFunction, "$observeNativeObjectNotifierPerformChange",
1773 native_object_notifier_perform_change);
1774 INSTALL_NATIVE(JSFunction, "$arrayValues", array_values_iterator);
1775 INSTALL_NATIVE(JSFunction, "$mapGet", map_get);
1776 INSTALL_NATIVE(JSFunction, "$mapSet", map_set);
1777 INSTALL_NATIVE(JSFunction, "$mapHas", map_has);
1778 INSTALL_NATIVE(JSFunction, "$mapDelete", map_delete);
1779 INSTALL_NATIVE(JSFunction, "$setAdd", set_add);
1780 INSTALL_NATIVE(JSFunction, "$setHas", set_has);
1781 INSTALL_NATIVE(JSFunction, "$setDelete", set_delete);
1782 INSTALL_NATIVE(JSFunction, "$mapFromArray", map_from_array);
1783 INSTALL_NATIVE(JSFunction, "$setFromArray", set_from_array);
1787 void Genesis::InstallExperimentalNativeFunctions() {
1788 if (FLAG_harmony_proxies) {
1789 INSTALL_NATIVE(JSFunction, "$proxyDerivedHasTrap", derived_has_trap);
1790 INSTALL_NATIVE(JSFunction, "$proxyDerivedGetTrap", derived_get_trap);
1791 INSTALL_NATIVE(JSFunction, "$proxyDerivedSetTrap", derived_set_trap);
1792 INSTALL_NATIVE(JSFunction, "$proxyEnumerate", proxy_enumerate);
1795 #define INSTALL_NATIVE_FUNCTIONS_FOR(id, descr) InstallNativeFunctions_##id();
1796 HARMONY_INPROGRESS(INSTALL_NATIVE_FUNCTIONS_FOR)
1797 HARMONY_STAGED(INSTALL_NATIVE_FUNCTIONS_FOR)
1798 HARMONY_SHIPPING(INSTALL_NATIVE_FUNCTIONS_FOR)
1799 #undef INSTALL_NATIVE_FUNCTIONS_FOR
1803 template <typename Data>
1804 Data* SetBuiltinTypedArray(Isolate* isolate, Handle<JSBuiltinsObject> builtins,
1805 ExternalArrayType type, Data* data,
1806 size_t num_elements, const char* name) {
1807 size_t byte_length = num_elements * sizeof(*data);
1808 Handle<JSArrayBuffer> buffer = isolate->factory()->NewJSArrayBuffer();
1809 bool is_external = data != nullptr;
1811 data = reinterpret_cast<Data*>(
1812 isolate->array_buffer_allocator()->Allocate(byte_length));
1814 Runtime::SetupArrayBuffer(isolate, buffer, is_external, data, byte_length);
1816 Handle<JSTypedArray> typed_array =
1817 isolate->factory()->NewJSTypedArray(type, buffer, 0, num_elements);
1818 Handle<String> name_string = isolate->factory()->InternalizeUtf8String(name);
1819 // Reset property cell type before (re)initializing.
1820 JSBuiltinsObject::InvalidatePropertyCell(builtins, name_string);
1821 JSObject::SetOwnPropertyIgnoreAttributes(builtins, name_string, typed_array,
1828 void Genesis::InitializeBuiltinTypedArrays() {
1829 Handle<JSBuiltinsObject> builtins(native_context()->builtins());
1830 { // Initially seed the per-context random number generator using the
1831 // per-isolate random number generator.
1832 const size_t num_elements = 2;
1833 const size_t num_bytes = num_elements * sizeof(uint32_t);
1834 uint32_t* state = SetBuiltinTypedArray<uint32_t>(isolate(), builtins,
1835 kExternalUint32Array, NULL,
1836 num_elements, "rngstate");
1838 isolate()->random_number_generator()->NextBytes(state, num_bytes);
1839 } while (state[0] == 0 || state[1] == 0);
1842 { // Initialize trigonometric lookup tables and constants.
1843 const size_t num_elements = arraysize(fdlibm::MathConstants::constants);
1844 double* data = const_cast<double*>(fdlibm::MathConstants::constants);
1845 SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1846 data, num_elements, "kMath");
1849 { // Initialize a result array for rempio2 calculation
1850 const size_t num_elements = 2;
1852 SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1853 NULL, num_elements, "rempio2result");
1854 for (size_t i = 0; i < num_elements; i++) data[i] = 0;
1859 #define EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(id) \
1860 void Genesis::InstallNativeFunctions_##id() {}
1862 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_modules)
1863 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_array_includes)
1864 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_regexps)
1865 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_arrow_functions)
1866 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_tostring)
1867 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy)
1868 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy_let)
1869 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_unicode)
1870 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_unicode_regexps)
1871 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_computed_property_names)
1872 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_rest_parameters)
1873 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_reflect)
1874 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spreadcalls)
1875 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_destructuring)
1876 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_object)
1877 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spread_arrays)
1878 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sharedarraybuffer)
1879 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_atomics)
1880 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_new_target)
1881 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_concat_spreadable)
1882 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_simd)
1885 void Genesis::InstallNativeFunctions_harmony_proxies() {
1886 if (FLAG_harmony_proxies) {
1887 INSTALL_NATIVE(JSFunction, "$proxyDerivedHasTrap", derived_has_trap);
1888 INSTALL_NATIVE(JSFunction, "$proxyDerivedGetTrap", derived_get_trap);
1889 INSTALL_NATIVE(JSFunction, "$proxyDerivedSetTrap", derived_set_trap);
1890 INSTALL_NATIVE(JSFunction, "$proxyEnumerate", proxy_enumerate);
1895 #undef INSTALL_NATIVE
1897 #define EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(id) \
1898 void Genesis::InitializeGlobal_##id() {}
1900 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_modules)
1901 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_array_includes)
1902 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_arrow_functions)
1903 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_proxies)
1904 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy)
1905 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy_let)
1906 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_unicode)
1907 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_computed_property_names)
1908 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_rest_parameters)
1909 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spreadcalls)
1910 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_destructuring)
1911 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_object)
1912 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spread_arrays)
1913 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_atomics)
1914 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_new_target)
1915 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_concat_spreadable)
1917 void Genesis::InitializeGlobal_harmony_regexps() {
1918 Handle<JSObject> builtins(native_context()->builtins());
1920 Handle<HeapObject> flag(FLAG_harmony_regexps ? heap()->true_value()
1921 : heap()->false_value());
1922 Runtime::SetObjectProperty(isolate(), builtins,
1923 factory()->harmony_regexps_string(), flag,
1928 void Genesis::InitializeGlobal_harmony_unicode_regexps() {
1929 Handle<JSObject> builtins(native_context()->builtins());
1931 Handle<HeapObject> flag(FLAG_harmony_unicode_regexps ? heap()->true_value()
1932 : heap()->false_value());
1933 Runtime::SetObjectProperty(isolate(), builtins,
1934 factory()->harmony_unicode_regexps_string(), flag,
1939 void Genesis::InitializeGlobal_harmony_reflect() {
1940 Handle<JSObject> builtins(native_context()->builtins());
1942 Handle<JSFunction> apply = InstallFunction(
1943 builtins, "$reflectApply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1944 MaybeHandle<JSObject>(), Builtins::kReflectApply);
1945 apply->shared()->set_internal_formal_parameter_count(3);
1946 apply->shared()->set_length(3);
1948 Handle<JSFunction> construct = InstallFunction(
1949 builtins, "$reflectConstruct", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1950 MaybeHandle<JSObject>(), Builtins::kReflectConstruct);
1951 construct->shared()->set_internal_formal_parameter_count(3);
1952 construct->shared()->set_length(2);
1954 if (!FLAG_harmony_reflect) return;
1956 Handle<JSGlobalObject> global(JSGlobalObject::cast(
1957 native_context()->global_object()));
1958 Handle<String> reflect_string =
1959 factory()->NewStringFromStaticChars("Reflect");
1960 Handle<Object> reflect =
1961 factory()->NewJSObject(isolate()->object_function(), TENURED);
1962 JSObject::AddProperty(global, reflect_string, reflect, DONT_ENUM);
1966 void Genesis::InitializeGlobal_harmony_tostring() {
1967 Handle<JSObject> builtins(native_context()->builtins());
1969 Handle<HeapObject> flag(FLAG_harmony_tostring ? heap()->true_value()
1970 : heap()->false_value());
1971 Runtime::SetObjectProperty(isolate(), builtins,
1972 factory()->harmony_tostring_string(), flag,
1977 void Genesis::InitializeGlobal_harmony_sharedarraybuffer() {
1978 if (!FLAG_harmony_sharedarraybuffer) return;
1980 Handle<JSGlobalObject> global(
1981 JSGlobalObject::cast(native_context()->global_object()));
1983 Handle<JSFunction> shared_array_buffer_fun = InstallFunction(
1984 global, "SharedArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1985 JSArrayBuffer::kSizeWithInternalFields,
1986 isolate()->initial_object_prototype(), Builtins::kIllegal);
1987 native_context()->set_shared_array_buffer_fun(*shared_array_buffer_fun);
1991 void Genesis::InitializeGlobal_harmony_simd() {
1992 if (!FLAG_harmony_simd) return;
1994 Handle<JSGlobalObject> global(
1995 JSGlobalObject::cast(native_context()->global_object()));
1996 Isolate* isolate = global->GetIsolate();
1997 Factory* factory = isolate->factory();
1999 Handle<String> name = factory->InternalizeUtf8String("SIMD");
2000 Handle<JSFunction> cons = factory->NewFunction(name);
2001 JSFunction::SetInstancePrototype(
2003 Handle<Object>(native_context()->initial_object_prototype(), isolate));
2004 cons->SetInstanceClassName(*name);
2005 Handle<JSObject> simd_object = factory->NewJSObject(cons, TENURED);
2006 DCHECK(simd_object->IsJSObject());
2007 JSObject::AddProperty(global, name, simd_object, DONT_ENUM);
2009 Handle<JSFunction> float32x4_function =
2010 InstallFunction(simd_object, "Float32x4", JS_VALUE_TYPE, JSValue::kSize,
2011 isolate->initial_object_prototype(), Builtins::kIllegal);
2012 // Set the instance class name since InstallFunction only does this when
2013 // we install on the GlobalObject.
2014 float32x4_function->SetInstanceClassName(*factory->Float32x4_string());
2015 native_context()->set_float32x4_function(*float32x4_function);
2019 Handle<JSFunction> Genesis::InstallInternalArray(Handle<JSObject> target,
2021 ElementsKind elements_kind) {
2022 // --- I n t e r n a l A r r a y ---
2023 // An array constructor on the builtins object that works like
2024 // the public Array constructor, except that its prototype
2025 // doesn't inherit from Object.prototype.
2026 // To be used only for internal work by builtins. Instances
2027 // must not be leaked to user code.
2028 Handle<JSObject> prototype =
2029 factory()->NewJSObject(isolate()->object_function(), TENURED);
2030 Handle<JSFunction> array_function =
2031 InstallFunction(target, name, JS_ARRAY_TYPE, JSArray::kSize, prototype,
2032 Builtins::kInternalArrayCode);
2034 InternalArrayConstructorStub internal_array_constructor_stub(isolate());
2035 Handle<Code> code = internal_array_constructor_stub.GetCode();
2036 array_function->shared()->set_construct_stub(*code);
2037 array_function->shared()->DontAdaptArguments();
2039 Handle<Map> original_map(array_function->initial_map());
2040 Handle<Map> initial_map = Map::Copy(original_map, "InternalArray");
2041 initial_map->set_elements_kind(elements_kind);
2042 JSFunction::SetInitialMap(array_function, initial_map, prototype);
2044 // Make "length" magic on instances.
2045 Map::EnsureDescriptorSlack(initial_map, 1);
2047 PropertyAttributes attribs = static_cast<PropertyAttributes>(
2048 DONT_ENUM | DONT_DELETE);
2050 Handle<AccessorInfo> array_length =
2051 Accessors::ArrayLengthInfo(isolate(), attribs);
2053 AccessorConstantDescriptor d(Handle<Name>(Name::cast(array_length->name())),
2054 array_length, attribs);
2055 initial_map->AppendDescriptor(&d);
2058 return array_function;
2062 bool Genesis::InstallNatives(ContextType context_type) {
2063 HandleScope scope(isolate());
2065 // Create a function for the builtins object. Allocate space for the
2066 // JavaScript builtins, a reference to the builtins object
2067 // (itself) and a reference to the native_context directly in the object.
2068 Handle<Code> code = Handle<Code>(
2069 isolate()->builtins()->builtin(Builtins::kIllegal));
2070 Handle<JSFunction> builtins_fun = factory()->NewFunction(
2071 factory()->empty_string(), code, JS_BUILTINS_OBJECT_TYPE,
2072 JSBuiltinsObject::kSize);
2074 Handle<String> name =
2075 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2076 builtins_fun->shared()->set_instance_class_name(*name);
2077 builtins_fun->initial_map()->set_dictionary_map(true);
2078 builtins_fun->initial_map()->set_prototype(heap()->null_value());
2080 // Allocate the builtins object.
2081 Handle<JSBuiltinsObject> builtins =
2082 Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
2083 builtins->set_builtins(*builtins);
2084 builtins->set_native_context(*native_context());
2085 builtins->set_global_proxy(native_context()->global_proxy());
2088 // Set up the 'builtin' property, which refers to the js builtins object.
2089 static const PropertyAttributes attributes =
2090 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2091 Handle<String> builtins_string =
2092 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2093 JSObject::AddProperty(builtins, builtins_string, builtins, attributes);
2095 // Set up the reference from the global object to the builtins object.
2096 JSGlobalObject::cast(native_context()->global_object())->
2097 set_builtins(*builtins);
2099 // Create a bridge function that has context in the native context.
2100 Handle<JSFunction> bridge = factory()->NewFunction(factory()->empty_string());
2101 DCHECK(bridge->context() == *isolate()->native_context());
2103 // Allocate the builtins context.
2104 Handle<Context> context =
2105 factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
2106 context->set_global_object(*builtins); // override builtins global object
2108 native_context()->set_runtime_context(*context);
2110 if (context_type == THIN_CONTEXT) {
2111 int js_builtins_script_index = Natives::GetDebuggerCount();
2112 if (!Bootstrapper::CompileBuiltin(isolate(), js_builtins_script_index))
2114 if (!InstallJSBuiltins(builtins)) return false;
2118 // Set up the utils object as shared container between native scripts.
2119 Handle<JSObject> utils = factory()->NewJSObject(isolate()->object_function());
2120 JSObject::NormalizeProperties(utils, CLEAR_INOBJECT_PROPERTIES, 16,
2121 "utils container for native scripts");
2122 native_context()->set_natives_utils_object(*utils);
2124 Handle<JSObject> extras_exports =
2125 factory()->NewJSObject(isolate()->object_function());
2126 JSObject::NormalizeProperties(extras_exports, CLEAR_INOBJECT_PROPERTIES, 2,
2127 "container to export to extra natives");
2128 native_context()->set_extras_exports_object(*extras_exports);
2130 if (FLAG_expose_natives_as != NULL) {
2131 Handle<String> utils_key = factory()->NewStringFromAsciiChecked("utils");
2132 JSObject::AddProperty(builtins, utils_key, utils, NONE);
2136 // Builtin functions for Script.
2137 Handle<JSFunction> script_fun = InstallFunction(
2138 builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
2139 isolate()->initial_object_prototype(), Builtins::kIllegal);
2140 Handle<JSObject> prototype =
2141 factory()->NewJSObject(isolate()->object_function(), TENURED);
2142 Accessors::FunctionSetPrototype(script_fun, prototype).Assert();
2143 native_context()->set_script_function(*script_fun);
2145 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
2146 Map::EnsureDescriptorSlack(script_map, 15);
2148 PropertyAttributes attribs =
2149 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2151 Handle<AccessorInfo> script_column =
2152 Accessors::ScriptColumnOffsetInfo(isolate(), attribs);
2154 AccessorConstantDescriptor d(
2155 Handle<Name>(Name::cast(script_column->name())), script_column,
2157 script_map->AppendDescriptor(&d);
2160 Handle<AccessorInfo> script_id =
2161 Accessors::ScriptIdInfo(isolate(), attribs);
2163 AccessorConstantDescriptor d(Handle<Name>(Name::cast(script_id->name())),
2164 script_id, attribs);
2165 script_map->AppendDescriptor(&d);
2169 Handle<AccessorInfo> script_name =
2170 Accessors::ScriptNameInfo(isolate(), attribs);
2172 AccessorConstantDescriptor d(
2173 Handle<Name>(Name::cast(script_name->name())), script_name, attribs);
2174 script_map->AppendDescriptor(&d);
2177 Handle<AccessorInfo> script_line =
2178 Accessors::ScriptLineOffsetInfo(isolate(), attribs);
2180 AccessorConstantDescriptor d(
2181 Handle<Name>(Name::cast(script_line->name())), script_line, attribs);
2182 script_map->AppendDescriptor(&d);
2185 Handle<AccessorInfo> script_source =
2186 Accessors::ScriptSourceInfo(isolate(), attribs);
2188 AccessorConstantDescriptor d(
2189 Handle<Name>(Name::cast(script_source->name())), script_source,
2191 script_map->AppendDescriptor(&d);
2194 Handle<AccessorInfo> script_type =
2195 Accessors::ScriptTypeInfo(isolate(), attribs);
2197 AccessorConstantDescriptor d(
2198 Handle<Name>(Name::cast(script_type->name())), script_type, attribs);
2199 script_map->AppendDescriptor(&d);
2202 Handle<AccessorInfo> script_compilation_type =
2203 Accessors::ScriptCompilationTypeInfo(isolate(), attribs);
2205 AccessorConstantDescriptor d(
2206 Handle<Name>(Name::cast(script_compilation_type->name())),
2207 script_compilation_type, attribs);
2208 script_map->AppendDescriptor(&d);
2211 Handle<AccessorInfo> script_line_ends =
2212 Accessors::ScriptLineEndsInfo(isolate(), attribs);
2214 AccessorConstantDescriptor d(
2215 Handle<Name>(Name::cast(script_line_ends->name())), script_line_ends,
2217 script_map->AppendDescriptor(&d);
2220 Handle<AccessorInfo> script_context_data =
2221 Accessors::ScriptContextDataInfo(isolate(), attribs);
2223 AccessorConstantDescriptor d(
2224 Handle<Name>(Name::cast(script_context_data->name())),
2225 script_context_data, attribs);
2226 script_map->AppendDescriptor(&d);
2229 Handle<AccessorInfo> script_eval_from_script =
2230 Accessors::ScriptEvalFromScriptInfo(isolate(), attribs);
2232 AccessorConstantDescriptor d(
2233 Handle<Name>(Name::cast(script_eval_from_script->name())),
2234 script_eval_from_script, attribs);
2235 script_map->AppendDescriptor(&d);
2238 Handle<AccessorInfo> script_eval_from_script_position =
2239 Accessors::ScriptEvalFromScriptPositionInfo(isolate(), attribs);
2241 AccessorConstantDescriptor d(
2242 Handle<Name>(Name::cast(script_eval_from_script_position->name())),
2243 script_eval_from_script_position, attribs);
2244 script_map->AppendDescriptor(&d);
2247 Handle<AccessorInfo> script_eval_from_function_name =
2248 Accessors::ScriptEvalFromFunctionNameInfo(isolate(), attribs);
2250 AccessorConstantDescriptor d(
2251 Handle<Name>(Name::cast(script_eval_from_function_name->name())),
2252 script_eval_from_function_name, attribs);
2253 script_map->AppendDescriptor(&d);
2256 Handle<AccessorInfo> script_source_url =
2257 Accessors::ScriptSourceUrlInfo(isolate(), attribs);
2259 AccessorConstantDescriptor d(
2260 Handle<Name>(Name::cast(script_source_url->name())),
2261 script_source_url, attribs);
2262 script_map->AppendDescriptor(&d);
2265 Handle<AccessorInfo> script_source_mapping_url =
2266 Accessors::ScriptSourceMappingUrlInfo(isolate(), attribs);
2268 AccessorConstantDescriptor d(
2269 Handle<Name>(Name::cast(script_source_mapping_url->name())),
2270 script_source_mapping_url, attribs);
2271 script_map->AppendDescriptor(&d);
2274 Handle<AccessorInfo> script_is_embedder_debug_script =
2275 Accessors::ScriptIsEmbedderDebugScriptInfo(isolate(), attribs);
2277 AccessorConstantDescriptor d(
2278 Handle<Name>(Name::cast(script_is_embedder_debug_script->name())),
2279 script_is_embedder_debug_script, attribs);
2280 script_map->AppendDescriptor(&d);
2283 // Allocate the empty script.
2284 Handle<Script> script = factory()->NewScript(factory()->empty_string());
2285 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
2286 heap()->public_set_empty_script(*script);
2289 // Builtin function for OpaqueReference -- a JSValue-based object,
2290 // that keeps its field isolated from JavaScript code. It may store
2291 // objects, that JavaScript code may not access.
2292 Handle<JSFunction> opaque_reference_fun = InstallFunction(
2293 builtins, "OpaqueReference", JS_VALUE_TYPE, JSValue::kSize,
2294 isolate()->initial_object_prototype(), Builtins::kIllegal);
2295 Handle<JSObject> prototype =
2296 factory()->NewJSObject(isolate()->object_function(), TENURED);
2297 Accessors::FunctionSetPrototype(opaque_reference_fun, prototype).Assert();
2298 native_context()->set_opaque_reference_function(*opaque_reference_fun);
2301 // InternalArrays should not use Smi-Only array optimizations. There are too
2302 // many places in the C++ runtime code (e.g. RegEx) that assume that
2303 // elements in InternalArrays can be set to non-Smi values without going
2304 // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
2305 // transition easy to trap. Moreover, they rarely are smi-only.
2307 HandleScope scope(isolate());
2308 Handle<JSObject> utils =
2309 Handle<JSObject>::cast(isolate()->natives_utils_object());
2310 Handle<JSFunction> array_function =
2311 InstallInternalArray(utils, "InternalArray", FAST_HOLEY_ELEMENTS);
2312 native_context()->set_internal_array_function(*array_function);
2313 InstallInternalArray(utils, "InternalPackedArray", FAST_ELEMENTS);
2316 { // -- S e t I t e r a t o r
2317 Handle<JSFunction> set_iterator_function = InstallFunction(
2318 builtins, "SetIterator", JS_SET_ITERATOR_TYPE, JSSetIterator::kSize,
2319 isolate()->initial_object_prototype(), Builtins::kIllegal);
2320 native_context()->set_set_iterator_map(
2321 set_iterator_function->initial_map());
2324 { // -- M a p I t e r a t o r
2325 Handle<JSFunction> map_iterator_function = InstallFunction(
2326 builtins, "MapIterator", JS_MAP_ITERATOR_TYPE, JSMapIterator::kSize,
2327 isolate()->initial_object_prototype(), Builtins::kIllegal);
2328 native_context()->set_map_iterator_map(
2329 map_iterator_function->initial_map());
2333 // Create generator meta-objects and install them on the builtins object.
2334 Handle<JSObject> builtins(native_context()->builtins());
2335 Handle<JSObject> iterator_prototype =
2336 factory()->NewJSObject(isolate()->object_function(), TENURED);
2337 Handle<JSObject> generator_object_prototype =
2338 factory()->NewJSObject(isolate()->object_function(), TENURED);
2339 Handle<JSObject> generator_function_prototype =
2340 factory()->NewJSObject(isolate()->object_function(), TENURED);
2341 SetObjectPrototype(generator_object_prototype, iterator_prototype);
2342 JSObject::AddProperty(
2343 builtins, factory()->InternalizeUtf8String("$iteratorPrototype"),
2345 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2346 JSObject::AddProperty(
2348 factory()->InternalizeUtf8String("GeneratorFunctionPrototype"),
2349 generator_function_prototype,
2350 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2352 JSObject::AddProperty(
2353 generator_function_prototype,
2354 factory()->InternalizeUtf8String("prototype"),
2355 generator_object_prototype,
2356 static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2358 static const bool kUseStrictFunctionMap = true;
2359 InstallFunction(builtins, "GeneratorFunction", JS_FUNCTION_TYPE,
2360 JSFunction::kSize, generator_function_prototype,
2361 Builtins::kIllegal, kUseStrictFunctionMap);
2363 // Create maps for generator functions and their prototypes. Store those
2364 // maps in the native context. The "prototype" property descriptor is
2365 // writable, non-enumerable, and non-configurable (as per ES6 draft
2366 // 04-14-15, section 25.2.4.3).
2367 Handle<Map> strict_function_map(strict_function_map_writable_prototype_);
2368 // Generator functions do not have "caller" or "arguments" accessors.
2369 Handle<Map> sloppy_generator_function_map =
2370 Map::Copy(strict_function_map, "SloppyGeneratorFunction");
2371 Map::SetPrototype(sloppy_generator_function_map,
2372 generator_function_prototype);
2373 native_context()->set_sloppy_generator_function_map(
2374 *sloppy_generator_function_map);
2376 Handle<Map> strict_generator_function_map =
2377 Map::Copy(strict_function_map, "StrictGeneratorFunction");
2378 Map::SetPrototype(strict_generator_function_map,
2379 generator_function_prototype);
2380 native_context()->set_strict_generator_function_map(
2381 *strict_generator_function_map);
2383 Handle<Map> strong_function_map(native_context()->strong_function_map());
2384 Handle<Map> strong_generator_function_map =
2385 Map::Copy(strong_function_map, "StrongGeneratorFunction");
2386 Map::SetPrototype(strong_generator_function_map,
2387 generator_function_prototype);
2388 native_context()->set_strong_generator_function_map(
2389 *strong_generator_function_map);
2391 Handle<JSFunction> object_function(native_context()->object_function());
2392 Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
2393 Map::SetPrototype(generator_object_prototype_map,
2394 generator_object_prototype);
2395 native_context()->set_generator_object_prototype_map(
2396 *generator_object_prototype_map);
2399 if (FLAG_disable_native_files) {
2400 PrintF("Warning: Running without installed natives!\n");
2404 // Install public symbols.
2406 static const PropertyAttributes attributes =
2407 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2408 #define INSTALL_PUBLIC_SYMBOL(name, varname, description) \
2409 Handle<String> varname = factory()->NewStringFromStaticChars(#varname); \
2410 JSObject::AddProperty(builtins, varname, factory()->name(), attributes);
2411 PUBLIC_SYMBOL_LIST(INSTALL_PUBLIC_SYMBOL)
2412 #undef INSTALL_PUBLIC_SYMBOL
2415 int i = Natives::GetDebuggerCount();
2416 if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2418 if (!InstallJSBuiltins(builtins)) return false;
2420 for (++i; i < Natives::GetBuiltinsCount(); ++i) {
2421 if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2424 if (!CallUtilsFunction(isolate(), "PostNatives")) return false;
2426 InstallNativeFunctions();
2428 auto function_cache =
2429 ObjectHashTable::New(isolate(), ApiNatives::kInitialFunctionCacheSize);
2430 native_context()->set_function_cache(*function_cache);
2432 // Store the map for the string prototype after the natives has been compiled
2433 // and the String function has been set up.
2434 Handle<JSFunction> string_function(native_context()->string_function());
2435 DCHECK(JSObject::cast(
2436 string_function->initial_map()->prototype())->HasFastProperties());
2437 native_context()->set_string_function_prototype_map(
2438 HeapObject::cast(string_function->initial_map()->prototype())->map());
2440 // Install Function.prototype.call and apply.
2442 Handle<String> key = factory()->Function_string();
2443 Handle<JSFunction> function =
2444 Handle<JSFunction>::cast(Object::GetProperty(
2445 handle(native_context()->global_object()), key).ToHandleChecked());
2446 Handle<JSObject> proto =
2447 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
2449 // Install the call and the apply functions.
2450 Handle<JSFunction> call =
2451 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2452 MaybeHandle<JSObject>(), Builtins::kFunctionCall);
2453 Handle<JSFunction> apply =
2454 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2455 MaybeHandle<JSObject>(), Builtins::kFunctionApply);
2457 // Make sure that Function.prototype.call appears to be compiled.
2458 // The code will never be called, but inline caching for call will
2459 // only work if it appears to be compiled.
2460 call->shared()->DontAdaptArguments();
2461 DCHECK(call->is_compiled());
2463 // Set the expected parameters for apply to 2; required by builtin.
2464 apply->shared()->set_internal_formal_parameter_count(2);
2466 // Set the lengths for the functions to satisfy ECMA-262.
2467 call->shared()->set_length(1);
2468 apply->shared()->set_length(2);
2471 InstallBuiltinFunctionIds();
2473 // Create a constructor for RegExp results (a variant of Array that
2474 // predefines the two properties index and match).
2476 // RegExpResult initial map.
2478 // Find global.Array.prototype to inherit from.
2479 Handle<JSFunction> array_constructor(native_context()->array_function());
2480 Handle<JSObject> array_prototype(
2481 JSObject::cast(array_constructor->instance_prototype()));
2484 Handle<Map> initial_map =
2485 factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
2486 initial_map->SetConstructor(*array_constructor);
2488 // Set prototype on map.
2489 initial_map->set_non_instance_prototype(false);
2490 Map::SetPrototype(initial_map, array_prototype);
2492 // Update map with length accessor from Array and add "index" and "input".
2493 Map::EnsureDescriptorSlack(initial_map, 3);
2496 JSFunction* array_function = native_context()->array_function();
2497 Handle<DescriptorArray> array_descriptors(
2498 array_function->initial_map()->instance_descriptors());
2499 Handle<String> length = factory()->length_string();
2500 int old = array_descriptors->SearchWithCache(
2501 *length, array_function->initial_map());
2502 DCHECK(old != DescriptorArray::kNotFound);
2503 AccessorConstantDescriptor desc(
2504 length, handle(array_descriptors->GetValue(old), isolate()),
2505 array_descriptors->GetDetails(old).attributes());
2506 initial_map->AppendDescriptor(&desc);
2509 DataDescriptor index_field(factory()->index_string(),
2510 JSRegExpResult::kIndexIndex, NONE,
2511 Representation::Tagged());
2512 initial_map->AppendDescriptor(&index_field);
2516 DataDescriptor input_field(factory()->input_string(),
2517 JSRegExpResult::kInputIndex, NONE,
2518 Representation::Tagged());
2519 initial_map->AppendDescriptor(&input_field);
2522 initial_map->set_inobject_properties(2);
2523 initial_map->set_unused_property_fields(0);
2525 native_context()->set_regexp_result_map(*initial_map);
2528 // Add @@iterator method to the arguments object maps.
2530 PropertyAttributes attribs = DONT_ENUM;
2531 Handle<AccessorInfo> arguments_iterator =
2532 Accessors::ArgumentsIteratorInfo(isolate(), attribs);
2534 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2535 arguments_iterator, attribs);
2536 Handle<Map> map(native_context()->sloppy_arguments_map());
2537 Map::EnsureDescriptorSlack(map, 1);
2538 map->AppendDescriptor(&d);
2541 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2542 arguments_iterator, attribs);
2543 Handle<Map> map(native_context()->fast_aliased_arguments_map());
2544 Map::EnsureDescriptorSlack(map, 1);
2545 map->AppendDescriptor(&d);
2548 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2549 arguments_iterator, attribs);
2550 Handle<Map> map(native_context()->slow_aliased_arguments_map());
2551 Map::EnsureDescriptorSlack(map, 1);
2552 map->AppendDescriptor(&d);
2555 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2556 arguments_iterator, attribs);
2557 Handle<Map> map(native_context()->strict_arguments_map());
2558 Map::EnsureDescriptorSlack(map, 1);
2559 map->AppendDescriptor(&d);
2564 if (FLAG_verify_heap) {
2565 builtins->ObjectVerify();
2573 bool Genesis::InstallExperimentalNatives() {
2574 static const char* harmony_array_includes_natives[] = {
2575 "native harmony-array-includes.js", nullptr};
2576 static const char* harmony_proxies_natives[] = {"native proxy.js", nullptr};
2577 static const char* harmony_modules_natives[] = {nullptr};
2578 static const char* harmony_regexps_natives[] = {"native harmony-regexp.js",
2580 static const char* harmony_arrow_functions_natives[] = {nullptr};
2581 static const char* harmony_tostring_natives[] = {"native harmony-tostring.js",
2583 static const char* harmony_sloppy_natives[] = {nullptr};
2584 static const char* harmony_sloppy_let_natives[] = {nullptr};
2585 static const char* harmony_unicode_natives[] = {nullptr};
2586 static const char* harmony_unicode_regexps_natives[] = {nullptr};
2587 static const char* harmony_computed_property_names_natives[] = {nullptr};
2588 static const char* harmony_rest_parameters_natives[] = {nullptr};
2589 static const char* harmony_reflect_natives[] = {"native harmony-reflect.js",
2591 static const char* harmony_spreadcalls_natives[] = {
2592 "native harmony-spread.js", nullptr};
2593 static const char* harmony_destructuring_natives[] = {nullptr};
2594 static const char* harmony_object_natives[] = {"native harmony-object.js",
2596 static const char* harmony_spread_arrays_natives[] = {nullptr};
2597 static const char* harmony_sharedarraybuffer_natives[] = {
2598 "native harmony-sharedarraybuffer.js", NULL};
2599 static const char* harmony_atomics_natives[] = {"native harmony-atomics.js",
2601 static const char* harmony_new_target_natives[] = {nullptr};
2602 static const char* harmony_concat_spreadable_natives[] = {
2603 "native harmony-concat-spreadable.js", nullptr};
2604 static const char* harmony_simd_natives[] = {"native harmony-simd.js",
2607 for (int i = ExperimentalNatives::GetDebuggerCount();
2608 i < ExperimentalNatives::GetBuiltinsCount(); i++) {
2609 #define INSTALL_EXPERIMENTAL_NATIVES(id, desc) \
2611 for (size_t j = 0; id##_natives[j] != NULL; j++) { \
2612 Vector<const char> script_name = ExperimentalNatives::GetScriptName(i); \
2613 if (strncmp(script_name.start(), id##_natives[j], \
2614 script_name.length()) == 0) { \
2615 if (!Bootstrapper::CompileExperimentalBuiltin(isolate(), i)) { \
2621 HARMONY_INPROGRESS(INSTALL_EXPERIMENTAL_NATIVES);
2622 HARMONY_STAGED(INSTALL_EXPERIMENTAL_NATIVES);
2623 HARMONY_SHIPPING(INSTALL_EXPERIMENTAL_NATIVES);
2624 #undef INSTALL_EXPERIMENTAL_NATIVES
2627 if (!CallUtilsFunction(isolate(), "PostExperimentals")) return false;
2629 InstallExperimentalNativeFunctions();
2630 InstallExperimentalBuiltinFunctionIds();
2635 bool Genesis::InstallExtraNatives() {
2636 for (int i = ExtraNatives::GetDebuggerCount();
2637 i < ExtraNatives::GetBuiltinsCount(); i++) {
2638 if (!Bootstrapper::CompileExtraBuiltin(isolate(), i)) return false;
2645 bool Bootstrapper::InstallCodeStubNatives(Isolate* isolate) {
2646 for (int i = CodeStubNatives::GetDebuggerCount();
2647 i < CodeStubNatives::GetBuiltinsCount(); i++) {
2648 if (!CompileCodeStubBuiltin(isolate, i)) return false;
2655 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
2656 const char* function_name,
2657 BuiltinFunctionId id) {
2658 Isolate* isolate = holder->GetIsolate();
2659 Handle<Object> function_object =
2660 Object::GetProperty(isolate, holder, function_name).ToHandleChecked();
2661 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2662 function->shared()->set_function_data(Smi::FromInt(id));
2666 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2667 { #holder_expr, #fun_name, k##name } \
2671 void Genesis::InstallBuiltinFunctionIds() {
2672 HandleScope scope(isolate());
2673 struct BuiltinFunctionIds {
2674 const char* holder_expr;
2675 const char* fun_name;
2676 BuiltinFunctionId id;
2679 const BuiltinFunctionIds builtins[] = {
2680 FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2682 for (const BuiltinFunctionIds& builtin : builtins) {
2683 Handle<JSObject> holder =
2684 ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2685 InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2690 void Genesis::InstallExperimentalBuiltinFunctionIds() {
2691 if (FLAG_harmony_atomics) {
2692 struct BuiltinFunctionIds {
2693 const char* holder_expr;
2694 const char* fun_name;
2695 BuiltinFunctionId id;
2698 const BuiltinFunctionIds atomic_builtins[] = {
2699 ATOMIC_FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2701 for (const BuiltinFunctionIds& builtin : atomic_builtins) {
2702 Handle<JSObject> holder =
2703 ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2704 InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2710 #undef INSTALL_BUILTIN_ID
2713 // Do not forget to update macros.py with named constant
2715 #define JSFUNCTION_RESULT_CACHE_LIST(F) \
2716 F(16, native_context()->regexp_function())
2719 static FixedArray* CreateCache(int size, Handle<JSFunction> factory_function) {
2720 Factory* factory = factory_function->GetIsolate()->factory();
2721 // Caches are supposed to live for a long time, allocate in old space.
2722 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
2723 // Cannot use cast as object is not fully initialized yet.
2724 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
2725 *factory->NewFixedArrayWithHoles(array_size, TENURED));
2726 cache->set(JSFunctionResultCache::kFactoryIndex, *factory_function);
2727 cache->MakeZeroSize();
2732 void Genesis::InstallJSFunctionResultCaches() {
2733 const int kNumberOfCaches = 0 +
2734 #define F(size, func) + 1
2735 JSFUNCTION_RESULT_CACHE_LIST(F)
2739 Handle<FixedArray> caches =
2740 factory()->NewFixedArray(kNumberOfCaches, TENURED);
2744 #define F(size, func) do { \
2745 FixedArray* cache = CreateCache((size), Handle<JSFunction>(func)); \
2746 caches->set(index++, cache); \
2749 JSFUNCTION_RESULT_CACHE_LIST(F);
2753 native_context()->set_jsfunction_result_caches(*caches);
2757 void Genesis::InitializeNormalizedMapCaches() {
2758 Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
2759 native_context()->set_normalized_map_cache(*cache);
2763 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
2764 v8::ExtensionConfiguration* extensions) {
2765 BootstrapperActive active(this);
2766 SaveContext saved_context(isolate_);
2767 isolate_->set_context(*native_context);
2768 return Genesis::InstallExtensions(native_context, extensions) &&
2769 Genesis::InstallSpecialObjects(native_context);
2773 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
2774 Isolate* isolate = native_context->GetIsolate();
2775 // Don't install extensions into the snapshot.
2776 if (isolate->serializer_enabled()) return true;
2778 Factory* factory = isolate->factory();
2779 HandleScope scope(isolate);
2780 Handle<JSGlobalObject> global(JSGlobalObject::cast(
2781 native_context->global_object()));
2783 Handle<JSObject> Error = Handle<JSObject>::cast(
2784 Object::GetProperty(isolate, global, "Error").ToHandleChecked());
2785 Handle<String> name =
2786 factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("stackTraceLimit"));
2787 Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit), isolate);
2788 JSObject::AddProperty(Error, name, stack_trace_limit, NONE);
2790 // By now the utils object is useless and can be removed.
2791 native_context->set_natives_utils_object(*factory->undefined_value());
2793 // Expose the natives in global if a name for it is specified.
2794 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
2795 Handle<String> natives_key =
2796 factory->InternalizeUtf8String(FLAG_expose_natives_as);
2797 uint32_t dummy_index;
2798 if (natives_key->AsArrayIndex(&dummy_index)) return true;
2799 Handle<JSBuiltinsObject> natives(global->builtins());
2800 JSObject::AddProperty(global, natives_key, natives, DONT_ENUM);
2803 // Expose the stack trace symbol to native JS.
2804 RETURN_ON_EXCEPTION_VALUE(isolate,
2805 JSObject::SetOwnPropertyIgnoreAttributes(
2806 handle(native_context->builtins(), isolate),
2807 factory->InternalizeOneByteString(
2808 STATIC_CHAR_VECTOR("$stackTraceSymbol")),
2809 factory->stack_trace_symbol(), NONE),
2812 // Expose the debug global object in global if a name for it is specified.
2813 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
2814 // If loading fails we just bail out without installing the
2815 // debugger but without tanking the whole context.
2816 Debug* debug = isolate->debug();
2817 if (!debug->Load()) return true;
2818 Handle<Context> debug_context = debug->debug_context();
2819 // Set the security token for the debugger context to the same as
2820 // the shell native context to allow calling between these (otherwise
2821 // exposing debug global object doesn't make much sense).
2822 debug_context->set_security_token(native_context->security_token());
2823 Handle<String> debug_string =
2824 factory->InternalizeUtf8String(FLAG_expose_debug_as);
2826 if (debug_string->AsArrayIndex(&index)) return true;
2827 Handle<Object> global_proxy(debug_context->global_proxy(), isolate);
2828 JSObject::AddProperty(global, debug_string, global_proxy, DONT_ENUM);
2834 static uint32_t Hash(RegisteredExtension* extension) {
2835 return v8::internal::ComputePointerHash(extension);
2839 Genesis::ExtensionStates::ExtensionStates() : map_(HashMap::PointersMatch, 8) {}
2841 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2842 RegisteredExtension* extension) {
2843 i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension));
2844 if (entry == NULL) {
2847 return static_cast<ExtensionTraversalState>(
2848 reinterpret_cast<intptr_t>(entry->value));
2851 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2852 ExtensionTraversalState state) {
2853 map_.LookupOrInsert(extension, Hash(extension))->value =
2854 reinterpret_cast<void*>(static_cast<intptr_t>(state));
2858 bool Genesis::InstallExtensions(Handle<Context> native_context,
2859 v8::ExtensionConfiguration* extensions) {
2860 Isolate* isolate = native_context->GetIsolate();
2861 ExtensionStates extension_states; // All extensions have state UNVISITED.
2862 return InstallAutoExtensions(isolate, &extension_states) &&
2863 (!FLAG_expose_free_buffer ||
2864 InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
2866 InstallExtension(isolate, "v8/gc", &extension_states)) &&
2867 (!FLAG_expose_externalize_string ||
2868 InstallExtension(isolate, "v8/externalize", &extension_states)) &&
2869 (!FLAG_track_gc_object_stats ||
2870 InstallExtension(isolate, "v8/statistics", &extension_states)) &&
2871 (!FLAG_expose_trigger_failure ||
2872 InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
2873 InstallRequestedExtensions(isolate, extensions, &extension_states);
2877 bool Genesis::InstallAutoExtensions(Isolate* isolate,
2878 ExtensionStates* extension_states) {
2879 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2882 if (it->extension()->auto_enable() &&
2883 !InstallExtension(isolate, it, extension_states)) {
2891 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
2892 v8::ExtensionConfiguration* extensions,
2893 ExtensionStates* extension_states) {
2894 for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
2895 if (!InstallExtension(isolate, *it, extension_states)) return false;
2901 // Installs a named extension. This methods is unoptimized and does
2902 // not scale well if we want to support a large number of extensions.
2903 bool Genesis::InstallExtension(Isolate* isolate,
2905 ExtensionStates* extension_states) {
2906 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2909 if (strcmp(name, it->extension()->name()) == 0) {
2910 return InstallExtension(isolate, it, extension_states);
2913 return Utils::ApiCheck(false,
2914 "v8::Context::New()",
2915 "Cannot find required extension");
2919 bool Genesis::InstallExtension(Isolate* isolate,
2920 v8::RegisteredExtension* current,
2921 ExtensionStates* extension_states) {
2922 HandleScope scope(isolate);
2924 if (extension_states->get_state(current) == INSTALLED) return true;
2925 // The current node has already been visited so there must be a
2926 // cycle in the dependency graph; fail.
2927 if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
2928 "v8::Context::New()",
2929 "Circular extension dependency")) {
2932 DCHECK(extension_states->get_state(current) == UNVISITED);
2933 extension_states->set_state(current, VISITED);
2934 v8::Extension* extension = current->extension();
2935 // Install the extension's dependencies
2936 for (int i = 0; i < extension->dependency_count(); i++) {
2937 if (!InstallExtension(isolate,
2938 extension->dependencies()[i],
2939 extension_states)) {
2943 // We do not expect this to throw an exception. Change this if it does.
2944 bool result = CompileExtension(isolate, extension);
2945 DCHECK(isolate->has_pending_exception() != result);
2947 // We print out the name of the extension that fail to install.
2948 // When an error is thrown during bootstrapping we automatically print
2949 // the line number at which this happened to the console in the isolate
2950 // error throwing functionality.
2951 base::OS::PrintError("Error installing extension '%s'.\n",
2952 current->extension()->name());
2953 isolate->clear_pending_exception();
2955 extension_states->set_state(current, INSTALLED);
2956 isolate->NotifyExtensionInstalled();
2961 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2962 HandleScope scope(isolate());
2963 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2964 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2965 Handle<Object> function_object = Object::GetProperty(
2966 isolate(), builtins, Builtins::GetName(id)).ToHandleChecked();
2967 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2968 builtins->set_javascript_builtin(id, *function);
2974 bool Genesis::ConfigureGlobalObjects(
2975 v8::Local<v8::ObjectTemplate> global_proxy_template) {
2976 Handle<JSObject> global_proxy(
2977 JSObject::cast(native_context()->global_proxy()));
2978 Handle<JSObject> global_object(
2979 JSObject::cast(native_context()->global_object()));
2981 if (!global_proxy_template.IsEmpty()) {
2982 // Configure the global proxy object.
2983 Handle<ObjectTemplateInfo> global_proxy_data =
2984 v8::Utils::OpenHandle(*global_proxy_template);
2985 if (!ConfigureApiObject(global_proxy, global_proxy_data)) return false;
2987 // Configure the global object.
2988 Handle<FunctionTemplateInfo> proxy_constructor(
2989 FunctionTemplateInfo::cast(global_proxy_data->constructor()));
2990 if (!proxy_constructor->prototype_template()->IsUndefined()) {
2991 Handle<ObjectTemplateInfo> global_object_data(
2992 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2993 if (!ConfigureApiObject(global_object, global_object_data)) return false;
2997 SetObjectPrototype(global_proxy, global_object);
2999 native_context()->set_initial_array_prototype(
3000 JSArray::cast(native_context()->array_function()->prototype()));
3001 native_context()->set_array_buffer_map(
3002 native_context()->array_buffer_fun()->initial_map());
3003 native_context()->set_js_map_map(
3004 native_context()->js_map_fun()->initial_map());
3005 native_context()->set_js_set_map(
3006 native_context()->js_set_fun()->initial_map());
3012 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
3013 Handle<ObjectTemplateInfo> object_template) {
3014 DCHECK(!object_template.is_null());
3015 DCHECK(FunctionTemplateInfo::cast(object_template->constructor())
3016 ->IsTemplateFor(object->map()));;
3018 MaybeHandle<JSObject> maybe_obj =
3019 ApiNatives::InstantiateObject(object_template);
3020 Handle<JSObject> obj;
3021 if (!maybe_obj.ToHandle(&obj)) {
3022 DCHECK(isolate()->has_pending_exception());
3023 isolate()->clear_pending_exception();
3026 TransferObject(obj, object);
3031 void Genesis::TransferNamedProperties(Handle<JSObject> from,
3032 Handle<JSObject> to) {
3033 // If JSObject::AddProperty asserts due to already existing property,
3034 // it is likely due to both global objects sharing property name(s).
3035 // Merging those two global objects is impossible.
3036 // The global template must not create properties that already exist
3037 // in the snapshotted global object.
3038 if (from->HasFastProperties()) {
3039 Handle<DescriptorArray> descs =
3040 Handle<DescriptorArray>(from->map()->instance_descriptors());
3041 for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
3042 PropertyDetails details = descs->GetDetails(i);
3043 switch (details.type()) {
3045 HandleScope inner(isolate());
3046 Handle<Name> key = Handle<Name>(descs->GetKey(i));
3047 FieldIndex index = FieldIndex::ForDescriptor(from->map(), i);
3048 DCHECK(!descs->GetDetails(i).representation().IsDouble());
3049 Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
3051 JSObject::AddProperty(to, key, value, details.attributes());
3054 case DATA_CONSTANT: {
3055 HandleScope inner(isolate());
3056 Handle<Name> key = Handle<Name>(descs->GetKey(i));
3057 Handle<Object> constant(descs->GetConstant(i), isolate());
3058 JSObject::AddProperty(to, key, constant, details.attributes());
3063 case ACCESSOR_CONSTANT: {
3064 Handle<Name> key(descs->GetKey(i));
3065 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3066 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3067 // If the property is already there we skip it
3068 if (it.IsFound()) continue;
3069 HandleScope inner(isolate());
3070 DCHECK(!to->HasFastProperties());
3071 // Add to dictionary.
3072 Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
3073 PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
3074 PropertyCellType::kMutable);
3075 JSObject::SetNormalizedProperty(to, key, callbacks, d);
3080 } else if (from->IsGlobalObject()) {
3081 Handle<GlobalDictionary> properties =
3082 Handle<GlobalDictionary>(from->global_dictionary());
3083 int capacity = properties->Capacity();
3084 for (int i = 0; i < capacity; i++) {
3085 Object* raw_key(properties->KeyAt(i));
3086 if (properties->IsKey(raw_key)) {
3087 DCHECK(raw_key->IsName());
3088 // If the property is already there we skip it.
3089 Handle<Name> key(Name::cast(raw_key));
3090 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3091 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3092 if (it.IsFound()) continue;
3093 // Set the property.
3094 DCHECK(properties->ValueAt(i)->IsPropertyCell());
3095 Handle<PropertyCell> cell(PropertyCell::cast(properties->ValueAt(i)));
3096 Handle<Object> value(cell->value(), isolate());
3097 if (value->IsTheHole()) continue;
3098 PropertyDetails details = cell->property_details();
3099 DCHECK_EQ(kData, details.kind());
3100 JSObject::AddProperty(to, key, value, details.attributes());
3104 Handle<NameDictionary> properties =
3105 Handle<NameDictionary>(from->property_dictionary());
3106 int capacity = properties->Capacity();
3107 for (int i = 0; i < capacity; i++) {
3108 Object* raw_key(properties->KeyAt(i));
3109 if (properties->IsKey(raw_key)) {
3110 DCHECK(raw_key->IsName());
3111 // If the property is already there we skip it.
3112 Handle<Name> key(Name::cast(raw_key));
3113 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3114 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3115 if (it.IsFound()) continue;
3116 // Set the property.
3117 Handle<Object> value = Handle<Object>(properties->ValueAt(i),
3119 DCHECK(!value->IsCell());
3120 DCHECK(!value->IsTheHole());
3121 PropertyDetails details = properties->DetailsAt(i);
3122 DCHECK_EQ(kData, details.kind());
3123 JSObject::AddProperty(to, key, value, details.attributes());
3130 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
3131 Handle<JSObject> to) {
3132 // Cloning the elements array is sufficient.
3133 Handle<FixedArray> from_elements =
3134 Handle<FixedArray>(FixedArray::cast(from->elements()));
3135 Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
3136 to->set_elements(*to_elements);
3140 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
3141 HandleScope outer(isolate());
3143 DCHECK(!from->IsJSArray());
3144 DCHECK(!to->IsJSArray());
3146 TransferNamedProperties(from, to);
3147 TransferIndexedProperties(from, to);
3149 // Transfer the prototype (new map is needed).
3150 Handle<Object> proto(from->map()->prototype(), isolate());
3151 SetObjectPrototype(to, proto);
3155 void Genesis::MakeFunctionInstancePrototypeWritable() {
3156 // The maps with writable prototype are created in CreateEmptyFunction
3157 // and CreateStrictModeFunctionMaps respectively. Initially the maps are
3158 // created with read-only prototype for JS builtins processing.
3159 DCHECK(!sloppy_function_map_writable_prototype_.is_null());
3160 DCHECK(!strict_function_map_writable_prototype_.is_null());
3162 // Replace function instance maps to make prototype writable.
3163 native_context()->set_sloppy_function_map(
3164 *sloppy_function_map_writable_prototype_);
3165 native_context()->set_strict_function_map(
3166 *strict_function_map_writable_prototype_);
3170 class NoTrackDoubleFieldsForSerializerScope {
3172 explicit NoTrackDoubleFieldsForSerializerScope(Isolate* isolate)
3173 : flag_(FLAG_track_double_fields), enabled_(false) {
3174 if (isolate->serializer_enabled()) {
3175 // Disable tracking double fields because heap numbers treated as
3176 // immutable by the serializer.
3177 FLAG_track_double_fields = false;
3182 ~NoTrackDoubleFieldsForSerializerScope() {
3184 FLAG_track_double_fields = flag_;
3194 Genesis::Genesis(Isolate* isolate,
3195 MaybeHandle<JSGlobalProxy> maybe_global_proxy,
3196 v8::Local<v8::ObjectTemplate> global_proxy_template,
3197 v8::ExtensionConfiguration* extensions,
3198 ContextType context_type)
3199 : isolate_(isolate), active_(isolate->bootstrapper()) {
3200 NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
3201 result_ = Handle<Context>::null();
3202 // Before creating the roots we must save the context and restore it
3203 // on all function exits.
3204 SaveContext saved_context(isolate);
3206 // During genesis, the boilerplate for stack overflow won't work until the
3207 // environment has been at least partially initialized. Add a stack check
3208 // before entering JS code to catch overflow early.
3209 StackLimitCheck check(isolate);
3210 if (check.HasOverflowed()) {
3211 isolate->StackOverflow();
3215 // The deserializer needs to hook up references to the global proxy.
3216 // Create an uninitialized global proxy now if we don't have one
3217 // and initialize it later in CreateNewGlobals.
3218 Handle<JSGlobalProxy> global_proxy;
3219 if (!maybe_global_proxy.ToHandle(&global_proxy)) {
3220 global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy();
3223 // We can only de-serialize a context if the isolate was initialized from
3224 // a snapshot. Otherwise we have to build the context from scratch.
3225 // Also create a context from scratch to expose natives, if required by flag.
3226 Handle<FixedArray> outdated_contexts;
3227 if (!isolate->initialized_from_snapshot() ||
3228 !Snapshot::NewContextFromSnapshot(isolate, global_proxy,
3230 .ToHandle(&native_context_)) {
3231 native_context_ = Handle<Context>();
3234 if (!native_context().is_null()) {
3235 AddToWeakNativeContextList(*native_context());
3236 isolate->set_context(*native_context());
3237 isolate->counters()->contexts_created_by_snapshot()->Increment();
3239 if (FLAG_trace_maps) {
3240 Handle<JSFunction> object_fun = isolate->object_function();
3241 PrintF("[TraceMap: InitialMap map= %p SFI= %d_Object ]\n",
3242 reinterpret_cast<void*>(object_fun->initial_map()),
3243 object_fun->shared()->unique_id());
3244 Map::TraceAllTransitions(object_fun->initial_map());
3247 Handle<GlobalObject> global_object =
3248 CreateNewGlobals(global_proxy_template, global_proxy);
3250 HookUpGlobalProxy(global_object, global_proxy);
3251 HookUpGlobalObject(global_object, outdated_contexts);
3252 native_context()->builtins()->set_global_proxy(
3253 native_context()->global_proxy());
3254 HookUpGlobalThisBinding(outdated_contexts);
3256 if (!ConfigureGlobalObjects(global_proxy_template)) return;
3258 // We get here if there was no context snapshot.
3260 Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
3261 CreateStrictModeFunctionMaps(empty_function);
3262 CreateStrongModeFunctionMaps(empty_function);
3263 Handle<GlobalObject> global_object =
3264 CreateNewGlobals(global_proxy_template, global_proxy);
3265 HookUpGlobalProxy(global_object, global_proxy);
3266 InitializeGlobal(global_object, empty_function, context_type);
3267 InstallJSFunctionResultCaches();
3268 InitializeNormalizedMapCaches();
3270 if (!InstallNatives(context_type)) return;
3272 MakeFunctionInstancePrototypeWritable();
3274 if (context_type == FULL_CONTEXT) {
3275 if (!ConfigureGlobalObjects(global_proxy_template)) return;
3277 isolate->counters()->contexts_created_from_scratch()->Increment();
3280 // Install experimental and extra natives. Do not include them into the
3281 // snapshot as we should be able to turn them off at runtime. Re-installing
3282 // them after they have already been deserialized would also fail.
3283 if (context_type == FULL_CONTEXT) {
3284 if (!isolate->serializer_enabled()) {
3285 InitializeExperimentalGlobal();
3286 if (!InstallExperimentalNatives()) return;
3287 if (!InstallExtraNatives()) return;
3290 // The serializer cannot serialize typed arrays. Reset those typed arrays
3291 // for each new context.
3292 InitializeBuiltinTypedArrays();
3295 result_ = native_context();
3299 // Support for thread preemption.
3301 // Reserve space for statics needing saving and restoring.
3302 int Bootstrapper::ArchiveSpacePerThread() {
3303 return sizeof(NestingCounterType);
3307 // Archive statics that are thread-local.
3308 char* Bootstrapper::ArchiveState(char* to) {
3309 *reinterpret_cast<NestingCounterType*>(to) = nesting_;
3311 return to + sizeof(NestingCounterType);
3315 // Restore statics that are thread-local.
3316 char* Bootstrapper::RestoreState(char* from) {
3317 nesting_ = *reinterpret_cast<NestingCounterType*>(from);
3318 return from + sizeof(NestingCounterType);
3322 // Called when the top-level V8 mutex is destroyed.
3323 void Bootstrapper::FreeThreadResources() {
3324 DCHECK(!IsActive());
3327 } // namespace internal