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