blob: 657d0dc3dac7acc3ec7084b22c66aafd583569ba [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) {
Steve Block6ded16b2010-05-10 14:33:55 +010058 v->VisitPointer(BitCast<Object**, FixedArray**>(&cache_));
Steve Blocka7e24c12009-10-30 11:49:00 +000059 }
60
61
Steve Block6ded16b2010-05-10 14:33:55 +010062 bool Lookup(Vector<const char> name, Handle<SharedFunctionInfo>* handle) {
Steve Blocka7e24c12009-10-30 11:49:00 +000063 for (int i = 0; i < cache_->length(); i+=2) {
64 SeqAsciiString* str = SeqAsciiString::cast(cache_->get(i));
65 if (str->IsEqualTo(name)) {
Steve Block6ded16b2010-05-10 14:33:55 +010066 *handle = Handle<SharedFunctionInfo>(
67 SharedFunctionInfo::cast(cache_->get(i + 1)));
Steve Blocka7e24c12009-10-30 11:49:00 +000068 return true;
69 }
70 }
71 return false;
72 }
73
74
Steve Block6ded16b2010-05-10 14:33:55 +010075 void Add(Vector<const char> name, Handle<SharedFunctionInfo> shared) {
Steve Blocka7e24c12009-10-30 11:49:00 +000076 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);
Steve Block6ded16b2010-05-10 14:33:55 +010084 cache_->set(length + 1, *shared);
85 Script::cast(shared->script())->set_type(Smi::FromInt(type_));
Steve Blocka7e24c12009-10-30 11:49:00 +000086 }
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
Steve Blocka7e24c12009-10-30 11:49:00 +0000180class Genesis BASE_EMBEDDED {
181 public:
182 Genesis(Handle<Object> global_object,
183 v8::Handle<v8::ObjectTemplate> global_template,
184 v8::ExtensionConfiguration* extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000185 ~Genesis() { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000186
187 Handle<Context> result() { return result_; }
188
189 Genesis* previous() { return previous_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000190
191 private:
192 Handle<Context> global_context_;
193
194 // There may be more than one active genesis object: When GC is
195 // triggered during environment creation there may be weak handle
196 // processing callbacks which may create new environments.
197 Genesis* previous_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000198
199 Handle<Context> global_context() { return global_context_; }
200
Andrei Popescu31002712010-02-23 13:46:05 +0000201 // Creates some basic objects. Used for creating a context from scratch.
202 void CreateRoots();
203 // Creates the empty function. Used for creating a context from scratch.
204 Handle<JSFunction> CreateEmptyFunction();
205 // Creates the global objects using the global and the template passed in
206 // through the API. We call this regardless of whether we are building a
207 // context from scratch or using a deserialized one from the partial snapshot
208 // but in the latter case we don't use the objects it produces directly, as
209 // we have to used the deserialized ones that are linked together with the
210 // rest of the context snapshot.
211 Handle<JSGlobalProxy> CreateNewGlobals(
212 v8::Handle<v8::ObjectTemplate> global_template,
213 Handle<Object> global_object,
214 Handle<GlobalObject>* global_proxy_out);
215 // Hooks the given global proxy into the context. If the context was created
216 // by deserialization then this will unhook the global proxy that was
217 // deserialized, leaving the GC to pick it up.
218 void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
219 Handle<JSGlobalProxy> global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +0000220 // Similarly, we want to use the inner global that has been created by the
221 // templates passed through the API. The inner global from the snapshot is
222 // detached from the other objects in the snapshot.
223 void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
Andrei Popescu31002712010-02-23 13:46:05 +0000224 // New context initialization. Used for creating a context from scratch.
225 void InitializeGlobal(Handle<GlobalObject> inner_global,
226 Handle<JSFunction> empty_function);
227 // Installs the contents of the native .js files on the global objects.
228 // Used for creating a context from scratch.
Steve Blocka7e24c12009-10-30 11:49:00 +0000229 void InstallNativeFunctions();
230 bool InstallNatives();
Steve Block6ded16b2010-05-10 14:33:55 +0100231 void InstallJSFunctionResultCaches();
Andrei Popescu31002712010-02-23 13:46:05 +0000232 // Used both for deserialized and from-scratch contexts to add the extensions
233 // provided.
234 static bool InstallExtensions(Handle<Context> global_context,
235 v8::ExtensionConfiguration* extensions);
236 static bool InstallExtension(const char* name);
237 static bool InstallExtension(v8::RegisteredExtension* current);
238 static void InstallSpecialObjects(Handle<Context> global_context);
Andrei Popescu402d9372010-02-26 13:31:12 +0000239 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
Steve Blocka7e24c12009-10-30 11:49:00 +0000240 bool ConfigureApiObject(Handle<JSObject> object,
241 Handle<ObjectTemplateInfo> object_template);
242 bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
243
244 // Migrates all properties from the 'from' object to the 'to'
245 // object and overrides the prototype in 'to' with the one from
246 // 'from'.
247 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
248 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
249 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
250
Steve Block6ded16b2010-05-10 14:33:55 +0100251 enum PrototypePropertyMode {
252 DONT_ADD_PROTOTYPE,
253 ADD_READONLY_PROTOTYPE,
254 ADD_WRITEABLE_PROTOTYPE
255 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000256 Handle<DescriptorArray> ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100257 PrototypePropertyMode prototypeMode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000258 void MakeFunctionInstancePrototypeWritable();
259
Steve Blocka7e24c12009-10-30 11:49:00 +0000260 static bool CompileBuiltin(int index);
261 static bool CompileNative(Vector<const char> name, Handle<String> source);
262 static bool CompileScriptCached(Vector<const char> name,
263 Handle<String> source,
264 SourceCodeCache* cache,
265 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000266 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000267 bool use_runtime_context);
268
269 Handle<Context> result_;
Andrei Popescu31002712010-02-23 13:46:05 +0000270 Handle<JSFunction> empty_function_;
271 BootstrapperActive active_;
272 friend class Bootstrapper;
Steve Blocka7e24c12009-10-30 11:49:00 +0000273};
274
Steve Blocka7e24c12009-10-30 11:49:00 +0000275
276void Bootstrapper::Iterate(ObjectVisitor* v) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000277 extensions_cache.Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +0000278 v->Synchronize("Extensions");
Steve Blocka7e24c12009-10-30 11:49:00 +0000279}
280
281
Steve Blocka7e24c12009-10-30 11:49:00 +0000282Handle<Context> Bootstrapper::CreateEnvironment(
283 Handle<Object> global_object,
284 v8::Handle<v8::ObjectTemplate> global_template,
285 v8::ExtensionConfiguration* extensions) {
Andrei Popescu31002712010-02-23 13:46:05 +0000286 HandleScope scope;
287 Handle<Context> env;
Steve Blocka7e24c12009-10-30 11:49:00 +0000288 Genesis genesis(global_object, global_template, extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000289 env = genesis.result();
290 if (!env.is_null()) {
291 if (InstallExtensions(env, extensions)) {
292 return env;
293 }
294 }
295 return Handle<Context>();
Steve Blocka7e24c12009-10-30 11:49:00 +0000296}
297
298
299static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
300 // object.__proto__ = proto;
301 Handle<Map> old_to_map = Handle<Map>(object->map());
302 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
303 new_to_map->set_prototype(*proto);
304 object->set_map(*new_to_map);
305}
306
307
308void Bootstrapper::DetachGlobal(Handle<Context> env) {
309 JSGlobalProxy::cast(env->global_proxy())->set_context(*Factory::null_value());
310 SetObjectPrototype(Handle<JSObject>(env->global_proxy()),
311 Factory::null_value());
312 env->set_global_proxy(env->global());
313 env->global()->set_global_receiver(env->global());
314}
315
316
Andrei Popescu74b3c142010-03-29 12:03:09 +0100317void Bootstrapper::ReattachGlobal(Handle<Context> env,
318 Handle<Object> global_object) {
319 ASSERT(global_object->IsJSGlobalProxy());
320 Handle<JSGlobalProxy> global = Handle<JSGlobalProxy>::cast(global_object);
321 env->global()->set_global_receiver(*global);
322 env->set_global_proxy(*global);
323 SetObjectPrototype(global, Handle<JSObject>(env->global()));
324 global->set_context(*env);
325}
326
327
Steve Blocka7e24c12009-10-30 11:49:00 +0000328static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
329 const char* name,
330 InstanceType type,
331 int instance_size,
332 Handle<JSObject> prototype,
333 Builtins::Name call,
334 bool is_ecma_native) {
335 Handle<String> symbol = Factory::LookupAsciiSymbol(name);
336 Handle<Code> call_code = Handle<Code>(Builtins::builtin(call));
Steve Block6ded16b2010-05-10 14:33:55 +0100337 Handle<JSFunction> function = prototype.is_null() ?
338 Factory::NewFunctionWithoutPrototype(symbol, call_code) :
Steve Blocka7e24c12009-10-30 11:49:00 +0000339 Factory::NewFunctionWithPrototype(symbol,
340 type,
341 instance_size,
342 prototype,
343 call_code,
344 is_ecma_native);
345 SetProperty(target, symbol, function, DONT_ENUM);
346 if (is_ecma_native) {
347 function->shared()->set_instance_class_name(*symbol);
348 }
349 return function;
350}
351
352
353Handle<DescriptorArray> Genesis::ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100354 PrototypePropertyMode prototypeMode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000355 Handle<DescriptorArray> result = Factory::empty_descriptor_array();
356
Steve Block6ded16b2010-05-10 14:33:55 +0100357 if (prototypeMode != DONT_ADD_PROTOTYPE) {
358 PropertyAttributes attributes = static_cast<PropertyAttributes>(
359 DONT_ENUM |
360 DONT_DELETE |
361 (prototypeMode == ADD_READONLY_PROTOTYPE ? READ_ONLY : 0));
362 result =
363 Factory::CopyAppendProxyDescriptor(
364 result,
365 Factory::prototype_symbol(),
366 Factory::NewProxy(&Accessors::FunctionPrototype),
367 attributes);
368 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000369
Steve Block6ded16b2010-05-10 14:33:55 +0100370 PropertyAttributes attributes =
Steve Blocka7e24c12009-10-30 11:49:00 +0000371 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
372 // Add length.
373 result =
374 Factory::CopyAppendProxyDescriptor(
375 result,
376 Factory::length_symbol(),
377 Factory::NewProxy(&Accessors::FunctionLength),
378 attributes);
379
380 // Add name.
381 result =
382 Factory::CopyAppendProxyDescriptor(
383 result,
384 Factory::name_symbol(),
385 Factory::NewProxy(&Accessors::FunctionName),
386 attributes);
387
388 // Add arguments.
389 result =
390 Factory::CopyAppendProxyDescriptor(
391 result,
392 Factory::arguments_symbol(),
393 Factory::NewProxy(&Accessors::FunctionArguments),
394 attributes);
395
396 // Add caller.
397 result =
398 Factory::CopyAppendProxyDescriptor(
399 result,
400 Factory::caller_symbol(),
401 Factory::NewProxy(&Accessors::FunctionCaller),
402 attributes);
403
404 return result;
405}
406
407
Andrei Popescu31002712010-02-23 13:46:05 +0000408Handle<JSFunction> Genesis::CreateEmptyFunction() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000409 // Allocate the map for function instances.
410 Handle<Map> fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
411 global_context()->set_function_instance_map(*fm);
412 // Please note that the prototype property for function instances must be
413 // writable.
414 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +0100415 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100417 fm->set_function_with_prototype(true);
418
419 // Functions with this map will not have a 'prototype' property, and
420 // can not be used as constructors.
421 Handle<Map> function_without_prototype_map =
422 Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
423 global_context()->set_function_without_prototype_map(
424 *function_without_prototype_map);
425 Handle<DescriptorArray> function_without_prototype_map_descriptors =
426 ComputeFunctionInstanceDescriptor(DONT_ADD_PROTOTYPE);
427 function_without_prototype_map->set_instance_descriptors(
428 *function_without_prototype_map_descriptors);
429 function_without_prototype_map->set_function_with_prototype(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000430
431 // Allocate the function map first and then patch the prototype later
432 fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
433 global_context()->set_function_map(*fm);
Steve Block6ded16b2010-05-10 14:33:55 +0100434 function_map_descriptors =
435 ComputeFunctionInstanceDescriptor(ADD_READONLY_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000436 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100437 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000438
439 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
440
441 { // --- O b j e c t ---
442 Handle<JSFunction> object_fun =
443 Factory::NewFunction(object_name, Factory::null_value());
444 Handle<Map> object_function_map =
445 Factory::NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
446 object_fun->set_initial_map(*object_function_map);
447 object_function_map->set_constructor(*object_fun);
448
449 global_context()->set_object_function(*object_fun);
450
451 // Allocate a new prototype for the object function.
452 Handle<JSObject> prototype = Factory::NewJSObject(Top::object_function(),
453 TENURED);
454
455 global_context()->set_initial_object_prototype(*prototype);
456 SetPrototype(object_fun, prototype);
457 object_function_map->
458 set_instance_descriptors(Heap::empty_descriptor_array());
459 }
460
461 // Allocate the empty function as the prototype for function ECMAScript
462 // 262 15.3.4.
463 Handle<String> symbol = Factory::LookupAsciiSymbol("Empty");
464 Handle<JSFunction> empty_function =
Steve Block6ded16b2010-05-10 14:33:55 +0100465 Factory::NewFunctionWithoutPrototype(symbol);
Steve Blocka7e24c12009-10-30 11:49:00 +0000466
Andrei Popescu31002712010-02-23 13:46:05 +0000467 // --- E m p t y ---
468 Handle<Code> code =
469 Handle<Code>(Builtins::builtin(Builtins::EmptyFunction));
470 empty_function->set_code(*code);
471 Handle<String> source = Factory::NewStringFromAscii(CStrVector("() {}"));
472 Handle<Script> script = Factory::NewScript(source);
473 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
474 empty_function->shared()->set_script(*script);
475 empty_function->shared()->set_start_position(0);
476 empty_function->shared()->set_end_position(source->length());
477 empty_function->shared()->DontAdaptArguments();
478 global_context()->function_map()->set_prototype(*empty_function);
479 global_context()->function_instance_map()->set_prototype(*empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +0100480 global_context()->function_without_prototype_map()->
481 set_prototype(*empty_function);
Steve Blocka7e24c12009-10-30 11:49:00 +0000482
Andrei Popescu31002712010-02-23 13:46:05 +0000483 // Allocate the function map first and then patch the prototype later
Steve Block6ded16b2010-05-10 14:33:55 +0100484 Handle<Map> empty_fm = Factory::CopyMapDropDescriptors(
485 function_without_prototype_map);
486 empty_fm->set_instance_descriptors(
487 *function_without_prototype_map_descriptors);
Andrei Popescu31002712010-02-23 13:46:05 +0000488 empty_fm->set_prototype(global_context()->object_function()->prototype());
489 empty_function->set_map(*empty_fm);
490 return empty_function;
491}
492
493
494void Genesis::CreateRoots() {
495 // Allocate the global context FixedArray first and then patch the
496 // closure and extension object later (we need the empty function
497 // and the global object, but in order to create those, we need the
498 // global context).
499 global_context_ =
500 Handle<Context>::cast(
501 GlobalHandles::Create(*Factory::NewGlobalContext()));
502 Top::set_context(*global_context());
503
504 // Allocate the message listeners object.
505 {
506 v8::NeanderArray listeners;
507 global_context()->set_message_listeners(*listeners.value());
508 }
509}
510
511
512Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
513 v8::Handle<v8::ObjectTemplate> global_template,
514 Handle<Object> global_object,
515 Handle<GlobalObject>* inner_global_out) {
516 // The argument global_template aka data is an ObjectTemplateInfo.
517 // It has a constructor pointer that points at global_constructor which is a
518 // FunctionTemplateInfo.
519 // The global_constructor is used to create or reinitialize the global_proxy.
520 // The global_constructor also has a prototype_template pointer that points at
521 // js_global_template which is an ObjectTemplateInfo.
522 // That in turn has a constructor pointer that points at
523 // js_global_constructor which is a FunctionTemplateInfo.
524 // js_global_constructor is used to make js_global_function
525 // js_global_function is used to make the new inner_global.
526 //
527 // --- G l o b a l ---
528 // Step 1: Create a fresh inner JSGlobalObject.
529 Handle<JSFunction> js_global_function;
530 Handle<ObjectTemplateInfo> js_global_template;
531 if (!global_template.IsEmpty()) {
532 // Get prototype template of the global_template.
533 Handle<ObjectTemplateInfo> data =
534 v8::Utils::OpenHandle(*global_template);
535 Handle<FunctionTemplateInfo> global_constructor =
536 Handle<FunctionTemplateInfo>(
537 FunctionTemplateInfo::cast(data->constructor()));
538 Handle<Object> proto_template(global_constructor->prototype_template());
539 if (!proto_template->IsUndefined()) {
540 js_global_template =
541 Handle<ObjectTemplateInfo>::cast(proto_template);
542 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000543 }
544
Andrei Popescu31002712010-02-23 13:46:05 +0000545 if (js_global_template.is_null()) {
546 Handle<String> name = Handle<String>(Heap::empty_symbol());
547 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
548 js_global_function =
549 Factory::NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
Andrei Popescu402d9372010-02-26 13:31:12 +0000550 JSGlobalObject::kSize, code, true);
Andrei Popescu31002712010-02-23 13:46:05 +0000551 // Change the constructor property of the prototype of the
552 // hidden global function to refer to the Object function.
553 Handle<JSObject> prototype =
554 Handle<JSObject>(
555 JSObject::cast(js_global_function->instance_prototype()));
556 SetProperty(prototype, Factory::constructor_symbol(),
557 Top::object_function(), NONE);
558 } else {
559 Handle<FunctionTemplateInfo> js_global_constructor(
560 FunctionTemplateInfo::cast(js_global_template->constructor()));
561 js_global_function =
562 Factory::CreateApiFunction(js_global_constructor,
563 Factory::InnerGlobalObject);
Steve Blocka7e24c12009-10-30 11:49:00 +0000564 }
565
Andrei Popescu31002712010-02-23 13:46:05 +0000566 js_global_function->initial_map()->set_is_hidden_prototype();
567 Handle<GlobalObject> inner_global =
568 Factory::NewGlobalObject(js_global_function);
569 if (inner_global_out != NULL) {
570 *inner_global_out = inner_global;
571 }
572
573 // Step 2: create or re-initialize the global proxy object.
574 Handle<JSFunction> global_proxy_function;
575 if (global_template.IsEmpty()) {
576 Handle<String> name = Handle<String>(Heap::empty_symbol());
577 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
578 global_proxy_function =
579 Factory::NewFunction(name, JS_GLOBAL_PROXY_TYPE,
580 JSGlobalProxy::kSize, code, true);
581 } else {
582 Handle<ObjectTemplateInfo> data =
583 v8::Utils::OpenHandle(*global_template);
584 Handle<FunctionTemplateInfo> global_constructor(
585 FunctionTemplateInfo::cast(data->constructor()));
586 global_proxy_function =
587 Factory::CreateApiFunction(global_constructor,
588 Factory::OuterGlobalObject);
589 }
590
591 Handle<String> global_name = Factory::LookupAsciiSymbol("global");
592 global_proxy_function->shared()->set_instance_class_name(*global_name);
593 global_proxy_function->initial_map()->set_is_access_check_needed(true);
594
595 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
596 // Return the global proxy.
597
598 if (global_object.location() != NULL) {
599 ASSERT(global_object->IsJSGlobalProxy());
600 return ReinitializeJSGlobalProxy(
601 global_proxy_function,
602 Handle<JSGlobalProxy>::cast(global_object));
603 } else {
604 return Handle<JSGlobalProxy>::cast(
605 Factory::NewJSObject(global_proxy_function, TENURED));
606 }
607}
608
609
610void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
611 Handle<JSGlobalProxy> global_proxy) {
612 // Set the global context for the global object.
613 inner_global->set_global_context(*global_context());
614 inner_global->set_global_receiver(*global_proxy);
615 global_proxy->set_context(*global_context());
616 global_context()->set_global_proxy(*global_proxy);
617}
618
619
Andrei Popescu402d9372010-02-26 13:31:12 +0000620void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
621 Handle<GlobalObject> inner_global_from_snapshot(
622 GlobalObject::cast(global_context_->extension()));
623 Handle<JSBuiltinsObject> builtins_global(global_context_->builtins());
624 global_context_->set_extension(*inner_global);
625 global_context_->set_global(*inner_global);
626 global_context_->set_security_token(*inner_global);
627 static const PropertyAttributes attributes =
628 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
629 ForceSetProperty(builtins_global,
630 Factory::LookupAsciiSymbol("global"),
631 inner_global,
632 attributes);
633 // Setup the reference from the global object to the builtins object.
634 JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
635 TransferNamedProperties(inner_global_from_snapshot, inner_global);
636 TransferIndexedProperties(inner_global_from_snapshot, inner_global);
637}
638
639
640// This is only called if we are not using snapshots. The equivalent
641// work in the snapshot case is done in HookUpInnerGlobal.
Andrei Popescu31002712010-02-23 13:46:05 +0000642void Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
643 Handle<JSFunction> empty_function) {
644 // --- G l o b a l C o n t e x t ---
645 // Use the empty function as closure (no scope info).
646 global_context()->set_closure(*empty_function);
647 global_context()->set_fcontext(*global_context());
648 global_context()->set_previous(NULL);
649 // Set extension and global object.
650 global_context()->set_extension(*inner_global);
651 global_context()->set_global(*inner_global);
652 // Security setup: Set the security token of the global object to
653 // its the inner global. This makes the security check between two
654 // different contexts fail by default even in case of global
655 // object reinitialization.
656 global_context()->set_security_token(*inner_global);
657
658 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
659 SetProperty(inner_global, object_name, Top::object_function(), DONT_ENUM);
660
Steve Blocka7e24c12009-10-30 11:49:00 +0000661 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
662
663 // Install global Function object
664 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
665 empty_function, Builtins::Illegal, true); // ECMA native.
666
667 { // --- A r r a y ---
668 Handle<JSFunction> array_function =
669 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
670 Top::initial_object_prototype(), Builtins::ArrayCode,
671 true);
672 array_function->shared()->set_construct_stub(
673 Builtins::builtin(Builtins::ArrayConstructCode));
674 array_function->shared()->DontAdaptArguments();
675
676 // This seems a bit hackish, but we need to make sure Array.length
677 // is 1.
678 array_function->shared()->set_length(1);
679 Handle<DescriptorArray> array_descriptors =
680 Factory::CopyAppendProxyDescriptor(
681 Factory::empty_descriptor_array(),
682 Factory::length_symbol(),
683 Factory::NewProxy(&Accessors::ArrayLength),
684 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
685
686 // Cache the fast JavaScript array map
687 global_context()->set_js_array_map(array_function->initial_map());
688 global_context()->js_array_map()->set_instance_descriptors(
689 *array_descriptors);
690 // array_function is used internally. JS code creating array object should
691 // search for the 'Array' property on the global object and use that one
692 // as the constructor. 'Array' property on a global object can be
693 // overwritten by JS code.
694 global_context()->set_array_function(*array_function);
695 }
696
697 { // --- N u m b e r ---
698 Handle<JSFunction> number_fun =
699 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
700 Top::initial_object_prototype(), Builtins::Illegal,
701 true);
702 global_context()->set_number_function(*number_fun);
703 }
704
705 { // --- B o o l e a n ---
706 Handle<JSFunction> boolean_fun =
707 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
708 Top::initial_object_prototype(), Builtins::Illegal,
709 true);
710 global_context()->set_boolean_function(*boolean_fun);
711 }
712
713 { // --- S t r i n g ---
714 Handle<JSFunction> string_fun =
715 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
716 Top::initial_object_prototype(), Builtins::Illegal,
717 true);
718 global_context()->set_string_function(*string_fun);
719 // Add 'length' property to strings.
720 Handle<DescriptorArray> string_descriptors =
721 Factory::CopyAppendProxyDescriptor(
722 Factory::empty_descriptor_array(),
723 Factory::length_symbol(),
724 Factory::NewProxy(&Accessors::StringLength),
725 static_cast<PropertyAttributes>(DONT_ENUM |
726 DONT_DELETE |
727 READ_ONLY));
728
729 Handle<Map> string_map =
730 Handle<Map>(global_context()->string_function()->initial_map());
731 string_map->set_instance_descriptors(*string_descriptors);
732 }
733
734 { // --- D a t e ---
735 // Builtin functions for Date.prototype.
736 Handle<JSFunction> date_fun =
737 InstallFunction(global, "Date", JS_VALUE_TYPE, JSValue::kSize,
738 Top::initial_object_prototype(), Builtins::Illegal,
739 true);
740
741 global_context()->set_date_function(*date_fun);
742 }
743
744
745 { // -- R e g E x p
746 // Builtin functions for RegExp.prototype.
747 Handle<JSFunction> regexp_fun =
748 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
749 Top::initial_object_prototype(), Builtins::Illegal,
750 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000751 global_context()->set_regexp_function(*regexp_fun);
Steve Block6ded16b2010-05-10 14:33:55 +0100752
753 ASSERT(regexp_fun->has_initial_map());
754 Handle<Map> initial_map(regexp_fun->initial_map());
755
756 ASSERT_EQ(0, initial_map->inobject_properties());
757
758 Handle<DescriptorArray> descriptors = Factory::NewDescriptorArray(5);
759 PropertyAttributes final =
760 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
761 int enum_index = 0;
762 {
763 // ECMA-262, section 15.10.7.1.
764 FieldDescriptor field(Heap::source_symbol(),
765 JSRegExp::kSourceFieldIndex,
766 final,
767 enum_index++);
768 descriptors->Set(0, &field);
769 }
770 {
771 // ECMA-262, section 15.10.7.2.
772 FieldDescriptor field(Heap::global_symbol(),
773 JSRegExp::kGlobalFieldIndex,
774 final,
775 enum_index++);
776 descriptors->Set(1, &field);
777 }
778 {
779 // ECMA-262, section 15.10.7.3.
780 FieldDescriptor field(Heap::ignore_case_symbol(),
781 JSRegExp::kIgnoreCaseFieldIndex,
782 final,
783 enum_index++);
784 descriptors->Set(2, &field);
785 }
786 {
787 // ECMA-262, section 15.10.7.4.
788 FieldDescriptor field(Heap::multiline_symbol(),
789 JSRegExp::kMultilineFieldIndex,
790 final,
791 enum_index++);
792 descriptors->Set(3, &field);
793 }
794 {
795 // ECMA-262, section 15.10.7.5.
796 PropertyAttributes writable =
797 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
798 FieldDescriptor field(Heap::last_index_symbol(),
799 JSRegExp::kLastIndexFieldIndex,
800 writable,
801 enum_index++);
802 descriptors->Set(4, &field);
803 }
804 descriptors->SetNextEnumerationIndex(enum_index);
805 descriptors->Sort();
806
807 initial_map->set_inobject_properties(5);
808 initial_map->set_pre_allocated_property_fields(5);
809 initial_map->set_unused_property_fields(0);
810 initial_map->set_instance_size(
811 initial_map->instance_size() + 5 * kPointerSize);
812 initial_map->set_instance_descriptors(*descriptors);
Steve Blocka7e24c12009-10-30 11:49:00 +0000813 }
814
815 { // -- J S O N
816 Handle<String> name = Factory::NewStringFromAscii(CStrVector("JSON"));
817 Handle<JSFunction> cons = Factory::NewFunction(
818 name,
819 Factory::the_hole_value());
820 cons->SetInstancePrototype(global_context()->initial_object_prototype());
821 cons->SetInstanceClassName(*name);
822 Handle<JSObject> json_object = Factory::NewJSObject(cons, TENURED);
823 ASSERT(json_object->IsJSObject());
824 SetProperty(global, name, json_object, DONT_ENUM);
825 global_context()->set_json_object(*json_object);
826 }
827
828 { // --- arguments_boilerplate_
829 // Make sure we can recognize argument objects at runtime.
830 // This is done by introducing an anonymous function with
831 // class_name equals 'Arguments'.
832 Handle<String> symbol = Factory::LookupAsciiSymbol("Arguments");
833 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
834 Handle<JSObject> prototype =
835 Handle<JSObject>(
836 JSObject::cast(global_context()->object_function()->prototype()));
837
838 Handle<JSFunction> function =
839 Factory::NewFunctionWithPrototype(symbol,
840 JS_OBJECT_TYPE,
841 JSObject::kHeaderSize,
842 prototype,
843 code,
844 false);
845 ASSERT(!function->has_initial_map());
846 function->shared()->set_instance_class_name(*symbol);
847 function->shared()->set_expected_nof_properties(2);
848 Handle<JSObject> result = Factory::NewJSObject(function);
849
850 global_context()->set_arguments_boilerplate(*result);
851 // Note: callee must be added as the first property and
852 // length must be added as the second property.
853 SetProperty(result, Factory::callee_symbol(),
854 Factory::undefined_value(),
855 DONT_ENUM);
856 SetProperty(result, Factory::length_symbol(),
857 Factory::undefined_value(),
858 DONT_ENUM);
859
860#ifdef DEBUG
861 LookupResult lookup;
862 result->LocalLookup(Heap::callee_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000863 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000864 ASSERT(lookup.GetFieldIndex() == Heap::arguments_callee_index);
865
866 result->LocalLookup(Heap::length_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000867 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000868 ASSERT(lookup.GetFieldIndex() == Heap::arguments_length_index);
869
870 ASSERT(result->map()->inobject_properties() > Heap::arguments_callee_index);
871 ASSERT(result->map()->inobject_properties() > Heap::arguments_length_index);
872
873 // Check the state of the object.
874 ASSERT(result->HasFastProperties());
875 ASSERT(result->HasFastElements());
876#endif
877 }
878
879 { // --- context extension
880 // Create a function for the context extension objects.
881 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
882 Handle<JSFunction> context_extension_fun =
883 Factory::NewFunction(Factory::empty_symbol(),
884 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
885 JSObject::kHeaderSize,
886 code,
887 true);
888
889 Handle<String> name = Factory::LookupAsciiSymbol("context_extension");
890 context_extension_fun->shared()->set_instance_class_name(*name);
891 global_context()->set_context_extension_function(*context_extension_fun);
892 }
893
894
895 {
896 // Setup the call-as-function delegate.
897 Handle<Code> code =
898 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsFunction));
899 Handle<JSFunction> delegate =
900 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
901 JSObject::kHeaderSize, code, true);
902 global_context()->set_call_as_function_delegate(*delegate);
903 delegate->shared()->DontAdaptArguments();
904 }
905
906 {
907 // Setup the call-as-constructor delegate.
908 Handle<Code> code =
909 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsConstructor));
910 Handle<JSFunction> delegate =
911 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
912 JSObject::kHeaderSize, code, true);
913 global_context()->set_call_as_constructor_delegate(*delegate);
914 delegate->shared()->DontAdaptArguments();
915 }
916
Steve Blocka7e24c12009-10-30 11:49:00 +0000917 // Initialize the out of memory slot.
918 global_context()->set_out_of_memory(Heap::false_value());
919
920 // Initialize the data slot.
921 global_context()->set_data(Heap::undefined_value());
922}
923
924
925bool Genesis::CompileBuiltin(int index) {
926 Vector<const char> name = Natives::GetScriptName(index);
927 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
928 return CompileNative(name, source_code);
929}
930
931
932bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
933 HandleScope scope;
934#ifdef ENABLE_DEBUGGER_SUPPORT
935 Debugger::set_compiling_natives(true);
936#endif
Andrei Popescu31002712010-02-23 13:46:05 +0000937 bool result = CompileScriptCached(name,
938 source,
939 NULL,
940 NULL,
941 Handle<Context>(Top::context()),
942 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000943 ASSERT(Top::has_pending_exception() != result);
944 if (!result) Top::clear_pending_exception();
945#ifdef ENABLE_DEBUGGER_SUPPORT
946 Debugger::set_compiling_natives(false);
947#endif
948 return result;
949}
950
951
952bool Genesis::CompileScriptCached(Vector<const char> name,
953 Handle<String> source,
954 SourceCodeCache* cache,
955 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000956 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000957 bool use_runtime_context) {
958 HandleScope scope;
Steve Block6ded16b2010-05-10 14:33:55 +0100959 Handle<SharedFunctionInfo> function_info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000960
961 // If we can't find the function in the cache, we compile a new
962 // function and insert it into the cache.
Steve Block6ded16b2010-05-10 14:33:55 +0100963 if (cache == NULL || !cache->Lookup(name, &function_info)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000964 ASSERT(source->IsAsciiRepresentation());
965 Handle<String> script_name = Factory::NewStringFromUtf8(name);
Steve Block6ded16b2010-05-10 14:33:55 +0100966 function_info = Compiler::Compile(
Andrei Popescu31002712010-02-23 13:46:05 +0000967 source,
968 script_name,
969 0,
970 0,
971 extension,
972 NULL,
Andrei Popescu402d9372010-02-26 13:31:12 +0000973 Handle<String>::null(),
Andrei Popescu31002712010-02-23 13:46:05 +0000974 use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
Steve Block6ded16b2010-05-10 14:33:55 +0100975 if (function_info.is_null()) return false;
976 if (cache != NULL) cache->Add(name, function_info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000977 }
978
979 // Setup the function context. Conceptually, we should clone the
980 // function before overwriting the context but since we're in a
981 // single-threaded environment it is not strictly necessary.
Andrei Popescu31002712010-02-23 13:46:05 +0000982 ASSERT(top_context->IsGlobalContext());
Steve Blocka7e24c12009-10-30 11:49:00 +0000983 Handle<Context> context =
984 Handle<Context>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +0000985 ? Handle<Context>(top_context->runtime_context())
986 : top_context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000987 Handle<JSFunction> fun =
Steve Block6ded16b2010-05-10 14:33:55 +0100988 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000989
Leon Clarke4515c472010-02-03 11:58:03 +0000990 // Call function using either the runtime object or the global
Steve Blocka7e24c12009-10-30 11:49:00 +0000991 // object as the receiver. Provide no parameters.
992 Handle<Object> receiver =
993 Handle<Object>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +0000994 ? top_context->builtins()
995 : top_context->global());
Steve Blocka7e24c12009-10-30 11:49:00 +0000996 bool has_pending_exception;
997 Handle<Object> result =
998 Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
999 if (has_pending_exception) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001000 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001001}
1002
1003
1004#define INSTALL_NATIVE(Type, name, var) \
1005 Handle<String> var##_name = Factory::LookupAsciiSymbol(name); \
1006 global_context()->set_##var(Type::cast(global_context()-> \
1007 builtins()-> \
1008 GetProperty(*var##_name)));
1009
1010void Genesis::InstallNativeFunctions() {
1011 HandleScope scope;
1012 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1013 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1014 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1015 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1016 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1017 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1018 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1019 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
Leon Clarkee46be812010-01-19 14:06:41 +00001020 INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
Steve Blocka7e24c12009-10-30 11:49:00 +00001021 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1022 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1023 configure_instance_fun);
1024 INSTALL_NATIVE(JSFunction, "MakeMessage", make_message_fun);
1025 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1026 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1027}
1028
1029#undef INSTALL_NATIVE
1030
1031
1032bool Genesis::InstallNatives() {
1033 HandleScope scope;
1034
1035 // Create a function for the builtins object. Allocate space for the
1036 // JavaScript builtins, a reference to the builtins object
1037 // (itself) and a reference to the global_context directly in the object.
1038 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
1039 Handle<JSFunction> builtins_fun =
1040 Factory::NewFunction(Factory::empty_symbol(), JS_BUILTINS_OBJECT_TYPE,
1041 JSBuiltinsObject::kSize, code, true);
1042
1043 Handle<String> name = Factory::LookupAsciiSymbol("builtins");
1044 builtins_fun->shared()->set_instance_class_name(*name);
1045
1046 // Allocate the builtins object.
1047 Handle<JSBuiltinsObject> builtins =
1048 Handle<JSBuiltinsObject>::cast(Factory::NewGlobalObject(builtins_fun));
1049 builtins->set_builtins(*builtins);
1050 builtins->set_global_context(*global_context());
1051 builtins->set_global_receiver(*builtins);
1052
1053 // Setup the 'global' properties of the builtins object. The
1054 // 'global' property that refers to the global object is the only
1055 // way to get from code running in the builtins context to the
1056 // global object.
1057 static const PropertyAttributes attributes =
1058 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1059 SetProperty(builtins, Factory::LookupAsciiSymbol("global"),
1060 Handle<Object>(global_context()->global()), attributes);
1061
1062 // Setup the reference from the global object to the builtins object.
1063 JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
1064
1065 // Create a bridge function that has context in the global context.
1066 Handle<JSFunction> bridge =
1067 Factory::NewFunction(Factory::empty_symbol(), Factory::undefined_value());
1068 ASSERT(bridge->context() == *Top::global_context());
1069
1070 // Allocate the builtins context.
1071 Handle<Context> context =
1072 Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1073 context->set_global(*builtins); // override builtins global object
1074
1075 global_context()->set_runtime_context(*context);
1076
1077 { // -- S c r i p t
1078 // Builtin functions for Script.
1079 Handle<JSFunction> script_fun =
1080 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1081 Top::initial_object_prototype(), Builtins::Illegal,
1082 false);
1083 Handle<JSObject> prototype =
1084 Factory::NewJSObject(Top::object_function(), TENURED);
1085 SetPrototype(script_fun, prototype);
1086 global_context()->set_script_function(*script_fun);
1087
1088 // Add 'source' and 'data' property to scripts.
1089 PropertyAttributes common_attributes =
1090 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1091 Handle<Proxy> proxy_source = Factory::NewProxy(&Accessors::ScriptSource);
1092 Handle<DescriptorArray> script_descriptors =
1093 Factory::CopyAppendProxyDescriptor(
1094 Factory::empty_descriptor_array(),
1095 Factory::LookupAsciiSymbol("source"),
1096 proxy_source,
1097 common_attributes);
1098 Handle<Proxy> proxy_name = Factory::NewProxy(&Accessors::ScriptName);
1099 script_descriptors =
1100 Factory::CopyAppendProxyDescriptor(
1101 script_descriptors,
1102 Factory::LookupAsciiSymbol("name"),
1103 proxy_name,
1104 common_attributes);
1105 Handle<Proxy> proxy_id = Factory::NewProxy(&Accessors::ScriptId);
1106 script_descriptors =
1107 Factory::CopyAppendProxyDescriptor(
1108 script_descriptors,
1109 Factory::LookupAsciiSymbol("id"),
1110 proxy_id,
1111 common_attributes);
1112 Handle<Proxy> proxy_line_offset =
1113 Factory::NewProxy(&Accessors::ScriptLineOffset);
1114 script_descriptors =
1115 Factory::CopyAppendProxyDescriptor(
1116 script_descriptors,
1117 Factory::LookupAsciiSymbol("line_offset"),
1118 proxy_line_offset,
1119 common_attributes);
1120 Handle<Proxy> proxy_column_offset =
1121 Factory::NewProxy(&Accessors::ScriptColumnOffset);
1122 script_descriptors =
1123 Factory::CopyAppendProxyDescriptor(
1124 script_descriptors,
1125 Factory::LookupAsciiSymbol("column_offset"),
1126 proxy_column_offset,
1127 common_attributes);
1128 Handle<Proxy> proxy_data = Factory::NewProxy(&Accessors::ScriptData);
1129 script_descriptors =
1130 Factory::CopyAppendProxyDescriptor(
1131 script_descriptors,
1132 Factory::LookupAsciiSymbol("data"),
1133 proxy_data,
1134 common_attributes);
1135 Handle<Proxy> proxy_type = Factory::NewProxy(&Accessors::ScriptType);
1136 script_descriptors =
1137 Factory::CopyAppendProxyDescriptor(
1138 script_descriptors,
1139 Factory::LookupAsciiSymbol("type"),
1140 proxy_type,
1141 common_attributes);
1142 Handle<Proxy> proxy_compilation_type =
1143 Factory::NewProxy(&Accessors::ScriptCompilationType);
1144 script_descriptors =
1145 Factory::CopyAppendProxyDescriptor(
1146 script_descriptors,
1147 Factory::LookupAsciiSymbol("compilation_type"),
1148 proxy_compilation_type,
1149 common_attributes);
1150 Handle<Proxy> proxy_line_ends =
1151 Factory::NewProxy(&Accessors::ScriptLineEnds);
1152 script_descriptors =
1153 Factory::CopyAppendProxyDescriptor(
1154 script_descriptors,
1155 Factory::LookupAsciiSymbol("line_ends"),
1156 proxy_line_ends,
1157 common_attributes);
1158 Handle<Proxy> proxy_context_data =
1159 Factory::NewProxy(&Accessors::ScriptContextData);
1160 script_descriptors =
1161 Factory::CopyAppendProxyDescriptor(
1162 script_descriptors,
1163 Factory::LookupAsciiSymbol("context_data"),
1164 proxy_context_data,
1165 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001166 Handle<Proxy> proxy_eval_from_script =
1167 Factory::NewProxy(&Accessors::ScriptEvalFromScript);
Steve Blocka7e24c12009-10-30 11:49:00 +00001168 script_descriptors =
1169 Factory::CopyAppendProxyDescriptor(
1170 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001171 Factory::LookupAsciiSymbol("eval_from_script"),
1172 proxy_eval_from_script,
Steve Blocka7e24c12009-10-30 11:49:00 +00001173 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001174 Handle<Proxy> proxy_eval_from_script_position =
1175 Factory::NewProxy(&Accessors::ScriptEvalFromScriptPosition);
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_position"),
1180 proxy_eval_from_script_position,
1181 common_attributes);
1182 Handle<Proxy> proxy_eval_from_function_name =
1183 Factory::NewProxy(&Accessors::ScriptEvalFromFunctionName);
1184 script_descriptors =
1185 Factory::CopyAppendProxyDescriptor(
1186 script_descriptors,
1187 Factory::LookupAsciiSymbol("eval_from_function_name"),
1188 proxy_eval_from_function_name,
Steve Blocka7e24c12009-10-30 11:49:00 +00001189 common_attributes);
1190
1191 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1192 script_map->set_instance_descriptors(*script_descriptors);
1193
1194 // Allocate the empty script.
1195 Handle<Script> script = Factory::NewScript(Factory::empty_string());
1196 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Andrei Popescu31002712010-02-23 13:46:05 +00001197 Heap::public_set_empty_script(*script);
Steve Blocka7e24c12009-10-30 11:49:00 +00001198 }
Steve Block6ded16b2010-05-10 14:33:55 +01001199 {
1200 // Builtin function for OpaqueReference -- a JSValue-based object,
1201 // that keeps its field isolated from JavaScript code. It may store
1202 // objects, that JavaScript code may not access.
1203 Handle<JSFunction> opaque_reference_fun =
1204 InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1205 JSValue::kSize, Top::initial_object_prototype(),
1206 Builtins::Illegal, false);
1207 Handle<JSObject> prototype =
1208 Factory::NewJSObject(Top::object_function(), TENURED);
1209 SetPrototype(opaque_reference_fun, prototype);
1210 global_context()->set_opaque_reference_function(*opaque_reference_fun);
1211 }
1212
1213 if (FLAG_disable_native_files) {
1214 PrintF("Warning: Running without installed natives!\n");
1215 return true;
1216 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001217
Andrei Popescu31002712010-02-23 13:46:05 +00001218 // Install natives.
1219 for (int i = Natives::GetDebuggerCount();
1220 i < Natives::GetBuiltinsCount();
1221 i++) {
1222 Vector<const char> name = Natives::GetScriptName(i);
1223 if (!CompileBuiltin(i)) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001224 // TODO(ager): We really only need to install the JS builtin
1225 // functions on the builtins object after compiling and running
1226 // runtime.js.
1227 if (!InstallJSBuiltins(builtins)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001228 }
1229
1230 InstallNativeFunctions();
1231
1232 // Install Function.prototype.call and apply.
1233 { Handle<String> key = Factory::function_class_symbol();
1234 Handle<JSFunction> function =
1235 Handle<JSFunction>::cast(GetProperty(Top::global(), key));
1236 Handle<JSObject> proto =
1237 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1238
1239 // Install the call and the apply functions.
1240 Handle<JSFunction> call =
1241 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001242 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001243 Builtins::FunctionCall,
1244 false);
1245 Handle<JSFunction> apply =
1246 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001247 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001248 Builtins::FunctionApply,
1249 false);
1250
1251 // Make sure that Function.prototype.call appears to be compiled.
1252 // The code will never be called, but inline caching for call will
1253 // only work if it appears to be compiled.
1254 call->shared()->DontAdaptArguments();
1255 ASSERT(call->is_compiled());
1256
1257 // Set the expected parameters for apply to 2; required by builtin.
1258 apply->shared()->set_formal_parameter_count(2);
1259
1260 // Set the lengths for the functions to satisfy ECMA-262.
1261 call->shared()->set_length(1);
1262 apply->shared()->set_length(2);
1263 }
1264
Steve Block6ded16b2010-05-10 14:33:55 +01001265 // Create a constructor for RegExp results (a variant of Array that
1266 // predefines the two properties index and match).
1267 {
1268 // RegExpResult initial map.
1269
1270 // Find global.Array.prototype to inherit from.
1271 Handle<JSFunction> array_constructor(global_context()->array_function());
1272 Handle<JSObject> array_prototype(
1273 JSObject::cast(array_constructor->instance_prototype()));
1274
1275 // Add initial map.
1276 Handle<Map> initial_map =
1277 Factory::NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1278 initial_map->set_constructor(*array_constructor);
1279
1280 // Set prototype on map.
1281 initial_map->set_non_instance_prototype(false);
1282 initial_map->set_prototype(*array_prototype);
1283
1284 // Update map with length accessor from Array and add "index" and "input".
1285 Handle<Map> array_map(global_context()->js_array_map());
1286 Handle<DescriptorArray> array_descriptors(
1287 array_map->instance_descriptors());
1288 ASSERT_EQ(1, array_descriptors->number_of_descriptors());
1289
1290 Handle<DescriptorArray> reresult_descriptors =
1291 Factory::NewDescriptorArray(3);
1292
1293 reresult_descriptors->CopyFrom(0, *array_descriptors, 0);
1294
1295 int enum_index = 0;
1296 {
1297 FieldDescriptor index_field(Heap::index_symbol(),
1298 JSRegExpResult::kIndexIndex,
1299 NONE,
1300 enum_index++);
1301 reresult_descriptors->Set(1, &index_field);
1302 }
1303
1304 {
1305 FieldDescriptor input_field(Heap::input_symbol(),
1306 JSRegExpResult::kInputIndex,
1307 NONE,
1308 enum_index++);
1309 reresult_descriptors->Set(2, &input_field);
1310 }
1311 reresult_descriptors->Sort();
1312
1313 initial_map->set_inobject_properties(2);
1314 initial_map->set_pre_allocated_property_fields(2);
1315 initial_map->set_unused_property_fields(0);
1316 initial_map->set_instance_descriptors(*reresult_descriptors);
1317
1318 global_context()->set_regexp_result_map(*initial_map);
1319 }
1320
Steve Blocka7e24c12009-10-30 11:49:00 +00001321#ifdef DEBUG
1322 builtins->Verify();
1323#endif
Andrei Popescu31002712010-02-23 13:46:05 +00001324
Steve Blocka7e24c12009-10-30 11:49:00 +00001325 return true;
1326}
1327
1328
Steve Block6ded16b2010-05-10 14:33:55 +01001329// Do not forget to update macros.py with named constant
1330// of cache id.
1331#define JSFUNCTION_RESULT_CACHE_LIST(F) \
1332 F(16, global_context()->regexp_function())
1333
1334
1335static FixedArray* CreateCache(int size, JSFunction* factory) {
1336 // Caches are supposed to live for a long time, allocate in old space.
1337 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1338 // Cannot use cast as object is not fully initialized yet.
1339 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1340 *Factory::NewFixedArrayWithHoles(array_size, TENURED));
1341 cache->set(JSFunctionResultCache::kFactoryIndex, factory);
1342 cache->MakeZeroSize();
1343 return cache;
1344}
1345
1346
1347void Genesis::InstallJSFunctionResultCaches() {
1348 const int kNumberOfCaches = 0 +
1349#define F(size, func) + 1
1350 JSFUNCTION_RESULT_CACHE_LIST(F)
1351#undef F
1352 ;
1353
1354 Handle<FixedArray> caches = Factory::NewFixedArray(kNumberOfCaches, TENURED);
1355
1356 int index = 0;
1357#define F(size, func) caches->set(index++, CreateCache(size, func));
1358 JSFUNCTION_RESULT_CACHE_LIST(F)
1359#undef F
1360
1361 global_context()->set_jsfunction_result_caches(*caches);
1362}
1363
1364
Andrei Popescu31002712010-02-23 13:46:05 +00001365int BootstrapperActive::nesting_ = 0;
1366
1367
1368bool Bootstrapper::InstallExtensions(Handle<Context> global_context,
1369 v8::ExtensionConfiguration* extensions) {
1370 BootstrapperActive active;
1371 SaveContext saved_context;
1372 Top::set_context(*global_context);
1373 if (!Genesis::InstallExtensions(global_context, extensions)) return false;
1374 Genesis::InstallSpecialObjects(global_context);
1375 return true;
1376}
1377
1378
1379void Genesis::InstallSpecialObjects(Handle<Context> global_context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001380 HandleScope scope;
1381 Handle<JSGlobalObject> js_global(
Andrei Popescu31002712010-02-23 13:46:05 +00001382 JSGlobalObject::cast(global_context->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001383 // Expose the natives in global if a name for it is specified.
1384 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1385 Handle<String> natives_string =
1386 Factory::LookupAsciiSymbol(FLAG_expose_natives_as);
1387 SetProperty(js_global, natives_string,
1388 Handle<JSObject>(js_global->builtins()), DONT_ENUM);
1389 }
1390
1391 Handle<Object> Error = GetProperty(js_global, "Error");
1392 if (Error->IsJSObject()) {
1393 Handle<String> name = Factory::LookupAsciiSymbol("stackTraceLimit");
1394 SetProperty(Handle<JSObject>::cast(Error),
1395 name,
1396 Handle<Smi>(Smi::FromInt(FLAG_stack_trace_limit)),
1397 NONE);
1398 }
1399
1400#ifdef ENABLE_DEBUGGER_SUPPORT
1401 // Expose the debug global object in global if a name for it is specified.
1402 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1403 // If loading fails we just bail out without installing the
1404 // debugger but without tanking the whole context.
Andrei Popescu31002712010-02-23 13:46:05 +00001405 if (!Debug::Load()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001406 // Set the security token for the debugger context to the same as
1407 // the shell global context to allow calling between these (otherwise
1408 // exposing debug global object doesn't make much sense).
1409 Debug::debug_context()->set_security_token(
Andrei Popescu31002712010-02-23 13:46:05 +00001410 global_context->security_token());
Steve Blocka7e24c12009-10-30 11:49:00 +00001411
1412 Handle<String> debug_string =
1413 Factory::LookupAsciiSymbol(FLAG_expose_debug_as);
1414 SetProperty(js_global, debug_string,
1415 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM);
1416 }
1417#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001418}
1419
1420
Andrei Popescu31002712010-02-23 13:46:05 +00001421bool Genesis::InstallExtensions(Handle<Context> global_context,
1422 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001423 // Clear coloring of extension list
1424 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1425 while (current != NULL) {
1426 current->set_state(v8::UNVISITED);
1427 current = current->next();
1428 }
Andrei Popescu31002712010-02-23 13:46:05 +00001429 // Install auto extensions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001430 current = v8::RegisteredExtension::first_extension();
1431 while (current != NULL) {
1432 if (current->extension()->auto_enable())
1433 InstallExtension(current);
1434 current = current->next();
1435 }
1436
1437 if (FLAG_expose_gc) InstallExtension("v8/gc");
1438
1439 if (extensions == NULL) return true;
1440 // Install required extensions
1441 int count = v8::ImplementationUtilities::GetNameCount(extensions);
1442 const char** names = v8::ImplementationUtilities::GetNames(extensions);
1443 for (int i = 0; i < count; i++) {
1444 if (!InstallExtension(names[i]))
1445 return false;
1446 }
1447
1448 return true;
1449}
1450
1451
1452// Installs a named extension. This methods is unoptimized and does
1453// not scale well if we want to support a large number of extensions.
1454bool Genesis::InstallExtension(const char* name) {
1455 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1456 // Loop until we find the relevant extension
1457 while (current != NULL) {
1458 if (strcmp(name, current->extension()->name()) == 0) break;
1459 current = current->next();
1460 }
1461 // Didn't find the extension; fail.
1462 if (current == NULL) {
1463 v8::Utils::ReportApiFailure(
1464 "v8::Context::New()", "Cannot find required extension");
1465 return false;
1466 }
1467 return InstallExtension(current);
1468}
1469
1470
1471bool Genesis::InstallExtension(v8::RegisteredExtension* current) {
1472 HandleScope scope;
1473
1474 if (current->state() == v8::INSTALLED) return true;
1475 // The current node has already been visited so there must be a
1476 // cycle in the dependency graph; fail.
1477 if (current->state() == v8::VISITED) {
1478 v8::Utils::ReportApiFailure(
1479 "v8::Context::New()", "Circular extension dependency");
1480 return false;
1481 }
1482 ASSERT(current->state() == v8::UNVISITED);
1483 current->set_state(v8::VISITED);
1484 v8::Extension* extension = current->extension();
1485 // Install the extension's dependencies
1486 for (int i = 0; i < extension->dependency_count(); i++) {
1487 if (!InstallExtension(extension->dependencies()[i])) return false;
1488 }
1489 Vector<const char> source = CStrVector(extension->source());
1490 Handle<String> source_code = Factory::NewStringFromAscii(source);
1491 bool result = CompileScriptCached(CStrVector(extension->name()),
1492 source_code,
Andrei Popescu31002712010-02-23 13:46:05 +00001493 &extensions_cache,
1494 extension,
1495 Handle<Context>(Top::context()),
Steve Blocka7e24c12009-10-30 11:49:00 +00001496 false);
1497 ASSERT(Top::has_pending_exception() != result);
1498 if (!result) {
1499 Top::clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001500 }
1501 current->set_state(v8::INSTALLED);
1502 return result;
1503}
1504
1505
Andrei Popescu402d9372010-02-26 13:31:12 +00001506bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
1507 HandleScope scope;
1508 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
1509 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
1510 Handle<String> name = Factory::LookupAsciiSymbol(Builtins::GetName(id));
1511 Handle<JSFunction> function
1512 = Handle<JSFunction>(JSFunction::cast(builtins->GetProperty(*name)));
1513 builtins->set_javascript_builtin(id, *function);
1514 Handle<SharedFunctionInfo> shared
1515 = Handle<SharedFunctionInfo>(function->shared());
1516 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Steve Block6ded16b2010-05-10 14:33:55 +01001517 builtins->set_javascript_builtin_code(id, shared->code());
Andrei Popescu402d9372010-02-26 13:31:12 +00001518 }
1519 return true;
Andrei Popescu31002712010-02-23 13:46:05 +00001520}
1521
1522
Steve Blocka7e24c12009-10-30 11:49:00 +00001523bool Genesis::ConfigureGlobalObjects(
1524 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
1525 Handle<JSObject> global_proxy(
1526 JSObject::cast(global_context()->global_proxy()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001527 Handle<JSObject> inner_global(JSObject::cast(global_context()->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001528
1529 if (!global_proxy_template.IsEmpty()) {
1530 // Configure the global proxy object.
1531 Handle<ObjectTemplateInfo> proxy_data =
1532 v8::Utils::OpenHandle(*global_proxy_template);
1533 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
1534
1535 // Configure the inner global object.
1536 Handle<FunctionTemplateInfo> proxy_constructor(
1537 FunctionTemplateInfo::cast(proxy_data->constructor()));
1538 if (!proxy_constructor->prototype_template()->IsUndefined()) {
1539 Handle<ObjectTemplateInfo> inner_data(
1540 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001541 if (!ConfigureApiObject(inner_global, inner_data)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001542 }
1543 }
1544
Andrei Popescu402d9372010-02-26 13:31:12 +00001545 SetObjectPrototype(global_proxy, inner_global);
Steve Blocka7e24c12009-10-30 11:49:00 +00001546 return true;
1547}
1548
1549
1550bool Genesis::ConfigureApiObject(Handle<JSObject> object,
1551 Handle<ObjectTemplateInfo> object_template) {
1552 ASSERT(!object_template.is_null());
1553 ASSERT(object->IsInstanceOf(
1554 FunctionTemplateInfo::cast(object_template->constructor())));
1555
1556 bool pending_exception = false;
1557 Handle<JSObject> obj =
1558 Execution::InstantiateObject(object_template, &pending_exception);
1559 if (pending_exception) {
1560 ASSERT(Top::has_pending_exception());
1561 Top::clear_pending_exception();
1562 return false;
1563 }
1564 TransferObject(obj, object);
1565 return true;
1566}
1567
1568
1569void Genesis::TransferNamedProperties(Handle<JSObject> from,
1570 Handle<JSObject> to) {
1571 if (from->HasFastProperties()) {
1572 Handle<DescriptorArray> descs =
1573 Handle<DescriptorArray>(from->map()->instance_descriptors());
1574 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1575 PropertyDetails details = PropertyDetails(descs->GetDetails(i));
1576 switch (details.type()) {
1577 case FIELD: {
1578 HandleScope inner;
1579 Handle<String> key = Handle<String>(descs->GetKey(i));
1580 int index = descs->GetFieldIndex(i);
1581 Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
1582 SetProperty(to, key, value, details.attributes());
1583 break;
1584 }
1585 case CONSTANT_FUNCTION: {
1586 HandleScope inner;
1587 Handle<String> key = Handle<String>(descs->GetKey(i));
1588 Handle<JSFunction> fun =
1589 Handle<JSFunction>(descs->GetConstantFunction(i));
1590 SetProperty(to, key, fun, details.attributes());
1591 break;
1592 }
1593 case CALLBACKS: {
1594 LookupResult result;
1595 to->LocalLookup(descs->GetKey(i), &result);
1596 // If the property is already there we skip it
Andrei Popescu402d9372010-02-26 13:31:12 +00001597 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001598 HandleScope inner;
Andrei Popescu31002712010-02-23 13:46:05 +00001599 ASSERT(!to->HasFastProperties());
1600 // Add to dictionary.
Steve Blocka7e24c12009-10-30 11:49:00 +00001601 Handle<String> key = Handle<String>(descs->GetKey(i));
Andrei Popescu31002712010-02-23 13:46:05 +00001602 Handle<Object> callbacks(descs->GetCallbacksObject(i));
1603 PropertyDetails d =
1604 PropertyDetails(details.attributes(), CALLBACKS, details.index());
1605 SetNormalizedProperty(to, key, callbacks, d);
Steve Blocka7e24c12009-10-30 11:49:00 +00001606 break;
1607 }
1608 case MAP_TRANSITION:
1609 case CONSTANT_TRANSITION:
1610 case NULL_DESCRIPTOR:
1611 // Ignore non-properties.
1612 break;
1613 case NORMAL:
1614 // Do not occur since the from object has fast properties.
1615 case INTERCEPTOR:
1616 // No element in instance descriptors have interceptor type.
1617 UNREACHABLE();
1618 break;
1619 }
1620 }
1621 } else {
1622 Handle<StringDictionary> properties =
1623 Handle<StringDictionary>(from->property_dictionary());
1624 int capacity = properties->Capacity();
1625 for (int i = 0; i < capacity; i++) {
1626 Object* raw_key(properties->KeyAt(i));
1627 if (properties->IsKey(raw_key)) {
1628 ASSERT(raw_key->IsString());
1629 // If the property is already there we skip it.
1630 LookupResult result;
1631 to->LocalLookup(String::cast(raw_key), &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001632 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001633 // Set the property.
1634 Handle<String> key = Handle<String>(String::cast(raw_key));
1635 Handle<Object> value = Handle<Object>(properties->ValueAt(i));
1636 if (value->IsJSGlobalPropertyCell()) {
1637 value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
1638 }
1639 PropertyDetails details = properties->DetailsAt(i);
1640 SetProperty(to, key, value, details.attributes());
1641 }
1642 }
1643 }
1644}
1645
1646
1647void Genesis::TransferIndexedProperties(Handle<JSObject> from,
1648 Handle<JSObject> to) {
1649 // Cloning the elements array is sufficient.
1650 Handle<FixedArray> from_elements =
1651 Handle<FixedArray>(FixedArray::cast(from->elements()));
1652 Handle<FixedArray> to_elements = Factory::CopyFixedArray(from_elements);
1653 to->set_elements(*to_elements);
1654}
1655
1656
1657void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
1658 HandleScope outer;
1659
1660 ASSERT(!from->IsJSArray());
1661 ASSERT(!to->IsJSArray());
1662
1663 TransferNamedProperties(from, to);
1664 TransferIndexedProperties(from, to);
1665
1666 // Transfer the prototype (new map is needed).
1667 Handle<Map> old_to_map = Handle<Map>(to->map());
1668 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
1669 new_to_map->set_prototype(from->map()->prototype());
1670 to->set_map(*new_to_map);
1671}
1672
1673
1674void Genesis::MakeFunctionInstancePrototypeWritable() {
1675 // Make a new function map so all future functions
1676 // will have settable and enumerable prototype properties.
1677 HandleScope scope;
1678
1679 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +01001680 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001681 Handle<Map> fm = Factory::CopyMapDropDescriptors(Top::function_map());
1682 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +01001683 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001684 Top::context()->global_context()->set_function_map(*fm);
1685}
1686
1687
Steve Blocka7e24c12009-10-30 11:49:00 +00001688Genesis::Genesis(Handle<Object> global_object,
1689 v8::Handle<v8::ObjectTemplate> global_template,
1690 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001691 result_ = Handle<Context>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +00001692 // If V8 isn't running and cannot be initialized, just return.
1693 if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
1694
1695 // Before creating the roots we must save the context and restore it
1696 // on all function exits.
1697 HandleScope scope;
Andrei Popescu31002712010-02-23 13:46:05 +00001698 SaveContext saved_context;
Steve Blocka7e24c12009-10-30 11:49:00 +00001699
Andrei Popescu31002712010-02-23 13:46:05 +00001700 Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
1701 if (!new_context.is_null()) {
1702 global_context_ =
1703 Handle<Context>::cast(GlobalHandles::Create(*new_context));
1704 Top::set_context(*global_context_);
1705 i::Counters::contexts_created_by_snapshot.Increment();
1706 result_ = global_context_;
1707 JSFunction* empty_function =
1708 JSFunction::cast(result_->function_map()->prototype());
1709 empty_function_ = Handle<JSFunction>(empty_function);
Andrei Popescu402d9372010-02-26 13:31:12 +00001710 Handle<GlobalObject> inner_global;
Andrei Popescu31002712010-02-23 13:46:05 +00001711 Handle<JSGlobalProxy> global_proxy =
1712 CreateNewGlobals(global_template,
1713 global_object,
Andrei Popescu402d9372010-02-26 13:31:12 +00001714 &inner_global);
1715
Andrei Popescu31002712010-02-23 13:46:05 +00001716 HookUpGlobalProxy(inner_global, global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +00001717 HookUpInnerGlobal(inner_global);
1718
Andrei Popescu31002712010-02-23 13:46:05 +00001719 if (!ConfigureGlobalObjects(global_template)) return;
1720 } else {
1721 // We get here if there was no context snapshot.
1722 CreateRoots();
1723 Handle<JSFunction> empty_function = CreateEmptyFunction();
1724 Handle<GlobalObject> inner_global;
1725 Handle<JSGlobalProxy> global_proxy =
1726 CreateNewGlobals(global_template, global_object, &inner_global);
1727 HookUpGlobalProxy(inner_global, global_proxy);
1728 InitializeGlobal(inner_global, empty_function);
1729 if (!InstallNatives()) return;
Steve Block6ded16b2010-05-10 14:33:55 +01001730 InstallJSFunctionResultCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +00001731
Andrei Popescu31002712010-02-23 13:46:05 +00001732 MakeFunctionInstancePrototypeWritable();
Steve Blocka7e24c12009-10-30 11:49:00 +00001733
Andrei Popescu31002712010-02-23 13:46:05 +00001734 if (!ConfigureGlobalObjects(global_template)) return;
1735 i::Counters::contexts_created_from_scratch.Increment();
1736 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001737
1738 result_ = global_context_;
1739}
1740
1741
1742// Support for thread preemption.
1743
1744// Reserve space for statics needing saving and restoring.
1745int Bootstrapper::ArchiveSpacePerThread() {
Andrei Popescu31002712010-02-23 13:46:05 +00001746 return BootstrapperActive::ArchiveSpacePerThread();
Steve Blocka7e24c12009-10-30 11:49:00 +00001747}
1748
1749
1750// Archive statics that are thread local.
1751char* Bootstrapper::ArchiveState(char* to) {
Andrei Popescu31002712010-02-23 13:46:05 +00001752 return BootstrapperActive::ArchiveState(to);
Steve Blocka7e24c12009-10-30 11:49:00 +00001753}
1754
1755
1756// Restore statics that are thread local.
1757char* Bootstrapper::RestoreState(char* from) {
Andrei Popescu31002712010-02-23 13:46:05 +00001758 return BootstrapperActive::RestoreState(from);
Steve Blocka7e24c12009-10-30 11:49:00 +00001759}
1760
1761
1762// Called when the top-level V8 mutex is destroyed.
1763void Bootstrapper::FreeThreadResources() {
Andrei Popescu31002712010-02-23 13:46:05 +00001764 ASSERT(!BootstrapperActive::IsActive());
Steve Blocka7e24c12009-10-30 11:49:00 +00001765}
1766
1767
1768// Reserve space for statics needing saving and restoring.
Andrei Popescu31002712010-02-23 13:46:05 +00001769int BootstrapperActive::ArchiveSpacePerThread() {
1770 return sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001771}
1772
1773
1774// Archive statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001775char* BootstrapperActive::ArchiveState(char* to) {
1776 *reinterpret_cast<int*>(to) = nesting_;
1777 nesting_ = 0;
1778 return to + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001779}
1780
1781
1782// Restore statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001783char* BootstrapperActive::RestoreState(char* from) {
1784 nesting_ = *reinterpret_cast<int*>(from);
1785 return from + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001786}
1787
1788} } // namespace v8::internal