blob: ce8e98d6a53e84502172e4a7e13ba90f394b98ef [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();
Andrei Popescu31002712010-02-23 13:46:05 +0000235 // Used both for deserialized and from-scratch contexts to add the extensions
236 // provided.
237 static bool InstallExtensions(Handle<Context> global_context,
238 v8::ExtensionConfiguration* extensions);
239 static bool InstallExtension(const char* name);
240 static bool InstallExtension(v8::RegisteredExtension* current);
241 static void InstallSpecialObjects(Handle<Context> global_context);
Andrei Popescu402d9372010-02-26 13:31:12 +0000242 bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
Steve Blocka7e24c12009-10-30 11:49:00 +0000243 bool ConfigureApiObject(Handle<JSObject> object,
244 Handle<ObjectTemplateInfo> object_template);
245 bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
246
247 // Migrates all properties from the 'from' object to the 'to'
248 // object and overrides the prototype in 'to' with the one from
249 // 'from'.
250 void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
251 void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
252 void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
253
Steve Block6ded16b2010-05-10 14:33:55 +0100254 enum PrototypePropertyMode {
255 DONT_ADD_PROTOTYPE,
256 ADD_READONLY_PROTOTYPE,
257 ADD_WRITEABLE_PROTOTYPE
258 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000259 Handle<DescriptorArray> ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100260 PrototypePropertyMode prototypeMode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000261 void MakeFunctionInstancePrototypeWritable();
262
Steve Blocka7e24c12009-10-30 11:49:00 +0000263 static bool CompileBuiltin(int index);
264 static bool CompileNative(Vector<const char> name, Handle<String> source);
265 static bool CompileScriptCached(Vector<const char> name,
266 Handle<String> source,
267 SourceCodeCache* cache,
268 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000269 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000270 bool use_runtime_context);
271
272 Handle<Context> result_;
Andrei Popescu31002712010-02-23 13:46:05 +0000273 Handle<JSFunction> empty_function_;
274 BootstrapperActive active_;
275 friend class Bootstrapper;
Steve Blocka7e24c12009-10-30 11:49:00 +0000276};
277
Steve Blocka7e24c12009-10-30 11:49:00 +0000278
279void Bootstrapper::Iterate(ObjectVisitor* v) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000280 extensions_cache.Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +0000281 v->Synchronize("Extensions");
Steve Blocka7e24c12009-10-30 11:49:00 +0000282}
283
284
Steve Blocka7e24c12009-10-30 11:49:00 +0000285Handle<Context> Bootstrapper::CreateEnvironment(
286 Handle<Object> global_object,
287 v8::Handle<v8::ObjectTemplate> global_template,
288 v8::ExtensionConfiguration* extensions) {
Andrei Popescu31002712010-02-23 13:46:05 +0000289 HandleScope scope;
290 Handle<Context> env;
Steve Blocka7e24c12009-10-30 11:49:00 +0000291 Genesis genesis(global_object, global_template, extensions);
Andrei Popescu31002712010-02-23 13:46:05 +0000292 env = genesis.result();
293 if (!env.is_null()) {
294 if (InstallExtensions(env, extensions)) {
295 return env;
296 }
297 }
298 return Handle<Context>();
Steve Blocka7e24c12009-10-30 11:49:00 +0000299}
300
301
302static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
303 // object.__proto__ = proto;
304 Handle<Map> old_to_map = Handle<Map>(object->map());
305 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
306 new_to_map->set_prototype(*proto);
307 object->set_map(*new_to_map);
308}
309
310
311void Bootstrapper::DetachGlobal(Handle<Context> env) {
312 JSGlobalProxy::cast(env->global_proxy())->set_context(*Factory::null_value());
313 SetObjectPrototype(Handle<JSObject>(env->global_proxy()),
314 Factory::null_value());
315 env->set_global_proxy(env->global());
316 env->global()->set_global_receiver(env->global());
317}
318
319
Andrei Popescu74b3c142010-03-29 12:03:09 +0100320void Bootstrapper::ReattachGlobal(Handle<Context> env,
321 Handle<Object> global_object) {
322 ASSERT(global_object->IsJSGlobalProxy());
323 Handle<JSGlobalProxy> global = Handle<JSGlobalProxy>::cast(global_object);
324 env->global()->set_global_receiver(*global);
325 env->set_global_proxy(*global);
326 SetObjectPrototype(global, Handle<JSObject>(env->global()));
327 global->set_context(*env);
328}
329
330
Steve Blocka7e24c12009-10-30 11:49:00 +0000331static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
332 const char* name,
333 InstanceType type,
334 int instance_size,
335 Handle<JSObject> prototype,
336 Builtins::Name call,
337 bool is_ecma_native) {
338 Handle<String> symbol = Factory::LookupAsciiSymbol(name);
339 Handle<Code> call_code = Handle<Code>(Builtins::builtin(call));
Steve Block6ded16b2010-05-10 14:33:55 +0100340 Handle<JSFunction> function = prototype.is_null() ?
341 Factory::NewFunctionWithoutPrototype(symbol, call_code) :
Steve Blocka7e24c12009-10-30 11:49:00 +0000342 Factory::NewFunctionWithPrototype(symbol,
343 type,
344 instance_size,
345 prototype,
346 call_code,
347 is_ecma_native);
348 SetProperty(target, symbol, function, DONT_ENUM);
349 if (is_ecma_native) {
350 function->shared()->set_instance_class_name(*symbol);
351 }
352 return function;
353}
354
355
356Handle<DescriptorArray> Genesis::ComputeFunctionInstanceDescriptor(
Steve Block6ded16b2010-05-10 14:33:55 +0100357 PrototypePropertyMode prototypeMode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000358 Handle<DescriptorArray> result = Factory::empty_descriptor_array();
359
Steve Block6ded16b2010-05-10 14:33:55 +0100360 if (prototypeMode != DONT_ADD_PROTOTYPE) {
361 PropertyAttributes attributes = static_cast<PropertyAttributes>(
362 DONT_ENUM |
363 DONT_DELETE |
364 (prototypeMode == ADD_READONLY_PROTOTYPE ? READ_ONLY : 0));
365 result =
366 Factory::CopyAppendProxyDescriptor(
367 result,
368 Factory::prototype_symbol(),
369 Factory::NewProxy(&Accessors::FunctionPrototype),
370 attributes);
371 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000372
Steve Block6ded16b2010-05-10 14:33:55 +0100373 PropertyAttributes attributes =
Steve Blocka7e24c12009-10-30 11:49:00 +0000374 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
375 // Add length.
376 result =
377 Factory::CopyAppendProxyDescriptor(
378 result,
379 Factory::length_symbol(),
380 Factory::NewProxy(&Accessors::FunctionLength),
381 attributes);
382
383 // Add name.
384 result =
385 Factory::CopyAppendProxyDescriptor(
386 result,
387 Factory::name_symbol(),
388 Factory::NewProxy(&Accessors::FunctionName),
389 attributes);
390
391 // Add arguments.
392 result =
393 Factory::CopyAppendProxyDescriptor(
394 result,
395 Factory::arguments_symbol(),
396 Factory::NewProxy(&Accessors::FunctionArguments),
397 attributes);
398
399 // Add caller.
400 result =
401 Factory::CopyAppendProxyDescriptor(
402 result,
403 Factory::caller_symbol(),
404 Factory::NewProxy(&Accessors::FunctionCaller),
405 attributes);
406
407 return result;
408}
409
410
Andrei Popescu31002712010-02-23 13:46:05 +0000411Handle<JSFunction> Genesis::CreateEmptyFunction() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000412 // Allocate the map for function instances.
413 Handle<Map> fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
414 global_context()->set_function_instance_map(*fm);
415 // Please note that the prototype property for function instances must be
416 // writable.
417 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +0100418 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000419 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100420 fm->set_function_with_prototype(true);
421
422 // Functions with this map will not have a 'prototype' property, and
423 // can not be used as constructors.
424 Handle<Map> function_without_prototype_map =
425 Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
426 global_context()->set_function_without_prototype_map(
427 *function_without_prototype_map);
428 Handle<DescriptorArray> function_without_prototype_map_descriptors =
429 ComputeFunctionInstanceDescriptor(DONT_ADD_PROTOTYPE);
430 function_without_prototype_map->set_instance_descriptors(
431 *function_without_prototype_map_descriptors);
432 function_without_prototype_map->set_function_with_prototype(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000433
434 // Allocate the function map first and then patch the prototype later
435 fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
436 global_context()->set_function_map(*fm);
Steve Block6ded16b2010-05-10 14:33:55 +0100437 function_map_descriptors =
438 ComputeFunctionInstanceDescriptor(ADD_READONLY_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000439 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +0100440 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000441
442 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
443
444 { // --- O b j e c t ---
445 Handle<JSFunction> object_fun =
446 Factory::NewFunction(object_name, Factory::null_value());
447 Handle<Map> object_function_map =
448 Factory::NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
449 object_fun->set_initial_map(*object_function_map);
450 object_function_map->set_constructor(*object_fun);
451
452 global_context()->set_object_function(*object_fun);
453
454 // Allocate a new prototype for the object function.
455 Handle<JSObject> prototype = Factory::NewJSObject(Top::object_function(),
456 TENURED);
457
458 global_context()->set_initial_object_prototype(*prototype);
459 SetPrototype(object_fun, prototype);
460 object_function_map->
461 set_instance_descriptors(Heap::empty_descriptor_array());
462 }
463
464 // Allocate the empty function as the prototype for function ECMAScript
465 // 262 15.3.4.
466 Handle<String> symbol = Factory::LookupAsciiSymbol("Empty");
467 Handle<JSFunction> empty_function =
Steve Block6ded16b2010-05-10 14:33:55 +0100468 Factory::NewFunctionWithoutPrototype(symbol);
Steve Blocka7e24c12009-10-30 11:49:00 +0000469
Andrei Popescu31002712010-02-23 13:46:05 +0000470 // --- E m p t y ---
471 Handle<Code> code =
472 Handle<Code>(Builtins::builtin(Builtins::EmptyFunction));
473 empty_function->set_code(*code);
Iain Merrick75681382010-08-19 15:07:18 +0100474 empty_function->shared()->set_code(*code);
Andrei Popescu31002712010-02-23 13:46:05 +0000475 Handle<String> source = Factory::NewStringFromAscii(CStrVector("() {}"));
476 Handle<Script> script = Factory::NewScript(source);
477 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
478 empty_function->shared()->set_script(*script);
479 empty_function->shared()->set_start_position(0);
480 empty_function->shared()->set_end_position(source->length());
481 empty_function->shared()->DontAdaptArguments();
482 global_context()->function_map()->set_prototype(*empty_function);
483 global_context()->function_instance_map()->set_prototype(*empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +0100484 global_context()->function_without_prototype_map()->
485 set_prototype(*empty_function);
Steve Blocka7e24c12009-10-30 11:49:00 +0000486
Andrei Popescu31002712010-02-23 13:46:05 +0000487 // Allocate the function map first and then patch the prototype later
Steve Block6ded16b2010-05-10 14:33:55 +0100488 Handle<Map> empty_fm = Factory::CopyMapDropDescriptors(
489 function_without_prototype_map);
490 empty_fm->set_instance_descriptors(
491 *function_without_prototype_map_descriptors);
Andrei Popescu31002712010-02-23 13:46:05 +0000492 empty_fm->set_prototype(global_context()->object_function()->prototype());
493 empty_function->set_map(*empty_fm);
494 return empty_function;
495}
496
497
498void Genesis::CreateRoots() {
499 // Allocate the global context FixedArray first and then patch the
500 // closure and extension object later (we need the empty function
501 // and the global object, but in order to create those, we need the
502 // global context).
503 global_context_ =
504 Handle<Context>::cast(
505 GlobalHandles::Create(*Factory::NewGlobalContext()));
506 Top::set_context(*global_context());
507
508 // Allocate the message listeners object.
509 {
510 v8::NeanderArray listeners;
511 global_context()->set_message_listeners(*listeners.value());
512 }
513}
514
515
516Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
517 v8::Handle<v8::ObjectTemplate> global_template,
518 Handle<Object> global_object,
519 Handle<GlobalObject>* inner_global_out) {
520 // The argument global_template aka data is an ObjectTemplateInfo.
521 // It has a constructor pointer that points at global_constructor which is a
522 // FunctionTemplateInfo.
523 // The global_constructor is used to create or reinitialize the global_proxy.
524 // The global_constructor also has a prototype_template pointer that points at
525 // js_global_template which is an ObjectTemplateInfo.
526 // That in turn has a constructor pointer that points at
527 // js_global_constructor which is a FunctionTemplateInfo.
528 // js_global_constructor is used to make js_global_function
529 // js_global_function is used to make the new inner_global.
530 //
531 // --- G l o b a l ---
532 // Step 1: Create a fresh inner JSGlobalObject.
533 Handle<JSFunction> js_global_function;
534 Handle<ObjectTemplateInfo> js_global_template;
535 if (!global_template.IsEmpty()) {
536 // Get prototype template of the global_template.
537 Handle<ObjectTemplateInfo> data =
538 v8::Utils::OpenHandle(*global_template);
539 Handle<FunctionTemplateInfo> global_constructor =
540 Handle<FunctionTemplateInfo>(
541 FunctionTemplateInfo::cast(data->constructor()));
542 Handle<Object> proto_template(global_constructor->prototype_template());
543 if (!proto_template->IsUndefined()) {
544 js_global_template =
545 Handle<ObjectTemplateInfo>::cast(proto_template);
546 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000547 }
548
Andrei Popescu31002712010-02-23 13:46:05 +0000549 if (js_global_template.is_null()) {
550 Handle<String> name = Handle<String>(Heap::empty_symbol());
551 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
552 js_global_function =
553 Factory::NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
Andrei Popescu402d9372010-02-26 13:31:12 +0000554 JSGlobalObject::kSize, code, true);
Andrei Popescu31002712010-02-23 13:46:05 +0000555 // Change the constructor property of the prototype of the
556 // hidden global function to refer to the Object function.
557 Handle<JSObject> prototype =
558 Handle<JSObject>(
559 JSObject::cast(js_global_function->instance_prototype()));
560 SetProperty(prototype, Factory::constructor_symbol(),
561 Top::object_function(), NONE);
562 } else {
563 Handle<FunctionTemplateInfo> js_global_constructor(
564 FunctionTemplateInfo::cast(js_global_template->constructor()));
565 js_global_function =
566 Factory::CreateApiFunction(js_global_constructor,
567 Factory::InnerGlobalObject);
Steve Blocka7e24c12009-10-30 11:49:00 +0000568 }
569
Andrei Popescu31002712010-02-23 13:46:05 +0000570 js_global_function->initial_map()->set_is_hidden_prototype();
571 Handle<GlobalObject> inner_global =
572 Factory::NewGlobalObject(js_global_function);
573 if (inner_global_out != NULL) {
574 *inner_global_out = inner_global;
575 }
576
577 // Step 2: create or re-initialize the global proxy object.
578 Handle<JSFunction> global_proxy_function;
579 if (global_template.IsEmpty()) {
580 Handle<String> name = Handle<String>(Heap::empty_symbol());
581 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
582 global_proxy_function =
583 Factory::NewFunction(name, JS_GLOBAL_PROXY_TYPE,
584 JSGlobalProxy::kSize, code, true);
585 } else {
586 Handle<ObjectTemplateInfo> data =
587 v8::Utils::OpenHandle(*global_template);
588 Handle<FunctionTemplateInfo> global_constructor(
589 FunctionTemplateInfo::cast(data->constructor()));
590 global_proxy_function =
591 Factory::CreateApiFunction(global_constructor,
592 Factory::OuterGlobalObject);
593 }
594
595 Handle<String> global_name = Factory::LookupAsciiSymbol("global");
596 global_proxy_function->shared()->set_instance_class_name(*global_name);
597 global_proxy_function->initial_map()->set_is_access_check_needed(true);
598
599 // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
600 // Return the global proxy.
601
602 if (global_object.location() != NULL) {
603 ASSERT(global_object->IsJSGlobalProxy());
604 return ReinitializeJSGlobalProxy(
605 global_proxy_function,
606 Handle<JSGlobalProxy>::cast(global_object));
607 } else {
608 return Handle<JSGlobalProxy>::cast(
609 Factory::NewJSObject(global_proxy_function, TENURED));
610 }
611}
612
613
614void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
615 Handle<JSGlobalProxy> global_proxy) {
616 // Set the global context for the global object.
617 inner_global->set_global_context(*global_context());
618 inner_global->set_global_receiver(*global_proxy);
619 global_proxy->set_context(*global_context());
620 global_context()->set_global_proxy(*global_proxy);
621}
622
623
Andrei Popescu402d9372010-02-26 13:31:12 +0000624void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
625 Handle<GlobalObject> inner_global_from_snapshot(
626 GlobalObject::cast(global_context_->extension()));
627 Handle<JSBuiltinsObject> builtins_global(global_context_->builtins());
628 global_context_->set_extension(*inner_global);
629 global_context_->set_global(*inner_global);
630 global_context_->set_security_token(*inner_global);
631 static const PropertyAttributes attributes =
632 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
633 ForceSetProperty(builtins_global,
634 Factory::LookupAsciiSymbol("global"),
635 inner_global,
636 attributes);
637 // Setup the reference from the global object to the builtins object.
638 JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
639 TransferNamedProperties(inner_global_from_snapshot, inner_global);
640 TransferIndexedProperties(inner_global_from_snapshot, inner_global);
641}
642
643
644// This is only called if we are not using snapshots. The equivalent
645// work in the snapshot case is done in HookUpInnerGlobal.
Andrei Popescu31002712010-02-23 13:46:05 +0000646void Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
647 Handle<JSFunction> empty_function) {
648 // --- G l o b a l C o n t e x t ---
649 // Use the empty function as closure (no scope info).
650 global_context()->set_closure(*empty_function);
651 global_context()->set_fcontext(*global_context());
652 global_context()->set_previous(NULL);
653 // Set extension and global object.
654 global_context()->set_extension(*inner_global);
655 global_context()->set_global(*inner_global);
656 // Security setup: Set the security token of the global object to
657 // its the inner global. This makes the security check between two
658 // different contexts fail by default even in case of global
659 // object reinitialization.
660 global_context()->set_security_token(*inner_global);
661
662 Handle<String> object_name = Handle<String>(Heap::Object_symbol());
663 SetProperty(inner_global, object_name, Top::object_function(), DONT_ENUM);
664
Steve Blocka7e24c12009-10-30 11:49:00 +0000665 Handle<JSObject> global = Handle<JSObject>(global_context()->global());
666
667 // Install global Function object
668 InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
669 empty_function, Builtins::Illegal, true); // ECMA native.
670
671 { // --- A r r a y ---
672 Handle<JSFunction> array_function =
673 InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
674 Top::initial_object_prototype(), Builtins::ArrayCode,
675 true);
676 array_function->shared()->set_construct_stub(
677 Builtins::builtin(Builtins::ArrayConstructCode));
678 array_function->shared()->DontAdaptArguments();
679
680 // This seems a bit hackish, but we need to make sure Array.length
681 // is 1.
682 array_function->shared()->set_length(1);
683 Handle<DescriptorArray> array_descriptors =
684 Factory::CopyAppendProxyDescriptor(
685 Factory::empty_descriptor_array(),
686 Factory::length_symbol(),
687 Factory::NewProxy(&Accessors::ArrayLength),
688 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
689
690 // Cache the fast JavaScript array map
691 global_context()->set_js_array_map(array_function->initial_map());
692 global_context()->js_array_map()->set_instance_descriptors(
693 *array_descriptors);
694 // array_function is used internally. JS code creating array object should
695 // search for the 'Array' property on the global object and use that one
696 // as the constructor. 'Array' property on a global object can be
697 // overwritten by JS code.
698 global_context()->set_array_function(*array_function);
699 }
700
701 { // --- N u m b e r ---
702 Handle<JSFunction> number_fun =
703 InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
704 Top::initial_object_prototype(), Builtins::Illegal,
705 true);
706 global_context()->set_number_function(*number_fun);
707 }
708
709 { // --- B o o l e a n ---
710 Handle<JSFunction> boolean_fun =
711 InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
712 Top::initial_object_prototype(), Builtins::Illegal,
713 true);
714 global_context()->set_boolean_function(*boolean_fun);
715 }
716
717 { // --- S t r i n g ---
718 Handle<JSFunction> string_fun =
719 InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
720 Top::initial_object_prototype(), Builtins::Illegal,
721 true);
722 global_context()->set_string_function(*string_fun);
723 // Add 'length' property to strings.
724 Handle<DescriptorArray> string_descriptors =
725 Factory::CopyAppendProxyDescriptor(
726 Factory::empty_descriptor_array(),
727 Factory::length_symbol(),
728 Factory::NewProxy(&Accessors::StringLength),
729 static_cast<PropertyAttributes>(DONT_ENUM |
730 DONT_DELETE |
731 READ_ONLY));
732
733 Handle<Map> string_map =
734 Handle<Map>(global_context()->string_function()->initial_map());
735 string_map->set_instance_descriptors(*string_descriptors);
736 }
737
738 { // --- D a t e ---
739 // Builtin functions for Date.prototype.
740 Handle<JSFunction> date_fun =
741 InstallFunction(global, "Date", JS_VALUE_TYPE, JSValue::kSize,
742 Top::initial_object_prototype(), Builtins::Illegal,
743 true);
744
745 global_context()->set_date_function(*date_fun);
746 }
747
748
749 { // -- R e g E x p
750 // Builtin functions for RegExp.prototype.
751 Handle<JSFunction> regexp_fun =
752 InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
753 Top::initial_object_prototype(), Builtins::Illegal,
754 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000755 global_context()->set_regexp_function(*regexp_fun);
Steve Block6ded16b2010-05-10 14:33:55 +0100756
757 ASSERT(regexp_fun->has_initial_map());
758 Handle<Map> initial_map(regexp_fun->initial_map());
759
760 ASSERT_EQ(0, initial_map->inobject_properties());
761
762 Handle<DescriptorArray> descriptors = Factory::NewDescriptorArray(5);
763 PropertyAttributes final =
764 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
765 int enum_index = 0;
766 {
767 // ECMA-262, section 15.10.7.1.
768 FieldDescriptor field(Heap::source_symbol(),
769 JSRegExp::kSourceFieldIndex,
770 final,
771 enum_index++);
772 descriptors->Set(0, &field);
773 }
774 {
775 // ECMA-262, section 15.10.7.2.
776 FieldDescriptor field(Heap::global_symbol(),
777 JSRegExp::kGlobalFieldIndex,
778 final,
779 enum_index++);
780 descriptors->Set(1, &field);
781 }
782 {
783 // ECMA-262, section 15.10.7.3.
784 FieldDescriptor field(Heap::ignore_case_symbol(),
785 JSRegExp::kIgnoreCaseFieldIndex,
786 final,
787 enum_index++);
788 descriptors->Set(2, &field);
789 }
790 {
791 // ECMA-262, section 15.10.7.4.
792 FieldDescriptor field(Heap::multiline_symbol(),
793 JSRegExp::kMultilineFieldIndex,
794 final,
795 enum_index++);
796 descriptors->Set(3, &field);
797 }
798 {
799 // ECMA-262, section 15.10.7.5.
800 PropertyAttributes writable =
801 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
802 FieldDescriptor field(Heap::last_index_symbol(),
803 JSRegExp::kLastIndexFieldIndex,
804 writable,
805 enum_index++);
806 descriptors->Set(4, &field);
807 }
808 descriptors->SetNextEnumerationIndex(enum_index);
809 descriptors->Sort();
810
811 initial_map->set_inobject_properties(5);
812 initial_map->set_pre_allocated_property_fields(5);
813 initial_map->set_unused_property_fields(0);
814 initial_map->set_instance_size(
815 initial_map->instance_size() + 5 * kPointerSize);
816 initial_map->set_instance_descriptors(*descriptors);
Iain Merrick75681382010-08-19 15:07:18 +0100817 initial_map->set_visitor_id(StaticVisitorBase::GetVisitorId(*initial_map));
Steve Blocka7e24c12009-10-30 11:49:00 +0000818 }
819
820 { // -- J S O N
821 Handle<String> name = Factory::NewStringFromAscii(CStrVector("JSON"));
822 Handle<JSFunction> cons = Factory::NewFunction(
823 name,
824 Factory::the_hole_value());
825 cons->SetInstancePrototype(global_context()->initial_object_prototype());
826 cons->SetInstanceClassName(*name);
827 Handle<JSObject> json_object = Factory::NewJSObject(cons, TENURED);
828 ASSERT(json_object->IsJSObject());
829 SetProperty(global, name, json_object, DONT_ENUM);
830 global_context()->set_json_object(*json_object);
831 }
832
833 { // --- arguments_boilerplate_
834 // Make sure we can recognize argument objects at runtime.
835 // This is done by introducing an anonymous function with
836 // class_name equals 'Arguments'.
837 Handle<String> symbol = Factory::LookupAsciiSymbol("Arguments");
838 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
839 Handle<JSObject> prototype =
840 Handle<JSObject>(
841 JSObject::cast(global_context()->object_function()->prototype()));
842
843 Handle<JSFunction> function =
844 Factory::NewFunctionWithPrototype(symbol,
845 JS_OBJECT_TYPE,
846 JSObject::kHeaderSize,
847 prototype,
848 code,
849 false);
850 ASSERT(!function->has_initial_map());
851 function->shared()->set_instance_class_name(*symbol);
852 function->shared()->set_expected_nof_properties(2);
853 Handle<JSObject> result = Factory::NewJSObject(function);
854
855 global_context()->set_arguments_boilerplate(*result);
856 // Note: callee must be added as the first property and
857 // length must be added as the second property.
858 SetProperty(result, Factory::callee_symbol(),
859 Factory::undefined_value(),
860 DONT_ENUM);
861 SetProperty(result, Factory::length_symbol(),
862 Factory::undefined_value(),
863 DONT_ENUM);
864
865#ifdef DEBUG
866 LookupResult lookup;
867 result->LocalLookup(Heap::callee_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000868 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000869 ASSERT(lookup.GetFieldIndex() == Heap::arguments_callee_index);
870
871 result->LocalLookup(Heap::length_symbol(), &lookup);
Andrei Popescu402d9372010-02-26 13:31:12 +0000872 ASSERT(lookup.IsProperty() && (lookup.type() == FIELD));
Steve Blocka7e24c12009-10-30 11:49:00 +0000873 ASSERT(lookup.GetFieldIndex() == Heap::arguments_length_index);
874
875 ASSERT(result->map()->inobject_properties() > Heap::arguments_callee_index);
876 ASSERT(result->map()->inobject_properties() > Heap::arguments_length_index);
877
878 // Check the state of the object.
879 ASSERT(result->HasFastProperties());
880 ASSERT(result->HasFastElements());
881#endif
882 }
883
884 { // --- context extension
885 // Create a function for the context extension objects.
886 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
887 Handle<JSFunction> context_extension_fun =
888 Factory::NewFunction(Factory::empty_symbol(),
889 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
890 JSObject::kHeaderSize,
891 code,
892 true);
893
894 Handle<String> name = Factory::LookupAsciiSymbol("context_extension");
895 context_extension_fun->shared()->set_instance_class_name(*name);
896 global_context()->set_context_extension_function(*context_extension_fun);
897 }
898
899
900 {
901 // Setup the call-as-function delegate.
902 Handle<Code> code =
903 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsFunction));
904 Handle<JSFunction> delegate =
905 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
906 JSObject::kHeaderSize, code, true);
907 global_context()->set_call_as_function_delegate(*delegate);
908 delegate->shared()->DontAdaptArguments();
909 }
910
911 {
912 // Setup the call-as-constructor delegate.
913 Handle<Code> code =
914 Handle<Code>(Builtins::builtin(Builtins::HandleApiCallAsConstructor));
915 Handle<JSFunction> delegate =
916 Factory::NewFunction(Factory::empty_symbol(), JS_OBJECT_TYPE,
917 JSObject::kHeaderSize, code, true);
918 global_context()->set_call_as_constructor_delegate(*delegate);
919 delegate->shared()->DontAdaptArguments();
920 }
921
Steve Blocka7e24c12009-10-30 11:49:00 +0000922 // Initialize the out of memory slot.
923 global_context()->set_out_of_memory(Heap::false_value());
924
925 // Initialize the data slot.
926 global_context()->set_data(Heap::undefined_value());
927}
928
929
930bool Genesis::CompileBuiltin(int index) {
931 Vector<const char> name = Natives::GetScriptName(index);
932 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
933 return CompileNative(name, source_code);
934}
935
936
937bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
938 HandleScope scope;
939#ifdef ENABLE_DEBUGGER_SUPPORT
940 Debugger::set_compiling_natives(true);
941#endif
Andrei Popescu31002712010-02-23 13:46:05 +0000942 bool result = CompileScriptCached(name,
943 source,
944 NULL,
945 NULL,
946 Handle<Context>(Top::context()),
947 true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000948 ASSERT(Top::has_pending_exception() != result);
949 if (!result) Top::clear_pending_exception();
950#ifdef ENABLE_DEBUGGER_SUPPORT
951 Debugger::set_compiling_natives(false);
952#endif
953 return result;
954}
955
956
957bool Genesis::CompileScriptCached(Vector<const char> name,
958 Handle<String> source,
959 SourceCodeCache* cache,
960 v8::Extension* extension,
Andrei Popescu31002712010-02-23 13:46:05 +0000961 Handle<Context> top_context,
Steve Blocka7e24c12009-10-30 11:49:00 +0000962 bool use_runtime_context) {
963 HandleScope scope;
Steve Block6ded16b2010-05-10 14:33:55 +0100964 Handle<SharedFunctionInfo> function_info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000965
966 // If we can't find the function in the cache, we compile a new
967 // function and insert it into the cache.
Steve Block6ded16b2010-05-10 14:33:55 +0100968 if (cache == NULL || !cache->Lookup(name, &function_info)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000969 ASSERT(source->IsAsciiRepresentation());
970 Handle<String> script_name = Factory::NewStringFromUtf8(name);
Steve Block6ded16b2010-05-10 14:33:55 +0100971 function_info = Compiler::Compile(
Andrei Popescu31002712010-02-23 13:46:05 +0000972 source,
973 script_name,
974 0,
975 0,
976 extension,
977 NULL,
Andrei Popescu402d9372010-02-26 13:31:12 +0000978 Handle<String>::null(),
Andrei Popescu31002712010-02-23 13:46:05 +0000979 use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
Steve Block6ded16b2010-05-10 14:33:55 +0100980 if (function_info.is_null()) return false;
981 if (cache != NULL) cache->Add(name, function_info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000982 }
983
984 // Setup the function context. Conceptually, we should clone the
985 // function before overwriting the context but since we're in a
986 // single-threaded environment it is not strictly necessary.
Andrei Popescu31002712010-02-23 13:46:05 +0000987 ASSERT(top_context->IsGlobalContext());
Steve Blocka7e24c12009-10-30 11:49:00 +0000988 Handle<Context> context =
989 Handle<Context>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +0000990 ? Handle<Context>(top_context->runtime_context())
991 : top_context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000992 Handle<JSFunction> fun =
Steve Block6ded16b2010-05-10 14:33:55 +0100993 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000994
Leon Clarke4515c472010-02-03 11:58:03 +0000995 // Call function using either the runtime object or the global
Steve Blocka7e24c12009-10-30 11:49:00 +0000996 // object as the receiver. Provide no parameters.
997 Handle<Object> receiver =
998 Handle<Object>(use_runtime_context
Andrei Popescu31002712010-02-23 13:46:05 +0000999 ? top_context->builtins()
1000 : top_context->global());
Steve Blocka7e24c12009-10-30 11:49:00 +00001001 bool has_pending_exception;
1002 Handle<Object> result =
1003 Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1004 if (has_pending_exception) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001005 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001006}
1007
1008
1009#define INSTALL_NATIVE(Type, name, var) \
1010 Handle<String> var##_name = Factory::LookupAsciiSymbol(name); \
1011 global_context()->set_##var(Type::cast(global_context()-> \
1012 builtins()-> \
1013 GetProperty(*var##_name)));
1014
1015void Genesis::InstallNativeFunctions() {
1016 HandleScope scope;
1017 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1018 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1019 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1020 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1021 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1022 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1023 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1024 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
Leon Clarkee46be812010-01-19 14:06:41 +00001025 INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
Steve Blocka7e24c12009-10-30 11:49:00 +00001026 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1027 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1028 configure_instance_fun);
1029 INSTALL_NATIVE(JSFunction, "MakeMessage", make_message_fun);
1030 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1031 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1032}
1033
1034#undef INSTALL_NATIVE
1035
1036
1037bool Genesis::InstallNatives() {
1038 HandleScope scope;
1039
1040 // Create a function for the builtins object. Allocate space for the
1041 // JavaScript builtins, a reference to the builtins object
1042 // (itself) and a reference to the global_context directly in the object.
1043 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
1044 Handle<JSFunction> builtins_fun =
1045 Factory::NewFunction(Factory::empty_symbol(), JS_BUILTINS_OBJECT_TYPE,
1046 JSBuiltinsObject::kSize, code, true);
1047
1048 Handle<String> name = Factory::LookupAsciiSymbol("builtins");
1049 builtins_fun->shared()->set_instance_class_name(*name);
1050
1051 // Allocate the builtins object.
1052 Handle<JSBuiltinsObject> builtins =
1053 Handle<JSBuiltinsObject>::cast(Factory::NewGlobalObject(builtins_fun));
1054 builtins->set_builtins(*builtins);
1055 builtins->set_global_context(*global_context());
1056 builtins->set_global_receiver(*builtins);
1057
1058 // Setup the 'global' properties of the builtins object. The
1059 // 'global' property that refers to the global object is the only
1060 // way to get from code running in the builtins context to the
1061 // global object.
1062 static const PropertyAttributes attributes =
1063 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1064 SetProperty(builtins, Factory::LookupAsciiSymbol("global"),
1065 Handle<Object>(global_context()->global()), attributes);
1066
1067 // Setup the reference from the global object to the builtins object.
1068 JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
1069
1070 // Create a bridge function that has context in the global context.
1071 Handle<JSFunction> bridge =
1072 Factory::NewFunction(Factory::empty_symbol(), Factory::undefined_value());
1073 ASSERT(bridge->context() == *Top::global_context());
1074
1075 // Allocate the builtins context.
1076 Handle<Context> context =
1077 Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1078 context->set_global(*builtins); // override builtins global object
1079
1080 global_context()->set_runtime_context(*context);
1081
1082 { // -- S c r i p t
1083 // Builtin functions for Script.
1084 Handle<JSFunction> script_fun =
1085 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1086 Top::initial_object_prototype(), Builtins::Illegal,
1087 false);
1088 Handle<JSObject> prototype =
1089 Factory::NewJSObject(Top::object_function(), TENURED);
1090 SetPrototype(script_fun, prototype);
1091 global_context()->set_script_function(*script_fun);
1092
1093 // Add 'source' and 'data' property to scripts.
1094 PropertyAttributes common_attributes =
1095 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1096 Handle<Proxy> proxy_source = Factory::NewProxy(&Accessors::ScriptSource);
1097 Handle<DescriptorArray> script_descriptors =
1098 Factory::CopyAppendProxyDescriptor(
1099 Factory::empty_descriptor_array(),
1100 Factory::LookupAsciiSymbol("source"),
1101 proxy_source,
1102 common_attributes);
1103 Handle<Proxy> proxy_name = Factory::NewProxy(&Accessors::ScriptName);
1104 script_descriptors =
1105 Factory::CopyAppendProxyDescriptor(
1106 script_descriptors,
1107 Factory::LookupAsciiSymbol("name"),
1108 proxy_name,
1109 common_attributes);
1110 Handle<Proxy> proxy_id = Factory::NewProxy(&Accessors::ScriptId);
1111 script_descriptors =
1112 Factory::CopyAppendProxyDescriptor(
1113 script_descriptors,
1114 Factory::LookupAsciiSymbol("id"),
1115 proxy_id,
1116 common_attributes);
1117 Handle<Proxy> proxy_line_offset =
1118 Factory::NewProxy(&Accessors::ScriptLineOffset);
1119 script_descriptors =
1120 Factory::CopyAppendProxyDescriptor(
1121 script_descriptors,
1122 Factory::LookupAsciiSymbol("line_offset"),
1123 proxy_line_offset,
1124 common_attributes);
1125 Handle<Proxy> proxy_column_offset =
1126 Factory::NewProxy(&Accessors::ScriptColumnOffset);
1127 script_descriptors =
1128 Factory::CopyAppendProxyDescriptor(
1129 script_descriptors,
1130 Factory::LookupAsciiSymbol("column_offset"),
1131 proxy_column_offset,
1132 common_attributes);
1133 Handle<Proxy> proxy_data = Factory::NewProxy(&Accessors::ScriptData);
1134 script_descriptors =
1135 Factory::CopyAppendProxyDescriptor(
1136 script_descriptors,
1137 Factory::LookupAsciiSymbol("data"),
1138 proxy_data,
1139 common_attributes);
1140 Handle<Proxy> proxy_type = Factory::NewProxy(&Accessors::ScriptType);
1141 script_descriptors =
1142 Factory::CopyAppendProxyDescriptor(
1143 script_descriptors,
1144 Factory::LookupAsciiSymbol("type"),
1145 proxy_type,
1146 common_attributes);
1147 Handle<Proxy> proxy_compilation_type =
1148 Factory::NewProxy(&Accessors::ScriptCompilationType);
1149 script_descriptors =
1150 Factory::CopyAppendProxyDescriptor(
1151 script_descriptors,
1152 Factory::LookupAsciiSymbol("compilation_type"),
1153 proxy_compilation_type,
1154 common_attributes);
1155 Handle<Proxy> proxy_line_ends =
1156 Factory::NewProxy(&Accessors::ScriptLineEnds);
1157 script_descriptors =
1158 Factory::CopyAppendProxyDescriptor(
1159 script_descriptors,
1160 Factory::LookupAsciiSymbol("line_ends"),
1161 proxy_line_ends,
1162 common_attributes);
1163 Handle<Proxy> proxy_context_data =
1164 Factory::NewProxy(&Accessors::ScriptContextData);
1165 script_descriptors =
1166 Factory::CopyAppendProxyDescriptor(
1167 script_descriptors,
1168 Factory::LookupAsciiSymbol("context_data"),
1169 proxy_context_data,
1170 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001171 Handle<Proxy> proxy_eval_from_script =
1172 Factory::NewProxy(&Accessors::ScriptEvalFromScript);
Steve Blocka7e24c12009-10-30 11:49:00 +00001173 script_descriptors =
1174 Factory::CopyAppendProxyDescriptor(
1175 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001176 Factory::LookupAsciiSymbol("eval_from_script"),
1177 proxy_eval_from_script,
Steve Blocka7e24c12009-10-30 11:49:00 +00001178 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001179 Handle<Proxy> proxy_eval_from_script_position =
1180 Factory::NewProxy(&Accessors::ScriptEvalFromScriptPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +00001181 script_descriptors =
1182 Factory::CopyAppendProxyDescriptor(
1183 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001184 Factory::LookupAsciiSymbol("eval_from_script_position"),
1185 proxy_eval_from_script_position,
1186 common_attributes);
1187 Handle<Proxy> proxy_eval_from_function_name =
1188 Factory::NewProxy(&Accessors::ScriptEvalFromFunctionName);
1189 script_descriptors =
1190 Factory::CopyAppendProxyDescriptor(
1191 script_descriptors,
1192 Factory::LookupAsciiSymbol("eval_from_function_name"),
1193 proxy_eval_from_function_name,
Steve Blocka7e24c12009-10-30 11:49:00 +00001194 common_attributes);
1195
1196 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1197 script_map->set_instance_descriptors(*script_descriptors);
1198
1199 // Allocate the empty script.
1200 Handle<Script> script = Factory::NewScript(Factory::empty_string());
1201 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Andrei Popescu31002712010-02-23 13:46:05 +00001202 Heap::public_set_empty_script(*script);
Steve Blocka7e24c12009-10-30 11:49:00 +00001203 }
Steve Block6ded16b2010-05-10 14:33:55 +01001204 {
1205 // Builtin function for OpaqueReference -- a JSValue-based object,
1206 // that keeps its field isolated from JavaScript code. It may store
1207 // objects, that JavaScript code may not access.
1208 Handle<JSFunction> opaque_reference_fun =
1209 InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1210 JSValue::kSize, Top::initial_object_prototype(),
1211 Builtins::Illegal, false);
1212 Handle<JSObject> prototype =
1213 Factory::NewJSObject(Top::object_function(), TENURED);
1214 SetPrototype(opaque_reference_fun, prototype);
1215 global_context()->set_opaque_reference_function(*opaque_reference_fun);
1216 }
1217
1218 if (FLAG_disable_native_files) {
1219 PrintF("Warning: Running without installed natives!\n");
1220 return true;
1221 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001222
Andrei Popescu31002712010-02-23 13:46:05 +00001223 // Install natives.
1224 for (int i = Natives::GetDebuggerCount();
1225 i < Natives::GetBuiltinsCount();
1226 i++) {
1227 Vector<const char> name = Natives::GetScriptName(i);
1228 if (!CompileBuiltin(i)) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001229 // TODO(ager): We really only need to install the JS builtin
1230 // functions on the builtins object after compiling and running
1231 // runtime.js.
1232 if (!InstallJSBuiltins(builtins)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001233 }
1234
1235 InstallNativeFunctions();
1236
Iain Merrick75681382010-08-19 15:07:18 +01001237 // Store the map for the string prototype after the natives has been compiled
1238 // and the String function has been setup.
1239 Handle<JSFunction> string_function(global_context()->string_function());
1240 ASSERT(JSObject::cast(
1241 string_function->initial_map()->prototype())->HasFastProperties());
1242 global_context()->set_string_function_prototype_map(
1243 HeapObject::cast(string_function->initial_map()->prototype())->map());
1244
Kristian Monsen25f61362010-05-21 11:50:48 +01001245 InstallCustomCallGenerators();
1246
Steve Blocka7e24c12009-10-30 11:49:00 +00001247 // Install Function.prototype.call and apply.
1248 { Handle<String> key = Factory::function_class_symbol();
1249 Handle<JSFunction> function =
1250 Handle<JSFunction>::cast(GetProperty(Top::global(), key));
1251 Handle<JSObject> proto =
1252 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1253
1254 // Install the call and the apply functions.
1255 Handle<JSFunction> call =
1256 InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001257 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001258 Builtins::FunctionCall,
1259 false);
1260 Handle<JSFunction> apply =
1261 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001262 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001263 Builtins::FunctionApply,
1264 false);
1265
1266 // Make sure that Function.prototype.call appears to be compiled.
1267 // The code will never be called, but inline caching for call will
1268 // only work if it appears to be compiled.
1269 call->shared()->DontAdaptArguments();
1270 ASSERT(call->is_compiled());
1271
1272 // Set the expected parameters for apply to 2; required by builtin.
1273 apply->shared()->set_formal_parameter_count(2);
1274
1275 // Set the lengths for the functions to satisfy ECMA-262.
1276 call->shared()->set_length(1);
1277 apply->shared()->set_length(2);
1278 }
1279
Steve Block6ded16b2010-05-10 14:33:55 +01001280 // Create a constructor for RegExp results (a variant of Array that
1281 // predefines the two properties index and match).
1282 {
1283 // RegExpResult initial map.
1284
1285 // Find global.Array.prototype to inherit from.
1286 Handle<JSFunction> array_constructor(global_context()->array_function());
1287 Handle<JSObject> array_prototype(
1288 JSObject::cast(array_constructor->instance_prototype()));
1289
1290 // Add initial map.
1291 Handle<Map> initial_map =
1292 Factory::NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1293 initial_map->set_constructor(*array_constructor);
1294
1295 // Set prototype on map.
1296 initial_map->set_non_instance_prototype(false);
1297 initial_map->set_prototype(*array_prototype);
1298
1299 // Update map with length accessor from Array and add "index" and "input".
1300 Handle<Map> array_map(global_context()->js_array_map());
1301 Handle<DescriptorArray> array_descriptors(
1302 array_map->instance_descriptors());
1303 ASSERT_EQ(1, array_descriptors->number_of_descriptors());
1304
1305 Handle<DescriptorArray> reresult_descriptors =
1306 Factory::NewDescriptorArray(3);
1307
1308 reresult_descriptors->CopyFrom(0, *array_descriptors, 0);
1309
1310 int enum_index = 0;
1311 {
1312 FieldDescriptor index_field(Heap::index_symbol(),
1313 JSRegExpResult::kIndexIndex,
1314 NONE,
1315 enum_index++);
1316 reresult_descriptors->Set(1, &index_field);
1317 }
1318
1319 {
1320 FieldDescriptor input_field(Heap::input_symbol(),
1321 JSRegExpResult::kInputIndex,
1322 NONE,
1323 enum_index++);
1324 reresult_descriptors->Set(2, &input_field);
1325 }
1326 reresult_descriptors->Sort();
1327
1328 initial_map->set_inobject_properties(2);
1329 initial_map->set_pre_allocated_property_fields(2);
1330 initial_map->set_unused_property_fields(0);
1331 initial_map->set_instance_descriptors(*reresult_descriptors);
1332
1333 global_context()->set_regexp_result_map(*initial_map);
1334 }
1335
Steve Blocka7e24c12009-10-30 11:49:00 +00001336#ifdef DEBUG
1337 builtins->Verify();
1338#endif
Andrei Popescu31002712010-02-23 13:46:05 +00001339
Steve Blocka7e24c12009-10-30 11:49:00 +00001340 return true;
1341}
1342
1343
Kristian Monsen25f61362010-05-21 11:50:48 +01001344static void InstallCustomCallGenerator(Handle<JSFunction> holder_function,
1345 const char* function_name,
1346 int id) {
1347 Handle<JSObject> proto(JSObject::cast(holder_function->instance_prototype()));
1348 Handle<String> name = Factory::LookupAsciiSymbol(function_name);
1349 Handle<JSFunction> function(JSFunction::cast(proto->GetProperty(*name)));
1350 function->shared()->set_function_data(Smi::FromInt(id));
1351}
1352
1353
1354void Genesis::InstallCustomCallGenerators() {
1355 HandleScope scope;
1356#define INSTALL_CALL_GENERATOR(holder_fun, fun_name, name) \
1357 { \
1358 Handle<JSFunction> holder(global_context()->holder_fun##_function()); \
1359 const int id = CallStubCompiler::k##name##CallGenerator; \
1360 InstallCustomCallGenerator(holder, #fun_name, id); \
1361 }
1362 CUSTOM_CALL_IC_GENERATORS(INSTALL_CALL_GENERATOR)
1363#undef INSTALL_CALL_GENERATOR
1364}
1365
1366
Steve Block6ded16b2010-05-10 14:33:55 +01001367// Do not forget to update macros.py with named constant
1368// of cache id.
1369#define JSFUNCTION_RESULT_CACHE_LIST(F) \
1370 F(16, global_context()->regexp_function())
1371
1372
1373static FixedArray* CreateCache(int size, JSFunction* factory) {
1374 // Caches are supposed to live for a long time, allocate in old space.
1375 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1376 // Cannot use cast as object is not fully initialized yet.
1377 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1378 *Factory::NewFixedArrayWithHoles(array_size, TENURED));
1379 cache->set(JSFunctionResultCache::kFactoryIndex, factory);
1380 cache->MakeZeroSize();
1381 return cache;
1382}
1383
1384
1385void Genesis::InstallJSFunctionResultCaches() {
1386 const int kNumberOfCaches = 0 +
1387#define F(size, func) + 1
1388 JSFUNCTION_RESULT_CACHE_LIST(F)
1389#undef F
1390 ;
1391
1392 Handle<FixedArray> caches = Factory::NewFixedArray(kNumberOfCaches, TENURED);
1393
1394 int index = 0;
1395#define F(size, func) caches->set(index++, CreateCache(size, func));
1396 JSFUNCTION_RESULT_CACHE_LIST(F)
1397#undef F
1398
1399 global_context()->set_jsfunction_result_caches(*caches);
1400}
1401
1402
Andrei Popescu31002712010-02-23 13:46:05 +00001403int BootstrapperActive::nesting_ = 0;
1404
1405
1406bool Bootstrapper::InstallExtensions(Handle<Context> global_context,
1407 v8::ExtensionConfiguration* extensions) {
1408 BootstrapperActive active;
1409 SaveContext saved_context;
1410 Top::set_context(*global_context);
1411 if (!Genesis::InstallExtensions(global_context, extensions)) return false;
1412 Genesis::InstallSpecialObjects(global_context);
1413 return true;
1414}
1415
1416
1417void Genesis::InstallSpecialObjects(Handle<Context> global_context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001418 HandleScope scope;
1419 Handle<JSGlobalObject> js_global(
Andrei Popescu31002712010-02-23 13:46:05 +00001420 JSGlobalObject::cast(global_context->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001421 // Expose the natives in global if a name for it is specified.
1422 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1423 Handle<String> natives_string =
1424 Factory::LookupAsciiSymbol(FLAG_expose_natives_as);
1425 SetProperty(js_global, natives_string,
1426 Handle<JSObject>(js_global->builtins()), DONT_ENUM);
1427 }
1428
1429 Handle<Object> Error = GetProperty(js_global, "Error");
1430 if (Error->IsJSObject()) {
1431 Handle<String> name = Factory::LookupAsciiSymbol("stackTraceLimit");
1432 SetProperty(Handle<JSObject>::cast(Error),
1433 name,
1434 Handle<Smi>(Smi::FromInt(FLAG_stack_trace_limit)),
1435 NONE);
1436 }
1437
1438#ifdef ENABLE_DEBUGGER_SUPPORT
1439 // Expose the debug global object in global if a name for it is specified.
1440 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1441 // If loading fails we just bail out without installing the
1442 // debugger but without tanking the whole context.
Andrei Popescu31002712010-02-23 13:46:05 +00001443 if (!Debug::Load()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001444 // Set the security token for the debugger context to the same as
1445 // the shell global context to allow calling between these (otherwise
1446 // exposing debug global object doesn't make much sense).
1447 Debug::debug_context()->set_security_token(
Andrei Popescu31002712010-02-23 13:46:05 +00001448 global_context->security_token());
Steve Blocka7e24c12009-10-30 11:49:00 +00001449
1450 Handle<String> debug_string =
1451 Factory::LookupAsciiSymbol(FLAG_expose_debug_as);
1452 SetProperty(js_global, debug_string,
1453 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM);
1454 }
1455#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001456}
1457
1458
Andrei Popescu31002712010-02-23 13:46:05 +00001459bool Genesis::InstallExtensions(Handle<Context> global_context,
1460 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001461 // Clear coloring of extension list
1462 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1463 while (current != NULL) {
1464 current->set_state(v8::UNVISITED);
1465 current = current->next();
1466 }
Andrei Popescu31002712010-02-23 13:46:05 +00001467 // Install auto extensions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001468 current = v8::RegisteredExtension::first_extension();
1469 while (current != NULL) {
1470 if (current->extension()->auto_enable())
1471 InstallExtension(current);
1472 current = current->next();
1473 }
1474
1475 if (FLAG_expose_gc) InstallExtension("v8/gc");
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001476 if (FLAG_expose_externalize_string) InstallExtension("v8/externalize");
Steve Blocka7e24c12009-10-30 11:49:00 +00001477
1478 if (extensions == NULL) return true;
1479 // Install required extensions
1480 int count = v8::ImplementationUtilities::GetNameCount(extensions);
1481 const char** names = v8::ImplementationUtilities::GetNames(extensions);
1482 for (int i = 0; i < count; i++) {
1483 if (!InstallExtension(names[i]))
1484 return false;
1485 }
1486
1487 return true;
1488}
1489
1490
1491// Installs a named extension. This methods is unoptimized and does
1492// not scale well if we want to support a large number of extensions.
1493bool Genesis::InstallExtension(const char* name) {
1494 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1495 // Loop until we find the relevant extension
1496 while (current != NULL) {
1497 if (strcmp(name, current->extension()->name()) == 0) break;
1498 current = current->next();
1499 }
1500 // Didn't find the extension; fail.
1501 if (current == NULL) {
1502 v8::Utils::ReportApiFailure(
1503 "v8::Context::New()", "Cannot find required extension");
1504 return false;
1505 }
1506 return InstallExtension(current);
1507}
1508
1509
1510bool Genesis::InstallExtension(v8::RegisteredExtension* current) {
1511 HandleScope scope;
1512
1513 if (current->state() == v8::INSTALLED) return true;
1514 // The current node has already been visited so there must be a
1515 // cycle in the dependency graph; fail.
1516 if (current->state() == v8::VISITED) {
1517 v8::Utils::ReportApiFailure(
1518 "v8::Context::New()", "Circular extension dependency");
1519 return false;
1520 }
1521 ASSERT(current->state() == v8::UNVISITED);
1522 current->set_state(v8::VISITED);
1523 v8::Extension* extension = current->extension();
1524 // Install the extension's dependencies
1525 for (int i = 0; i < extension->dependency_count(); i++) {
1526 if (!InstallExtension(extension->dependencies()[i])) return false;
1527 }
1528 Vector<const char> source = CStrVector(extension->source());
1529 Handle<String> source_code = Factory::NewStringFromAscii(source);
1530 bool result = CompileScriptCached(CStrVector(extension->name()),
1531 source_code,
Andrei Popescu31002712010-02-23 13:46:05 +00001532 &extensions_cache,
1533 extension,
1534 Handle<Context>(Top::context()),
Steve Blocka7e24c12009-10-30 11:49:00 +00001535 false);
1536 ASSERT(Top::has_pending_exception() != result);
1537 if (!result) {
1538 Top::clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001539 }
1540 current->set_state(v8::INSTALLED);
1541 return result;
1542}
1543
1544
Andrei Popescu402d9372010-02-26 13:31:12 +00001545bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
1546 HandleScope scope;
1547 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
1548 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
1549 Handle<String> name = Factory::LookupAsciiSymbol(Builtins::GetName(id));
1550 Handle<JSFunction> function
1551 = Handle<JSFunction>(JSFunction::cast(builtins->GetProperty(*name)));
1552 builtins->set_javascript_builtin(id, *function);
1553 Handle<SharedFunctionInfo> shared
1554 = Handle<SharedFunctionInfo>(function->shared());
1555 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Iain Merrick75681382010-08-19 15:07:18 +01001556 // Set the code object on the function object.
1557 function->set_code(function->shared()->code());
Steve Block6ded16b2010-05-10 14:33:55 +01001558 builtins->set_javascript_builtin_code(id, shared->code());
Andrei Popescu402d9372010-02-26 13:31:12 +00001559 }
1560 return true;
Andrei Popescu31002712010-02-23 13:46:05 +00001561}
1562
1563
Steve Blocka7e24c12009-10-30 11:49:00 +00001564bool Genesis::ConfigureGlobalObjects(
1565 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
1566 Handle<JSObject> global_proxy(
1567 JSObject::cast(global_context()->global_proxy()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001568 Handle<JSObject> inner_global(JSObject::cast(global_context()->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001569
1570 if (!global_proxy_template.IsEmpty()) {
1571 // Configure the global proxy object.
1572 Handle<ObjectTemplateInfo> proxy_data =
1573 v8::Utils::OpenHandle(*global_proxy_template);
1574 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
1575
1576 // Configure the inner global object.
1577 Handle<FunctionTemplateInfo> proxy_constructor(
1578 FunctionTemplateInfo::cast(proxy_data->constructor()));
1579 if (!proxy_constructor->prototype_template()->IsUndefined()) {
1580 Handle<ObjectTemplateInfo> inner_data(
1581 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001582 if (!ConfigureApiObject(inner_global, inner_data)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001583 }
1584 }
1585
Andrei Popescu402d9372010-02-26 13:31:12 +00001586 SetObjectPrototype(global_proxy, inner_global);
Steve Blocka7e24c12009-10-30 11:49:00 +00001587 return true;
1588}
1589
1590
1591bool Genesis::ConfigureApiObject(Handle<JSObject> object,
1592 Handle<ObjectTemplateInfo> object_template) {
1593 ASSERT(!object_template.is_null());
1594 ASSERT(object->IsInstanceOf(
1595 FunctionTemplateInfo::cast(object_template->constructor())));
1596
1597 bool pending_exception = false;
1598 Handle<JSObject> obj =
1599 Execution::InstantiateObject(object_template, &pending_exception);
1600 if (pending_exception) {
1601 ASSERT(Top::has_pending_exception());
1602 Top::clear_pending_exception();
1603 return false;
1604 }
1605 TransferObject(obj, object);
1606 return true;
1607}
1608
1609
1610void Genesis::TransferNamedProperties(Handle<JSObject> from,
1611 Handle<JSObject> to) {
1612 if (from->HasFastProperties()) {
1613 Handle<DescriptorArray> descs =
1614 Handle<DescriptorArray>(from->map()->instance_descriptors());
1615 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1616 PropertyDetails details = PropertyDetails(descs->GetDetails(i));
1617 switch (details.type()) {
1618 case FIELD: {
1619 HandleScope inner;
1620 Handle<String> key = Handle<String>(descs->GetKey(i));
1621 int index = descs->GetFieldIndex(i);
1622 Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
1623 SetProperty(to, key, value, details.attributes());
1624 break;
1625 }
1626 case CONSTANT_FUNCTION: {
1627 HandleScope inner;
1628 Handle<String> key = Handle<String>(descs->GetKey(i));
1629 Handle<JSFunction> fun =
1630 Handle<JSFunction>(descs->GetConstantFunction(i));
1631 SetProperty(to, key, fun, details.attributes());
1632 break;
1633 }
1634 case CALLBACKS: {
1635 LookupResult result;
1636 to->LocalLookup(descs->GetKey(i), &result);
1637 // If the property is already there we skip it
Andrei Popescu402d9372010-02-26 13:31:12 +00001638 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001639 HandleScope inner;
Andrei Popescu31002712010-02-23 13:46:05 +00001640 ASSERT(!to->HasFastProperties());
1641 // Add to dictionary.
Steve Blocka7e24c12009-10-30 11:49:00 +00001642 Handle<String> key = Handle<String>(descs->GetKey(i));
Andrei Popescu31002712010-02-23 13:46:05 +00001643 Handle<Object> callbacks(descs->GetCallbacksObject(i));
1644 PropertyDetails d =
1645 PropertyDetails(details.attributes(), CALLBACKS, details.index());
1646 SetNormalizedProperty(to, key, callbacks, d);
Steve Blocka7e24c12009-10-30 11:49:00 +00001647 break;
1648 }
1649 case MAP_TRANSITION:
1650 case CONSTANT_TRANSITION:
1651 case NULL_DESCRIPTOR:
1652 // Ignore non-properties.
1653 break;
1654 case NORMAL:
1655 // Do not occur since the from object has fast properties.
1656 case INTERCEPTOR:
1657 // No element in instance descriptors have interceptor type.
1658 UNREACHABLE();
1659 break;
1660 }
1661 }
1662 } else {
1663 Handle<StringDictionary> properties =
1664 Handle<StringDictionary>(from->property_dictionary());
1665 int capacity = properties->Capacity();
1666 for (int i = 0; i < capacity; i++) {
1667 Object* raw_key(properties->KeyAt(i));
1668 if (properties->IsKey(raw_key)) {
1669 ASSERT(raw_key->IsString());
1670 // If the property is already there we skip it.
1671 LookupResult result;
1672 to->LocalLookup(String::cast(raw_key), &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001673 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001674 // Set the property.
1675 Handle<String> key = Handle<String>(String::cast(raw_key));
1676 Handle<Object> value = Handle<Object>(properties->ValueAt(i));
1677 if (value->IsJSGlobalPropertyCell()) {
1678 value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
1679 }
1680 PropertyDetails details = properties->DetailsAt(i);
1681 SetProperty(to, key, value, details.attributes());
1682 }
1683 }
1684 }
1685}
1686
1687
1688void Genesis::TransferIndexedProperties(Handle<JSObject> from,
1689 Handle<JSObject> to) {
1690 // Cloning the elements array is sufficient.
1691 Handle<FixedArray> from_elements =
1692 Handle<FixedArray>(FixedArray::cast(from->elements()));
1693 Handle<FixedArray> to_elements = Factory::CopyFixedArray(from_elements);
1694 to->set_elements(*to_elements);
1695}
1696
1697
1698void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
1699 HandleScope outer;
1700
1701 ASSERT(!from->IsJSArray());
1702 ASSERT(!to->IsJSArray());
1703
1704 TransferNamedProperties(from, to);
1705 TransferIndexedProperties(from, to);
1706
1707 // Transfer the prototype (new map is needed).
1708 Handle<Map> old_to_map = Handle<Map>(to->map());
1709 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
1710 new_to_map->set_prototype(from->map()->prototype());
1711 to->set_map(*new_to_map);
1712}
1713
1714
1715void Genesis::MakeFunctionInstancePrototypeWritable() {
1716 // Make a new function map so all future functions
1717 // will have settable and enumerable prototype properties.
1718 HandleScope scope;
1719
1720 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +01001721 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001722 Handle<Map> fm = Factory::CopyMapDropDescriptors(Top::function_map());
1723 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +01001724 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001725 Top::context()->global_context()->set_function_map(*fm);
1726}
1727
1728
Steve Blocka7e24c12009-10-30 11:49:00 +00001729Genesis::Genesis(Handle<Object> global_object,
1730 v8::Handle<v8::ObjectTemplate> global_template,
1731 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001732 result_ = Handle<Context>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +00001733 // If V8 isn't running and cannot be initialized, just return.
1734 if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
1735
1736 // Before creating the roots we must save the context and restore it
1737 // on all function exits.
1738 HandleScope scope;
Andrei Popescu31002712010-02-23 13:46:05 +00001739 SaveContext saved_context;
Steve Blocka7e24c12009-10-30 11:49:00 +00001740
Andrei Popescu31002712010-02-23 13:46:05 +00001741 Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
1742 if (!new_context.is_null()) {
1743 global_context_ =
1744 Handle<Context>::cast(GlobalHandles::Create(*new_context));
1745 Top::set_context(*global_context_);
1746 i::Counters::contexts_created_by_snapshot.Increment();
1747 result_ = global_context_;
1748 JSFunction* empty_function =
1749 JSFunction::cast(result_->function_map()->prototype());
1750 empty_function_ = Handle<JSFunction>(empty_function);
Andrei Popescu402d9372010-02-26 13:31:12 +00001751 Handle<GlobalObject> inner_global;
Andrei Popescu31002712010-02-23 13:46:05 +00001752 Handle<JSGlobalProxy> global_proxy =
1753 CreateNewGlobals(global_template,
1754 global_object,
Andrei Popescu402d9372010-02-26 13:31:12 +00001755 &inner_global);
1756
Andrei Popescu31002712010-02-23 13:46:05 +00001757 HookUpGlobalProxy(inner_global, global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +00001758 HookUpInnerGlobal(inner_global);
1759
Andrei Popescu31002712010-02-23 13:46:05 +00001760 if (!ConfigureGlobalObjects(global_template)) return;
1761 } else {
1762 // We get here if there was no context snapshot.
1763 CreateRoots();
1764 Handle<JSFunction> empty_function = CreateEmptyFunction();
1765 Handle<GlobalObject> inner_global;
1766 Handle<JSGlobalProxy> global_proxy =
1767 CreateNewGlobals(global_template, global_object, &inner_global);
1768 HookUpGlobalProxy(inner_global, global_proxy);
1769 InitializeGlobal(inner_global, empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +01001770 InstallJSFunctionResultCaches();
Kristian Monsen25f61362010-05-21 11:50:48 +01001771 if (!InstallNatives()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001772
Andrei Popescu31002712010-02-23 13:46:05 +00001773 MakeFunctionInstancePrototypeWritable();
Steve Blocka7e24c12009-10-30 11:49:00 +00001774
Andrei Popescu31002712010-02-23 13:46:05 +00001775 if (!ConfigureGlobalObjects(global_template)) return;
1776 i::Counters::contexts_created_from_scratch.Increment();
1777 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001778
1779 result_ = global_context_;
1780}
1781
1782
1783// Support for thread preemption.
1784
1785// Reserve space for statics needing saving and restoring.
1786int Bootstrapper::ArchiveSpacePerThread() {
Andrei Popescu31002712010-02-23 13:46:05 +00001787 return BootstrapperActive::ArchiveSpacePerThread();
Steve Blocka7e24c12009-10-30 11:49:00 +00001788}
1789
1790
1791// Archive statics that are thread local.
1792char* Bootstrapper::ArchiveState(char* to) {
Andrei Popescu31002712010-02-23 13:46:05 +00001793 return BootstrapperActive::ArchiveState(to);
Steve Blocka7e24c12009-10-30 11:49:00 +00001794}
1795
1796
1797// Restore statics that are thread local.
1798char* Bootstrapper::RestoreState(char* from) {
Andrei Popescu31002712010-02-23 13:46:05 +00001799 return BootstrapperActive::RestoreState(from);
Steve Blocka7e24c12009-10-30 11:49:00 +00001800}
1801
1802
1803// Called when the top-level V8 mutex is destroyed.
1804void Bootstrapper::FreeThreadResources() {
Andrei Popescu31002712010-02-23 13:46:05 +00001805 ASSERT(!BootstrapperActive::IsActive());
Steve Blocka7e24c12009-10-30 11:49:00 +00001806}
1807
1808
1809// Reserve space for statics needing saving and restoring.
Andrei Popescu31002712010-02-23 13:46:05 +00001810int BootstrapperActive::ArchiveSpacePerThread() {
1811 return sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001812}
1813
1814
1815// Archive statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001816char* BootstrapperActive::ArchiveState(char* to) {
1817 *reinterpret_cast<int*>(to) = nesting_;
1818 nesting_ = 0;
1819 return to + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001820}
1821
1822
1823// Restore statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001824char* BootstrapperActive::RestoreState(char* from) {
1825 nesting_ = *reinterpret_cast<int*>(from);
1826 return from + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001827}
1828
1829} } // namespace v8::internal