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