blob: a82d1d69661f14d2e94757f724e17921075e1676 [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"
Kristian Monsen25f61362010-05-21 11:50:48 +010041#include "stub-cache.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43namespace v8 {
44namespace internal {
45
46// A SourceCodeCache uses a FixedArray to store pairs of
47// (AsciiString*, JSFunction*), mapping names of native code files
48// (runtime.js, etc.) to precompiled functions. Instead of mapping
49// names to functions it might make sense to let the JS2C tool
50// generate an index for each native JS file.
51class SourceCodeCache BASE_EMBEDDED {
52 public:
53 explicit SourceCodeCache(Script::Type type): type_(type), cache_(NULL) { }
54
55 void Initialize(bool create_heap_objects) {
56 cache_ = create_heap_objects ? Heap::empty_fixed_array() : NULL;
57 }
58
59 void Iterate(ObjectVisitor* v) {
Iain Merrick75681382010-08-19 15:07:18 +010060 v->VisitPointer(BitCast<Object**>(&cache_));
Steve Blocka7e24c12009-10-30 11:49:00 +000061 }
62
63
Steve Block6ded16b2010-05-10 14:33:55 +010064 bool Lookup(Vector<const char> name, Handle<SharedFunctionInfo>* handle) {
Steve Blocka7e24c12009-10-30 11:49:00 +000065 for (int i = 0; i < cache_->length(); i+=2) {
66 SeqAsciiString* str = SeqAsciiString::cast(cache_->get(i));
67 if (str->IsEqualTo(name)) {
Steve Block6ded16b2010-05-10 14:33:55 +010068 *handle = Handle<SharedFunctionInfo>(
69 SharedFunctionInfo::cast(cache_->get(i + 1)));
Steve Blocka7e24c12009-10-30 11:49:00 +000070 return true;
71 }
72 }
73 return false;
74 }
75
76
Steve Block6ded16b2010-05-10 14:33:55 +010077 void Add(Vector<const char> name, Handle<SharedFunctionInfo> shared) {
Steve Blocka7e24c12009-10-30 11:49:00 +000078 HandleScope scope;
79 int length = cache_->length();
80 Handle<FixedArray> new_array =
81 Factory::NewFixedArray(length + 2, TENURED);
82 cache_->CopyTo(0, *new_array, 0, cache_->length());
83 cache_ = *new_array;
84 Handle<String> str = Factory::NewStringFromAscii(name, TENURED);
85 cache_->set(length, *str);
Steve Block6ded16b2010-05-10 14:33:55 +010086 cache_->set(length + 1, *shared);
87 Script::cast(shared->script())->set_type(Smi::FromInt(type_));
Steve Blocka7e24c12009-10-30 11:49:00 +000088 }
89
90 private:
91 Script::Type type_;
92 FixedArray* cache_;
93 DISALLOW_COPY_AND_ASSIGN(SourceCodeCache);
94};
95
Steve Blocka7e24c12009-10-30 11:49:00 +000096static SourceCodeCache extensions_cache(Script::TYPE_EXTENSION);
Steve Blockd0582a62009-12-15 09:54:21 +000097// This is for delete, not delete[].
98static List<char*>* delete_these_non_arrays_on_tear_down = NULL;
Leon Clarkee46be812010-01-19 14:06:41 +000099// This is for delete[]
100static List<char*>* delete_these_arrays_on_tear_down = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000101
102
103NativesExternalStringResource::NativesExternalStringResource(const char* source)
104 : data_(source), length_(StrLength(source)) {
105 if (delete_these_non_arrays_on_tear_down == NULL) {
106 delete_these_non_arrays_on_tear_down = new List<char*>(2);
107 }
108 // The resources are small objects and we only make a fixed number of
109 // them, but let's clean them up on exit for neatness.
110 delete_these_non_arrays_on_tear_down->
111 Add(reinterpret_cast<char*>(this));
112}
Steve Blocka7e24c12009-10-30 11:49:00 +0000113
114
115Handle<String> Bootstrapper::NativesSourceLookup(int index) {
116 ASSERT(0 <= index && index < Natives::GetBuiltinsCount());
117 if (Heap::natives_source_cache()->get(index)->IsUndefined()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000118 if (!Snapshot::IsEnabled() || FLAG_new_snapshot) {
119 // We can use external strings for the natives.
120 NativesExternalStringResource* resource =
121 new NativesExternalStringResource(
122 Natives::GetScriptSource(index).start());
123 Handle<String> source_code =
124 Factory::NewExternalStringFromAscii(resource);
125 Heap::natives_source_cache()->set(index, *source_code);
126 } else {
127 // Old snapshot code can't cope with external strings at all.
128 Handle<String> source_code =
129 Factory::NewStringFromAscii(Natives::GetScriptSource(index));
130 Heap::natives_source_cache()->set(index, *source_code);
131 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000132 }
133 Handle<Object> cached_source(Heap::natives_source_cache()->get(index));
134 return Handle<String>::cast(cached_source);
135}
136
137
Steve Blocka7e24c12009-10-30 11:49:00 +0000138void Bootstrapper::Initialize(bool create_heap_objects) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000139 extensions_cache.Initialize(create_heap_objects);
140}
141
142
Leon Clarkee46be812010-01-19 14:06:41 +0000143char* Bootstrapper::AllocateAutoDeletedArray(int bytes) {
144 char* memory = new char[bytes];
145 if (memory != NULL) {
146 if (delete_these_arrays_on_tear_down == NULL) {
147 delete_these_arrays_on_tear_down = new List<char*>(2);
148 }
149 delete_these_arrays_on_tear_down->Add(memory);
150 }
151 return memory;
152}
153
154
Steve Blocka7e24c12009-10-30 11:49:00 +0000155void Bootstrapper::TearDown() {
Steve Blockd0582a62009-12-15 09:54:21 +0000156 if (delete_these_non_arrays_on_tear_down != NULL) {
157 int len = delete_these_non_arrays_on_tear_down->length();
158 ASSERT(len < 20); // Don't use this mechanism for unbounded allocations.
159 for (int i = 0; i < len; i++) {
160 delete delete_these_non_arrays_on_tear_down->at(i);
Leon Clarkee46be812010-01-19 14:06:41 +0000161 delete_these_non_arrays_on_tear_down->at(i) = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000162 }
163 delete delete_these_non_arrays_on_tear_down;
164 delete_these_non_arrays_on_tear_down = NULL;
165 }
166
Leon Clarkee46be812010-01-19 14:06:41 +0000167 if (delete_these_arrays_on_tear_down != NULL) {
168 int len = delete_these_arrays_on_tear_down->length();
169 ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations.
170 for (int i = 0; i < len; i++) {
171 delete[] delete_these_arrays_on_tear_down->at(i);
172 delete_these_arrays_on_tear_down->at(i) = NULL;
173 }
174 delete delete_these_arrays_on_tear_down;
175 delete_these_arrays_on_tear_down = NULL;
176 }
177
Andrei Popescu31002712010-02-23 13:46:05 +0000178 extensions_cache.Initialize(false); // Yes, symmetrical
Steve Blocka7e24c12009-10-30 11:49:00 +0000179}
180
181
Steve Blocka7e24c12009-10-30 11:49:00 +0000182class Genesis BASE_EMBEDDED {
183 public:
184 Genesis(Handle<Object> global_object,
185 v8::Handle<v8::ObjectTemplate> global_template,
186 v8::ExtensionConfiguration* extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000187 ~Genesis() { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000188
189 Handle<Context> result() { return result_; }
190
191 Genesis* previous() { return previous_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000192
193 private:
194 Handle<Context> global_context_;
195
196 // There may be more than one active genesis object: When GC is
197 // triggered during environment creation there may be weak handle
198 // processing callbacks which may create new environments.
199 Genesis* previous_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000200
201 Handle<Context> global_context() { return global_context_; }
202
Andrei Popescu31002712010-02-23 13:46:05 +0000203 // Creates some basic objects. Used for creating a context from scratch.
204 void CreateRoots();
205 // Creates the empty function. Used for creating a context from scratch.
206 Handle<JSFunction> CreateEmptyFunction();
207 // Creates the global objects using the global and the template passed in
208 // through the API. We call this regardless of whether we are building a
209 // context from scratch or using a deserialized one from the partial snapshot
210 // but in the latter case we don't use the objects it produces directly, as
211 // we have to used the deserialized ones that are linked together with the
212 // rest of the context snapshot.
213 Handle<JSGlobalProxy> CreateNewGlobals(
214 v8::Handle<v8::ObjectTemplate> global_template,
215 Handle<Object> global_object,
216 Handle<GlobalObject>* global_proxy_out);
217 // Hooks the given global proxy into the context. If the context was created
218 // by deserialization then this will unhook the global proxy that was
219 // deserialized, leaving the GC to pick it up.
220 void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
221 Handle<JSGlobalProxy> global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +0000222 // Similarly, we want to use the inner global that has been created by the
223 // templates passed through the API. The inner global from the snapshot is
224 // detached from the other objects in the snapshot.
225 void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
Andrei Popescu31002712010-02-23 13:46:05 +0000226 // New context initialization. Used for creating a context from scratch.
227 void InitializeGlobal(Handle<GlobalObject> inner_global,
228 Handle<JSFunction> empty_function);
229 // Installs the contents of the native .js files on the global objects.
230 // Used for creating a context from scratch.
Steve Blocka7e24c12009-10-30 11:49:00 +0000231 void InstallNativeFunctions();
232 bool InstallNatives();
Kristian Monsen25f61362010-05-21 11:50:48 +0100233 void InstallCustomCallGenerators();
Steve Block6ded16b2010-05-10 14:33:55 +0100234 void InstallJSFunctionResultCaches();
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100235 void InitializeNormalizedMapCaches();
Andrei Popescu31002712010-02-23 13:46:05 +0000236 // Used both for deserialized and from-scratch contexts to add the extensions
237 // provided.
238 static bool InstallExtensions(Handle<Context> global_context,
239 v8::ExtensionConfiguration* extensions);
240 static bool InstallExtension(const char* name);
241 static bool InstallExtension(v8::RegisteredExtension* current);
242 static void InstallSpecialObjects(Handle<Context> global_context);
Andrei Popescu402d9372010-02-26 13:31:12 +0000243 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
Steve Blocka7e24c12009-10-30 11:49:00 +0000244 bool ConfigureApiObject(Handle<JSObject> object,
245 Handle<ObjectTemplateInfo> object_template);
246 bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
247
248 // Migrates all properties from the 'from' object to the 'to'
249 // object and overrides the prototype in 'to' with the one from
250 // 'from'.
251 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
252 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
253 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
254
Steve Block6ded16b2010-05-10 14:33:55 +0100255 enum PrototypePropertyMode {
256 DONT_ADD_PROTOTYPE,
257 ADD_READONLY_PROTOTYPE,
258 ADD_WRITEABLE_PROTOTYPE
259 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000260 Handle<DescriptorArray> ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100261 PrototypePropertyMode prototypeMode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000262 void MakeFunctionInstancePrototypeWritable();
263
Steve Blocka7e24c12009-10-30 11:49:00 +0000264 static bool CompileBuiltin(int index);
265 static bool CompileNative(Vector<const char> name, Handle<String> source);
266 static bool CompileScriptCached(Vector<const char> name,
267 Handle<String> source,
268 SourceCodeCache* cache,
269 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000270 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000271 bool use_runtime_context);
272
273 Handle<Context> result_;
Andrei Popescu31002712010-02-23 13:46:05 +0000274 Handle<JSFunction> empty_function_;
275 BootstrapperActive active_;
276 friend class Bootstrapper;
Steve Blocka7e24c12009-10-30 11:49:00 +0000277};
278
Steve Blocka7e24c12009-10-30 11:49:00 +0000279
280void Bootstrapper::Iterate(ObjectVisitor* v) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000281 extensions_cache.Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +0000282 v->Synchronize("Extensions");
Steve Blocka7e24c12009-10-30 11:49:00 +0000283}
284
285
Steve Blocka7e24c12009-10-30 11:49:00 +0000286Handle<Context> Bootstrapper::CreateEnvironment(
287 Handle<Object> global_object,
288 v8::Handle<v8::ObjectTemplate> global_template,
289 v8::ExtensionConfiguration* extensions) {
Andrei Popescu31002712010-02-23 13:46:05 +0000290 HandleScope scope;
291 Handle<Context> env;
Steve Blocka7e24c12009-10-30 11:49:00 +0000292 Genesis genesis(global_object, global_template, extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000293 env = genesis.result();
294 if (!env.is_null()) {
295 if (InstallExtensions(env, extensions)) {
296 return env;
297 }
298 }
299 return Handle<Context>();
Steve Blocka7e24c12009-10-30 11:49:00 +0000300}
301
302
303static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
304 // object.__proto__ = proto;
305 Handle<Map> old_to_map = Handle<Map>(object->map());
306 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
307 new_to_map->set_prototype(*proto);
308 object->set_map(*new_to_map);
309}
310
311
312void Bootstrapper::DetachGlobal(Handle<Context> env) {
313 JSGlobalProxy::cast(env->global_proxy())->set_context(*Factory::null_value());
314 SetObjectPrototype(Handle<JSObject>(env->global_proxy()),
315 Factory::null_value());
316 env->set_global_proxy(env->global());
317 env->global()->set_global_receiver(env->global());
318}
319
320
Andrei Popescu74b3c142010-03-29 12:03:09 +0100321void Bootstrapper::ReattachGlobal(Handle<Context> env,
322 Handle<Object> global_object) {
323 ASSERT(global_object->IsJSGlobalProxy());
324 Handle<JSGlobalProxy> global = Handle<JSGlobalProxy>::cast(global_object);
325 env->global()->set_global_receiver(*global);
326 env->set_global_proxy(*global);
327 SetObjectPrototype(global, Handle<JSObject>(env->global()));
328 global->set_context(*env);
329}
330
331
Steve Blocka7e24c12009-10-30 11:49:00 +0000332static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
333 const char* name,
334 InstanceType type,
335 int instance_size,
336 Handle<JSObject> prototype,
337 Builtins::Name call,
338 bool is_ecma_native) {
339 Handle<String> symbol = Factory::LookupAsciiSymbol(name);
340 Handle<Code> call_code = Handle<Code>(Builtins::builtin(call));
Steve Block6ded16b2010-05-10 14:33:55 +0100341 Handle<JSFunction> function = prototype.is_null() ?
342 Factory::NewFunctionWithoutPrototype(symbol, call_code) :
Steve Blocka7e24c12009-10-30 11:49:00 +0000343 Factory::NewFunctionWithPrototype(symbol,
344 type,
345 instance_size,
346 prototype,
347 call_code,
348 is_ecma_native);
349 SetProperty(target, symbol, function, DONT_ENUM);
350 if (is_ecma_native) {
351 function->shared()->set_instance_class_name(*symbol);
352 }
353 return function;
354}
355
356
357Handle<DescriptorArray> Genesis::ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100358 PrototypePropertyMode prototypeMode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000359 Handle<DescriptorArray> result = Factory::empty_descriptor_array();
360
Steve Block6ded16b2010-05-10 14:33:55 +0100361 if (prototypeMode != DONT_ADD_PROTOTYPE) {
362 PropertyAttributes attributes = static_cast<PropertyAttributes>(
363 DONT_ENUM |
364 DONT_DELETE |
365 (prototypeMode == ADD_READONLY_PROTOTYPE ? READ_ONLY : 0));
366 result =
367 Factory::CopyAppendProxyDescriptor(
368 result,
369 Factory::prototype_symbol(),
370 Factory::NewProxy(&Accessors::FunctionPrototype),
371 attributes);
372 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000373
Steve Block6ded16b2010-05-10 14:33:55 +0100374 PropertyAttributes attributes =
Steve Blocka7e24c12009-10-30 11:49:00 +0000375 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
376 // Add length.
377 result =
378 Factory::CopyAppendProxyDescriptor(
379 result,
380 Factory::length_symbol(),
381 Factory::NewProxy(&Accessors::FunctionLength),
382 attributes);
383
384 // Add name.
385 result =
386 Factory::CopyAppendProxyDescriptor(
387 result,
388 Factory::name_symbol(),
389 Factory::NewProxy(&Accessors::FunctionName),
390 attributes);
391
392 // Add arguments.
393 result =
394 Factory::CopyAppendProxyDescriptor(
395 result,
396 Factory::arguments_symbol(),
397 Factory::NewProxy(&Accessors::FunctionArguments),
398 attributes);
399
400 // Add caller.
401 result =
402 Factory::CopyAppendProxyDescriptor(
403 result,
404 Factory::caller_symbol(),
405 Factory::NewProxy(&Accessors::FunctionCaller),
406 attributes);
407
408 return result;
409}
410
411
Andrei Popescu31002712010-02-23 13:46:05 +0000412Handle<JSFunction> Genesis::CreateEmptyFunction() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000413 // Allocate the map for function instances.
414 Handle<Map> fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
415 global_context()->set_function_instance_map(*fm);
416 // Please note that the prototype property for function instances must be
417 // writable.
418 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +0100419 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000420 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100421 fm->set_function_with_prototype(true);
422
423 // Functions with this map will not have a 'prototype' property, and
424 // can not be used as constructors.
425 Handle<Map> function_without_prototype_map =
426 Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
427 global_context()->set_function_without_prototype_map(
428 *function_without_prototype_map);
429 Handle<DescriptorArray> function_without_prototype_map_descriptors =
430 ComputeFunctionInstanceDescriptor(DONT_ADD_PROTOTYPE);
431 function_without_prototype_map->set_instance_descriptors(
432 *function_without_prototype_map_descriptors);
433 function_without_prototype_map->set_function_with_prototype(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000434
435 // Allocate the function map first and then patch the prototype later
436 fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
437 global_context()->set_function_map(*fm);
Steve Block6ded16b2010-05-10 14:33:55 +0100438 function_map_descriptors =
439 ComputeFunctionInstanceDescriptor(ADD_READONLY_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000440 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100441 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000442
443 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
444
445 { // --- O b j e c t ---
446 Handle<JSFunction> object_fun =
447 Factory::NewFunction(object_name, Factory::null_value());
448 Handle<Map> object_function_map =
449 Factory::NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
450 object_fun->set_initial_map(*object_function_map);
451 object_function_map->set_constructor(*object_fun);
452
453 global_context()->set_object_function(*object_fun);
454
455 // Allocate a new prototype for the object function.
456 Handle<JSObject> prototype = Factory::NewJSObject(Top::object_function(),
457 TENURED);
458
459 global_context()->set_initial_object_prototype(*prototype);
460 SetPrototype(object_fun, prototype);
461 object_function_map->
462 set_instance_descriptors(Heap::empty_descriptor_array());
463 }
464
465 // Allocate the empty function as the prototype for function ECMAScript
466 // 262 15.3.4.
467 Handle<String> symbol = Factory::LookupAsciiSymbol("Empty");
468 Handle<JSFunction> empty_function =
Steve Block6ded16b2010-05-10 14:33:55 +0100469 Factory::NewFunctionWithoutPrototype(symbol);
Steve Blocka7e24c12009-10-30 11:49:00 +0000470
Andrei Popescu31002712010-02-23 13:46:05 +0000471 // --- E m p t y ---
472 Handle<Code> code =
473 Handle<Code>(Builtins::builtin(Builtins::EmptyFunction));
474 empty_function->set_code(*code);
Iain Merrick75681382010-08-19 15:07:18 +0100475 empty_function->shared()->set_code(*code);
Andrei Popescu31002712010-02-23 13:46:05 +0000476 Handle<String> source = Factory::NewStringFromAscii(CStrVector("() {}"));
477 Handle<Script> script = Factory::NewScript(source);
478 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
479 empty_function->shared()->set_script(*script);
480 empty_function->shared()->set_start_position(0);
481 empty_function->shared()->set_end_position(source->length());
482 empty_function->shared()->DontAdaptArguments();
483 global_context()->function_map()->set_prototype(*empty_function);
484 global_context()->function_instance_map()->set_prototype(*empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +0100485 global_context()->function_without_prototype_map()->
486 set_prototype(*empty_function);
Steve Blocka7e24c12009-10-30 11:49:00 +0000487
Andrei Popescu31002712010-02-23 13:46:05 +0000488 // Allocate the function map first and then patch the prototype later
Steve Block6ded16b2010-05-10 14:33:55 +0100489 Handle<Map> empty_fm = Factory::CopyMapDropDescriptors(
490 function_without_prototype_map);
491 empty_fm->set_instance_descriptors(
492 *function_without_prototype_map_descriptors);
Andrei Popescu31002712010-02-23 13:46:05 +0000493 empty_fm->set_prototype(global_context()->object_function()->prototype());
494 empty_function->set_map(*empty_fm);
495 return empty_function;
496}
497
498
499void Genesis::CreateRoots() {
500 // Allocate the global context FixedArray first and then patch the
501 // closure and extension object later (we need the empty function
502 // and the global object, but in order to create those, we need the
503 // global context).
504 global_context_ =
505 Handle<Context>::cast(
506 GlobalHandles::Create(*Factory::NewGlobalContext()));
507 Top::set_context(*global_context());
508
509 // Allocate the message listeners object.
510 {
511 v8::NeanderArray listeners;
512 global_context()->set_message_listeners(*listeners.value());
513 }
514}
515
516
517Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
518 v8::Handle<v8::ObjectTemplate> global_template,
519 Handle<Object> global_object,
520 Handle<GlobalObject>* inner_global_out) {
521 // The argument global_template aka data is an ObjectTemplateInfo.
522 // It has a constructor pointer that points at global_constructor which is a
523 // FunctionTemplateInfo.
524 // The global_constructor is used to create or reinitialize the global_proxy.
525 // The global_constructor also has a prototype_template pointer that points at
526 // js_global_template which is an ObjectTemplateInfo.
527 // That in turn has a constructor pointer that points at
528 // js_global_constructor which is a FunctionTemplateInfo.
529 // js_global_constructor is used to make js_global_function
530 // js_global_function is used to make the new inner_global.
531 //
532 // --- G l o b a l ---
533 // Step 1: Create a fresh inner JSGlobalObject.
534 Handle<JSFunction> js_global_function;
535 Handle<ObjectTemplateInfo> js_global_template;
536 if (!global_template.IsEmpty()) {
537 // Get prototype template of the global_template.
538 Handle<ObjectTemplateInfo> data =
539 v8::Utils::OpenHandle(*global_template);
540 Handle<FunctionTemplateInfo> global_constructor =
541 Handle<FunctionTemplateInfo>(
542 FunctionTemplateInfo::cast(data->constructor()));
543 Handle<Object> proto_template(global_constructor->prototype_template());
544 if (!proto_template->IsUndefined()) {
545 js_global_template =
546 Handle<ObjectTemplateInfo>::cast(proto_template);
547 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000548 }
549
Andrei Popescu31002712010-02-23 13:46:05 +0000550 if (js_global_template.is_null()) {
551 Handle<String> name = Handle<String>(Heap::empty_symbol());
552 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
553 js_global_function =
554 Factory::NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
Andrei Popescu402d9372010-02-26 13:31:12 +0000555 JSGlobalObject::kSize, code, true);
Andrei Popescu31002712010-02-23 13:46:05 +0000556 // Change the constructor property of the prototype of the
557 // hidden global function to refer to the Object function.
558 Handle<JSObject> prototype =
559 Handle<JSObject>(
560 JSObject::cast(js_global_function->instance_prototype()));
561 SetProperty(prototype, Factory::constructor_symbol(),
562 Top::object_function(), NONE);
563 } else {
564 Handle<FunctionTemplateInfo> js_global_constructor(
565 FunctionTemplateInfo::cast(js_global_template->constructor()));
566 js_global_function =
567 Factory::CreateApiFunction(js_global_constructor,
568 Factory::InnerGlobalObject);
Steve Blocka7e24c12009-10-30 11:49:00 +0000569 }
570
Andrei Popescu31002712010-02-23 13:46:05 +0000571 js_global_function->initial_map()->set_is_hidden_prototype();
572 Handle<GlobalObject> inner_global =
573 Factory::NewGlobalObject(js_global_function);
574 if (inner_global_out != NULL) {
575 *inner_global_out = inner_global;
576 }
577
578 // Step 2: create or re-initialize the global proxy object.
579 Handle<JSFunction> global_proxy_function;
580 if (global_template.IsEmpty()) {
581 Handle<String> name = Handle<String>(Heap::empty_symbol());
582 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
583 global_proxy_function =
584 Factory::NewFunction(name, JS_GLOBAL_PROXY_TYPE,
585 JSGlobalProxy::kSize, code, true);
586 } else {
587 Handle<ObjectTemplateInfo> data =
588 v8::Utils::OpenHandle(*global_template);
589 Handle<FunctionTemplateInfo> global_constructor(
590 FunctionTemplateInfo::cast(data->constructor()));
591 global_proxy_function =
592 Factory::CreateApiFunction(global_constructor,
593 Factory::OuterGlobalObject);
594 }
595
596 Handle<String> global_name = Factory::LookupAsciiSymbol("global");
597 global_proxy_function->shared()->set_instance_class_name(*global_name);
598 global_proxy_function->initial_map()->set_is_access_check_needed(true);
599
600 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
601 // Return the global proxy.
602
603 if (global_object.location() != NULL) {
604 ASSERT(global_object->IsJSGlobalProxy());
605 return ReinitializeJSGlobalProxy(
606 global_proxy_function,
607 Handle<JSGlobalProxy>::cast(global_object));
608 } else {
609 return Handle<JSGlobalProxy>::cast(
610 Factory::NewJSObject(global_proxy_function, TENURED));
611 }
612}
613
614
615void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
616 Handle<JSGlobalProxy> global_proxy) {
617 // Set the global context for the global object.
618 inner_global->set_global_context(*global_context());
619 inner_global->set_global_receiver(*global_proxy);
620 global_proxy->set_context(*global_context());
621 global_context()->set_global_proxy(*global_proxy);
622}
623
624
Andrei Popescu402d9372010-02-26 13:31:12 +0000625void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
626 Handle<GlobalObject> inner_global_from_snapshot(
627 GlobalObject::cast(global_context_->extension()));
628 Handle<JSBuiltinsObject> builtins_global(global_context_->builtins());
629 global_context_->set_extension(*inner_global);
630 global_context_->set_global(*inner_global);
631 global_context_->set_security_token(*inner_global);
632 static const PropertyAttributes attributes =
633 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
634 ForceSetProperty(builtins_global,
635 Factory::LookupAsciiSymbol("global"),
636 inner_global,
637 attributes);
638 // Setup the reference from the global object to the builtins object.
639 JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
640 TransferNamedProperties(inner_global_from_snapshot, inner_global);
641 TransferIndexedProperties(inner_global_from_snapshot, inner_global);
642}
643
644
645// This is only called if we are not using snapshots. The equivalent
646// work in the snapshot case is done in HookUpInnerGlobal.
Andrei Popescu31002712010-02-23 13:46:05 +0000647void Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
648 Handle<JSFunction> empty_function) {
649 // --- G l o b a l C o n t e x t ---
650 // Use the empty function as closure (no scope info).
651 global_context()->set_closure(*empty_function);
652 global_context()->set_fcontext(*global_context());
653 global_context()->set_previous(NULL);
654 // Set extension and global object.
655 global_context()->set_extension(*inner_global);
656 global_context()->set_global(*inner_global);
657 // Security setup: Set the security token of the global object to
658 // its the inner global. This makes the security check between two
659 // different contexts fail by default even in case of global
660 // object reinitialization.
661 global_context()->set_security_token(*inner_global);
662
663 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
664 SetProperty(inner_global, object_name, Top::object_function(), DONT_ENUM);
665
Steve Blocka7e24c12009-10-30 11:49:00 +0000666 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
667
668 // Install global Function object
669 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
670 empty_function, Builtins::Illegal, true); // ECMA native.
671
672 { // --- A r r a y ---
673 Handle<JSFunction> array_function =
674 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
675 Top::initial_object_prototype(), Builtins::ArrayCode,
676 true);
677 array_function->shared()->set_construct_stub(
678 Builtins::builtin(Builtins::ArrayConstructCode));
679 array_function->shared()->DontAdaptArguments();
680
681 // This seems a bit hackish, but we need to make sure Array.length
682 // is 1.
683 array_function->shared()->set_length(1);
684 Handle<DescriptorArray> array_descriptors =
685 Factory::CopyAppendProxyDescriptor(
686 Factory::empty_descriptor_array(),
687 Factory::length_symbol(),
688 Factory::NewProxy(&Accessors::ArrayLength),
689 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
690
691 // Cache the fast JavaScript array map
692 global_context()->set_js_array_map(array_function->initial_map());
693 global_context()->js_array_map()->set_instance_descriptors(
694 *array_descriptors);
695 // array_function is used internally. JS code creating array object should
696 // search for the 'Array' property on the global object and use that one
697 // as the constructor. 'Array' property on a global object can be
698 // overwritten by JS code.
699 global_context()->set_array_function(*array_function);
700 }
701
702 { // --- N u m b e r ---
703 Handle<JSFunction> number_fun =
704 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
705 Top::initial_object_prototype(), Builtins::Illegal,
706 true);
707 global_context()->set_number_function(*number_fun);
708 }
709
710 { // --- B o o l e a n ---
711 Handle<JSFunction> boolean_fun =
712 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
713 Top::initial_object_prototype(), Builtins::Illegal,
714 true);
715 global_context()->set_boolean_function(*boolean_fun);
716 }
717
718 { // --- S t r i n g ---
719 Handle<JSFunction> string_fun =
720 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
721 Top::initial_object_prototype(), Builtins::Illegal,
722 true);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100723 string_fun->shared()->set_construct_stub(
724 Builtins::builtin(Builtins::StringConstructCode));
Steve Blocka7e24c12009-10-30 11:49:00 +0000725 global_context()->set_string_function(*string_fun);
726 // Add 'length' property to strings.
727 Handle<DescriptorArray> string_descriptors =
728 Factory::CopyAppendProxyDescriptor(
729 Factory::empty_descriptor_array(),
730 Factory::length_symbol(),
731 Factory::NewProxy(&Accessors::StringLength),
732 static_cast<PropertyAttributes>(DONT_ENUM |
733 DONT_DELETE |
734 READ_ONLY));
735
736 Handle<Map> string_map =
737 Handle<Map>(global_context()->string_function()->initial_map());
738 string_map->set_instance_descriptors(*string_descriptors);
739 }
740
741 { // --- D a t e ---
742 // Builtin functions for Date.prototype.
743 Handle<JSFunction> date_fun =
744 InstallFunction(global, "Date", JS_VALUE_TYPE, JSValue::kSize,
745 Top::initial_object_prototype(), Builtins::Illegal,
746 true);
747
748 global_context()->set_date_function(*date_fun);
749 }
750
751
752 { // -- R e g E x p
753 // Builtin functions for RegExp.prototype.
754 Handle<JSFunction> regexp_fun =
755 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
756 Top::initial_object_prototype(), Builtins::Illegal,
757 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000758 global_context()->set_regexp_function(*regexp_fun);
Steve Block6ded16b2010-05-10 14:33:55 +0100759
760 ASSERT(regexp_fun->has_initial_map());
761 Handle<Map> initial_map(regexp_fun->initial_map());
762
763 ASSERT_EQ(0, initial_map->inobject_properties());
764
765 Handle<DescriptorArray> descriptors = Factory::NewDescriptorArray(5);
766 PropertyAttributes final =
767 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
768 int enum_index = 0;
769 {
770 // ECMA-262, section 15.10.7.1.
771 FieldDescriptor field(Heap::source_symbol(),
772 JSRegExp::kSourceFieldIndex,
773 final,
774 enum_index++);
775 descriptors->Set(0, &field);
776 }
777 {
778 // ECMA-262, section 15.10.7.2.
779 FieldDescriptor field(Heap::global_symbol(),
780 JSRegExp::kGlobalFieldIndex,
781 final,
782 enum_index++);
783 descriptors->Set(1, &field);
784 }
785 {
786 // ECMA-262, section 15.10.7.3.
787 FieldDescriptor field(Heap::ignore_case_symbol(),
788 JSRegExp::kIgnoreCaseFieldIndex,
789 final,
790 enum_index++);
791 descriptors->Set(2, &field);
792 }
793 {
794 // ECMA-262, section 15.10.7.4.
795 FieldDescriptor field(Heap::multiline_symbol(),
796 JSRegExp::kMultilineFieldIndex,
797 final,
798 enum_index++);
799 descriptors->Set(3, &field);
800 }
801 {
802 // ECMA-262, section 15.10.7.5.
803 PropertyAttributes writable =
804 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
805 FieldDescriptor field(Heap::last_index_symbol(),
806 JSRegExp::kLastIndexFieldIndex,
807 writable,
808 enum_index++);
809 descriptors->Set(4, &field);
810 }
811 descriptors->SetNextEnumerationIndex(enum_index);
812 descriptors->Sort();
813
814 initial_map->set_inobject_properties(5);
815 initial_map->set_pre_allocated_property_fields(5);
816 initial_map->set_unused_property_fields(0);
817 initial_map->set_instance_size(
818 initial_map->instance_size() + 5 * kPointerSize);
819 initial_map->set_instance_descriptors(*descriptors);
Iain Merrick75681382010-08-19 15:07:18 +0100820 initial_map->set_visitor_id(StaticVisitorBase::GetVisitorId(*initial_map));
Steve Blocka7e24c12009-10-30 11:49:00 +0000821 }
822
823 { // -- J S O N
824 Handle<String> name = Factory::NewStringFromAscii(CStrVector("JSON"));
825 Handle<JSFunction> cons = Factory::NewFunction(
826 name,
827 Factory::the_hole_value());
828 cons->SetInstancePrototype(global_context()->initial_object_prototype());
829 cons->SetInstanceClassName(*name);
830 Handle<JSObject> json_object = Factory::NewJSObject(cons, TENURED);
831 ASSERT(json_object->IsJSObject());
832 SetProperty(global, name, json_object, DONT_ENUM);
833 global_context()->set_json_object(*json_object);
834 }
835
836 { // --- arguments_boilerplate_
837 // Make sure we can recognize argument objects at runtime.
838 // This is done by introducing an anonymous function with
839 // class_name equals 'Arguments'.
840 Handle<String> symbol = Factory::LookupAsciiSymbol("Arguments");
841 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
842 Handle<JSObject> prototype =
843 Handle<JSObject>(
844 JSObject::cast(global_context()->object_function()->prototype()));
845
846 Handle<JSFunction> function =
847 Factory::NewFunctionWithPrototype(symbol,
848 JS_OBJECT_TYPE,
849 JSObject::kHeaderSize,
850 prototype,
851 code,
852 false);
853 ASSERT(!function->has_initial_map());
854 function->shared()->set_instance_class_name(*symbol);
855 function->shared()->set_expected_nof_properties(2);
856 Handle<JSObject> result = Factory::NewJSObject(function);
857
858 global_context()->set_arguments_boilerplate(*result);
859 // Note: callee must be added as the first property and
860 // length must be added as the second property.
861 SetProperty(result, Factory::callee_symbol(),
862 Factory::undefined_value(),
863 DONT_ENUM);
864 SetProperty(result, Factory::length_symbol(),
865 Factory::undefined_value(),
866 DONT_ENUM);
867
868#ifdef DEBUG
869 LookupResult lookup;
870 result->LocalLookup(Heap::callee_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000871 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000872 ASSERT(lookup.GetFieldIndex() == Heap::arguments_callee_index);
873
874 result->LocalLookup(Heap::length_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000875 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000876 ASSERT(lookup.GetFieldIndex() == Heap::arguments_length_index);
877
878 ASSERT(result->map()->inobject_properties() > Heap::arguments_callee_index);
879 ASSERT(result->map()->inobject_properties() > Heap::arguments_length_index);
880
881 // Check the state of the object.
882 ASSERT(result->HasFastProperties());
883 ASSERT(result->HasFastElements());
884#endif
885 }
886
887 { // --- context extension
888 // Create a function for the context extension objects.
889 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
890 Handle<JSFunction> context_extension_fun =
891 Factory::NewFunction(Factory::empty_symbol(),
892 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
893 JSObject::kHeaderSize,
894 code,
895 true);
896
897 Handle<String> name = Factory::LookupAsciiSymbol("context_extension");
898 context_extension_fun->shared()->set_instance_class_name(*name);
899 global_context()->set_context_extension_function(*context_extension_fun);
900 }
901
902
903 {
904 // Setup the call-as-function delegate.
905 Handle<Code> code =
906 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsFunction));
907 Handle<JSFunction> delegate =
908 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
909 JSObject::kHeaderSize, code, true);
910 global_context()->set_call_as_function_delegate(*delegate);
911 delegate->shared()->DontAdaptArguments();
912 }
913
914 {
915 // Setup the call-as-constructor delegate.
916 Handle<Code> code =
917 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsConstructor));
918 Handle<JSFunction> delegate =
919 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
920 JSObject::kHeaderSize, code, true);
921 global_context()->set_call_as_constructor_delegate(*delegate);
922 delegate->shared()->DontAdaptArguments();
923 }
924
Steve Blocka7e24c12009-10-30 11:49:00 +0000925 // Initialize the out of memory slot.
926 global_context()->set_out_of_memory(Heap::false_value());
927
928 // Initialize the data slot.
929 global_context()->set_data(Heap::undefined_value());
930}
931
932
933bool Genesis::CompileBuiltin(int index) {
934 Vector<const char> name = Natives::GetScriptName(index);
935 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
936 return CompileNative(name, source_code);
937}
938
939
940bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
941 HandleScope scope;
942#ifdef ENABLE_DEBUGGER_SUPPORT
943 Debugger::set_compiling_natives(true);
944#endif
Andrei Popescu31002712010-02-23 13:46:05 +0000945 bool result = CompileScriptCached(name,
946 source,
947 NULL,
948 NULL,
949 Handle<Context>(Top::context()),
950 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000951 ASSERT(Top::has_pending_exception() != result);
952 if (!result) Top::clear_pending_exception();
953#ifdef ENABLE_DEBUGGER_SUPPORT
954 Debugger::set_compiling_natives(false);
955#endif
956 return result;
957}
958
959
960bool Genesis::CompileScriptCached(Vector<const char> name,
961 Handle<String> source,
962 SourceCodeCache* cache,
963 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000964 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000965 bool use_runtime_context) {
966 HandleScope scope;
Steve Block6ded16b2010-05-10 14:33:55 +0100967 Handle<SharedFunctionInfo> function_info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000968
969 // If we can't find the function in the cache, we compile a new
970 // function and insert it into the cache.
Steve Block6ded16b2010-05-10 14:33:55 +0100971 if (cache == NULL || !cache->Lookup(name, &function_info)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000972 ASSERT(source->IsAsciiRepresentation());
973 Handle<String> script_name = Factory::NewStringFromUtf8(name);
Steve Block6ded16b2010-05-10 14:33:55 +0100974 function_info = Compiler::Compile(
Andrei Popescu31002712010-02-23 13:46:05 +0000975 source,
976 script_name,
977 0,
978 0,
979 extension,
980 NULL,
Andrei Popescu402d9372010-02-26 13:31:12 +0000981 Handle<String>::null(),
Andrei Popescu31002712010-02-23 13:46:05 +0000982 use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
Steve Block6ded16b2010-05-10 14:33:55 +0100983 if (function_info.is_null()) return false;
984 if (cache != NULL) cache->Add(name, function_info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000985 }
986
987 // Setup the function context. Conceptually, we should clone the
988 // function before overwriting the context but since we're in a
989 // single-threaded environment it is not strictly necessary.
Andrei Popescu31002712010-02-23 13:46:05 +0000990 ASSERT(top_context->IsGlobalContext());
Steve Blocka7e24c12009-10-30 11:49:00 +0000991 Handle<Context> context =
992 Handle<Context>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +0000993 ? Handle<Context>(top_context->runtime_context())
994 : top_context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000995 Handle<JSFunction> fun =
Steve Block6ded16b2010-05-10 14:33:55 +0100996 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000997
Leon Clarke4515c472010-02-03 11:58:03 +0000998 // Call function using either the runtime object or the global
Steve Blocka7e24c12009-10-30 11:49:00 +0000999 // object as the receiver. Provide no parameters.
1000 Handle<Object> receiver =
1001 Handle<Object>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +00001002 ? top_context->builtins()
1003 : top_context->global());
Steve Blocka7e24c12009-10-30 11:49:00 +00001004 bool has_pending_exception;
1005 Handle<Object> result =
1006 Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1007 if (has_pending_exception) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001008 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001009}
1010
1011
1012#define INSTALL_NATIVE(Type, name, var) \
1013 Handle<String> var##_name = Factory::LookupAsciiSymbol(name); \
1014 global_context()->set_##var(Type::cast(global_context()-> \
1015 builtins()-> \
1016 GetProperty(*var##_name)));
1017
1018void Genesis::InstallNativeFunctions() {
1019 HandleScope scope;
1020 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1021 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1022 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1023 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1024 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1025 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1026 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1027 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
Leon Clarkee46be812010-01-19 14:06:41 +00001028 INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
Steve Blocka7e24c12009-10-30 11:49:00 +00001029 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1030 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1031 configure_instance_fun);
1032 INSTALL_NATIVE(JSFunction, "MakeMessage", make_message_fun);
1033 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1034 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1035}
1036
1037#undef INSTALL_NATIVE
1038
1039
1040bool Genesis::InstallNatives() {
1041 HandleScope scope;
1042
1043 // Create a function for the builtins object. Allocate space for the
1044 // JavaScript builtins, a reference to the builtins object
1045 // (itself) and a reference to the global_context directly in the object.
1046 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
1047 Handle<JSFunction> builtins_fun =
1048 Factory::NewFunction(Factory::empty_symbol(), JS_BUILTINS_OBJECT_TYPE,
1049 JSBuiltinsObject::kSize, code, true);
1050
1051 Handle<String> name = Factory::LookupAsciiSymbol("builtins");
1052 builtins_fun->shared()->set_instance_class_name(*name);
1053
1054 // Allocate the builtins object.
1055 Handle<JSBuiltinsObject> builtins =
1056 Handle<JSBuiltinsObject>::cast(Factory::NewGlobalObject(builtins_fun));
1057 builtins->set_builtins(*builtins);
1058 builtins->set_global_context(*global_context());
1059 builtins->set_global_receiver(*builtins);
1060
1061 // Setup the 'global' properties of the builtins object. The
1062 // 'global' property that refers to the global object is the only
1063 // way to get from code running in the builtins context to the
1064 // global object.
1065 static const PropertyAttributes attributes =
1066 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1067 SetProperty(builtins, Factory::LookupAsciiSymbol("global"),
1068 Handle<Object>(global_context()->global()), attributes);
1069
1070 // Setup the reference from the global object to the builtins object.
1071 JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
1072
1073 // Create a bridge function that has context in the global context.
1074 Handle<JSFunction> bridge =
1075 Factory::NewFunction(Factory::empty_symbol(), Factory::undefined_value());
1076 ASSERT(bridge->context() == *Top::global_context());
1077
1078 // Allocate the builtins context.
1079 Handle<Context> context =
1080 Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1081 context->set_global(*builtins); // override builtins global object
1082
1083 global_context()->set_runtime_context(*context);
1084
1085 { // -- S c r i p t
1086 // Builtin functions for Script.
1087 Handle<JSFunction> script_fun =
1088 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1089 Top::initial_object_prototype(), Builtins::Illegal,
1090 false);
1091 Handle<JSObject> prototype =
1092 Factory::NewJSObject(Top::object_function(), TENURED);
1093 SetPrototype(script_fun, prototype);
1094 global_context()->set_script_function(*script_fun);
1095
1096 // Add 'source' and 'data' property to scripts.
1097 PropertyAttributes common_attributes =
1098 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1099 Handle<Proxy> proxy_source = Factory::NewProxy(&Accessors::ScriptSource);
1100 Handle<DescriptorArray> script_descriptors =
1101 Factory::CopyAppendProxyDescriptor(
1102 Factory::empty_descriptor_array(),
1103 Factory::LookupAsciiSymbol("source"),
1104 proxy_source,
1105 common_attributes);
1106 Handle<Proxy> proxy_name = Factory::NewProxy(&Accessors::ScriptName);
1107 script_descriptors =
1108 Factory::CopyAppendProxyDescriptor(
1109 script_descriptors,
1110 Factory::LookupAsciiSymbol("name"),
1111 proxy_name,
1112 common_attributes);
1113 Handle<Proxy> proxy_id = Factory::NewProxy(&Accessors::ScriptId);
1114 script_descriptors =
1115 Factory::CopyAppendProxyDescriptor(
1116 script_descriptors,
1117 Factory::LookupAsciiSymbol("id"),
1118 proxy_id,
1119 common_attributes);
1120 Handle<Proxy> proxy_line_offset =
1121 Factory::NewProxy(&Accessors::ScriptLineOffset);
1122 script_descriptors =
1123 Factory::CopyAppendProxyDescriptor(
1124 script_descriptors,
1125 Factory::LookupAsciiSymbol("line_offset"),
1126 proxy_line_offset,
1127 common_attributes);
1128 Handle<Proxy> proxy_column_offset =
1129 Factory::NewProxy(&Accessors::ScriptColumnOffset);
1130 script_descriptors =
1131 Factory::CopyAppendProxyDescriptor(
1132 script_descriptors,
1133 Factory::LookupAsciiSymbol("column_offset"),
1134 proxy_column_offset,
1135 common_attributes);
1136 Handle<Proxy> proxy_data = Factory::NewProxy(&Accessors::ScriptData);
1137 script_descriptors =
1138 Factory::CopyAppendProxyDescriptor(
1139 script_descriptors,
1140 Factory::LookupAsciiSymbol("data"),
1141 proxy_data,
1142 common_attributes);
1143 Handle<Proxy> proxy_type = Factory::NewProxy(&Accessors::ScriptType);
1144 script_descriptors =
1145 Factory::CopyAppendProxyDescriptor(
1146 script_descriptors,
1147 Factory::LookupAsciiSymbol("type"),
1148 proxy_type,
1149 common_attributes);
1150 Handle<Proxy> proxy_compilation_type =
1151 Factory::NewProxy(&Accessors::ScriptCompilationType);
1152 script_descriptors =
1153 Factory::CopyAppendProxyDescriptor(
1154 script_descriptors,
1155 Factory::LookupAsciiSymbol("compilation_type"),
1156 proxy_compilation_type,
1157 common_attributes);
1158 Handle<Proxy> proxy_line_ends =
1159 Factory::NewProxy(&Accessors::ScriptLineEnds);
1160 script_descriptors =
1161 Factory::CopyAppendProxyDescriptor(
1162 script_descriptors,
1163 Factory::LookupAsciiSymbol("line_ends"),
1164 proxy_line_ends,
1165 common_attributes);
1166 Handle<Proxy> proxy_context_data =
1167 Factory::NewProxy(&Accessors::ScriptContextData);
1168 script_descriptors =
1169 Factory::CopyAppendProxyDescriptor(
1170 script_descriptors,
1171 Factory::LookupAsciiSymbol("context_data"),
1172 proxy_context_data,
1173 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001174 Handle<Proxy> proxy_eval_from_script =
1175 Factory::NewProxy(&Accessors::ScriptEvalFromScript);
Steve Blocka7e24c12009-10-30 11:49:00 +00001176 script_descriptors =
1177 Factory::CopyAppendProxyDescriptor(
1178 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001179 Factory::LookupAsciiSymbol("eval_from_script"),
1180 proxy_eval_from_script,
Steve Blocka7e24c12009-10-30 11:49:00 +00001181 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001182 Handle<Proxy> proxy_eval_from_script_position =
1183 Factory::NewProxy(&Accessors::ScriptEvalFromScriptPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +00001184 script_descriptors =
1185 Factory::CopyAppendProxyDescriptor(
1186 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001187 Factory::LookupAsciiSymbol("eval_from_script_position"),
1188 proxy_eval_from_script_position,
1189 common_attributes);
1190 Handle<Proxy> proxy_eval_from_function_name =
1191 Factory::NewProxy(&Accessors::ScriptEvalFromFunctionName);
1192 script_descriptors =
1193 Factory::CopyAppendProxyDescriptor(
1194 script_descriptors,
1195 Factory::LookupAsciiSymbol("eval_from_function_name"),
1196 proxy_eval_from_function_name,
Steve Blocka7e24c12009-10-30 11:49:00 +00001197 common_attributes);
1198
1199 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1200 script_map->set_instance_descriptors(*script_descriptors);
1201
1202 // Allocate the empty script.
1203 Handle<Script> script = Factory::NewScript(Factory::empty_string());
1204 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Andrei Popescu31002712010-02-23 13:46:05 +00001205 Heap::public_set_empty_script(*script);
Steve Blocka7e24c12009-10-30 11:49:00 +00001206 }
Steve Block6ded16b2010-05-10 14:33:55 +01001207 {
1208 // Builtin function for OpaqueReference -- a JSValue-based object,
1209 // that keeps its field isolated from JavaScript code. It may store
1210 // objects, that JavaScript code may not access.
1211 Handle<JSFunction> opaque_reference_fun =
1212 InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1213 JSValue::kSize, Top::initial_object_prototype(),
1214 Builtins::Illegal, false);
1215 Handle<JSObject> prototype =
1216 Factory::NewJSObject(Top::object_function(), TENURED);
1217 SetPrototype(opaque_reference_fun, prototype);
1218 global_context()->set_opaque_reference_function(*opaque_reference_fun);
1219 }
1220
1221 if (FLAG_disable_native_files) {
1222 PrintF("Warning: Running without installed natives!\n");
1223 return true;
1224 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001225
Andrei Popescu31002712010-02-23 13:46:05 +00001226 // Install natives.
1227 for (int i = Natives::GetDebuggerCount();
1228 i < Natives::GetBuiltinsCount();
1229 i++) {
1230 Vector<const char> name = Natives::GetScriptName(i);
1231 if (!CompileBuiltin(i)) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001232 // TODO(ager): We really only need to install the JS builtin
1233 // functions on the builtins object after compiling and running
1234 // runtime.js.
1235 if (!InstallJSBuiltins(builtins)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001236 }
1237
1238 InstallNativeFunctions();
1239
Iain Merrick75681382010-08-19 15:07:18 +01001240 // Store the map for the string prototype after the natives has been compiled
1241 // and the String function has been setup.
1242 Handle<JSFunction> string_function(global_context()->string_function());
1243 ASSERT(JSObject::cast(
1244 string_function->initial_map()->prototype())->HasFastProperties());
1245 global_context()->set_string_function_prototype_map(
1246 HeapObject::cast(string_function->initial_map()->prototype())->map());
1247
Kristian Monsen25f61362010-05-21 11:50:48 +01001248 InstallCustomCallGenerators();
1249
Steve Blocka7e24c12009-10-30 11:49:00 +00001250 // Install Function.prototype.call and apply.
1251 { Handle<String> key = Factory::function_class_symbol();
1252 Handle<JSFunction> function =
1253 Handle<JSFunction>::cast(GetProperty(Top::global(), key));
1254 Handle<JSObject> proto =
1255 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1256
1257 // Install the call and the apply functions.
1258 Handle<JSFunction> call =
1259 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001260 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001261 Builtins::FunctionCall,
1262 false);
1263 Handle<JSFunction> apply =
1264 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001265 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001266 Builtins::FunctionApply,
1267 false);
1268
1269 // Make sure that Function.prototype.call appears to be compiled.
1270 // The code will never be called, but inline caching for call will
1271 // only work if it appears to be compiled.
1272 call->shared()->DontAdaptArguments();
1273 ASSERT(call->is_compiled());
1274
1275 // Set the expected parameters for apply to 2; required by builtin.
1276 apply->shared()->set_formal_parameter_count(2);
1277
1278 // Set the lengths for the functions to satisfy ECMA-262.
1279 call->shared()->set_length(1);
1280 apply->shared()->set_length(2);
1281 }
1282
Steve Block6ded16b2010-05-10 14:33:55 +01001283 // Create a constructor for RegExp results (a variant of Array that
1284 // predefines the two properties index and match).
1285 {
1286 // RegExpResult initial map.
1287
1288 // Find global.Array.prototype to inherit from.
1289 Handle<JSFunction> array_constructor(global_context()->array_function());
1290 Handle<JSObject> array_prototype(
1291 JSObject::cast(array_constructor->instance_prototype()));
1292
1293 // Add initial map.
1294 Handle<Map> initial_map =
1295 Factory::NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1296 initial_map->set_constructor(*array_constructor);
1297
1298 // Set prototype on map.
1299 initial_map->set_non_instance_prototype(false);
1300 initial_map->set_prototype(*array_prototype);
1301
1302 // Update map with length accessor from Array and add "index" and "input".
1303 Handle<Map> array_map(global_context()->js_array_map());
1304 Handle<DescriptorArray> array_descriptors(
1305 array_map->instance_descriptors());
1306 ASSERT_EQ(1, array_descriptors->number_of_descriptors());
1307
1308 Handle<DescriptorArray> reresult_descriptors =
1309 Factory::NewDescriptorArray(3);
1310
1311 reresult_descriptors->CopyFrom(0, *array_descriptors, 0);
1312
1313 int enum_index = 0;
1314 {
1315 FieldDescriptor index_field(Heap::index_symbol(),
1316 JSRegExpResult::kIndexIndex,
1317 NONE,
1318 enum_index++);
1319 reresult_descriptors->Set(1, &index_field);
1320 }
1321
1322 {
1323 FieldDescriptor input_field(Heap::input_symbol(),
1324 JSRegExpResult::kInputIndex,
1325 NONE,
1326 enum_index++);
1327 reresult_descriptors->Set(2, &input_field);
1328 }
1329 reresult_descriptors->Sort();
1330
1331 initial_map->set_inobject_properties(2);
1332 initial_map->set_pre_allocated_property_fields(2);
1333 initial_map->set_unused_property_fields(0);
1334 initial_map->set_instance_descriptors(*reresult_descriptors);
1335
1336 global_context()->set_regexp_result_map(*initial_map);
1337 }
1338
Steve Blocka7e24c12009-10-30 11:49:00 +00001339#ifdef DEBUG
1340 builtins->Verify();
1341#endif
Andrei Popescu31002712010-02-23 13:46:05 +00001342
Steve Blocka7e24c12009-10-30 11:49:00 +00001343 return true;
1344}
1345
1346
Kristian Monsen25f61362010-05-21 11:50:48 +01001347static void InstallCustomCallGenerator(Handle<JSFunction> holder_function,
1348 const char* function_name,
1349 int id) {
1350 Handle<JSObject> proto(JSObject::cast(holder_function->instance_prototype()));
1351 Handle<String> name = Factory::LookupAsciiSymbol(function_name);
1352 Handle<JSFunction> function(JSFunction::cast(proto->GetProperty(*name)));
1353 function->shared()->set_function_data(Smi::FromInt(id));
1354}
1355
1356
1357void Genesis::InstallCustomCallGenerators() {
1358 HandleScope scope;
1359#define INSTALL_CALL_GENERATOR(holder_fun, fun_name, name) \
1360 { \
1361 Handle<JSFunction> holder(global_context()->holder_fun##_function()); \
1362 const int id = CallStubCompiler::k##name##CallGenerator; \
1363 InstallCustomCallGenerator(holder, #fun_name, id); \
1364 }
1365 CUSTOM_CALL_IC_GENERATORS(INSTALL_CALL_GENERATOR)
1366#undef INSTALL_CALL_GENERATOR
1367}
1368
1369
Steve Block6ded16b2010-05-10 14:33:55 +01001370// Do not forget to update macros.py with named constant
1371// of cache id.
1372#define JSFUNCTION_RESULT_CACHE_LIST(F) \
1373 F(16, global_context()->regexp_function())
1374
1375
1376static FixedArray* CreateCache(int size, JSFunction* factory) {
1377 // Caches are supposed to live for a long time, allocate in old space.
1378 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1379 // Cannot use cast as object is not fully initialized yet.
1380 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1381 *Factory::NewFixedArrayWithHoles(array_size, TENURED));
1382 cache->set(JSFunctionResultCache::kFactoryIndex, factory);
1383 cache->MakeZeroSize();
1384 return cache;
1385}
1386
1387
1388void Genesis::InstallJSFunctionResultCaches() {
1389 const int kNumberOfCaches = 0 +
1390#define F(size, func) + 1
1391 JSFUNCTION_RESULT_CACHE_LIST(F)
1392#undef F
1393 ;
1394
1395 Handle<FixedArray> caches = Factory::NewFixedArray(kNumberOfCaches, TENURED);
1396
1397 int index = 0;
1398#define F(size, func) caches->set(index++, CreateCache(size, func));
1399 JSFUNCTION_RESULT_CACHE_LIST(F)
1400#undef F
1401
1402 global_context()->set_jsfunction_result_caches(*caches);
1403}
1404
1405
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001406void Genesis::InitializeNormalizedMapCaches() {
1407 Handle<FixedArray> array(
1408 Factory::NewFixedArray(NormalizedMapCache::kEntries, TENURED));
1409 global_context()->set_normalized_map_cache(NormalizedMapCache::cast(*array));
1410}
1411
1412
Andrei Popescu31002712010-02-23 13:46:05 +00001413int BootstrapperActive::nesting_ = 0;
1414
1415
1416bool Bootstrapper::InstallExtensions(Handle<Context> global_context,
1417 v8::ExtensionConfiguration* extensions) {
1418 BootstrapperActive active;
1419 SaveContext saved_context;
1420 Top::set_context(*global_context);
1421 if (!Genesis::InstallExtensions(global_context, extensions)) return false;
1422 Genesis::InstallSpecialObjects(global_context);
1423 return true;
1424}
1425
1426
1427void Genesis::InstallSpecialObjects(Handle<Context> global_context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001428 HandleScope scope;
1429 Handle<JSGlobalObject> js_global(
Andrei Popescu31002712010-02-23 13:46:05 +00001430 JSGlobalObject::cast(global_context->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001431 // Expose the natives in global if a name for it is specified.
1432 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1433 Handle<String> natives_string =
1434 Factory::LookupAsciiSymbol(FLAG_expose_natives_as);
1435 SetProperty(js_global, natives_string,
1436 Handle<JSObject>(js_global->builtins()), DONT_ENUM);
1437 }
1438
1439 Handle<Object> Error = GetProperty(js_global, "Error");
1440 if (Error->IsJSObject()) {
1441 Handle<String> name = Factory::LookupAsciiSymbol("stackTraceLimit");
1442 SetProperty(Handle<JSObject>::cast(Error),
1443 name,
1444 Handle<Smi>(Smi::FromInt(FLAG_stack_trace_limit)),
1445 NONE);
1446 }
1447
1448#ifdef ENABLE_DEBUGGER_SUPPORT
1449 // Expose the debug global object in global if a name for it is specified.
1450 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1451 // If loading fails we just bail out without installing the
1452 // debugger but without tanking the whole context.
Andrei Popescu31002712010-02-23 13:46:05 +00001453 if (!Debug::Load()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001454 // Set the security token for the debugger context to the same as
1455 // the shell global context to allow calling between these (otherwise
1456 // exposing debug global object doesn't make much sense).
1457 Debug::debug_context()->set_security_token(
Andrei Popescu31002712010-02-23 13:46:05 +00001458 global_context->security_token());
Steve Blocka7e24c12009-10-30 11:49:00 +00001459
1460 Handle<String> debug_string =
1461 Factory::LookupAsciiSymbol(FLAG_expose_debug_as);
1462 SetProperty(js_global, debug_string,
1463 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM);
1464 }
1465#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001466}
1467
1468
Andrei Popescu31002712010-02-23 13:46:05 +00001469bool Genesis::InstallExtensions(Handle<Context> global_context,
1470 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001471 // Clear coloring of extension list
1472 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1473 while (current != NULL) {
1474 current->set_state(v8::UNVISITED);
1475 current = current->next();
1476 }
Andrei Popescu31002712010-02-23 13:46:05 +00001477 // Install auto extensions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001478 current = v8::RegisteredExtension::first_extension();
1479 while (current != NULL) {
1480 if (current->extension()->auto_enable())
1481 InstallExtension(current);
1482 current = current->next();
1483 }
1484
1485 if (FLAG_expose_gc) InstallExtension("v8/gc");
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001486 if (FLAG_expose_externalize_string) InstallExtension("v8/externalize");
Steve Blocka7e24c12009-10-30 11:49:00 +00001487
1488 if (extensions == NULL) return true;
1489 // Install required extensions
1490 int count = v8::ImplementationUtilities::GetNameCount(extensions);
1491 const char** names = v8::ImplementationUtilities::GetNames(extensions);
1492 for (int i = 0; i < count; i++) {
1493 if (!InstallExtension(names[i]))
1494 return false;
1495 }
1496
1497 return true;
1498}
1499
1500
1501// Installs a named extension. This methods is unoptimized and does
1502// not scale well if we want to support a large number of extensions.
1503bool Genesis::InstallExtension(const char* name) {
1504 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1505 // Loop until we find the relevant extension
1506 while (current != NULL) {
1507 if (strcmp(name, current->extension()->name()) == 0) break;
1508 current = current->next();
1509 }
1510 // Didn't find the extension; fail.
1511 if (current == NULL) {
1512 v8::Utils::ReportApiFailure(
1513 "v8::Context::New()", "Cannot find required extension");
1514 return false;
1515 }
1516 return InstallExtension(current);
1517}
1518
1519
1520bool Genesis::InstallExtension(v8::RegisteredExtension* current) {
1521 HandleScope scope;
1522
1523 if (current->state() == v8::INSTALLED) return true;
1524 // The current node has already been visited so there must be a
1525 // cycle in the dependency graph; fail.
1526 if (current->state() == v8::VISITED) {
1527 v8::Utils::ReportApiFailure(
1528 "v8::Context::New()", "Circular extension dependency");
1529 return false;
1530 }
1531 ASSERT(current->state() == v8::UNVISITED);
1532 current->set_state(v8::VISITED);
1533 v8::Extension* extension = current->extension();
1534 // Install the extension's dependencies
1535 for (int i = 0; i < extension->dependency_count(); i++) {
1536 if (!InstallExtension(extension->dependencies()[i])) return false;
1537 }
1538 Vector<const char> source = CStrVector(extension->source());
1539 Handle<String> source_code = Factory::NewStringFromAscii(source);
1540 bool result = CompileScriptCached(CStrVector(extension->name()),
1541 source_code,
Andrei Popescu31002712010-02-23 13:46:05 +00001542 &extensions_cache,
1543 extension,
1544 Handle<Context>(Top::context()),
Steve Blocka7e24c12009-10-30 11:49:00 +00001545 false);
1546 ASSERT(Top::has_pending_exception() != result);
1547 if (!result) {
1548 Top::clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001549 }
1550 current->set_state(v8::INSTALLED);
1551 return result;
1552}
1553
1554
Andrei Popescu402d9372010-02-26 13:31:12 +00001555bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
1556 HandleScope scope;
1557 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
1558 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
1559 Handle<String> name = Factory::LookupAsciiSymbol(Builtins::GetName(id));
1560 Handle<JSFunction> function
1561 = Handle<JSFunction>(JSFunction::cast(builtins->GetProperty(*name)));
1562 builtins->set_javascript_builtin(id, *function);
1563 Handle<SharedFunctionInfo> shared
1564 = Handle<SharedFunctionInfo>(function->shared());
1565 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Iain Merrick75681382010-08-19 15:07:18 +01001566 // Set the code object on the function object.
1567 function->set_code(function->shared()->code());
Steve Block6ded16b2010-05-10 14:33:55 +01001568 builtins->set_javascript_builtin_code(id, shared->code());
Andrei Popescu402d9372010-02-26 13:31:12 +00001569 }
1570 return true;
Andrei Popescu31002712010-02-23 13:46:05 +00001571}
1572
1573
Steve Blocka7e24c12009-10-30 11:49:00 +00001574bool Genesis::ConfigureGlobalObjects(
1575 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
1576 Handle<JSObject> global_proxy(
1577 JSObject::cast(global_context()->global_proxy()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001578 Handle<JSObject> inner_global(JSObject::cast(global_context()->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001579
1580 if (!global_proxy_template.IsEmpty()) {
1581 // Configure the global proxy object.
1582 Handle<ObjectTemplateInfo> proxy_data =
1583 v8::Utils::OpenHandle(*global_proxy_template);
1584 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
1585
1586 // Configure the inner global object.
1587 Handle<FunctionTemplateInfo> proxy_constructor(
1588 FunctionTemplateInfo::cast(proxy_data->constructor()));
1589 if (!proxy_constructor->prototype_template()->IsUndefined()) {
1590 Handle<ObjectTemplateInfo> inner_data(
1591 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001592 if (!ConfigureApiObject(inner_global, inner_data)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001593 }
1594 }
1595
Andrei Popescu402d9372010-02-26 13:31:12 +00001596 SetObjectPrototype(global_proxy, inner_global);
Steve Blocka7e24c12009-10-30 11:49:00 +00001597 return true;
1598}
1599
1600
1601bool Genesis::ConfigureApiObject(Handle<JSObject> object,
1602 Handle<ObjectTemplateInfo> object_template) {
1603 ASSERT(!object_template.is_null());
1604 ASSERT(object->IsInstanceOf(
1605 FunctionTemplateInfo::cast(object_template->constructor())));
1606
1607 bool pending_exception = false;
1608 Handle<JSObject> obj =
1609 Execution::InstantiateObject(object_template, &pending_exception);
1610 if (pending_exception) {
1611 ASSERT(Top::has_pending_exception());
1612 Top::clear_pending_exception();
1613 return false;
1614 }
1615 TransferObject(obj, object);
1616 return true;
1617}
1618
1619
1620void Genesis::TransferNamedProperties(Handle<JSObject> from,
1621 Handle<JSObject> to) {
1622 if (from->HasFastProperties()) {
1623 Handle<DescriptorArray> descs =
1624 Handle<DescriptorArray>(from->map()->instance_descriptors());
1625 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1626 PropertyDetails details = PropertyDetails(descs->GetDetails(i));
1627 switch (details.type()) {
1628 case FIELD: {
1629 HandleScope inner;
1630 Handle<String> key = Handle<String>(descs->GetKey(i));
1631 int index = descs->GetFieldIndex(i);
1632 Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
1633 SetProperty(to, key, value, details.attributes());
1634 break;
1635 }
1636 case CONSTANT_FUNCTION: {
1637 HandleScope inner;
1638 Handle<String> key = Handle<String>(descs->GetKey(i));
1639 Handle<JSFunction> fun =
1640 Handle<JSFunction>(descs->GetConstantFunction(i));
1641 SetProperty(to, key, fun, details.attributes());
1642 break;
1643 }
1644 case CALLBACKS: {
1645 LookupResult result;
1646 to->LocalLookup(descs->GetKey(i), &result);
1647 // If the property is already there we skip it
Andrei Popescu402d9372010-02-26 13:31:12 +00001648 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001649 HandleScope inner;
Andrei Popescu31002712010-02-23 13:46:05 +00001650 ASSERT(!to->HasFastProperties());
1651 // Add to dictionary.
Steve Blocka7e24c12009-10-30 11:49:00 +00001652 Handle<String> key = Handle<String>(descs->GetKey(i));
Andrei Popescu31002712010-02-23 13:46:05 +00001653 Handle<Object> callbacks(descs->GetCallbacksObject(i));
1654 PropertyDetails d =
1655 PropertyDetails(details.attributes(), CALLBACKS, details.index());
1656 SetNormalizedProperty(to, key, callbacks, d);
Steve Blocka7e24c12009-10-30 11:49:00 +00001657 break;
1658 }
1659 case MAP_TRANSITION:
1660 case CONSTANT_TRANSITION:
1661 case NULL_DESCRIPTOR:
1662 // Ignore non-properties.
1663 break;
1664 case NORMAL:
1665 // Do not occur since the from object has fast properties.
1666 case INTERCEPTOR:
1667 // No element in instance descriptors have interceptor type.
1668 UNREACHABLE();
1669 break;
1670 }
1671 }
1672 } else {
1673 Handle<StringDictionary> properties =
1674 Handle<StringDictionary>(from->property_dictionary());
1675 int capacity = properties->Capacity();
1676 for (int i = 0; i < capacity; i++) {
1677 Object* raw_key(properties->KeyAt(i));
1678 if (properties->IsKey(raw_key)) {
1679 ASSERT(raw_key->IsString());
1680 // If the property is already there we skip it.
1681 LookupResult result;
1682 to->LocalLookup(String::cast(raw_key), &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001683 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001684 // Set the property.
1685 Handle<String> key = Handle<String>(String::cast(raw_key));
1686 Handle<Object> value = Handle<Object>(properties->ValueAt(i));
1687 if (value->IsJSGlobalPropertyCell()) {
1688 value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
1689 }
1690 PropertyDetails details = properties->DetailsAt(i);
1691 SetProperty(to, key, value, details.attributes());
1692 }
1693 }
1694 }
1695}
1696
1697
1698void Genesis::TransferIndexedProperties(Handle<JSObject> from,
1699 Handle<JSObject> to) {
1700 // Cloning the elements array is sufficient.
1701 Handle<FixedArray> from_elements =
1702 Handle<FixedArray>(FixedArray::cast(from->elements()));
1703 Handle<FixedArray> to_elements = Factory::CopyFixedArray(from_elements);
1704 to->set_elements(*to_elements);
1705}
1706
1707
1708void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
1709 HandleScope outer;
1710
1711 ASSERT(!from->IsJSArray());
1712 ASSERT(!to->IsJSArray());
1713
1714 TransferNamedProperties(from, to);
1715 TransferIndexedProperties(from, to);
1716
1717 // Transfer the prototype (new map is needed).
1718 Handle<Map> old_to_map = Handle<Map>(to->map());
1719 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
1720 new_to_map->set_prototype(from->map()->prototype());
1721 to->set_map(*new_to_map);
1722}
1723
1724
1725void Genesis::MakeFunctionInstancePrototypeWritable() {
1726 // Make a new function map so all future functions
1727 // will have settable and enumerable prototype properties.
1728 HandleScope scope;
1729
1730 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +01001731 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001732 Handle<Map> fm = Factory::CopyMapDropDescriptors(Top::function_map());
1733 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +01001734 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001735 Top::context()->global_context()->set_function_map(*fm);
1736}
1737
1738
Steve Blocka7e24c12009-10-30 11:49:00 +00001739Genesis::Genesis(Handle<Object> global_object,
1740 v8::Handle<v8::ObjectTemplate> global_template,
1741 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001742 result_ = Handle<Context>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +00001743 // If V8 isn't running and cannot be initialized, just return.
1744 if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
1745
1746 // Before creating the roots we must save the context and restore it
1747 // on all function exits.
1748 HandleScope scope;
Andrei Popescu31002712010-02-23 13:46:05 +00001749 SaveContext saved_context;
Steve Blocka7e24c12009-10-30 11:49:00 +00001750
Andrei Popescu31002712010-02-23 13:46:05 +00001751 Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
1752 if (!new_context.is_null()) {
1753 global_context_ =
1754 Handle<Context>::cast(GlobalHandles::Create(*new_context));
1755 Top::set_context(*global_context_);
1756 i::Counters::contexts_created_by_snapshot.Increment();
1757 result_ = global_context_;
1758 JSFunction* empty_function =
1759 JSFunction::cast(result_->function_map()->prototype());
1760 empty_function_ = Handle<JSFunction>(empty_function);
Andrei Popescu402d9372010-02-26 13:31:12 +00001761 Handle<GlobalObject> inner_global;
Andrei Popescu31002712010-02-23 13:46:05 +00001762 Handle<JSGlobalProxy> global_proxy =
1763 CreateNewGlobals(global_template,
1764 global_object,
Andrei Popescu402d9372010-02-26 13:31:12 +00001765 &inner_global);
1766
Andrei Popescu31002712010-02-23 13:46:05 +00001767 HookUpGlobalProxy(inner_global, global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +00001768 HookUpInnerGlobal(inner_global);
1769
Andrei Popescu31002712010-02-23 13:46:05 +00001770 if (!ConfigureGlobalObjects(global_template)) return;
1771 } else {
1772 // We get here if there was no context snapshot.
1773 CreateRoots();
1774 Handle<JSFunction> empty_function = CreateEmptyFunction();
1775 Handle<GlobalObject> inner_global;
1776 Handle<JSGlobalProxy> global_proxy =
1777 CreateNewGlobals(global_template, global_object, &inner_global);
1778 HookUpGlobalProxy(inner_global, global_proxy);
1779 InitializeGlobal(inner_global, empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +01001780 InstallJSFunctionResultCaches();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001781 InitializeNormalizedMapCaches();
Kristian Monsen25f61362010-05-21 11:50:48 +01001782 if (!InstallNatives()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001783
Andrei Popescu31002712010-02-23 13:46:05 +00001784 MakeFunctionInstancePrototypeWritable();
Steve Blocka7e24c12009-10-30 11:49:00 +00001785
Andrei Popescu31002712010-02-23 13:46:05 +00001786 if (!ConfigureGlobalObjects(global_template)) return;
1787 i::Counters::contexts_created_from_scratch.Increment();
1788 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001789
1790 result_ = global_context_;
1791}
1792
1793
1794// Support for thread preemption.
1795
1796// Reserve space for statics needing saving and restoring.
1797int Bootstrapper::ArchiveSpacePerThread() {
Andrei Popescu31002712010-02-23 13:46:05 +00001798 return BootstrapperActive::ArchiveSpacePerThread();
Steve Blocka7e24c12009-10-30 11:49:00 +00001799}
1800
1801
1802// Archive statics that are thread local.
1803char* Bootstrapper::ArchiveState(char* to) {
Andrei Popescu31002712010-02-23 13:46:05 +00001804 return BootstrapperActive::ArchiveState(to);
Steve Blocka7e24c12009-10-30 11:49:00 +00001805}
1806
1807
1808// Restore statics that are thread local.
1809char* Bootstrapper::RestoreState(char* from) {
Andrei Popescu31002712010-02-23 13:46:05 +00001810 return BootstrapperActive::RestoreState(from);
Steve Blocka7e24c12009-10-30 11:49:00 +00001811}
1812
1813
1814// Called when the top-level V8 mutex is destroyed.
1815void Bootstrapper::FreeThreadResources() {
Andrei Popescu31002712010-02-23 13:46:05 +00001816 ASSERT(!BootstrapperActive::IsActive());
Steve Blocka7e24c12009-10-30 11:49:00 +00001817}
1818
1819
1820// Reserve space for statics needing saving and restoring.
Andrei Popescu31002712010-02-23 13:46:05 +00001821int BootstrapperActive::ArchiveSpacePerThread() {
1822 return sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001823}
1824
1825
1826// Archive statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001827char* BootstrapperActive::ArchiveState(char* to) {
1828 *reinterpret_cast<int*>(to) = nesting_;
1829 nesting_ = 0;
1830 return to + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001831}
1832
1833
1834// Restore statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001835char* BootstrapperActive::RestoreState(char* from) {
1836 nesting_ = *reinterpret_cast<int*>(from);
1837 return from + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001838}
1839
1840} } // namespace v8::internal