blob: 43aa1a3b8997c64e72a93054dfa27b799fd27ffa [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "bootstrapper.h"
33#include "compiler.h"
34#include "debug.h"
35#include "execution.h"
36#include "global-handles.h"
37#include "macro-assembler.h"
38#include "natives.h"
39
40namespace v8 {
41namespace internal {
42
43// A SourceCodeCache uses a FixedArray to store pairs of
44// (AsciiString*, JSFunction*), mapping names of native code files
45// (runtime.js, etc.) to precompiled functions. Instead of mapping
46// names to functions it might make sense to let the JS2C tool
47// generate an index for each native JS file.
48class SourceCodeCache BASE_EMBEDDED {
49 public:
50 explicit SourceCodeCache(Script::Type type): type_(type), cache_(NULL) { }
51
52 void Initialize(bool create_heap_objects) {
53 cache_ = create_heap_objects ? Heap::empty_fixed_array() : NULL;
54 }
55
56 void Iterate(ObjectVisitor* v) {
57 v->VisitPointer(bit_cast<Object**, FixedArray**>(&cache_));
58 }
59
60
61 bool Lookup(Vector<const char> name, Handle<JSFunction>* handle) {
62 for (int i = 0; i < cache_->length(); i+=2) {
63 SeqAsciiString* str = SeqAsciiString::cast(cache_->get(i));
64 if (str->IsEqualTo(name)) {
65 *handle = Handle<JSFunction>(JSFunction::cast(cache_->get(i + 1)));
66 return true;
67 }
68 }
69 return false;
70 }
71
72
73 void Add(Vector<const char> name, Handle<JSFunction> fun) {
74 ASSERT(fun->IsBoilerplate());
75 HandleScope scope;
76 int length = cache_->length();
77 Handle<FixedArray> new_array =
78 Factory::NewFixedArray(length + 2, TENURED);
79 cache_->CopyTo(0, *new_array, 0, cache_->length());
80 cache_ = *new_array;
81 Handle<String> str = Factory::NewStringFromAscii(name, TENURED);
82 cache_->set(length, *str);
83 cache_->set(length + 1, *fun);
84 Script::cast(fun->shared()->script())->set_type(Smi::FromInt(type_));
85 }
86
87 private:
88 Script::Type type_;
89 FixedArray* cache_;
90 DISALLOW_COPY_AND_ASSIGN(SourceCodeCache);
91};
92
93static SourceCodeCache natives_cache(Script::TYPE_NATIVE);
94static SourceCodeCache extensions_cache(Script::TYPE_EXTENSION);
95
96
97Handle<String> Bootstrapper::NativesSourceLookup(int index) {
98 ASSERT(0 <= index && index < Natives::GetBuiltinsCount());
99 if (Heap::natives_source_cache()->get(index)->IsUndefined()) {
100 Handle<String> source_code =
101 Factory::NewStringFromAscii(Natives::GetScriptSource(index));
102 Heap::natives_source_cache()->set(index, *source_code);
103 }
104 Handle<Object> cached_source(Heap::natives_source_cache()->get(index));
105 return Handle<String>::cast(cached_source);
106}
107
108
109bool Bootstrapper::NativesCacheLookup(Vector<const char> name,
110 Handle<JSFunction>* handle) {
111 return natives_cache.Lookup(name, handle);
112}
113
114
115void Bootstrapper::NativesCacheAdd(Vector<const char> name,
116 Handle<JSFunction> fun) {
117 natives_cache.Add(name, fun);
118}
119
120
121void Bootstrapper::Initialize(bool create_heap_objects) {
122 natives_cache.Initialize(create_heap_objects);
123 extensions_cache.Initialize(create_heap_objects);
124}
125
126
127void Bootstrapper::TearDown() {
128 natives_cache.Initialize(false); // Yes, symmetrical
129 extensions_cache.Initialize(false);
130}
131
132
133// Pending fixups are code positions that refer to builtin code
134// objects that were not available at the time the code was generated.
135// The pending list is processed whenever an environment has been
136// created.
137class PendingFixups : public AllStatic {
138 public:
139 static void Add(Code* code, MacroAssembler* masm);
140 static bool Process(Handle<JSBuiltinsObject> builtins);
141
142 static void Iterate(ObjectVisitor* v);
143
144 private:
145 static List<Object*> code_;
146 static List<const char*> name_;
147 static List<int> pc_;
148 static List<uint32_t> flags_;
149
150 static void Clear();
151};
152
153
154List<Object*> PendingFixups::code_(0);
155List<const char*> PendingFixups::name_(0);
156List<int> PendingFixups::pc_(0);
157List<uint32_t> PendingFixups::flags_(0);
158
159
160void PendingFixups::Add(Code* code, MacroAssembler* masm) {
161 // Note this code is not only called during bootstrapping.
162 List<MacroAssembler::Unresolved>* unresolved = masm->unresolved();
163 int n = unresolved->length();
164 for (int i = 0; i < n; i++) {
165 const char* name = unresolved->at(i).name;
166 code_.Add(code);
167 name_.Add(name);
168 pc_.Add(unresolved->at(i).pc);
169 flags_.Add(unresolved->at(i).flags);
170 LOG(StringEvent("unresolved", name));
171 }
172}
173
174
175bool PendingFixups::Process(Handle<JSBuiltinsObject> builtins) {
176 HandleScope scope;
177 // NOTE: Extra fixups may be added to the list during the iteration
178 // due to lazy compilation of functions during the processing. Do not
179 // cache the result of getting the length of the code list.
180 for (int i = 0; i < code_.length(); i++) {
181 const char* name = name_[i];
182 uint32_t flags = flags_[i];
183 Handle<String> symbol = Factory::LookupAsciiSymbol(name);
184 Object* o = builtins->GetProperty(*symbol);
185#ifdef DEBUG
186 if (!o->IsJSFunction()) {
187 V8_Fatal(__FILE__, __LINE__, "Cannot resolve call to builtin %s", name);
188 }
189#endif
190 Handle<JSFunction> f = Handle<JSFunction>(JSFunction::cast(o));
191 // Make sure the number of parameters match the formal parameter count.
192 int argc = Bootstrapper::FixupFlagsArgumentsCount::decode(flags);
193 USE(argc);
194 ASSERT(f->shared()->formal_parameter_count() == argc);
195 if (!f->is_compiled()) {
196 // Do lazy compilation and check for stack overflows.
197 if (!CompileLazy(f, CLEAR_EXCEPTION)) {
198 Clear();
199 return false;
200 }
201 }
202 Code* code = Code::cast(code_[i]);
203 Address pc = code->instruction_start() + pc_[i];
Steve Block3ce2e202009-11-05 08:53:23 +0000204 RelocInfo target(pc, RelocInfo::CODE_TARGET, 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000205 bool use_code_object = Bootstrapper::FixupFlagsUseCodeObject::decode(flags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000206 if (use_code_object) {
Steve Block3ce2e202009-11-05 08:53:23 +0000207 target.set_target_object(f->code());
Steve Blocka7e24c12009-10-30 11:49:00 +0000208 } else {
Steve Block3ce2e202009-11-05 08:53:23 +0000209 target.set_target_address(f->code()->instruction_start());
Steve Blocka7e24c12009-10-30 11:49:00 +0000210 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000211 LOG(StringEvent("resolved", name));
212 }
213 Clear();
214
215 // TODO(1240818): We should probably try to avoid doing this for all
216 // the V8 builtin JS files. It should only happen after running
217 // runtime.js - just like there shouldn't be any fixups left after
218 // that.
219 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
220 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
221 Handle<String> name = Factory::LookupAsciiSymbol(Builtins::GetName(id));
222 JSFunction* function = JSFunction::cast(builtins->GetProperty(*name));
223 builtins->set_javascript_builtin(id, function);
224 }
225
226 return true;
227}
228
229
230void PendingFixups::Clear() {
231 code_.Clear();
232 name_.Clear();
233 pc_.Clear();
234 flags_.Clear();
235}
236
237
238void PendingFixups::Iterate(ObjectVisitor* v) {
239 if (!code_.is_empty()) {
240 v->VisitPointers(&code_[0], &code_[0] + code_.length());
241 }
242}
243
244
245class Genesis BASE_EMBEDDED {
246 public:
247 Genesis(Handle<Object> global_object,
248 v8::Handle<v8::ObjectTemplate> global_template,
249 v8::ExtensionConfiguration* extensions);
250 ~Genesis();
251
252 Handle<Context> result() { return result_; }
253
254 Genesis* previous() { return previous_; }
255 static Genesis* current() { return current_; }
256
257 // Support for thread preemption.
258 static int ArchiveSpacePerThread();
259 static char* ArchiveState(char* to);
260 static char* RestoreState(char* from);
261
262 private:
263 Handle<Context> global_context_;
264
265 // There may be more than one active genesis object: When GC is
266 // triggered during environment creation there may be weak handle
267 // processing callbacks which may create new environments.
268 Genesis* previous_;
269 static Genesis* current_;
270
271 Handle<Context> global_context() { return global_context_; }
272
273 void CreateRoots(v8::Handle<v8::ObjectTemplate> global_template,
274 Handle<Object> global_object);
275 void InstallNativeFunctions();
276 bool InstallNatives();
277 bool InstallExtensions(v8::ExtensionConfiguration* extensions);
278 bool InstallExtension(const char* name);
279 bool InstallExtension(v8::RegisteredExtension* current);
280 bool InstallSpecialObjects();
281 bool ConfigureApiObject(Handle<JSObject> object,
282 Handle<ObjectTemplateInfo> object_template);
283 bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
284
285 // Migrates all properties from the 'from' object to the 'to'
286 // object and overrides the prototype in 'to' with the one from
287 // 'from'.
288 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
289 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
290 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
291
292 Handle<DescriptorArray> ComputeFunctionInstanceDescriptor(
293 bool make_prototype_read_only,
294 bool make_prototype_enumerable = false);
295 void MakeFunctionInstancePrototypeWritable();
296
297 void AddSpecialFunction(Handle<JSObject> prototype,
298 const char* name,
299 Handle<Code> code);
300
301 void BuildSpecialFunctionTable();
302
303 static bool CompileBuiltin(int index);
304 static bool CompileNative(Vector<const char> name, Handle<String> source);
305 static bool CompileScriptCached(Vector<const char> name,
306 Handle<String> source,
307 SourceCodeCache* cache,
308 v8::Extension* extension,
309 bool use_runtime_context);
310
311 Handle<Context> result_;
312};
313
314Genesis* Genesis::current_ = NULL;
315
316
317void Bootstrapper::Iterate(ObjectVisitor* v) {
318 natives_cache.Iterate(v);
319 extensions_cache.Iterate(v);
320 PendingFixups::Iterate(v);
321}
322
323
324// While setting up the environment, we collect code positions that
325// need to be patched before we can run any code in the environment.
326void Bootstrapper::AddFixup(Code* code, MacroAssembler* masm) {
327 PendingFixups::Add(code, masm);
328}
329
330
331bool Bootstrapper::IsActive() {
332 return Genesis::current() != NULL;
333}
334
335
336Handle<Context> Bootstrapper::CreateEnvironment(
337 Handle<Object> global_object,
338 v8::Handle<v8::ObjectTemplate> global_template,
339 v8::ExtensionConfiguration* extensions) {
340 Genesis genesis(global_object, global_template, extensions);
341 return genesis.result();
342}
343
344
345static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
346 // object.__proto__ = proto;
347 Handle<Map> old_to_map = Handle<Map>(object->map());
348 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
349 new_to_map->set_prototype(*proto);
350 object->set_map(*new_to_map);
351}
352
353
354void Bootstrapper::DetachGlobal(Handle<Context> env) {
355 JSGlobalProxy::cast(env->global_proxy())->set_context(*Factory::null_value());
356 SetObjectPrototype(Handle<JSObject>(env->global_proxy()),
357 Factory::null_value());
358 env->set_global_proxy(env->global());
359 env->global()->set_global_receiver(env->global());
360}
361
362
363Genesis::~Genesis() {
364 ASSERT(current_ == this);
365 current_ = previous_;
366}
367
368
369static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
370 const char* name,
371 InstanceType type,
372 int instance_size,
373 Handle<JSObject> prototype,
374 Builtins::Name call,
375 bool is_ecma_native) {
376 Handle<String> symbol = Factory::LookupAsciiSymbol(name);
377 Handle<Code> call_code = Handle<Code>(Builtins::builtin(call));
378 Handle<JSFunction> function =
379 Factory::NewFunctionWithPrototype(symbol,
380 type,
381 instance_size,
382 prototype,
383 call_code,
384 is_ecma_native);
385 SetProperty(target, symbol, function, DONT_ENUM);
386 if (is_ecma_native) {
387 function->shared()->set_instance_class_name(*symbol);
388 }
389 return function;
390}
391
392
393Handle<DescriptorArray> Genesis::ComputeFunctionInstanceDescriptor(
394 bool make_prototype_read_only,
395 bool make_prototype_enumerable) {
396 Handle<DescriptorArray> result = Factory::empty_descriptor_array();
397
398 // Add prototype.
399 PropertyAttributes attributes = static_cast<PropertyAttributes>(
400 (make_prototype_enumerable ? 0 : DONT_ENUM)
401 | DONT_DELETE
402 | (make_prototype_read_only ? READ_ONLY : 0));
403 result =
404 Factory::CopyAppendProxyDescriptor(
405 result,
406 Factory::prototype_symbol(),
407 Factory::NewProxy(&Accessors::FunctionPrototype),
408 attributes);
409
410 attributes =
411 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
412 // Add length.
413 result =
414 Factory::CopyAppendProxyDescriptor(
415 result,
416 Factory::length_symbol(),
417 Factory::NewProxy(&Accessors::FunctionLength),
418 attributes);
419
420 // Add name.
421 result =
422 Factory::CopyAppendProxyDescriptor(
423 result,
424 Factory::name_symbol(),
425 Factory::NewProxy(&Accessors::FunctionName),
426 attributes);
427
428 // Add arguments.
429 result =
430 Factory::CopyAppendProxyDescriptor(
431 result,
432 Factory::arguments_symbol(),
433 Factory::NewProxy(&Accessors::FunctionArguments),
434 attributes);
435
436 // Add caller.
437 result =
438 Factory::CopyAppendProxyDescriptor(
439 result,
440 Factory::caller_symbol(),
441 Factory::NewProxy(&Accessors::FunctionCaller),
442 attributes);
443
444 return result;
445}
446
447
448void Genesis::CreateRoots(v8::Handle<v8::ObjectTemplate> global_template,
449 Handle<Object> global_object) {
450 HandleScope scope;
451 // Allocate the global context FixedArray first and then patch the
452 // closure and extension object later (we need the empty function
453 // and the global object, but in order to create those, we need the
454 // global context).
455 global_context_ =
456 Handle<Context>::cast(
457 GlobalHandles::Create(*Factory::NewGlobalContext()));
458 Top::set_context(*global_context());
459
460 // Allocate the message listeners object.
461 v8::NeanderArray listeners;
462 global_context()->set_message_listeners(*listeners.value());
463
464 // Allocate the map for function instances.
465 Handle<Map> fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
466 global_context()->set_function_instance_map(*fm);
467 // Please note that the prototype property for function instances must be
468 // writable.
469 Handle<DescriptorArray> function_map_descriptors =
470 ComputeFunctionInstanceDescriptor(false, false);
471 fm->set_instance_descriptors(*function_map_descriptors);
472
473 // Allocate the function map first and then patch the prototype later
474 fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
475 global_context()->set_function_map(*fm);
476 function_map_descriptors = ComputeFunctionInstanceDescriptor(true);
477 fm->set_instance_descriptors(*function_map_descriptors);
478
479 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
480
481 { // --- O b j e c t ---
482 Handle<JSFunction> object_fun =
483 Factory::NewFunction(object_name, Factory::null_value());
484 Handle<Map> object_function_map =
485 Factory::NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
486 object_fun->set_initial_map(*object_function_map);
487 object_function_map->set_constructor(*object_fun);
488
489 global_context()->set_object_function(*object_fun);
490
491 // Allocate a new prototype for the object function.
492 Handle<JSObject> prototype = Factory::NewJSObject(Top::object_function(),
493 TENURED);
494
495 global_context()->set_initial_object_prototype(*prototype);
496 SetPrototype(object_fun, prototype);
497 object_function_map->
498 set_instance_descriptors(Heap::empty_descriptor_array());
499 }
500
501 // Allocate the empty function as the prototype for function ECMAScript
502 // 262 15.3.4.
503 Handle<String> symbol = Factory::LookupAsciiSymbol("Empty");
504 Handle<JSFunction> empty_function =
505 Factory::NewFunction(symbol, Factory::null_value());
506
507 { // --- E m p t y ---
508 Handle<Code> code =
509 Handle<Code>(Builtins::builtin(Builtins::EmptyFunction));
510 empty_function->set_code(*code);
511 Handle<String> source = Factory::NewStringFromAscii(CStrVector("() {}"));
512 Handle<Script> script = Factory::NewScript(source);
513 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
514 empty_function->shared()->set_script(*script);
515 empty_function->shared()->set_start_position(0);
516 empty_function->shared()->set_end_position(source->length());
517 empty_function->shared()->DontAdaptArguments();
518 global_context()->function_map()->set_prototype(*empty_function);
519 global_context()->function_instance_map()->set_prototype(*empty_function);
520
521 // Allocate the function map first and then patch the prototype later
522 Handle<Map> empty_fm = Factory::CopyMapDropDescriptors(fm);
523 empty_fm->set_instance_descriptors(*function_map_descriptors);
524 empty_fm->set_prototype(global_context()->object_function()->prototype());
525 empty_function->set_map(*empty_fm);
526 }
527
528 { // --- G l o b a l ---
529 // Step 1: create a fresh inner JSGlobalObject
530 Handle<GlobalObject> object;
531 {
532 Handle<JSFunction> js_global_function;
533 Handle<ObjectTemplateInfo> js_global_template;
534 if (!global_template.IsEmpty()) {
535 // Get prototype template of the global_template
536 Handle<ObjectTemplateInfo> data =
537 v8::Utils::OpenHandle(*global_template);
538 Handle<FunctionTemplateInfo> global_constructor =
539 Handle<FunctionTemplateInfo>(
540 FunctionTemplateInfo::cast(data->constructor()));
541 Handle<Object> proto_template(global_constructor->prototype_template());
542 if (!proto_template->IsUndefined()) {
543 js_global_template =
544 Handle<ObjectTemplateInfo>::cast(proto_template);
545 }
546 }
547
548 if (js_global_template.is_null()) {
549 Handle<String> name = Handle<String>(Heap::empty_symbol());
550 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
551 js_global_function =
552 Factory::NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
553 JSGlobalObject::kSize, code, true);
554 // Change the constructor property of the prototype of the
555 // hidden global function to refer to the Object function.
556 Handle<JSObject> prototype =
557 Handle<JSObject>(
558 JSObject::cast(js_global_function->instance_prototype()));
559 SetProperty(prototype, Factory::constructor_symbol(),
560 Top::object_function(), NONE);
561 } else {
562 Handle<FunctionTemplateInfo> js_global_constructor(
563 FunctionTemplateInfo::cast(js_global_template->constructor()));
564 js_global_function =
565 Factory::CreateApiFunction(js_global_constructor,
566 Factory::InnerGlobalObject);
567 }
568
569 js_global_function->initial_map()->set_is_hidden_prototype();
570 object = Factory::NewGlobalObject(js_global_function);
571 }
572
573 // Set the global context for the global object.
574 object->set_global_context(*global_context());
575
576 // Step 2: create or re-initialize the global proxy object.
577 Handle<JSGlobalProxy> global_proxy;
578 {
579 Handle<JSFunction> global_proxy_function;
580 if (global_template.IsEmpty()) {
581 Handle<String> name = Handle<String>(Heap::empty_symbol());
582 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
583 global_proxy_function =
584 Factory::NewFunction(name, JS_GLOBAL_PROXY_TYPE,
585 JSGlobalProxy::kSize, code, true);
586 } else {
587 Handle<ObjectTemplateInfo> data =
588 v8::Utils::OpenHandle(*global_template);
589 Handle<FunctionTemplateInfo> global_constructor(
590 FunctionTemplateInfo::cast(data->constructor()));
591 global_proxy_function =
592 Factory::CreateApiFunction(global_constructor,
593 Factory::OuterGlobalObject);
594 }
595
596 Handle<String> global_name = Factory::LookupAsciiSymbol("global");
597 global_proxy_function->shared()->set_instance_class_name(*global_name);
598 global_proxy_function->initial_map()->set_is_access_check_needed(true);
599
600 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
601
602 if (global_object.location() != NULL) {
603 ASSERT(global_object->IsJSGlobalProxy());
604 global_proxy =
605 ReinitializeJSGlobalProxy(
606 global_proxy_function,
607 Handle<JSGlobalProxy>::cast(global_object));
608 } else {
609 global_proxy = Handle<JSGlobalProxy>::cast(
610 Factory::NewJSObject(global_proxy_function, TENURED));
611 }
612
613 // Security setup: Set the security token of the global object to
614 // its the inner global. This makes the security check between two
615 // different contexts fail by default even in case of global
616 // object reinitialization.
617 object->set_global_receiver(*global_proxy);
618 global_proxy->set_context(*global_context());
619 }
620
621 { // --- G l o b a l C o n t e x t ---
622 // use the empty function as closure (no scope info)
623 global_context()->set_closure(*empty_function);
624 global_context()->set_fcontext(*global_context());
625 global_context()->set_previous(NULL);
626
627 // set extension and global object
628 global_context()->set_extension(*object);
629 global_context()->set_global(*object);
630 global_context()->set_global_proxy(*global_proxy);
631 // use inner global object as security token by default
632 global_context()->set_security_token(*object);
633 }
634
635 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
636 SetProperty(global, object_name, Top::object_function(), DONT_ENUM);
637 }
638
639 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
640
641 // Install global Function object
642 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
643 empty_function, Builtins::Illegal, true); // ECMA native.
644
645 { // --- A r r a y ---
646 Handle<JSFunction> array_function =
647 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
648 Top::initial_object_prototype(), Builtins::ArrayCode,
649 true);
650 array_function->shared()->set_construct_stub(
651 Builtins::builtin(Builtins::ArrayConstructCode));
652 array_function->shared()->DontAdaptArguments();
653
654 // This seems a bit hackish, but we need to make sure Array.length
655 // is 1.
656 array_function->shared()->set_length(1);
657 Handle<DescriptorArray> array_descriptors =
658 Factory::CopyAppendProxyDescriptor(
659 Factory::empty_descriptor_array(),
660 Factory::length_symbol(),
661 Factory::NewProxy(&Accessors::ArrayLength),
662 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
663
664 // Cache the fast JavaScript array map
665 global_context()->set_js_array_map(array_function->initial_map());
666 global_context()->js_array_map()->set_instance_descriptors(
667 *array_descriptors);
668 // array_function is used internally. JS code creating array object should
669 // search for the 'Array' property on the global object and use that one
670 // as the constructor. 'Array' property on a global object can be
671 // overwritten by JS code.
672 global_context()->set_array_function(*array_function);
673 }
674
675 { // --- N u m b e r ---
676 Handle<JSFunction> number_fun =
677 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
678 Top::initial_object_prototype(), Builtins::Illegal,
679 true);
680 global_context()->set_number_function(*number_fun);
681 }
682
683 { // --- B o o l e a n ---
684 Handle<JSFunction> boolean_fun =
685 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
686 Top::initial_object_prototype(), Builtins::Illegal,
687 true);
688 global_context()->set_boolean_function(*boolean_fun);
689 }
690
691 { // --- S t r i n g ---
692 Handle<JSFunction> string_fun =
693 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
694 Top::initial_object_prototype(), Builtins::Illegal,
695 true);
696 global_context()->set_string_function(*string_fun);
697 // Add 'length' property to strings.
698 Handle<DescriptorArray> string_descriptors =
699 Factory::CopyAppendProxyDescriptor(
700 Factory::empty_descriptor_array(),
701 Factory::length_symbol(),
702 Factory::NewProxy(&Accessors::StringLength),
703 static_cast<PropertyAttributes>(DONT_ENUM |
704 DONT_DELETE |
705 READ_ONLY));
706
707 Handle<Map> string_map =
708 Handle<Map>(global_context()->string_function()->initial_map());
709 string_map->set_instance_descriptors(*string_descriptors);
710 }
711
712 { // --- D a t e ---
713 // Builtin functions for Date.prototype.
714 Handle<JSFunction> date_fun =
715 InstallFunction(global, "Date", JS_VALUE_TYPE, JSValue::kSize,
716 Top::initial_object_prototype(), Builtins::Illegal,
717 true);
718
719 global_context()->set_date_function(*date_fun);
720 }
721
722
723 { // -- R e g E x p
724 // Builtin functions for RegExp.prototype.
725 Handle<JSFunction> regexp_fun =
726 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
727 Top::initial_object_prototype(), Builtins::Illegal,
728 true);
729
730 global_context()->set_regexp_function(*regexp_fun);
731 }
732
733 { // -- J S O N
734 Handle<String> name = Factory::NewStringFromAscii(CStrVector("JSON"));
735 Handle<JSFunction> cons = Factory::NewFunction(
736 name,
737 Factory::the_hole_value());
738 cons->SetInstancePrototype(global_context()->initial_object_prototype());
739 cons->SetInstanceClassName(*name);
740 Handle<JSObject> json_object = Factory::NewJSObject(cons, TENURED);
741 ASSERT(json_object->IsJSObject());
742 SetProperty(global, name, json_object, DONT_ENUM);
743 global_context()->set_json_object(*json_object);
744 }
745
746 { // --- arguments_boilerplate_
747 // Make sure we can recognize argument objects at runtime.
748 // This is done by introducing an anonymous function with
749 // class_name equals 'Arguments'.
750 Handle<String> symbol = Factory::LookupAsciiSymbol("Arguments");
751 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
752 Handle<JSObject> prototype =
753 Handle<JSObject>(
754 JSObject::cast(global_context()->object_function()->prototype()));
755
756 Handle<JSFunction> function =
757 Factory::NewFunctionWithPrototype(symbol,
758 JS_OBJECT_TYPE,
759 JSObject::kHeaderSize,
760 prototype,
761 code,
762 false);
763 ASSERT(!function->has_initial_map());
764 function->shared()->set_instance_class_name(*symbol);
765 function->shared()->set_expected_nof_properties(2);
766 Handle<JSObject> result = Factory::NewJSObject(function);
767
768 global_context()->set_arguments_boilerplate(*result);
769 // Note: callee must be added as the first property and
770 // length must be added as the second property.
771 SetProperty(result, Factory::callee_symbol(),
772 Factory::undefined_value(),
773 DONT_ENUM);
774 SetProperty(result, Factory::length_symbol(),
775 Factory::undefined_value(),
776 DONT_ENUM);
777
778#ifdef DEBUG
779 LookupResult lookup;
780 result->LocalLookup(Heap::callee_symbol(), &lookup);
781 ASSERT(lookup.IsValid() && (lookup.type() == FIELD));
782 ASSERT(lookup.GetFieldIndex() == Heap::arguments_callee_index);
783
784 result->LocalLookup(Heap::length_symbol(), &lookup);
785 ASSERT(lookup.IsValid() && (lookup.type() == FIELD));
786 ASSERT(lookup.GetFieldIndex() == Heap::arguments_length_index);
787
788 ASSERT(result->map()->inobject_properties() > Heap::arguments_callee_index);
789 ASSERT(result->map()->inobject_properties() > Heap::arguments_length_index);
790
791 // Check the state of the object.
792 ASSERT(result->HasFastProperties());
793 ASSERT(result->HasFastElements());
794#endif
795 }
796
797 { // --- context extension
798 // Create a function for the context extension objects.
799 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
800 Handle<JSFunction> context_extension_fun =
801 Factory::NewFunction(Factory::empty_symbol(),
802 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
803 JSObject::kHeaderSize,
804 code,
805 true);
806
807 Handle<String> name = Factory::LookupAsciiSymbol("context_extension");
808 context_extension_fun->shared()->set_instance_class_name(*name);
809 global_context()->set_context_extension_function(*context_extension_fun);
810 }
811
812
813 {
814 // Setup the call-as-function delegate.
815 Handle<Code> code =
816 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsFunction));
817 Handle<JSFunction> delegate =
818 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
819 JSObject::kHeaderSize, code, true);
820 global_context()->set_call_as_function_delegate(*delegate);
821 delegate->shared()->DontAdaptArguments();
822 }
823
824 {
825 // Setup the call-as-constructor delegate.
826 Handle<Code> code =
827 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsConstructor));
828 Handle<JSFunction> delegate =
829 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
830 JSObject::kHeaderSize, code, true);
831 global_context()->set_call_as_constructor_delegate(*delegate);
832 delegate->shared()->DontAdaptArguments();
833 }
834
835 global_context()->set_special_function_table(Heap::empty_fixed_array());
836
837 // Initialize the out of memory slot.
838 global_context()->set_out_of_memory(Heap::false_value());
839
840 // Initialize the data slot.
841 global_context()->set_data(Heap::undefined_value());
842}
843
844
845bool Genesis::CompileBuiltin(int index) {
846 Vector<const char> name = Natives::GetScriptName(index);
847 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
848 return CompileNative(name, source_code);
849}
850
851
852bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
853 HandleScope scope;
854#ifdef ENABLE_DEBUGGER_SUPPORT
855 Debugger::set_compiling_natives(true);
856#endif
857 bool result =
858 CompileScriptCached(name, source, &natives_cache, NULL, true);
859 ASSERT(Top::has_pending_exception() != result);
860 if (!result) Top::clear_pending_exception();
861#ifdef ENABLE_DEBUGGER_SUPPORT
862 Debugger::set_compiling_natives(false);
863#endif
864 return result;
865}
866
867
868bool Genesis::CompileScriptCached(Vector<const char> name,
869 Handle<String> source,
870 SourceCodeCache* cache,
871 v8::Extension* extension,
872 bool use_runtime_context) {
873 HandleScope scope;
874 Handle<JSFunction> boilerplate;
875
876 // If we can't find the function in the cache, we compile a new
877 // function and insert it into the cache.
878 if (!cache->Lookup(name, &boilerplate)) {
879 ASSERT(source->IsAsciiRepresentation());
880 Handle<String> script_name = Factory::NewStringFromUtf8(name);
881 boilerplate =
882 Compiler::Compile(source, script_name, 0, 0, extension, NULL);
883 if (boilerplate.is_null()) return false;
884 cache->Add(name, boilerplate);
885 }
886
887 // Setup the function context. Conceptually, we should clone the
888 // function before overwriting the context but since we're in a
889 // single-threaded environment it is not strictly necessary.
890 ASSERT(Top::context()->IsGlobalContext());
891 Handle<Context> context =
892 Handle<Context>(use_runtime_context
893 ? Top::context()->runtime_context()
894 : Top::context());
895 Handle<JSFunction> fun =
896 Factory::NewFunctionFromBoilerplate(boilerplate, context);
897
898 // Call function using the either the runtime object or the global
899 // object as the receiver. Provide no parameters.
900 Handle<Object> receiver =
901 Handle<Object>(use_runtime_context
902 ? Top::context()->builtins()
903 : Top::context()->global());
904 bool has_pending_exception;
905 Handle<Object> result =
906 Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
907 if (has_pending_exception) return false;
908 return PendingFixups::Process(
909 Handle<JSBuiltinsObject>(Top::context()->builtins()));
910}
911
912
913#define INSTALL_NATIVE(Type, name, var) \
914 Handle<String> var##_name = Factory::LookupAsciiSymbol(name); \
915 global_context()->set_##var(Type::cast(global_context()-> \
916 builtins()-> \
917 GetProperty(*var##_name)));
918
919void Genesis::InstallNativeFunctions() {
920 HandleScope scope;
921 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
922 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
923 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
924 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
925 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
926 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
927 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
928 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
929 INSTALL_NATIVE(JSFunction, "ToBoolean", to_boolean_fun);
930 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
931 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
932 configure_instance_fun);
933 INSTALL_NATIVE(JSFunction, "MakeMessage", make_message_fun);
934 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
935 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
936}
937
938#undef INSTALL_NATIVE
939
940
941bool Genesis::InstallNatives() {
942 HandleScope scope;
943
944 // Create a function for the builtins object. Allocate space for the
945 // JavaScript builtins, a reference to the builtins object
946 // (itself) and a reference to the global_context directly in the object.
947 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
948 Handle<JSFunction> builtins_fun =
949 Factory::NewFunction(Factory::empty_symbol(), JS_BUILTINS_OBJECT_TYPE,
950 JSBuiltinsObject::kSize, code, true);
951
952 Handle<String> name = Factory::LookupAsciiSymbol("builtins");
953 builtins_fun->shared()->set_instance_class_name(*name);
954
955 // Allocate the builtins object.
956 Handle<JSBuiltinsObject> builtins =
957 Handle<JSBuiltinsObject>::cast(Factory::NewGlobalObject(builtins_fun));
958 builtins->set_builtins(*builtins);
959 builtins->set_global_context(*global_context());
960 builtins->set_global_receiver(*builtins);
961
962 // Setup the 'global' properties of the builtins object. The
963 // 'global' property that refers to the global object is the only
964 // way to get from code running in the builtins context to the
965 // global object.
966 static const PropertyAttributes attributes =
967 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
968 SetProperty(builtins, Factory::LookupAsciiSymbol("global"),
969 Handle<Object>(global_context()->global()), attributes);
970
971 // Setup the reference from the global object to the builtins object.
972 JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
973
974 // Create a bridge function that has context in the global context.
975 Handle<JSFunction> bridge =
976 Factory::NewFunction(Factory::empty_symbol(), Factory::undefined_value());
977 ASSERT(bridge->context() == *Top::global_context());
978
979 // Allocate the builtins context.
980 Handle<Context> context =
981 Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
982 context->set_global(*builtins); // override builtins global object
983
984 global_context()->set_runtime_context(*context);
985
986 { // -- S c r i p t
987 // Builtin functions for Script.
988 Handle<JSFunction> script_fun =
989 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
990 Top::initial_object_prototype(), Builtins::Illegal,
991 false);
992 Handle<JSObject> prototype =
993 Factory::NewJSObject(Top::object_function(), TENURED);
994 SetPrototype(script_fun, prototype);
995 global_context()->set_script_function(*script_fun);
996
997 // Add 'source' and 'data' property to scripts.
998 PropertyAttributes common_attributes =
999 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1000 Handle<Proxy> proxy_source = Factory::NewProxy(&Accessors::ScriptSource);
1001 Handle<DescriptorArray> script_descriptors =
1002 Factory::CopyAppendProxyDescriptor(
1003 Factory::empty_descriptor_array(),
1004 Factory::LookupAsciiSymbol("source"),
1005 proxy_source,
1006 common_attributes);
1007 Handle<Proxy> proxy_name = Factory::NewProxy(&Accessors::ScriptName);
1008 script_descriptors =
1009 Factory::CopyAppendProxyDescriptor(
1010 script_descriptors,
1011 Factory::LookupAsciiSymbol("name"),
1012 proxy_name,
1013 common_attributes);
1014 Handle<Proxy> proxy_id = Factory::NewProxy(&Accessors::ScriptId);
1015 script_descriptors =
1016 Factory::CopyAppendProxyDescriptor(
1017 script_descriptors,
1018 Factory::LookupAsciiSymbol("id"),
1019 proxy_id,
1020 common_attributes);
1021 Handle<Proxy> proxy_line_offset =
1022 Factory::NewProxy(&Accessors::ScriptLineOffset);
1023 script_descriptors =
1024 Factory::CopyAppendProxyDescriptor(
1025 script_descriptors,
1026 Factory::LookupAsciiSymbol("line_offset"),
1027 proxy_line_offset,
1028 common_attributes);
1029 Handle<Proxy> proxy_column_offset =
1030 Factory::NewProxy(&Accessors::ScriptColumnOffset);
1031 script_descriptors =
1032 Factory::CopyAppendProxyDescriptor(
1033 script_descriptors,
1034 Factory::LookupAsciiSymbol("column_offset"),
1035 proxy_column_offset,
1036 common_attributes);
1037 Handle<Proxy> proxy_data = Factory::NewProxy(&Accessors::ScriptData);
1038 script_descriptors =
1039 Factory::CopyAppendProxyDescriptor(
1040 script_descriptors,
1041 Factory::LookupAsciiSymbol("data"),
1042 proxy_data,
1043 common_attributes);
1044 Handle<Proxy> proxy_type = Factory::NewProxy(&Accessors::ScriptType);
1045 script_descriptors =
1046 Factory::CopyAppendProxyDescriptor(
1047 script_descriptors,
1048 Factory::LookupAsciiSymbol("type"),
1049 proxy_type,
1050 common_attributes);
1051 Handle<Proxy> proxy_compilation_type =
1052 Factory::NewProxy(&Accessors::ScriptCompilationType);
1053 script_descriptors =
1054 Factory::CopyAppendProxyDescriptor(
1055 script_descriptors,
1056 Factory::LookupAsciiSymbol("compilation_type"),
1057 proxy_compilation_type,
1058 common_attributes);
1059 Handle<Proxy> proxy_line_ends =
1060 Factory::NewProxy(&Accessors::ScriptLineEnds);
1061 script_descriptors =
1062 Factory::CopyAppendProxyDescriptor(
1063 script_descriptors,
1064 Factory::LookupAsciiSymbol("line_ends"),
1065 proxy_line_ends,
1066 common_attributes);
1067 Handle<Proxy> proxy_context_data =
1068 Factory::NewProxy(&Accessors::ScriptContextData);
1069 script_descriptors =
1070 Factory::CopyAppendProxyDescriptor(
1071 script_descriptors,
1072 Factory::LookupAsciiSymbol("context_data"),
1073 proxy_context_data,
1074 common_attributes);
1075 Handle<Proxy> proxy_eval_from_function =
1076 Factory::NewProxy(&Accessors::ScriptEvalFromFunction);
1077 script_descriptors =
1078 Factory::CopyAppendProxyDescriptor(
1079 script_descriptors,
1080 Factory::LookupAsciiSymbol("eval_from_function"),
1081 proxy_eval_from_function,
1082 common_attributes);
1083 Handle<Proxy> proxy_eval_from_position =
1084 Factory::NewProxy(&Accessors::ScriptEvalFromPosition);
1085 script_descriptors =
1086 Factory::CopyAppendProxyDescriptor(
1087 script_descriptors,
1088 Factory::LookupAsciiSymbol("eval_from_position"),
1089 proxy_eval_from_position,
1090 common_attributes);
1091
1092 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1093 script_map->set_instance_descriptors(*script_descriptors);
1094
1095 // Allocate the empty script.
1096 Handle<Script> script = Factory::NewScript(Factory::empty_string());
1097 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
1098 global_context()->set_empty_script(*script);
1099 }
1100
1101 if (FLAG_natives_file == NULL) {
1102 // Without natives file, install default natives.
1103 for (int i = Natives::GetDelayCount();
1104 i < Natives::GetBuiltinsCount();
1105 i++) {
1106 if (!CompileBuiltin(i)) return false;
1107 }
1108
1109 // Setup natives with lazy loading.
1110 SetupLazy(Handle<JSFunction>(global_context()->date_function()),
1111 Natives::GetIndex("date"),
1112 Top::global_context(),
1113 Handle<Context>(Top::context()->runtime_context()));
1114 SetupLazy(Handle<JSFunction>(global_context()->regexp_function()),
1115 Natives::GetIndex("regexp"),
1116 Top::global_context(),
1117 Handle<Context>(Top::context()->runtime_context()));
1118 SetupLazy(Handle<JSObject>(global_context()->json_object()),
1119 Natives::GetIndex("json"),
1120 Top::global_context(),
1121 Handle<Context>(Top::context()->runtime_context()));
1122
1123 } else if (strlen(FLAG_natives_file) != 0) {
1124 // Otherwise install natives from natives file if file exists and
1125 // compiles.
1126 bool exists;
1127 Vector<const char> source = ReadFile(FLAG_natives_file, &exists);
1128 Handle<String> source_string = Factory::NewStringFromAscii(source);
1129 if (source.is_empty()) return false;
1130 bool result = CompileNative(CStrVector(FLAG_natives_file), source_string);
1131 if (!result) return false;
1132
1133 } else {
1134 // Empty natives file name - do not install any natives.
1135 PrintF("Warning: Running without installed natives!\n");
1136 return true;
1137 }
1138
1139 InstallNativeFunctions();
1140
1141 // Install Function.prototype.call and apply.
1142 { Handle<String> key = Factory::function_class_symbol();
1143 Handle<JSFunction> function =
1144 Handle<JSFunction>::cast(GetProperty(Top::global(), key));
1145 Handle<JSObject> proto =
1146 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1147
1148 // Install the call and the apply functions.
1149 Handle<JSFunction> call =
1150 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1151 Factory::NewJSObject(Top::object_function(), TENURED),
1152 Builtins::FunctionCall,
1153 false);
1154 Handle<JSFunction> apply =
1155 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1156 Factory::NewJSObject(Top::object_function(), TENURED),
1157 Builtins::FunctionApply,
1158 false);
1159
1160 // Make sure that Function.prototype.call appears to be compiled.
1161 // The code will never be called, but inline caching for call will
1162 // only work if it appears to be compiled.
1163 call->shared()->DontAdaptArguments();
1164 ASSERT(call->is_compiled());
1165
1166 // Set the expected parameters for apply to 2; required by builtin.
1167 apply->shared()->set_formal_parameter_count(2);
1168
1169 // Set the lengths for the functions to satisfy ECMA-262.
1170 call->shared()->set_length(1);
1171 apply->shared()->set_length(2);
1172 }
1173
1174#ifdef DEBUG
1175 builtins->Verify();
1176#endif
1177 return true;
1178}
1179
1180
1181bool Genesis::InstallSpecialObjects() {
1182 HandleScope scope;
1183 Handle<JSGlobalObject> js_global(
1184 JSGlobalObject::cast(global_context()->global()));
1185 // Expose the natives in global if a name for it is specified.
1186 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1187 Handle<String> natives_string =
1188 Factory::LookupAsciiSymbol(FLAG_expose_natives_as);
1189 SetProperty(js_global, natives_string,
1190 Handle<JSObject>(js_global->builtins()), DONT_ENUM);
1191 }
1192
1193 Handle<Object> Error = GetProperty(js_global, "Error");
1194 if (Error->IsJSObject()) {
1195 Handle<String> name = Factory::LookupAsciiSymbol("stackTraceLimit");
1196 SetProperty(Handle<JSObject>::cast(Error),
1197 name,
1198 Handle<Smi>(Smi::FromInt(FLAG_stack_trace_limit)),
1199 NONE);
1200 }
1201
1202#ifdef ENABLE_DEBUGGER_SUPPORT
1203 // Expose the debug global object in global if a name for it is specified.
1204 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1205 // If loading fails we just bail out without installing the
1206 // debugger but without tanking the whole context.
1207 if (!Debug::Load())
1208 return true;
1209 // Set the security token for the debugger context to the same as
1210 // the shell global context to allow calling between these (otherwise
1211 // exposing debug global object doesn't make much sense).
1212 Debug::debug_context()->set_security_token(
1213 global_context()->security_token());
1214
1215 Handle<String> debug_string =
1216 Factory::LookupAsciiSymbol(FLAG_expose_debug_as);
1217 SetProperty(js_global, debug_string,
1218 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM);
1219 }
1220#endif
1221
1222 return true;
1223}
1224
1225
1226bool Genesis::InstallExtensions(v8::ExtensionConfiguration* extensions) {
1227 // Clear coloring of extension list
1228 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1229 while (current != NULL) {
1230 current->set_state(v8::UNVISITED);
1231 current = current->next();
1232 }
1233 // Install auto extensions
1234 current = v8::RegisteredExtension::first_extension();
1235 while (current != NULL) {
1236 if (current->extension()->auto_enable())
1237 InstallExtension(current);
1238 current = current->next();
1239 }
1240
1241 if (FLAG_expose_gc) InstallExtension("v8/gc");
1242
1243 if (extensions == NULL) return true;
1244 // Install required extensions
1245 int count = v8::ImplementationUtilities::GetNameCount(extensions);
1246 const char** names = v8::ImplementationUtilities::GetNames(extensions);
1247 for (int i = 0; i < count; i++) {
1248 if (!InstallExtension(names[i]))
1249 return false;
1250 }
1251
1252 return true;
1253}
1254
1255
1256// Installs a named extension. This methods is unoptimized and does
1257// not scale well if we want to support a large number of extensions.
1258bool Genesis::InstallExtension(const char* name) {
1259 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1260 // Loop until we find the relevant extension
1261 while (current != NULL) {
1262 if (strcmp(name, current->extension()->name()) == 0) break;
1263 current = current->next();
1264 }
1265 // Didn't find the extension; fail.
1266 if (current == NULL) {
1267 v8::Utils::ReportApiFailure(
1268 "v8::Context::New()", "Cannot find required extension");
1269 return false;
1270 }
1271 return InstallExtension(current);
1272}
1273
1274
1275bool Genesis::InstallExtension(v8::RegisteredExtension* current) {
1276 HandleScope scope;
1277
1278 if (current->state() == v8::INSTALLED) return true;
1279 // The current node has already been visited so there must be a
1280 // cycle in the dependency graph; fail.
1281 if (current->state() == v8::VISITED) {
1282 v8::Utils::ReportApiFailure(
1283 "v8::Context::New()", "Circular extension dependency");
1284 return false;
1285 }
1286 ASSERT(current->state() == v8::UNVISITED);
1287 current->set_state(v8::VISITED);
1288 v8::Extension* extension = current->extension();
1289 // Install the extension's dependencies
1290 for (int i = 0; i < extension->dependency_count(); i++) {
1291 if (!InstallExtension(extension->dependencies()[i])) return false;
1292 }
1293 Vector<const char> source = CStrVector(extension->source());
1294 Handle<String> source_code = Factory::NewStringFromAscii(source);
1295 bool result = CompileScriptCached(CStrVector(extension->name()),
1296 source_code,
1297 &extensions_cache, extension,
1298 false);
1299 ASSERT(Top::has_pending_exception() != result);
1300 if (!result) {
1301 Top::clear_pending_exception();
1302 v8::Utils::ReportApiFailure(
1303 "v8::Context::New()", "Error installing extension");
1304 }
1305 current->set_state(v8::INSTALLED);
1306 return result;
1307}
1308
1309
1310bool Genesis::ConfigureGlobalObjects(
1311 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
1312 Handle<JSObject> global_proxy(
1313 JSObject::cast(global_context()->global_proxy()));
1314 Handle<JSObject> js_global(JSObject::cast(global_context()->global()));
1315
1316 if (!global_proxy_template.IsEmpty()) {
1317 // Configure the global proxy object.
1318 Handle<ObjectTemplateInfo> proxy_data =
1319 v8::Utils::OpenHandle(*global_proxy_template);
1320 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
1321
1322 // Configure the inner global object.
1323 Handle<FunctionTemplateInfo> proxy_constructor(
1324 FunctionTemplateInfo::cast(proxy_data->constructor()));
1325 if (!proxy_constructor->prototype_template()->IsUndefined()) {
1326 Handle<ObjectTemplateInfo> inner_data(
1327 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
1328 if (!ConfigureApiObject(js_global, inner_data)) return false;
1329 }
1330 }
1331
1332 SetObjectPrototype(global_proxy, js_global);
1333 return true;
1334}
1335
1336
1337bool Genesis::ConfigureApiObject(Handle<JSObject> object,
1338 Handle<ObjectTemplateInfo> object_template) {
1339 ASSERT(!object_template.is_null());
1340 ASSERT(object->IsInstanceOf(
1341 FunctionTemplateInfo::cast(object_template->constructor())));
1342
1343 bool pending_exception = false;
1344 Handle<JSObject> obj =
1345 Execution::InstantiateObject(object_template, &pending_exception);
1346 if (pending_exception) {
1347 ASSERT(Top::has_pending_exception());
1348 Top::clear_pending_exception();
1349 return false;
1350 }
1351 TransferObject(obj, object);
1352 return true;
1353}
1354
1355
1356void Genesis::TransferNamedProperties(Handle<JSObject> from,
1357 Handle<JSObject> to) {
1358 if (from->HasFastProperties()) {
1359 Handle<DescriptorArray> descs =
1360 Handle<DescriptorArray>(from->map()->instance_descriptors());
1361 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1362 PropertyDetails details = PropertyDetails(descs->GetDetails(i));
1363 switch (details.type()) {
1364 case FIELD: {
1365 HandleScope inner;
1366 Handle<String> key = Handle<String>(descs->GetKey(i));
1367 int index = descs->GetFieldIndex(i);
1368 Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
1369 SetProperty(to, key, value, details.attributes());
1370 break;
1371 }
1372 case CONSTANT_FUNCTION: {
1373 HandleScope inner;
1374 Handle<String> key = Handle<String>(descs->GetKey(i));
1375 Handle<JSFunction> fun =
1376 Handle<JSFunction>(descs->GetConstantFunction(i));
1377 SetProperty(to, key, fun, details.attributes());
1378 break;
1379 }
1380 case CALLBACKS: {
1381 LookupResult result;
1382 to->LocalLookup(descs->GetKey(i), &result);
1383 // If the property is already there we skip it
1384 if (result.IsValid()) continue;
1385 HandleScope inner;
1386 Handle<DescriptorArray> inst_descs =
1387 Handle<DescriptorArray>(to->map()->instance_descriptors());
1388 Handle<String> key = Handle<String>(descs->GetKey(i));
1389 Handle<Object> entry = Handle<Object>(descs->GetCallbacksObject(i));
1390 inst_descs = Factory::CopyAppendProxyDescriptor(inst_descs,
1391 key,
1392 entry,
1393 details.attributes());
1394 to->map()->set_instance_descriptors(*inst_descs);
1395 break;
1396 }
1397 case MAP_TRANSITION:
1398 case CONSTANT_TRANSITION:
1399 case NULL_DESCRIPTOR:
1400 // Ignore non-properties.
1401 break;
1402 case NORMAL:
1403 // Do not occur since the from object has fast properties.
1404 case INTERCEPTOR:
1405 // No element in instance descriptors have interceptor type.
1406 UNREACHABLE();
1407 break;
1408 }
1409 }
1410 } else {
1411 Handle<StringDictionary> properties =
1412 Handle<StringDictionary>(from->property_dictionary());
1413 int capacity = properties->Capacity();
1414 for (int i = 0; i < capacity; i++) {
1415 Object* raw_key(properties->KeyAt(i));
1416 if (properties->IsKey(raw_key)) {
1417 ASSERT(raw_key->IsString());
1418 // If the property is already there we skip it.
1419 LookupResult result;
1420 to->LocalLookup(String::cast(raw_key), &result);
1421 if (result.IsValid()) continue;
1422 // Set the property.
1423 Handle<String> key = Handle<String>(String::cast(raw_key));
1424 Handle<Object> value = Handle<Object>(properties->ValueAt(i));
1425 if (value->IsJSGlobalPropertyCell()) {
1426 value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
1427 }
1428 PropertyDetails details = properties->DetailsAt(i);
1429 SetProperty(to, key, value, details.attributes());
1430 }
1431 }
1432 }
1433}
1434
1435
1436void Genesis::TransferIndexedProperties(Handle<JSObject> from,
1437 Handle<JSObject> to) {
1438 // Cloning the elements array is sufficient.
1439 Handle<FixedArray> from_elements =
1440 Handle<FixedArray>(FixedArray::cast(from->elements()));
1441 Handle<FixedArray> to_elements = Factory::CopyFixedArray(from_elements);
1442 to->set_elements(*to_elements);
1443}
1444
1445
1446void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
1447 HandleScope outer;
1448
1449 ASSERT(!from->IsJSArray());
1450 ASSERT(!to->IsJSArray());
1451
1452 TransferNamedProperties(from, to);
1453 TransferIndexedProperties(from, to);
1454
1455 // Transfer the prototype (new map is needed).
1456 Handle<Map> old_to_map = Handle<Map>(to->map());
1457 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
1458 new_to_map->set_prototype(from->map()->prototype());
1459 to->set_map(*new_to_map);
1460}
1461
1462
1463void Genesis::MakeFunctionInstancePrototypeWritable() {
1464 // Make a new function map so all future functions
1465 // will have settable and enumerable prototype properties.
1466 HandleScope scope;
1467
1468 Handle<DescriptorArray> function_map_descriptors =
1469 ComputeFunctionInstanceDescriptor(false);
1470 Handle<Map> fm = Factory::CopyMapDropDescriptors(Top::function_map());
1471 fm->set_instance_descriptors(*function_map_descriptors);
1472 Top::context()->global_context()->set_function_map(*fm);
1473}
1474
1475
1476void Genesis::AddSpecialFunction(Handle<JSObject> prototype,
1477 const char* name,
1478 Handle<Code> code) {
1479 Handle<String> key = Factory::LookupAsciiSymbol(name);
1480 Handle<Object> value = Handle<Object>(prototype->GetProperty(*key));
1481 if (value->IsJSFunction()) {
1482 Handle<JSFunction> optimized = Factory::NewFunction(key,
1483 JS_OBJECT_TYPE,
1484 JSObject::kHeaderSize,
1485 code,
1486 false);
1487 optimized->shared()->DontAdaptArguments();
1488 int len = global_context()->special_function_table()->length();
1489 Handle<FixedArray> new_array = Factory::NewFixedArray(len + 3);
1490 for (int index = 0; index < len; index++) {
1491 new_array->set(index,
1492 global_context()->special_function_table()->get(index));
1493 }
1494 new_array->set(len+0, *prototype);
1495 new_array->set(len+1, *value);
1496 new_array->set(len+2, *optimized);
1497 global_context()->set_special_function_table(*new_array);
1498 }
1499}
1500
1501
1502void Genesis::BuildSpecialFunctionTable() {
1503 HandleScope scope;
1504 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
1505 // Add special versions for Array.prototype.pop and push.
1506 Handle<JSFunction> function =
1507 Handle<JSFunction>(
1508 JSFunction::cast(global->GetProperty(Heap::Array_symbol())));
1509 Handle<JSObject> visible_prototype =
1510 Handle<JSObject>(JSObject::cast(function->prototype()));
1511 // Remember to put push and pop on the hidden prototype if it's there.
1512 Handle<JSObject> push_and_pop_prototype;
1513 Handle<Object> superproto(visible_prototype->GetPrototype());
1514 if (superproto->IsJSObject() &&
1515 JSObject::cast(*superproto)->map()->is_hidden_prototype()) {
1516 push_and_pop_prototype = Handle<JSObject>::cast(superproto);
1517 } else {
1518 push_and_pop_prototype = visible_prototype;
1519 }
1520 AddSpecialFunction(push_and_pop_prototype, "pop",
1521 Handle<Code>(Builtins::builtin(Builtins::ArrayPop)));
1522 AddSpecialFunction(push_and_pop_prototype, "push",
1523 Handle<Code>(Builtins::builtin(Builtins::ArrayPush)));
1524}
1525
1526
1527Genesis::Genesis(Handle<Object> global_object,
1528 v8::Handle<v8::ObjectTemplate> global_template,
1529 v8::ExtensionConfiguration* extensions) {
1530 // Link this genesis object into the stacked genesis chain. This
1531 // must be done before any early exits because the destructor
1532 // will always do unlinking.
1533 previous_ = current_;
1534 current_ = this;
1535 result_ = Handle<Context>::null();
1536
1537 // If V8 isn't running and cannot be initialized, just return.
1538 if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
1539
1540 // Before creating the roots we must save the context and restore it
1541 // on all function exits.
1542 HandleScope scope;
1543 SaveContext context;
1544
1545 CreateRoots(global_template, global_object);
1546
1547 if (!InstallNatives()) return;
1548
1549 MakeFunctionInstancePrototypeWritable();
1550 BuildSpecialFunctionTable();
1551
1552 if (!ConfigureGlobalObjects(global_template)) return;
1553
1554 if (!InstallExtensions(extensions)) return;
1555
1556 if (!InstallSpecialObjects()) return;
1557
1558 result_ = global_context_;
1559}
1560
1561
1562// Support for thread preemption.
1563
1564// Reserve space for statics needing saving and restoring.
1565int Bootstrapper::ArchiveSpacePerThread() {
1566 return Genesis::ArchiveSpacePerThread();
1567}
1568
1569
1570// Archive statics that are thread local.
1571char* Bootstrapper::ArchiveState(char* to) {
1572 return Genesis::ArchiveState(to);
1573}
1574
1575
1576// Restore statics that are thread local.
1577char* Bootstrapper::RestoreState(char* from) {
1578 return Genesis::RestoreState(from);
1579}
1580
1581
1582// Called when the top-level V8 mutex is destroyed.
1583void Bootstrapper::FreeThreadResources() {
1584 ASSERT(Genesis::current() == NULL);
1585}
1586
1587
1588// Reserve space for statics needing saving and restoring.
1589int Genesis::ArchiveSpacePerThread() {
1590 return sizeof(current_);
1591}
1592
1593
1594// Archive statics that are thread local.
1595char* Genesis::ArchiveState(char* to) {
1596 *reinterpret_cast<Genesis**>(to) = current_;
1597 current_ = NULL;
1598 return to + sizeof(current_);
1599}
1600
1601
1602// Restore statics that are thread local.
1603char* Genesis::RestoreState(char* from) {
1604 current_ = *reinterpret_cast<Genesis**>(from);
1605 return from + sizeof(current_);
1606}
1607
1608} } // namespace v8::internal