blob: cae1a9a288e9ab97250411f255a61e2cae55a411 [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"
Iain Merrick75681382010-08-19 15:07:18 +010039#include "objects-visiting.h"
Steve Blockd0582a62009-12-15 09:54:21 +000040#include "snapshot.h"
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080041#include "extensions/externalize-string-extension.h"
42#include "extensions/gc-extension.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043
44namespace v8 {
45namespace internal {
46
47// A SourceCodeCache uses a FixedArray to store pairs of
48// (AsciiString*, JSFunction*), mapping names of native code files
49// (runtime.js, etc.) to precompiled functions. Instead of mapping
50// names to functions it might make sense to let the JS2C tool
51// generate an index for each native JS file.
52class SourceCodeCache BASE_EMBEDDED {
53 public:
54 explicit SourceCodeCache(Script::Type type): type_(type), cache_(NULL) { }
55
56 void Initialize(bool create_heap_objects) {
57 cache_ = create_heap_objects ? Heap::empty_fixed_array() : NULL;
58 }
59
60 void Iterate(ObjectVisitor* v) {
Iain Merrick75681382010-08-19 15:07:18 +010061 v->VisitPointer(BitCast<Object**>(&cache_));
Steve Blocka7e24c12009-10-30 11:49:00 +000062 }
63
64
Steve Block6ded16b2010-05-10 14:33:55 +010065 bool Lookup(Vector<const char> name, Handle<SharedFunctionInfo>* handle) {
Steve Blocka7e24c12009-10-30 11:49:00 +000066 for (int i = 0; i < cache_->length(); i+=2) {
67 SeqAsciiString* str = SeqAsciiString::cast(cache_->get(i));
68 if (str->IsEqualTo(name)) {
Steve Block6ded16b2010-05-10 14:33:55 +010069 *handle = Handle<SharedFunctionInfo>(
70 SharedFunctionInfo::cast(cache_->get(i + 1)));
Steve Blocka7e24c12009-10-30 11:49:00 +000071 return true;
72 }
73 }
74 return false;
75 }
76
77
Steve Block6ded16b2010-05-10 14:33:55 +010078 void Add(Vector<const char> name, Handle<SharedFunctionInfo> shared) {
Steve Blocka7e24c12009-10-30 11:49:00 +000079 HandleScope scope;
80 int length = cache_->length();
81 Handle<FixedArray> new_array =
82 Factory::NewFixedArray(length + 2, TENURED);
83 cache_->CopyTo(0, *new_array, 0, cache_->length());
84 cache_ = *new_array;
85 Handle<String> str = Factory::NewStringFromAscii(name, TENURED);
86 cache_->set(length, *str);
Steve Block6ded16b2010-05-10 14:33:55 +010087 cache_->set(length + 1, *shared);
88 Script::cast(shared->script())->set_type(Smi::FromInt(type_));
Steve Blocka7e24c12009-10-30 11:49:00 +000089 }
90
91 private:
92 Script::Type type_;
93 FixedArray* cache_;
94 DISALLOW_COPY_AND_ASSIGN(SourceCodeCache);
95};
96
Steve Blocka7e24c12009-10-30 11:49:00 +000097static SourceCodeCache extensions_cache(Script::TYPE_EXTENSION);
Steve Blockd0582a62009-12-15 09:54:21 +000098// This is for delete, not delete[].
99static List<char*>* delete_these_non_arrays_on_tear_down = NULL;
Leon Clarkee46be812010-01-19 14:06:41 +0000100// This is for delete[]
101static List<char*>* delete_these_arrays_on_tear_down = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000102
103
104NativesExternalStringResource::NativesExternalStringResource(const char* source)
105 : data_(source), length_(StrLength(source)) {
106 if (delete_these_non_arrays_on_tear_down == NULL) {
107 delete_these_non_arrays_on_tear_down = new List<char*>(2);
108 }
109 // The resources are small objects and we only make a fixed number of
110 // them, but let's clean them up on exit for neatness.
111 delete_these_non_arrays_on_tear_down->
112 Add(reinterpret_cast<char*>(this));
113}
Steve Blocka7e24c12009-10-30 11:49:00 +0000114
115
116Handle<String> Bootstrapper::NativesSourceLookup(int index) {
117 ASSERT(0 <= index && index < Natives::GetBuiltinsCount());
118 if (Heap::natives_source_cache()->get(index)->IsUndefined()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000119 if (!Snapshot::IsEnabled() || FLAG_new_snapshot) {
120 // We can use external strings for the natives.
121 NativesExternalStringResource* resource =
122 new NativesExternalStringResource(
123 Natives::GetScriptSource(index).start());
124 Handle<String> source_code =
125 Factory::NewExternalStringFromAscii(resource);
126 Heap::natives_source_cache()->set(index, *source_code);
127 } else {
128 // Old snapshot code can't cope with external strings at all.
129 Handle<String> source_code =
130 Factory::NewStringFromAscii(Natives::GetScriptSource(index));
131 Heap::natives_source_cache()->set(index, *source_code);
132 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000133 }
134 Handle<Object> cached_source(Heap::natives_source_cache()->get(index));
135 return Handle<String>::cast(cached_source);
136}
137
138
Steve Blocka7e24c12009-10-30 11:49:00 +0000139void Bootstrapper::Initialize(bool create_heap_objects) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000140 extensions_cache.Initialize(create_heap_objects);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800141 GCExtension::Register();
142 ExternalizeStringExtension::Register();
Steve Blocka7e24c12009-10-30 11:49:00 +0000143}
144
145
Leon Clarkee46be812010-01-19 14:06:41 +0000146char* Bootstrapper::AllocateAutoDeletedArray(int bytes) {
147 char* memory = new char[bytes];
148 if (memory != NULL) {
149 if (delete_these_arrays_on_tear_down == NULL) {
150 delete_these_arrays_on_tear_down = new List<char*>(2);
151 }
152 delete_these_arrays_on_tear_down->Add(memory);
153 }
154 return memory;
155}
156
157
Steve Blocka7e24c12009-10-30 11:49:00 +0000158void Bootstrapper::TearDown() {
Steve Blockd0582a62009-12-15 09:54:21 +0000159 if (delete_these_non_arrays_on_tear_down != NULL) {
160 int len = delete_these_non_arrays_on_tear_down->length();
161 ASSERT(len < 20); // Don't use this mechanism for unbounded allocations.
162 for (int i = 0; i < len; i++) {
163 delete delete_these_non_arrays_on_tear_down->at(i);
Leon Clarkee46be812010-01-19 14:06:41 +0000164 delete_these_non_arrays_on_tear_down->at(i) = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000165 }
166 delete delete_these_non_arrays_on_tear_down;
167 delete_these_non_arrays_on_tear_down = NULL;
168 }
169
Leon Clarkee46be812010-01-19 14:06:41 +0000170 if (delete_these_arrays_on_tear_down != NULL) {
171 int len = delete_these_arrays_on_tear_down->length();
172 ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations.
173 for (int i = 0; i < len; i++) {
174 delete[] delete_these_arrays_on_tear_down->at(i);
175 delete_these_arrays_on_tear_down->at(i) = NULL;
176 }
177 delete delete_these_arrays_on_tear_down;
178 delete_these_arrays_on_tear_down = NULL;
179 }
180
Andrei Popescu31002712010-02-23 13:46:05 +0000181 extensions_cache.Initialize(false); // Yes, symmetrical
Steve Blocka7e24c12009-10-30 11:49:00 +0000182}
183
184
Steve Blocka7e24c12009-10-30 11:49:00 +0000185class Genesis BASE_EMBEDDED {
186 public:
187 Genesis(Handle<Object> global_object,
188 v8::Handle<v8::ObjectTemplate> global_template,
189 v8::ExtensionConfiguration* extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000190 ~Genesis() { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000191
192 Handle<Context> result() { return result_; }
193
194 Genesis* previous() { return previous_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000195
196 private:
197 Handle<Context> global_context_;
198
199 // There may be more than one active genesis object: When GC is
200 // triggered during environment creation there may be weak handle
201 // processing callbacks which may create new environments.
202 Genesis* previous_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000203
204 Handle<Context> global_context() { return global_context_; }
205
Andrei Popescu31002712010-02-23 13:46:05 +0000206 // Creates some basic objects. Used for creating a context from scratch.
207 void CreateRoots();
208 // Creates the empty function. Used for creating a context from scratch.
209 Handle<JSFunction> CreateEmptyFunction();
210 // Creates the global objects using the global and the template passed in
211 // through the API. We call this regardless of whether we are building a
212 // context from scratch or using a deserialized one from the partial snapshot
213 // but in the latter case we don't use the objects it produces directly, as
214 // we have to used the deserialized ones that are linked together with the
215 // rest of the context snapshot.
216 Handle<JSGlobalProxy> CreateNewGlobals(
217 v8::Handle<v8::ObjectTemplate> global_template,
218 Handle<Object> global_object,
219 Handle<GlobalObject>* global_proxy_out);
220 // Hooks the given global proxy into the context. If the context was created
221 // by deserialization then this will unhook the global proxy that was
222 // deserialized, leaving the GC to pick it up.
223 void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
224 Handle<JSGlobalProxy> global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +0000225 // Similarly, we want to use the inner global that has been created by the
226 // templates passed through the API. The inner global from the snapshot is
227 // detached from the other objects in the snapshot.
228 void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
Andrei Popescu31002712010-02-23 13:46:05 +0000229 // New context initialization. Used for creating a context from scratch.
230 void InitializeGlobal(Handle<GlobalObject> inner_global,
231 Handle<JSFunction> empty_function);
232 // Installs the contents of the native .js files on the global objects.
233 // Used for creating a context from scratch.
Steve Blocka7e24c12009-10-30 11:49:00 +0000234 void InstallNativeFunctions();
235 bool InstallNatives();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100236 void InstallBuiltinFunctionIds();
Steve Block6ded16b2010-05-10 14:33:55 +0100237 void InstallJSFunctionResultCaches();
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100238 void InitializeNormalizedMapCaches();
Andrei Popescu31002712010-02-23 13:46:05 +0000239 // Used both for deserialized and from-scratch contexts to add the extensions
240 // provided.
241 static bool InstallExtensions(Handle<Context> global_context,
242 v8::ExtensionConfiguration* extensions);
243 static bool InstallExtension(const char* name);
244 static bool InstallExtension(v8::RegisteredExtension* current);
245 static void InstallSpecialObjects(Handle<Context> global_context);
Andrei Popescu402d9372010-02-26 13:31:12 +0000246 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
Steve Blocka7e24c12009-10-30 11:49:00 +0000247 bool ConfigureApiObject(Handle<JSObject> object,
248 Handle<ObjectTemplateInfo> object_template);
249 bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
250
251 // Migrates all properties from the 'from' object to the 'to'
252 // object and overrides the prototype in 'to' with the one from
253 // 'from'.
254 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
255 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
256 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
257
Steve Block6ded16b2010-05-10 14:33:55 +0100258 enum PrototypePropertyMode {
259 DONT_ADD_PROTOTYPE,
260 ADD_READONLY_PROTOTYPE,
261 ADD_WRITEABLE_PROTOTYPE
262 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000263 Handle<DescriptorArray> ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100264 PrototypePropertyMode prototypeMode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000265 void MakeFunctionInstancePrototypeWritable();
266
Steve Blocka7e24c12009-10-30 11:49:00 +0000267 static bool CompileBuiltin(int index);
268 static bool CompileNative(Vector<const char> name, Handle<String> source);
269 static bool CompileScriptCached(Vector<const char> name,
270 Handle<String> source,
271 SourceCodeCache* cache,
272 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000273 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000274 bool use_runtime_context);
275
276 Handle<Context> result_;
Andrei Popescu31002712010-02-23 13:46:05 +0000277 Handle<JSFunction> empty_function_;
278 BootstrapperActive active_;
279 friend class Bootstrapper;
Steve Blocka7e24c12009-10-30 11:49:00 +0000280};
281
Steve Blocka7e24c12009-10-30 11:49:00 +0000282
283void Bootstrapper::Iterate(ObjectVisitor* v) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000284 extensions_cache.Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +0000285 v->Synchronize("Extensions");
Steve Blocka7e24c12009-10-30 11:49:00 +0000286}
287
288
Steve Blocka7e24c12009-10-30 11:49:00 +0000289Handle<Context> Bootstrapper::CreateEnvironment(
290 Handle<Object> global_object,
291 v8::Handle<v8::ObjectTemplate> global_template,
292 v8::ExtensionConfiguration* extensions) {
Andrei Popescu31002712010-02-23 13:46:05 +0000293 HandleScope scope;
294 Handle<Context> env;
Steve Blocka7e24c12009-10-30 11:49:00 +0000295 Genesis genesis(global_object, global_template, extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000296 env = genesis.result();
297 if (!env.is_null()) {
298 if (InstallExtensions(env, extensions)) {
299 return env;
300 }
301 }
302 return Handle<Context>();
Steve Blocka7e24c12009-10-30 11:49:00 +0000303}
304
305
306static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
307 // object.__proto__ = proto;
308 Handle<Map> old_to_map = Handle<Map>(object->map());
309 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
310 new_to_map->set_prototype(*proto);
311 object->set_map(*new_to_map);
312}
313
314
315void Bootstrapper::DetachGlobal(Handle<Context> env) {
316 JSGlobalProxy::cast(env->global_proxy())->set_context(*Factory::null_value());
317 SetObjectPrototype(Handle<JSObject>(env->global_proxy()),
318 Factory::null_value());
319 env->set_global_proxy(env->global());
320 env->global()->set_global_receiver(env->global());
321}
322
323
Andrei Popescu74b3c142010-03-29 12:03:09 +0100324void Bootstrapper::ReattachGlobal(Handle<Context> env,
325 Handle<Object> global_object) {
326 ASSERT(global_object->IsJSGlobalProxy());
327 Handle<JSGlobalProxy> global = Handle<JSGlobalProxy>::cast(global_object);
328 env->global()->set_global_receiver(*global);
329 env->set_global_proxy(*global);
330 SetObjectPrototype(global, Handle<JSObject>(env->global()));
331 global->set_context(*env);
332}
333
334
Steve Blocka7e24c12009-10-30 11:49:00 +0000335static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
336 const char* name,
337 InstanceType type,
338 int instance_size,
339 Handle<JSObject> prototype,
340 Builtins::Name call,
341 bool is_ecma_native) {
342 Handle<String> symbol = Factory::LookupAsciiSymbol(name);
343 Handle<Code> call_code = Handle<Code>(Builtins::builtin(call));
Steve Block6ded16b2010-05-10 14:33:55 +0100344 Handle<JSFunction> function = prototype.is_null() ?
345 Factory::NewFunctionWithoutPrototype(symbol, call_code) :
Steve Blocka7e24c12009-10-30 11:49:00 +0000346 Factory::NewFunctionWithPrototype(symbol,
347 type,
348 instance_size,
349 prototype,
350 call_code,
351 is_ecma_native);
352 SetProperty(target, symbol, function, DONT_ENUM);
353 if (is_ecma_native) {
354 function->shared()->set_instance_class_name(*symbol);
355 }
356 return function;
357}
358
359
360Handle<DescriptorArray> Genesis::ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100361 PrototypePropertyMode prototypeMode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000362 Handle<DescriptorArray> result = Factory::empty_descriptor_array();
363
Steve Block6ded16b2010-05-10 14:33:55 +0100364 if (prototypeMode != DONT_ADD_PROTOTYPE) {
365 PropertyAttributes attributes = static_cast<PropertyAttributes>(
366 DONT_ENUM |
367 DONT_DELETE |
368 (prototypeMode == ADD_READONLY_PROTOTYPE ? READ_ONLY : 0));
369 result =
370 Factory::CopyAppendProxyDescriptor(
371 result,
372 Factory::prototype_symbol(),
373 Factory::NewProxy(&Accessors::FunctionPrototype),
374 attributes);
375 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000376
Steve Block6ded16b2010-05-10 14:33:55 +0100377 PropertyAttributes attributes =
Steve Blocka7e24c12009-10-30 11:49:00 +0000378 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
379 // Add length.
380 result =
381 Factory::CopyAppendProxyDescriptor(
382 result,
383 Factory::length_symbol(),
384 Factory::NewProxy(&Accessors::FunctionLength),
385 attributes);
386
387 // Add name.
388 result =
389 Factory::CopyAppendProxyDescriptor(
390 result,
391 Factory::name_symbol(),
392 Factory::NewProxy(&Accessors::FunctionName),
393 attributes);
394
395 // Add arguments.
396 result =
397 Factory::CopyAppendProxyDescriptor(
398 result,
399 Factory::arguments_symbol(),
400 Factory::NewProxy(&Accessors::FunctionArguments),
401 attributes);
402
403 // Add caller.
404 result =
405 Factory::CopyAppendProxyDescriptor(
406 result,
407 Factory::caller_symbol(),
408 Factory::NewProxy(&Accessors::FunctionCaller),
409 attributes);
410
411 return result;
412}
413
414
Andrei Popescu31002712010-02-23 13:46:05 +0000415Handle<JSFunction> Genesis::CreateEmptyFunction() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 // Allocate the map for function instances.
417 Handle<Map> fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
418 global_context()->set_function_instance_map(*fm);
419 // Please note that the prototype property for function instances must be
420 // writable.
421 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +0100422 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000423 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100424 fm->set_function_with_prototype(true);
425
426 // Functions with this map will not have a 'prototype' property, and
427 // can not be used as constructors.
428 Handle<Map> function_without_prototype_map =
429 Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
430 global_context()->set_function_without_prototype_map(
431 *function_without_prototype_map);
432 Handle<DescriptorArray> function_without_prototype_map_descriptors =
433 ComputeFunctionInstanceDescriptor(DONT_ADD_PROTOTYPE);
434 function_without_prototype_map->set_instance_descriptors(
435 *function_without_prototype_map_descriptors);
436 function_without_prototype_map->set_function_with_prototype(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000437
438 // Allocate the function map first and then patch the prototype later
439 fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
440 global_context()->set_function_map(*fm);
Steve Block6ded16b2010-05-10 14:33:55 +0100441 function_map_descriptors =
442 ComputeFunctionInstanceDescriptor(ADD_READONLY_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000443 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100444 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000445
446 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
447
448 { // --- O b j e c t ---
449 Handle<JSFunction> object_fun =
450 Factory::NewFunction(object_name, Factory::null_value());
451 Handle<Map> object_function_map =
452 Factory::NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
453 object_fun->set_initial_map(*object_function_map);
454 object_function_map->set_constructor(*object_fun);
455
456 global_context()->set_object_function(*object_fun);
457
458 // Allocate a new prototype for the object function.
459 Handle<JSObject> prototype = Factory::NewJSObject(Top::object_function(),
460 TENURED);
461
462 global_context()->set_initial_object_prototype(*prototype);
463 SetPrototype(object_fun, prototype);
464 object_function_map->
465 set_instance_descriptors(Heap::empty_descriptor_array());
466 }
467
468 // Allocate the empty function as the prototype for function ECMAScript
469 // 262 15.3.4.
470 Handle<String> symbol = Factory::LookupAsciiSymbol("Empty");
471 Handle<JSFunction> empty_function =
Steve Block6ded16b2010-05-10 14:33:55 +0100472 Factory::NewFunctionWithoutPrototype(symbol);
Steve Blocka7e24c12009-10-30 11:49:00 +0000473
Andrei Popescu31002712010-02-23 13:46:05 +0000474 // --- E m p t y ---
475 Handle<Code> code =
476 Handle<Code>(Builtins::builtin(Builtins::EmptyFunction));
477 empty_function->set_code(*code);
Iain Merrick75681382010-08-19 15:07:18 +0100478 empty_function->shared()->set_code(*code);
Andrei Popescu31002712010-02-23 13:46:05 +0000479 Handle<String> source = Factory::NewStringFromAscii(CStrVector("() {}"));
480 Handle<Script> script = Factory::NewScript(source);
481 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
482 empty_function->shared()->set_script(*script);
483 empty_function->shared()->set_start_position(0);
484 empty_function->shared()->set_end_position(source->length());
485 empty_function->shared()->DontAdaptArguments();
486 global_context()->function_map()->set_prototype(*empty_function);
487 global_context()->function_instance_map()->set_prototype(*empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +0100488 global_context()->function_without_prototype_map()->
489 set_prototype(*empty_function);
Steve Blocka7e24c12009-10-30 11:49:00 +0000490
Andrei Popescu31002712010-02-23 13:46:05 +0000491 // Allocate the function map first and then patch the prototype later
Steve Block6ded16b2010-05-10 14:33:55 +0100492 Handle<Map> empty_fm = Factory::CopyMapDropDescriptors(
493 function_without_prototype_map);
494 empty_fm->set_instance_descriptors(
495 *function_without_prototype_map_descriptors);
Andrei Popescu31002712010-02-23 13:46:05 +0000496 empty_fm->set_prototype(global_context()->object_function()->prototype());
497 empty_function->set_map(*empty_fm);
498 return empty_function;
499}
500
501
Ben Murdochb0fe1622011-05-05 13:52:32 +0100502static void AddToWeakGlobalContextList(Context* context) {
503 ASSERT(context->IsGlobalContext());
504#ifdef DEBUG
505 { // NOLINT
506 ASSERT(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
507 // Check that context is not in the list yet.
508 for (Object* current = Heap::global_contexts_list();
509 !current->IsUndefined();
510 current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
511 ASSERT(current != context);
512 }
513 }
514#endif
515 context->set(Context::NEXT_CONTEXT_LINK, Heap::global_contexts_list());
516 Heap::set_global_contexts_list(context);
517}
518
519
Andrei Popescu31002712010-02-23 13:46:05 +0000520void Genesis::CreateRoots() {
521 // Allocate the global context FixedArray first and then patch the
522 // closure and extension object later (we need the empty function
523 // and the global object, but in order to create those, we need the
524 // global context).
525 global_context_ =
526 Handle<Context>::cast(
527 GlobalHandles::Create(*Factory::NewGlobalContext()));
Ben Murdochb0fe1622011-05-05 13:52:32 +0100528 AddToWeakGlobalContextList(*global_context_);
Andrei Popescu31002712010-02-23 13:46:05 +0000529 Top::set_context(*global_context());
530
531 // Allocate the message listeners object.
532 {
533 v8::NeanderArray listeners;
534 global_context()->set_message_listeners(*listeners.value());
535 }
536}
537
538
539Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
540 v8::Handle<v8::ObjectTemplate> global_template,
541 Handle<Object> global_object,
542 Handle<GlobalObject>* inner_global_out) {
543 // The argument global_template aka data is an ObjectTemplateInfo.
544 // It has a constructor pointer that points at global_constructor which is a
545 // FunctionTemplateInfo.
546 // The global_constructor is used to create or reinitialize the global_proxy.
547 // The global_constructor also has a prototype_template pointer that points at
548 // js_global_template which is an ObjectTemplateInfo.
549 // That in turn has a constructor pointer that points at
550 // js_global_constructor which is a FunctionTemplateInfo.
551 // js_global_constructor is used to make js_global_function
552 // js_global_function is used to make the new inner_global.
553 //
554 // --- G l o b a l ---
555 // Step 1: Create a fresh inner JSGlobalObject.
556 Handle<JSFunction> js_global_function;
557 Handle<ObjectTemplateInfo> js_global_template;
558 if (!global_template.IsEmpty()) {
559 // Get prototype template of the global_template.
560 Handle<ObjectTemplateInfo> data =
561 v8::Utils::OpenHandle(*global_template);
562 Handle<FunctionTemplateInfo> global_constructor =
563 Handle<FunctionTemplateInfo>(
564 FunctionTemplateInfo::cast(data->constructor()));
565 Handle<Object> proto_template(global_constructor->prototype_template());
566 if (!proto_template->IsUndefined()) {
567 js_global_template =
568 Handle<ObjectTemplateInfo>::cast(proto_template);
569 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000570 }
571
Andrei Popescu31002712010-02-23 13:46:05 +0000572 if (js_global_template.is_null()) {
573 Handle<String> name = Handle<String>(Heap::empty_symbol());
574 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
575 js_global_function =
576 Factory::NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
Andrei Popescu402d9372010-02-26 13:31:12 +0000577 JSGlobalObject::kSize, code, true);
Andrei Popescu31002712010-02-23 13:46:05 +0000578 // Change the constructor property of the prototype of the
579 // hidden global function to refer to the Object function.
580 Handle<JSObject> prototype =
581 Handle<JSObject>(
582 JSObject::cast(js_global_function->instance_prototype()));
583 SetProperty(prototype, Factory::constructor_symbol(),
584 Top::object_function(), NONE);
585 } else {
586 Handle<FunctionTemplateInfo> js_global_constructor(
587 FunctionTemplateInfo::cast(js_global_template->constructor()));
588 js_global_function =
589 Factory::CreateApiFunction(js_global_constructor,
590 Factory::InnerGlobalObject);
Steve Blocka7e24c12009-10-30 11:49:00 +0000591 }
592
Andrei Popescu31002712010-02-23 13:46:05 +0000593 js_global_function->initial_map()->set_is_hidden_prototype();
594 Handle<GlobalObject> inner_global =
595 Factory::NewGlobalObject(js_global_function);
596 if (inner_global_out != NULL) {
597 *inner_global_out = inner_global;
598 }
599
600 // Step 2: create or re-initialize the global proxy object.
601 Handle<JSFunction> global_proxy_function;
602 if (global_template.IsEmpty()) {
603 Handle<String> name = Handle<String>(Heap::empty_symbol());
604 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
605 global_proxy_function =
606 Factory::NewFunction(name, JS_GLOBAL_PROXY_TYPE,
607 JSGlobalProxy::kSize, code, true);
608 } else {
609 Handle<ObjectTemplateInfo> data =
610 v8::Utils::OpenHandle(*global_template);
611 Handle<FunctionTemplateInfo> global_constructor(
612 FunctionTemplateInfo::cast(data->constructor()));
613 global_proxy_function =
614 Factory::CreateApiFunction(global_constructor,
615 Factory::OuterGlobalObject);
616 }
617
618 Handle<String> global_name = Factory::LookupAsciiSymbol("global");
619 global_proxy_function->shared()->set_instance_class_name(*global_name);
620 global_proxy_function->initial_map()->set_is_access_check_needed(true);
621
622 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
623 // Return the global proxy.
624
625 if (global_object.location() != NULL) {
626 ASSERT(global_object->IsJSGlobalProxy());
627 return ReinitializeJSGlobalProxy(
628 global_proxy_function,
629 Handle<JSGlobalProxy>::cast(global_object));
630 } else {
631 return Handle<JSGlobalProxy>::cast(
632 Factory::NewJSObject(global_proxy_function, TENURED));
633 }
634}
635
636
637void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
638 Handle<JSGlobalProxy> global_proxy) {
639 // Set the global context for the global object.
640 inner_global->set_global_context(*global_context());
641 inner_global->set_global_receiver(*global_proxy);
642 global_proxy->set_context(*global_context());
643 global_context()->set_global_proxy(*global_proxy);
644}
645
646
Andrei Popescu402d9372010-02-26 13:31:12 +0000647void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
648 Handle<GlobalObject> inner_global_from_snapshot(
649 GlobalObject::cast(global_context_->extension()));
650 Handle<JSBuiltinsObject> builtins_global(global_context_->builtins());
651 global_context_->set_extension(*inner_global);
652 global_context_->set_global(*inner_global);
653 global_context_->set_security_token(*inner_global);
654 static const PropertyAttributes attributes =
655 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
656 ForceSetProperty(builtins_global,
657 Factory::LookupAsciiSymbol("global"),
658 inner_global,
659 attributes);
660 // Setup the reference from the global object to the builtins object.
661 JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
662 TransferNamedProperties(inner_global_from_snapshot, inner_global);
663 TransferIndexedProperties(inner_global_from_snapshot, inner_global);
664}
665
666
667// This is only called if we are not using snapshots. The equivalent
668// work in the snapshot case is done in HookUpInnerGlobal.
Andrei Popescu31002712010-02-23 13:46:05 +0000669void Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
670 Handle<JSFunction> empty_function) {
671 // --- G l o b a l C o n t e x t ---
672 // Use the empty function as closure (no scope info).
673 global_context()->set_closure(*empty_function);
674 global_context()->set_fcontext(*global_context());
675 global_context()->set_previous(NULL);
676 // Set extension and global object.
677 global_context()->set_extension(*inner_global);
678 global_context()->set_global(*inner_global);
679 // Security setup: Set the security token of the global object to
680 // its the inner global. This makes the security check between two
681 // different contexts fail by default even in case of global
682 // object reinitialization.
683 global_context()->set_security_token(*inner_global);
684
685 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
686 SetProperty(inner_global, object_name, Top::object_function(), DONT_ENUM);
687
Steve Blocka7e24c12009-10-30 11:49:00 +0000688 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
689
690 // Install global Function object
691 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
692 empty_function, Builtins::Illegal, true); // ECMA native.
693
694 { // --- A r r a y ---
695 Handle<JSFunction> array_function =
696 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
697 Top::initial_object_prototype(), Builtins::ArrayCode,
698 true);
699 array_function->shared()->set_construct_stub(
700 Builtins::builtin(Builtins::ArrayConstructCode));
701 array_function->shared()->DontAdaptArguments();
702
703 // This seems a bit hackish, but we need to make sure Array.length
704 // is 1.
705 array_function->shared()->set_length(1);
706 Handle<DescriptorArray> array_descriptors =
707 Factory::CopyAppendProxyDescriptor(
708 Factory::empty_descriptor_array(),
709 Factory::length_symbol(),
710 Factory::NewProxy(&Accessors::ArrayLength),
711 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
712
713 // Cache the fast JavaScript array map
714 global_context()->set_js_array_map(array_function->initial_map());
715 global_context()->js_array_map()->set_instance_descriptors(
716 *array_descriptors);
717 // array_function is used internally. JS code creating array object should
718 // search for the 'Array' property on the global object and use that one
719 // as the constructor. 'Array' property on a global object can be
720 // overwritten by JS code.
721 global_context()->set_array_function(*array_function);
722 }
723
724 { // --- N u m b e r ---
725 Handle<JSFunction> number_fun =
726 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
727 Top::initial_object_prototype(), Builtins::Illegal,
728 true);
729 global_context()->set_number_function(*number_fun);
730 }
731
732 { // --- B o o l e a n ---
733 Handle<JSFunction> boolean_fun =
734 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
735 Top::initial_object_prototype(), Builtins::Illegal,
736 true);
737 global_context()->set_boolean_function(*boolean_fun);
738 }
739
740 { // --- S t r i n g ---
741 Handle<JSFunction> string_fun =
742 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
743 Top::initial_object_prototype(), Builtins::Illegal,
744 true);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100745 string_fun->shared()->set_construct_stub(
746 Builtins::builtin(Builtins::StringConstructCode));
Steve Blocka7e24c12009-10-30 11:49:00 +0000747 global_context()->set_string_function(*string_fun);
748 // Add 'length' property to strings.
749 Handle<DescriptorArray> string_descriptors =
750 Factory::CopyAppendProxyDescriptor(
751 Factory::empty_descriptor_array(),
752 Factory::length_symbol(),
753 Factory::NewProxy(&Accessors::StringLength),
754 static_cast<PropertyAttributes>(DONT_ENUM |
755 DONT_DELETE |
756 READ_ONLY));
757
758 Handle<Map> string_map =
759 Handle<Map>(global_context()->string_function()->initial_map());
760 string_map->set_instance_descriptors(*string_descriptors);
761 }
762
763 { // --- D a t e ---
764 // Builtin functions for Date.prototype.
765 Handle<JSFunction> date_fun =
766 InstallFunction(global, "Date", JS_VALUE_TYPE, JSValue::kSize,
767 Top::initial_object_prototype(), Builtins::Illegal,
768 true);
769
770 global_context()->set_date_function(*date_fun);
771 }
772
773
774 { // -- R e g E x p
775 // Builtin functions for RegExp.prototype.
776 Handle<JSFunction> regexp_fun =
777 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
778 Top::initial_object_prototype(), Builtins::Illegal,
779 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000780 global_context()->set_regexp_function(*regexp_fun);
Steve Block6ded16b2010-05-10 14:33:55 +0100781
782 ASSERT(regexp_fun->has_initial_map());
783 Handle<Map> initial_map(regexp_fun->initial_map());
784
785 ASSERT_EQ(0, initial_map->inobject_properties());
786
787 Handle<DescriptorArray> descriptors = Factory::NewDescriptorArray(5);
788 PropertyAttributes final =
789 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
790 int enum_index = 0;
791 {
792 // ECMA-262, section 15.10.7.1.
793 FieldDescriptor field(Heap::source_symbol(),
794 JSRegExp::kSourceFieldIndex,
795 final,
796 enum_index++);
797 descriptors->Set(0, &field);
798 }
799 {
800 // ECMA-262, section 15.10.7.2.
801 FieldDescriptor field(Heap::global_symbol(),
802 JSRegExp::kGlobalFieldIndex,
803 final,
804 enum_index++);
805 descriptors->Set(1, &field);
806 }
807 {
808 // ECMA-262, section 15.10.7.3.
809 FieldDescriptor field(Heap::ignore_case_symbol(),
810 JSRegExp::kIgnoreCaseFieldIndex,
811 final,
812 enum_index++);
813 descriptors->Set(2, &field);
814 }
815 {
816 // ECMA-262, section 15.10.7.4.
817 FieldDescriptor field(Heap::multiline_symbol(),
818 JSRegExp::kMultilineFieldIndex,
819 final,
820 enum_index++);
821 descriptors->Set(3, &field);
822 }
823 {
824 // ECMA-262, section 15.10.7.5.
825 PropertyAttributes writable =
826 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
827 FieldDescriptor field(Heap::last_index_symbol(),
828 JSRegExp::kLastIndexFieldIndex,
829 writable,
830 enum_index++);
831 descriptors->Set(4, &field);
832 }
833 descriptors->SetNextEnumerationIndex(enum_index);
834 descriptors->Sort();
835
836 initial_map->set_inobject_properties(5);
837 initial_map->set_pre_allocated_property_fields(5);
838 initial_map->set_unused_property_fields(0);
839 initial_map->set_instance_size(
840 initial_map->instance_size() + 5 * kPointerSize);
841 initial_map->set_instance_descriptors(*descriptors);
Iain Merrick75681382010-08-19 15:07:18 +0100842 initial_map->set_visitor_id(StaticVisitorBase::GetVisitorId(*initial_map));
Steve Blocka7e24c12009-10-30 11:49:00 +0000843 }
844
845 { // -- J S O N
846 Handle<String> name = Factory::NewStringFromAscii(CStrVector("JSON"));
847 Handle<JSFunction> cons = Factory::NewFunction(
848 name,
849 Factory::the_hole_value());
850 cons->SetInstancePrototype(global_context()->initial_object_prototype());
851 cons->SetInstanceClassName(*name);
852 Handle<JSObject> json_object = Factory::NewJSObject(cons, TENURED);
853 ASSERT(json_object->IsJSObject());
854 SetProperty(global, name, json_object, DONT_ENUM);
855 global_context()->set_json_object(*json_object);
856 }
857
858 { // --- arguments_boilerplate_
859 // Make sure we can recognize argument objects at runtime.
860 // This is done by introducing an anonymous function with
861 // class_name equals 'Arguments'.
862 Handle<String> symbol = Factory::LookupAsciiSymbol("Arguments");
863 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
864 Handle<JSObject> prototype =
865 Handle<JSObject>(
866 JSObject::cast(global_context()->object_function()->prototype()));
867
868 Handle<JSFunction> function =
869 Factory::NewFunctionWithPrototype(symbol,
870 JS_OBJECT_TYPE,
871 JSObject::kHeaderSize,
872 prototype,
873 code,
874 false);
875 ASSERT(!function->has_initial_map());
876 function->shared()->set_instance_class_name(*symbol);
877 function->shared()->set_expected_nof_properties(2);
878 Handle<JSObject> result = Factory::NewJSObject(function);
879
880 global_context()->set_arguments_boilerplate(*result);
881 // Note: callee must be added as the first property and
882 // length must be added as the second property.
883 SetProperty(result, Factory::callee_symbol(),
884 Factory::undefined_value(),
885 DONT_ENUM);
886 SetProperty(result, Factory::length_symbol(),
887 Factory::undefined_value(),
888 DONT_ENUM);
889
890#ifdef DEBUG
891 LookupResult lookup;
892 result->LocalLookup(Heap::callee_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000893 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000894 ASSERT(lookup.GetFieldIndex() == Heap::arguments_callee_index);
895
896 result->LocalLookup(Heap::length_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000897 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000898 ASSERT(lookup.GetFieldIndex() == Heap::arguments_length_index);
899
900 ASSERT(result->map()->inobject_properties() > Heap::arguments_callee_index);
901 ASSERT(result->map()->inobject_properties() > Heap::arguments_length_index);
902
903 // Check the state of the object.
904 ASSERT(result->HasFastProperties());
905 ASSERT(result->HasFastElements());
906#endif
907 }
908
909 { // --- context extension
910 // Create a function for the context extension objects.
911 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
912 Handle<JSFunction> context_extension_fun =
913 Factory::NewFunction(Factory::empty_symbol(),
914 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
915 JSObject::kHeaderSize,
916 code,
917 true);
918
919 Handle<String> name = Factory::LookupAsciiSymbol("context_extension");
920 context_extension_fun->shared()->set_instance_class_name(*name);
921 global_context()->set_context_extension_function(*context_extension_fun);
922 }
923
924
925 {
926 // Setup the call-as-function delegate.
927 Handle<Code> code =
928 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsFunction));
929 Handle<JSFunction> delegate =
930 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
931 JSObject::kHeaderSize, code, true);
932 global_context()->set_call_as_function_delegate(*delegate);
933 delegate->shared()->DontAdaptArguments();
934 }
935
936 {
937 // Setup the call-as-constructor delegate.
938 Handle<Code> code =
939 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsConstructor));
940 Handle<JSFunction> delegate =
941 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
942 JSObject::kHeaderSize, code, true);
943 global_context()->set_call_as_constructor_delegate(*delegate);
944 delegate->shared()->DontAdaptArguments();
945 }
946
Steve Blocka7e24c12009-10-30 11:49:00 +0000947 // Initialize the out of memory slot.
948 global_context()->set_out_of_memory(Heap::false_value());
949
950 // Initialize the data slot.
951 global_context()->set_data(Heap::undefined_value());
952}
953
954
955bool Genesis::CompileBuiltin(int index) {
956 Vector<const char> name = Natives::GetScriptName(index);
957 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
958 return CompileNative(name, source_code);
959}
960
961
962bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
963 HandleScope scope;
964#ifdef ENABLE_DEBUGGER_SUPPORT
965 Debugger::set_compiling_natives(true);
966#endif
Andrei Popescu31002712010-02-23 13:46:05 +0000967 bool result = CompileScriptCached(name,
968 source,
969 NULL,
970 NULL,
971 Handle<Context>(Top::context()),
972 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000973 ASSERT(Top::has_pending_exception() != result);
974 if (!result) Top::clear_pending_exception();
975#ifdef ENABLE_DEBUGGER_SUPPORT
976 Debugger::set_compiling_natives(false);
977#endif
978 return result;
979}
980
981
982bool Genesis::CompileScriptCached(Vector<const char> name,
983 Handle<String> source,
984 SourceCodeCache* cache,
985 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000986 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000987 bool use_runtime_context) {
988 HandleScope scope;
Steve Block6ded16b2010-05-10 14:33:55 +0100989 Handle<SharedFunctionInfo> function_info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000990
991 // If we can't find the function in the cache, we compile a new
992 // function and insert it into the cache.
Steve Block6ded16b2010-05-10 14:33:55 +0100993 if (cache == NULL || !cache->Lookup(name, &function_info)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000994 ASSERT(source->IsAsciiRepresentation());
995 Handle<String> script_name = Factory::NewStringFromUtf8(name);
Steve Block6ded16b2010-05-10 14:33:55 +0100996 function_info = Compiler::Compile(
Andrei Popescu31002712010-02-23 13:46:05 +0000997 source,
998 script_name,
999 0,
1000 0,
1001 extension,
1002 NULL,
Andrei Popescu402d9372010-02-26 13:31:12 +00001003 Handle<String>::null(),
Andrei Popescu31002712010-02-23 13:46:05 +00001004 use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
Steve Block6ded16b2010-05-10 14:33:55 +01001005 if (function_info.is_null()) return false;
1006 if (cache != NULL) cache->Add(name, function_info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001007 }
1008
1009 // Setup the function context. Conceptually, we should clone the
1010 // function before overwriting the context but since we're in a
1011 // single-threaded environment it is not strictly necessary.
Andrei Popescu31002712010-02-23 13:46:05 +00001012 ASSERT(top_context->IsGlobalContext());
Steve Blocka7e24c12009-10-30 11:49:00 +00001013 Handle<Context> context =
1014 Handle<Context>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +00001015 ? Handle<Context>(top_context->runtime_context())
1016 : top_context);
Steve Blocka7e24c12009-10-30 11:49:00 +00001017 Handle<JSFunction> fun =
Steve Block6ded16b2010-05-10 14:33:55 +01001018 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
Steve Blocka7e24c12009-10-30 11:49:00 +00001019
Leon Clarke4515c472010-02-03 11:58:03 +00001020 // Call function using either the runtime object or the global
Steve Blocka7e24c12009-10-30 11:49:00 +00001021 // object as the receiver. Provide no parameters.
1022 Handle<Object> receiver =
1023 Handle<Object>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +00001024 ? top_context->builtins()
1025 : top_context->global());
Steve Blocka7e24c12009-10-30 11:49:00 +00001026 bool has_pending_exception;
1027 Handle<Object> result =
1028 Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1029 if (has_pending_exception) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001030 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001031}
1032
1033
John Reck59135872010-11-02 12:39:01 -07001034#define INSTALL_NATIVE(Type, name, var) \
1035 Handle<String> var##_name = Factory::LookupAsciiSymbol(name); \
1036 global_context()->set_##var(Type::cast( \
1037 global_context()->builtins()->GetPropertyNoExceptionThrown(*var##_name)));
Steve Blocka7e24c12009-10-30 11:49:00 +00001038
1039void Genesis::InstallNativeFunctions() {
1040 HandleScope scope;
1041 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1042 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1043 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1044 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1045 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1046 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1047 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1048 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
Leon Clarkee46be812010-01-19 14:06:41 +00001049 INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
Steve Blocka7e24c12009-10-30 11:49:00 +00001050 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1051 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1052 configure_instance_fun);
1053 INSTALL_NATIVE(JSFunction, "MakeMessage", make_message_fun);
1054 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1055 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1056}
1057
1058#undef INSTALL_NATIVE
1059
1060
1061bool Genesis::InstallNatives() {
1062 HandleScope scope;
1063
1064 // Create a function for the builtins object. Allocate space for the
1065 // JavaScript builtins, a reference to the builtins object
1066 // (itself) and a reference to the global_context directly in the object.
1067 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
1068 Handle<JSFunction> builtins_fun =
1069 Factory::NewFunction(Factory::empty_symbol(), JS_BUILTINS_OBJECT_TYPE,
1070 JSBuiltinsObject::kSize, code, true);
1071
1072 Handle<String> name = Factory::LookupAsciiSymbol("builtins");
1073 builtins_fun->shared()->set_instance_class_name(*name);
1074
1075 // Allocate the builtins object.
1076 Handle<JSBuiltinsObject> builtins =
1077 Handle<JSBuiltinsObject>::cast(Factory::NewGlobalObject(builtins_fun));
1078 builtins->set_builtins(*builtins);
1079 builtins->set_global_context(*global_context());
1080 builtins->set_global_receiver(*builtins);
1081
1082 // Setup the 'global' properties of the builtins object. The
1083 // 'global' property that refers to the global object is the only
1084 // way to get from code running in the builtins context to the
1085 // global object.
1086 static const PropertyAttributes attributes =
1087 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001088 Handle<String> global_symbol = Factory::LookupAsciiSymbol("global");
1089 SetProperty(builtins,
1090 global_symbol,
1091 Handle<Object>(global_context()->global()),
1092 attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001093
1094 // Setup the reference from the global object to the builtins object.
1095 JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
1096
1097 // Create a bridge function that has context in the global context.
1098 Handle<JSFunction> bridge =
1099 Factory::NewFunction(Factory::empty_symbol(), Factory::undefined_value());
1100 ASSERT(bridge->context() == *Top::global_context());
1101
1102 // Allocate the builtins context.
1103 Handle<Context> context =
1104 Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1105 context->set_global(*builtins); // override builtins global object
1106
1107 global_context()->set_runtime_context(*context);
1108
1109 { // -- S c r i p t
1110 // Builtin functions for Script.
1111 Handle<JSFunction> script_fun =
1112 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1113 Top::initial_object_prototype(), Builtins::Illegal,
1114 false);
1115 Handle<JSObject> prototype =
1116 Factory::NewJSObject(Top::object_function(), TENURED);
1117 SetPrototype(script_fun, prototype);
1118 global_context()->set_script_function(*script_fun);
1119
1120 // Add 'source' and 'data' property to scripts.
1121 PropertyAttributes common_attributes =
1122 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1123 Handle<Proxy> proxy_source = Factory::NewProxy(&Accessors::ScriptSource);
1124 Handle<DescriptorArray> script_descriptors =
1125 Factory::CopyAppendProxyDescriptor(
1126 Factory::empty_descriptor_array(),
1127 Factory::LookupAsciiSymbol("source"),
1128 proxy_source,
1129 common_attributes);
1130 Handle<Proxy> proxy_name = Factory::NewProxy(&Accessors::ScriptName);
1131 script_descriptors =
1132 Factory::CopyAppendProxyDescriptor(
1133 script_descriptors,
1134 Factory::LookupAsciiSymbol("name"),
1135 proxy_name,
1136 common_attributes);
1137 Handle<Proxy> proxy_id = Factory::NewProxy(&Accessors::ScriptId);
1138 script_descriptors =
1139 Factory::CopyAppendProxyDescriptor(
1140 script_descriptors,
1141 Factory::LookupAsciiSymbol("id"),
1142 proxy_id,
1143 common_attributes);
1144 Handle<Proxy> proxy_line_offset =
1145 Factory::NewProxy(&Accessors::ScriptLineOffset);
1146 script_descriptors =
1147 Factory::CopyAppendProxyDescriptor(
1148 script_descriptors,
1149 Factory::LookupAsciiSymbol("line_offset"),
1150 proxy_line_offset,
1151 common_attributes);
1152 Handle<Proxy> proxy_column_offset =
1153 Factory::NewProxy(&Accessors::ScriptColumnOffset);
1154 script_descriptors =
1155 Factory::CopyAppendProxyDescriptor(
1156 script_descriptors,
1157 Factory::LookupAsciiSymbol("column_offset"),
1158 proxy_column_offset,
1159 common_attributes);
1160 Handle<Proxy> proxy_data = Factory::NewProxy(&Accessors::ScriptData);
1161 script_descriptors =
1162 Factory::CopyAppendProxyDescriptor(
1163 script_descriptors,
1164 Factory::LookupAsciiSymbol("data"),
1165 proxy_data,
1166 common_attributes);
1167 Handle<Proxy> proxy_type = Factory::NewProxy(&Accessors::ScriptType);
1168 script_descriptors =
1169 Factory::CopyAppendProxyDescriptor(
1170 script_descriptors,
1171 Factory::LookupAsciiSymbol("type"),
1172 proxy_type,
1173 common_attributes);
1174 Handle<Proxy> proxy_compilation_type =
1175 Factory::NewProxy(&Accessors::ScriptCompilationType);
1176 script_descriptors =
1177 Factory::CopyAppendProxyDescriptor(
1178 script_descriptors,
1179 Factory::LookupAsciiSymbol("compilation_type"),
1180 proxy_compilation_type,
1181 common_attributes);
1182 Handle<Proxy> proxy_line_ends =
1183 Factory::NewProxy(&Accessors::ScriptLineEnds);
1184 script_descriptors =
1185 Factory::CopyAppendProxyDescriptor(
1186 script_descriptors,
1187 Factory::LookupAsciiSymbol("line_ends"),
1188 proxy_line_ends,
1189 common_attributes);
1190 Handle<Proxy> proxy_context_data =
1191 Factory::NewProxy(&Accessors::ScriptContextData);
1192 script_descriptors =
1193 Factory::CopyAppendProxyDescriptor(
1194 script_descriptors,
1195 Factory::LookupAsciiSymbol("context_data"),
1196 proxy_context_data,
1197 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001198 Handle<Proxy> proxy_eval_from_script =
1199 Factory::NewProxy(&Accessors::ScriptEvalFromScript);
Steve Blocka7e24c12009-10-30 11:49:00 +00001200 script_descriptors =
1201 Factory::CopyAppendProxyDescriptor(
1202 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001203 Factory::LookupAsciiSymbol("eval_from_script"),
1204 proxy_eval_from_script,
Steve Blocka7e24c12009-10-30 11:49:00 +00001205 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001206 Handle<Proxy> proxy_eval_from_script_position =
1207 Factory::NewProxy(&Accessors::ScriptEvalFromScriptPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +00001208 script_descriptors =
1209 Factory::CopyAppendProxyDescriptor(
1210 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001211 Factory::LookupAsciiSymbol("eval_from_script_position"),
1212 proxy_eval_from_script_position,
1213 common_attributes);
1214 Handle<Proxy> proxy_eval_from_function_name =
1215 Factory::NewProxy(&Accessors::ScriptEvalFromFunctionName);
1216 script_descriptors =
1217 Factory::CopyAppendProxyDescriptor(
1218 script_descriptors,
1219 Factory::LookupAsciiSymbol("eval_from_function_name"),
1220 proxy_eval_from_function_name,
Steve Blocka7e24c12009-10-30 11:49:00 +00001221 common_attributes);
1222
1223 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1224 script_map->set_instance_descriptors(*script_descriptors);
1225
1226 // Allocate the empty script.
1227 Handle<Script> script = Factory::NewScript(Factory::empty_string());
1228 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Andrei Popescu31002712010-02-23 13:46:05 +00001229 Heap::public_set_empty_script(*script);
Steve Blocka7e24c12009-10-30 11:49:00 +00001230 }
Steve Block6ded16b2010-05-10 14:33:55 +01001231 {
1232 // Builtin function for OpaqueReference -- a JSValue-based object,
1233 // that keeps its field isolated from JavaScript code. It may store
1234 // objects, that JavaScript code may not access.
1235 Handle<JSFunction> opaque_reference_fun =
1236 InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1237 JSValue::kSize, Top::initial_object_prototype(),
1238 Builtins::Illegal, false);
1239 Handle<JSObject> prototype =
1240 Factory::NewJSObject(Top::object_function(), TENURED);
1241 SetPrototype(opaque_reference_fun, prototype);
1242 global_context()->set_opaque_reference_function(*opaque_reference_fun);
1243 }
1244
1245 if (FLAG_disable_native_files) {
1246 PrintF("Warning: Running without installed natives!\n");
1247 return true;
1248 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001249
Andrei Popescu31002712010-02-23 13:46:05 +00001250 // Install natives.
1251 for (int i = Natives::GetDebuggerCount();
1252 i < Natives::GetBuiltinsCount();
1253 i++) {
1254 Vector<const char> name = Natives::GetScriptName(i);
1255 if (!CompileBuiltin(i)) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001256 // TODO(ager): We really only need to install the JS builtin
1257 // functions on the builtins object after compiling and running
1258 // runtime.js.
1259 if (!InstallJSBuiltins(builtins)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001260 }
1261
1262 InstallNativeFunctions();
1263
Iain Merrick75681382010-08-19 15:07:18 +01001264 // Store the map for the string prototype after the natives has been compiled
1265 // and the String function has been setup.
1266 Handle<JSFunction> string_function(global_context()->string_function());
1267 ASSERT(JSObject::cast(
1268 string_function->initial_map()->prototype())->HasFastProperties());
1269 global_context()->set_string_function_prototype_map(
1270 HeapObject::cast(string_function->initial_map()->prototype())->map());
1271
Ben Murdochb0fe1622011-05-05 13:52:32 +01001272 InstallBuiltinFunctionIds();
Kristian Monsen25f61362010-05-21 11:50:48 +01001273
Steve Blocka7e24c12009-10-30 11:49:00 +00001274 // Install Function.prototype.call and apply.
1275 { Handle<String> key = Factory::function_class_symbol();
1276 Handle<JSFunction> function =
1277 Handle<JSFunction>::cast(GetProperty(Top::global(), key));
1278 Handle<JSObject> proto =
1279 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1280
1281 // Install the call and the apply functions.
1282 Handle<JSFunction> call =
1283 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001284 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001285 Builtins::FunctionCall,
1286 false);
1287 Handle<JSFunction> apply =
1288 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001289 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001290 Builtins::FunctionApply,
1291 false);
1292
1293 // Make sure that Function.prototype.call appears to be compiled.
1294 // The code will never be called, but inline caching for call will
1295 // only work if it appears to be compiled.
1296 call->shared()->DontAdaptArguments();
1297 ASSERT(call->is_compiled());
1298
1299 // Set the expected parameters for apply to 2; required by builtin.
1300 apply->shared()->set_formal_parameter_count(2);
1301
1302 // Set the lengths for the functions to satisfy ECMA-262.
1303 call->shared()->set_length(1);
1304 apply->shared()->set_length(2);
1305 }
1306
Steve Block6ded16b2010-05-10 14:33:55 +01001307 // Create a constructor for RegExp results (a variant of Array that
1308 // predefines the two properties index and match).
1309 {
1310 // RegExpResult initial map.
1311
1312 // Find global.Array.prototype to inherit from.
1313 Handle<JSFunction> array_constructor(global_context()->array_function());
1314 Handle<JSObject> array_prototype(
1315 JSObject::cast(array_constructor->instance_prototype()));
1316
1317 // Add initial map.
1318 Handle<Map> initial_map =
1319 Factory::NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1320 initial_map->set_constructor(*array_constructor);
1321
1322 // Set prototype on map.
1323 initial_map->set_non_instance_prototype(false);
1324 initial_map->set_prototype(*array_prototype);
1325
1326 // Update map with length accessor from Array and add "index" and "input".
1327 Handle<Map> array_map(global_context()->js_array_map());
1328 Handle<DescriptorArray> array_descriptors(
1329 array_map->instance_descriptors());
1330 ASSERT_EQ(1, array_descriptors->number_of_descriptors());
1331
1332 Handle<DescriptorArray> reresult_descriptors =
1333 Factory::NewDescriptorArray(3);
1334
1335 reresult_descriptors->CopyFrom(0, *array_descriptors, 0);
1336
1337 int enum_index = 0;
1338 {
1339 FieldDescriptor index_field(Heap::index_symbol(),
1340 JSRegExpResult::kIndexIndex,
1341 NONE,
1342 enum_index++);
1343 reresult_descriptors->Set(1, &index_field);
1344 }
1345
1346 {
1347 FieldDescriptor input_field(Heap::input_symbol(),
1348 JSRegExpResult::kInputIndex,
1349 NONE,
1350 enum_index++);
1351 reresult_descriptors->Set(2, &input_field);
1352 }
1353 reresult_descriptors->Sort();
1354
1355 initial_map->set_inobject_properties(2);
1356 initial_map->set_pre_allocated_property_fields(2);
1357 initial_map->set_unused_property_fields(0);
1358 initial_map->set_instance_descriptors(*reresult_descriptors);
1359
1360 global_context()->set_regexp_result_map(*initial_map);
1361 }
1362
Steve Blocka7e24c12009-10-30 11:49:00 +00001363#ifdef DEBUG
1364 builtins->Verify();
1365#endif
Andrei Popescu31002712010-02-23 13:46:05 +00001366
Steve Blocka7e24c12009-10-30 11:49:00 +00001367 return true;
1368}
1369
1370
Ben Murdochb0fe1622011-05-05 13:52:32 +01001371static Handle<JSObject> ResolveBuiltinIdHolder(
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001372 Handle<Context> global_context,
1373 const char* holder_expr) {
1374 Handle<GlobalObject> global(global_context->global());
1375 const char* period_pos = strchr(holder_expr, '.');
1376 if (period_pos == NULL) {
1377 return Handle<JSObject>::cast(
1378 GetProperty(global, Factory::LookupAsciiSymbol(holder_expr)));
Steve Block59151502010-09-22 15:07:15 +01001379 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001380 ASSERT_EQ(".prototype", period_pos);
1381 Vector<const char> property(holder_expr,
1382 static_cast<int>(period_pos - holder_expr));
1383 Handle<JSFunction> function = Handle<JSFunction>::cast(
1384 GetProperty(global, Factory::LookupSymbol(property)));
1385 return Handle<JSObject>(JSObject::cast(function->prototype()));
1386}
1387
1388
Ben Murdochb0fe1622011-05-05 13:52:32 +01001389static void InstallBuiltinFunctionId(Handle<JSObject> holder,
1390 const char* function_name,
1391 BuiltinFunctionId id) {
Kristian Monsen25f61362010-05-21 11:50:48 +01001392 Handle<String> name = Factory::LookupAsciiSymbol(function_name);
John Reck59135872010-11-02 12:39:01 -07001393 Object* function_object = holder->GetProperty(*name)->ToObjectUnchecked();
1394 Handle<JSFunction> function(JSFunction::cast(function_object));
Kristian Monsen25f61362010-05-21 11:50:48 +01001395 function->shared()->set_function_data(Smi::FromInt(id));
1396}
1397
1398
Ben Murdochb0fe1622011-05-05 13:52:32 +01001399void Genesis::InstallBuiltinFunctionIds() {
Kristian Monsen25f61362010-05-21 11:50:48 +01001400 HandleScope scope;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001401#define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
1402 { \
1403 Handle<JSObject> holder = ResolveBuiltinIdHolder( \
1404 global_context(), #holder_expr); \
1405 BuiltinFunctionId id = k##name; \
1406 InstallBuiltinFunctionId(holder, #fun_name, id); \
Kristian Monsen25f61362010-05-21 11:50:48 +01001407 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01001408 FUNCTIONS_WITH_ID_LIST(INSTALL_BUILTIN_ID)
1409#undef INSTALL_BUILTIN_ID
Kristian Monsen25f61362010-05-21 11:50:48 +01001410}
1411
1412
Steve Block6ded16b2010-05-10 14:33:55 +01001413// Do not forget to update macros.py with named constant
1414// of cache id.
1415#define JSFUNCTION_RESULT_CACHE_LIST(F) \
1416 F(16, global_context()->regexp_function())
1417
1418
1419static FixedArray* CreateCache(int size, JSFunction* factory) {
1420 // Caches are supposed to live for a long time, allocate in old space.
1421 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1422 // Cannot use cast as object is not fully initialized yet.
1423 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1424 *Factory::NewFixedArrayWithHoles(array_size, TENURED));
1425 cache->set(JSFunctionResultCache::kFactoryIndex, factory);
1426 cache->MakeZeroSize();
1427 return cache;
1428}
1429
1430
1431void Genesis::InstallJSFunctionResultCaches() {
1432 const int kNumberOfCaches = 0 +
1433#define F(size, func) + 1
1434 JSFUNCTION_RESULT_CACHE_LIST(F)
1435#undef F
1436 ;
1437
1438 Handle<FixedArray> caches = Factory::NewFixedArray(kNumberOfCaches, TENURED);
1439
1440 int index = 0;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001441
1442#define F(size, func) do { \
1443 FixedArray* cache = CreateCache((size), (func)); \
1444 caches->set(index++, cache); \
1445 } while (false)
1446
1447 JSFUNCTION_RESULT_CACHE_LIST(F);
1448
Steve Block6ded16b2010-05-10 14:33:55 +01001449#undef F
1450
1451 global_context()->set_jsfunction_result_caches(*caches);
1452}
1453
1454
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001455void Genesis::InitializeNormalizedMapCaches() {
1456 Handle<FixedArray> array(
1457 Factory::NewFixedArray(NormalizedMapCache::kEntries, TENURED));
1458 global_context()->set_normalized_map_cache(NormalizedMapCache::cast(*array));
1459}
1460
1461
Andrei Popescu31002712010-02-23 13:46:05 +00001462int BootstrapperActive::nesting_ = 0;
1463
1464
1465bool Bootstrapper::InstallExtensions(Handle<Context> global_context,
1466 v8::ExtensionConfiguration* extensions) {
1467 BootstrapperActive active;
1468 SaveContext saved_context;
1469 Top::set_context(*global_context);
1470 if (!Genesis::InstallExtensions(global_context, extensions)) return false;
1471 Genesis::InstallSpecialObjects(global_context);
1472 return true;
1473}
1474
1475
1476void Genesis::InstallSpecialObjects(Handle<Context> global_context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001477 HandleScope scope;
1478 Handle<JSGlobalObject> js_global(
Andrei Popescu31002712010-02-23 13:46:05 +00001479 JSGlobalObject::cast(global_context->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001480 // Expose the natives in global if a name for it is specified.
1481 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1482 Handle<String> natives_string =
1483 Factory::LookupAsciiSymbol(FLAG_expose_natives_as);
1484 SetProperty(js_global, natives_string,
1485 Handle<JSObject>(js_global->builtins()), DONT_ENUM);
1486 }
1487
1488 Handle<Object> Error = GetProperty(js_global, "Error");
1489 if (Error->IsJSObject()) {
1490 Handle<String> name = Factory::LookupAsciiSymbol("stackTraceLimit");
1491 SetProperty(Handle<JSObject>::cast(Error),
1492 name,
1493 Handle<Smi>(Smi::FromInt(FLAG_stack_trace_limit)),
1494 NONE);
1495 }
1496
1497#ifdef ENABLE_DEBUGGER_SUPPORT
1498 // Expose the debug global object in global if a name for it is specified.
1499 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1500 // If loading fails we just bail out without installing the
1501 // debugger but without tanking the whole context.
Andrei Popescu31002712010-02-23 13:46:05 +00001502 if (!Debug::Load()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001503 // Set the security token for the debugger context to the same as
1504 // the shell global context to allow calling between these (otherwise
1505 // exposing debug global object doesn't make much sense).
1506 Debug::debug_context()->set_security_token(
Andrei Popescu31002712010-02-23 13:46:05 +00001507 global_context->security_token());
Steve Blocka7e24c12009-10-30 11:49:00 +00001508
1509 Handle<String> debug_string =
1510 Factory::LookupAsciiSymbol(FLAG_expose_debug_as);
1511 SetProperty(js_global, debug_string,
1512 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM);
1513 }
1514#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001515}
1516
1517
Andrei Popescu31002712010-02-23 13:46:05 +00001518bool Genesis::InstallExtensions(Handle<Context> global_context,
1519 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001520 // Clear coloring of extension list
1521 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1522 while (current != NULL) {
1523 current->set_state(v8::UNVISITED);
1524 current = current->next();
1525 }
Andrei Popescu31002712010-02-23 13:46:05 +00001526 // Install auto extensions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001527 current = v8::RegisteredExtension::first_extension();
1528 while (current != NULL) {
1529 if (current->extension()->auto_enable())
1530 InstallExtension(current);
1531 current = current->next();
1532 }
1533
1534 if (FLAG_expose_gc) InstallExtension("v8/gc");
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001535 if (FLAG_expose_externalize_string) InstallExtension("v8/externalize");
Steve Blocka7e24c12009-10-30 11:49:00 +00001536
1537 if (extensions == NULL) return true;
1538 // Install required extensions
1539 int count = v8::ImplementationUtilities::GetNameCount(extensions);
1540 const char** names = v8::ImplementationUtilities::GetNames(extensions);
1541 for (int i = 0; i < count; i++) {
1542 if (!InstallExtension(names[i]))
1543 return false;
1544 }
1545
1546 return true;
1547}
1548
1549
1550// Installs a named extension. This methods is unoptimized and does
1551// not scale well if we want to support a large number of extensions.
1552bool Genesis::InstallExtension(const char* name) {
1553 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1554 // Loop until we find the relevant extension
1555 while (current != NULL) {
1556 if (strcmp(name, current->extension()->name()) == 0) break;
1557 current = current->next();
1558 }
1559 // Didn't find the extension; fail.
1560 if (current == NULL) {
1561 v8::Utils::ReportApiFailure(
1562 "v8::Context::New()", "Cannot find required extension");
1563 return false;
1564 }
1565 return InstallExtension(current);
1566}
1567
1568
1569bool Genesis::InstallExtension(v8::RegisteredExtension* current) {
1570 HandleScope scope;
1571
1572 if (current->state() == v8::INSTALLED) return true;
1573 // The current node has already been visited so there must be a
1574 // cycle in the dependency graph; fail.
1575 if (current->state() == v8::VISITED) {
1576 v8::Utils::ReportApiFailure(
1577 "v8::Context::New()", "Circular extension dependency");
1578 return false;
1579 }
1580 ASSERT(current->state() == v8::UNVISITED);
1581 current->set_state(v8::VISITED);
1582 v8::Extension* extension = current->extension();
1583 // Install the extension's dependencies
1584 for (int i = 0; i < extension->dependency_count(); i++) {
1585 if (!InstallExtension(extension->dependencies()[i])) return false;
1586 }
1587 Vector<const char> source = CStrVector(extension->source());
1588 Handle<String> source_code = Factory::NewStringFromAscii(source);
1589 bool result = CompileScriptCached(CStrVector(extension->name()),
1590 source_code,
Andrei Popescu31002712010-02-23 13:46:05 +00001591 &extensions_cache,
1592 extension,
1593 Handle<Context>(Top::context()),
Steve Blocka7e24c12009-10-30 11:49:00 +00001594 false);
1595 ASSERT(Top::has_pending_exception() != result);
1596 if (!result) {
1597 Top::clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001598 }
1599 current->set_state(v8::INSTALLED);
1600 return result;
1601}
1602
1603
Andrei Popescu402d9372010-02-26 13:31:12 +00001604bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
1605 HandleScope scope;
1606 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
1607 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
1608 Handle<String> name = Factory::LookupAsciiSymbol(Builtins::GetName(id));
John Reck59135872010-11-02 12:39:01 -07001609 Object* function_object = builtins->GetPropertyNoExceptionThrown(*name);
Andrei Popescu402d9372010-02-26 13:31:12 +00001610 Handle<JSFunction> function
John Reck59135872010-11-02 12:39:01 -07001611 = Handle<JSFunction>(JSFunction::cast(function_object));
Andrei Popescu402d9372010-02-26 13:31:12 +00001612 builtins->set_javascript_builtin(id, *function);
1613 Handle<SharedFunctionInfo> shared
1614 = Handle<SharedFunctionInfo>(function->shared());
1615 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Iain Merrick75681382010-08-19 15:07:18 +01001616 // Set the code object on the function object.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001617 function->ReplaceCode(function->shared()->code());
Steve Block6ded16b2010-05-10 14:33:55 +01001618 builtins->set_javascript_builtin_code(id, shared->code());
Andrei Popescu402d9372010-02-26 13:31:12 +00001619 }
1620 return true;
Andrei Popescu31002712010-02-23 13:46:05 +00001621}
1622
1623
Steve Blocka7e24c12009-10-30 11:49:00 +00001624bool Genesis::ConfigureGlobalObjects(
1625 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
1626 Handle<JSObject> global_proxy(
1627 JSObject::cast(global_context()->global_proxy()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001628 Handle<JSObject> inner_global(JSObject::cast(global_context()->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001629
1630 if (!global_proxy_template.IsEmpty()) {
1631 // Configure the global proxy object.
1632 Handle<ObjectTemplateInfo> proxy_data =
1633 v8::Utils::OpenHandle(*global_proxy_template);
1634 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
1635
1636 // Configure the inner global object.
1637 Handle<FunctionTemplateInfo> proxy_constructor(
1638 FunctionTemplateInfo::cast(proxy_data->constructor()));
1639 if (!proxy_constructor->prototype_template()->IsUndefined()) {
1640 Handle<ObjectTemplateInfo> inner_data(
1641 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001642 if (!ConfigureApiObject(inner_global, inner_data)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001643 }
1644 }
1645
Andrei Popescu402d9372010-02-26 13:31:12 +00001646 SetObjectPrototype(global_proxy, inner_global);
Steve Blocka7e24c12009-10-30 11:49:00 +00001647 return true;
1648}
1649
1650
1651bool Genesis::ConfigureApiObject(Handle<JSObject> object,
1652 Handle<ObjectTemplateInfo> object_template) {
1653 ASSERT(!object_template.is_null());
1654 ASSERT(object->IsInstanceOf(
1655 FunctionTemplateInfo::cast(object_template->constructor())));
1656
1657 bool pending_exception = false;
1658 Handle<JSObject> obj =
1659 Execution::InstantiateObject(object_template, &pending_exception);
1660 if (pending_exception) {
1661 ASSERT(Top::has_pending_exception());
1662 Top::clear_pending_exception();
1663 return false;
1664 }
1665 TransferObject(obj, object);
1666 return true;
1667}
1668
1669
1670void Genesis::TransferNamedProperties(Handle<JSObject> from,
1671 Handle<JSObject> to) {
1672 if (from->HasFastProperties()) {
1673 Handle<DescriptorArray> descs =
1674 Handle<DescriptorArray>(from->map()->instance_descriptors());
1675 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1676 PropertyDetails details = PropertyDetails(descs->GetDetails(i));
1677 switch (details.type()) {
1678 case FIELD: {
1679 HandleScope inner;
1680 Handle<String> key = Handle<String>(descs->GetKey(i));
1681 int index = descs->GetFieldIndex(i);
1682 Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
1683 SetProperty(to, key, value, details.attributes());
1684 break;
1685 }
1686 case CONSTANT_FUNCTION: {
1687 HandleScope inner;
1688 Handle<String> key = Handle<String>(descs->GetKey(i));
1689 Handle<JSFunction> fun =
1690 Handle<JSFunction>(descs->GetConstantFunction(i));
1691 SetProperty(to, key, fun, details.attributes());
1692 break;
1693 }
1694 case CALLBACKS: {
1695 LookupResult result;
1696 to->LocalLookup(descs->GetKey(i), &result);
1697 // If the property is already there we skip it
Andrei Popescu402d9372010-02-26 13:31:12 +00001698 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001699 HandleScope inner;
Andrei Popescu31002712010-02-23 13:46:05 +00001700 ASSERT(!to->HasFastProperties());
1701 // Add to dictionary.
Steve Blocka7e24c12009-10-30 11:49:00 +00001702 Handle<String> key = Handle<String>(descs->GetKey(i));
Andrei Popescu31002712010-02-23 13:46:05 +00001703 Handle<Object> callbacks(descs->GetCallbacksObject(i));
1704 PropertyDetails d =
1705 PropertyDetails(details.attributes(), CALLBACKS, details.index());
1706 SetNormalizedProperty(to, key, callbacks, d);
Steve Blocka7e24c12009-10-30 11:49:00 +00001707 break;
1708 }
1709 case MAP_TRANSITION:
1710 case CONSTANT_TRANSITION:
1711 case NULL_DESCRIPTOR:
1712 // Ignore non-properties.
1713 break;
1714 case NORMAL:
1715 // Do not occur since the from object has fast properties.
1716 case INTERCEPTOR:
1717 // No element in instance descriptors have interceptor type.
1718 UNREACHABLE();
1719 break;
1720 }
1721 }
1722 } else {
1723 Handle<StringDictionary> properties =
1724 Handle<StringDictionary>(from->property_dictionary());
1725 int capacity = properties->Capacity();
1726 for (int i = 0; i < capacity; i++) {
1727 Object* raw_key(properties->KeyAt(i));
1728 if (properties->IsKey(raw_key)) {
1729 ASSERT(raw_key->IsString());
1730 // If the property is already there we skip it.
1731 LookupResult result;
1732 to->LocalLookup(String::cast(raw_key), &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001733 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001734 // Set the property.
1735 Handle<String> key = Handle<String>(String::cast(raw_key));
1736 Handle<Object> value = Handle<Object>(properties->ValueAt(i));
1737 if (value->IsJSGlobalPropertyCell()) {
1738 value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
1739 }
1740 PropertyDetails details = properties->DetailsAt(i);
1741 SetProperty(to, key, value, details.attributes());
1742 }
1743 }
1744 }
1745}
1746
1747
1748void Genesis::TransferIndexedProperties(Handle<JSObject> from,
1749 Handle<JSObject> to) {
1750 // Cloning the elements array is sufficient.
1751 Handle<FixedArray> from_elements =
1752 Handle<FixedArray>(FixedArray::cast(from->elements()));
1753 Handle<FixedArray> to_elements = Factory::CopyFixedArray(from_elements);
1754 to->set_elements(*to_elements);
1755}
1756
1757
1758void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
1759 HandleScope outer;
1760
1761 ASSERT(!from->IsJSArray());
1762 ASSERT(!to->IsJSArray());
1763
1764 TransferNamedProperties(from, to);
1765 TransferIndexedProperties(from, to);
1766
1767 // Transfer the prototype (new map is needed).
1768 Handle<Map> old_to_map = Handle<Map>(to->map());
1769 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
1770 new_to_map->set_prototype(from->map()->prototype());
1771 to->set_map(*new_to_map);
1772}
1773
1774
1775void Genesis::MakeFunctionInstancePrototypeWritable() {
1776 // Make a new function map so all future functions
1777 // will have settable and enumerable prototype properties.
1778 HandleScope scope;
1779
1780 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +01001781 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001782 Handle<Map> fm = Factory::CopyMapDropDescriptors(Top::function_map());
1783 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +01001784 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001785 Top::context()->global_context()->set_function_map(*fm);
1786}
1787
1788
Steve Blocka7e24c12009-10-30 11:49:00 +00001789Genesis::Genesis(Handle<Object> global_object,
1790 v8::Handle<v8::ObjectTemplate> global_template,
1791 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001792 result_ = Handle<Context>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +00001793 // If V8 isn't running and cannot be initialized, just return.
1794 if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
1795
1796 // Before creating the roots we must save the context and restore it
1797 // on all function exits.
1798 HandleScope scope;
Andrei Popescu31002712010-02-23 13:46:05 +00001799 SaveContext saved_context;
Steve Blocka7e24c12009-10-30 11:49:00 +00001800
Andrei Popescu31002712010-02-23 13:46:05 +00001801 Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
1802 if (!new_context.is_null()) {
1803 global_context_ =
1804 Handle<Context>::cast(GlobalHandles::Create(*new_context));
Ben Murdochb0fe1622011-05-05 13:52:32 +01001805 AddToWeakGlobalContextList(*global_context_);
Andrei Popescu31002712010-02-23 13:46:05 +00001806 Top::set_context(*global_context_);
1807 i::Counters::contexts_created_by_snapshot.Increment();
1808 result_ = global_context_;
1809 JSFunction* empty_function =
1810 JSFunction::cast(result_->function_map()->prototype());
1811 empty_function_ = Handle<JSFunction>(empty_function);
Andrei Popescu402d9372010-02-26 13:31:12 +00001812 Handle<GlobalObject> inner_global;
Andrei Popescu31002712010-02-23 13:46:05 +00001813 Handle<JSGlobalProxy> global_proxy =
1814 CreateNewGlobals(global_template,
1815 global_object,
Andrei Popescu402d9372010-02-26 13:31:12 +00001816 &inner_global);
1817
Andrei Popescu31002712010-02-23 13:46:05 +00001818 HookUpGlobalProxy(inner_global, global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +00001819 HookUpInnerGlobal(inner_global);
1820
Andrei Popescu31002712010-02-23 13:46:05 +00001821 if (!ConfigureGlobalObjects(global_template)) return;
1822 } else {
1823 // We get here if there was no context snapshot.
1824 CreateRoots();
1825 Handle<JSFunction> empty_function = CreateEmptyFunction();
1826 Handle<GlobalObject> inner_global;
1827 Handle<JSGlobalProxy> global_proxy =
1828 CreateNewGlobals(global_template, global_object, &inner_global);
1829 HookUpGlobalProxy(inner_global, global_proxy);
1830 InitializeGlobal(inner_global, empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +01001831 InstallJSFunctionResultCaches();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001832 InitializeNormalizedMapCaches();
Kristian Monsen25f61362010-05-21 11:50:48 +01001833 if (!InstallNatives()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001834
Andrei Popescu31002712010-02-23 13:46:05 +00001835 MakeFunctionInstancePrototypeWritable();
Steve Blocka7e24c12009-10-30 11:49:00 +00001836
Andrei Popescu31002712010-02-23 13:46:05 +00001837 if (!ConfigureGlobalObjects(global_template)) return;
1838 i::Counters::contexts_created_from_scratch.Increment();
1839 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001840
1841 result_ = global_context_;
1842}
1843
1844
1845// Support for thread preemption.
1846
1847// Reserve space for statics needing saving and restoring.
1848int Bootstrapper::ArchiveSpacePerThread() {
Andrei Popescu31002712010-02-23 13:46:05 +00001849 return BootstrapperActive::ArchiveSpacePerThread();
Steve Blocka7e24c12009-10-30 11:49:00 +00001850}
1851
1852
1853// Archive statics that are thread local.
1854char* Bootstrapper::ArchiveState(char* to) {
Andrei Popescu31002712010-02-23 13:46:05 +00001855 return BootstrapperActive::ArchiveState(to);
Steve Blocka7e24c12009-10-30 11:49:00 +00001856}
1857
1858
1859// Restore statics that are thread local.
1860char* Bootstrapper::RestoreState(char* from) {
Andrei Popescu31002712010-02-23 13:46:05 +00001861 return BootstrapperActive::RestoreState(from);
Steve Blocka7e24c12009-10-30 11:49:00 +00001862}
1863
1864
1865// Called when the top-level V8 mutex is destroyed.
1866void Bootstrapper::FreeThreadResources() {
Andrei Popescu31002712010-02-23 13:46:05 +00001867 ASSERT(!BootstrapperActive::IsActive());
Steve Blocka7e24c12009-10-30 11:49:00 +00001868}
1869
1870
1871// Reserve space for statics needing saving and restoring.
Andrei Popescu31002712010-02-23 13:46:05 +00001872int BootstrapperActive::ArchiveSpacePerThread() {
1873 return sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001874}
1875
1876
1877// Archive statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001878char* BootstrapperActive::ArchiveState(char* to) {
1879 *reinterpret_cast<int*>(to) = nesting_;
1880 nesting_ = 0;
1881 return to + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001882}
1883
1884
1885// Restore statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001886char* BootstrapperActive::RestoreState(char* from) {
1887 nesting_ = *reinterpret_cast<int*>(from);
1888 return from + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001889}
1890
1891} } // namespace v8::internal