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