blob: 087413118f3b38417ce051f922cbf3d7c891f753 [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"
Kristian Monsen25f61362010-05-21 11:50:48 +010040#include "stub-cache.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000041
42namespace v8 {
43namespace internal {
44
45// A SourceCodeCache uses a FixedArray to store pairs of
46// (AsciiString*, JSFunction*), mapping names of native code files
47// (runtime.js, etc.) to precompiled functions. Instead of mapping
48// names to functions it might make sense to let the JS2C tool
49// generate an index for each native JS file.
50class SourceCodeCache BASE_EMBEDDED {
51 public:
52 explicit SourceCodeCache(Script::Type type): type_(type), cache_(NULL) { }
53
54 void Initialize(bool create_heap_objects) {
55 cache_ = create_heap_objects ? Heap::empty_fixed_array() : NULL;
56 }
57
58 void Iterate(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +010059 v->VisitPointer(BitCast<Object**, FixedArray**>(&cache_));
Steve Blocka7e24c12009-10-30 11:49:00 +000060 }
61
62
Steve Block6ded16b2010-05-10 14:33:55 +010063 bool Lookup(Vector<const char> name, Handle<SharedFunctionInfo>* handle) {
Steve Blocka7e24c12009-10-30 11:49:00 +000064 for (int i = 0; i < cache_->length(); i+=2) {
65 SeqAsciiString* str = SeqAsciiString::cast(cache_->get(i));
66 if (str->IsEqualTo(name)) {
Steve Block6ded16b2010-05-10 14:33:55 +010067 *handle = Handle<SharedFunctionInfo>(
68 SharedFunctionInfo::cast(cache_->get(i + 1)));
Steve Blocka7e24c12009-10-30 11:49:00 +000069 return true;
70 }
71 }
72 return false;
73 }
74
75
Steve Block6ded16b2010-05-10 14:33:55 +010076 void Add(Vector<const char> name, Handle<SharedFunctionInfo> shared) {
Steve Blocka7e24c12009-10-30 11:49:00 +000077 HandleScope scope;
78 int length = cache_->length();
79 Handle<FixedArray> new_array =
80 Factory::NewFixedArray(length + 2, TENURED);
81 cache_->CopyTo(0, *new_array, 0, cache_->length());
82 cache_ = *new_array;
83 Handle<String> str = Factory::NewStringFromAscii(name, TENURED);
84 cache_->set(length, *str);
Steve Block6ded16b2010-05-10 14:33:55 +010085 cache_->set(length + 1, *shared);
86 Script::cast(shared->script())->set_type(Smi::FromInt(type_));
Steve Blocka7e24c12009-10-30 11:49:00 +000087 }
88
89 private:
90 Script::Type type_;
91 FixedArray* cache_;
92 DISALLOW_COPY_AND_ASSIGN(SourceCodeCache);
93};
94
Steve Blocka7e24c12009-10-30 11:49:00 +000095static 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
Steve Blocka7e24c12009-10-30 11:49:00 +0000137void Bootstrapper::Initialize(bool create_heap_objects) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000138 extensions_cache.Initialize(create_heap_objects);
139}
140
141
Leon Clarkee46be812010-01-19 14:06:41 +0000142char* Bootstrapper::AllocateAutoDeletedArray(int bytes) {
143 char* memory = new char[bytes];
144 if (memory != NULL) {
145 if (delete_these_arrays_on_tear_down == NULL) {
146 delete_these_arrays_on_tear_down = new List<char*>(2);
147 }
148 delete_these_arrays_on_tear_down->Add(memory);
149 }
150 return memory;
151}
152
153
Steve Blocka7e24c12009-10-30 11:49:00 +0000154void Bootstrapper::TearDown() {
Steve Blockd0582a62009-12-15 09:54:21 +0000155 if (delete_these_non_arrays_on_tear_down != NULL) {
156 int len = delete_these_non_arrays_on_tear_down->length();
157 ASSERT(len < 20); // Don't use this mechanism for unbounded allocations.
158 for (int i = 0; i < len; i++) {
159 delete delete_these_non_arrays_on_tear_down->at(i);
Leon Clarkee46be812010-01-19 14:06:41 +0000160 delete_these_non_arrays_on_tear_down->at(i) = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000161 }
162 delete delete_these_non_arrays_on_tear_down;
163 delete_these_non_arrays_on_tear_down = NULL;
164 }
165
Leon Clarkee46be812010-01-19 14:06:41 +0000166 if (delete_these_arrays_on_tear_down != NULL) {
167 int len = delete_these_arrays_on_tear_down->length();
168 ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations.
169 for (int i = 0; i < len; i++) {
170 delete[] delete_these_arrays_on_tear_down->at(i);
171 delete_these_arrays_on_tear_down->at(i) = NULL;
172 }
173 delete delete_these_arrays_on_tear_down;
174 delete_these_arrays_on_tear_down = NULL;
175 }
176
Andrei Popescu31002712010-02-23 13:46:05 +0000177 extensions_cache.Initialize(false); // Yes, symmetrical
Steve Blocka7e24c12009-10-30 11:49:00 +0000178}
179
180
Steve Blocka7e24c12009-10-30 11:49:00 +0000181class Genesis BASE_EMBEDDED {
182 public:
183 Genesis(Handle<Object> global_object,
184 v8::Handle<v8::ObjectTemplate> global_template,
185 v8::ExtensionConfiguration* extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000186 ~Genesis() { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000187
188 Handle<Context> result() { return result_; }
189
190 Genesis* previous() { return previous_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000191
192 private:
193 Handle<Context> global_context_;
194
195 // There may be more than one active genesis object: When GC is
196 // triggered during environment creation there may be weak handle
197 // processing callbacks which may create new environments.
198 Genesis* previous_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000199
200 Handle<Context> global_context() { return global_context_; }
201
Andrei Popescu31002712010-02-23 13:46:05 +0000202 // Creates some basic objects. Used for creating a context from scratch.
203 void CreateRoots();
204 // Creates the empty function. Used for creating a context from scratch.
205 Handle<JSFunction> CreateEmptyFunction();
206 // Creates the global objects using the global and the template passed in
207 // through the API. We call this regardless of whether we are building a
208 // context from scratch or using a deserialized one from the partial snapshot
209 // but in the latter case we don't use the objects it produces directly, as
210 // we have to used the deserialized ones that are linked together with the
211 // rest of the context snapshot.
212 Handle<JSGlobalProxy> CreateNewGlobals(
213 v8::Handle<v8::ObjectTemplate> global_template,
214 Handle<Object> global_object,
215 Handle<GlobalObject>* global_proxy_out);
216 // Hooks the given global proxy into the context. If the context was created
217 // by deserialization then this will unhook the global proxy that was
218 // deserialized, leaving the GC to pick it up.
219 void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
220 Handle<JSGlobalProxy> global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +0000221 // Similarly, we want to use the inner global that has been created by the
222 // templates passed through the API. The inner global from the snapshot is
223 // detached from the other objects in the snapshot.
224 void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
Andrei Popescu31002712010-02-23 13:46:05 +0000225 // New context initialization. Used for creating a context from scratch.
226 void InitializeGlobal(Handle<GlobalObject> inner_global,
227 Handle<JSFunction> empty_function);
228 // Installs the contents of the native .js files on the global objects.
229 // Used for creating a context from scratch.
Steve Blocka7e24c12009-10-30 11:49:00 +0000230 void InstallNativeFunctions();
231 bool InstallNatives();
Kristian Monsen25f61362010-05-21 11:50:48 +0100232 void InstallCustomCallGenerators();
Steve Block6ded16b2010-05-10 14:33:55 +0100233 void InstallJSFunctionResultCaches();
Andrei Popescu31002712010-02-23 13:46:05 +0000234 // Used both for deserialized and from-scratch contexts to add the extensions
235 // provided.
236 static bool InstallExtensions(Handle<Context> global_context,
237 v8::ExtensionConfiguration* extensions);
238 static bool InstallExtension(const char* name);
239 static bool InstallExtension(v8::RegisteredExtension* current);
240 static void InstallSpecialObjects(Handle<Context> global_context);
Andrei Popescu402d9372010-02-26 13:31:12 +0000241 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
Steve Blocka7e24c12009-10-30 11:49:00 +0000242 bool ConfigureApiObject(Handle<JSObject> object,
243 Handle<ObjectTemplateInfo> object_template);
244 bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
245
246 // Migrates all properties from the 'from' object to the 'to'
247 // object and overrides the prototype in 'to' with the one from
248 // 'from'.
249 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
250 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
251 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
252
Steve Block6ded16b2010-05-10 14:33:55 +0100253 enum PrototypePropertyMode {
254 DONT_ADD_PROTOTYPE,
255 ADD_READONLY_PROTOTYPE,
256 ADD_WRITEABLE_PROTOTYPE
257 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000258 Handle<DescriptorArray> ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100259 PrototypePropertyMode prototypeMode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000260 void MakeFunctionInstancePrototypeWritable();
261
Steve Blocka7e24c12009-10-30 11:49:00 +0000262 static bool CompileBuiltin(int index);
263 static bool CompileNative(Vector<const char> name, Handle<String> source);
264 static bool CompileScriptCached(Vector<const char> name,
265 Handle<String> source,
266 SourceCodeCache* cache,
267 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000268 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000269 bool use_runtime_context);
270
271 Handle<Context> result_;
Andrei Popescu31002712010-02-23 13:46:05 +0000272 Handle<JSFunction> empty_function_;
273 BootstrapperActive active_;
274 friend class Bootstrapper;
Steve Blocka7e24c12009-10-30 11:49:00 +0000275};
276
Steve Blocka7e24c12009-10-30 11:49:00 +0000277
278void Bootstrapper::Iterate(ObjectVisitor* v) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000279 extensions_cache.Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +0000280 v->Synchronize("Extensions");
Steve Blocka7e24c12009-10-30 11:49:00 +0000281}
282
283
Steve Blocka7e24c12009-10-30 11:49:00 +0000284Handle<Context> Bootstrapper::CreateEnvironment(
285 Handle<Object> global_object,
286 v8::Handle<v8::ObjectTemplate> global_template,
287 v8::ExtensionConfiguration* extensions) {
Andrei Popescu31002712010-02-23 13:46:05 +0000288 HandleScope scope;
289 Handle<Context> env;
Steve Blocka7e24c12009-10-30 11:49:00 +0000290 Genesis genesis(global_object, global_template, extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000291 env = genesis.result();
292 if (!env.is_null()) {
293 if (InstallExtensions(env, extensions)) {
294 return env;
295 }
296 }
297 return Handle<Context>();
Steve Blocka7e24c12009-10-30 11:49:00 +0000298}
299
300
301static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
302 // object.__proto__ = proto;
303 Handle<Map> old_to_map = Handle<Map>(object->map());
304 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
305 new_to_map->set_prototype(*proto);
306 object->set_map(*new_to_map);
307}
308
309
310void Bootstrapper::DetachGlobal(Handle<Context> env) {
311 JSGlobalProxy::cast(env->global_proxy())->set_context(*Factory::null_value());
312 SetObjectPrototype(Handle<JSObject>(env->global_proxy()),
313 Factory::null_value());
314 env->set_global_proxy(env->global());
315 env->global()->set_global_receiver(env->global());
316}
317
318
Andrei Popescu74b3c142010-03-29 12:03:09 +0100319void Bootstrapper::ReattachGlobal(Handle<Context> env,
320 Handle<Object> global_object) {
321 ASSERT(global_object->IsJSGlobalProxy());
322 Handle<JSGlobalProxy> global = Handle<JSGlobalProxy>::cast(global_object);
323 env->global()->set_global_receiver(*global);
324 env->set_global_proxy(*global);
325 SetObjectPrototype(global, Handle<JSObject>(env->global()));
326 global->set_context(*env);
327}
328
329
Steve Blocka7e24c12009-10-30 11:49:00 +0000330static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
331 const char* name,
332 InstanceType type,
333 int instance_size,
334 Handle<JSObject> prototype,
335 Builtins::Name call,
336 bool is_ecma_native) {
337 Handle<String> symbol = Factory::LookupAsciiSymbol(name);
338 Handle<Code> call_code = Handle<Code>(Builtins::builtin(call));
Steve Block6ded16b2010-05-10 14:33:55 +0100339 Handle<JSFunction> function = prototype.is_null() ?
340 Factory::NewFunctionWithoutPrototype(symbol, call_code) :
Steve Blocka7e24c12009-10-30 11:49:00 +0000341 Factory::NewFunctionWithPrototype(symbol,
342 type,
343 instance_size,
344 prototype,
345 call_code,
346 is_ecma_native);
347 SetProperty(target, symbol, function, DONT_ENUM);
348 if (is_ecma_native) {
349 function->shared()->set_instance_class_name(*symbol);
350 }
351 return function;
352}
353
354
355Handle<DescriptorArray> Genesis::ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100356 PrototypePropertyMode prototypeMode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000357 Handle<DescriptorArray> result = Factory::empty_descriptor_array();
358
Steve Block6ded16b2010-05-10 14:33:55 +0100359 if (prototypeMode != DONT_ADD_PROTOTYPE) {
360 PropertyAttributes attributes = static_cast<PropertyAttributes>(
361 DONT_ENUM |
362 DONT_DELETE |
363 (prototypeMode == ADD_READONLY_PROTOTYPE ? READ_ONLY : 0));
364 result =
365 Factory::CopyAppendProxyDescriptor(
366 result,
367 Factory::prototype_symbol(),
368 Factory::NewProxy(&Accessors::FunctionPrototype),
369 attributes);
370 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000371
Steve Block6ded16b2010-05-10 14:33:55 +0100372 PropertyAttributes attributes =
Steve Blocka7e24c12009-10-30 11:49:00 +0000373 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
374 // Add length.
375 result =
376 Factory::CopyAppendProxyDescriptor(
377 result,
378 Factory::length_symbol(),
379 Factory::NewProxy(&Accessors::FunctionLength),
380 attributes);
381
382 // Add name.
383 result =
384 Factory::CopyAppendProxyDescriptor(
385 result,
386 Factory::name_symbol(),
387 Factory::NewProxy(&Accessors::FunctionName),
388 attributes);
389
390 // Add arguments.
391 result =
392 Factory::CopyAppendProxyDescriptor(
393 result,
394 Factory::arguments_symbol(),
395 Factory::NewProxy(&Accessors::FunctionArguments),
396 attributes);
397
398 // Add caller.
399 result =
400 Factory::CopyAppendProxyDescriptor(
401 result,
402 Factory::caller_symbol(),
403 Factory::NewProxy(&Accessors::FunctionCaller),
404 attributes);
405
406 return result;
407}
408
409
Andrei Popescu31002712010-02-23 13:46:05 +0000410Handle<JSFunction> Genesis::CreateEmptyFunction() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000411 // Allocate the map for function instances.
412 Handle<Map> fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
413 global_context()->set_function_instance_map(*fm);
414 // Please note that the prototype property for function instances must be
415 // writable.
416 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +0100417 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000418 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100419 fm->set_function_with_prototype(true);
420
421 // Functions with this map will not have a 'prototype' property, and
422 // can not be used as constructors.
423 Handle<Map> function_without_prototype_map =
424 Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
425 global_context()->set_function_without_prototype_map(
426 *function_without_prototype_map);
427 Handle<DescriptorArray> function_without_prototype_map_descriptors =
428 ComputeFunctionInstanceDescriptor(DONT_ADD_PROTOTYPE);
429 function_without_prototype_map->set_instance_descriptors(
430 *function_without_prototype_map_descriptors);
431 function_without_prototype_map->set_function_with_prototype(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000432
433 // Allocate the function map first and then patch the prototype later
434 fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
435 global_context()->set_function_map(*fm);
Steve Block6ded16b2010-05-10 14:33:55 +0100436 function_map_descriptors =
437 ComputeFunctionInstanceDescriptor(ADD_READONLY_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000438 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100439 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000440
441 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
442
443 { // --- O b j e c t ---
444 Handle<JSFunction> object_fun =
445 Factory::NewFunction(object_name, Factory::null_value());
446 Handle<Map> object_function_map =
447 Factory::NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
448 object_fun->set_initial_map(*object_function_map);
449 object_function_map->set_constructor(*object_fun);
450
451 global_context()->set_object_function(*object_fun);
452
453 // Allocate a new prototype for the object function.
454 Handle<JSObject> prototype = Factory::NewJSObject(Top::object_function(),
455 TENURED);
456
457 global_context()->set_initial_object_prototype(*prototype);
458 SetPrototype(object_fun, prototype);
459 object_function_map->
460 set_instance_descriptors(Heap::empty_descriptor_array());
461 }
462
463 // Allocate the empty function as the prototype for function ECMAScript
464 // 262 15.3.4.
465 Handle<String> symbol = Factory::LookupAsciiSymbol("Empty");
466 Handle<JSFunction> empty_function =
Steve Block6ded16b2010-05-10 14:33:55 +0100467 Factory::NewFunctionWithoutPrototype(symbol);
Steve Blocka7e24c12009-10-30 11:49:00 +0000468
Andrei Popescu31002712010-02-23 13:46:05 +0000469 // --- E m p t y ---
470 Handle<Code> code =
471 Handle<Code>(Builtins::builtin(Builtins::EmptyFunction));
472 empty_function->set_code(*code);
473 Handle<String> source = Factory::NewStringFromAscii(CStrVector("() {}"));
474 Handle<Script> script = Factory::NewScript(source);
475 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
476 empty_function->shared()->set_script(*script);
477 empty_function->shared()->set_start_position(0);
478 empty_function->shared()->set_end_position(source->length());
479 empty_function->shared()->DontAdaptArguments();
480 global_context()->function_map()->set_prototype(*empty_function);
481 global_context()->function_instance_map()->set_prototype(*empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +0100482 global_context()->function_without_prototype_map()->
483 set_prototype(*empty_function);
Steve Blocka7e24c12009-10-30 11:49:00 +0000484
Andrei Popescu31002712010-02-23 13:46:05 +0000485 // Allocate the function map first and then patch the prototype later
Steve Block6ded16b2010-05-10 14:33:55 +0100486 Handle<Map> empty_fm = Factory::CopyMapDropDescriptors(
487 function_without_prototype_map);
488 empty_fm->set_instance_descriptors(
489 *function_without_prototype_map_descriptors);
Andrei Popescu31002712010-02-23 13:46:05 +0000490 empty_fm->set_prototype(global_context()->object_function()->prototype());
491 empty_function->set_map(*empty_fm);
492 return empty_function;
493}
494
495
496void Genesis::CreateRoots() {
497 // Allocate the global context FixedArray first and then patch the
498 // closure and extension object later (we need the empty function
499 // and the global object, but in order to create those, we need the
500 // global context).
501 global_context_ =
502 Handle<Context>::cast(
503 GlobalHandles::Create(*Factory::NewGlobalContext()));
504 Top::set_context(*global_context());
505
506 // Allocate the message listeners object.
507 {
508 v8::NeanderArray listeners;
509 global_context()->set_message_listeners(*listeners.value());
510 }
511}
512
513
514Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
515 v8::Handle<v8::ObjectTemplate> global_template,
516 Handle<Object> global_object,
517 Handle<GlobalObject>* inner_global_out) {
518 // The argument global_template aka data is an ObjectTemplateInfo.
519 // It has a constructor pointer that points at global_constructor which is a
520 // FunctionTemplateInfo.
521 // The global_constructor is used to create or reinitialize the global_proxy.
522 // The global_constructor also has a prototype_template pointer that points at
523 // js_global_template which is an ObjectTemplateInfo.
524 // That in turn has a constructor pointer that points at
525 // js_global_constructor which is a FunctionTemplateInfo.
526 // js_global_constructor is used to make js_global_function
527 // js_global_function is used to make the new inner_global.
528 //
529 // --- G l o b a l ---
530 // Step 1: Create a fresh inner JSGlobalObject.
531 Handle<JSFunction> js_global_function;
532 Handle<ObjectTemplateInfo> js_global_template;
533 if (!global_template.IsEmpty()) {
534 // Get prototype template of the global_template.
535 Handle<ObjectTemplateInfo> data =
536 v8::Utils::OpenHandle(*global_template);
537 Handle<FunctionTemplateInfo> global_constructor =
538 Handle<FunctionTemplateInfo>(
539 FunctionTemplateInfo::cast(data->constructor()));
540 Handle<Object> proto_template(global_constructor->prototype_template());
541 if (!proto_template->IsUndefined()) {
542 js_global_template =
543 Handle<ObjectTemplateInfo>::cast(proto_template);
544 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000545 }
546
Andrei Popescu31002712010-02-23 13:46:05 +0000547 if (js_global_template.is_null()) {
548 Handle<String> name = Handle<String>(Heap::empty_symbol());
549 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
550 js_global_function =
551 Factory::NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
Andrei Popescu402d9372010-02-26 13:31:12 +0000552 JSGlobalObject::kSize, code, true);
Andrei Popescu31002712010-02-23 13:46:05 +0000553 // Change the constructor property of the prototype of the
554 // hidden global function to refer to the Object function.
555 Handle<JSObject> prototype =
556 Handle<JSObject>(
557 JSObject::cast(js_global_function->instance_prototype()));
558 SetProperty(prototype, Factory::constructor_symbol(),
559 Top::object_function(), NONE);
560 } else {
561 Handle<FunctionTemplateInfo> js_global_constructor(
562 FunctionTemplateInfo::cast(js_global_template->constructor()));
563 js_global_function =
564 Factory::CreateApiFunction(js_global_constructor,
565 Factory::InnerGlobalObject);
Steve Blocka7e24c12009-10-30 11:49:00 +0000566 }
567
Andrei Popescu31002712010-02-23 13:46:05 +0000568 js_global_function->initial_map()->set_is_hidden_prototype();
569 Handle<GlobalObject> inner_global =
570 Factory::NewGlobalObject(js_global_function);
571 if (inner_global_out != NULL) {
572 *inner_global_out = inner_global;
573 }
574
575 // Step 2: create or re-initialize the global proxy object.
576 Handle<JSFunction> global_proxy_function;
577 if (global_template.IsEmpty()) {
578 Handle<String> name = Handle<String>(Heap::empty_symbol());
579 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
580 global_proxy_function =
581 Factory::NewFunction(name, JS_GLOBAL_PROXY_TYPE,
582 JSGlobalProxy::kSize, code, true);
583 } else {
584 Handle<ObjectTemplateInfo> data =
585 v8::Utils::OpenHandle(*global_template);
586 Handle<FunctionTemplateInfo> global_constructor(
587 FunctionTemplateInfo::cast(data->constructor()));
588 global_proxy_function =
589 Factory::CreateApiFunction(global_constructor,
590 Factory::OuterGlobalObject);
591 }
592
593 Handle<String> global_name = Factory::LookupAsciiSymbol("global");
594 global_proxy_function->shared()->set_instance_class_name(*global_name);
595 global_proxy_function->initial_map()->set_is_access_check_needed(true);
596
597 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
598 // Return the global proxy.
599
600 if (global_object.location() != NULL) {
601 ASSERT(global_object->IsJSGlobalProxy());
602 return ReinitializeJSGlobalProxy(
603 global_proxy_function,
604 Handle<JSGlobalProxy>::cast(global_object));
605 } else {
606 return Handle<JSGlobalProxy>::cast(
607 Factory::NewJSObject(global_proxy_function, TENURED));
608 }
609}
610
611
612void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
613 Handle<JSGlobalProxy> global_proxy) {
614 // Set the global context for the global object.
615 inner_global->set_global_context(*global_context());
616 inner_global->set_global_receiver(*global_proxy);
617 global_proxy->set_context(*global_context());
618 global_context()->set_global_proxy(*global_proxy);
619}
620
621
Andrei Popescu402d9372010-02-26 13:31:12 +0000622void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
623 Handle<GlobalObject> inner_global_from_snapshot(
624 GlobalObject::cast(global_context_->extension()));
625 Handle<JSBuiltinsObject> builtins_global(global_context_->builtins());
626 global_context_->set_extension(*inner_global);
627 global_context_->set_global(*inner_global);
628 global_context_->set_security_token(*inner_global);
629 static const PropertyAttributes attributes =
630 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
631 ForceSetProperty(builtins_global,
632 Factory::LookupAsciiSymbol("global"),
633 inner_global,
634 attributes);
635 // Setup the reference from the global object to the builtins object.
636 JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
637 TransferNamedProperties(inner_global_from_snapshot, inner_global);
638 TransferIndexedProperties(inner_global_from_snapshot, inner_global);
639}
640
641
642// This is only called if we are not using snapshots. The equivalent
643// work in the snapshot case is done in HookUpInnerGlobal.
Andrei Popescu31002712010-02-23 13:46:05 +0000644void Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
645 Handle<JSFunction> empty_function) {
646 // --- G l o b a l C o n t e x t ---
647 // Use the empty function as closure (no scope info).
648 global_context()->set_closure(*empty_function);
649 global_context()->set_fcontext(*global_context());
650 global_context()->set_previous(NULL);
651 // Set extension and global object.
652 global_context()->set_extension(*inner_global);
653 global_context()->set_global(*inner_global);
654 // Security setup: Set the security token of the global object to
655 // its the inner global. This makes the security check between two
656 // different contexts fail by default even in case of global
657 // object reinitialization.
658 global_context()->set_security_token(*inner_global);
659
660 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
661 SetProperty(inner_global, object_name, Top::object_function(), DONT_ENUM);
662
Steve Blocka7e24c12009-10-30 11:49:00 +0000663 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
664
665 // Install global Function object
666 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
667 empty_function, Builtins::Illegal, true); // ECMA native.
668
669 { // --- A r r a y ---
670 Handle<JSFunction> array_function =
671 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
672 Top::initial_object_prototype(), Builtins::ArrayCode,
673 true);
674 array_function->shared()->set_construct_stub(
675 Builtins::builtin(Builtins::ArrayConstructCode));
676 array_function->shared()->DontAdaptArguments();
677
678 // This seems a bit hackish, but we need to make sure Array.length
679 // is 1.
680 array_function->shared()->set_length(1);
681 Handle<DescriptorArray> array_descriptors =
682 Factory::CopyAppendProxyDescriptor(
683 Factory::empty_descriptor_array(),
684 Factory::length_symbol(),
685 Factory::NewProxy(&Accessors::ArrayLength),
686 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
687
688 // Cache the fast JavaScript array map
689 global_context()->set_js_array_map(array_function->initial_map());
690 global_context()->js_array_map()->set_instance_descriptors(
691 *array_descriptors);
692 // array_function is used internally. JS code creating array object should
693 // search for the 'Array' property on the global object and use that one
694 // as the constructor. 'Array' property on a global object can be
695 // overwritten by JS code.
696 global_context()->set_array_function(*array_function);
697 }
698
699 { // --- N u m b e r ---
700 Handle<JSFunction> number_fun =
701 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
702 Top::initial_object_prototype(), Builtins::Illegal,
703 true);
704 global_context()->set_number_function(*number_fun);
705 }
706
707 { // --- B o o l e a n ---
708 Handle<JSFunction> boolean_fun =
709 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
710 Top::initial_object_prototype(), Builtins::Illegal,
711 true);
712 global_context()->set_boolean_function(*boolean_fun);
713 }
714
715 { // --- S t r i n g ---
716 Handle<JSFunction> string_fun =
717 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
718 Top::initial_object_prototype(), Builtins::Illegal,
719 true);
720 global_context()->set_string_function(*string_fun);
721 // Add 'length' property to strings.
722 Handle<DescriptorArray> string_descriptors =
723 Factory::CopyAppendProxyDescriptor(
724 Factory::empty_descriptor_array(),
725 Factory::length_symbol(),
726 Factory::NewProxy(&Accessors::StringLength),
727 static_cast<PropertyAttributes>(DONT_ENUM |
728 DONT_DELETE |
729 READ_ONLY));
730
731 Handle<Map> string_map =
732 Handle<Map>(global_context()->string_function()->initial_map());
733 string_map->set_instance_descriptors(*string_descriptors);
734 }
735
736 { // --- D a t e ---
737 // Builtin functions for Date.prototype.
738 Handle<JSFunction> date_fun =
739 InstallFunction(global, "Date", JS_VALUE_TYPE, JSValue::kSize,
740 Top::initial_object_prototype(), Builtins::Illegal,
741 true);
742
743 global_context()->set_date_function(*date_fun);
744 }
745
746
747 { // -- R e g E x p
748 // Builtin functions for RegExp.prototype.
749 Handle<JSFunction> regexp_fun =
750 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
751 Top::initial_object_prototype(), Builtins::Illegal,
752 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000753 global_context()->set_regexp_function(*regexp_fun);
Steve Block6ded16b2010-05-10 14:33:55 +0100754
755 ASSERT(regexp_fun->has_initial_map());
756 Handle<Map> initial_map(regexp_fun->initial_map());
757
758 ASSERT_EQ(0, initial_map->inobject_properties());
759
760 Handle<DescriptorArray> descriptors = Factory::NewDescriptorArray(5);
761 PropertyAttributes final =
762 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
763 int enum_index = 0;
764 {
765 // ECMA-262, section 15.10.7.1.
766 FieldDescriptor field(Heap::source_symbol(),
767 JSRegExp::kSourceFieldIndex,
768 final,
769 enum_index++);
770 descriptors->Set(0, &field);
771 }
772 {
773 // ECMA-262, section 15.10.7.2.
774 FieldDescriptor field(Heap::global_symbol(),
775 JSRegExp::kGlobalFieldIndex,
776 final,
777 enum_index++);
778 descriptors->Set(1, &field);
779 }
780 {
781 // ECMA-262, section 15.10.7.3.
782 FieldDescriptor field(Heap::ignore_case_symbol(),
783 JSRegExp::kIgnoreCaseFieldIndex,
784 final,
785 enum_index++);
786 descriptors->Set(2, &field);
787 }
788 {
789 // ECMA-262, section 15.10.7.4.
790 FieldDescriptor field(Heap::multiline_symbol(),
791 JSRegExp::kMultilineFieldIndex,
792 final,
793 enum_index++);
794 descriptors->Set(3, &field);
795 }
796 {
797 // ECMA-262, section 15.10.7.5.
798 PropertyAttributes writable =
799 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
800 FieldDescriptor field(Heap::last_index_symbol(),
801 JSRegExp::kLastIndexFieldIndex,
802 writable,
803 enum_index++);
804 descriptors->Set(4, &field);
805 }
806 descriptors->SetNextEnumerationIndex(enum_index);
807 descriptors->Sort();
808
809 initial_map->set_inobject_properties(5);
810 initial_map->set_pre_allocated_property_fields(5);
811 initial_map->set_unused_property_fields(0);
812 initial_map->set_instance_size(
813 initial_map->instance_size() + 5 * kPointerSize);
814 initial_map->set_instance_descriptors(*descriptors);
Steve Blocka7e24c12009-10-30 11:49:00 +0000815 }
816
817 { // -- J S O N
818 Handle<String> name = Factory::NewStringFromAscii(CStrVector("JSON"));
819 Handle<JSFunction> cons = Factory::NewFunction(
820 name,
821 Factory::the_hole_value());
822 cons->SetInstancePrototype(global_context()->initial_object_prototype());
823 cons->SetInstanceClassName(*name);
824 Handle<JSObject> json_object = Factory::NewJSObject(cons, TENURED);
825 ASSERT(json_object->IsJSObject());
826 SetProperty(global, name, json_object, DONT_ENUM);
827 global_context()->set_json_object(*json_object);
828 }
829
830 { // --- arguments_boilerplate_
831 // Make sure we can recognize argument objects at runtime.
832 // This is done by introducing an anonymous function with
833 // class_name equals 'Arguments'.
834 Handle<String> symbol = Factory::LookupAsciiSymbol("Arguments");
835 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
836 Handle<JSObject> prototype =
837 Handle<JSObject>(
838 JSObject::cast(global_context()->object_function()->prototype()));
839
840 Handle<JSFunction> function =
841 Factory::NewFunctionWithPrototype(symbol,
842 JS_OBJECT_TYPE,
843 JSObject::kHeaderSize,
844 prototype,
845 code,
846 false);
847 ASSERT(!function->has_initial_map());
848 function->shared()->set_instance_class_name(*symbol);
849 function->shared()->set_expected_nof_properties(2);
850 Handle<JSObject> result = Factory::NewJSObject(function);
851
852 global_context()->set_arguments_boilerplate(*result);
853 // Note: callee must be added as the first property and
854 // length must be added as the second property.
855 SetProperty(result, Factory::callee_symbol(),
856 Factory::undefined_value(),
857 DONT_ENUM);
858 SetProperty(result, Factory::length_symbol(),
859 Factory::undefined_value(),
860 DONT_ENUM);
861
862#ifdef DEBUG
863 LookupResult lookup;
864 result->LocalLookup(Heap::callee_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000865 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000866 ASSERT(lookup.GetFieldIndex() == Heap::arguments_callee_index);
867
868 result->LocalLookup(Heap::length_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000869 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000870 ASSERT(lookup.GetFieldIndex() == Heap::arguments_length_index);
871
872 ASSERT(result->map()->inobject_properties() > Heap::arguments_callee_index);
873 ASSERT(result->map()->inobject_properties() > Heap::arguments_length_index);
874
875 // Check the state of the object.
876 ASSERT(result->HasFastProperties());
877 ASSERT(result->HasFastElements());
878#endif
879 }
880
881 { // --- context extension
882 // Create a function for the context extension objects.
883 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
884 Handle<JSFunction> context_extension_fun =
885 Factory::NewFunction(Factory::empty_symbol(),
886 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
887 JSObject::kHeaderSize,
888 code,
889 true);
890
891 Handle<String> name = Factory::LookupAsciiSymbol("context_extension");
892 context_extension_fun->shared()->set_instance_class_name(*name);
893 global_context()->set_context_extension_function(*context_extension_fun);
894 }
895
896
897 {
898 // Setup the call-as-function delegate.
899 Handle<Code> code =
900 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsFunction));
901 Handle<JSFunction> delegate =
902 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
903 JSObject::kHeaderSize, code, true);
904 global_context()->set_call_as_function_delegate(*delegate);
905 delegate->shared()->DontAdaptArguments();
906 }
907
908 {
909 // Setup the call-as-constructor delegate.
910 Handle<Code> code =
911 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsConstructor));
912 Handle<JSFunction> delegate =
913 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
914 JSObject::kHeaderSize, code, true);
915 global_context()->set_call_as_constructor_delegate(*delegate);
916 delegate->shared()->DontAdaptArguments();
917 }
918
Steve Blocka7e24c12009-10-30 11:49:00 +0000919 // Initialize the out of memory slot.
920 global_context()->set_out_of_memory(Heap::false_value());
921
922 // Initialize the data slot.
923 global_context()->set_data(Heap::undefined_value());
924}
925
926
927bool Genesis::CompileBuiltin(int index) {
928 Vector<const char> name = Natives::GetScriptName(index);
929 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
930 return CompileNative(name, source_code);
931}
932
933
934bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
935 HandleScope scope;
936#ifdef ENABLE_DEBUGGER_SUPPORT
937 Debugger::set_compiling_natives(true);
938#endif
Andrei Popescu31002712010-02-23 13:46:05 +0000939 bool result = CompileScriptCached(name,
940 source,
941 NULL,
942 NULL,
943 Handle<Context>(Top::context()),
944 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000945 ASSERT(Top::has_pending_exception() != result);
946 if (!result) Top::clear_pending_exception();
947#ifdef ENABLE_DEBUGGER_SUPPORT
948 Debugger::set_compiling_natives(false);
949#endif
950 return result;
951}
952
953
954bool Genesis::CompileScriptCached(Vector<const char> name,
955 Handle<String> source,
956 SourceCodeCache* cache,
957 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000958 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000959 bool use_runtime_context) {
960 HandleScope scope;
Steve Block6ded16b2010-05-10 14:33:55 +0100961 Handle<SharedFunctionInfo> function_info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000962
963 // If we can't find the function in the cache, we compile a new
964 // function and insert it into the cache.
Steve Block6ded16b2010-05-10 14:33:55 +0100965 if (cache == NULL || !cache->Lookup(name, &function_info)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000966 ASSERT(source->IsAsciiRepresentation());
967 Handle<String> script_name = Factory::NewStringFromUtf8(name);
Steve Block6ded16b2010-05-10 14:33:55 +0100968 function_info = Compiler::Compile(
Andrei Popescu31002712010-02-23 13:46:05 +0000969 source,
970 script_name,
971 0,
972 0,
973 extension,
974 NULL,
Andrei Popescu402d9372010-02-26 13:31:12 +0000975 Handle<String>::null(),
Andrei Popescu31002712010-02-23 13:46:05 +0000976 use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
Steve Block6ded16b2010-05-10 14:33:55 +0100977 if (function_info.is_null()) return false;
978 if (cache != NULL) cache->Add(name, function_info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 }
980
981 // Setup the function context. Conceptually, we should clone the
982 // function before overwriting the context but since we're in a
983 // single-threaded environment it is not strictly necessary.
Andrei Popescu31002712010-02-23 13:46:05 +0000984 ASSERT(top_context->IsGlobalContext());
Steve Blocka7e24c12009-10-30 11:49:00 +0000985 Handle<Context> context =
986 Handle<Context>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +0000987 ? Handle<Context>(top_context->runtime_context())
988 : top_context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000989 Handle<JSFunction> fun =
Steve Block6ded16b2010-05-10 14:33:55 +0100990 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000991
Leon Clarke4515c472010-02-03 11:58:03 +0000992 // Call function using either the runtime object or the global
Steve Blocka7e24c12009-10-30 11:49:00 +0000993 // object as the receiver. Provide no parameters.
994 Handle<Object> receiver =
995 Handle<Object>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +0000996 ? top_context->builtins()
997 : top_context->global());
Steve Blocka7e24c12009-10-30 11:49:00 +0000998 bool has_pending_exception;
999 Handle<Object> result =
1000 Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1001 if (has_pending_exception) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001002 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001003}
1004
1005
1006#define INSTALL_NATIVE(Type, name, var) \
1007 Handle<String> var##_name = Factory::LookupAsciiSymbol(name); \
1008 global_context()->set_##var(Type::cast(global_context()-> \
1009 builtins()-> \
1010 GetProperty(*var##_name)));
1011
1012void Genesis::InstallNativeFunctions() {
1013 HandleScope scope;
1014 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1015 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1016 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1017 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1018 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1019 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1020 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1021 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
Leon Clarkee46be812010-01-19 14:06:41 +00001022 INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
Steve Blocka7e24c12009-10-30 11:49:00 +00001023 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1024 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1025 configure_instance_fun);
1026 INSTALL_NATIVE(JSFunction, "MakeMessage", make_message_fun);
1027 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1028 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1029}
1030
1031#undef INSTALL_NATIVE
1032
1033
1034bool Genesis::InstallNatives() {
1035 HandleScope scope;
1036
1037 // Create a function for the builtins object. Allocate space for the
1038 // JavaScript builtins, a reference to the builtins object
1039 // (itself) and a reference to the global_context directly in the object.
1040 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
1041 Handle<JSFunction> builtins_fun =
1042 Factory::NewFunction(Factory::empty_symbol(), JS_BUILTINS_OBJECT_TYPE,
1043 JSBuiltinsObject::kSize, code, true);
1044
1045 Handle<String> name = Factory::LookupAsciiSymbol("builtins");
1046 builtins_fun->shared()->set_instance_class_name(*name);
1047
1048 // Allocate the builtins object.
1049 Handle<JSBuiltinsObject> builtins =
1050 Handle<JSBuiltinsObject>::cast(Factory::NewGlobalObject(builtins_fun));
1051 builtins->set_builtins(*builtins);
1052 builtins->set_global_context(*global_context());
1053 builtins->set_global_receiver(*builtins);
1054
1055 // Setup the 'global' properties of the builtins object. The
1056 // 'global' property that refers to the global object is the only
1057 // way to get from code running in the builtins context to the
1058 // global object.
1059 static const PropertyAttributes attributes =
1060 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1061 SetProperty(builtins, Factory::LookupAsciiSymbol("global"),
1062 Handle<Object>(global_context()->global()), attributes);
1063
1064 // Setup the reference from the global object to the builtins object.
1065 JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
1066
1067 // Create a bridge function that has context in the global context.
1068 Handle<JSFunction> bridge =
1069 Factory::NewFunction(Factory::empty_symbol(), Factory::undefined_value());
1070 ASSERT(bridge->context() == *Top::global_context());
1071
1072 // Allocate the builtins context.
1073 Handle<Context> context =
1074 Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1075 context->set_global(*builtins); // override builtins global object
1076
1077 global_context()->set_runtime_context(*context);
1078
1079 { // -- S c r i p t
1080 // Builtin functions for Script.
1081 Handle<JSFunction> script_fun =
1082 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1083 Top::initial_object_prototype(), Builtins::Illegal,
1084 false);
1085 Handle<JSObject> prototype =
1086 Factory::NewJSObject(Top::object_function(), TENURED);
1087 SetPrototype(script_fun, prototype);
1088 global_context()->set_script_function(*script_fun);
1089
1090 // Add 'source' and 'data' property to scripts.
1091 PropertyAttributes common_attributes =
1092 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1093 Handle<Proxy> proxy_source = Factory::NewProxy(&Accessors::ScriptSource);
1094 Handle<DescriptorArray> script_descriptors =
1095 Factory::CopyAppendProxyDescriptor(
1096 Factory::empty_descriptor_array(),
1097 Factory::LookupAsciiSymbol("source"),
1098 proxy_source,
1099 common_attributes);
1100 Handle<Proxy> proxy_name = Factory::NewProxy(&Accessors::ScriptName);
1101 script_descriptors =
1102 Factory::CopyAppendProxyDescriptor(
1103 script_descriptors,
1104 Factory::LookupAsciiSymbol("name"),
1105 proxy_name,
1106 common_attributes);
1107 Handle<Proxy> proxy_id = Factory::NewProxy(&Accessors::ScriptId);
1108 script_descriptors =
1109 Factory::CopyAppendProxyDescriptor(
1110 script_descriptors,
1111 Factory::LookupAsciiSymbol("id"),
1112 proxy_id,
1113 common_attributes);
1114 Handle<Proxy> proxy_line_offset =
1115 Factory::NewProxy(&Accessors::ScriptLineOffset);
1116 script_descriptors =
1117 Factory::CopyAppendProxyDescriptor(
1118 script_descriptors,
1119 Factory::LookupAsciiSymbol("line_offset"),
1120 proxy_line_offset,
1121 common_attributes);
1122 Handle<Proxy> proxy_column_offset =
1123 Factory::NewProxy(&Accessors::ScriptColumnOffset);
1124 script_descriptors =
1125 Factory::CopyAppendProxyDescriptor(
1126 script_descriptors,
1127 Factory::LookupAsciiSymbol("column_offset"),
1128 proxy_column_offset,
1129 common_attributes);
1130 Handle<Proxy> proxy_data = Factory::NewProxy(&Accessors::ScriptData);
1131 script_descriptors =
1132 Factory::CopyAppendProxyDescriptor(
1133 script_descriptors,
1134 Factory::LookupAsciiSymbol("data"),
1135 proxy_data,
1136 common_attributes);
1137 Handle<Proxy> proxy_type = Factory::NewProxy(&Accessors::ScriptType);
1138 script_descriptors =
1139 Factory::CopyAppendProxyDescriptor(
1140 script_descriptors,
1141 Factory::LookupAsciiSymbol("type"),
1142 proxy_type,
1143 common_attributes);
1144 Handle<Proxy> proxy_compilation_type =
1145 Factory::NewProxy(&Accessors::ScriptCompilationType);
1146 script_descriptors =
1147 Factory::CopyAppendProxyDescriptor(
1148 script_descriptors,
1149 Factory::LookupAsciiSymbol("compilation_type"),
1150 proxy_compilation_type,
1151 common_attributes);
1152 Handle<Proxy> proxy_line_ends =
1153 Factory::NewProxy(&Accessors::ScriptLineEnds);
1154 script_descriptors =
1155 Factory::CopyAppendProxyDescriptor(
1156 script_descriptors,
1157 Factory::LookupAsciiSymbol("line_ends"),
1158 proxy_line_ends,
1159 common_attributes);
1160 Handle<Proxy> proxy_context_data =
1161 Factory::NewProxy(&Accessors::ScriptContextData);
1162 script_descriptors =
1163 Factory::CopyAppendProxyDescriptor(
1164 script_descriptors,
1165 Factory::LookupAsciiSymbol("context_data"),
1166 proxy_context_data,
1167 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001168 Handle<Proxy> proxy_eval_from_script =
1169 Factory::NewProxy(&Accessors::ScriptEvalFromScript);
Steve Blocka7e24c12009-10-30 11:49:00 +00001170 script_descriptors =
1171 Factory::CopyAppendProxyDescriptor(
1172 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001173 Factory::LookupAsciiSymbol("eval_from_script"),
1174 proxy_eval_from_script,
Steve Blocka7e24c12009-10-30 11:49:00 +00001175 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001176 Handle<Proxy> proxy_eval_from_script_position =
1177 Factory::NewProxy(&Accessors::ScriptEvalFromScriptPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +00001178 script_descriptors =
1179 Factory::CopyAppendProxyDescriptor(
1180 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001181 Factory::LookupAsciiSymbol("eval_from_script_position"),
1182 proxy_eval_from_script_position,
1183 common_attributes);
1184 Handle<Proxy> proxy_eval_from_function_name =
1185 Factory::NewProxy(&Accessors::ScriptEvalFromFunctionName);
1186 script_descriptors =
1187 Factory::CopyAppendProxyDescriptor(
1188 script_descriptors,
1189 Factory::LookupAsciiSymbol("eval_from_function_name"),
1190 proxy_eval_from_function_name,
Steve Blocka7e24c12009-10-30 11:49:00 +00001191 common_attributes);
1192
1193 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1194 script_map->set_instance_descriptors(*script_descriptors);
1195
1196 // Allocate the empty script.
1197 Handle<Script> script = Factory::NewScript(Factory::empty_string());
1198 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Andrei Popescu31002712010-02-23 13:46:05 +00001199 Heap::public_set_empty_script(*script);
Steve Blocka7e24c12009-10-30 11:49:00 +00001200 }
Steve Block6ded16b2010-05-10 14:33:55 +01001201 {
1202 // Builtin function for OpaqueReference -- a JSValue-based object,
1203 // that keeps its field isolated from JavaScript code. It may store
1204 // objects, that JavaScript code may not access.
1205 Handle<JSFunction> opaque_reference_fun =
1206 InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1207 JSValue::kSize, Top::initial_object_prototype(),
1208 Builtins::Illegal, false);
1209 Handle<JSObject> prototype =
1210 Factory::NewJSObject(Top::object_function(), TENURED);
1211 SetPrototype(opaque_reference_fun, prototype);
1212 global_context()->set_opaque_reference_function(*opaque_reference_fun);
1213 }
1214
1215 if (FLAG_disable_native_files) {
1216 PrintF("Warning: Running without installed natives!\n");
1217 return true;
1218 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001219
Andrei Popescu31002712010-02-23 13:46:05 +00001220 // Install natives.
1221 for (int i = Natives::GetDebuggerCount();
1222 i < Natives::GetBuiltinsCount();
1223 i++) {
1224 Vector<const char> name = Natives::GetScriptName(i);
1225 if (!CompileBuiltin(i)) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001226 // TODO(ager): We really only need to install the JS builtin
1227 // functions on the builtins object after compiling and running
1228 // runtime.js.
1229 if (!InstallJSBuiltins(builtins)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001230 }
1231
1232 InstallNativeFunctions();
1233
Kristian Monsen25f61362010-05-21 11:50:48 +01001234 InstallCustomCallGenerators();
1235
Steve Blocka7e24c12009-10-30 11:49:00 +00001236 // Install Function.prototype.call and apply.
1237 { Handle<String> key = Factory::function_class_symbol();
1238 Handle<JSFunction> function =
1239 Handle<JSFunction>::cast(GetProperty(Top::global(), key));
1240 Handle<JSObject> proto =
1241 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1242
1243 // Install the call and the apply functions.
1244 Handle<JSFunction> call =
1245 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001246 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001247 Builtins::FunctionCall,
1248 false);
1249 Handle<JSFunction> apply =
1250 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001251 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001252 Builtins::FunctionApply,
1253 false);
1254
1255 // Make sure that Function.prototype.call appears to be compiled.
1256 // The code will never be called, but inline caching for call will
1257 // only work if it appears to be compiled.
1258 call->shared()->DontAdaptArguments();
1259 ASSERT(call->is_compiled());
1260
1261 // Set the expected parameters for apply to 2; required by builtin.
1262 apply->shared()->set_formal_parameter_count(2);
1263
1264 // Set the lengths for the functions to satisfy ECMA-262.
1265 call->shared()->set_length(1);
1266 apply->shared()->set_length(2);
1267 }
1268
Steve Block6ded16b2010-05-10 14:33:55 +01001269 // Create a constructor for RegExp results (a variant of Array that
1270 // predefines the two properties index and match).
1271 {
1272 // RegExpResult initial map.
1273
1274 // Find global.Array.prototype to inherit from.
1275 Handle<JSFunction> array_constructor(global_context()->array_function());
1276 Handle<JSObject> array_prototype(
1277 JSObject::cast(array_constructor->instance_prototype()));
1278
1279 // Add initial map.
1280 Handle<Map> initial_map =
1281 Factory::NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1282 initial_map->set_constructor(*array_constructor);
1283
1284 // Set prototype on map.
1285 initial_map->set_non_instance_prototype(false);
1286 initial_map->set_prototype(*array_prototype);
1287
1288 // Update map with length accessor from Array and add "index" and "input".
1289 Handle<Map> array_map(global_context()->js_array_map());
1290 Handle<DescriptorArray> array_descriptors(
1291 array_map->instance_descriptors());
1292 ASSERT_EQ(1, array_descriptors->number_of_descriptors());
1293
1294 Handle<DescriptorArray> reresult_descriptors =
1295 Factory::NewDescriptorArray(3);
1296
1297 reresult_descriptors->CopyFrom(0, *array_descriptors, 0);
1298
1299 int enum_index = 0;
1300 {
1301 FieldDescriptor index_field(Heap::index_symbol(),
1302 JSRegExpResult::kIndexIndex,
1303 NONE,
1304 enum_index++);
1305 reresult_descriptors->Set(1, &index_field);
1306 }
1307
1308 {
1309 FieldDescriptor input_field(Heap::input_symbol(),
1310 JSRegExpResult::kInputIndex,
1311 NONE,
1312 enum_index++);
1313 reresult_descriptors->Set(2, &input_field);
1314 }
1315 reresult_descriptors->Sort();
1316
1317 initial_map->set_inobject_properties(2);
1318 initial_map->set_pre_allocated_property_fields(2);
1319 initial_map->set_unused_property_fields(0);
1320 initial_map->set_instance_descriptors(*reresult_descriptors);
1321
1322 global_context()->set_regexp_result_map(*initial_map);
1323 }
1324
Steve Blocka7e24c12009-10-30 11:49:00 +00001325#ifdef DEBUG
1326 builtins->Verify();
1327#endif
Andrei Popescu31002712010-02-23 13:46:05 +00001328
Steve Blocka7e24c12009-10-30 11:49:00 +00001329 return true;
1330}
1331
1332
Kristian Monsen25f61362010-05-21 11:50:48 +01001333static void InstallCustomCallGenerator(Handle<JSFunction> holder_function,
1334 const char* function_name,
1335 int id) {
1336 Handle<JSObject> proto(JSObject::cast(holder_function->instance_prototype()));
1337 Handle<String> name = Factory::LookupAsciiSymbol(function_name);
1338 Handle<JSFunction> function(JSFunction::cast(proto->GetProperty(*name)));
1339 function->shared()->set_function_data(Smi::FromInt(id));
1340}
1341
1342
1343void Genesis::InstallCustomCallGenerators() {
1344 HandleScope scope;
1345#define INSTALL_CALL_GENERATOR(holder_fun, fun_name, name) \
1346 { \
1347 Handle<JSFunction> holder(global_context()->holder_fun##_function()); \
1348 const int id = CallStubCompiler::k##name##CallGenerator; \
1349 InstallCustomCallGenerator(holder, #fun_name, id); \
1350 }
1351 CUSTOM_CALL_IC_GENERATORS(INSTALL_CALL_GENERATOR)
1352#undef INSTALL_CALL_GENERATOR
1353}
1354
1355
Steve Block6ded16b2010-05-10 14:33:55 +01001356// Do not forget to update macros.py with named constant
1357// of cache id.
1358#define JSFUNCTION_RESULT_CACHE_LIST(F) \
1359 F(16, global_context()->regexp_function())
1360
1361
1362static FixedArray* CreateCache(int size, JSFunction* factory) {
1363 // Caches are supposed to live for a long time, allocate in old space.
1364 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1365 // Cannot use cast as object is not fully initialized yet.
1366 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1367 *Factory::NewFixedArrayWithHoles(array_size, TENURED));
1368 cache->set(JSFunctionResultCache::kFactoryIndex, factory);
1369 cache->MakeZeroSize();
1370 return cache;
1371}
1372
1373
1374void Genesis::InstallJSFunctionResultCaches() {
1375 const int kNumberOfCaches = 0 +
1376#define F(size, func) + 1
1377 JSFUNCTION_RESULT_CACHE_LIST(F)
1378#undef F
1379 ;
1380
1381 Handle<FixedArray> caches = Factory::NewFixedArray(kNumberOfCaches, TENURED);
1382
1383 int index = 0;
1384#define F(size, func) caches->set(index++, CreateCache(size, func));
1385 JSFUNCTION_RESULT_CACHE_LIST(F)
1386#undef F
1387
1388 global_context()->set_jsfunction_result_caches(*caches);
1389}
1390
1391
Andrei Popescu31002712010-02-23 13:46:05 +00001392int BootstrapperActive::nesting_ = 0;
1393
1394
1395bool Bootstrapper::InstallExtensions(Handle<Context> global_context,
1396 v8::ExtensionConfiguration* extensions) {
1397 BootstrapperActive active;
1398 SaveContext saved_context;
1399 Top::set_context(*global_context);
1400 if (!Genesis::InstallExtensions(global_context, extensions)) return false;
1401 Genesis::InstallSpecialObjects(global_context);
1402 return true;
1403}
1404
1405
1406void Genesis::InstallSpecialObjects(Handle<Context> global_context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001407 HandleScope scope;
1408 Handle<JSGlobalObject> js_global(
Andrei Popescu31002712010-02-23 13:46:05 +00001409 JSGlobalObject::cast(global_context->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001410 // Expose the natives in global if a name for it is specified.
1411 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1412 Handle<String> natives_string =
1413 Factory::LookupAsciiSymbol(FLAG_expose_natives_as);
1414 SetProperty(js_global, natives_string,
1415 Handle<JSObject>(js_global->builtins()), DONT_ENUM);
1416 }
1417
1418 Handle<Object> Error = GetProperty(js_global, "Error");
1419 if (Error->IsJSObject()) {
1420 Handle<String> name = Factory::LookupAsciiSymbol("stackTraceLimit");
1421 SetProperty(Handle<JSObject>::cast(Error),
1422 name,
1423 Handle<Smi>(Smi::FromInt(FLAG_stack_trace_limit)),
1424 NONE);
1425 }
1426
1427#ifdef ENABLE_DEBUGGER_SUPPORT
1428 // Expose the debug global object in global if a name for it is specified.
1429 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1430 // If loading fails we just bail out without installing the
1431 // debugger but without tanking the whole context.
Andrei Popescu31002712010-02-23 13:46:05 +00001432 if (!Debug::Load()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001433 // Set the security token for the debugger context to the same as
1434 // the shell global context to allow calling between these (otherwise
1435 // exposing debug global object doesn't make much sense).
1436 Debug::debug_context()->set_security_token(
Andrei Popescu31002712010-02-23 13:46:05 +00001437 global_context->security_token());
Steve Blocka7e24c12009-10-30 11:49:00 +00001438
1439 Handle<String> debug_string =
1440 Factory::LookupAsciiSymbol(FLAG_expose_debug_as);
1441 SetProperty(js_global, debug_string,
1442 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM);
1443 }
1444#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001445}
1446
1447
Andrei Popescu31002712010-02-23 13:46:05 +00001448bool Genesis::InstallExtensions(Handle<Context> global_context,
1449 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001450 // Clear coloring of extension list
1451 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1452 while (current != NULL) {
1453 current->set_state(v8::UNVISITED);
1454 current = current->next();
1455 }
Andrei Popescu31002712010-02-23 13:46:05 +00001456 // Install auto extensions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001457 current = v8::RegisteredExtension::first_extension();
1458 while (current != NULL) {
1459 if (current->extension()->auto_enable())
1460 InstallExtension(current);
1461 current = current->next();
1462 }
1463
1464 if (FLAG_expose_gc) InstallExtension("v8/gc");
1465
1466 if (extensions == NULL) return true;
1467 // Install required extensions
1468 int count = v8::ImplementationUtilities::GetNameCount(extensions);
1469 const char** names = v8::ImplementationUtilities::GetNames(extensions);
1470 for (int i = 0; i < count; i++) {
1471 if (!InstallExtension(names[i]))
1472 return false;
1473 }
1474
1475 return true;
1476}
1477
1478
1479// Installs a named extension. This methods is unoptimized and does
1480// not scale well if we want to support a large number of extensions.
1481bool Genesis::InstallExtension(const char* name) {
1482 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1483 // Loop until we find the relevant extension
1484 while (current != NULL) {
1485 if (strcmp(name, current->extension()->name()) == 0) break;
1486 current = current->next();
1487 }
1488 // Didn't find the extension; fail.
1489 if (current == NULL) {
1490 v8::Utils::ReportApiFailure(
1491 "v8::Context::New()", "Cannot find required extension");
1492 return false;
1493 }
1494 return InstallExtension(current);
1495}
1496
1497
1498bool Genesis::InstallExtension(v8::RegisteredExtension* current) {
1499 HandleScope scope;
1500
1501 if (current->state() == v8::INSTALLED) return true;
1502 // The current node has already been visited so there must be a
1503 // cycle in the dependency graph; fail.
1504 if (current->state() == v8::VISITED) {
1505 v8::Utils::ReportApiFailure(
1506 "v8::Context::New()", "Circular extension dependency");
1507 return false;
1508 }
1509 ASSERT(current->state() == v8::UNVISITED);
1510 current->set_state(v8::VISITED);
1511 v8::Extension* extension = current->extension();
1512 // Install the extension's dependencies
1513 for (int i = 0; i < extension->dependency_count(); i++) {
1514 if (!InstallExtension(extension->dependencies()[i])) return false;
1515 }
1516 Vector<const char> source = CStrVector(extension->source());
1517 Handle<String> source_code = Factory::NewStringFromAscii(source);
1518 bool result = CompileScriptCached(CStrVector(extension->name()),
1519 source_code,
Andrei Popescu31002712010-02-23 13:46:05 +00001520 &extensions_cache,
1521 extension,
1522 Handle<Context>(Top::context()),
Steve Blocka7e24c12009-10-30 11:49:00 +00001523 false);
1524 ASSERT(Top::has_pending_exception() != result);
1525 if (!result) {
1526 Top::clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001527 }
1528 current->set_state(v8::INSTALLED);
1529 return result;
1530}
1531
1532
Andrei Popescu402d9372010-02-26 13:31:12 +00001533bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
1534 HandleScope scope;
1535 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
1536 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
1537 Handle<String> name = Factory::LookupAsciiSymbol(Builtins::GetName(id));
1538 Handle<JSFunction> function
1539 = Handle<JSFunction>(JSFunction::cast(builtins->GetProperty(*name)));
1540 builtins->set_javascript_builtin(id, *function);
1541 Handle<SharedFunctionInfo> shared
1542 = Handle<SharedFunctionInfo>(function->shared());
1543 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Steve Block6ded16b2010-05-10 14:33:55 +01001544 builtins->set_javascript_builtin_code(id, shared->code());
Andrei Popescu402d9372010-02-26 13:31:12 +00001545 }
1546 return true;
Andrei Popescu31002712010-02-23 13:46:05 +00001547}
1548
1549
Steve Blocka7e24c12009-10-30 11:49:00 +00001550bool Genesis::ConfigureGlobalObjects(
1551 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
1552 Handle<JSObject> global_proxy(
1553 JSObject::cast(global_context()->global_proxy()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001554 Handle<JSObject> inner_global(JSObject::cast(global_context()->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001555
1556 if (!global_proxy_template.IsEmpty()) {
1557 // Configure the global proxy object.
1558 Handle<ObjectTemplateInfo> proxy_data =
1559 v8::Utils::OpenHandle(*global_proxy_template);
1560 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
1561
1562 // Configure the inner global object.
1563 Handle<FunctionTemplateInfo> proxy_constructor(
1564 FunctionTemplateInfo::cast(proxy_data->constructor()));
1565 if (!proxy_constructor->prototype_template()->IsUndefined()) {
1566 Handle<ObjectTemplateInfo> inner_data(
1567 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001568 if (!ConfigureApiObject(inner_global, inner_data)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001569 }
1570 }
1571
Andrei Popescu402d9372010-02-26 13:31:12 +00001572 SetObjectPrototype(global_proxy, inner_global);
Steve Blocka7e24c12009-10-30 11:49:00 +00001573 return true;
1574}
1575
1576
1577bool Genesis::ConfigureApiObject(Handle<JSObject> object,
1578 Handle<ObjectTemplateInfo> object_template) {
1579 ASSERT(!object_template.is_null());
1580 ASSERT(object->IsInstanceOf(
1581 FunctionTemplateInfo::cast(object_template->constructor())));
1582
1583 bool pending_exception = false;
1584 Handle<JSObject> obj =
1585 Execution::InstantiateObject(object_template, &pending_exception);
1586 if (pending_exception) {
1587 ASSERT(Top::has_pending_exception());
1588 Top::clear_pending_exception();
1589 return false;
1590 }
1591 TransferObject(obj, object);
1592 return true;
1593}
1594
1595
1596void Genesis::TransferNamedProperties(Handle<JSObject> from,
1597 Handle<JSObject> to) {
1598 if (from->HasFastProperties()) {
1599 Handle<DescriptorArray> descs =
1600 Handle<DescriptorArray>(from->map()->instance_descriptors());
1601 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1602 PropertyDetails details = PropertyDetails(descs->GetDetails(i));
1603 switch (details.type()) {
1604 case FIELD: {
1605 HandleScope inner;
1606 Handle<String> key = Handle<String>(descs->GetKey(i));
1607 int index = descs->GetFieldIndex(i);
1608 Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
1609 SetProperty(to, key, value, details.attributes());
1610 break;
1611 }
1612 case CONSTANT_FUNCTION: {
1613 HandleScope inner;
1614 Handle<String> key = Handle<String>(descs->GetKey(i));
1615 Handle<JSFunction> fun =
1616 Handle<JSFunction>(descs->GetConstantFunction(i));
1617 SetProperty(to, key, fun, details.attributes());
1618 break;
1619 }
1620 case CALLBACKS: {
1621 LookupResult result;
1622 to->LocalLookup(descs->GetKey(i), &result);
1623 // If the property is already there we skip it
Andrei Popescu402d9372010-02-26 13:31:12 +00001624 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001625 HandleScope inner;
Andrei Popescu31002712010-02-23 13:46:05 +00001626 ASSERT(!to->HasFastProperties());
1627 // Add to dictionary.
Steve Blocka7e24c12009-10-30 11:49:00 +00001628 Handle<String> key = Handle<String>(descs->GetKey(i));
Andrei Popescu31002712010-02-23 13:46:05 +00001629 Handle<Object> callbacks(descs->GetCallbacksObject(i));
1630 PropertyDetails d =
1631 PropertyDetails(details.attributes(), CALLBACKS, details.index());
1632 SetNormalizedProperty(to, key, callbacks, d);
Steve Blocka7e24c12009-10-30 11:49:00 +00001633 break;
1634 }
1635 case MAP_TRANSITION:
1636 case CONSTANT_TRANSITION:
1637 case NULL_DESCRIPTOR:
1638 // Ignore non-properties.
1639 break;
1640 case NORMAL:
1641 // Do not occur since the from object has fast properties.
1642 case INTERCEPTOR:
1643 // No element in instance descriptors have interceptor type.
1644 UNREACHABLE();
1645 break;
1646 }
1647 }
1648 } else {
1649 Handle<StringDictionary> properties =
1650 Handle<StringDictionary>(from->property_dictionary());
1651 int capacity = properties->Capacity();
1652 for (int i = 0; i < capacity; i++) {
1653 Object* raw_key(properties->KeyAt(i));
1654 if (properties->IsKey(raw_key)) {
1655 ASSERT(raw_key->IsString());
1656 // If the property is already there we skip it.
1657 LookupResult result;
1658 to->LocalLookup(String::cast(raw_key), &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001659 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001660 // Set the property.
1661 Handle<String> key = Handle<String>(String::cast(raw_key));
1662 Handle<Object> value = Handle<Object>(properties->ValueAt(i));
1663 if (value->IsJSGlobalPropertyCell()) {
1664 value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
1665 }
1666 PropertyDetails details = properties->DetailsAt(i);
1667 SetProperty(to, key, value, details.attributes());
1668 }
1669 }
1670 }
1671}
1672
1673
1674void Genesis::TransferIndexedProperties(Handle<JSObject> from,
1675 Handle<JSObject> to) {
1676 // Cloning the elements array is sufficient.
1677 Handle<FixedArray> from_elements =
1678 Handle<FixedArray>(FixedArray::cast(from->elements()));
1679 Handle<FixedArray> to_elements = Factory::CopyFixedArray(from_elements);
1680 to->set_elements(*to_elements);
1681}
1682
1683
1684void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
1685 HandleScope outer;
1686
1687 ASSERT(!from->IsJSArray());
1688 ASSERT(!to->IsJSArray());
1689
1690 TransferNamedProperties(from, to);
1691 TransferIndexedProperties(from, to);
1692
1693 // Transfer the prototype (new map is needed).
1694 Handle<Map> old_to_map = Handle<Map>(to->map());
1695 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
1696 new_to_map->set_prototype(from->map()->prototype());
1697 to->set_map(*new_to_map);
1698}
1699
1700
1701void Genesis::MakeFunctionInstancePrototypeWritable() {
1702 // Make a new function map so all future functions
1703 // will have settable and enumerable prototype properties.
1704 HandleScope scope;
1705
1706 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +01001707 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001708 Handle<Map> fm = Factory::CopyMapDropDescriptors(Top::function_map());
1709 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +01001710 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001711 Top::context()->global_context()->set_function_map(*fm);
1712}
1713
1714
Steve Blocka7e24c12009-10-30 11:49:00 +00001715Genesis::Genesis(Handle<Object> global_object,
1716 v8::Handle<v8::ObjectTemplate> global_template,
1717 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001718 result_ = Handle<Context>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +00001719 // If V8 isn't running and cannot be initialized, just return.
1720 if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
1721
1722 // Before creating the roots we must save the context and restore it
1723 // on all function exits.
1724 HandleScope scope;
Andrei Popescu31002712010-02-23 13:46:05 +00001725 SaveContext saved_context;
Steve Blocka7e24c12009-10-30 11:49:00 +00001726
Andrei Popescu31002712010-02-23 13:46:05 +00001727 Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
1728 if (!new_context.is_null()) {
1729 global_context_ =
1730 Handle<Context>::cast(GlobalHandles::Create(*new_context));
1731 Top::set_context(*global_context_);
1732 i::Counters::contexts_created_by_snapshot.Increment();
1733 result_ = global_context_;
1734 JSFunction* empty_function =
1735 JSFunction::cast(result_->function_map()->prototype());
1736 empty_function_ = Handle<JSFunction>(empty_function);
Andrei Popescu402d9372010-02-26 13:31:12 +00001737 Handle<GlobalObject> inner_global;
Andrei Popescu31002712010-02-23 13:46:05 +00001738 Handle<JSGlobalProxy> global_proxy =
1739 CreateNewGlobals(global_template,
1740 global_object,
Andrei Popescu402d9372010-02-26 13:31:12 +00001741 &inner_global);
1742
Andrei Popescu31002712010-02-23 13:46:05 +00001743 HookUpGlobalProxy(inner_global, global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +00001744 HookUpInnerGlobal(inner_global);
1745
Andrei Popescu31002712010-02-23 13:46:05 +00001746 if (!ConfigureGlobalObjects(global_template)) return;
1747 } else {
1748 // We get here if there was no context snapshot.
1749 CreateRoots();
1750 Handle<JSFunction> empty_function = CreateEmptyFunction();
1751 Handle<GlobalObject> inner_global;
1752 Handle<JSGlobalProxy> global_proxy =
1753 CreateNewGlobals(global_template, global_object, &inner_global);
1754 HookUpGlobalProxy(inner_global, global_proxy);
1755 InitializeGlobal(inner_global, empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +01001756 InstallJSFunctionResultCaches();
Kristian Monsen25f61362010-05-21 11:50:48 +01001757 if (!InstallNatives()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001758
Andrei Popescu31002712010-02-23 13:46:05 +00001759 MakeFunctionInstancePrototypeWritable();
Steve Blocka7e24c12009-10-30 11:49:00 +00001760
Andrei Popescu31002712010-02-23 13:46:05 +00001761 if (!ConfigureGlobalObjects(global_template)) return;
1762 i::Counters::contexts_created_from_scratch.Increment();
1763 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001764
1765 result_ = global_context_;
1766}
1767
1768
1769// Support for thread preemption.
1770
1771// Reserve space for statics needing saving and restoring.
1772int Bootstrapper::ArchiveSpacePerThread() {
Andrei Popescu31002712010-02-23 13:46:05 +00001773 return BootstrapperActive::ArchiveSpacePerThread();
Steve Blocka7e24c12009-10-30 11:49:00 +00001774}
1775
1776
1777// Archive statics that are thread local.
1778char* Bootstrapper::ArchiveState(char* to) {
Andrei Popescu31002712010-02-23 13:46:05 +00001779 return BootstrapperActive::ArchiveState(to);
Steve Blocka7e24c12009-10-30 11:49:00 +00001780}
1781
1782
1783// Restore statics that are thread local.
1784char* Bootstrapper::RestoreState(char* from) {
Andrei Popescu31002712010-02-23 13:46:05 +00001785 return BootstrapperActive::RestoreState(from);
Steve Blocka7e24c12009-10-30 11:49:00 +00001786}
1787
1788
1789// Called when the top-level V8 mutex is destroyed.
1790void Bootstrapper::FreeThreadResources() {
Andrei Popescu31002712010-02-23 13:46:05 +00001791 ASSERT(!BootstrapperActive::IsActive());
Steve Blocka7e24c12009-10-30 11:49:00 +00001792}
1793
1794
1795// Reserve space for statics needing saving and restoring.
Andrei Popescu31002712010-02-23 13:46:05 +00001796int BootstrapperActive::ArchiveSpacePerThread() {
1797 return sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001798}
1799
1800
1801// Archive statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001802char* BootstrapperActive::ArchiveState(char* to) {
1803 *reinterpret_cast<int*>(to) = nesting_;
1804 nesting_ = 0;
1805 return to + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001806}
1807
1808
1809// Restore statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001810char* BootstrapperActive::RestoreState(char* from) {
1811 nesting_ = *reinterpret_cast<int*>(from);
1812 return from + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001813}
1814
1815} } // namespace v8::internal