blob: 0e49966bbdd7f50570569c1d34364786bfc2eaaa [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
John Reck59135872010-11-02 12:39:01 -07001012#define INSTALL_NATIVE(Type, name, var) \
1013 Handle<String> var##_name = Factory::LookupAsciiSymbol(name); \
1014 global_context()->set_##var(Type::cast( \
1015 global_context()->builtins()->GetPropertyNoExceptionThrown(*var##_name)));
Steve Blocka7e24c12009-10-30 11:49:00 +00001016
1017void Genesis::InstallNativeFunctions() {
1018 HandleScope scope;
1019 INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1020 INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1021 INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1022 INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1023 INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1024 INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1025 INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1026 INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
Leon Clarkee46be812010-01-19 14:06:41 +00001027 INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
Steve Blocka7e24c12009-10-30 11:49:00 +00001028 INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1029 INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1030 configure_instance_fun);
1031 INSTALL_NATIVE(JSFunction, "MakeMessage", make_message_fun);
1032 INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1033 INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1034}
1035
1036#undef INSTALL_NATIVE
1037
1038
1039bool Genesis::InstallNatives() {
1040 HandleScope scope;
1041
1042 // Create a function for the builtins object. Allocate space for the
1043 // JavaScript builtins, a reference to the builtins object
1044 // (itself) and a reference to the global_context directly in the object.
1045 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::Illegal));
1046 Handle<JSFunction> builtins_fun =
1047 Factory::NewFunction(Factory::empty_symbol(), JS_BUILTINS_OBJECT_TYPE,
1048 JSBuiltinsObject::kSize, code, true);
1049
1050 Handle<String> name = Factory::LookupAsciiSymbol("builtins");
1051 builtins_fun->shared()->set_instance_class_name(*name);
1052
1053 // Allocate the builtins object.
1054 Handle<JSBuiltinsObject> builtins =
1055 Handle<JSBuiltinsObject>::cast(Factory::NewGlobalObject(builtins_fun));
1056 builtins->set_builtins(*builtins);
1057 builtins->set_global_context(*global_context());
1058 builtins->set_global_receiver(*builtins);
1059
1060 // Setup the 'global' properties of the builtins object. The
1061 // 'global' property that refers to the global object is the only
1062 // way to get from code running in the builtins context to the
1063 // global object.
1064 static const PropertyAttributes attributes =
1065 static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001066 Handle<String> global_symbol = Factory::LookupAsciiSymbol("global");
1067 SetProperty(builtins,
1068 global_symbol,
1069 Handle<Object>(global_context()->global()),
1070 attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001071
1072 // Setup the reference from the global object to the builtins object.
1073 JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
1074
1075 // Create a bridge function that has context in the global context.
1076 Handle<JSFunction> bridge =
1077 Factory::NewFunction(Factory::empty_symbol(), Factory::undefined_value());
1078 ASSERT(bridge->context() == *Top::global_context());
1079
1080 // Allocate the builtins context.
1081 Handle<Context> context =
1082 Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1083 context->set_global(*builtins); // override builtins global object
1084
1085 global_context()->set_runtime_context(*context);
1086
1087 { // -- S c r i p t
1088 // Builtin functions for Script.
1089 Handle<JSFunction> script_fun =
1090 InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1091 Top::initial_object_prototype(), Builtins::Illegal,
1092 false);
1093 Handle<JSObject> prototype =
1094 Factory::NewJSObject(Top::object_function(), TENURED);
1095 SetPrototype(script_fun, prototype);
1096 global_context()->set_script_function(*script_fun);
1097
1098 // Add 'source' and 'data' property to scripts.
1099 PropertyAttributes common_attributes =
1100 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1101 Handle<Proxy> proxy_source = Factory::NewProxy(&Accessors::ScriptSource);
1102 Handle<DescriptorArray> script_descriptors =
1103 Factory::CopyAppendProxyDescriptor(
1104 Factory::empty_descriptor_array(),
1105 Factory::LookupAsciiSymbol("source"),
1106 proxy_source,
1107 common_attributes);
1108 Handle<Proxy> proxy_name = Factory::NewProxy(&Accessors::ScriptName);
1109 script_descriptors =
1110 Factory::CopyAppendProxyDescriptor(
1111 script_descriptors,
1112 Factory::LookupAsciiSymbol("name"),
1113 proxy_name,
1114 common_attributes);
1115 Handle<Proxy> proxy_id = Factory::NewProxy(&Accessors::ScriptId);
1116 script_descriptors =
1117 Factory::CopyAppendProxyDescriptor(
1118 script_descriptors,
1119 Factory::LookupAsciiSymbol("id"),
1120 proxy_id,
1121 common_attributes);
1122 Handle<Proxy> proxy_line_offset =
1123 Factory::NewProxy(&Accessors::ScriptLineOffset);
1124 script_descriptors =
1125 Factory::CopyAppendProxyDescriptor(
1126 script_descriptors,
1127 Factory::LookupAsciiSymbol("line_offset"),
1128 proxy_line_offset,
1129 common_attributes);
1130 Handle<Proxy> proxy_column_offset =
1131 Factory::NewProxy(&Accessors::ScriptColumnOffset);
1132 script_descriptors =
1133 Factory::CopyAppendProxyDescriptor(
1134 script_descriptors,
1135 Factory::LookupAsciiSymbol("column_offset"),
1136 proxy_column_offset,
1137 common_attributes);
1138 Handle<Proxy> proxy_data = Factory::NewProxy(&Accessors::ScriptData);
1139 script_descriptors =
1140 Factory::CopyAppendProxyDescriptor(
1141 script_descriptors,
1142 Factory::LookupAsciiSymbol("data"),
1143 proxy_data,
1144 common_attributes);
1145 Handle<Proxy> proxy_type = Factory::NewProxy(&Accessors::ScriptType);
1146 script_descriptors =
1147 Factory::CopyAppendProxyDescriptor(
1148 script_descriptors,
1149 Factory::LookupAsciiSymbol("type"),
1150 proxy_type,
1151 common_attributes);
1152 Handle<Proxy> proxy_compilation_type =
1153 Factory::NewProxy(&Accessors::ScriptCompilationType);
1154 script_descriptors =
1155 Factory::CopyAppendProxyDescriptor(
1156 script_descriptors,
1157 Factory::LookupAsciiSymbol("compilation_type"),
1158 proxy_compilation_type,
1159 common_attributes);
1160 Handle<Proxy> proxy_line_ends =
1161 Factory::NewProxy(&Accessors::ScriptLineEnds);
1162 script_descriptors =
1163 Factory::CopyAppendProxyDescriptor(
1164 script_descriptors,
1165 Factory::LookupAsciiSymbol("line_ends"),
1166 proxy_line_ends,
1167 common_attributes);
1168 Handle<Proxy> proxy_context_data =
1169 Factory::NewProxy(&Accessors::ScriptContextData);
1170 script_descriptors =
1171 Factory::CopyAppendProxyDescriptor(
1172 script_descriptors,
1173 Factory::LookupAsciiSymbol("context_data"),
1174 proxy_context_data,
1175 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001176 Handle<Proxy> proxy_eval_from_script =
1177 Factory::NewProxy(&Accessors::ScriptEvalFromScript);
Steve Blocka7e24c12009-10-30 11:49:00 +00001178 script_descriptors =
1179 Factory::CopyAppendProxyDescriptor(
1180 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001181 Factory::LookupAsciiSymbol("eval_from_script"),
1182 proxy_eval_from_script,
Steve Blocka7e24c12009-10-30 11:49:00 +00001183 common_attributes);
Steve Blockd0582a62009-12-15 09:54:21 +00001184 Handle<Proxy> proxy_eval_from_script_position =
1185 Factory::NewProxy(&Accessors::ScriptEvalFromScriptPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +00001186 script_descriptors =
1187 Factory::CopyAppendProxyDescriptor(
1188 script_descriptors,
Steve Blockd0582a62009-12-15 09:54:21 +00001189 Factory::LookupAsciiSymbol("eval_from_script_position"),
1190 proxy_eval_from_script_position,
1191 common_attributes);
1192 Handle<Proxy> proxy_eval_from_function_name =
1193 Factory::NewProxy(&Accessors::ScriptEvalFromFunctionName);
1194 script_descriptors =
1195 Factory::CopyAppendProxyDescriptor(
1196 script_descriptors,
1197 Factory::LookupAsciiSymbol("eval_from_function_name"),
1198 proxy_eval_from_function_name,
Steve Blocka7e24c12009-10-30 11:49:00 +00001199 common_attributes);
1200
1201 Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1202 script_map->set_instance_descriptors(*script_descriptors);
1203
1204 // Allocate the empty script.
1205 Handle<Script> script = Factory::NewScript(Factory::empty_string());
1206 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Andrei Popescu31002712010-02-23 13:46:05 +00001207 Heap::public_set_empty_script(*script);
Steve Blocka7e24c12009-10-30 11:49:00 +00001208 }
Steve Block6ded16b2010-05-10 14:33:55 +01001209 {
1210 // Builtin function for OpaqueReference -- a JSValue-based object,
1211 // that keeps its field isolated from JavaScript code. It may store
1212 // objects, that JavaScript code may not access.
1213 Handle<JSFunction> opaque_reference_fun =
1214 InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1215 JSValue::kSize, Top::initial_object_prototype(),
1216 Builtins::Illegal, false);
1217 Handle<JSObject> prototype =
1218 Factory::NewJSObject(Top::object_function(), TENURED);
1219 SetPrototype(opaque_reference_fun, prototype);
1220 global_context()->set_opaque_reference_function(*opaque_reference_fun);
1221 }
1222
1223 if (FLAG_disable_native_files) {
1224 PrintF("Warning: Running without installed natives!\n");
1225 return true;
1226 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001227
Andrei Popescu31002712010-02-23 13:46:05 +00001228 // Install natives.
1229 for (int i = Natives::GetDebuggerCount();
1230 i < Natives::GetBuiltinsCount();
1231 i++) {
1232 Vector<const char> name = Natives::GetScriptName(i);
1233 if (!CompileBuiltin(i)) return false;
Andrei Popescu402d9372010-02-26 13:31:12 +00001234 // TODO(ager): We really only need to install the JS builtin
1235 // functions on the builtins object after compiling and running
1236 // runtime.js.
1237 if (!InstallJSBuiltins(builtins)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001238 }
1239
1240 InstallNativeFunctions();
1241
Iain Merrick75681382010-08-19 15:07:18 +01001242 // Store the map for the string prototype after the natives has been compiled
1243 // and the String function has been setup.
1244 Handle<JSFunction> string_function(global_context()->string_function());
1245 ASSERT(JSObject::cast(
1246 string_function->initial_map()->prototype())->HasFastProperties());
1247 global_context()->set_string_function_prototype_map(
1248 HeapObject::cast(string_function->initial_map()->prototype())->map());
1249
Kristian Monsen25f61362010-05-21 11:50:48 +01001250 InstallCustomCallGenerators();
1251
Steve Blocka7e24c12009-10-30 11:49:00 +00001252 // Install Function.prototype.call and apply.
1253 { Handle<String> key = Factory::function_class_symbol();
1254 Handle<JSFunction> function =
1255 Handle<JSFunction>::cast(GetProperty(Top::global(), key));
1256 Handle<JSObject> proto =
1257 Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1258
1259 // Install the call and the apply functions.
1260 Handle<JSFunction> call =
1261 InstallFunction(proto, "call", 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::FunctionCall,
1264 false);
1265 Handle<JSFunction> apply =
1266 InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
Steve Block6ded16b2010-05-10 14:33:55 +01001267 Handle<JSObject>::null(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001268 Builtins::FunctionApply,
1269 false);
1270
1271 // Make sure that Function.prototype.call appears to be compiled.
1272 // The code will never be called, but inline caching for call will
1273 // only work if it appears to be compiled.
1274 call->shared()->DontAdaptArguments();
1275 ASSERT(call->is_compiled());
1276
1277 // Set the expected parameters for apply to 2; required by builtin.
1278 apply->shared()->set_formal_parameter_count(2);
1279
1280 // Set the lengths for the functions to satisfy ECMA-262.
1281 call->shared()->set_length(1);
1282 apply->shared()->set_length(2);
1283 }
1284
Steve Block6ded16b2010-05-10 14:33:55 +01001285 // Create a constructor for RegExp results (a variant of Array that
1286 // predefines the two properties index and match).
1287 {
1288 // RegExpResult initial map.
1289
1290 // Find global.Array.prototype to inherit from.
1291 Handle<JSFunction> array_constructor(global_context()->array_function());
1292 Handle<JSObject> array_prototype(
1293 JSObject::cast(array_constructor->instance_prototype()));
1294
1295 // Add initial map.
1296 Handle<Map> initial_map =
1297 Factory::NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1298 initial_map->set_constructor(*array_constructor);
1299
1300 // Set prototype on map.
1301 initial_map->set_non_instance_prototype(false);
1302 initial_map->set_prototype(*array_prototype);
1303
1304 // Update map with length accessor from Array and add "index" and "input".
1305 Handle<Map> array_map(global_context()->js_array_map());
1306 Handle<DescriptorArray> array_descriptors(
1307 array_map->instance_descriptors());
1308 ASSERT_EQ(1, array_descriptors->number_of_descriptors());
1309
1310 Handle<DescriptorArray> reresult_descriptors =
1311 Factory::NewDescriptorArray(3);
1312
1313 reresult_descriptors->CopyFrom(0, *array_descriptors, 0);
1314
1315 int enum_index = 0;
1316 {
1317 FieldDescriptor index_field(Heap::index_symbol(),
1318 JSRegExpResult::kIndexIndex,
1319 NONE,
1320 enum_index++);
1321 reresult_descriptors->Set(1, &index_field);
1322 }
1323
1324 {
1325 FieldDescriptor input_field(Heap::input_symbol(),
1326 JSRegExpResult::kInputIndex,
1327 NONE,
1328 enum_index++);
1329 reresult_descriptors->Set(2, &input_field);
1330 }
1331 reresult_descriptors->Sort();
1332
1333 initial_map->set_inobject_properties(2);
1334 initial_map->set_pre_allocated_property_fields(2);
1335 initial_map->set_unused_property_fields(0);
1336 initial_map->set_instance_descriptors(*reresult_descriptors);
1337
1338 global_context()->set_regexp_result_map(*initial_map);
1339 }
1340
Steve Blocka7e24c12009-10-30 11:49:00 +00001341#ifdef DEBUG
1342 builtins->Verify();
1343#endif
Andrei Popescu31002712010-02-23 13:46:05 +00001344
Steve Blocka7e24c12009-10-30 11:49:00 +00001345 return true;
1346}
1347
1348
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001349static Handle<JSObject> ResolveCustomCallGeneratorHolder(
1350 Handle<Context> global_context,
1351 const char* holder_expr) {
1352 Handle<GlobalObject> global(global_context->global());
1353 const char* period_pos = strchr(holder_expr, '.');
1354 if (period_pos == NULL) {
1355 return Handle<JSObject>::cast(
1356 GetProperty(global, Factory::LookupAsciiSymbol(holder_expr)));
Steve Block59151502010-09-22 15:07:15 +01001357 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001358 ASSERT_EQ(".prototype", period_pos);
1359 Vector<const char> property(holder_expr,
1360 static_cast<int>(period_pos - holder_expr));
1361 Handle<JSFunction> function = Handle<JSFunction>::cast(
1362 GetProperty(global, Factory::LookupSymbol(property)));
1363 return Handle<JSObject>(JSObject::cast(function->prototype()));
1364}
1365
1366
1367static void InstallCustomCallGenerator(Handle<JSObject> holder,
1368 const char* function_name,
1369 int id) {
Kristian Monsen25f61362010-05-21 11:50:48 +01001370 Handle<String> name = Factory::LookupAsciiSymbol(function_name);
John Reck59135872010-11-02 12:39:01 -07001371 Object* function_object = holder->GetProperty(*name)->ToObjectUnchecked();
1372 Handle<JSFunction> function(JSFunction::cast(function_object));
Kristian Monsen25f61362010-05-21 11:50:48 +01001373 function->shared()->set_function_data(Smi::FromInt(id));
1374}
1375
1376
1377void Genesis::InstallCustomCallGenerators() {
1378 HandleScope scope;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001379#define INSTALL_CALL_GENERATOR(holder_expr, fun_name, name) \
1380 { \
1381 Handle<JSObject> holder = ResolveCustomCallGeneratorHolder( \
1382 global_context(), #holder_expr); \
1383 const int id = CallStubCompiler::k##name##CallGenerator; \
1384 InstallCustomCallGenerator(holder, #fun_name, id); \
Kristian Monsen25f61362010-05-21 11:50:48 +01001385 }
1386 CUSTOM_CALL_IC_GENERATORS(INSTALL_CALL_GENERATOR)
1387#undef INSTALL_CALL_GENERATOR
1388}
1389
1390
Steve Block6ded16b2010-05-10 14:33:55 +01001391// Do not forget to update macros.py with named constant
1392// of cache id.
1393#define JSFUNCTION_RESULT_CACHE_LIST(F) \
1394 F(16, global_context()->regexp_function())
1395
1396
1397static FixedArray* CreateCache(int size, JSFunction* factory) {
1398 // Caches are supposed to live for a long time, allocate in old space.
1399 int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1400 // Cannot use cast as object is not fully initialized yet.
1401 JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1402 *Factory::NewFixedArrayWithHoles(array_size, TENURED));
1403 cache->set(JSFunctionResultCache::kFactoryIndex, factory);
1404 cache->MakeZeroSize();
1405 return cache;
1406}
1407
1408
1409void Genesis::InstallJSFunctionResultCaches() {
1410 const int kNumberOfCaches = 0 +
1411#define F(size, func) + 1
1412 JSFUNCTION_RESULT_CACHE_LIST(F)
1413#undef F
1414 ;
1415
1416 Handle<FixedArray> caches = Factory::NewFixedArray(kNumberOfCaches, TENURED);
1417
1418 int index = 0;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001419
1420#define F(size, func) do { \
1421 FixedArray* cache = CreateCache((size), (func)); \
1422 caches->set(index++, cache); \
1423 } while (false)
1424
1425 JSFUNCTION_RESULT_CACHE_LIST(F);
1426
Steve Block6ded16b2010-05-10 14:33:55 +01001427#undef F
1428
1429 global_context()->set_jsfunction_result_caches(*caches);
1430}
1431
1432
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001433void Genesis::InitializeNormalizedMapCaches() {
1434 Handle<FixedArray> array(
1435 Factory::NewFixedArray(NormalizedMapCache::kEntries, TENURED));
1436 global_context()->set_normalized_map_cache(NormalizedMapCache::cast(*array));
1437}
1438
1439
Andrei Popescu31002712010-02-23 13:46:05 +00001440int BootstrapperActive::nesting_ = 0;
1441
1442
1443bool Bootstrapper::InstallExtensions(Handle<Context> global_context,
1444 v8::ExtensionConfiguration* extensions) {
1445 BootstrapperActive active;
1446 SaveContext saved_context;
1447 Top::set_context(*global_context);
1448 if (!Genesis::InstallExtensions(global_context, extensions)) return false;
1449 Genesis::InstallSpecialObjects(global_context);
1450 return true;
1451}
1452
1453
1454void Genesis::InstallSpecialObjects(Handle<Context> global_context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001455 HandleScope scope;
1456 Handle<JSGlobalObject> js_global(
Andrei Popescu31002712010-02-23 13:46:05 +00001457 JSGlobalObject::cast(global_context->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001458 // Expose the natives in global if a name for it is specified.
1459 if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1460 Handle<String> natives_string =
1461 Factory::LookupAsciiSymbol(FLAG_expose_natives_as);
1462 SetProperty(js_global, natives_string,
1463 Handle<JSObject>(js_global->builtins()), DONT_ENUM);
1464 }
1465
1466 Handle<Object> Error = GetProperty(js_global, "Error");
1467 if (Error->IsJSObject()) {
1468 Handle<String> name = Factory::LookupAsciiSymbol("stackTraceLimit");
1469 SetProperty(Handle<JSObject>::cast(Error),
1470 name,
1471 Handle<Smi>(Smi::FromInt(FLAG_stack_trace_limit)),
1472 NONE);
1473 }
1474
1475#ifdef ENABLE_DEBUGGER_SUPPORT
1476 // Expose the debug global object in global if a name for it is specified.
1477 if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1478 // If loading fails we just bail out without installing the
1479 // debugger but without tanking the whole context.
Andrei Popescu31002712010-02-23 13:46:05 +00001480 if (!Debug::Load()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001481 // Set the security token for the debugger context to the same as
1482 // the shell global context to allow calling between these (otherwise
1483 // exposing debug global object doesn't make much sense).
1484 Debug::debug_context()->set_security_token(
Andrei Popescu31002712010-02-23 13:46:05 +00001485 global_context->security_token());
Steve Blocka7e24c12009-10-30 11:49:00 +00001486
1487 Handle<String> debug_string =
1488 Factory::LookupAsciiSymbol(FLAG_expose_debug_as);
1489 SetProperty(js_global, debug_string,
1490 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM);
1491 }
1492#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001493}
1494
1495
Andrei Popescu31002712010-02-23 13:46:05 +00001496bool Genesis::InstallExtensions(Handle<Context> global_context,
1497 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001498 // Clear coloring of extension list
1499 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1500 while (current != NULL) {
1501 current->set_state(v8::UNVISITED);
1502 current = current->next();
1503 }
Andrei Popescu31002712010-02-23 13:46:05 +00001504 // Install auto extensions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001505 current = v8::RegisteredExtension::first_extension();
1506 while (current != NULL) {
1507 if (current->extension()->auto_enable())
1508 InstallExtension(current);
1509 current = current->next();
1510 }
1511
1512 if (FLAG_expose_gc) InstallExtension("v8/gc");
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001513 if (FLAG_expose_externalize_string) InstallExtension("v8/externalize");
Steve Blocka7e24c12009-10-30 11:49:00 +00001514
1515 if (extensions == NULL) return true;
1516 // Install required extensions
1517 int count = v8::ImplementationUtilities::GetNameCount(extensions);
1518 const char** names = v8::ImplementationUtilities::GetNames(extensions);
1519 for (int i = 0; i < count; i++) {
1520 if (!InstallExtension(names[i]))
1521 return false;
1522 }
1523
1524 return true;
1525}
1526
1527
1528// Installs a named extension. This methods is unoptimized and does
1529// not scale well if we want to support a large number of extensions.
1530bool Genesis::InstallExtension(const char* name) {
1531 v8::RegisteredExtension* current = v8::RegisteredExtension::first_extension();
1532 // Loop until we find the relevant extension
1533 while (current != NULL) {
1534 if (strcmp(name, current->extension()->name()) == 0) break;
1535 current = current->next();
1536 }
1537 // Didn't find the extension; fail.
1538 if (current == NULL) {
1539 v8::Utils::ReportApiFailure(
1540 "v8::Context::New()", "Cannot find required extension");
1541 return false;
1542 }
1543 return InstallExtension(current);
1544}
1545
1546
1547bool Genesis::InstallExtension(v8::RegisteredExtension* current) {
1548 HandleScope scope;
1549
1550 if (current->state() == v8::INSTALLED) return true;
1551 // The current node has already been visited so there must be a
1552 // cycle in the dependency graph; fail.
1553 if (current->state() == v8::VISITED) {
1554 v8::Utils::ReportApiFailure(
1555 "v8::Context::New()", "Circular extension dependency");
1556 return false;
1557 }
1558 ASSERT(current->state() == v8::UNVISITED);
1559 current->set_state(v8::VISITED);
1560 v8::Extension* extension = current->extension();
1561 // Install the extension's dependencies
1562 for (int i = 0; i < extension->dependency_count(); i++) {
1563 if (!InstallExtension(extension->dependencies()[i])) return false;
1564 }
1565 Vector<const char> source = CStrVector(extension->source());
1566 Handle<String> source_code = Factory::NewStringFromAscii(source);
1567 bool result = CompileScriptCached(CStrVector(extension->name()),
1568 source_code,
Andrei Popescu31002712010-02-23 13:46:05 +00001569 &extensions_cache,
1570 extension,
1571 Handle<Context>(Top::context()),
Steve Blocka7e24c12009-10-30 11:49:00 +00001572 false);
1573 ASSERT(Top::has_pending_exception() != result);
1574 if (!result) {
1575 Top::clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001576 }
1577 current->set_state(v8::INSTALLED);
1578 return result;
1579}
1580
1581
Andrei Popescu402d9372010-02-26 13:31:12 +00001582bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
1583 HandleScope scope;
1584 for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
1585 Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
1586 Handle<String> name = Factory::LookupAsciiSymbol(Builtins::GetName(id));
John Reck59135872010-11-02 12:39:01 -07001587 Object* function_object = builtins->GetPropertyNoExceptionThrown(*name);
Andrei Popescu402d9372010-02-26 13:31:12 +00001588 Handle<JSFunction> function
John Reck59135872010-11-02 12:39:01 -07001589 = Handle<JSFunction>(JSFunction::cast(function_object));
Andrei Popescu402d9372010-02-26 13:31:12 +00001590 builtins->set_javascript_builtin(id, *function);
1591 Handle<SharedFunctionInfo> shared
1592 = Handle<SharedFunctionInfo>(function->shared());
1593 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Iain Merrick75681382010-08-19 15:07:18 +01001594 // Set the code object on the function object.
1595 function->set_code(function->shared()->code());
Steve Block6ded16b2010-05-10 14:33:55 +01001596 builtins->set_javascript_builtin_code(id, shared->code());
Andrei Popescu402d9372010-02-26 13:31:12 +00001597 }
1598 return true;
Andrei Popescu31002712010-02-23 13:46:05 +00001599}
1600
1601
Steve Blocka7e24c12009-10-30 11:49:00 +00001602bool Genesis::ConfigureGlobalObjects(
1603 v8::Handle<v8::ObjectTemplate> global_proxy_template) {
1604 Handle<JSObject> global_proxy(
1605 JSObject::cast(global_context()->global_proxy()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001606 Handle<JSObject> inner_global(JSObject::cast(global_context()->global()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001607
1608 if (!global_proxy_template.IsEmpty()) {
1609 // Configure the global proxy object.
1610 Handle<ObjectTemplateInfo> proxy_data =
1611 v8::Utils::OpenHandle(*global_proxy_template);
1612 if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
1613
1614 // Configure the inner global object.
1615 Handle<FunctionTemplateInfo> proxy_constructor(
1616 FunctionTemplateInfo::cast(proxy_data->constructor()));
1617 if (!proxy_constructor->prototype_template()->IsUndefined()) {
1618 Handle<ObjectTemplateInfo> inner_data(
1619 ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
Andrei Popescu402d9372010-02-26 13:31:12 +00001620 if (!ConfigureApiObject(inner_global, inner_data)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001621 }
1622 }
1623
Andrei Popescu402d9372010-02-26 13:31:12 +00001624 SetObjectPrototype(global_proxy, inner_global);
Steve Blocka7e24c12009-10-30 11:49:00 +00001625 return true;
1626}
1627
1628
1629bool Genesis::ConfigureApiObject(Handle<JSObject> object,
1630 Handle<ObjectTemplateInfo> object_template) {
1631 ASSERT(!object_template.is_null());
1632 ASSERT(object->IsInstanceOf(
1633 FunctionTemplateInfo::cast(object_template->constructor())));
1634
1635 bool pending_exception = false;
1636 Handle<JSObject> obj =
1637 Execution::InstantiateObject(object_template, &pending_exception);
1638 if (pending_exception) {
1639 ASSERT(Top::has_pending_exception());
1640 Top::clear_pending_exception();
1641 return false;
1642 }
1643 TransferObject(obj, object);
1644 return true;
1645}
1646
1647
1648void Genesis::TransferNamedProperties(Handle<JSObject> from,
1649 Handle<JSObject> to) {
1650 if (from->HasFastProperties()) {
1651 Handle<DescriptorArray> descs =
1652 Handle<DescriptorArray>(from->map()->instance_descriptors());
1653 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1654 PropertyDetails details = PropertyDetails(descs->GetDetails(i));
1655 switch (details.type()) {
1656 case FIELD: {
1657 HandleScope inner;
1658 Handle<String> key = Handle<String>(descs->GetKey(i));
1659 int index = descs->GetFieldIndex(i);
1660 Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
1661 SetProperty(to, key, value, details.attributes());
1662 break;
1663 }
1664 case CONSTANT_FUNCTION: {
1665 HandleScope inner;
1666 Handle<String> key = Handle<String>(descs->GetKey(i));
1667 Handle<JSFunction> fun =
1668 Handle<JSFunction>(descs->GetConstantFunction(i));
1669 SetProperty(to, key, fun, details.attributes());
1670 break;
1671 }
1672 case CALLBACKS: {
1673 LookupResult result;
1674 to->LocalLookup(descs->GetKey(i), &result);
1675 // If the property is already there we skip it
Andrei Popescu402d9372010-02-26 13:31:12 +00001676 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001677 HandleScope inner;
Andrei Popescu31002712010-02-23 13:46:05 +00001678 ASSERT(!to->HasFastProperties());
1679 // Add to dictionary.
Steve Blocka7e24c12009-10-30 11:49:00 +00001680 Handle<String> key = Handle<String>(descs->GetKey(i));
Andrei Popescu31002712010-02-23 13:46:05 +00001681 Handle<Object> callbacks(descs->GetCallbacksObject(i));
1682 PropertyDetails d =
1683 PropertyDetails(details.attributes(), CALLBACKS, details.index());
1684 SetNormalizedProperty(to, key, callbacks, d);
Steve Blocka7e24c12009-10-30 11:49:00 +00001685 break;
1686 }
1687 case MAP_TRANSITION:
1688 case CONSTANT_TRANSITION:
1689 case NULL_DESCRIPTOR:
1690 // Ignore non-properties.
1691 break;
1692 case NORMAL:
1693 // Do not occur since the from object has fast properties.
1694 case INTERCEPTOR:
1695 // No element in instance descriptors have interceptor type.
1696 UNREACHABLE();
1697 break;
1698 }
1699 }
1700 } else {
1701 Handle<StringDictionary> properties =
1702 Handle<StringDictionary>(from->property_dictionary());
1703 int capacity = properties->Capacity();
1704 for (int i = 0; i < capacity; i++) {
1705 Object* raw_key(properties->KeyAt(i));
1706 if (properties->IsKey(raw_key)) {
1707 ASSERT(raw_key->IsString());
1708 // If the property is already there we skip it.
1709 LookupResult result;
1710 to->LocalLookup(String::cast(raw_key), &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001711 if (result.IsProperty()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00001712 // Set the property.
1713 Handle<String> key = Handle<String>(String::cast(raw_key));
1714 Handle<Object> value = Handle<Object>(properties->ValueAt(i));
1715 if (value->IsJSGlobalPropertyCell()) {
1716 value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
1717 }
1718 PropertyDetails details = properties->DetailsAt(i);
1719 SetProperty(to, key, value, details.attributes());
1720 }
1721 }
1722 }
1723}
1724
1725
1726void Genesis::TransferIndexedProperties(Handle<JSObject> from,
1727 Handle<JSObject> to) {
1728 // Cloning the elements array is sufficient.
1729 Handle<FixedArray> from_elements =
1730 Handle<FixedArray>(FixedArray::cast(from->elements()));
1731 Handle<FixedArray> to_elements = Factory::CopyFixedArray(from_elements);
1732 to->set_elements(*to_elements);
1733}
1734
1735
1736void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
1737 HandleScope outer;
1738
1739 ASSERT(!from->IsJSArray());
1740 ASSERT(!to->IsJSArray());
1741
1742 TransferNamedProperties(from, to);
1743 TransferIndexedProperties(from, to);
1744
1745 // Transfer the prototype (new map is needed).
1746 Handle<Map> old_to_map = Handle<Map>(to->map());
1747 Handle<Map> new_to_map = Factory::CopyMapDropTransitions(old_to_map);
1748 new_to_map->set_prototype(from->map()->prototype());
1749 to->set_map(*new_to_map);
1750}
1751
1752
1753void Genesis::MakeFunctionInstancePrototypeWritable() {
1754 // Make a new function map so all future functions
1755 // will have settable and enumerable prototype properties.
1756 HandleScope scope;
1757
1758 Handle<DescriptorArray> function_map_descriptors =
Steve Block6ded16b2010-05-10 14:33:55 +01001759 ComputeFunctionInstanceDescriptor(ADD_WRITEABLE_PROTOTYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001760 Handle<Map> fm = Factory::CopyMapDropDescriptors(Top::function_map());
1761 fm->set_instance_descriptors(*function_map_descriptors);
Steve Block6ded16b2010-05-10 14:33:55 +01001762 fm->set_function_with_prototype(true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001763 Top::context()->global_context()->set_function_map(*fm);
1764}
1765
1766
Steve Blocka7e24c12009-10-30 11:49:00 +00001767Genesis::Genesis(Handle<Object> global_object,
1768 v8::Handle<v8::ObjectTemplate> global_template,
1769 v8::ExtensionConfiguration* extensions) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001770 result_ = Handle<Context>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +00001771 // If V8 isn't running and cannot be initialized, just return.
1772 if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
1773
1774 // Before creating the roots we must save the context and restore it
1775 // on all function exits.
1776 HandleScope scope;
Andrei Popescu31002712010-02-23 13:46:05 +00001777 SaveContext saved_context;
Steve Blocka7e24c12009-10-30 11:49:00 +00001778
Andrei Popescu31002712010-02-23 13:46:05 +00001779 Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
1780 if (!new_context.is_null()) {
1781 global_context_ =
1782 Handle<Context>::cast(GlobalHandles::Create(*new_context));
1783 Top::set_context(*global_context_);
1784 i::Counters::contexts_created_by_snapshot.Increment();
1785 result_ = global_context_;
1786 JSFunction* empty_function =
1787 JSFunction::cast(result_->function_map()->prototype());
1788 empty_function_ = Handle<JSFunction>(empty_function);
Andrei Popescu402d9372010-02-26 13:31:12 +00001789 Handle<GlobalObject> inner_global;
Andrei Popescu31002712010-02-23 13:46:05 +00001790 Handle<JSGlobalProxy> global_proxy =
1791 CreateNewGlobals(global_template,
1792 global_object,
Andrei Popescu402d9372010-02-26 13:31:12 +00001793 &inner_global);
1794
Andrei Popescu31002712010-02-23 13:46:05 +00001795 HookUpGlobalProxy(inner_global, global_proxy);
Andrei Popescu402d9372010-02-26 13:31:12 +00001796 HookUpInnerGlobal(inner_global);
1797
Andrei Popescu31002712010-02-23 13:46:05 +00001798 if (!ConfigureGlobalObjects(global_template)) return;
1799 } else {
1800 // We get here if there was no context snapshot.
1801 CreateRoots();
1802 Handle<JSFunction> empty_function = CreateEmptyFunction();
1803 Handle<GlobalObject> inner_global;
1804 Handle<JSGlobalProxy> global_proxy =
1805 CreateNewGlobals(global_template, global_object, &inner_global);
1806 HookUpGlobalProxy(inner_global, global_proxy);
1807 InitializeGlobal(inner_global, empty_function);
Steve Block6ded16b2010-05-10 14:33:55 +01001808 InstallJSFunctionResultCaches();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001809 InitializeNormalizedMapCaches();
Kristian Monsen25f61362010-05-21 11:50:48 +01001810 if (!InstallNatives()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001811
Andrei Popescu31002712010-02-23 13:46:05 +00001812 MakeFunctionInstancePrototypeWritable();
Steve Blocka7e24c12009-10-30 11:49:00 +00001813
Andrei Popescu31002712010-02-23 13:46:05 +00001814 if (!ConfigureGlobalObjects(global_template)) return;
1815 i::Counters::contexts_created_from_scratch.Increment();
1816 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001817
Ben Murdochf87a2032010-10-22 12:50:53 +01001818 // Add this context to the weak list of global contexts.
1819 (*global_context_)->set(Context::NEXT_CONTEXT_LINK,
1820 Heap::global_contexts_list());
1821 Heap::set_global_contexts_list(*global_context_);
1822
Steve Blocka7e24c12009-10-30 11:49:00 +00001823 result_ = global_context_;
1824}
1825
1826
1827// Support for thread preemption.
1828
1829// Reserve space for statics needing saving and restoring.
1830int Bootstrapper::ArchiveSpacePerThread() {
Andrei Popescu31002712010-02-23 13:46:05 +00001831 return BootstrapperActive::ArchiveSpacePerThread();
Steve Blocka7e24c12009-10-30 11:49:00 +00001832}
1833
1834
1835// Archive statics that are thread local.
1836char* Bootstrapper::ArchiveState(char* to) {
Andrei Popescu31002712010-02-23 13:46:05 +00001837 return BootstrapperActive::ArchiveState(to);
Steve Blocka7e24c12009-10-30 11:49:00 +00001838}
1839
1840
1841// Restore statics that are thread local.
1842char* Bootstrapper::RestoreState(char* from) {
Andrei Popescu31002712010-02-23 13:46:05 +00001843 return BootstrapperActive::RestoreState(from);
Steve Blocka7e24c12009-10-30 11:49:00 +00001844}
1845
1846
1847// Called when the top-level V8 mutex is destroyed.
1848void Bootstrapper::FreeThreadResources() {
Andrei Popescu31002712010-02-23 13:46:05 +00001849 ASSERT(!BootstrapperActive::IsActive());
Steve Blocka7e24c12009-10-30 11:49:00 +00001850}
1851
1852
1853// Reserve space for statics needing saving and restoring.
Andrei Popescu31002712010-02-23 13:46:05 +00001854int BootstrapperActive::ArchiveSpacePerThread() {
1855 return sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001856}
1857
1858
1859// Archive statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001860char* BootstrapperActive::ArchiveState(char* to) {
1861 *reinterpret_cast<int*>(to) = nesting_;
1862 nesting_ = 0;
1863 return to + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001864}
1865
1866
1867// Restore statics that are thread local.
Andrei Popescu31002712010-02-23 13:46:05 +00001868char* BootstrapperActive::RestoreState(char* from) {
1869 nesting_ = *reinterpret_cast<int*>(from);
1870 return from + sizeof(nesting_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001871}
1872
1873} } // namespace v8::internal