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,
1822 DONT_DELETE).Assert();
1827 void Genesis::InitializeBuiltinTypedArrays() {
1828 Handle<JSBuiltinsObject> builtins(native_context()->builtins());
1829 { // Initially seed the per-context random number generator using the
1830 // per-isolate random number generator.
1831 const size_t num_elements = 2;
1832 const size_t num_bytes = num_elements * sizeof(uint32_t);
1833 uint32_t* state = SetBuiltinTypedArray<uint32_t>(isolate(), builtins,
1834 kExternalUint32Array, NULL,
1835 num_elements, "rngstate");
1837 isolate()->random_number_generator()->NextBytes(state, num_bytes);
1838 } while (state[0] == 0 || state[1] == 0);
1841 { // Initialize trigonometric lookup tables and constants.
1842 const size_t num_elements = arraysize(fdlibm::MathConstants::constants);
1843 double* data = const_cast<double*>(fdlibm::MathConstants::constants);
1844 SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1845 data, num_elements, "kMath");
1848 { // Initialize a result array for rempio2 calculation
1849 const size_t num_elements = 2;
1851 SetBuiltinTypedArray<double>(isolate(), builtins, kExternalFloat64Array,
1852 NULL, num_elements, "rempio2result");
1853 for (size_t i = 0; i < num_elements; i++) data[i] = 0;
1858 #define EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(id) \
1859 void Genesis::InstallNativeFunctions_##id() {}
1861 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_modules)
1862 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_array_includes)
1863 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_regexps)
1864 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_arrow_functions)
1865 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_tostring)
1866 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sloppy)
1867 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_unicode)
1868 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_unicode_regexps)
1869 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_computed_property_names)
1870 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_rest_parameters)
1871 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_reflect)
1872 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spreadcalls)
1873 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_destructuring)
1874 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_object)
1875 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_spread_arrays)
1876 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_sharedarraybuffer)
1877 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_atomics)
1878 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_new_target)
1879 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_concat_spreadable)
1880 EMPTY_NATIVE_FUNCTIONS_FOR_FEATURE(harmony_simd)
1883 void Genesis::InstallNativeFunctions_harmony_proxies() {
1884 if (FLAG_harmony_proxies) {
1885 INSTALL_NATIVE(JSFunction, "$proxyDerivedHasTrap", derived_has_trap);
1886 INSTALL_NATIVE(JSFunction, "$proxyDerivedGetTrap", derived_get_trap);
1887 INSTALL_NATIVE(JSFunction, "$proxyDerivedSetTrap", derived_set_trap);
1888 INSTALL_NATIVE(JSFunction, "$proxyEnumerate", proxy_enumerate);
1893 #undef INSTALL_NATIVE
1895 #define EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(id) \
1896 void Genesis::InitializeGlobal_##id() {}
1898 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_modules)
1899 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_array_includes)
1900 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_arrow_functions)
1901 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_proxies)
1902 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_sloppy)
1903 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_unicode)
1904 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_computed_property_names)
1905 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_rest_parameters)
1906 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spreadcalls)
1907 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_destructuring)
1908 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_object)
1909 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_spread_arrays)
1910 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_atomics)
1911 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_new_target)
1912 EMPTY_INITIALIZE_GLOBAL_FOR_FEATURE(harmony_concat_spreadable)
1914 void Genesis::InitializeGlobal_harmony_regexps() {
1915 Handle<JSObject> builtins(native_context()->builtins());
1917 Handle<HeapObject> flag(FLAG_harmony_regexps ? heap()->true_value()
1918 : heap()->false_value());
1919 Runtime::SetObjectProperty(isolate(), builtins,
1920 factory()->harmony_regexps_string(), flag,
1925 void Genesis::InitializeGlobal_harmony_unicode_regexps() {
1926 Handle<JSObject> builtins(native_context()->builtins());
1928 Handle<HeapObject> flag(FLAG_harmony_unicode_regexps ? heap()->true_value()
1929 : heap()->false_value());
1930 Runtime::SetObjectProperty(isolate(), builtins,
1931 factory()->harmony_unicode_regexps_string(), flag,
1936 void Genesis::InitializeGlobal_harmony_reflect() {
1937 Handle<JSObject> builtins(native_context()->builtins());
1938 // Install references to functions of the Reflect object
1939 if (FLAG_harmony_reflect || FLAG_harmony_spreadcalls) {
1940 Handle<JSFunction> apply = InstallFunction(
1941 builtins, "$reflectApply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1942 MaybeHandle<JSObject>(), Builtins::kReflectApply);
1943 Handle<JSFunction> construct = InstallFunction(
1944 builtins, "$reflectConstruct", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1945 MaybeHandle<JSObject>(), Builtins::kReflectConstruct);
1946 apply->shared()->set_internal_formal_parameter_count(3);
1947 apply->shared()->set_length(3);
1949 construct->shared()->set_internal_formal_parameter_count(3);
1950 construct->shared()->set_length(2);
1953 if (!FLAG_harmony_reflect) return;
1954 Handle<JSGlobalObject> global(JSGlobalObject::cast(
1955 native_context()->global_object()));
1956 Handle<String> reflect_string =
1957 factory()->NewStringFromStaticChars("Reflect");
1958 Handle<Object> reflect =
1959 factory()->NewJSObject(isolate()->object_function(), TENURED);
1960 JSObject::AddProperty(global, reflect_string, reflect, DONT_ENUM);
1964 void Genesis::InitializeGlobal_harmony_tostring() {
1965 Handle<JSObject> builtins(native_context()->builtins());
1967 Handle<HeapObject> flag(FLAG_harmony_tostring ? heap()->true_value()
1968 : heap()->false_value());
1969 Runtime::SetObjectProperty(isolate(), builtins,
1970 factory()->harmony_tostring_string(), flag,
1975 void Genesis::InitializeGlobal_harmony_sharedarraybuffer() {
1976 if (!FLAG_harmony_sharedarraybuffer) return;
1978 Handle<JSGlobalObject> global(
1979 JSGlobalObject::cast(native_context()->global_object()));
1981 Handle<JSFunction> shared_array_buffer_fun = InstallFunction(
1982 global, "SharedArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1983 JSArrayBuffer::kSizeWithInternalFields,
1984 isolate()->initial_object_prototype(), Builtins::kIllegal);
1985 native_context()->set_shared_array_buffer_fun(*shared_array_buffer_fun);
1989 void Genesis::InitializeGlobal_harmony_simd() {
1990 Handle<JSGlobalObject> global(
1991 JSGlobalObject::cast(native_context()->global_object()));
1992 Isolate* isolate = global->GetIsolate();
1993 Factory* factory = isolate->factory();
1995 Handle<String> name = factory->InternalizeUtf8String("SIMD");
1996 Handle<JSFunction> cons = factory->NewFunction(name);
1997 JSFunction::SetInstancePrototype(
1999 Handle<Object>(native_context()->initial_object_prototype(), isolate));
2000 cons->SetInstanceClassName(*name);
2001 Handle<JSObject> simd_object = factory->NewJSObject(cons, TENURED);
2002 DCHECK(simd_object->IsJSObject());
2003 JSObject::AddProperty(global, name, simd_object, DONT_ENUM);
2005 Handle<JSFunction> float32x4_function =
2006 InstallFunction(simd_object, "Float32x4", JS_VALUE_TYPE, JSValue::kSize,
2007 isolate->initial_object_prototype(), Builtins::kIllegal);
2008 // Set the instance class name since InstallFunction only does this when
2009 // we install on the GlobalObject.
2010 float32x4_function->SetInstanceClassName(*factory->Float32x4_string());
2011 native_context()->set_float32x4_function(*float32x4_function);
2015 Handle<JSFunction> Genesis::InstallInternalArray(Handle<JSObject> target,
2017 ElementsKind elements_kind) {
2018 // --- I n t e r n a l A r r a y ---
2019 // An array constructor on the builtins object that works like
2020 // the public Array constructor, except that its prototype
2021 // doesn't inherit from Object.prototype.
2022 // To be used only for internal work by builtins. Instances
2023 // must not be leaked to user code.
2024 Handle<JSObject> prototype =
2025 factory()->NewJSObject(isolate()->object_function(), TENURED);
2026 Handle<JSFunction> array_function =
2027 InstallFunction(target, name, JS_ARRAY_TYPE, JSArray::kSize, prototype,
2028 Builtins::kInternalArrayCode);
2030 InternalArrayConstructorStub internal_array_constructor_stub(isolate());
2031 Handle<Code> code = internal_array_constructor_stub.GetCode();
2032 array_function->shared()->set_construct_stub(*code);
2033 array_function->shared()->DontAdaptArguments();
2035 Handle<Map> original_map(array_function->initial_map());
2036 Handle<Map> initial_map = Map::Copy(original_map, "InternalArray");
2037 initial_map->set_elements_kind(elements_kind);
2038 JSFunction::SetInitialMap(array_function, initial_map, prototype);
2040 // Make "length" magic on instances.
2041 Map::EnsureDescriptorSlack(initial_map, 1);
2043 PropertyAttributes attribs = static_cast<PropertyAttributes>(
2044 DONT_ENUM | DONT_DELETE);
2046 Handle<AccessorInfo> array_length =
2047 Accessors::ArrayLengthInfo(isolate(), attribs);
2049 AccessorConstantDescriptor d(Handle<Name>(Name::cast(array_length->name())),
2050 array_length, attribs);
2051 initial_map->AppendDescriptor(&d);
2054 return array_function;
2058 bool Genesis::InstallNatives(ContextType context_type) {
2059 HandleScope scope(isolate());
2061 // Create a function for the builtins object. Allocate space for the
2062 // JavaScript builtins, a reference to the builtins object
2063 // (itself) and a reference to the native_context directly in the object.
2064 Handle<Code> code = Handle<Code>(
2065 isolate()->builtins()->builtin(Builtins::kIllegal));
2066 Handle<JSFunction> builtins_fun = factory()->NewFunction(
2067 factory()->empty_string(), code, JS_BUILTINS_OBJECT_TYPE,
2068 JSBuiltinsObject::kSize);
2070 Handle<String> name =
2071 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2072 builtins_fun->shared()->set_instance_class_name(*name);
2073 builtins_fun->initial_map()->set_dictionary_map(true);
2074 builtins_fun->initial_map()->set_prototype(heap()->null_value());
2076 // Allocate the builtins object.
2077 Handle<JSBuiltinsObject> builtins =
2078 Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
2079 builtins->set_builtins(*builtins);
2080 builtins->set_native_context(*native_context());
2081 builtins->set_global_proxy(native_context()->global_proxy());
2084 // Set up the 'builtin' property, which refers to the js builtins object.
2085 static const PropertyAttributes attributes =
2086 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2087 Handle<String> builtins_string =
2088 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("builtins"));
2089 JSObject::AddProperty(builtins, builtins_string, builtins, attributes);
2091 // Set up the reference from the global object to the builtins object.
2092 JSGlobalObject::cast(native_context()->global_object())->
2093 set_builtins(*builtins);
2095 // Create a bridge function that has context in the native context.
2096 Handle<JSFunction> bridge = factory()->NewFunction(factory()->empty_string());
2097 DCHECK(bridge->context() == *isolate()->native_context());
2099 // Allocate the builtins context.
2100 Handle<Context> context =
2101 factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
2102 context->set_global_object(*builtins); // override builtins global object
2104 native_context()->set_runtime_context(*context);
2106 if (context_type == THIN_CONTEXT) {
2107 int js_builtins_script_index = Natives::GetDebuggerCount();
2108 if (!Bootstrapper::CompileBuiltin(isolate(), js_builtins_script_index))
2110 if (!InstallJSBuiltins(builtins)) return false;
2114 // Set up the utils object as shared container between native scripts.
2115 Handle<JSObject> utils = factory()->NewJSObject(isolate()->object_function());
2116 JSObject::NormalizeProperties(utils, CLEAR_INOBJECT_PROPERTIES, 16,
2117 "utils container for native scripts");
2118 native_context()->set_natives_utils_object(*utils);
2120 Handle<JSObject> extras_exports =
2121 factory()->NewJSObject(isolate()->object_function());
2122 JSObject::NormalizeProperties(extras_exports, CLEAR_INOBJECT_PROPERTIES, 2,
2123 "container to export to extra natives");
2124 native_context()->set_extras_exports_object(*extras_exports);
2126 if (FLAG_expose_natives_as != NULL) {
2127 Handle<String> utils_key = factory()->NewStringFromAsciiChecked("utils");
2128 JSObject::AddProperty(builtins, utils_key, utils, NONE);
2132 // Builtin functions for Script.
2133 Handle<JSFunction> script_fun = InstallFunction(
2134 builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
2135 isolate()->initial_object_prototype(), Builtins::kIllegal);
2136 Handle<JSObject> prototype =
2137 factory()->NewJSObject(isolate()->object_function(), TENURED);
2138 Accessors::FunctionSetPrototype(script_fun, prototype).Assert();
2139 native_context()->set_script_function(*script_fun);
2141 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
2142 Map::EnsureDescriptorSlack(script_map, 15);
2144 PropertyAttributes attribs =
2145 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2147 Handle<AccessorInfo> script_column =
2148 Accessors::ScriptColumnOffsetInfo(isolate(), attribs);
2150 AccessorConstantDescriptor d(
2151 Handle<Name>(Name::cast(script_column->name())), script_column,
2153 script_map->AppendDescriptor(&d);
2156 Handle<AccessorInfo> script_id =
2157 Accessors::ScriptIdInfo(isolate(), attribs);
2159 AccessorConstantDescriptor d(Handle<Name>(Name::cast(script_id->name())),
2160 script_id, attribs);
2161 script_map->AppendDescriptor(&d);
2165 Handle<AccessorInfo> script_name =
2166 Accessors::ScriptNameInfo(isolate(), attribs);
2168 AccessorConstantDescriptor d(
2169 Handle<Name>(Name::cast(script_name->name())), script_name, attribs);
2170 script_map->AppendDescriptor(&d);
2173 Handle<AccessorInfo> script_line =
2174 Accessors::ScriptLineOffsetInfo(isolate(), attribs);
2176 AccessorConstantDescriptor d(
2177 Handle<Name>(Name::cast(script_line->name())), script_line, attribs);
2178 script_map->AppendDescriptor(&d);
2181 Handle<AccessorInfo> script_source =
2182 Accessors::ScriptSourceInfo(isolate(), attribs);
2184 AccessorConstantDescriptor d(
2185 Handle<Name>(Name::cast(script_source->name())), script_source,
2187 script_map->AppendDescriptor(&d);
2190 Handle<AccessorInfo> script_type =
2191 Accessors::ScriptTypeInfo(isolate(), attribs);
2193 AccessorConstantDescriptor d(
2194 Handle<Name>(Name::cast(script_type->name())), script_type, attribs);
2195 script_map->AppendDescriptor(&d);
2198 Handle<AccessorInfo> script_compilation_type =
2199 Accessors::ScriptCompilationTypeInfo(isolate(), attribs);
2201 AccessorConstantDescriptor d(
2202 Handle<Name>(Name::cast(script_compilation_type->name())),
2203 script_compilation_type, attribs);
2204 script_map->AppendDescriptor(&d);
2207 Handle<AccessorInfo> script_line_ends =
2208 Accessors::ScriptLineEndsInfo(isolate(), attribs);
2210 AccessorConstantDescriptor d(
2211 Handle<Name>(Name::cast(script_line_ends->name())), script_line_ends,
2213 script_map->AppendDescriptor(&d);
2216 Handle<AccessorInfo> script_context_data =
2217 Accessors::ScriptContextDataInfo(isolate(), attribs);
2219 AccessorConstantDescriptor d(
2220 Handle<Name>(Name::cast(script_context_data->name())),
2221 script_context_data, attribs);
2222 script_map->AppendDescriptor(&d);
2225 Handle<AccessorInfo> script_eval_from_script =
2226 Accessors::ScriptEvalFromScriptInfo(isolate(), attribs);
2228 AccessorConstantDescriptor d(
2229 Handle<Name>(Name::cast(script_eval_from_script->name())),
2230 script_eval_from_script, attribs);
2231 script_map->AppendDescriptor(&d);
2234 Handle<AccessorInfo> script_eval_from_script_position =
2235 Accessors::ScriptEvalFromScriptPositionInfo(isolate(), attribs);
2237 AccessorConstantDescriptor d(
2238 Handle<Name>(Name::cast(script_eval_from_script_position->name())),
2239 script_eval_from_script_position, attribs);
2240 script_map->AppendDescriptor(&d);
2243 Handle<AccessorInfo> script_eval_from_function_name =
2244 Accessors::ScriptEvalFromFunctionNameInfo(isolate(), attribs);
2246 AccessorConstantDescriptor d(
2247 Handle<Name>(Name::cast(script_eval_from_function_name->name())),
2248 script_eval_from_function_name, attribs);
2249 script_map->AppendDescriptor(&d);
2252 Handle<AccessorInfo> script_source_url =
2253 Accessors::ScriptSourceUrlInfo(isolate(), attribs);
2255 AccessorConstantDescriptor d(
2256 Handle<Name>(Name::cast(script_source_url->name())),
2257 script_source_url, attribs);
2258 script_map->AppendDescriptor(&d);
2261 Handle<AccessorInfo> script_source_mapping_url =
2262 Accessors::ScriptSourceMappingUrlInfo(isolate(), attribs);
2264 AccessorConstantDescriptor d(
2265 Handle<Name>(Name::cast(script_source_mapping_url->name())),
2266 script_source_mapping_url, attribs);
2267 script_map->AppendDescriptor(&d);
2270 Handle<AccessorInfo> script_is_embedder_debug_script =
2271 Accessors::ScriptIsEmbedderDebugScriptInfo(isolate(), attribs);
2273 AccessorConstantDescriptor d(
2274 Handle<Name>(Name::cast(script_is_embedder_debug_script->name())),
2275 script_is_embedder_debug_script, attribs);
2276 script_map->AppendDescriptor(&d);
2279 // Allocate the empty script.
2280 Handle<Script> script = factory()->NewScript(factory()->empty_string());
2281 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
2282 heap()->public_set_empty_script(*script);
2285 // Builtin function for OpaqueReference -- a JSValue-based object,
2286 // that keeps its field isolated from JavaScript code. It may store
2287 // objects, that JavaScript code may not access.
2288 Handle<JSFunction> opaque_reference_fun = InstallFunction(
2289 builtins, "OpaqueReference", JS_VALUE_TYPE, JSValue::kSize,
2290 isolate()->initial_object_prototype(), Builtins::kIllegal);
2291 Handle<JSObject> prototype =
2292 factory()->NewJSObject(isolate()->object_function(), TENURED);
2293 Accessors::FunctionSetPrototype(opaque_reference_fun, prototype).Assert();
2294 native_context()->set_opaque_reference_function(*opaque_reference_fun);
2297 // InternalArrays should not use Smi-Only array optimizations. There are too
2298 // many places in the C++ runtime code (e.g. RegEx) that assume that
2299 // elements in InternalArrays can be set to non-Smi values without going
2300 // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
2301 // transition easy to trap. Moreover, they rarely are smi-only.
2303 HandleScope scope(isolate());
2304 Handle<JSObject> utils =
2305 Handle<JSObject>::cast(isolate()->natives_utils_object());
2306 Handle<JSFunction> array_function =
2307 InstallInternalArray(utils, "InternalArray", FAST_HOLEY_ELEMENTS);
2308 native_context()->set_internal_array_function(*array_function);
2309 InstallInternalArray(utils, "InternalPackedArray", FAST_ELEMENTS);
2312 { // -- S e t I t e r a t o r
2313 Handle<JSFunction> set_iterator_function = InstallFunction(
2314 builtins, "SetIterator", JS_SET_ITERATOR_TYPE, JSSetIterator::kSize,
2315 isolate()->initial_object_prototype(), Builtins::kIllegal);
2316 native_context()->set_set_iterator_map(
2317 set_iterator_function->initial_map());
2320 { // -- M a p I t e r a t o r
2321 Handle<JSFunction> map_iterator_function = InstallFunction(
2322 builtins, "MapIterator", JS_MAP_ITERATOR_TYPE, JSMapIterator::kSize,
2323 isolate()->initial_object_prototype(), Builtins::kIllegal);
2324 native_context()->set_map_iterator_map(
2325 map_iterator_function->initial_map());
2329 // Create generator meta-objects and install them on the builtins object.
2330 Handle<JSObject> builtins(native_context()->builtins());
2331 Handle<JSObject> iterator_prototype =
2332 factory()->NewJSObject(isolate()->object_function(), TENURED);
2333 Handle<JSObject> generator_object_prototype =
2334 factory()->NewJSObject(isolate()->object_function(), TENURED);
2335 Handle<JSObject> generator_function_prototype =
2336 factory()->NewJSObject(isolate()->object_function(), TENURED);
2337 SetObjectPrototype(generator_object_prototype, iterator_prototype);
2338 JSObject::AddProperty(
2339 builtins, factory()->InternalizeUtf8String("$iteratorPrototype"),
2341 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2342 JSObject::AddProperty(
2344 factory()->InternalizeUtf8String("GeneratorFunctionPrototype"),
2345 generator_function_prototype,
2346 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY));
2348 JSObject::AddProperty(
2349 generator_function_prototype,
2350 factory()->InternalizeUtf8String("prototype"),
2351 generator_object_prototype,
2352 static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY));
2354 static const bool kUseStrictFunctionMap = true;
2355 InstallFunction(builtins, "GeneratorFunction", JS_FUNCTION_TYPE,
2356 JSFunction::kSize, generator_function_prototype,
2357 Builtins::kIllegal, kUseStrictFunctionMap);
2359 // Create maps for generator functions and their prototypes. Store those
2360 // maps in the native context. The "prototype" property descriptor is
2361 // writable, non-enumerable, and non-configurable (as per ES6 draft
2362 // 04-14-15, section 25.2.4.3).
2363 Handle<Map> strict_function_map(strict_function_map_writable_prototype_);
2364 // Generator functions do not have "caller" or "arguments" accessors.
2365 Handle<Map> sloppy_generator_function_map =
2366 Map::Copy(strict_function_map, "SloppyGeneratorFunction");
2367 Map::SetPrototype(sloppy_generator_function_map,
2368 generator_function_prototype);
2369 native_context()->set_sloppy_generator_function_map(
2370 *sloppy_generator_function_map);
2372 Handle<Map> strict_generator_function_map =
2373 Map::Copy(strict_function_map, "StrictGeneratorFunction");
2374 Map::SetPrototype(strict_generator_function_map,
2375 generator_function_prototype);
2376 native_context()->set_strict_generator_function_map(
2377 *strict_generator_function_map);
2379 Handle<Map> strong_function_map(native_context()->strong_function_map());
2380 Handle<Map> strong_generator_function_map =
2381 Map::Copy(strong_function_map, "StrongGeneratorFunction");
2382 Map::SetPrototype(strong_generator_function_map,
2383 generator_function_prototype);
2384 native_context()->set_strong_generator_function_map(
2385 *strong_generator_function_map);
2387 Handle<JSFunction> object_function(native_context()->object_function());
2388 Handle<Map> generator_object_prototype_map = Map::Create(isolate(), 0);
2389 Map::SetPrototype(generator_object_prototype_map,
2390 generator_object_prototype);
2391 native_context()->set_generator_object_prototype_map(
2392 *generator_object_prototype_map);
2395 if (FLAG_disable_native_files) {
2396 PrintF("Warning: Running without installed natives!\n");
2400 // Install public symbols.
2402 static const PropertyAttributes attributes =
2403 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
2404 #define INSTALL_PUBLIC_SYMBOL(name, varname, description) \
2405 Handle<String> varname = factory()->NewStringFromStaticChars(#varname); \
2406 JSObject::AddProperty(builtins, varname, factory()->name(), attributes);
2407 PUBLIC_SYMBOL_LIST(INSTALL_PUBLIC_SYMBOL)
2408 #undef INSTALL_PUBLIC_SYMBOL
2411 int i = Natives::GetDebuggerCount();
2412 if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2414 if (!InstallJSBuiltins(builtins)) return false;
2416 for (++i; i < Natives::GetBuiltinsCount(); ++i) {
2417 if (!Bootstrapper::CompileBuiltin(isolate(), i)) return false;
2420 if (!CallUtilsFunction(isolate(), "PostNatives")) return false;
2422 InstallNativeFunctions();
2424 auto function_cache =
2425 ObjectHashTable::New(isolate(), ApiNatives::kInitialFunctionCacheSize);
2426 native_context()->set_function_cache(*function_cache);
2428 // Store the map for the string prototype after the natives has been compiled
2429 // and the String function has been set up.
2430 Handle<JSFunction> string_function(native_context()->string_function());
2431 DCHECK(JSObject::cast(
2432 string_function->initial_map()->prototype())->HasFastProperties());
2433 native_context()->set_string_function_prototype_map(
2434 HeapObject::cast(string_function->initial_map()->prototype())->map());
2436 // Install Function.prototype.call and apply.
2438 Handle<String> key = factory()->Function_string();
2439 Handle<JSFunction> function =
2440 Handle<JSFunction>::cast(Object::GetProperty(
2441 handle(native_context()->global_object()), key).ToHandleChecked());
2442 Handle<JSObject> proto =
2443 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
2445 // Install the call and the apply functions.
2446 Handle<JSFunction> call =
2447 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2448 MaybeHandle<JSObject>(), Builtins::kFunctionCall);
2449 Handle<JSFunction> apply =
2450 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
2451 MaybeHandle<JSObject>(), Builtins::kFunctionApply);
2453 // Make sure that Function.prototype.call appears to be compiled.
2454 // The code will never be called, but inline caching for call will
2455 // only work if it appears to be compiled.
2456 call->shared()->DontAdaptArguments();
2457 DCHECK(call->is_compiled());
2459 // Set the expected parameters for apply to 2; required by builtin.
2460 apply->shared()->set_internal_formal_parameter_count(2);
2462 // Set the lengths for the functions to satisfy ECMA-262.
2463 call->shared()->set_length(1);
2464 apply->shared()->set_length(2);
2467 InstallBuiltinFunctionIds();
2469 // Create a constructor for RegExp results (a variant of Array that
2470 // predefines the two properties index and match).
2472 // RegExpResult initial map.
2474 // Find global.Array.prototype to inherit from.
2475 Handle<JSFunction> array_constructor(native_context()->array_function());
2476 Handle<JSObject> array_prototype(
2477 JSObject::cast(array_constructor->instance_prototype()));
2480 Handle<Map> initial_map =
2481 factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
2482 initial_map->SetConstructor(*array_constructor);
2484 // Set prototype on map.
2485 initial_map->set_non_instance_prototype(false);
2486 Map::SetPrototype(initial_map, array_prototype);
2488 // Update map with length accessor from Array and add "index" and "input".
2489 Map::EnsureDescriptorSlack(initial_map, 3);
2492 JSFunction* array_function = native_context()->array_function();
2493 Handle<DescriptorArray> array_descriptors(
2494 array_function->initial_map()->instance_descriptors());
2495 Handle<String> length = factory()->length_string();
2496 int old = array_descriptors->SearchWithCache(
2497 *length, array_function->initial_map());
2498 DCHECK(old != DescriptorArray::kNotFound);
2499 AccessorConstantDescriptor desc(
2500 length, handle(array_descriptors->GetValue(old), isolate()),
2501 array_descriptors->GetDetails(old).attributes());
2502 initial_map->AppendDescriptor(&desc);
2505 DataDescriptor index_field(factory()->index_string(),
2506 JSRegExpResult::kIndexIndex, NONE,
2507 Representation::Tagged());
2508 initial_map->AppendDescriptor(&index_field);
2512 DataDescriptor input_field(factory()->input_string(),
2513 JSRegExpResult::kInputIndex, NONE,
2514 Representation::Tagged());
2515 initial_map->AppendDescriptor(&input_field);
2518 initial_map->set_inobject_properties(2);
2519 initial_map->set_unused_property_fields(0);
2521 native_context()->set_regexp_result_map(*initial_map);
2524 // Add @@iterator method to the arguments object maps.
2526 PropertyAttributes attribs = DONT_ENUM;
2527 Handle<AccessorInfo> arguments_iterator =
2528 Accessors::ArgumentsIteratorInfo(isolate(), attribs);
2530 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2531 arguments_iterator, attribs);
2532 Handle<Map> map(native_context()->sloppy_arguments_map());
2533 Map::EnsureDescriptorSlack(map, 1);
2534 map->AppendDescriptor(&d);
2537 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2538 arguments_iterator, attribs);
2539 Handle<Map> map(native_context()->fast_aliased_arguments_map());
2540 Map::EnsureDescriptorSlack(map, 1);
2541 map->AppendDescriptor(&d);
2544 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2545 arguments_iterator, attribs);
2546 Handle<Map> map(native_context()->slow_aliased_arguments_map());
2547 Map::EnsureDescriptorSlack(map, 1);
2548 map->AppendDescriptor(&d);
2551 AccessorConstantDescriptor d(factory()->iterator_symbol(),
2552 arguments_iterator, attribs);
2553 Handle<Map> map(native_context()->strict_arguments_map());
2554 Map::EnsureDescriptorSlack(map, 1);
2555 map->AppendDescriptor(&d);
2560 if (FLAG_verify_heap) {
2561 builtins->ObjectVerify();
2569 bool Genesis::InstallExperimentalNatives() {
2570 static const char* harmony_array_includes_natives[] = {
2571 "native harmony-array-includes.js", nullptr};
2572 static const char* harmony_proxies_natives[] = {"native proxy.js", nullptr};
2573 static const char* harmony_modules_natives[] = {nullptr};
2574 static const char* harmony_regexps_natives[] = {"native harmony-regexp.js",
2576 static const char* harmony_arrow_functions_natives[] = {nullptr};
2577 static const char* harmony_tostring_natives[] = {"native harmony-tostring.js",
2579 static const char* harmony_sloppy_natives[] = {nullptr};
2580 static const char* harmony_unicode_natives[] = {nullptr};
2581 static const char* harmony_unicode_regexps_natives[] = {nullptr};
2582 static const char* harmony_computed_property_names_natives[] = {nullptr};
2583 static const char* harmony_rest_parameters_natives[] = {nullptr};
2584 static const char* harmony_reflect_natives[] = {"native harmony-reflect.js",
2586 static const char* harmony_spreadcalls_natives[] = {
2587 "native harmony-spread.js", nullptr};
2588 static const char* harmony_destructuring_natives[] = {nullptr};
2589 static const char* harmony_object_natives[] = {"native harmony-object.js",
2591 static const char* harmony_spread_arrays_natives[] = {nullptr};
2592 static const char* harmony_sharedarraybuffer_natives[] = {
2593 "native harmony-sharedarraybuffer.js", NULL};
2594 static const char* harmony_atomics_natives[] = {"native harmony-atomics.js",
2596 static const char* harmony_new_target_natives[] = {nullptr};
2597 static const char* harmony_concat_spreadable_natives[] = {
2598 "native harmony-concat-spreadable.js", nullptr};
2599 static const char* harmony_simd_natives[] = {"native harmony-simd.js",
2602 for (int i = ExperimentalNatives::GetDebuggerCount();
2603 i < ExperimentalNatives::GetBuiltinsCount(); i++) {
2604 #define INSTALL_EXPERIMENTAL_NATIVES(id, desc) \
2606 for (size_t j = 0; id##_natives[j] != NULL; j++) { \
2607 Vector<const char> script_name = ExperimentalNatives::GetScriptName(i); \
2608 if (strncmp(script_name.start(), id##_natives[j], \
2609 script_name.length()) == 0) { \
2610 if (!Bootstrapper::CompileExperimentalBuiltin(isolate(), i)) { \
2616 HARMONY_INPROGRESS(INSTALL_EXPERIMENTAL_NATIVES);
2617 HARMONY_STAGED(INSTALL_EXPERIMENTAL_NATIVES);
2618 HARMONY_SHIPPING(INSTALL_EXPERIMENTAL_NATIVES);
2619 #undef INSTALL_EXPERIMENTAL_NATIVES
2622 if (!CallUtilsFunction(isolate(), "PostExperimentals")) return false;
2624 InstallExperimentalNativeFunctions();
2625 InstallExperimentalBuiltinFunctionIds();
2630 bool Genesis::InstallExtraNatives() {
2631 for (int i = ExtraNatives::GetDebuggerCount();
2632 i < ExtraNatives::GetBuiltinsCount(); i++) {
2633 if (!Bootstrapper::CompileExtraBuiltin(isolate(), i)) return false;
2640 bool Bootstrapper::InstallCodeStubNatives(Isolate* isolate) {
2641 for (int i = CodeStubNatives::GetDebuggerCount();
2642 i < CodeStubNatives::GetBuiltinsCount(); i++) {
2643 if (!CompileCodeStubBuiltin(isolate, i)) return false;
2650 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
2651 const char* function_name,
2652 BuiltinFunctionId id) {
2653 Isolate* isolate = holder->GetIsolate();
2654 Handle<Object> function_object =
2655 Object::GetProperty(isolate, holder, function_name).ToHandleChecked();
2656 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2657 function->shared()->set_function_data(Smi::FromInt(id));
2661 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2662 { #holder_expr, #fun_name, k##name } \
2666 void Genesis::InstallBuiltinFunctionIds() {
2667 HandleScope scope(isolate());
2668 struct BuiltinFunctionIds {
2669 const char* holder_expr;
2670 const char* fun_name;
2671 BuiltinFunctionId id;
2674 const BuiltinFunctionIds builtins[] = {
2675 FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2677 for (const BuiltinFunctionIds& builtin : builtins) {
2678 Handle<JSObject> holder =
2679 ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2680 InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2685 void Genesis::InstallExperimentalBuiltinFunctionIds() {
2686 if (FLAG_harmony_atomics) {
2687 struct BuiltinFunctionIds {
2688 const char* holder_expr;
2689 const char* fun_name;
2690 BuiltinFunctionId id;
2693 const BuiltinFunctionIds atomic_builtins[] = {
2694 ATOMIC_FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)};
2696 for (const BuiltinFunctionIds& builtin : atomic_builtins) {
2697 Handle<JSObject> holder =
2698 ResolveBuiltinIdHolder(native_context(), builtin.holder_expr);
2699 InstallBuiltinFunctionId(holder, builtin.fun_name, builtin.id);
2705 #undef INSTALL_BUILTIN_ID
2708 // Do not forget to update macros.py with named constant
2710 #define JSFUNCTION_RESULT_CACHE_LIST(F) \
2711 F(16, native_context()->regexp_function())
2714 static FixedArray* CreateCache(int size, Handle<JSFunction> factory_function) {
2715 Factory* factory = factory_function->GetIsolate()->factory();
2716 // Caches are supposed to live for a long time, allocate in old space.
2717 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
2718 // Cannot use cast as object is not fully initialized yet.
2719 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
2720 *factory->NewFixedArrayWithHoles(array_size, TENURED));
2721 cache->set(JSFunctionResultCache::kFactoryIndex, *factory_function);
2722 cache->MakeZeroSize();
2727 void Genesis::InstallJSFunctionResultCaches() {
2728 const int kNumberOfCaches = 0 +
2729 #define F(size, func) + 1
2730 JSFUNCTION_RESULT_CACHE_LIST(F)
2734 Handle<FixedArray> caches =
2735 factory()->NewFixedArray(kNumberOfCaches, TENURED);
2739 #define F(size, func) do { \
2740 FixedArray* cache = CreateCache((size), Handle<JSFunction>(func)); \
2741 caches->set(index++, cache); \
2744 JSFUNCTION_RESULT_CACHE_LIST(F);
2748 native_context()->set_jsfunction_result_caches(*caches);
2752 void Genesis::InitializeNormalizedMapCaches() {
2753 Handle<NormalizedMapCache> cache = NormalizedMapCache::New(isolate());
2754 native_context()->set_normalized_map_cache(*cache);
2758 bool Bootstrapper::InstallExtensions(Handle<Context> native_context,
2759 v8::ExtensionConfiguration* extensions) {
2760 BootstrapperActive active(this);
2761 SaveContext saved_context(isolate_);
2762 isolate_->set_context(*native_context);
2763 return Genesis::InstallExtensions(native_context, extensions) &&
2764 Genesis::InstallSpecialObjects(native_context);
2768 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
2769 Isolate* isolate = native_context->GetIsolate();
2770 // Don't install extensions into the snapshot.
2771 if (isolate->serializer_enabled()) return true;
2773 Factory* factory = isolate->factory();
2774 HandleScope scope(isolate);
2775 Handle<JSGlobalObject> global(JSGlobalObject::cast(
2776 native_context->global_object()));
2778 Handle<JSObject> Error = Handle<JSObject>::cast(
2779 Object::GetProperty(isolate, global, "Error").ToHandleChecked());
2780 Handle<String> name =
2781 factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("stackTraceLimit"));
2782 Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit), isolate);
2783 JSObject::AddProperty(Error, name, stack_trace_limit, NONE);
2785 // By now the utils object is useless and can be removed.
2786 native_context->set_natives_utils_object(*factory->undefined_value());
2788 // Expose the natives in global if a name for it is specified.
2789 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
2790 Handle<String> natives_key =
2791 factory->InternalizeUtf8String(FLAG_expose_natives_as);
2792 uint32_t dummy_index;
2793 if (natives_key->AsArrayIndex(&dummy_index)) return true;
2794 Handle<JSBuiltinsObject> natives(global->builtins());
2795 JSObject::AddProperty(global, natives_key, natives, DONT_ENUM);
2798 // Expose the stack trace symbol to native JS.
2799 RETURN_ON_EXCEPTION_VALUE(isolate,
2800 JSObject::SetOwnPropertyIgnoreAttributes(
2801 handle(native_context->builtins(), isolate),
2802 factory->InternalizeOneByteString(
2803 STATIC_CHAR_VECTOR("$stackTraceSymbol")),
2804 factory->stack_trace_symbol(), NONE),
2807 // Expose the debug global object in global if a name for it is specified.
2808 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
2809 // If loading fails we just bail out without installing the
2810 // debugger but without tanking the whole context.
2811 Debug* debug = isolate->debug();
2812 if (!debug->Load()) return true;
2813 Handle<Context> debug_context = debug->debug_context();
2814 // Set the security token for the debugger context to the same as
2815 // the shell native context to allow calling between these (otherwise
2816 // exposing debug global object doesn't make much sense).
2817 debug_context->set_security_token(native_context->security_token());
2818 Handle<String> debug_string =
2819 factory->InternalizeUtf8String(FLAG_expose_debug_as);
2821 if (debug_string->AsArrayIndex(&index)) return true;
2822 Handle<Object> global_proxy(debug_context->global_proxy(), isolate);
2823 JSObject::AddProperty(global, debug_string, global_proxy, DONT_ENUM);
2829 static uint32_t Hash(RegisteredExtension* extension) {
2830 return v8::internal::ComputePointerHash(extension);
2834 Genesis::ExtensionStates::ExtensionStates() : map_(HashMap::PointersMatch, 8) {}
2836 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2837 RegisteredExtension* extension) {
2838 i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension));
2839 if (entry == NULL) {
2842 return static_cast<ExtensionTraversalState>(
2843 reinterpret_cast<intptr_t>(entry->value));
2846 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2847 ExtensionTraversalState state) {
2848 map_.LookupOrInsert(extension, Hash(extension))->value =
2849 reinterpret_cast<void*>(static_cast<intptr_t>(state));
2853 bool Genesis::InstallExtensions(Handle<Context> native_context,
2854 v8::ExtensionConfiguration* extensions) {
2855 Isolate* isolate = native_context->GetIsolate();
2856 ExtensionStates extension_states; // All extensions have state UNVISITED.
2857 return InstallAutoExtensions(isolate, &extension_states) &&
2858 (!FLAG_expose_free_buffer ||
2859 InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
2861 InstallExtension(isolate, "v8/gc", &extension_states)) &&
2862 (!FLAG_expose_externalize_string ||
2863 InstallExtension(isolate, "v8/externalize", &extension_states)) &&
2864 (!FLAG_track_gc_object_stats ||
2865 InstallExtension(isolate, "v8/statistics", &extension_states)) &&
2866 (!FLAG_expose_trigger_failure ||
2867 InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
2868 InstallRequestedExtensions(isolate, extensions, &extension_states);
2872 bool Genesis::InstallAutoExtensions(Isolate* isolate,
2873 ExtensionStates* extension_states) {
2874 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2877 if (it->extension()->auto_enable() &&
2878 !InstallExtension(isolate, it, extension_states)) {
2886 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
2887 v8::ExtensionConfiguration* extensions,
2888 ExtensionStates* extension_states) {
2889 for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
2890 if (!InstallExtension(isolate, *it, extension_states)) return false;
2896 // Installs a named extension. This methods is unoptimized and does
2897 // not scale well if we want to support a large number of extensions.
2898 bool Genesis::InstallExtension(Isolate* isolate,
2900 ExtensionStates* extension_states) {
2901 for (v8::RegisteredExtension* it = v8::RegisteredExtension::first_extension();
2904 if (strcmp(name, it->extension()->name()) == 0) {
2905 return InstallExtension(isolate, it, extension_states);
2908 return Utils::ApiCheck(false,
2909 "v8::Context::New()",
2910 "Cannot find required extension");
2914 bool Genesis::InstallExtension(Isolate* isolate,
2915 v8::RegisteredExtension* current,
2916 ExtensionStates* extension_states) {
2917 HandleScope scope(isolate);
2919 if (extension_states->get_state(current) == INSTALLED) return true;
2920 // The current node has already been visited so there must be a
2921 // cycle in the dependency graph; fail.
2922 if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
2923 "v8::Context::New()",
2924 "Circular extension dependency")) {
2927 DCHECK(extension_states->get_state(current) == UNVISITED);
2928 extension_states->set_state(current, VISITED);
2929 v8::Extension* extension = current->extension();
2930 // Install the extension's dependencies
2931 for (int i = 0; i < extension->dependency_count(); i++) {
2932 if (!InstallExtension(isolate,
2933 extension->dependencies()[i],
2934 extension_states)) {
2938 // We do not expect this to throw an exception. Change this if it does.
2939 bool result = CompileExtension(isolate, extension);
2940 DCHECK(isolate->has_pending_exception() != result);
2942 // We print out the name of the extension that fail to install.
2943 // When an error is thrown during bootstrapping we automatically print
2944 // the line number at which this happened to the console in the isolate
2945 // error throwing functionality.
2946 base::OS::PrintError("Error installing extension '%s'.\n",
2947 current->extension()->name());
2948 isolate->clear_pending_exception();
2950 extension_states->set_state(current, INSTALLED);
2951 isolate->NotifyExtensionInstalled();
2956 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2957 HandleScope scope(isolate());
2958 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2959 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2960 Handle<Object> function_object = Object::GetProperty(
2961 isolate(), builtins, Builtins::GetName(id)).ToHandleChecked();
2962 Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);
2963 builtins->set_javascript_builtin(id, *function);
2969 bool Genesis::ConfigureGlobalObjects(
2970 v8::Local<v8::ObjectTemplate> global_proxy_template) {
2971 Handle<JSObject> global_proxy(
2972 JSObject::cast(native_context()->global_proxy()));
2973 Handle<JSObject> global_object(
2974 JSObject::cast(native_context()->global_object()));
2976 if (!global_proxy_template.IsEmpty()) {
2977 // Configure the global proxy object.
2978 Handle<ObjectTemplateInfo> global_proxy_data =
2979 v8::Utils::OpenHandle(*global_proxy_template);
2980 if (!ConfigureApiObject(global_proxy, global_proxy_data)) return false;
2982 // Configure the global object.
2983 Handle<FunctionTemplateInfo> proxy_constructor(
2984 FunctionTemplateInfo::cast(global_proxy_data->constructor()));
2985 if (!proxy_constructor->prototype_template()->IsUndefined()) {
2986 Handle<ObjectTemplateInfo> global_object_data(
2987 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2988 if (!ConfigureApiObject(global_object, global_object_data)) return false;
2992 SetObjectPrototype(global_proxy, global_object);
2994 native_context()->set_initial_array_prototype(
2995 JSArray::cast(native_context()->array_function()->prototype()));
2996 native_context()->set_array_buffer_map(
2997 native_context()->array_buffer_fun()->initial_map());
2998 native_context()->set_js_map_map(
2999 native_context()->js_map_fun()->initial_map());
3000 native_context()->set_js_set_map(
3001 native_context()->js_set_fun()->initial_map());
3007 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
3008 Handle<ObjectTemplateInfo> object_template) {
3009 DCHECK(!object_template.is_null());
3010 DCHECK(FunctionTemplateInfo::cast(object_template->constructor())
3011 ->IsTemplateFor(object->map()));;
3013 MaybeHandle<JSObject> maybe_obj =
3014 ApiNatives::InstantiateObject(object_template);
3015 Handle<JSObject> obj;
3016 if (!maybe_obj.ToHandle(&obj)) {
3017 DCHECK(isolate()->has_pending_exception());
3018 isolate()->clear_pending_exception();
3021 TransferObject(obj, object);
3026 void Genesis::TransferNamedProperties(Handle<JSObject> from,
3027 Handle<JSObject> to) {
3028 // If JSObject::AddProperty asserts due to already existing property,
3029 // it is likely due to both global objects sharing property name(s).
3030 // Merging those two global objects is impossible.
3031 // The global template must not create properties that already exist
3032 // in the snapshotted global object.
3033 if (from->HasFastProperties()) {
3034 Handle<DescriptorArray> descs =
3035 Handle<DescriptorArray>(from->map()->instance_descriptors());
3036 for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
3037 PropertyDetails details = descs->GetDetails(i);
3038 switch (details.type()) {
3040 HandleScope inner(isolate());
3041 Handle<Name> key = Handle<Name>(descs->GetKey(i));
3042 FieldIndex index = FieldIndex::ForDescriptor(from->map(), i);
3043 DCHECK(!descs->GetDetails(i).representation().IsDouble());
3044 Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
3046 JSObject::AddProperty(to, key, value, details.attributes());
3049 case DATA_CONSTANT: {
3050 HandleScope inner(isolate());
3051 Handle<Name> key = Handle<Name>(descs->GetKey(i));
3052 Handle<Object> constant(descs->GetConstant(i), isolate());
3053 JSObject::AddProperty(to, key, constant, details.attributes());
3058 case ACCESSOR_CONSTANT: {
3059 Handle<Name> key(descs->GetKey(i));
3060 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3061 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3062 // If the property is already there we skip it
3063 if (it.IsFound()) continue;
3064 HandleScope inner(isolate());
3065 DCHECK(!to->HasFastProperties());
3066 // Add to dictionary.
3067 Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
3068 PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
3069 PropertyCellType::kMutable);
3070 JSObject::SetNormalizedProperty(to, key, callbacks, d);
3075 } else if (from->IsGlobalObject()) {
3076 Handle<GlobalDictionary> properties =
3077 Handle<GlobalDictionary>(from->global_dictionary());
3078 int capacity = properties->Capacity();
3079 for (int i = 0; i < capacity; i++) {
3080 Object* raw_key(properties->KeyAt(i));
3081 if (properties->IsKey(raw_key)) {
3082 DCHECK(raw_key->IsName());
3083 // If the property is already there we skip it.
3084 Handle<Name> key(Name::cast(raw_key));
3085 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3086 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3087 if (it.IsFound()) continue;
3088 // Set the property.
3089 DCHECK(properties->ValueAt(i)->IsPropertyCell());
3090 Handle<PropertyCell> cell(PropertyCell::cast(properties->ValueAt(i)));
3091 Handle<Object> value(cell->value(), isolate());
3092 if (value->IsTheHole()) continue;
3093 PropertyDetails details = cell->property_details();
3094 DCHECK_EQ(kData, details.kind());
3095 JSObject::AddProperty(to, key, value, details.attributes());
3099 Handle<NameDictionary> properties =
3100 Handle<NameDictionary>(from->property_dictionary());
3101 int capacity = properties->Capacity();
3102 for (int i = 0; i < capacity; i++) {
3103 Object* raw_key(properties->KeyAt(i));
3104 if (properties->IsKey(raw_key)) {
3105 DCHECK(raw_key->IsName());
3106 // If the property is already there we skip it.
3107 Handle<Name> key(Name::cast(raw_key));
3108 LookupIterator it(to, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
3109 CHECK_NE(LookupIterator::ACCESS_CHECK, it.state());
3110 if (it.IsFound()) continue;
3111 // Set the property.
3112 Handle<Object> value = Handle<Object>(properties->ValueAt(i),
3114 DCHECK(!value->IsCell());
3115 DCHECK(!value->IsTheHole());
3116 PropertyDetails details = properties->DetailsAt(i);
3117 DCHECK_EQ(kData, details.kind());
3118 JSObject::AddProperty(to, key, value, details.attributes());
3125 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
3126 Handle<JSObject> to) {
3127 // Cloning the elements array is sufficient.
3128 Handle<FixedArray> from_elements =
3129 Handle<FixedArray>(FixedArray::cast(from->elements()));
3130 Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
3131 to->set_elements(*to_elements);
3135 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
3136 HandleScope outer(isolate());
3138 DCHECK(!from->IsJSArray());
3139 DCHECK(!to->IsJSArray());
3141 TransferNamedProperties(from, to);
3142 TransferIndexedProperties(from, to);
3144 // Transfer the prototype (new map is needed).
3145 Handle<Object> proto(from->map()->prototype(), isolate());
3146 SetObjectPrototype(to, proto);
3150 void Genesis::MakeFunctionInstancePrototypeWritable() {
3151 // The maps with writable prototype are created in CreateEmptyFunction
3152 // and CreateStrictModeFunctionMaps respectively. Initially the maps are
3153 // created with read-only prototype for JS builtins processing.
3154 DCHECK(!sloppy_function_map_writable_prototype_.is_null());
3155 DCHECK(!strict_function_map_writable_prototype_.is_null());
3157 // Replace function instance maps to make prototype writable.
3158 native_context()->set_sloppy_function_map(
3159 *sloppy_function_map_writable_prototype_);
3160 native_context()->set_strict_function_map(
3161 *strict_function_map_writable_prototype_);
3165 class NoTrackDoubleFieldsForSerializerScope {
3167 explicit NoTrackDoubleFieldsForSerializerScope(Isolate* isolate)
3168 : flag_(FLAG_track_double_fields), enabled_(false) {
3169 if (isolate->serializer_enabled()) {
3170 // Disable tracking double fields because heap numbers treated as
3171 // immutable by the serializer.
3172 FLAG_track_double_fields = false;
3177 ~NoTrackDoubleFieldsForSerializerScope() {
3179 FLAG_track_double_fields = flag_;
3189 Genesis::Genesis(Isolate* isolate,
3190 MaybeHandle<JSGlobalProxy> maybe_global_proxy,
3191 v8::Local<v8::ObjectTemplate> global_proxy_template,
3192 v8::ExtensionConfiguration* extensions,
3193 ContextType context_type)
3194 : isolate_(isolate), active_(isolate->bootstrapper()) {
3195 NoTrackDoubleFieldsForSerializerScope disable_scope(isolate);
3196 result_ = Handle<Context>::null();
3197 // Before creating the roots we must save the context and restore it
3198 // on all function exits.
3199 SaveContext saved_context(isolate);
3201 // During genesis, the boilerplate for stack overflow won't work until the
3202 // environment has been at least partially initialized. Add a stack check
3203 // before entering JS code to catch overflow early.
3204 StackLimitCheck check(isolate);
3205 if (check.HasOverflowed()) {
3206 isolate->StackOverflow();
3210 // The deserializer needs to hook up references to the global proxy.
3211 // Create an uninitialized global proxy now if we don't have one
3212 // and initialize it later in CreateNewGlobals.
3213 Handle<JSGlobalProxy> global_proxy;
3214 if (!maybe_global_proxy.ToHandle(&global_proxy)) {
3215 global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy();
3218 // We can only de-serialize a context if the isolate was initialized from
3219 // a snapshot. Otherwise we have to build the context from scratch.
3220 // Also create a context from scratch to expose natives, if required by flag.
3221 Handle<FixedArray> outdated_contexts;
3222 if (!isolate->initialized_from_snapshot() ||
3223 !Snapshot::NewContextFromSnapshot(isolate, global_proxy,
3225 .ToHandle(&native_context_)) {
3226 native_context_ = Handle<Context>();
3229 if (!native_context().is_null()) {
3230 AddToWeakNativeContextList(*native_context());
3231 isolate->set_context(*native_context());
3232 isolate->counters()->contexts_created_by_snapshot()->Increment();
3234 if (FLAG_trace_maps) {
3235 Handle<JSFunction> object_fun = isolate->object_function();
3236 PrintF("[TraceMap: InitialMap map= %p SFI= %d_Object ]\n",
3237 reinterpret_cast<void*>(object_fun->initial_map()),
3238 object_fun->shared()->unique_id());
3239 Map::TraceAllTransitions(object_fun->initial_map());
3242 Handle<GlobalObject> global_object =
3243 CreateNewGlobals(global_proxy_template, global_proxy);
3245 HookUpGlobalProxy(global_object, global_proxy);
3246 HookUpGlobalObject(global_object, outdated_contexts);
3247 native_context()->builtins()->set_global_proxy(
3248 native_context()->global_proxy());
3249 HookUpGlobalThisBinding(outdated_contexts);
3251 if (!ConfigureGlobalObjects(global_proxy_template)) return;
3253 // We get here if there was no context snapshot.
3255 Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
3256 CreateStrictModeFunctionMaps(empty_function);
3257 CreateStrongModeFunctionMaps(empty_function);
3258 Handle<GlobalObject> global_object =
3259 CreateNewGlobals(global_proxy_template, global_proxy);
3260 HookUpGlobalProxy(global_object, global_proxy);
3261 InitializeGlobal(global_object, empty_function, context_type);
3262 InstallJSFunctionResultCaches();
3263 InitializeNormalizedMapCaches();
3265 if (!InstallNatives(context_type)) return;
3267 MakeFunctionInstancePrototypeWritable();
3269 if (context_type == FULL_CONTEXT) {
3270 if (!ConfigureGlobalObjects(global_proxy_template)) return;
3272 isolate->counters()->contexts_created_from_scratch()->Increment();
3275 // Install experimental and extra natives. Do not include them into the
3276 // snapshot as we should be able to turn them off at runtime. Re-installing
3277 // them after they have already been deserialized would also fail.
3278 if (context_type == FULL_CONTEXT) {
3279 if (!isolate->serializer_enabled()) {
3280 InitializeExperimentalGlobal();
3281 if (!InstallExperimentalNatives()) return;
3282 if (!InstallExtraNatives()) return;
3285 // The serializer cannot serialize typed arrays. Reset those typed arrays
3286 // for each new context.
3287 InitializeBuiltinTypedArrays();
3290 result_ = native_context();
3294 // Support for thread preemption.
3296 // Reserve space for statics needing saving and restoring.
3297 int Bootstrapper::ArchiveSpacePerThread() {
3298 return sizeof(NestingCounterType);
3302 // Archive statics that are thread-local.
3303 char* Bootstrapper::ArchiveState(char* to) {
3304 *reinterpret_cast<NestingCounterType*>(to) = nesting_;
3306 return to + sizeof(NestingCounterType);
3310 // Restore statics that are thread-local.
3311 char* Bootstrapper::RestoreState(char* from) {
3312 nesting_ = *reinterpret_cast<NestingCounterType*>(from);
3313 return from + sizeof(NestingCounterType);
3317 // Called when the top-level V8 mutex is destroyed.
3318 void Bootstrapper::FreeThreadResources() {
3319 DCHECK(!IsActive());
3322 } // namespace internal