v8  3.14.5(node0.10.28)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
bootstrapper.cc
Go to the documentation of this file.
1 // Copyright 2012 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 "isolate-inl.h"
38 #include "macro-assembler.h"
39 #include "natives.h"
40 #include "objects-visiting.h"
41 #include "platform.h"
42 #include "snapshot.h"
46 
47 namespace v8 {
48 namespace internal {
49 
50 
52  Bootstrapper* bootstrapper,
53  const char* source,
54  size_t length)
55  : data_(source), length_(length) {
56  if (bootstrapper->delete_these_non_arrays_on_tear_down_ == NULL) {
57  bootstrapper->delete_these_non_arrays_on_tear_down_ = new List<char*>(2);
58  }
59  // The resources are small objects and we only make a fixed number of
60  // them, but let's clean them up on exit for neatness.
61  bootstrapper->delete_these_non_arrays_on_tear_down_->
62  Add(reinterpret_cast<char*>(this));
63 }
64 
65 
66 Bootstrapper::Bootstrapper()
67  : nesting_(0),
68  extensions_cache_(Script::TYPE_EXTENSION),
69  delete_these_non_arrays_on_tear_down_(NULL),
70  delete_these_arrays_on_tear_down_(NULL) {
71 }
72 
73 
75  ASSERT(0 <= index && index < Natives::GetBuiltinsCount());
76  Isolate* isolate = Isolate::Current();
77  Factory* factory = isolate->factory();
78  Heap* heap = isolate->heap();
79  if (heap->natives_source_cache()->get(index)->IsUndefined()) {
80  // We can use external strings for the natives.
84  source.start(),
85  source.length());
86  Handle<String> source_code =
87  factory->NewExternalStringFromAscii(resource);
88  heap->natives_source_cache()->set(index, *source_code);
89  }
90  Handle<Object> cached_source(heap->natives_source_cache()->get(index));
91  return Handle<String>::cast(cached_source);
92 }
93 
94 
95 void Bootstrapper::Initialize(bool create_heap_objects) {
96  extensions_cache_.Initialize(create_heap_objects);
100 }
101 
102 
104  char* memory = new char[bytes];
105  if (memory != NULL) {
106  if (delete_these_arrays_on_tear_down_ == NULL) {
107  delete_these_arrays_on_tear_down_ = new List<char*>(2);
108  }
109  delete_these_arrays_on_tear_down_->Add(memory);
110  }
111  return memory;
112 }
113 
114 
116  if (delete_these_non_arrays_on_tear_down_ != NULL) {
117  int len = delete_these_non_arrays_on_tear_down_->length();
118  ASSERT(len < 20); // Don't use this mechanism for unbounded allocations.
119  for (int i = 0; i < len; i++) {
120  delete delete_these_non_arrays_on_tear_down_->at(i);
121  delete_these_non_arrays_on_tear_down_->at(i) = NULL;
122  }
123  delete delete_these_non_arrays_on_tear_down_;
124  delete_these_non_arrays_on_tear_down_ = NULL;
125  }
126 
127  if (delete_these_arrays_on_tear_down_ != NULL) {
128  int len = delete_these_arrays_on_tear_down_->length();
129  ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations.
130  for (int i = 0; i < len; i++) {
131  delete[] delete_these_arrays_on_tear_down_->at(i);
132  delete_these_arrays_on_tear_down_->at(i) = NULL;
133  }
134  delete delete_these_arrays_on_tear_down_;
135  delete_these_arrays_on_tear_down_ = NULL;
136  }
137 
138  extensions_cache_.Initialize(false); // Yes, symmetrical
139 }
140 
141 
142 class Genesis BASE_EMBEDDED {
143  public:
144  Genesis(Isolate* isolate,
145  Handle<Object> global_object,
146  v8::Handle<v8::ObjectTemplate> global_template,
147  v8::ExtensionConfiguration* extensions);
148  ~Genesis() { }
149 
150  Handle<Context> result() { return result_; }
151 
152  Genesis* previous() { return previous_; }
153 
154  Isolate* isolate() const { return isolate_; }
155  Factory* factory() const { return isolate_->factory(); }
156  Heap* heap() const { return isolate_->heap(); }
157 
158  private:
159  Handle<Context> native_context_;
160  Isolate* isolate_;
161 
162  // There may be more than one active genesis object: When GC is
163  // triggered during environment creation there may be weak handle
164  // processing callbacks which may create new environments.
165  Genesis* previous_;
166 
167  Handle<Context> native_context() { return native_context_; }
168 
169  // Creates some basic objects. Used for creating a context from scratch.
170  void CreateRoots();
171  // Creates the empty function. Used for creating a context from scratch.
172  Handle<JSFunction> CreateEmptyFunction(Isolate* isolate);
173  // Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
174  Handle<JSFunction> GetThrowTypeErrorFunction();
175 
176  void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
177 
178  // Make the "arguments" and "caller" properties throw a TypeError on access.
179  void PoisonArgumentsAndCaller(Handle<Map> map);
180 
181  // Creates the global objects using the global and the template passed in
182  // through the API. We call this regardless of whether we are building a
183  // context from scratch or using a deserialized one from the partial snapshot
184  // but in the latter case we don't use the objects it produces directly, as
185  // we have to used the deserialized ones that are linked together with the
186  // rest of the context snapshot.
187  Handle<JSGlobalProxy> CreateNewGlobals(
188  v8::Handle<v8::ObjectTemplate> global_template,
189  Handle<Object> global_object,
190  Handle<GlobalObject>* global_proxy_out);
191  // Hooks the given global proxy into the context. If the context was created
192  // by deserialization then this will unhook the global proxy that was
193  // deserialized, leaving the GC to pick it up.
194  void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
195  Handle<JSGlobalProxy> global_proxy);
196  // Similarly, we want to use the inner global that has been created by the
197  // templates passed through the API. The inner global from the snapshot is
198  // detached from the other objects in the snapshot.
199  void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
200  // New context initialization. Used for creating a context from scratch.
201  bool InitializeGlobal(Handle<GlobalObject> inner_global,
202  Handle<JSFunction> empty_function);
203  void InitializeExperimentalGlobal();
204  // Installs the contents of the native .js files on the global objects.
205  // Used for creating a context from scratch.
206  void InstallNativeFunctions();
207  void InstallExperimentalNativeFunctions();
208  bool InstallNatives();
209  bool InstallExperimentalNatives();
210  void InstallBuiltinFunctionIds();
211  void InstallJSFunctionResultCaches();
212  void InitializeNormalizedMapCaches();
213 
214  enum ExtensionTraversalState {
215  UNVISITED, VISITED, INSTALLED
216  };
217 
218  class ExtensionStates {
219  public:
220  ExtensionStates();
221  ExtensionTraversalState get_state(RegisteredExtension* extension);
222  void set_state(RegisteredExtension* extension,
223  ExtensionTraversalState state);
224  private:
225  HashMap map_;
226  DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
227  };
228 
229  // Used both for deserialized and from-scratch contexts to add the extensions
230  // provided.
231  static bool InstallExtensions(Handle<Context> native_context,
232  v8::ExtensionConfiguration* extensions);
233  static bool InstallExtension(const char* name,
234  ExtensionStates* extension_states);
235  static bool InstallExtension(v8::RegisteredExtension* current,
236  ExtensionStates* extension_states);
237  static void InstallSpecialObjects(Handle<Context> native_context);
238  bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
239  bool ConfigureApiObject(Handle<JSObject> object,
240  Handle<ObjectTemplateInfo> object_template);
241  bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
242 
243  // Migrates all properties from the 'from' object to the 'to'
244  // object and overrides the prototype in 'to' with the one from
245  // 'from'.
246  void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
247  void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
248  void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
249 
250  enum PrototypePropertyMode {
251  DONT_ADD_PROTOTYPE,
252  ADD_READONLY_PROTOTYPE,
253  ADD_WRITEABLE_PROTOTYPE
254  };
255 
256  Handle<Map> CreateFunctionMap(PrototypePropertyMode prototype_mode);
257 
258  void SetFunctionInstanceDescriptor(Handle<Map> map,
259  PrototypePropertyMode prototypeMode);
260  void MakeFunctionInstancePrototypeWritable();
261 
262  Handle<Map> CreateStrictModeFunctionMap(
263  PrototypePropertyMode prototype_mode,
264  Handle<JSFunction> empty_function);
265 
266  void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
267  PrototypePropertyMode propertyMode);
268 
269  static bool CompileBuiltin(Isolate* isolate, int index);
270  static bool CompileExperimentalBuiltin(Isolate* isolate, int index);
271  static bool CompileNative(Vector<const char> name, Handle<String> source);
272  static bool CompileScriptCached(Vector<const char> name,
273  Handle<String> source,
274  SourceCodeCache* cache,
275  v8::Extension* extension,
276  Handle<Context> top_context,
277  bool use_runtime_context);
278 
279  Handle<Context> result_;
280 
281  // Function instance maps. Function literal maps are created initially with
282  // a read only prototype for the processing of JS builtins. Later the function
283  // instance maps are replaced in order to make prototype writable.
284  // These are the final, writable prototype, maps.
285  Handle<Map> function_instance_map_writable_prototype_;
286  Handle<Map> strict_mode_function_instance_map_writable_prototype_;
287  Handle<JSFunction> throw_type_error_function;
288 
289  BootstrapperActive active_;
290  friend class Bootstrapper;
291 };
292 
293 
294 void Bootstrapper::Iterate(ObjectVisitor* v) {
295  extensions_cache_.Iterate(v);
296  v->Synchronize(VisitorSynchronization::kExtensions);
297 }
298 
299 
301  Isolate* isolate,
302  Handle<Object> global_object,
303  v8::Handle<v8::ObjectTemplate> global_template,
304  v8::ExtensionConfiguration* extensions) {
305  HandleScope scope;
306  Handle<Context> env;
307  Genesis genesis(isolate, global_object, global_template, extensions);
308  env = genesis.result();
309  if (!env.is_null()) {
310  if (InstallExtensions(env, extensions)) {
311  return env;
312  }
313  }
314  return Handle<Context>();
315 }
316 
317 
318 static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
319  // object.__proto__ = proto;
320  Factory* factory = object->GetIsolate()->factory();
321  Handle<Map> old_to_map = Handle<Map>(object->map());
322  Handle<Map> new_to_map = factory->CopyMap(old_to_map);
323  new_to_map->set_prototype(*proto);
324  object->set_map(*new_to_map);
325 }
326 
327 
329  Factory* factory = env->GetIsolate()->factory();
330  Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
331  global_proxy->set_native_context(*factory->null_value());
332  SetObjectPrototype(global_proxy, factory->null_value());
333  env->set_global_proxy(env->global_object());
334  env->global_object()->set_global_receiver(env->global_object());
335 }
336 
337 
339  Handle<JSGlobalProxy> global_proxy) {
340  env->global_object()->set_global_receiver(*global_proxy);
341  env->set_global_proxy(*global_proxy);
342  SetObjectPrototype(global_proxy, Handle<JSObject>(env->global_object()));
343  global_proxy->set_native_context(*env);
344 }
345 
346 
347 static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
348  const char* name,
349  InstanceType type,
350  int instance_size,
351  Handle<JSObject> prototype,
352  Builtins::Name call,
353  bool is_ecma_native) {
354  Isolate* isolate = target->GetIsolate();
355  Factory* factory = isolate->factory();
356  Handle<String> symbol = factory->LookupAsciiSymbol(name);
357  Handle<Code> call_code = Handle<Code>(isolate->builtins()->builtin(call));
358  Handle<JSFunction> function = prototype.is_null() ?
359  factory->NewFunctionWithoutPrototype(symbol, call_code) :
360  factory->NewFunctionWithPrototype(symbol,
361  type,
362  instance_size,
363  prototype,
364  call_code,
365  is_ecma_native);
366  PropertyAttributes attributes;
367  if (target->IsJSBuiltinsObject()) {
368  attributes =
370  } else {
371  attributes = DONT_ENUM;
372  }
373  CHECK_NOT_EMPTY_HANDLE(isolate,
375  target, symbol, function, attributes));
376  if (is_ecma_native) {
377  function->shared()->set_instance_class_name(*symbol);
378  }
379  function->shared()->set_native(true);
380  return function;
381 }
382 
383 
384 void Genesis::SetFunctionInstanceDescriptor(
385  Handle<Map> map, PrototypePropertyMode prototypeMode) {
386  int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
387  Handle<DescriptorArray> descriptors(factory()->NewDescriptorArray(0, size));
388  DescriptorArray::WhitenessWitness witness(*descriptors);
389 
390  Handle<Foreign> length(factory()->NewForeign(&Accessors::FunctionLength));
391  Handle<Foreign> name(factory()->NewForeign(&Accessors::FunctionName));
392  Handle<Foreign> args(factory()->NewForeign(&Accessors::FunctionArguments));
393  Handle<Foreign> caller(factory()->NewForeign(&Accessors::FunctionCaller));
394  Handle<Foreign> prototype;
395  if (prototypeMode != DONT_ADD_PROTOTYPE) {
396  prototype = factory()->NewForeign(&Accessors::FunctionPrototype);
397  }
398  PropertyAttributes attribs = static_cast<PropertyAttributes>(
400  map->set_instance_descriptors(*descriptors);
401 
402  { // Add length.
403  CallbacksDescriptor d(*factory()->length_symbol(), *length, attribs);
404  map->AppendDescriptor(&d, witness);
405  }
406  { // Add name.
407  CallbacksDescriptor d(*factory()->name_symbol(), *name, attribs);
408  map->AppendDescriptor(&d, witness);
409  }
410  { // Add arguments.
411  CallbacksDescriptor d(*factory()->arguments_symbol(), *args, attribs);
412  map->AppendDescriptor(&d, witness);
413  }
414  { // Add caller.
415  CallbacksDescriptor d(*factory()->caller_symbol(), *caller, attribs);
416  map->AppendDescriptor(&d, witness);
417  }
418  if (prototypeMode != DONT_ADD_PROTOTYPE) {
419  // Add prototype.
420  if (prototypeMode == ADD_WRITEABLE_PROTOTYPE) {
421  attribs = static_cast<PropertyAttributes>(attribs & ~READ_ONLY);
422  }
423  CallbacksDescriptor d(*factory()->prototype_symbol(), *prototype, attribs);
424  map->AppendDescriptor(&d, witness);
425  }
426 }
427 
428 
429 Handle<Map> Genesis::CreateFunctionMap(PrototypePropertyMode prototype_mode) {
430  Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
431  SetFunctionInstanceDescriptor(map, prototype_mode);
432  map->set_function_with_prototype(prototype_mode != DONT_ADD_PROTOTYPE);
433  return map;
434 }
435 
436 
437 Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
438  // Allocate the map for function instances. Maps are allocated first and their
439  // prototypes patched later, once empty function is created.
440 
441  // Please note that the prototype property for function instances must be
442  // writable.
443  Handle<Map> function_instance_map =
444  CreateFunctionMap(ADD_WRITEABLE_PROTOTYPE);
445  native_context()->set_function_instance_map(*function_instance_map);
446 
447  // Functions with this map will not have a 'prototype' property, and
448  // can not be used as constructors.
449  Handle<Map> function_without_prototype_map =
450  CreateFunctionMap(DONT_ADD_PROTOTYPE);
451  native_context()->set_function_without_prototype_map(
452  *function_without_prototype_map);
453 
454  // Allocate the function map. This map is temporary, used only for processing
455  // of builtins.
456  // Later the map is replaced with writable prototype map, allocated below.
457  Handle<Map> function_map = CreateFunctionMap(ADD_READONLY_PROTOTYPE);
458  native_context()->set_function_map(*function_map);
459 
460  // The final map for functions. Writeable prototype.
461  // This map is installed in MakeFunctionInstancePrototypeWritable.
462  function_instance_map_writable_prototype_ =
463  CreateFunctionMap(ADD_WRITEABLE_PROTOTYPE);
464 
465  Factory* factory = isolate->factory();
466  Heap* heap = isolate->heap();
467 
468  Handle<String> object_name = Handle<String>(heap->Object_symbol());
469 
470  { // --- O b j e c t ---
471  Handle<JSFunction> object_fun =
472  factory->NewFunction(object_name, factory->null_value());
473  Handle<Map> object_function_map =
474  factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
475  object_fun->set_initial_map(*object_function_map);
476  object_function_map->set_constructor(*object_fun);
477 
478  native_context()->set_object_function(*object_fun);
479 
480  // Allocate a new prototype for the object function.
481  Handle<JSObject> prototype = factory->NewJSObject(
482  isolate->object_function(),
483  TENURED);
484 
485  native_context()->set_initial_object_prototype(*prototype);
486  SetPrototype(object_fun, prototype);
487  }
488 
489  // Allocate the empty function as the prototype for function ECMAScript
490  // 262 15.3.4.
491  Handle<String> symbol = factory->LookupAsciiSymbol("Empty");
492  Handle<JSFunction> empty_function =
493  factory->NewFunctionWithoutPrototype(symbol, CLASSIC_MODE);
494 
495  // --- E m p t y ---
496  Handle<Code> code =
497  Handle<Code>(isolate->builtins()->builtin(
498  Builtins::kEmptyFunction));
499  empty_function->set_code(*code);
500  empty_function->shared()->set_code(*code);
501  Handle<String> source = factory->NewStringFromAscii(CStrVector("() {}"));
502  Handle<Script> script = factory->NewScript(source);
503  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
504  empty_function->shared()->set_script(*script);
505  empty_function->shared()->set_start_position(0);
506  empty_function->shared()->set_end_position(source->length());
507  empty_function->shared()->DontAdaptArguments();
508 
509  // Set prototypes for the function maps.
510  native_context()->function_map()->set_prototype(*empty_function);
511  native_context()->function_instance_map()->set_prototype(*empty_function);
512  native_context()->function_without_prototype_map()->
513  set_prototype(*empty_function);
514  function_instance_map_writable_prototype_->set_prototype(*empty_function);
515 
516  // Allocate the function map first and then patch the prototype later
517  Handle<Map> empty_function_map = CreateFunctionMap(DONT_ADD_PROTOTYPE);
518  empty_function_map->set_prototype(
519  native_context()->object_function()->prototype());
520  empty_function->set_map(*empty_function_map);
521  return empty_function;
522 }
523 
524 
525 void Genesis::SetStrictFunctionInstanceDescriptor(
526  Handle<Map> map, PrototypePropertyMode prototypeMode) {
527  int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
528  Handle<DescriptorArray> descriptors(factory()->NewDescriptorArray(0, size));
529  DescriptorArray::WhitenessWitness witness(*descriptors);
530 
531  Handle<Foreign> length(factory()->NewForeign(&Accessors::FunctionLength));
532  Handle<Foreign> name(factory()->NewForeign(&Accessors::FunctionName));
533  Handle<AccessorPair> arguments(factory()->NewAccessorPair());
534  Handle<AccessorPair> caller(factory()->NewAccessorPair());
535  Handle<Foreign> prototype;
536  if (prototypeMode != DONT_ADD_PROTOTYPE) {
537  prototype = factory()->NewForeign(&Accessors::FunctionPrototype);
538  }
539  PropertyAttributes attribs = static_cast<PropertyAttributes>(
541  map->set_instance_descriptors(*descriptors);
542 
543  { // Add length.
544  CallbacksDescriptor d(*factory()->length_symbol(), *length, attribs);
545  map->AppendDescriptor(&d, witness);
546  }
547  { // Add name.
548  CallbacksDescriptor d(*factory()->name_symbol(), *name, attribs);
549  map->AppendDescriptor(&d, witness);
550  }
551  { // Add arguments.
552  CallbacksDescriptor d(*factory()->arguments_symbol(), *arguments, attribs);
553  map->AppendDescriptor(&d, witness);
554  }
555  { // Add caller.
556  CallbacksDescriptor d(*factory()->caller_symbol(), *caller, attribs);
557  map->AppendDescriptor(&d, witness);
558  }
559  if (prototypeMode != DONT_ADD_PROTOTYPE) {
560  // Add prototype.
561  if (prototypeMode != ADD_WRITEABLE_PROTOTYPE) {
562  attribs = static_cast<PropertyAttributes>(attribs | READ_ONLY);
563  }
564  CallbacksDescriptor d(*factory()->prototype_symbol(), *prototype, attribs);
565  map->AppendDescriptor(&d, witness);
566  }
567 }
568 
569 
570 // ECMAScript 5th Edition, 13.2.3
571 Handle<JSFunction> Genesis::GetThrowTypeErrorFunction() {
572  if (throw_type_error_function.is_null()) {
573  Handle<String> name = factory()->LookupAsciiSymbol("ThrowTypeError");
574  throw_type_error_function =
575  factory()->NewFunctionWithoutPrototype(name, CLASSIC_MODE);
576  Handle<Code> code(isolate()->builtins()->builtin(
577  Builtins::kStrictModePoisonPill));
578  throw_type_error_function->set_map(
579  native_context()->function_map());
580  throw_type_error_function->set_code(*code);
581  throw_type_error_function->shared()->set_code(*code);
582  throw_type_error_function->shared()->DontAdaptArguments();
583 
584  JSObject::PreventExtensions(throw_type_error_function);
585  }
586  return throw_type_error_function;
587 }
588 
589 
590 Handle<Map> Genesis::CreateStrictModeFunctionMap(
591  PrototypePropertyMode prototype_mode,
592  Handle<JSFunction> empty_function) {
593  Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
594  SetStrictFunctionInstanceDescriptor(map, prototype_mode);
595  map->set_function_with_prototype(prototype_mode != DONT_ADD_PROTOTYPE);
596  map->set_prototype(*empty_function);
597  return map;
598 }
599 
600 
601 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
602  // Allocate map for the strict mode function instances.
603  Handle<Map> strict_mode_function_instance_map =
604  CreateStrictModeFunctionMap(ADD_WRITEABLE_PROTOTYPE, empty);
605  native_context()->set_strict_mode_function_instance_map(
606  *strict_mode_function_instance_map);
607 
608  // Allocate map for the prototype-less strict mode instances.
609  Handle<Map> strict_mode_function_without_prototype_map =
610  CreateStrictModeFunctionMap(DONT_ADD_PROTOTYPE, empty);
611  native_context()->set_strict_mode_function_without_prototype_map(
612  *strict_mode_function_without_prototype_map);
613 
614  // Allocate map for the strict mode functions. This map is temporary, used
615  // only for processing of builtins.
616  // Later the map is replaced with writable prototype map, allocated below.
617  Handle<Map> strict_mode_function_map =
618  CreateStrictModeFunctionMap(ADD_READONLY_PROTOTYPE, empty);
619  native_context()->set_strict_mode_function_map(
620  *strict_mode_function_map);
621 
622  // The final map for the strict mode functions. Writeable prototype.
623  // This map is installed in MakeFunctionInstancePrototypeWritable.
624  strict_mode_function_instance_map_writable_prototype_ =
625  CreateStrictModeFunctionMap(ADD_WRITEABLE_PROTOTYPE, empty);
626 
627  // Complete the callbacks.
628  PoisonArgumentsAndCaller(strict_mode_function_instance_map);
629  PoisonArgumentsAndCaller(strict_mode_function_without_prototype_map);
630  PoisonArgumentsAndCaller(strict_mode_function_map);
631  PoisonArgumentsAndCaller(
632  strict_mode_function_instance_map_writable_prototype_);
633 }
634 
635 
636 static void SetAccessors(Handle<Map> map,
637  Handle<String> name,
638  Handle<JSFunction> func) {
639  DescriptorArray* descs = map->instance_descriptors();
640  int number = descs->SearchWithCache(*name, *map);
641  AccessorPair* accessors = AccessorPair::cast(descs->GetValue(number));
642  accessors->set_getter(*func);
643  accessors->set_setter(*func);
644 }
645 
646 
647 void Genesis::PoisonArgumentsAndCaller(Handle<Map> map) {
648  SetAccessors(map, factory()->arguments_symbol(), GetThrowTypeErrorFunction());
649  SetAccessors(map, factory()->caller_symbol(), GetThrowTypeErrorFunction());
650 }
651 
652 
653 static void AddToWeakNativeContextList(Context* context) {
654  ASSERT(context->IsNativeContext());
655  Heap* heap = context->GetIsolate()->heap();
656 #ifdef DEBUG
657  { // NOLINT
658  ASSERT(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
659  // Check that context is not in the list yet.
660  for (Object* current = heap->native_contexts_list();
661  !current->IsUndefined();
662  current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
663  ASSERT(current != context);
664  }
665  }
666 #endif
667  context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list());
668  heap->set_native_contexts_list(context);
669 }
670 
671 
672 void Genesis::CreateRoots() {
673  // Allocate the native context FixedArray first and then patch the
674  // closure and extension object later (we need the empty function
675  // and the global object, but in order to create those, we need the
676  // native context).
677  native_context_ = Handle<Context>::cast(isolate()->global_handles()->Create(
678  *factory()->NewNativeContext()));
679  AddToWeakNativeContextList(*native_context_);
680  isolate()->set_context(*native_context());
681 
682  // Allocate the message listeners object.
683  {
684  v8::NeanderArray listeners;
685  native_context()->set_message_listeners(*listeners.value());
686  }
687 }
688 
689 
690 Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
691  v8::Handle<v8::ObjectTemplate> global_template,
692  Handle<Object> global_object,
693  Handle<GlobalObject>* inner_global_out) {
694  // The argument global_template aka data is an ObjectTemplateInfo.
695  // It has a constructor pointer that points at global_constructor which is a
696  // FunctionTemplateInfo.
697  // The global_constructor is used to create or reinitialize the global_proxy.
698  // The global_constructor also has a prototype_template pointer that points at
699  // js_global_template which is an ObjectTemplateInfo.
700  // That in turn has a constructor pointer that points at
701  // js_global_constructor which is a FunctionTemplateInfo.
702  // js_global_constructor is used to make js_global_function
703  // js_global_function is used to make the new inner_global.
704  //
705  // --- G l o b a l ---
706  // Step 1: Create a fresh inner JSGlobalObject.
707  Handle<JSFunction> js_global_function;
708  Handle<ObjectTemplateInfo> js_global_template;
709  if (!global_template.IsEmpty()) {
710  // Get prototype template of the global_template.
711  Handle<ObjectTemplateInfo> data =
712  v8::Utils::OpenHandle(*global_template);
713  Handle<FunctionTemplateInfo> global_constructor =
714  Handle<FunctionTemplateInfo>(
715  FunctionTemplateInfo::cast(data->constructor()));
716  Handle<Object> proto_template(global_constructor->prototype_template());
717  if (!proto_template->IsUndefined()) {
718  js_global_template =
719  Handle<ObjectTemplateInfo>::cast(proto_template);
720  }
721  }
722 
723  if (js_global_template.is_null()) {
724  Handle<String> name = Handle<String>(heap()->empty_symbol());
725  Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
726  Builtins::kIllegal));
727  js_global_function =
728  factory()->NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
729  JSGlobalObject::kSize, code, true);
730  // Change the constructor property of the prototype of the
731  // hidden global function to refer to the Object function.
732  Handle<JSObject> prototype =
733  Handle<JSObject>(
734  JSObject::cast(js_global_function->instance_prototype()));
735  CHECK_NOT_EMPTY_HANDLE(isolate(),
737  prototype, factory()->constructor_symbol(),
738  isolate()->object_function(), NONE));
739  } else {
740  Handle<FunctionTemplateInfo> js_global_constructor(
741  FunctionTemplateInfo::cast(js_global_template->constructor()));
742  js_global_function =
743  factory()->CreateApiFunction(js_global_constructor,
744  factory()->InnerGlobalObject);
745  }
746 
747  js_global_function->initial_map()->set_is_hidden_prototype();
748  js_global_function->initial_map()->set_dictionary_map(true);
749  Handle<GlobalObject> inner_global =
750  factory()->NewGlobalObject(js_global_function);
751  if (inner_global_out != NULL) {
752  *inner_global_out = inner_global;
753  }
754 
755  // Step 2: create or re-initialize the global proxy object.
756  Handle<JSFunction> global_proxy_function;
757  if (global_template.IsEmpty()) {
758  Handle<String> name = Handle<String>(heap()->empty_symbol());
759  Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
760  Builtins::kIllegal));
761  global_proxy_function =
762  factory()->NewFunction(name, JS_GLOBAL_PROXY_TYPE,
763  JSGlobalProxy::kSize, code, true);
764  } else {
765  Handle<ObjectTemplateInfo> data =
766  v8::Utils::OpenHandle(*global_template);
767  Handle<FunctionTemplateInfo> global_constructor(
768  FunctionTemplateInfo::cast(data->constructor()));
769  global_proxy_function =
770  factory()->CreateApiFunction(global_constructor,
771  factory()->OuterGlobalObject);
772  }
773 
774  Handle<String> global_name = factory()->LookupAsciiSymbol("global");
775  global_proxy_function->shared()->set_instance_class_name(*global_name);
776  global_proxy_function->initial_map()->set_is_access_check_needed(true);
777 
778  // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
779  // Return the global proxy.
780 
781  if (global_object.location() != NULL) {
782  ASSERT(global_object->IsJSGlobalProxy());
784  global_proxy_function,
785  Handle<JSGlobalProxy>::cast(global_object));
786  } else {
788  factory()->NewJSObject(global_proxy_function, TENURED));
789  }
790 }
791 
792 
793 void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
794  Handle<JSGlobalProxy> global_proxy) {
795  // Set the native context for the global object.
796  inner_global->set_native_context(*native_context());
797  inner_global->set_global_context(*native_context());
798  inner_global->set_global_receiver(*global_proxy);
799  global_proxy->set_native_context(*native_context());
800  native_context()->set_global_proxy(*global_proxy);
801 }
802 
803 
804 void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
805  Handle<GlobalObject> inner_global_from_snapshot(
806  GlobalObject::cast(native_context_->extension()));
807  Handle<JSBuiltinsObject> builtins_global(native_context_->builtins());
808  native_context_->set_extension(*inner_global);
809  native_context_->set_global_object(*inner_global);
810  native_context_->set_security_token(*inner_global);
811  static const PropertyAttributes attributes =
812  static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
813  ForceSetProperty(builtins_global,
814  factory()->LookupAsciiSymbol("global"),
815  inner_global,
816  attributes);
817  // Set up the reference from the global object to the builtins object.
818  JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
819  TransferNamedProperties(inner_global_from_snapshot, inner_global);
820  TransferIndexedProperties(inner_global_from_snapshot, inner_global);
821 }
822 
823 
824 // This is only called if we are not using snapshots. The equivalent
825 // work in the snapshot case is done in HookUpInnerGlobal.
826 bool Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
827  Handle<JSFunction> empty_function) {
828  // --- G l o b a l C o n t e x t ---
829  // Use the empty function as closure (no scope info).
830  native_context()->set_closure(*empty_function);
831  native_context()->set_previous(NULL);
832  // Set extension and global object.
833  native_context()->set_extension(*inner_global);
834  native_context()->set_global_object(*inner_global);
835  // Security setup: Set the security token of the global object to
836  // its the inner global. This makes the security check between two
837  // different contexts fail by default even in case of global
838  // object reinitialization.
839  native_context()->set_security_token(*inner_global);
840 
841  Isolate* isolate = inner_global->GetIsolate();
842  Factory* factory = isolate->factory();
843  Heap* heap = isolate->heap();
844 
845  Handle<String> object_name = Handle<String>(heap->Object_symbol());
846  CHECK_NOT_EMPTY_HANDLE(isolate,
848  inner_global, object_name,
849  isolate->object_function(), DONT_ENUM));
850 
851  Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
852 
853  // Install global Function object
854  InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
855  empty_function, Builtins::kIllegal, true); // ECMA native.
856 
857  { // --- A r r a y ---
858  Handle<JSFunction> array_function =
859  InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
860  isolate->initial_object_prototype(),
861  Builtins::kArrayCode, true);
862  array_function->shared()->set_construct_stub(
863  isolate->builtins()->builtin(Builtins::kArrayConstructCode));
864  array_function->shared()->DontAdaptArguments();
865 
866  // This seems a bit hackish, but we need to make sure Array.length
867  // is 1.
868  array_function->shared()->set_length(1);
869 
870  Handle<Map> initial_map(array_function->initial_map());
871  Handle<DescriptorArray> array_descriptors(
872  factory->NewDescriptorArray(0, 1));
873  DescriptorArray::WhitenessWitness witness(*array_descriptors);
874 
875  Handle<Foreign> array_length(factory->NewForeign(&Accessors::ArrayLength));
876  PropertyAttributes attribs = static_cast<PropertyAttributes>(
878  initial_map->set_instance_descriptors(*array_descriptors);
879 
880  { // Add length.
881  CallbacksDescriptor d(*factory->length_symbol(), *array_length, attribs);
882  array_function->initial_map()->AppendDescriptor(&d, witness);
883  }
884 
885  // array_function is used internally. JS code creating array object should
886  // search for the 'Array' property on the global object and use that one
887  // as the constructor. 'Array' property on a global object can be
888  // overwritten by JS code.
889  native_context()->set_array_function(*array_function);
890  }
891 
892  { // --- N u m b e r ---
893  Handle<JSFunction> number_fun =
894  InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
895  isolate->initial_object_prototype(),
896  Builtins::kIllegal, true);
897  native_context()->set_number_function(*number_fun);
898  }
899 
900  { // --- B o o l e a n ---
901  Handle<JSFunction> boolean_fun =
902  InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
903  isolate->initial_object_prototype(),
904  Builtins::kIllegal, true);
905  native_context()->set_boolean_function(*boolean_fun);
906  }
907 
908  { // --- S t r i n g ---
909  Handle<JSFunction> string_fun =
910  InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
911  isolate->initial_object_prototype(),
912  Builtins::kIllegal, true);
913  string_fun->shared()->set_construct_stub(
914  isolate->builtins()->builtin(Builtins::kStringConstructCode));
915  native_context()->set_string_function(*string_fun);
916 
917  Handle<Map> string_map =
918  Handle<Map>(native_context()->string_function()->initial_map());
919  Handle<DescriptorArray> string_descriptors(
920  factory->NewDescriptorArray(0, 1));
921  DescriptorArray::WhitenessWitness witness(*string_descriptors);
922 
923  Handle<Foreign> string_length(
924  factory->NewForeign(&Accessors::StringLength));
925  PropertyAttributes attribs = static_cast<PropertyAttributes>(
927  string_map->set_instance_descriptors(*string_descriptors);
928 
929  { // Add length.
930  CallbacksDescriptor d(*factory->length_symbol(), *string_length, attribs);
931  string_map->AppendDescriptor(&d, witness);
932  }
933  }
934 
935  { // --- D a t e ---
936  // Builtin functions for Date.prototype.
937  Handle<JSFunction> date_fun =
938  InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize,
939  isolate->initial_object_prototype(),
940  Builtins::kIllegal, true);
941 
942  native_context()->set_date_function(*date_fun);
943  }
944 
945 
946  { // -- R e g E x p
947  // Builtin functions for RegExp.prototype.
948  Handle<JSFunction> regexp_fun =
949  InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
950  isolate->initial_object_prototype(),
951  Builtins::kIllegal, true);
952  native_context()->set_regexp_function(*regexp_fun);
953 
954  ASSERT(regexp_fun->has_initial_map());
955  Handle<Map> initial_map(regexp_fun->initial_map());
956 
957  ASSERT_EQ(0, initial_map->inobject_properties());
958 
959  PropertyAttributes final =
960  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
961  Handle<DescriptorArray> descriptors = factory->NewDescriptorArray(0, 5);
962  DescriptorArray::WhitenessWitness witness(*descriptors);
963  initial_map->set_instance_descriptors(*descriptors);
964 
965  {
966  // ECMA-262, section 15.10.7.1.
967  FieldDescriptor field(heap->source_symbol(),
969  final);
970  initial_map->AppendDescriptor(&field, witness);
971  }
972  {
973  // ECMA-262, section 15.10.7.2.
974  FieldDescriptor field(heap->global_symbol(),
976  final);
977  initial_map->AppendDescriptor(&field, witness);
978  }
979  {
980  // ECMA-262, section 15.10.7.3.
981  FieldDescriptor field(heap->ignore_case_symbol(),
983  final);
984  initial_map->AppendDescriptor(&field, witness);
985  }
986  {
987  // ECMA-262, section 15.10.7.4.
988  FieldDescriptor field(heap->multiline_symbol(),
990  final);
991  initial_map->AppendDescriptor(&field, witness);
992  }
993  {
994  // ECMA-262, section 15.10.7.5.
995  PropertyAttributes writable =
996  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
997  FieldDescriptor field(heap->last_index_symbol(),
999  writable);
1000  initial_map->AppendDescriptor(&field, witness);
1001  }
1002 
1003  initial_map->set_inobject_properties(5);
1004  initial_map->set_pre_allocated_property_fields(5);
1005  initial_map->set_unused_property_fields(0);
1006  initial_map->set_instance_size(
1007  initial_map->instance_size() + 5 * kPointerSize);
1008  initial_map->set_visitor_id(StaticVisitorBase::GetVisitorId(*initial_map));
1009 
1010  // RegExp prototype object is itself a RegExp.
1011  Handle<Map> proto_map = factory->CopyMap(initial_map);
1012  proto_map->set_prototype(native_context()->initial_object_prototype());
1013  Handle<JSObject> proto = factory->NewJSObjectFromMap(proto_map);
1014  proto->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex,
1015  heap->query_colon_symbol());
1016  proto->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex,
1017  heap->false_value());
1018  proto->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex,
1019  heap->false_value());
1020  proto->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex,
1021  heap->false_value());
1022  proto->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
1023  Smi::FromInt(0),
1024  SKIP_WRITE_BARRIER); // It's a Smi.
1025  initial_map->set_prototype(*proto);
1026  factory->SetRegExpIrregexpData(Handle<JSRegExp>::cast(proto),
1027  JSRegExp::IRREGEXP, factory->empty_string(),
1028  JSRegExp::Flags(0), 0);
1029  }
1030 
1031  { // -- J S O N
1032  Handle<String> name = factory->NewStringFromAscii(CStrVector("JSON"));
1033  Handle<JSFunction> cons = factory->NewFunction(name,
1034  factory->the_hole_value());
1035  { MaybeObject* result = cons->SetInstancePrototype(
1036  native_context()->initial_object_prototype());
1037  if (result->IsFailure()) return false;
1038  }
1039  cons->SetInstanceClassName(*name);
1040  Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1041  ASSERT(json_object->IsJSObject());
1042  CHECK_NOT_EMPTY_HANDLE(isolate,
1044  global, name, json_object, DONT_ENUM));
1045  native_context()->set_json_object(*json_object);
1046  }
1047 
1048  { // --- arguments_boilerplate_
1049  // Make sure we can recognize argument objects at runtime.
1050  // This is done by introducing an anonymous function with
1051  // class_name equals 'Arguments'.
1052  Handle<String> symbol = factory->LookupAsciiSymbol("Arguments");
1053  Handle<Code> code = Handle<Code>(
1054  isolate->builtins()->builtin(Builtins::kIllegal));
1055  Handle<JSObject> prototype =
1056  Handle<JSObject>(
1057  JSObject::cast(native_context()->object_function()->prototype()));
1058 
1059  Handle<JSFunction> function =
1060  factory->NewFunctionWithPrototype(symbol,
1063  prototype,
1064  code,
1065  false);
1066  ASSERT(!function->has_initial_map());
1067  function->shared()->set_instance_class_name(*symbol);
1068  function->shared()->set_expected_nof_properties(2);
1069  Handle<JSObject> result = factory->NewJSObject(function);
1070 
1071  native_context()->set_arguments_boilerplate(*result);
1072  // Note: length must be added as the first property and
1073  // callee must be added as the second property.
1074  CHECK_NOT_EMPTY_HANDLE(isolate,
1076  result, factory->length_symbol(),
1077  factory->undefined_value(), DONT_ENUM));
1078  CHECK_NOT_EMPTY_HANDLE(isolate,
1080  result, factory->callee_symbol(),
1081  factory->undefined_value(), DONT_ENUM));
1082 
1083 #ifdef DEBUG
1084  LookupResult lookup(isolate);
1085  result->LocalLookup(heap->callee_symbol(), &lookup);
1086  ASSERT(lookup.IsField());
1087  ASSERT(lookup.GetFieldIndex() == Heap::kArgumentsCalleeIndex);
1088 
1089  result->LocalLookup(heap->length_symbol(), &lookup);
1090  ASSERT(lookup.IsField());
1091  ASSERT(lookup.GetFieldIndex() == Heap::kArgumentsLengthIndex);
1092 
1093  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsCalleeIndex);
1094  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1095 
1096  // Check the state of the object.
1097  ASSERT(result->HasFastProperties());
1098  ASSERT(result->HasFastObjectElements());
1099 #endif
1100  }
1101 
1102  { // --- aliased_arguments_boilerplate_
1103  // Set up a well-formed parameter map to make assertions happy.
1104  Handle<FixedArray> elements = factory->NewFixedArray(2);
1105  elements->set_map(heap->non_strict_arguments_elements_map());
1106  Handle<FixedArray> array;
1107  array = factory->NewFixedArray(0);
1108  elements->set(0, *array);
1109  array = factory->NewFixedArray(0);
1110  elements->set(1, *array);
1111 
1112  Handle<Map> old_map(native_context()->arguments_boilerplate()->map());
1113  Handle<Map> new_map = factory->CopyMap(old_map);
1114  new_map->set_pre_allocated_property_fields(2);
1115  Handle<JSObject> result = factory->NewJSObjectFromMap(new_map);
1116  // Set elements kind after allocating the object because
1117  // NewJSObjectFromMap assumes a fast elements map.
1118  new_map->set_elements_kind(NON_STRICT_ARGUMENTS_ELEMENTS);
1119  result->set_elements(*elements);
1120  ASSERT(result->HasNonStrictArgumentsElements());
1121  native_context()->set_aliased_arguments_boilerplate(*result);
1122  }
1123 
1124  { // --- strict mode arguments boilerplate
1125  const PropertyAttributes attributes =
1126  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1127 
1128  // Create the ThrowTypeError functions.
1129  Handle<AccessorPair> callee = factory->NewAccessorPair();
1130  Handle<AccessorPair> caller = factory->NewAccessorPair();
1131 
1132  Handle<JSFunction> throw_function =
1133  GetThrowTypeErrorFunction();
1134 
1135  // Install the ThrowTypeError functions.
1136  callee->set_getter(*throw_function);
1137  callee->set_setter(*throw_function);
1138  caller->set_getter(*throw_function);
1139  caller->set_setter(*throw_function);
1140 
1141  // Create the map. Allocate one in-object field for length.
1142  Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE,
1144  // Create the descriptor array for the arguments object.
1145  Handle<DescriptorArray> descriptors = factory->NewDescriptorArray(0, 3);
1146  DescriptorArray::WhitenessWitness witness(*descriptors);
1147  map->set_instance_descriptors(*descriptors);
1148 
1149  { // length
1150  FieldDescriptor d(*factory->length_symbol(), 0, DONT_ENUM);
1151  map->AppendDescriptor(&d, witness);
1152  }
1153  { // callee
1154  CallbacksDescriptor d(*factory->callee_symbol(),
1155  *callee,
1156  attributes);
1157  map->AppendDescriptor(&d, witness);
1158  }
1159  { // caller
1160  CallbacksDescriptor d(*factory->caller_symbol(),
1161  *caller,
1162  attributes);
1163  map->AppendDescriptor(&d, witness);
1164  }
1165 
1166  map->set_function_with_prototype(true);
1167  map->set_prototype(native_context()->object_function()->prototype());
1168  map->set_pre_allocated_property_fields(1);
1169  map->set_inobject_properties(1);
1170 
1171  // Copy constructor from the non-strict arguments boilerplate.
1172  map->set_constructor(
1173  native_context()->arguments_boilerplate()->map()->constructor());
1174 
1175  // Allocate the arguments boilerplate object.
1176  Handle<JSObject> result = factory->NewJSObjectFromMap(map);
1177  native_context()->set_strict_mode_arguments_boilerplate(*result);
1178 
1179  // Add length property only for strict mode boilerplate.
1180  CHECK_NOT_EMPTY_HANDLE(isolate,
1182  result, factory->length_symbol(),
1183  factory->undefined_value(), DONT_ENUM));
1184 
1185 #ifdef DEBUG
1186  LookupResult lookup(isolate);
1187  result->LocalLookup(heap->length_symbol(), &lookup);
1188  ASSERT(lookup.IsField());
1189  ASSERT(lookup.GetFieldIndex() == Heap::kArgumentsLengthIndex);
1190 
1191  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1192 
1193  // Check the state of the object.
1194  ASSERT(result->HasFastProperties());
1195  ASSERT(result->HasFastObjectElements());
1196 #endif
1197  }
1198 
1199  { // --- context extension
1200  // Create a function for the context extension objects.
1201  Handle<Code> code = Handle<Code>(
1202  isolate->builtins()->builtin(Builtins::kIllegal));
1203  Handle<JSFunction> context_extension_fun =
1204  factory->NewFunction(factory->empty_symbol(),
1207  code,
1208  true);
1209 
1210  Handle<String> name = factory->LookupAsciiSymbol("context_extension");
1211  context_extension_fun->shared()->set_instance_class_name(*name);
1212  native_context()->set_context_extension_function(*context_extension_fun);
1213  }
1214 
1215 
1216  {
1217  // Set up the call-as-function delegate.
1218  Handle<Code> code =
1219  Handle<Code>(isolate->builtins()->builtin(
1220  Builtins::kHandleApiCallAsFunction));
1221  Handle<JSFunction> delegate =
1222  factory->NewFunction(factory->empty_symbol(), JS_OBJECT_TYPE,
1223  JSObject::kHeaderSize, code, true);
1224  native_context()->set_call_as_function_delegate(*delegate);
1225  delegate->shared()->DontAdaptArguments();
1226  }
1227 
1228  {
1229  // Set up the call-as-constructor delegate.
1230  Handle<Code> code =
1231  Handle<Code>(isolate->builtins()->builtin(
1232  Builtins::kHandleApiCallAsConstructor));
1233  Handle<JSFunction> delegate =
1234  factory->NewFunction(factory->empty_symbol(), JS_OBJECT_TYPE,
1235  JSObject::kHeaderSize, code, true);
1236  native_context()->set_call_as_constructor_delegate(*delegate);
1237  delegate->shared()->DontAdaptArguments();
1238  }
1239 
1240  // Initialize the out of memory slot.
1241  native_context()->set_out_of_memory(heap->false_value());
1242 
1243  // Initialize the data slot.
1244  native_context()->set_data(heap->undefined_value());
1245 
1246  {
1247  // Initialize the random seed slot.
1248  Handle<ByteArray> zeroed_byte_array(
1249  factory->NewByteArray(kRandomStateSize));
1250  native_context()->set_random_seed(*zeroed_byte_array);
1251  memset(zeroed_byte_array->GetDataStartAddress(), 0, kRandomStateSize);
1252  }
1253  return true;
1254 }
1255 
1256 
1257 void Genesis::InitializeExperimentalGlobal() {
1258  Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1259 
1260  // TODO(mstarzinger): Move this into Genesis::InitializeGlobal once we no
1261  // longer need to live behind a flag, so functions get added to the snapshot.
1262  if (FLAG_harmony_collections) {
1263  { // -- S e t
1264  Handle<JSObject> prototype =
1265  factory()->NewJSObject(isolate()->object_function(), TENURED);
1266  InstallFunction(global, "Set", JS_SET_TYPE, JSSet::kSize,
1267  prototype, Builtins::kIllegal, true);
1268  }
1269  { // -- M a p
1270  Handle<JSObject> prototype =
1271  factory()->NewJSObject(isolate()->object_function(), TENURED);
1272  InstallFunction(global, "Map", JS_MAP_TYPE, JSMap::kSize,
1273  prototype, Builtins::kIllegal, true);
1274  }
1275  { // -- W e a k M a p
1276  Handle<JSObject> prototype =
1277  factory()->NewJSObject(isolate()->object_function(), TENURED);
1278  InstallFunction(global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
1279  prototype, Builtins::kIllegal, true);
1280  }
1281  }
1282 }
1283 
1284 
1285 bool Genesis::CompileBuiltin(Isolate* isolate, int index) {
1286  Vector<const char> name = Natives::GetScriptName(index);
1287  Handle<String> source_code =
1288  isolate->bootstrapper()->NativesSourceLookup(index);
1289  return CompileNative(name, source_code);
1290 }
1291 
1292 
1293 bool Genesis::CompileExperimentalBuiltin(Isolate* isolate, int index) {
1294  Vector<const char> name = ExperimentalNatives::GetScriptName(index);
1295  Factory* factory = isolate->factory();
1296  Handle<String> source_code =
1297  factory->NewStringFromAscii(
1299  return CompileNative(name, source_code);
1300 }
1301 
1302 
1303 bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
1304  HandleScope scope;
1305  Isolate* isolate = source->GetIsolate();
1306 #ifdef ENABLE_DEBUGGER_SUPPORT
1307  isolate->debugger()->set_compiling_natives(true);
1308 #endif
1309  // During genesis, the boilerplate for stack overflow won't work until the
1310  // environment has been at least partially initialized. Add a stack check
1311  // before entering JS code to catch overflow early.
1312  StackLimitCheck check(Isolate::Current());
1313  if (check.HasOverflowed()) return false;
1314 
1315  bool result = CompileScriptCached(name,
1316  source,
1317  NULL,
1318  NULL,
1319  Handle<Context>(isolate->context()),
1320  true);
1321  ASSERT(isolate->has_pending_exception() != result);
1322  if (!result) isolate->clear_pending_exception();
1323 #ifdef ENABLE_DEBUGGER_SUPPORT
1324  isolate->debugger()->set_compiling_natives(false);
1325 #endif
1326  return result;
1327 }
1328 
1329 
1330 bool Genesis::CompileScriptCached(Vector<const char> name,
1331  Handle<String> source,
1332  SourceCodeCache* cache,
1333  v8::Extension* extension,
1334  Handle<Context> top_context,
1335  bool use_runtime_context) {
1336  Factory* factory = source->GetIsolate()->factory();
1337  HandleScope scope;
1338  Handle<SharedFunctionInfo> function_info;
1339 
1340  // If we can't find the function in the cache, we compile a new
1341  // function and insert it into the cache.
1342  if (cache == NULL || !cache->Lookup(name, &function_info)) {
1343  ASSERT(source->IsAsciiRepresentation());
1344  Handle<String> script_name = factory->NewStringFromUtf8(name);
1345  function_info = Compiler::Compile(
1346  source,
1347  script_name,
1348  0,
1349  0,
1350  top_context,
1351  extension,
1352  NULL,
1354  use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
1355  if (function_info.is_null()) return false;
1356  if (cache != NULL) cache->Add(name, function_info);
1357  }
1358 
1359  // Set up the function context. Conceptually, we should clone the
1360  // function before overwriting the context but since we're in a
1361  // single-threaded environment it is not strictly necessary.
1362  ASSERT(top_context->IsNativeContext());
1363  Handle<Context> context =
1364  Handle<Context>(use_runtime_context
1365  ? Handle<Context>(top_context->runtime_context())
1366  : top_context);
1367  Handle<JSFunction> fun =
1368  factory->NewFunctionFromSharedFunctionInfo(function_info, context);
1369 
1370  // Call function using either the runtime object or the global
1371  // object as the receiver. Provide no parameters.
1372  Handle<Object> receiver =
1373  Handle<Object>(use_runtime_context
1374  ? top_context->builtins()
1375  : top_context->global_object());
1376  bool has_pending_exception;
1377  Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1378  if (has_pending_exception) return false;
1379  return true;
1380 }
1381 
1382 
1383 #define INSTALL_NATIVE(Type, name, var) \
1384  Handle<String> var##_name = factory()->LookupAsciiSymbol(name); \
1385  Object* var##_native = \
1386  native_context()->builtins()->GetPropertyNoExceptionThrown( \
1387  *var##_name); \
1388  native_context()->set_##var(Type::cast(var##_native));
1389 
1390 
1391 void Genesis::InstallNativeFunctions() {
1392  HandleScope scope;
1393  INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1394  INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1395  INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1396  INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1397  INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1398  INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1399  INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1400  INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
1401  INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
1402  INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1403  INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1404  configure_instance_fun);
1405  INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1406  INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1407  INSTALL_NATIVE(JSFunction, "ToCompletePropertyDescriptor",
1408  to_complete_property_descriptor);
1409 }
1410 
1411 void Genesis::InstallExperimentalNativeFunctions() {
1412  if (FLAG_harmony_proxies) {
1413  INSTALL_NATIVE(JSFunction, "DerivedHasTrap", derived_has_trap);
1414  INSTALL_NATIVE(JSFunction, "DerivedGetTrap", derived_get_trap);
1415  INSTALL_NATIVE(JSFunction, "DerivedSetTrap", derived_set_trap);
1416  INSTALL_NATIVE(JSFunction, "ProxyEnumerate", proxy_enumerate);
1417  }
1418 }
1419 
1420 #undef INSTALL_NATIVE
1421 
1422 
1423 bool Genesis::InstallNatives() {
1424  HandleScope scope;
1425 
1426  // Create a function for the builtins object. Allocate space for the
1427  // JavaScript builtins, a reference to the builtins object
1428  // (itself) and a reference to the native_context directly in the object.
1429  Handle<Code> code = Handle<Code>(
1430  isolate()->builtins()->builtin(Builtins::kIllegal));
1431  Handle<JSFunction> builtins_fun =
1432  factory()->NewFunction(factory()->empty_symbol(),
1434  JSBuiltinsObject::kSize, code, true);
1435 
1436  Handle<String> name = factory()->LookupAsciiSymbol("builtins");
1437  builtins_fun->shared()->set_instance_class_name(*name);
1438  builtins_fun->initial_map()->set_dictionary_map(true);
1439  builtins_fun->initial_map()->set_prototype(heap()->null_value());
1440 
1441  // Allocate the builtins object.
1442  Handle<JSBuiltinsObject> builtins =
1443  Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
1444  builtins->set_builtins(*builtins);
1445  builtins->set_native_context(*native_context());
1446  builtins->set_global_context(*native_context());
1447  builtins->set_global_receiver(*builtins);
1448 
1449  // Set up the 'global' properties of the builtins object. The
1450  // 'global' property that refers to the global object is the only
1451  // way to get from code running in the builtins context to the
1452  // global object.
1453  static const PropertyAttributes attributes =
1454  static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1455  Handle<String> global_symbol = factory()->LookupAsciiSymbol("global");
1456  Handle<Object> global_obj(native_context()->global_object());
1457  CHECK_NOT_EMPTY_HANDLE(isolate(),
1459  builtins, global_symbol, global_obj, attributes));
1460 
1461  // Set up the reference from the global object to the builtins object.
1462  JSGlobalObject::cast(native_context()->global_object())->
1463  set_builtins(*builtins);
1464 
1465  // Create a bridge function that has context in the native context.
1466  Handle<JSFunction> bridge =
1467  factory()->NewFunction(factory()->empty_symbol(),
1468  factory()->undefined_value());
1469  ASSERT(bridge->context() == *isolate()->native_context());
1470 
1471  // Allocate the builtins context.
1472  Handle<Context> context =
1473  factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1474  context->set_global_object(*builtins); // override builtins global object
1475 
1476  native_context()->set_runtime_context(*context);
1477 
1478  { // -- S c r i p t
1479  // Builtin functions for Script.
1480  Handle<JSFunction> script_fun =
1481  InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1482  isolate()->initial_object_prototype(),
1483  Builtins::kIllegal, false);
1484  Handle<JSObject> prototype =
1485  factory()->NewJSObject(isolate()->object_function(), TENURED);
1486  SetPrototype(script_fun, prototype);
1487  native_context()->set_script_function(*script_fun);
1488 
1489  Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1490 
1491  Handle<DescriptorArray> script_descriptors(
1492  factory()->NewDescriptorArray(0, 13));
1493  DescriptorArray::WhitenessWitness witness(*script_descriptors);
1494 
1495  Handle<Foreign> script_source(
1496  factory()->NewForeign(&Accessors::ScriptSource));
1497  Handle<Foreign> script_name(factory()->NewForeign(&Accessors::ScriptName));
1498  Handle<String> id_symbol(factory()->LookupAsciiSymbol("id"));
1499  Handle<Foreign> script_id(factory()->NewForeign(&Accessors::ScriptId));
1500  Handle<String> line_offset_symbol(
1501  factory()->LookupAsciiSymbol("line_offset"));
1502  Handle<Foreign> script_line_offset(
1503  factory()->NewForeign(&Accessors::ScriptLineOffset));
1504  Handle<String> column_offset_symbol(
1505  factory()->LookupAsciiSymbol("column_offset"));
1506  Handle<Foreign> script_column_offset(
1507  factory()->NewForeign(&Accessors::ScriptColumnOffset));
1508  Handle<String> data_symbol(factory()->LookupAsciiSymbol("data"));
1509  Handle<Foreign> script_data(factory()->NewForeign(&Accessors::ScriptData));
1510  Handle<String> type_symbol(factory()->LookupAsciiSymbol("type"));
1511  Handle<Foreign> script_type(factory()->NewForeign(&Accessors::ScriptType));
1512  Handle<String> compilation_type_symbol(
1513  factory()->LookupAsciiSymbol("compilation_type"));
1514  Handle<Foreign> script_compilation_type(
1515  factory()->NewForeign(&Accessors::ScriptCompilationType));
1516  Handle<String> line_ends_symbol(factory()->LookupAsciiSymbol("line_ends"));
1517  Handle<Foreign> script_line_ends(
1518  factory()->NewForeign(&Accessors::ScriptLineEnds));
1519  Handle<String> context_data_symbol(
1520  factory()->LookupAsciiSymbol("context_data"));
1521  Handle<Foreign> script_context_data(
1522  factory()->NewForeign(&Accessors::ScriptContextData));
1523  Handle<String> eval_from_script_symbol(
1524  factory()->LookupAsciiSymbol("eval_from_script"));
1525  Handle<Foreign> script_eval_from_script(
1526  factory()->NewForeign(&Accessors::ScriptEvalFromScript));
1527  Handle<String> eval_from_script_position_symbol(
1528  factory()->LookupAsciiSymbol("eval_from_script_position"));
1529  Handle<Foreign> script_eval_from_script_position(
1530  factory()->NewForeign(&Accessors::ScriptEvalFromScriptPosition));
1531  Handle<String> eval_from_function_name_symbol(
1532  factory()->LookupAsciiSymbol("eval_from_function_name"));
1533  Handle<Foreign> script_eval_from_function_name(
1534  factory()->NewForeign(&Accessors::ScriptEvalFromFunctionName));
1535  PropertyAttributes attribs =
1536  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1537  script_map->set_instance_descriptors(*script_descriptors);
1538 
1539  {
1540  CallbacksDescriptor d(
1541  *factory()->source_symbol(), *script_source, attribs);
1542  script_map->AppendDescriptor(&d, witness);
1543  }
1544 
1545  {
1546  CallbacksDescriptor d(*factory()->name_symbol(), *script_name, attribs);
1547  script_map->AppendDescriptor(&d, witness);
1548  }
1549 
1550  {
1551  CallbacksDescriptor d(*id_symbol, *script_id, attribs);
1552  script_map->AppendDescriptor(&d, witness);
1553  }
1554 
1555  {
1556  CallbacksDescriptor d(*line_offset_symbol, *script_line_offset, attribs);
1557  script_map->AppendDescriptor(&d, witness);
1558  }
1559 
1560  {
1561  CallbacksDescriptor d(
1562  *column_offset_symbol, *script_column_offset, attribs);
1563  script_map->AppendDescriptor(&d, witness);
1564  }
1565 
1566  {
1567  CallbacksDescriptor d(*data_symbol, *script_data, attribs);
1568  script_map->AppendDescriptor(&d, witness);
1569  }
1570 
1571  {
1572  CallbacksDescriptor d(*type_symbol, *script_type, attribs);
1573  script_map->AppendDescriptor(&d, witness);
1574  }
1575 
1576  {
1577  CallbacksDescriptor d(
1578  *compilation_type_symbol, *script_compilation_type, attribs);
1579  script_map->AppendDescriptor(&d, witness);
1580  }
1581 
1582  {
1583  CallbacksDescriptor d(*line_ends_symbol, *script_line_ends, attribs);
1584  script_map->AppendDescriptor(&d, witness);
1585  }
1586 
1587  {
1588  CallbacksDescriptor d(
1589  *context_data_symbol, *script_context_data, attribs);
1590  script_map->AppendDescriptor(&d, witness);
1591  }
1592 
1593  {
1594  CallbacksDescriptor d(
1595  *eval_from_script_symbol, *script_eval_from_script, attribs);
1596  script_map->AppendDescriptor(&d, witness);
1597  }
1598 
1599  {
1600  CallbacksDescriptor d(
1601  *eval_from_script_position_symbol,
1602  *script_eval_from_script_position,
1603  attribs);
1604  script_map->AppendDescriptor(&d, witness);
1605  }
1606 
1607  {
1608  CallbacksDescriptor d(
1609  *eval_from_function_name_symbol,
1610  *script_eval_from_function_name,
1611  attribs);
1612  script_map->AppendDescriptor(&d, witness);
1613  }
1614 
1615  // Allocate the empty script.
1616  Handle<Script> script = factory()->NewScript(factory()->empty_string());
1617  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
1618  heap()->public_set_empty_script(*script);
1619  }
1620  {
1621  // Builtin function for OpaqueReference -- a JSValue-based object,
1622  // that keeps its field isolated from JavaScript code. It may store
1623  // objects, that JavaScript code may not access.
1624  Handle<JSFunction> opaque_reference_fun =
1625  InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1627  isolate()->initial_object_prototype(),
1628  Builtins::kIllegal, false);
1629  Handle<JSObject> prototype =
1630  factory()->NewJSObject(isolate()->object_function(), TENURED);
1631  SetPrototype(opaque_reference_fun, prototype);
1632  native_context()->set_opaque_reference_function(*opaque_reference_fun);
1633  }
1634 
1635  { // --- I n t e r n a l A r r a y ---
1636  // An array constructor on the builtins object that works like
1637  // the public Array constructor, except that its prototype
1638  // doesn't inherit from Object.prototype.
1639  // To be used only for internal work by builtins. Instances
1640  // must not be leaked to user code.
1641  Handle<JSFunction> array_function =
1642  InstallFunction(builtins,
1643  "InternalArray",
1644  JS_ARRAY_TYPE,
1646  isolate()->initial_object_prototype(),
1647  Builtins::kInternalArrayCode,
1648  true);
1649  Handle<JSObject> prototype =
1650  factory()->NewJSObject(isolate()->object_function(), TENURED);
1651  SetPrototype(array_function, prototype);
1652 
1653  array_function->shared()->set_construct_stub(
1654  isolate()->builtins()->builtin(Builtins::kArrayConstructCode));
1655  array_function->shared()->DontAdaptArguments();
1656 
1657  // InternalArrays should not use Smi-Only array optimizations. There are too
1658  // many places in the C++ runtime code (e.g. RegEx) that assume that
1659  // elements in InternalArrays can be set to non-Smi values without going
1660  // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
1661  // transition easy to trap. Moreover, they rarely are smi-only.
1662  MaybeObject* maybe_map = array_function->initial_map()->Copy();
1663  Map* new_map;
1664  if (!maybe_map->To(&new_map)) return false;
1665  new_map->set_elements_kind(FAST_HOLEY_ELEMENTS);
1666  array_function->set_initial_map(new_map);
1667 
1668  // Make "length" magic on instances.
1669  Handle<Map> initial_map(array_function->initial_map());
1670  Handle<DescriptorArray> array_descriptors(
1671  factory()->NewDescriptorArray(0, 1));
1672  DescriptorArray::WhitenessWitness witness(*array_descriptors);
1673 
1674  Handle<Foreign> array_length(factory()->NewForeign(
1675  &Accessors::ArrayLength));
1676  PropertyAttributes attribs = static_cast<PropertyAttributes>(
1678  initial_map->set_instance_descriptors(*array_descriptors);
1679 
1680  { // Add length.
1681  CallbacksDescriptor d(
1682  *factory()->length_symbol(), *array_length, attribs);
1683  array_function->initial_map()->AppendDescriptor(&d, witness);
1684  }
1685 
1686  native_context()->set_internal_array_function(*array_function);
1687  }
1688 
1689  if (FLAG_disable_native_files) {
1690  PrintF("Warning: Running without installed natives!\n");
1691  return true;
1692  }
1693 
1694  // Install natives.
1695  for (int i = Natives::GetDebuggerCount();
1697  i++) {
1698  if (!CompileBuiltin(isolate(), i)) return false;
1699  // TODO(ager): We really only need to install the JS builtin
1700  // functions on the builtins object after compiling and running
1701  // runtime.js.
1702  if (!InstallJSBuiltins(builtins)) return false;
1703  }
1704 
1705  InstallNativeFunctions();
1706 
1707  // Store the map for the string prototype after the natives has been compiled
1708  // and the String function has been set up.
1709  Handle<JSFunction> string_function(native_context()->string_function());
1711  string_function->initial_map()->prototype())->HasFastProperties());
1712  native_context()->set_string_function_prototype_map(
1713  HeapObject::cast(string_function->initial_map()->prototype())->map());
1714 
1715  // Install Function.prototype.call and apply.
1716  { Handle<String> key = factory()->function_class_symbol();
1717  Handle<JSFunction> function =
1718  Handle<JSFunction>::cast(GetProperty(isolate()->global_object(), key));
1719  Handle<JSObject> proto =
1720  Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1721 
1722  // Install the call and the apply functions.
1723  Handle<JSFunction> call =
1724  InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1725  Handle<JSObject>::null(),
1726  Builtins::kFunctionCall,
1727  false);
1728  Handle<JSFunction> apply =
1729  InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1730  Handle<JSObject>::null(),
1731  Builtins::kFunctionApply,
1732  false);
1733 
1734  // Make sure that Function.prototype.call appears to be compiled.
1735  // The code will never be called, but inline caching for call will
1736  // only work if it appears to be compiled.
1737  call->shared()->DontAdaptArguments();
1738  ASSERT(call->is_compiled());
1739 
1740  // Set the expected parameters for apply to 2; required by builtin.
1741  apply->shared()->set_formal_parameter_count(2);
1742 
1743  // Set the lengths for the functions to satisfy ECMA-262.
1744  call->shared()->set_length(1);
1745  apply->shared()->set_length(2);
1746  }
1747 
1748  InstallBuiltinFunctionIds();
1749 
1750  // Create a constructor for RegExp results (a variant of Array that
1751  // predefines the two properties index and match).
1752  {
1753  // RegExpResult initial map.
1754 
1755  // Find global.Array.prototype to inherit from.
1756  Handle<JSFunction> array_constructor(native_context()->array_function());
1757  Handle<JSObject> array_prototype(
1758  JSObject::cast(array_constructor->instance_prototype()));
1759 
1760  // Add initial map.
1761  Handle<Map> initial_map =
1762  factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1763  initial_map->set_constructor(*array_constructor);
1764 
1765  // Set prototype on map.
1766  initial_map->set_non_instance_prototype(false);
1767  initial_map->set_prototype(*array_prototype);
1768 
1769  // Update map with length accessor from Array and add "index" and "input".
1770  Handle<DescriptorArray> reresult_descriptors =
1771  factory()->NewDescriptorArray(0, 3);
1772  DescriptorArray::WhitenessWitness witness(*reresult_descriptors);
1773  initial_map->set_instance_descriptors(*reresult_descriptors);
1774 
1775  {
1776  JSFunction* array_function = native_context()->array_function();
1777  Handle<DescriptorArray> array_descriptors(
1778  array_function->initial_map()->instance_descriptors());
1779  String* length = heap()->length_symbol();
1780  int old = array_descriptors->SearchWithCache(
1781  length, array_function->initial_map());
1783  CallbacksDescriptor desc(length,
1784  array_descriptors->GetValue(old),
1785  array_descriptors->GetDetails(old).attributes());
1786  initial_map->AppendDescriptor(&desc, witness);
1787  }
1788  {
1789  FieldDescriptor index_field(heap()->index_symbol(),
1791  NONE);
1792  initial_map->AppendDescriptor(&index_field, witness);
1793  }
1794 
1795  {
1796  FieldDescriptor input_field(heap()->input_symbol(),
1798  NONE);
1799  initial_map->AppendDescriptor(&input_field, witness);
1800  }
1801 
1802  initial_map->set_inobject_properties(2);
1803  initial_map->set_pre_allocated_property_fields(2);
1804  initial_map->set_unused_property_fields(0);
1805 
1806  native_context()->set_regexp_result_map(*initial_map);
1807  }
1808 
1809 #ifdef VERIFY_HEAP
1810  builtins->Verify();
1811 #endif
1812 
1813  return true;
1814 }
1815 
1816 
1817 bool Genesis::InstallExperimentalNatives() {
1820  i++) {
1821  if (FLAG_harmony_proxies &&
1822  strcmp(ExperimentalNatives::GetScriptName(i).start(),
1823  "native proxy.js") == 0) {
1824  if (!CompileExperimentalBuiltin(isolate(), i)) return false;
1825  }
1826  if (FLAG_harmony_collections &&
1827  strcmp(ExperimentalNatives::GetScriptName(i).start(),
1828  "native collection.js") == 0) {
1829  if (!CompileExperimentalBuiltin(isolate(), i)) return false;
1830  }
1831  }
1832 
1833  InstallExperimentalNativeFunctions();
1834 
1835  return true;
1836 }
1837 
1838 
1839 static Handle<JSObject> ResolveBuiltinIdHolder(
1840  Handle<Context> native_context,
1841  const char* holder_expr) {
1842  Factory* factory = native_context->GetIsolate()->factory();
1843  Handle<GlobalObject> global(native_context->global_object());
1844  const char* period_pos = strchr(holder_expr, '.');
1845  if (period_pos == NULL) {
1846  return Handle<JSObject>::cast(
1847  GetProperty(global, factory->LookupAsciiSymbol(holder_expr)));
1848  }
1849  ASSERT_EQ(".prototype", period_pos);
1850  Vector<const char> property(holder_expr,
1851  static_cast<int>(period_pos - holder_expr));
1852  Handle<JSFunction> function = Handle<JSFunction>::cast(
1853  GetProperty(global, factory->LookupSymbol(property)));
1854  return Handle<JSObject>(JSObject::cast(function->prototype()));
1855 }
1856 
1857 
1858 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
1859  const char* function_name,
1860  BuiltinFunctionId id) {
1861  Factory* factory = holder->GetIsolate()->factory();
1862  Handle<String> name = factory->LookupAsciiSymbol(function_name);
1863  Object* function_object = holder->GetProperty(*name)->ToObjectUnchecked();
1864  Handle<JSFunction> function(JSFunction::cast(function_object));
1865  function->shared()->set_function_data(Smi::FromInt(id));
1866 }
1867 
1868 
1869 void Genesis::InstallBuiltinFunctionIds() {
1870  HandleScope scope;
1871 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
1872  { \
1873  Handle<JSObject> holder = ResolveBuiltinIdHolder( \
1874  native_context(), #holder_expr); \
1875  BuiltinFunctionId id = k##name; \
1876  InstallBuiltinFunctionId(holder, #fun_name, id); \
1877  }
1879 #undef INSTALL_BUILTIN_ID
1880 }
1881 
1882 
1883 // Do not forget to update macros.py with named constant
1884 // of cache id.
1885 #define JSFUNCTION_RESULT_CACHE_LIST(F) \
1886  F(16, native_context()->regexp_function())
1887 
1888 
1889 static FixedArray* CreateCache(int size, Handle<JSFunction> factory_function) {
1890  Factory* factory = factory_function->GetIsolate()->factory();
1891  // Caches are supposed to live for a long time, allocate in old space.
1892  int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1893  // Cannot use cast as object is not fully initialized yet.
1894  JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1895  *factory->NewFixedArrayWithHoles(array_size, TENURED));
1896  cache->set(JSFunctionResultCache::kFactoryIndex, *factory_function);
1897  cache->MakeZeroSize();
1898  return cache;
1899 }
1900 
1901 
1902 void Genesis::InstallJSFunctionResultCaches() {
1903  const int kNumberOfCaches = 0 +
1904 #define F(size, func) + 1
1906 #undef F
1907  ;
1908 
1909  Handle<FixedArray> caches = FACTORY->NewFixedArray(kNumberOfCaches, TENURED);
1910 
1911  int index = 0;
1912 
1913 #define F(size, func) do { \
1914  FixedArray* cache = CreateCache((size), Handle<JSFunction>(func)); \
1915  caches->set(index++, cache); \
1916  } while (false)
1917 
1919 
1920 #undef F
1921 
1922  native_context()->set_jsfunction_result_caches(*caches);
1923 }
1924 
1925 
1926 void Genesis::InitializeNormalizedMapCaches() {
1927  Handle<FixedArray> array(
1928  FACTORY->NewFixedArray(NormalizedMapCache::kEntries, TENURED));
1929  native_context()->set_normalized_map_cache(NormalizedMapCache::cast(*array));
1930 }
1931 
1932 
1934  v8::ExtensionConfiguration* extensions) {
1935  Isolate* isolate = native_context->GetIsolate();
1936  BootstrapperActive active;
1937  SaveContext saved_context(isolate);
1938  isolate->set_context(*native_context);
1939  if (!Genesis::InstallExtensions(native_context, extensions)) return false;
1940  Genesis::InstallSpecialObjects(native_context);
1941  return true;
1942 }
1943 
1944 
1945 void Genesis::InstallSpecialObjects(Handle<Context> native_context) {
1946  Isolate* isolate = native_context->GetIsolate();
1947  Factory* factory = isolate->factory();
1948  HandleScope scope;
1950  native_context->global_object()));
1951  // Expose the natives in global if a name for it is specified.
1952  if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1953  Handle<String> natives = factory->LookupAsciiSymbol(FLAG_expose_natives_as);
1954  CHECK_NOT_EMPTY_HANDLE(isolate,
1956  global, natives,
1957  Handle<JSObject>(global->builtins()),
1958  DONT_ENUM));
1959  }
1960 
1961  Handle<Object> Error = GetProperty(global, "Error");
1962  if (Error->IsJSObject()) {
1963  Handle<String> name = factory->LookupAsciiSymbol("stackTraceLimit");
1964  Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit));
1965  CHECK_NOT_EMPTY_HANDLE(isolate,
1967  Handle<JSObject>::cast(Error), name,
1968  stack_trace_limit, NONE));
1969  }
1970 
1971 #ifdef ENABLE_DEBUGGER_SUPPORT
1972  // Expose the debug global object in global if a name for it is specified.
1973  if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1974  Debug* debug = Isolate::Current()->debug();
1975  // If loading fails we just bail out without installing the
1976  // debugger but without tanking the whole context.
1977  if (!debug->Load()) return;
1978  // Set the security token for the debugger context to the same as
1979  // the shell native context to allow calling between these (otherwise
1980  // exposing debug global object doesn't make much sense).
1981  debug->debug_context()->set_security_token(
1982  native_context->security_token());
1983 
1984  Handle<String> debug_string =
1985  factory->LookupAsciiSymbol(FLAG_expose_debug_as);
1986  Handle<Object> global_proxy(debug->debug_context()->global_proxy());
1987  CHECK_NOT_EMPTY_HANDLE(isolate,
1989  global, debug_string, global_proxy, DONT_ENUM));
1990  }
1991 #endif
1992 }
1993 
1994 static uint32_t Hash(RegisteredExtension* extension) {
1995  return v8::internal::ComputePointerHash(extension);
1996 }
1997 
1998 static bool MatchRegisteredExtensions(void* key1, void* key2) {
1999  return key1 == key2;
2000 }
2001 
2002 Genesis::ExtensionStates::ExtensionStates()
2003  : map_(MatchRegisteredExtensions, 8) { }
2004 
2005 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2006  RegisteredExtension* extension) {
2007  i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension), false);
2008  if (entry == NULL) {
2009  return UNVISITED;
2010  }
2011  return static_cast<ExtensionTraversalState>(
2012  reinterpret_cast<intptr_t>(entry->value));
2013 }
2014 
2015 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2016  ExtensionTraversalState state) {
2017  map_.Lookup(extension, Hash(extension), true)->value =
2018  reinterpret_cast<void*>(static_cast<intptr_t>(state));
2019 }
2020 
2021 bool Genesis::InstallExtensions(Handle<Context> native_context,
2022  v8::ExtensionConfiguration* extensions) {
2023  // TODO(isolates): Extensions on multiple isolates may take a little more
2024  // effort. (The external API reads 'ignore'-- does that mean
2025  // we can break the interface?)
2026 
2027 
2028  ExtensionStates extension_states; // All extensions have state UNVISITED.
2029  // Install auto extensions.
2031  while (current != NULL) {
2032  if (current->extension()->auto_enable())
2033  InstallExtension(current, &extension_states);
2034  current = current->next();
2035  }
2036 
2037  if (FLAG_expose_gc) InstallExtension("v8/gc", &extension_states);
2038  if (FLAG_expose_externalize_string) {
2039  InstallExtension("v8/externalize", &extension_states);
2040  }
2041  if (FLAG_track_gc_object_stats) {
2042  InstallExtension("v8/statistics", &extension_states);
2043  }
2044 
2045  if (extensions == NULL) return true;
2046  // Install required extensions
2047  int count = v8::ImplementationUtilities::GetNameCount(extensions);
2048  const char** names = v8::ImplementationUtilities::GetNames(extensions);
2049  for (int i = 0; i < count; i++) {
2050  if (!InstallExtension(names[i], &extension_states))
2051  return false;
2052  }
2053 
2054  return true;
2055 }
2056 
2057 
2058 // Installs a named extension. This methods is unoptimized and does
2059 // not scale well if we want to support a large number of extensions.
2060 bool Genesis::InstallExtension(const char* name,
2061  ExtensionStates* extension_states) {
2063  // Loop until we find the relevant extension
2064  while (current != NULL) {
2065  if (strcmp(name, current->extension()->name()) == 0) break;
2066  current = current->next();
2067  }
2068  // Didn't find the extension; fail.
2069  if (current == NULL) {
2071  "v8::Context::New()", "Cannot find required extension");
2072  return false;
2073  }
2074  return InstallExtension(current, extension_states);
2075 }
2076 
2077 
2078 bool Genesis::InstallExtension(v8::RegisteredExtension* current,
2079  ExtensionStates* extension_states) {
2080  HandleScope scope;
2081 
2082  if (extension_states->get_state(current) == INSTALLED) return true;
2083  // The current node has already been visited so there must be a
2084  // cycle in the dependency graph; fail.
2085  if (extension_states->get_state(current) == VISITED) {
2087  "v8::Context::New()", "Circular extension dependency");
2088  return false;
2089  }
2090  ASSERT(extension_states->get_state(current) == UNVISITED);
2091  extension_states->set_state(current, VISITED);
2092  v8::Extension* extension = current->extension();
2093  // Install the extension's dependencies
2094  for (int i = 0; i < extension->dependency_count(); i++) {
2095  if (!InstallExtension(extension->dependencies()[i], extension_states))
2096  return false;
2097  }
2098  Isolate* isolate = Isolate::Current();
2099  Handle<String> source_code =
2100  isolate->factory()->NewExternalStringFromAscii(extension->source());
2101  bool result = CompileScriptCached(
2102  CStrVector(extension->name()),
2103  source_code,
2104  isolate->bootstrapper()->extensions_cache(),
2105  extension,
2106  Handle<Context>(isolate->context()),
2107  false);
2108  ASSERT(isolate->has_pending_exception() != result);
2109  if (!result) {
2110  // We print out the name of the extension that fail to install.
2111  // When an error is thrown during bootstrapping we automatically print
2112  // the line number at which this happened to the console in the isolate
2113  // error throwing functionality.
2114  OS::PrintError("Error installing extension '%s'.\n",
2115  current->extension()->name());
2116  isolate->clear_pending_exception();
2117  }
2118  extension_states->set_state(current, INSTALLED);
2119  isolate->NotifyExtensionInstalled();
2120  return result;
2121 }
2122 
2123 
2124 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2125  HandleScope scope;
2126  Factory* factory = builtins->GetIsolate()->factory();
2127  for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2128  Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2129  Handle<String> name = factory->LookupAsciiSymbol(Builtins::GetName(id));
2130  Object* function_object = builtins->GetPropertyNoExceptionThrown(*name);
2131  Handle<JSFunction> function
2132  = Handle<JSFunction>(JSFunction::cast(function_object));
2133  builtins->set_javascript_builtin(id, *function);
2134  if (!JSFunction::CompileLazy(function, CLEAR_EXCEPTION)) {
2135  return false;
2136  }
2137  builtins->set_javascript_builtin_code(id, function->shared()->code());
2138  }
2139  return true;
2140 }
2141 
2142 
2143 bool Genesis::ConfigureGlobalObjects(
2144  v8::Handle<v8::ObjectTemplate> global_proxy_template) {
2145  Handle<JSObject> global_proxy(
2146  JSObject::cast(native_context()->global_proxy()));
2147  Handle<JSObject> inner_global(
2148  JSObject::cast(native_context()->global_object()));
2149 
2150  if (!global_proxy_template.IsEmpty()) {
2151  // Configure the global proxy object.
2152  Handle<ObjectTemplateInfo> proxy_data =
2153  v8::Utils::OpenHandle(*global_proxy_template);
2154  if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
2155 
2156  // Configure the inner global object.
2157  Handle<FunctionTemplateInfo> proxy_constructor(
2158  FunctionTemplateInfo::cast(proxy_data->constructor()));
2159  if (!proxy_constructor->prototype_template()->IsUndefined()) {
2160  Handle<ObjectTemplateInfo> inner_data(
2161  ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2162  if (!ConfigureApiObject(inner_global, inner_data)) return false;
2163  }
2164  }
2165 
2166  SetObjectPrototype(global_proxy, inner_global);
2167  return true;
2168 }
2169 
2170 
2171 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
2172  Handle<ObjectTemplateInfo> object_template) {
2173  ASSERT(!object_template.is_null());
2174  ASSERT(object->IsInstanceOf(
2175  FunctionTemplateInfo::cast(object_template->constructor())));
2176 
2177  bool pending_exception = false;
2178  Handle<JSObject> obj =
2179  Execution::InstantiateObject(object_template, &pending_exception);
2180  if (pending_exception) {
2181  ASSERT(isolate()->has_pending_exception());
2182  isolate()->clear_pending_exception();
2183  return false;
2184  }
2185  TransferObject(obj, object);
2186  return true;
2187 }
2188 
2189 
2190 void Genesis::TransferNamedProperties(Handle<JSObject> from,
2191  Handle<JSObject> to) {
2192  if (from->HasFastProperties()) {
2193  Handle<DescriptorArray> descs =
2194  Handle<DescriptorArray>(from->map()->instance_descriptors());
2195  for (int i = 0; i < descs->number_of_descriptors(); i++) {
2196  PropertyDetails details = descs->GetDetails(i);
2197  switch (details.type()) {
2198  case FIELD: {
2199  HandleScope inner;
2200  Handle<String> key = Handle<String>(descs->GetKey(i));
2201  int index = descs->GetFieldIndex(i);
2202  Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
2203  CHECK_NOT_EMPTY_HANDLE(to->GetIsolate(),
2205  to, key, value, details.attributes()));
2206  break;
2207  }
2208  case CONSTANT_FUNCTION: {
2209  HandleScope inner;
2210  Handle<String> key = Handle<String>(descs->GetKey(i));
2211  Handle<JSFunction> fun =
2212  Handle<JSFunction>(descs->GetConstantFunction(i));
2213  CHECK_NOT_EMPTY_HANDLE(to->GetIsolate(),
2215  to, key, fun, details.attributes()));
2216  break;
2217  }
2218  case CALLBACKS: {
2219  LookupResult result(isolate());
2220  to->LocalLookup(descs->GetKey(i), &result);
2221  // If the property is already there we skip it
2222  if (result.IsFound()) continue;
2223  HandleScope inner;
2224  ASSERT(!to->HasFastProperties());
2225  // Add to dictionary.
2226  Handle<String> key = Handle<String>(descs->GetKey(i));
2227  Handle<Object> callbacks(descs->GetCallbacksObject(i));
2228  PropertyDetails d = PropertyDetails(details.attributes(),
2229  CALLBACKS,
2230  details.descriptor_index());
2231  JSObject::SetNormalizedProperty(to, key, callbacks, d);
2232  break;
2233  }
2234  case NORMAL:
2235  // Do not occur since the from object has fast properties.
2236  case HANDLER:
2237  case INTERCEPTOR:
2238  case TRANSITION:
2239  case NONEXISTENT:
2240  // No element in instance descriptors have proxy or interceptor type.
2241  UNREACHABLE();
2242  break;
2243  }
2244  }
2245  } else {
2246  Handle<StringDictionary> properties =
2247  Handle<StringDictionary>(from->property_dictionary());
2248  int capacity = properties->Capacity();
2249  for (int i = 0; i < capacity; i++) {
2250  Object* raw_key(properties->KeyAt(i));
2251  if (properties->IsKey(raw_key)) {
2252  ASSERT(raw_key->IsString());
2253  // If the property is already there we skip it.
2254  LookupResult result(isolate());
2255  to->LocalLookup(String::cast(raw_key), &result);
2256  if (result.IsFound()) continue;
2257  // Set the property.
2258  Handle<String> key = Handle<String>(String::cast(raw_key));
2259  Handle<Object> value = Handle<Object>(properties->ValueAt(i));
2260  if (value->IsJSGlobalPropertyCell()) {
2261  value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
2262  }
2263  PropertyDetails details = properties->DetailsAt(i);
2264  CHECK_NOT_EMPTY_HANDLE(to->GetIsolate(),
2266  to, key, value, details.attributes()));
2267  }
2268  }
2269  }
2270 }
2271 
2272 
2273 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
2274  Handle<JSObject> to) {
2275  // Cloning the elements array is sufficient.
2276  Handle<FixedArray> from_elements =
2277  Handle<FixedArray>(FixedArray::cast(from->elements()));
2278  Handle<FixedArray> to_elements = FACTORY->CopyFixedArray(from_elements);
2279  to->set_elements(*to_elements);
2280 }
2281 
2282 
2283 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
2284  HandleScope outer;
2285  Factory* factory = from->GetIsolate()->factory();
2286 
2287  ASSERT(!from->IsJSArray());
2288  ASSERT(!to->IsJSArray());
2289 
2290  TransferNamedProperties(from, to);
2291  TransferIndexedProperties(from, to);
2292 
2293  // Transfer the prototype (new map is needed).
2294  Handle<Map> old_to_map = Handle<Map>(to->map());
2295  Handle<Map> new_to_map = factory->CopyMap(old_to_map);
2296  new_to_map->set_prototype(from->map()->prototype());
2297  to->set_map(*new_to_map);
2298 }
2299 
2300 
2301 void Genesis::MakeFunctionInstancePrototypeWritable() {
2302  // The maps with writable prototype are created in CreateEmptyFunction
2303  // and CreateStrictModeFunctionMaps respectively. Initially the maps are
2304  // created with read-only prototype for JS builtins processing.
2305  ASSERT(!function_instance_map_writable_prototype_.is_null());
2306  ASSERT(!strict_mode_function_instance_map_writable_prototype_.is_null());
2307 
2308  // Replace function instance maps to make prototype writable.
2309  native_context()->set_function_map(
2310  *function_instance_map_writable_prototype_);
2311  native_context()->set_strict_mode_function_map(
2312  *strict_mode_function_instance_map_writable_prototype_);
2313 }
2314 
2315 
2316 Genesis::Genesis(Isolate* isolate,
2317  Handle<Object> global_object,
2318  v8::Handle<v8::ObjectTemplate> global_template,
2319  v8::ExtensionConfiguration* extensions) : isolate_(isolate) {
2320  result_ = Handle<Context>::null();
2321  // If V8 isn't running and cannot be initialized, just return.
2322  if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
2323 
2324  // Before creating the roots we must save the context and restore it
2325  // on all function exits.
2326  HandleScope scope;
2327  SaveContext saved_context(isolate);
2328 
2329  // During genesis, the boilerplate for stack overflow won't work until the
2330  // environment has been at least partially initialized. Add a stack check
2331  // before entering JS code to catch overflow early.
2332  StackLimitCheck check(Isolate::Current());
2333  if (check.HasOverflowed()) return;
2334 
2335  Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
2336  if (!new_context.is_null()) {
2337  native_context_ =
2338  Handle<Context>::cast(isolate->global_handles()->Create(*new_context));
2339  AddToWeakNativeContextList(*native_context_);
2340  isolate->set_context(*native_context_);
2341  isolate->counters()->contexts_created_by_snapshot()->Increment();
2342  Handle<GlobalObject> inner_global;
2343  Handle<JSGlobalProxy> global_proxy =
2344  CreateNewGlobals(global_template,
2345  global_object,
2346  &inner_global);
2347 
2348  HookUpGlobalProxy(inner_global, global_proxy);
2349  HookUpInnerGlobal(inner_global);
2350 
2351  if (!ConfigureGlobalObjects(global_template)) return;
2352  } else {
2353  // We get here if there was no context snapshot.
2354  CreateRoots();
2355  Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
2356  CreateStrictModeFunctionMaps(empty_function);
2357  Handle<GlobalObject> inner_global;
2358  Handle<JSGlobalProxy> global_proxy =
2359  CreateNewGlobals(global_template, global_object, &inner_global);
2360  HookUpGlobalProxy(inner_global, global_proxy);
2361  if (!InitializeGlobal(inner_global, empty_function)) return;
2362  InstallJSFunctionResultCaches();
2363  InitializeNormalizedMapCaches();
2364  if (!InstallNatives()) return;
2365 
2366  MakeFunctionInstancePrototypeWritable();
2367 
2368  if (!ConfigureGlobalObjects(global_template)) return;
2369  isolate->counters()->contexts_created_from_scratch()->Increment();
2370  }
2371 
2372  // Initialize experimental globals and install experimental natives.
2373  InitializeExperimentalGlobal();
2374  if (!InstallExperimentalNatives()) return;
2375 
2376  result_ = native_context_;
2377 }
2378 
2379 
2380 // Support for thread preemption.
2381 
2382 // Reserve space for statics needing saving and restoring.
2384  return sizeof(NestingCounterType);
2385 }
2386 
2387 
2388 // Archive statics that are thread local.
2390  *reinterpret_cast<NestingCounterType*>(to) = nesting_;
2391  nesting_ = 0;
2392  return to + sizeof(NestingCounterType);
2393 }
2394 
2395 
2396 // Restore statics that are thread local.
2397 char* Bootstrapper::RestoreState(char* from) {
2398  nesting_ = *reinterpret_cast<NestingCounterType*>(from);
2399  return from + sizeof(NestingCounterType);
2400 }
2401 
2402 
2403 // Called when the top-level V8 mutex is destroyed.
2405  ASSERT(!IsActive());
2406 }
2407 
2408 } } // namespace v8::internal
#define CHECK_NOT_EMPTY_HANDLE(isolate, call)
Definition: isolate.h:128
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if expose natives in global object expose gc extension number of stack frames to capture disable builtin natives files print a stack trace if an assertion failure occurs use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations prepare for turning on always opt minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions automatically set the debug break flag when debugger commands are in the queue always cause a debug break before aborting maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable memory(in Mbytes)") DEFINE_bool(gc_global
RegisteredExtension * next()
Definition: api.h:151
static bool Initialize(Deserializer *des)
Definition: v8.cc:64
Code * builtin(Name name)
Definition: builtins.h:320
static bool CompileLazy(Handle< JSFunction > function, ClearExceptionFlag flag)
Definition: objects.cc:7643
char * ArchiveState(char *to)
Handle< String > NewExternalStringFromAscii(const ExternalAsciiString::Resource *resource)
Definition: factory.cc:270
static const int kGlobalFieldIndex
Definition: objects.h:6675
void PrintF(const char *format,...)
Definition: v8utils.cc:40
void Initialize(bool create_heap_objects)
Definition: bootstrapper.cc:95
static const int kSize
Definition: objects.h:6350
char * AllocateAutoDeletedArray(int bytes)
static String * cast(Object *obj)
v8::internal::Handle< v8::internal::JSObject > value()
Definition: api.h:77
Handle< Context > result()
static Smi * FromInt(int value)
Definition: objects-inl.h:981
static ObjectTemplateInfo * cast(Object *obj)
static Vector< const char > GetRawScriptSource(int index)
static HeapObject * cast(Object *obj)
bool auto_enable()
Definition: v8.h:2581
static Handle< T > cast(Handle< S > that)
Definition: handles.h:81
static const int kSourceFieldIndex
Definition: objects.h:6674
static Vector< const char > GetScriptName(int index)
static AccessorPair * cast(Object *obj)
static const char ** GetNames(ExtensionConfiguration *that)
Definition: apiutils.h:38
T & at(int i) const
Definition: list.h:90
Builtins * builtins()
Definition: isolate.h:924
static const int kSize
Definition: objects.h:6235
static Handle< Context > NewContextFromSnapshot()
static const int kSize
Definition: objects.h:6625
#define ASSERT(condition)
Definition: checks.h:270
MUST_USE_RESULT MaybeObject * PreventExtensions()
Definition: objects.cc:4143
char * RestoreState(char *from)
Handle< JSFunction > NewFunctionWithPrototype(Handle< String > name, InstanceType type, int instance_size, Handle< JSObject > prototype, Handle< Code > code, bool force_initial_map)
Definition: factory.cc:817
bool InstallExtensions(Handle< Context > native_context, v8::ExtensionConfiguration *extensions)
static const char * GetName(JavaScript id)
Definition: builtins.h:334
static Context * cast(Object *context)
Definition: contexts.h:212
static const int kSize
Definition: objects.h:8209
static const int kSize
Definition: objects.h:8355
Handle< Object > GetProperty(Handle< JSReceiver > obj, const char *name)
Definition: handles.cc:282
Factory * factory()
Definition: isolate.h:992
PropertyAttributes
Handle< String > LookupAsciiSymbol(Vector< const char > str)
Definition: factory.cc:174
Extension * extension()
Definition: api.h:150
static const int kMultilineFieldIndex
Definition: objects.h:6677
static const int kSize
Definition: objects.h:8333
GlobalObject * global_object()
Definition: contexts.h:328
friend class NativesExternalStringResource
Definition: bootstrapper.h:145
uint32_t ComputePointerHash(void *ptr)
Definition: utils.h:311
#define UNREACHABLE()
Definition: checks.h:50
Handle< Map > CopyMap(Handle< Map > map, int extra_inobject_props)
Definition: factory.cc:483
static const int kArgumentsObjectSizeStrict
Definition: heap.h:898
T * start() const
Definition: utils.h:390
static JSGlobalProxy * cast(Object *obj)
static const int kInputIndex
Definition: objects.h:8358
#define INSTALL_BUILTIN_ID(holder_expr, fun_name, name)
friend class BootstrapperActive
Definition: bootstrapper.h:143
void set_context(Context *context)
Definition: isolate.h:521
const int kPointerSize
Definition: globals.h:220
const char * name() const
Definition: v8.h:2574
static int GetNameCount(ExtensionConfiguration *that)
Definition: apiutils.h:34
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: globals.h:307
static Handle< Object > SetLocalPropertyIgnoreAttributes(Handle< JSObject > object, Handle< String > key, Handle< Object > value, PropertyAttributes attributes)
Definition: objects.cc:2952
static FunctionTemplateInfo * cast(Object *obj)
Handle< String > NativesSourceLookup(int index)
Definition: bootstrapper.cc:74
int length() const
Definition: utils.h:384
static int NumberOfJavaScriptBuiltins()
Definition: builtins.h:337
static const int kIgnoreCaseFieldIndex
Definition: objects.h:6676
Definition: v8.h:105
static Handle< Object > Call(Handle< Object > callable, Handle< Object > receiver, int argc, Handle< Object > argv[], bool *pending_exception, bool convert_receiver=false)
Definition: execution.cc:150
Vector< const char > CStrVector(const char *data)
Definition: utils.h:526
static const int kSize
Definition: objects.h:8184
Handle< Context > CreateEnvironment(Isolate *isolate, Handle< Object > global_object, v8::Handle< v8::ObjectTemplate > global_template, v8::ExtensionConfiguration *extensions)
void Iterate(ObjectVisitor *v)
Isolate * isolate() const
int dependency_count()
Definition: v8.h:2578
Handle< JSFunction > NewFunctionWithoutPrototype(Handle< String > name, LanguageMode language_mode)
Definition: factory.cc:1144
static const int kSize
Definition: objects.h:6386
#define INSTALL_NATIVE(Type, name, var)
static Handle< SharedFunctionInfo > Compile(Handle< String > source, Handle< Object > script_name, int line_offset, int column_offset, Handle< Context > context, v8::Extension *extension, ScriptDataImpl *pre_data, Handle< Object > script_data, NativesFlag is_natives_code)
Definition: compiler.cc:542
bool is_null() const
Definition: handles.h:87
#define JSFUNCTION_RESULT_CACHE_LIST(F)
static const int kArgumentsLengthIndex
Definition: heap.h:901
void DetachGlobal(Handle< Context > env)
const String::ExternalAsciiStringResource * source() const
Definition: v8.h:2576
static JSGlobalPropertyCell * cast(Object *obj)
static RegisteredExtension * first_extension()
Definition: api.h:153
static void PrintError(const char *format,...)
Handle< JSGlobalProxy > ReinitializeJSGlobalProxy(Handle< JSFunction > constructor, Handle< JSGlobalProxy > global)
Definition: handles.cc:147
static Handle< String > null()
Definition: handles.h:86
TemplateHashMapImpl< FreeStoreAllocationPolicy > HashMap
Definition: hashmap.h:113
Handle< Foreign > NewForeign(Address addr, PretenureFlag pretenure=NOT_TENURED)
Definition: factory.cc:414
static const int kSize
Definition: objects.h:6477
#define ASSERT_EQ(v1, v2)
Definition: checks.h:271
static const int kIndexIndex
Definition: objects.h:8357
const int kRandomStateSize
Definition: globals.h:225
static Handle< JSObject > InstantiateObject(Handle< ObjectTemplateInfo > data, bool *exc)
Definition: execution.cc:744
static const int kArgumentsCalleeIndex
Definition: heap.h:903
static FixedArray * cast(Object *obj)
static const int kHeaderSize
Definition: objects.h:2173
Object * SetNormalizedProperty(LookupResult *result, Object *value)
Definition: objects.cc:445
static bool ReportApiFailure(const char *location, const char *message)
Definition: api.cc:220
void Add(const T &element, AllocationPolicy allocator=AllocationPolicy())
Definition: list-inl.h:38
bool IsEmpty() const
Definition: v8.h:209
#define FACTORY
Definition: isolate.h:1434
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if NULL
Definition: flags.cc:301
Object * get(int index)
Definition: objects-inl.h:1737
static VisitorId GetVisitorId(int instance_type, int instance_size)
static const int kSize
Definition: objects.h:6191
Handle< Object > ForceSetProperty(Handle< JSObject > object, Handle< Object > key, Handle< Object > value, PropertyAttributes attributes)
Definition: handles.cc:246
static const int kSize
Definition: objects.h:8238
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra code(assertions) for debugging") DEFINE_bool(code_comments
static NormalizedMapCache * cast(Object *obj)
void ReattachGlobal(Handle< Context > env, Handle< JSGlobalProxy > global_proxy)
Handle< Object > SetPrototype(Handle< JSFunction > function, Handle< Object > prototype)
Definition: handles.cc:221
static const int kLastIndexFieldIndex
Definition: objects.h:6678
static GlobalObject * cast(Object *obj)
static const int kSize
Definition: objects.h:6312
#define FUNCTIONS_WITH_ID_LIST(V)
Definition: objects.h:5334
NativesExternalStringResource(Bootstrapper *bootstrapper, const char *source, size_t length)
Definition: bootstrapper.cc:51
Handle< Map > NewMap(InstanceType type, int instance_size, ElementsKind elements_kind=TERMINAL_FAST_ELEMENTS_KIND)
Definition: factory.cc:459
Factory * factory() const
const char ** dependencies()
Definition: v8.h:2579
static const int kNotFound
Definition: objects.h:2619
void check(i::Vector< const char > string)
static int ArchiveSpacePerThread()
static JSObject * cast(Object *obj)
static bool IsRunning()
Definition: v8.h:85
static JSGlobalObject * cast(Object *obj)
static JSFunction * cast(Object *obj)