v8  3.11.10(node0.8.26)
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"
45 
46 namespace v8 {
47 namespace internal {
48 
49 
51  Bootstrapper* bootstrapper,
52  const char* source,
53  size_t length)
54  : data_(source), length_(length) {
55  if (bootstrapper->delete_these_non_arrays_on_tear_down_ == NULL) {
56  bootstrapper->delete_these_non_arrays_on_tear_down_ = new List<char*>(2);
57  }
58  // The resources are small objects and we only make a fixed number of
59  // them, but let's clean them up on exit for neatness.
60  bootstrapper->delete_these_non_arrays_on_tear_down_->
61  Add(reinterpret_cast<char*>(this));
62 }
63 
64 
65 Bootstrapper::Bootstrapper()
66  : nesting_(0),
67  extensions_cache_(Script::TYPE_EXTENSION),
68  delete_these_non_arrays_on_tear_down_(NULL),
69  delete_these_arrays_on_tear_down_(NULL) {
70 }
71 
72 
74  ASSERT(0 <= index && index < Natives::GetBuiltinsCount());
75  Isolate* isolate = Isolate::Current();
76  Factory* factory = isolate->factory();
77  Heap* heap = isolate->heap();
78  if (heap->natives_source_cache()->get(index)->IsUndefined()) {
79  // We can use external strings for the natives.
83  source.start(),
84  source.length());
85  Handle<String> source_code =
86  factory->NewExternalStringFromAscii(resource);
87  heap->natives_source_cache()->set(index, *source_code);
88  }
89  Handle<Object> cached_source(heap->natives_source_cache()->get(index));
90  return Handle<String>::cast(cached_source);
91 }
92 
93 
94 void Bootstrapper::Initialize(bool create_heap_objects) {
95  extensions_cache_.Initialize(create_heap_objects);
98 }
99 
100 
102  char* memory = new char[bytes];
103  if (memory != NULL) {
104  if (delete_these_arrays_on_tear_down_ == NULL) {
105  delete_these_arrays_on_tear_down_ = new List<char*>(2);
106  }
107  delete_these_arrays_on_tear_down_->Add(memory);
108  }
109  return memory;
110 }
111 
112 
114  if (delete_these_non_arrays_on_tear_down_ != NULL) {
115  int len = delete_these_non_arrays_on_tear_down_->length();
116  ASSERT(len < 20); // Don't use this mechanism for unbounded allocations.
117  for (int i = 0; i < len; i++) {
118  delete delete_these_non_arrays_on_tear_down_->at(i);
119  delete_these_non_arrays_on_tear_down_->at(i) = NULL;
120  }
121  delete delete_these_non_arrays_on_tear_down_;
122  delete_these_non_arrays_on_tear_down_ = NULL;
123  }
124 
125  if (delete_these_arrays_on_tear_down_ != NULL) {
126  int len = delete_these_arrays_on_tear_down_->length();
127  ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations.
128  for (int i = 0; i < len; i++) {
129  delete[] delete_these_arrays_on_tear_down_->at(i);
130  delete_these_arrays_on_tear_down_->at(i) = NULL;
131  }
132  delete delete_these_arrays_on_tear_down_;
133  delete_these_arrays_on_tear_down_ = NULL;
134  }
135 
136  extensions_cache_.Initialize(false); // Yes, symmetrical
137 }
138 
139 
140 class Genesis BASE_EMBEDDED {
141  public:
142  Genesis(Isolate* isolate,
143  Handle<Object> global_object,
144  v8::Handle<v8::ObjectTemplate> global_template,
145  v8::ExtensionConfiguration* extensions);
146  ~Genesis() { }
147 
148  Handle<Context> result() { return result_; }
149 
150  Genesis* previous() { return previous_; }
151 
152  Isolate* isolate() const { return isolate_; }
153  Factory* factory() const { return isolate_->factory(); }
154  Heap* heap() const { return isolate_->heap(); }
155 
156  private:
157  Handle<Context> global_context_;
158  Isolate* isolate_;
159 
160  // There may be more than one active genesis object: When GC is
161  // triggered during environment creation there may be weak handle
162  // processing callbacks which may create new environments.
163  Genesis* previous_;
164 
165  Handle<Context> global_context() { return global_context_; }
166 
167  // Creates some basic objects. Used for creating a context from scratch.
168  void CreateRoots();
169  // Creates the empty function. Used for creating a context from scratch.
170  Handle<JSFunction> CreateEmptyFunction(Isolate* isolate);
171  // Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
172  Handle<JSFunction> GetThrowTypeErrorFunction();
173 
174  void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
175 
176  // Make the "arguments" and "caller" properties throw a TypeError on access.
177  void PoisonArgumentsAndCaller(Handle<Map> map);
178 
179  // Creates the global objects using the global and the template passed in
180  // through the API. We call this regardless of whether we are building a
181  // context from scratch or using a deserialized one from the partial snapshot
182  // but in the latter case we don't use the objects it produces directly, as
183  // we have to used the deserialized ones that are linked together with the
184  // rest of the context snapshot.
185  Handle<JSGlobalProxy> CreateNewGlobals(
186  v8::Handle<v8::ObjectTemplate> global_template,
187  Handle<Object> global_object,
188  Handle<GlobalObject>* global_proxy_out);
189  // Hooks the given global proxy into the context. If the context was created
190  // by deserialization then this will unhook the global proxy that was
191  // deserialized, leaving the GC to pick it up.
192  void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
193  Handle<JSGlobalProxy> global_proxy);
194  // Similarly, we want to use the inner global that has been created by the
195  // templates passed through the API. The inner global from the snapshot is
196  // detached from the other objects in the snapshot.
197  void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
198  // New context initialization. Used for creating a context from scratch.
199  bool InitializeGlobal(Handle<GlobalObject> inner_global,
200  Handle<JSFunction> empty_function);
201  void InitializeExperimentalGlobal();
202  // Installs the contents of the native .js files on the global objects.
203  // Used for creating a context from scratch.
204  void InstallNativeFunctions();
205  void InstallExperimentalNativeFunctions();
206  bool InstallNatives();
207  bool InstallExperimentalNatives();
208  void InstallBuiltinFunctionIds();
209  void InstallJSFunctionResultCaches();
210  void InitializeNormalizedMapCaches();
211 
212  enum ExtensionTraversalState {
213  UNVISITED, VISITED, INSTALLED
214  };
215 
216  class ExtensionStates {
217  public:
218  ExtensionStates();
219  ExtensionTraversalState get_state(RegisteredExtension* extension);
220  void set_state(RegisteredExtension* extension,
221  ExtensionTraversalState state);
222  private:
223  HashMap map_;
224  DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
225  };
226 
227  // Used both for deserialized and from-scratch contexts to add the extensions
228  // provided.
229  static bool InstallExtensions(Handle<Context> global_context,
230  v8::ExtensionConfiguration* extensions);
231  static bool InstallExtension(const char* name,
232  ExtensionStates* extension_states);
233  static bool InstallExtension(v8::RegisteredExtension* current,
234  ExtensionStates* extension_states);
235  static void InstallSpecialObjects(Handle<Context> global_context);
236  bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
237  bool ConfigureApiObject(Handle<JSObject> object,
238  Handle<ObjectTemplateInfo> object_template);
239  bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
240 
241  // Migrates all properties from the 'from' object to the 'to'
242  // object and overrides the prototype in 'to' with the one from
243  // 'from'.
244  void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
245  void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
246  void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
247 
248  enum PrototypePropertyMode {
249  DONT_ADD_PROTOTYPE,
250  ADD_READONLY_PROTOTYPE,
251  ADD_WRITEABLE_PROTOTYPE
252  };
253 
254  Handle<Map> CreateFunctionMap(PrototypePropertyMode prototype_mode);
255 
256  Handle<DescriptorArray> ComputeFunctionInstanceDescriptor(
257  PrototypePropertyMode prototypeMode);
258  void MakeFunctionInstancePrototypeWritable();
259 
260  Handle<Map> CreateStrictModeFunctionMap(
261  PrototypePropertyMode prototype_mode,
262  Handle<JSFunction> empty_function);
263 
264  Handle<DescriptorArray> ComputeStrictFunctionInstanceDescriptor(
265  PrototypePropertyMode propertyMode);
266 
267  static bool CompileBuiltin(Isolate* isolate, int index);
268  static bool CompileExperimentalBuiltin(Isolate* isolate, int index);
269  static bool CompileNative(Vector<const char> name, Handle<String> source);
270  static bool CompileScriptCached(Vector<const char> name,
271  Handle<String> source,
272  SourceCodeCache* cache,
273  v8::Extension* extension,
274  Handle<Context> top_context,
275  bool use_runtime_context);
276 
277  Handle<Context> result_;
278 
279  // Function instance maps. Function literal maps are created initially with
280  // a read only prototype for the processing of JS builtins. Later the function
281  // instance maps are replaced in order to make prototype writable.
282  // These are the final, writable prototype, maps.
283  Handle<Map> function_instance_map_writable_prototype_;
284  Handle<Map> strict_mode_function_instance_map_writable_prototype_;
285  Handle<JSFunction> throw_type_error_function;
286 
287  BootstrapperActive active_;
288  friend class Bootstrapper;
289 };
290 
291 
292 void Bootstrapper::Iterate(ObjectVisitor* v) {
293  extensions_cache_.Iterate(v);
294  v->Synchronize(VisitorSynchronization::kExtensions);
295 }
296 
297 
299  Isolate* isolate,
300  Handle<Object> global_object,
301  v8::Handle<v8::ObjectTemplate> global_template,
302  v8::ExtensionConfiguration* extensions) {
303  HandleScope scope;
304  Handle<Context> env;
305  Genesis genesis(isolate, global_object, global_template, extensions);
306  env = genesis.result();
307  if (!env.is_null()) {
308  if (InstallExtensions(env, extensions)) {
309  return env;
310  }
311  }
312  return Handle<Context>();
313 }
314 
315 
316 static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
317  // object.__proto__ = proto;
318  Factory* factory = object->GetIsolate()->factory();
319  Handle<Map> old_to_map = Handle<Map>(object->map());
320  Handle<Map> new_to_map = factory->CopyMapDropTransitions(old_to_map);
321  new_to_map->set_prototype(*proto);
322  object->set_map(*new_to_map);
323 }
324 
325 
327  Factory* factory = env->GetIsolate()->factory();
328  JSGlobalProxy::cast(env->global_proxy())->set_context(*factory->null_value());
329  SetObjectPrototype(Handle<JSObject>(env->global_proxy()),
330  factory->null_value());
331  env->set_global_proxy(env->global());
332  env->global()->set_global_receiver(env->global());
333 }
334 
335 
337  Handle<Object> global_object) {
338  ASSERT(global_object->IsJSGlobalProxy());
339  Handle<JSGlobalProxy> global = Handle<JSGlobalProxy>::cast(global_object);
340  env->global()->set_global_receiver(*global);
341  env->set_global_proxy(*global);
342  SetObjectPrototype(global, Handle<JSObject>(env->global()));
343  global->set_context(*env);
344 }
345 
346 
347 static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
348  const char* name,
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 Handle<DescriptorArray> Genesis::ComputeFunctionInstanceDescriptor(
385  PrototypePropertyMode prototypeMode) {
386  int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
387  Handle<DescriptorArray> descriptors(factory()->NewDescriptorArray(size));
388  PropertyAttributes attribs = static_cast<PropertyAttributes>(
390 
391  DescriptorArray::WhitenessWitness witness(*descriptors);
392 
393  { // Add length.
394  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionLength));
395  CallbacksDescriptor d(*factory()->length_symbol(), *f, attribs);
396  descriptors->Set(0, &d, witness);
397  }
398  { // Add name.
399  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionName));
400  CallbacksDescriptor d(*factory()->name_symbol(), *f, attribs);
401  descriptors->Set(1, &d, witness);
402  }
403  { // Add arguments.
404  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionArguments));
405  CallbacksDescriptor d(*factory()->arguments_symbol(), *f, attribs);
406  descriptors->Set(2, &d, witness);
407  }
408  { // Add caller.
409  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionCaller));
410  CallbacksDescriptor d(*factory()->caller_symbol(), *f, attribs);
411  descriptors->Set(3, &d, witness);
412  }
413  if (prototypeMode != DONT_ADD_PROTOTYPE) {
414  // Add prototype.
415  if (prototypeMode == ADD_WRITEABLE_PROTOTYPE) {
416  attribs = static_cast<PropertyAttributes>(attribs & ~READ_ONLY);
417  }
418  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionPrototype));
419  CallbacksDescriptor d(*factory()->prototype_symbol(), *f, attribs);
420  descriptors->Set(4, &d, witness);
421  }
422  descriptors->Sort(witness);
423  return descriptors;
424 }
425 
426 
427 Handle<Map> Genesis::CreateFunctionMap(PrototypePropertyMode prototype_mode) {
428  Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
429  Handle<DescriptorArray> descriptors =
430  ComputeFunctionInstanceDescriptor(prototype_mode);
431  map->set_instance_descriptors(*descriptors);
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  global_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  global_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  global_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  global_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  global_context()->set_initial_object_prototype(*prototype);
486  SetPrototype(object_fun, prototype);
487  object_function_map->set_instance_descriptors(
488  heap->empty_descriptor_array());
489  }
490 
491  // Allocate the empty function as the prototype for function ECMAScript
492  // 262 15.3.4.
493  Handle<String> symbol = factory->LookupAsciiSymbol("Empty");
494  Handle<JSFunction> empty_function =
495  factory->NewFunctionWithoutPrototype(symbol, CLASSIC_MODE);
496 
497  // --- E m p t y ---
498  Handle<Code> code =
499  Handle<Code>(isolate->builtins()->builtin(
500  Builtins::kEmptyFunction));
501  empty_function->set_code(*code);
502  empty_function->shared()->set_code(*code);
503  Handle<String> source = factory->NewStringFromAscii(CStrVector("() {}"));
504  Handle<Script> script = factory->NewScript(source);
505  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
506  empty_function->shared()->set_script(*script);
507  empty_function->shared()->set_start_position(0);
508  empty_function->shared()->set_end_position(source->length());
509  empty_function->shared()->DontAdaptArguments();
510 
511  // Set prototypes for the function maps.
512  global_context()->function_map()->set_prototype(*empty_function);
513  global_context()->function_instance_map()->set_prototype(*empty_function);
514  global_context()->function_without_prototype_map()->
515  set_prototype(*empty_function);
516  function_instance_map_writable_prototype_->set_prototype(*empty_function);
517 
518  // Allocate the function map first and then patch the prototype later
519  Handle<Map> empty_function_map = CreateFunctionMap(DONT_ADD_PROTOTYPE);
520  empty_function_map->set_prototype(
521  global_context()->object_function()->prototype());
522  empty_function->set_map(*empty_function_map);
523  return empty_function;
524 }
525 
526 
527 Handle<DescriptorArray> Genesis::ComputeStrictFunctionInstanceDescriptor(
528  PrototypePropertyMode prototypeMode) {
529  int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
530  Handle<DescriptorArray> descriptors(factory()->NewDescriptorArray(size));
531  PropertyAttributes attribs = static_cast<PropertyAttributes>(
533 
534  DescriptorArray::WhitenessWitness witness(*descriptors);
535 
536  { // Add length.
537  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionLength));
538  CallbacksDescriptor d(*factory()->length_symbol(), *f, attribs);
539  descriptors->Set(0, &d, witness);
540  }
541  { // Add name.
542  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionName));
543  CallbacksDescriptor d(*factory()->name_symbol(), *f, attribs);
544  descriptors->Set(1, &d, witness);
545  }
546  { // Add arguments.
547  Handle<AccessorPair> arguments(factory()->NewAccessorPair());
548  CallbacksDescriptor d(*factory()->arguments_symbol(), *arguments, attribs);
549  descriptors->Set(2, &d, witness);
550  }
551  { // Add caller.
552  Handle<AccessorPair> caller(factory()->NewAccessorPair());
553  CallbacksDescriptor d(*factory()->caller_symbol(), *caller, attribs);
554  descriptors->Set(3, &d, witness);
555  }
556 
557  if (prototypeMode != DONT_ADD_PROTOTYPE) {
558  // Add prototype.
559  if (prototypeMode != ADD_WRITEABLE_PROTOTYPE) {
560  attribs = static_cast<PropertyAttributes>(attribs | READ_ONLY);
561  }
562  Handle<Foreign> f(factory()->NewForeign(&Accessors::FunctionPrototype));
563  CallbacksDescriptor d(*factory()->prototype_symbol(), *f, attribs);
564  descriptors->Set(4, &d, witness);
565  }
566 
567  descriptors->Sort(witness);
568  return descriptors;
569 }
570 
571 
572 // ECMAScript 5th Edition, 13.2.3
573 Handle<JSFunction> Genesis::GetThrowTypeErrorFunction() {
574  if (throw_type_error_function.is_null()) {
575  Handle<String> name = factory()->LookupAsciiSymbol("ThrowTypeError");
576  throw_type_error_function =
577  factory()->NewFunctionWithoutPrototype(name, CLASSIC_MODE);
578  Handle<Code> code(isolate()->builtins()->builtin(
579  Builtins::kStrictModePoisonPill));
580  throw_type_error_function->set_map(
581  global_context()->function_map());
582  throw_type_error_function->set_code(*code);
583  throw_type_error_function->shared()->set_code(*code);
584  throw_type_error_function->shared()->DontAdaptArguments();
585 
586  JSObject::PreventExtensions(throw_type_error_function);
587  }
588  return throw_type_error_function;
589 }
590 
591 
592 Handle<Map> Genesis::CreateStrictModeFunctionMap(
593  PrototypePropertyMode prototype_mode,
594  Handle<JSFunction> empty_function) {
595  Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
596  Handle<DescriptorArray> descriptors =
597  ComputeStrictFunctionInstanceDescriptor(prototype_mode);
598  map->set_instance_descriptors(*descriptors);
599  map->set_function_with_prototype(prototype_mode != DONT_ADD_PROTOTYPE);
600  map->set_prototype(*empty_function);
601  return map;
602 }
603 
604 
605 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
606  // Allocate map for the strict mode function instances.
607  Handle<Map> strict_mode_function_instance_map =
608  CreateStrictModeFunctionMap(ADD_WRITEABLE_PROTOTYPE, empty);
609  global_context()->set_strict_mode_function_instance_map(
610  *strict_mode_function_instance_map);
611 
612  // Allocate map for the prototype-less strict mode instances.
613  Handle<Map> strict_mode_function_without_prototype_map =
614  CreateStrictModeFunctionMap(DONT_ADD_PROTOTYPE, empty);
615  global_context()->set_strict_mode_function_without_prototype_map(
616  *strict_mode_function_without_prototype_map);
617 
618  // Allocate map for the strict mode functions. This map is temporary, used
619  // only for processing of builtins.
620  // Later the map is replaced with writable prototype map, allocated below.
621  Handle<Map> strict_mode_function_map =
622  CreateStrictModeFunctionMap(ADD_READONLY_PROTOTYPE, empty);
623  global_context()->set_strict_mode_function_map(
624  *strict_mode_function_map);
625 
626  // The final map for the strict mode functions. Writeable prototype.
627  // This map is installed in MakeFunctionInstancePrototypeWritable.
628  strict_mode_function_instance_map_writable_prototype_ =
629  CreateStrictModeFunctionMap(ADD_WRITEABLE_PROTOTYPE, empty);
630 
631  // Complete the callbacks.
632  PoisonArgumentsAndCaller(strict_mode_function_instance_map);
633  PoisonArgumentsAndCaller(strict_mode_function_without_prototype_map);
634  PoisonArgumentsAndCaller(strict_mode_function_map);
635  PoisonArgumentsAndCaller(
636  strict_mode_function_instance_map_writable_prototype_);
637 }
638 
639 
640 static void SetAccessors(Handle<Map> map,
641  Handle<String> name,
642  Handle<JSFunction> func) {
643  DescriptorArray* descs = map->instance_descriptors();
644  int number = descs->Search(*name);
645  AccessorPair* accessors = AccessorPair::cast(descs->GetValue(number));
646  accessors->set_getter(*func);
647  accessors->set_setter(*func);
648 }
649 
650 
651 void Genesis::PoisonArgumentsAndCaller(Handle<Map> map) {
652  SetAccessors(map, factory()->arguments_symbol(), GetThrowTypeErrorFunction());
653  SetAccessors(map, factory()->caller_symbol(), GetThrowTypeErrorFunction());
654 }
655 
656 
657 static void AddToWeakGlobalContextList(Context* context) {
658  ASSERT(context->IsGlobalContext());
659  Heap* heap = context->GetIsolate()->heap();
660 #ifdef DEBUG
661  { // NOLINT
662  ASSERT(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
663  // Check that context is not in the list yet.
664  for (Object* current = heap->global_contexts_list();
665  !current->IsUndefined();
666  current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
667  ASSERT(current != context);
668  }
669  }
670 #endif
671  context->set(Context::NEXT_CONTEXT_LINK, heap->global_contexts_list());
672  heap->set_global_contexts_list(context);
673 }
674 
675 
676 void Genesis::CreateRoots() {
677  // Allocate the global context FixedArray first and then patch the
678  // closure and extension object later (we need the empty function
679  // and the global object, but in order to create those, we need the
680  // global context).
681  global_context_ = Handle<Context>::cast(isolate()->global_handles()->Create(
682  *factory()->NewGlobalContext()));
683  AddToWeakGlobalContextList(*global_context_);
684  isolate()->set_context(*global_context());
685 
686  // Allocate the message listeners object.
687  {
688  v8::NeanderArray listeners;
689  global_context()->set_message_listeners(*listeners.value());
690  }
691 }
692 
693 
694 Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
695  v8::Handle<v8::ObjectTemplate> global_template,
696  Handle<Object> global_object,
697  Handle<GlobalObject>* inner_global_out) {
698  // The argument global_template aka data is an ObjectTemplateInfo.
699  // It has a constructor pointer that points at global_constructor which is a
700  // FunctionTemplateInfo.
701  // The global_constructor is used to create or reinitialize the global_proxy.
702  // The global_constructor also has a prototype_template pointer that points at
703  // js_global_template which is an ObjectTemplateInfo.
704  // That in turn has a constructor pointer that points at
705  // js_global_constructor which is a FunctionTemplateInfo.
706  // js_global_constructor is used to make js_global_function
707  // js_global_function is used to make the new inner_global.
708  //
709  // --- G l o b a l ---
710  // Step 1: Create a fresh inner JSGlobalObject.
711  Handle<JSFunction> js_global_function;
712  Handle<ObjectTemplateInfo> js_global_template;
713  if (!global_template.IsEmpty()) {
714  // Get prototype template of the global_template.
715  Handle<ObjectTemplateInfo> data =
716  v8::Utils::OpenHandle(*global_template);
717  Handle<FunctionTemplateInfo> global_constructor =
718  Handle<FunctionTemplateInfo>(
719  FunctionTemplateInfo::cast(data->constructor()));
720  Handle<Object> proto_template(global_constructor->prototype_template());
721  if (!proto_template->IsUndefined()) {
722  js_global_template =
723  Handle<ObjectTemplateInfo>::cast(proto_template);
724  }
725  }
726 
727  if (js_global_template.is_null()) {
728  Handle<String> name = Handle<String>(heap()->empty_symbol());
729  Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
730  Builtins::kIllegal));
731  js_global_function =
732  factory()->NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
733  JSGlobalObject::kSize, code, true);
734  // Change the constructor property of the prototype of the
735  // hidden global function to refer to the Object function.
736  Handle<JSObject> prototype =
737  Handle<JSObject>(
738  JSObject::cast(js_global_function->instance_prototype()));
739  CHECK_NOT_EMPTY_HANDLE(isolate(),
741  prototype, factory()->constructor_symbol(),
742  isolate()->object_function(), NONE));
743  } else {
744  Handle<FunctionTemplateInfo> js_global_constructor(
745  FunctionTemplateInfo::cast(js_global_template->constructor()));
746  js_global_function =
747  factory()->CreateApiFunction(js_global_constructor,
748  factory()->InnerGlobalObject);
749  }
750 
751  js_global_function->initial_map()->set_is_hidden_prototype();
752  Handle<GlobalObject> inner_global =
753  factory()->NewGlobalObject(js_global_function);
754  if (inner_global_out != NULL) {
755  *inner_global_out = inner_global;
756  }
757 
758  // Step 2: create or re-initialize the global proxy object.
759  Handle<JSFunction> global_proxy_function;
760  if (global_template.IsEmpty()) {
761  Handle<String> name = Handle<String>(heap()->empty_symbol());
762  Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
763  Builtins::kIllegal));
764  global_proxy_function =
765  factory()->NewFunction(name, JS_GLOBAL_PROXY_TYPE,
766  JSGlobalProxy::kSize, code, true);
767  } else {
768  Handle<ObjectTemplateInfo> data =
769  v8::Utils::OpenHandle(*global_template);
770  Handle<FunctionTemplateInfo> global_constructor(
771  FunctionTemplateInfo::cast(data->constructor()));
772  global_proxy_function =
773  factory()->CreateApiFunction(global_constructor,
774  factory()->OuterGlobalObject);
775  }
776 
777  Handle<String> global_name = factory()->LookupAsciiSymbol("global");
778  global_proxy_function->shared()->set_instance_class_name(*global_name);
779  global_proxy_function->initial_map()->set_is_access_check_needed(true);
780 
781  // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
782  // Return the global proxy.
783 
784  if (global_object.location() != NULL) {
785  ASSERT(global_object->IsJSGlobalProxy());
787  global_proxy_function,
788  Handle<JSGlobalProxy>::cast(global_object));
789  } else {
791  factory()->NewJSObject(global_proxy_function, TENURED));
792  }
793 }
794 
795 
796 void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
797  Handle<JSGlobalProxy> global_proxy) {
798  // Set the global context for the global object.
799  inner_global->set_global_context(*global_context());
800  inner_global->set_global_receiver(*global_proxy);
801  global_proxy->set_context(*global_context());
802  global_context()->set_global_proxy(*global_proxy);
803 }
804 
805 
806 void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
807  Handle<GlobalObject> inner_global_from_snapshot(
808  GlobalObject::cast(global_context_->extension()));
809  Handle<JSBuiltinsObject> builtins_global(global_context_->builtins());
810  global_context_->set_extension(*inner_global);
811  global_context_->set_global(*inner_global);
812  global_context_->set_security_token(*inner_global);
813  static const PropertyAttributes attributes =
814  static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
815  ForceSetProperty(builtins_global,
816  factory()->LookupAsciiSymbol("global"),
817  inner_global,
818  attributes);
819  // Set up the reference from the global object to the builtins object.
820  JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
821  TransferNamedProperties(inner_global_from_snapshot, inner_global);
822  TransferIndexedProperties(inner_global_from_snapshot, inner_global);
823 }
824 
825 
826 // This is only called if we are not using snapshots. The equivalent
827 // work in the snapshot case is done in HookUpInnerGlobal.
828 bool Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
829  Handle<JSFunction> empty_function) {
830  // --- G l o b a l C o n t e x t ---
831  // Use the empty function as closure (no scope info).
832  global_context()->set_closure(*empty_function);
833  global_context()->set_previous(NULL);
834  // Set extension and global object.
835  global_context()->set_extension(*inner_global);
836  global_context()->set_global(*inner_global);
837  // Security setup: Set the security token of the global object to
838  // its the inner global. This makes the security check between two
839  // different contexts fail by default even in case of global
840  // object reinitialization.
841  global_context()->set_security_token(*inner_global);
842 
843  Isolate* isolate = inner_global->GetIsolate();
844  Factory* factory = isolate->factory();
845  Heap* heap = isolate->heap();
846 
847  Handle<String> object_name = Handle<String>(heap->Object_symbol());
848  CHECK_NOT_EMPTY_HANDLE(isolate,
850  inner_global, object_name,
851  isolate->object_function(), DONT_ENUM));
852 
853  Handle<JSObject> global = Handle<JSObject>(global_context()->global());
854 
855  // Install global Function object
856  InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
857  empty_function, Builtins::kIllegal, true); // ECMA native.
858 
859  { // --- A r r a y ---
860  Handle<JSFunction> array_function =
861  InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
862  isolate->initial_object_prototype(),
863  Builtins::kArrayCode, true);
864  array_function->shared()->set_construct_stub(
865  isolate->builtins()->builtin(Builtins::kArrayConstructCode));
866  array_function->shared()->DontAdaptArguments();
867 
868  // This seems a bit hackish, but we need to make sure Array.length
869  // is 1.
870  array_function->shared()->set_length(1);
871  Handle<DescriptorArray> array_descriptors =
872  factory->CopyAppendForeignDescriptor(
873  factory->empty_descriptor_array(),
874  factory->length_symbol(),
875  factory->NewForeign(&Accessors::ArrayLength),
876  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
877 
878  // array_function is used internally. JS code creating array object should
879  // search for the 'Array' property on the global object and use that one
880  // as the constructor. 'Array' property on a global object can be
881  // overwritten by JS code.
882  global_context()->set_array_function(*array_function);
883  array_function->initial_map()->set_instance_descriptors(*array_descriptors);
884  }
885 
886  { // --- N u m b e r ---
887  Handle<JSFunction> number_fun =
888  InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
889  isolate->initial_object_prototype(),
890  Builtins::kIllegal, true);
891  global_context()->set_number_function(*number_fun);
892  }
893 
894  { // --- B o o l e a n ---
895  Handle<JSFunction> boolean_fun =
896  InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
897  isolate->initial_object_prototype(),
898  Builtins::kIllegal, true);
899  global_context()->set_boolean_function(*boolean_fun);
900  }
901 
902  { // --- S t r i n g ---
903  Handle<JSFunction> string_fun =
904  InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
905  isolate->initial_object_prototype(),
906  Builtins::kIllegal, true);
907  string_fun->shared()->set_construct_stub(
908  isolate->builtins()->builtin(Builtins::kStringConstructCode));
909  global_context()->set_string_function(*string_fun);
910  // Add 'length' property to strings.
911  Handle<DescriptorArray> string_descriptors =
912  factory->CopyAppendForeignDescriptor(
913  factory->empty_descriptor_array(),
914  factory->length_symbol(),
915  factory->NewForeign(&Accessors::StringLength),
916  static_cast<PropertyAttributes>(DONT_ENUM |
917  DONT_DELETE |
918  READ_ONLY));
919 
920  Handle<Map> string_map =
921  Handle<Map>(global_context()->string_function()->initial_map());
922  string_map->set_instance_descriptors(*string_descriptors);
923  }
924 
925  { // --- D a t e ---
926  // Builtin functions for Date.prototype.
927  Handle<JSFunction> date_fun =
928  InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize,
929  isolate->initial_object_prototype(),
930  Builtins::kIllegal, true);
931 
932  global_context()->set_date_function(*date_fun);
933  }
934 
935 
936  { // -- R e g E x p
937  // Builtin functions for RegExp.prototype.
938  Handle<JSFunction> regexp_fun =
939  InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
940  isolate->initial_object_prototype(),
941  Builtins::kIllegal, true);
942  global_context()->set_regexp_function(*regexp_fun);
943 
944  ASSERT(regexp_fun->has_initial_map());
945  Handle<Map> initial_map(regexp_fun->initial_map());
946 
947  ASSERT_EQ(0, initial_map->inobject_properties());
948 
949  Handle<DescriptorArray> descriptors = factory->NewDescriptorArray(5);
950  DescriptorArray::WhitenessWitness witness(*descriptors);
951  PropertyAttributes final =
953  int enum_index = 0;
954  {
955  // ECMA-262, section 15.10.7.1.
956  FieldDescriptor field(heap->source_symbol(),
958  final,
959  enum_index++);
960  descriptors->Set(0, &field, witness);
961  }
962  {
963  // ECMA-262, section 15.10.7.2.
964  FieldDescriptor field(heap->global_symbol(),
966  final,
967  enum_index++);
968  descriptors->Set(1, &field, witness);
969  }
970  {
971  // ECMA-262, section 15.10.7.3.
972  FieldDescriptor field(heap->ignore_case_symbol(),
974  final,
975  enum_index++);
976  descriptors->Set(2, &field, witness);
977  }
978  {
979  // ECMA-262, section 15.10.7.4.
980  FieldDescriptor field(heap->multiline_symbol(),
982  final,
983  enum_index++);
984  descriptors->Set(3, &field, witness);
985  }
986  {
987  // ECMA-262, section 15.10.7.5.
988  PropertyAttributes writable =
989  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
990  FieldDescriptor field(heap->last_index_symbol(),
992  writable,
993  enum_index++);
994  descriptors->Set(4, &field, witness);
995  }
996  descriptors->SetNextEnumerationIndex(enum_index);
997  descriptors->Sort(witness);
998 
999  initial_map->set_inobject_properties(5);
1000  initial_map->set_pre_allocated_property_fields(5);
1001  initial_map->set_unused_property_fields(0);
1002  initial_map->set_instance_size(
1003  initial_map->instance_size() + 5 * kPointerSize);
1004  initial_map->set_instance_descriptors(*descriptors);
1005  initial_map->set_visitor_id(StaticVisitorBase::GetVisitorId(*initial_map));
1006 
1007  // RegExp prototype object is itself a RegExp.
1008  Handle<Map> proto_map = factory->CopyMapDropTransitions(initial_map);
1009  proto_map->set_prototype(global_context()->initial_object_prototype());
1010  Handle<JSObject> proto = factory->NewJSObjectFromMap(proto_map);
1011  proto->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex,
1012  heap->query_colon_symbol());
1013  proto->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex,
1014  heap->false_value());
1015  proto->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex,
1016  heap->false_value());
1017  proto->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex,
1018  heap->false_value());
1019  proto->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
1020  Smi::FromInt(0),
1021  SKIP_WRITE_BARRIER); // It's a Smi.
1022  initial_map->set_prototype(*proto);
1023  factory->SetRegExpIrregexpData(Handle<JSRegExp>::cast(proto),
1024  JSRegExp::IRREGEXP, factory->empty_string(),
1025  JSRegExp::Flags(0), 0);
1026  }
1027 
1028  { // -- J S O N
1029  Handle<String> name = factory->NewStringFromAscii(CStrVector("JSON"));
1030  Handle<JSFunction> cons = factory->NewFunction(name,
1031  factory->the_hole_value());
1032  { MaybeObject* result = cons->SetInstancePrototype(
1033  global_context()->initial_object_prototype());
1034  if (result->IsFailure()) return false;
1035  }
1036  cons->SetInstanceClassName(*name);
1037  Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1038  ASSERT(json_object->IsJSObject());
1039  CHECK_NOT_EMPTY_HANDLE(isolate,
1041  global, name, json_object, DONT_ENUM));
1042  global_context()->set_json_object(*json_object);
1043  }
1044 
1045  { // --- arguments_boilerplate_
1046  // Make sure we can recognize argument objects at runtime.
1047  // This is done by introducing an anonymous function with
1048  // class_name equals 'Arguments'.
1049  Handle<String> symbol = factory->LookupAsciiSymbol("Arguments");
1050  Handle<Code> code = Handle<Code>(
1051  isolate->builtins()->builtin(Builtins::kIllegal));
1052  Handle<JSObject> prototype =
1053  Handle<JSObject>(
1054  JSObject::cast(global_context()->object_function()->prototype()));
1055 
1056  Handle<JSFunction> function =
1057  factory->NewFunctionWithPrototype(symbol,
1060  prototype,
1061  code,
1062  false);
1063  ASSERT(!function->has_initial_map());
1064  function->shared()->set_instance_class_name(*symbol);
1065  function->shared()->set_expected_nof_properties(2);
1066  Handle<JSObject> result = factory->NewJSObject(function);
1067 
1068  global_context()->set_arguments_boilerplate(*result);
1069  // Note: length must be added as the first property and
1070  // callee must be added as the second property.
1071  CHECK_NOT_EMPTY_HANDLE(isolate,
1073  result, factory->length_symbol(),
1074  factory->undefined_value(), DONT_ENUM));
1075  CHECK_NOT_EMPTY_HANDLE(isolate,
1077  result, factory->callee_symbol(),
1078  factory->undefined_value(), DONT_ENUM));
1079 
1080 #ifdef DEBUG
1081  LookupResult lookup(isolate);
1082  result->LocalLookup(heap->callee_symbol(), &lookup);
1083  ASSERT(lookup.IsFound() && (lookup.type() == FIELD));
1084  ASSERT(lookup.GetFieldIndex() == Heap::kArgumentsCalleeIndex);
1085 
1086  result->LocalLookup(heap->length_symbol(), &lookup);
1087  ASSERT(lookup.IsFound() && (lookup.type() == FIELD));
1088  ASSERT(lookup.GetFieldIndex() == Heap::kArgumentsLengthIndex);
1089 
1090  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsCalleeIndex);
1091  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1092 
1093  // Check the state of the object.
1094  ASSERT(result->HasFastProperties());
1095  ASSERT(result->HasFastObjectElements());
1096 #endif
1097  }
1098 
1099  { // --- aliased_arguments_boilerplate_
1100  // Set up a well-formed parameter map to make assertions happy.
1101  Handle<FixedArray> elements = factory->NewFixedArray(2);
1102  elements->set_map(heap->non_strict_arguments_elements_map());
1103  Handle<FixedArray> array;
1104  array = factory->NewFixedArray(0);
1105  elements->set(0, *array);
1106  array = factory->NewFixedArray(0);
1107  elements->set(1, *array);
1108 
1109  Handle<Map> old_map(global_context()->arguments_boilerplate()->map());
1110  Handle<Map> new_map = factory->CopyMapDropTransitions(old_map);
1111  new_map->set_pre_allocated_property_fields(2);
1112  Handle<JSObject> result = factory->NewJSObjectFromMap(new_map);
1113  // Set elements kind after allocating the object because
1114  // NewJSObjectFromMap assumes a fast elements map.
1115  new_map->set_elements_kind(NON_STRICT_ARGUMENTS_ELEMENTS);
1116  result->set_elements(*elements);
1117  ASSERT(result->HasNonStrictArgumentsElements());
1118  global_context()->set_aliased_arguments_boilerplate(*result);
1119  }
1120 
1121  { // --- strict mode arguments boilerplate
1122  const PropertyAttributes attributes =
1124 
1125  // Create the ThrowTypeError functions.
1126  Handle<AccessorPair> callee = factory->NewAccessorPair();
1127  Handle<AccessorPair> caller = factory->NewAccessorPair();
1128 
1129  Handle<JSFunction> throw_function =
1130  GetThrowTypeErrorFunction();
1131 
1132  // Install the ThrowTypeError functions.
1133  callee->set_getter(*throw_function);
1134  callee->set_setter(*throw_function);
1135  caller->set_getter(*throw_function);
1136  caller->set_setter(*throw_function);
1137 
1138  // Create the descriptor array for the arguments object.
1139  Handle<DescriptorArray> descriptors = factory->NewDescriptorArray(3);
1140  DescriptorArray::WhitenessWitness witness(*descriptors);
1141  { // length
1142  FieldDescriptor d(*factory->length_symbol(), 0, DONT_ENUM);
1143  descriptors->Set(0, &d, witness);
1144  }
1145  { // callee
1146  CallbacksDescriptor d(*factory->callee_symbol(), *callee, attributes);
1147  descriptors->Set(1, &d, witness);
1148  }
1149  { // caller
1150  CallbacksDescriptor d(*factory->caller_symbol(), *caller, attributes);
1151  descriptors->Set(2, &d, witness);
1152  }
1153  descriptors->Sort(witness);
1154 
1155  // Create the map. Allocate one in-object field for length.
1156  Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE,
1158  map->set_instance_descriptors(*descriptors);
1159  map->set_function_with_prototype(true);
1160  map->set_prototype(global_context()->object_function()->prototype());
1161  map->set_pre_allocated_property_fields(1);
1162  map->set_inobject_properties(1);
1163 
1164  // Copy constructor from the non-strict arguments boilerplate.
1165  map->set_constructor(
1166  global_context()->arguments_boilerplate()->map()->constructor());
1167 
1168  // Allocate the arguments boilerplate object.
1169  Handle<JSObject> result = factory->NewJSObjectFromMap(map);
1170  global_context()->set_strict_mode_arguments_boilerplate(*result);
1171 
1172  // Add length property only for strict mode boilerplate.
1173  CHECK_NOT_EMPTY_HANDLE(isolate,
1175  result, factory->length_symbol(),
1176  factory->undefined_value(), DONT_ENUM));
1177 
1178 #ifdef DEBUG
1179  LookupResult lookup(isolate);
1180  result->LocalLookup(heap->length_symbol(), &lookup);
1181  ASSERT(lookup.IsFound() && (lookup.type() == FIELD));
1182  ASSERT(lookup.GetFieldIndex() == Heap::kArgumentsLengthIndex);
1183 
1184  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1185 
1186  // Check the state of the object.
1187  ASSERT(result->HasFastProperties());
1188  ASSERT(result->HasFastObjectElements());
1189 #endif
1190  }
1191 
1192  { // --- context extension
1193  // Create a function for the context extension objects.
1194  Handle<Code> code = Handle<Code>(
1195  isolate->builtins()->builtin(Builtins::kIllegal));
1196  Handle<JSFunction> context_extension_fun =
1197  factory->NewFunction(factory->empty_symbol(),
1200  code,
1201  true);
1202 
1203  Handle<String> name = factory->LookupAsciiSymbol("context_extension");
1204  context_extension_fun->shared()->set_instance_class_name(*name);
1205  global_context()->set_context_extension_function(*context_extension_fun);
1206  }
1207 
1208 
1209  {
1210  // Set up the call-as-function delegate.
1211  Handle<Code> code =
1212  Handle<Code>(isolate->builtins()->builtin(
1213  Builtins::kHandleApiCallAsFunction));
1214  Handle<JSFunction> delegate =
1215  factory->NewFunction(factory->empty_symbol(), JS_OBJECT_TYPE,
1216  JSObject::kHeaderSize, code, true);
1217  global_context()->set_call_as_function_delegate(*delegate);
1218  delegate->shared()->DontAdaptArguments();
1219  }
1220 
1221  {
1222  // Set up the call-as-constructor delegate.
1223  Handle<Code> code =
1224  Handle<Code>(isolate->builtins()->builtin(
1225  Builtins::kHandleApiCallAsConstructor));
1226  Handle<JSFunction> delegate =
1227  factory->NewFunction(factory->empty_symbol(), JS_OBJECT_TYPE,
1228  JSObject::kHeaderSize, code, true);
1229  global_context()->set_call_as_constructor_delegate(*delegate);
1230  delegate->shared()->DontAdaptArguments();
1231  }
1232 
1233  // Initialize the out of memory slot.
1234  global_context()->set_out_of_memory(heap->false_value());
1235 
1236  // Initialize the data slot.
1237  global_context()->set_data(heap->undefined_value());
1238 
1239  {
1240  // Initialize the random seed slot.
1241  Handle<ByteArray> zeroed_byte_array(
1242  factory->NewByteArray(kRandomStateSize));
1243  global_context()->set_random_seed(*zeroed_byte_array);
1244  memset(zeroed_byte_array->GetDataStartAddress(), 0, kRandomStateSize);
1245  }
1246  return true;
1247 }
1248 
1249 
1250 void Genesis::InitializeExperimentalGlobal() {
1251  Handle<JSObject> global = Handle<JSObject>(global_context()->global());
1252 
1253  // TODO(mstarzinger): Move this into Genesis::InitializeGlobal once we no
1254  // longer need to live behind a flag, so functions get added to the snapshot.
1255  if (FLAG_harmony_collections) {
1256  { // -- S e t
1257  Handle<JSObject> prototype =
1258  factory()->NewJSObject(isolate()->object_function(), TENURED);
1259  InstallFunction(global, "Set", JS_SET_TYPE, JSSet::kSize,
1260  prototype, Builtins::kIllegal, true);
1261  }
1262  { // -- M a p
1263  Handle<JSObject> prototype =
1264  factory()->NewJSObject(isolate()->object_function(), TENURED);
1265  InstallFunction(global, "Map", JS_MAP_TYPE, JSMap::kSize,
1266  prototype, Builtins::kIllegal, true);
1267  }
1268  { // -- W e a k M a p
1269  Handle<JSObject> prototype =
1270  factory()->NewJSObject(isolate()->object_function(), TENURED);
1271  InstallFunction(global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
1272  prototype, Builtins::kIllegal, true);
1273  }
1274  }
1275 }
1276 
1277 
1278 bool Genesis::CompileBuiltin(Isolate* isolate, int index) {
1279  Vector<const char> name = Natives::GetScriptName(index);
1280  Handle<String> source_code =
1281  isolate->bootstrapper()->NativesSourceLookup(index);
1282  return CompileNative(name, source_code);
1283 }
1284 
1285 
1286 bool Genesis::CompileExperimentalBuiltin(Isolate* isolate, int index) {
1287  Vector<const char> name = ExperimentalNatives::GetScriptName(index);
1288  Factory* factory = isolate->factory();
1289  Handle<String> source_code =
1290  factory->NewStringFromAscii(
1292  return CompileNative(name, source_code);
1293 }
1294 
1295 
1296 bool Genesis::CompileNative(Vector<const char> name, Handle<String> source) {
1297  HandleScope scope;
1298  Isolate* isolate = source->GetIsolate();
1299 #ifdef ENABLE_DEBUGGER_SUPPORT
1300  isolate->debugger()->set_compiling_natives(true);
1301 #endif
1302  // During genesis, the boilerplate for stack overflow won't work until the
1303  // environment has been at least partially initialized. Add a stack check
1304  // before entering JS code to catch overflow early.
1305  StackLimitCheck check(Isolate::Current());
1306  if (check.HasOverflowed()) return false;
1307 
1308  bool result = CompileScriptCached(name,
1309  source,
1310  NULL,
1311  NULL,
1312  Handle<Context>(isolate->context()),
1313  true);
1314  ASSERT(isolate->has_pending_exception() != result);
1315  if (!result) isolate->clear_pending_exception();
1316 #ifdef ENABLE_DEBUGGER_SUPPORT
1317  isolate->debugger()->set_compiling_natives(false);
1318 #endif
1319  return result;
1320 }
1321 
1322 
1323 bool Genesis::CompileScriptCached(Vector<const char> name,
1324  Handle<String> source,
1325  SourceCodeCache* cache,
1326  v8::Extension* extension,
1327  Handle<Context> top_context,
1328  bool use_runtime_context) {
1329  Factory* factory = source->GetIsolate()->factory();
1330  HandleScope scope;
1331  Handle<SharedFunctionInfo> function_info;
1332 
1333  // If we can't find the function in the cache, we compile a new
1334  // function and insert it into the cache.
1335  if (cache == NULL || !cache->Lookup(name, &function_info)) {
1336  ASSERT(source->IsAsciiRepresentation());
1337  Handle<String> script_name = factory->NewStringFromUtf8(name);
1338  function_info = Compiler::Compile(
1339  source,
1340  script_name,
1341  0,
1342  0,
1343  extension,
1344  NULL,
1346  use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
1347  if (function_info.is_null()) return false;
1348  if (cache != NULL) cache->Add(name, function_info);
1349  }
1350 
1351  // Set up the function context. Conceptually, we should clone the
1352  // function before overwriting the context but since we're in a
1353  // single-threaded environment it is not strictly necessary.
1354  ASSERT(top_context->IsGlobalContext());
1355  Handle<Context> context =
1356  Handle<Context>(use_runtime_context
1357  ? Handle<Context>(top_context->runtime_context())
1358  : top_context);
1359  Handle<JSFunction> fun =
1360  factory->NewFunctionFromSharedFunctionInfo(function_info, context);
1361 
1362  // Call function using either the runtime object or the global
1363  // object as the receiver. Provide no parameters.
1364  Handle<Object> receiver =
1365  Handle<Object>(use_runtime_context
1366  ? top_context->builtins()
1367  : top_context->global());
1368  bool has_pending_exception;
1369  Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1370  if (has_pending_exception) return false;
1371  return true;
1372 }
1373 
1374 
1375 #define INSTALL_NATIVE(Type, name, var) \
1376  Handle<String> var##_name = factory()->LookupAsciiSymbol(name); \
1377  Object* var##_native = \
1378  global_context()->builtins()->GetPropertyNoExceptionThrown( \
1379  *var##_name); \
1380  global_context()->set_##var(Type::cast(var##_native));
1381 
1382 
1383 void Genesis::InstallNativeFunctions() {
1384  HandleScope scope;
1385  INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1386  INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1387  INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1388  INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1389  INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1390  INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1391  INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1392  INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
1393  INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
1394  INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1395  INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1396  configure_instance_fun);
1397  INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1398  INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1399  INSTALL_NATIVE(JSFunction, "ToCompletePropertyDescriptor",
1400  to_complete_property_descriptor);
1401 }
1402 
1403 void Genesis::InstallExperimentalNativeFunctions() {
1404  if (FLAG_harmony_proxies) {
1405  INSTALL_NATIVE(JSFunction, "DerivedHasTrap", derived_has_trap);
1406  INSTALL_NATIVE(JSFunction, "DerivedGetTrap", derived_get_trap);
1407  INSTALL_NATIVE(JSFunction, "DerivedSetTrap", derived_set_trap);
1408  INSTALL_NATIVE(JSFunction, "ProxyEnumerate", proxy_enumerate);
1409  }
1410 }
1411 
1412 #undef INSTALL_NATIVE
1413 
1414 
1415 bool Genesis::InstallNatives() {
1416  HandleScope scope;
1417 
1418  // Create a function for the builtins object. Allocate space for the
1419  // JavaScript builtins, a reference to the builtins object
1420  // (itself) and a reference to the global_context directly in the object.
1421  Handle<Code> code = Handle<Code>(
1422  isolate()->builtins()->builtin(Builtins::kIllegal));
1423  Handle<JSFunction> builtins_fun =
1424  factory()->NewFunction(factory()->empty_symbol(),
1426  JSBuiltinsObject::kSize, code, true);
1427 
1428  Handle<String> name = factory()->LookupAsciiSymbol("builtins");
1429  builtins_fun->shared()->set_instance_class_name(*name);
1430 
1431  // Allocate the builtins object.
1432  Handle<JSBuiltinsObject> builtins =
1433  Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
1434  builtins->set_builtins(*builtins);
1435  builtins->set_global_context(*global_context());
1436  builtins->set_global_receiver(*builtins);
1437 
1438  // Set up the 'global' properties of the builtins object. The
1439  // 'global' property that refers to the global object is the only
1440  // way to get from code running in the builtins context to the
1441  // global object.
1442  static const PropertyAttributes attributes =
1443  static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1444  Handle<String> global_symbol = factory()->LookupAsciiSymbol("global");
1445  Handle<Object> global_obj(global_context()->global());
1446  CHECK_NOT_EMPTY_HANDLE(isolate(),
1448  builtins, global_symbol, global_obj, attributes));
1449 
1450  // Set up the reference from the global object to the builtins object.
1451  JSGlobalObject::cast(global_context()->global())->set_builtins(*builtins);
1452 
1453  // Create a bridge function that has context in the global context.
1454  Handle<JSFunction> bridge =
1455  factory()->NewFunction(factory()->empty_symbol(),
1456  factory()->undefined_value());
1457  ASSERT(bridge->context() == *isolate()->global_context());
1458 
1459  // Allocate the builtins context.
1460  Handle<Context> context =
1461  factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1462  context->set_global(*builtins); // override builtins global object
1463 
1464  global_context()->set_runtime_context(*context);
1465 
1466  { // -- S c r i p t
1467  // Builtin functions for Script.
1468  Handle<JSFunction> script_fun =
1469  InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1470  isolate()->initial_object_prototype(),
1471  Builtins::kIllegal, false);
1472  Handle<JSObject> prototype =
1473  factory()->NewJSObject(isolate()->object_function(), TENURED);
1474  SetPrototype(script_fun, prototype);
1475  global_context()->set_script_function(*script_fun);
1476 
1477  // Add 'source' and 'data' property to scripts.
1478  PropertyAttributes common_attributes =
1480  Handle<Foreign> foreign_source =
1481  factory()->NewForeign(&Accessors::ScriptSource);
1482  Handle<DescriptorArray> script_descriptors =
1483  factory()->CopyAppendForeignDescriptor(
1484  factory()->empty_descriptor_array(),
1485  factory()->LookupAsciiSymbol("source"),
1486  foreign_source,
1487  common_attributes);
1488  Handle<Foreign> foreign_name =
1489  factory()->NewForeign(&Accessors::ScriptName);
1490  script_descriptors =
1491  factory()->CopyAppendForeignDescriptor(
1492  script_descriptors,
1493  factory()->LookupAsciiSymbol("name"),
1494  foreign_name,
1495  common_attributes);
1496  Handle<Foreign> foreign_id = factory()->NewForeign(&Accessors::ScriptId);
1497  script_descriptors =
1498  factory()->CopyAppendForeignDescriptor(
1499  script_descriptors,
1500  factory()->LookupAsciiSymbol("id"),
1501  foreign_id,
1502  common_attributes);
1503  Handle<Foreign> foreign_line_offset =
1504  factory()->NewForeign(&Accessors::ScriptLineOffset);
1505  script_descriptors =
1506  factory()->CopyAppendForeignDescriptor(
1507  script_descriptors,
1508  factory()->LookupAsciiSymbol("line_offset"),
1509  foreign_line_offset,
1510  common_attributes);
1511  Handle<Foreign> foreign_column_offset =
1512  factory()->NewForeign(&Accessors::ScriptColumnOffset);
1513  script_descriptors =
1514  factory()->CopyAppendForeignDescriptor(
1515  script_descriptors,
1516  factory()->LookupAsciiSymbol("column_offset"),
1517  foreign_column_offset,
1518  common_attributes);
1519  Handle<Foreign> foreign_data =
1520  factory()->NewForeign(&Accessors::ScriptData);
1521  script_descriptors =
1522  factory()->CopyAppendForeignDescriptor(
1523  script_descriptors,
1524  factory()->LookupAsciiSymbol("data"),
1525  foreign_data,
1526  common_attributes);
1527  Handle<Foreign> foreign_type =
1528  factory()->NewForeign(&Accessors::ScriptType);
1529  script_descriptors =
1530  factory()->CopyAppendForeignDescriptor(
1531  script_descriptors,
1532  factory()->LookupAsciiSymbol("type"),
1533  foreign_type,
1534  common_attributes);
1535  Handle<Foreign> foreign_compilation_type =
1536  factory()->NewForeign(&Accessors::ScriptCompilationType);
1537  script_descriptors =
1538  factory()->CopyAppendForeignDescriptor(
1539  script_descriptors,
1540  factory()->LookupAsciiSymbol("compilation_type"),
1541  foreign_compilation_type,
1542  common_attributes);
1543  Handle<Foreign> foreign_line_ends =
1544  factory()->NewForeign(&Accessors::ScriptLineEnds);
1545  script_descriptors =
1546  factory()->CopyAppendForeignDescriptor(
1547  script_descriptors,
1548  factory()->LookupAsciiSymbol("line_ends"),
1549  foreign_line_ends,
1550  common_attributes);
1551  Handle<Foreign> foreign_context_data =
1552  factory()->NewForeign(&Accessors::ScriptContextData);
1553  script_descriptors =
1554  factory()->CopyAppendForeignDescriptor(
1555  script_descriptors,
1556  factory()->LookupAsciiSymbol("context_data"),
1557  foreign_context_data,
1558  common_attributes);
1559  Handle<Foreign> foreign_eval_from_script =
1560  factory()->NewForeign(&Accessors::ScriptEvalFromScript);
1561  script_descriptors =
1562  factory()->CopyAppendForeignDescriptor(
1563  script_descriptors,
1564  factory()->LookupAsciiSymbol("eval_from_script"),
1565  foreign_eval_from_script,
1566  common_attributes);
1567  Handle<Foreign> foreign_eval_from_script_position =
1568  factory()->NewForeign(&Accessors::ScriptEvalFromScriptPosition);
1569  script_descriptors =
1570  factory()->CopyAppendForeignDescriptor(
1571  script_descriptors,
1572  factory()->LookupAsciiSymbol("eval_from_script_position"),
1573  foreign_eval_from_script_position,
1574  common_attributes);
1575  Handle<Foreign> foreign_eval_from_function_name =
1576  factory()->NewForeign(&Accessors::ScriptEvalFromFunctionName);
1577  script_descriptors =
1578  factory()->CopyAppendForeignDescriptor(
1579  script_descriptors,
1580  factory()->LookupAsciiSymbol("eval_from_function_name"),
1581  foreign_eval_from_function_name,
1582  common_attributes);
1583 
1584  Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1585  script_map->set_instance_descriptors(*script_descriptors);
1586 
1587  // Allocate the empty script.
1588  Handle<Script> script = factory()->NewScript(factory()->empty_string());
1589  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
1590  heap()->public_set_empty_script(*script);
1591  }
1592  {
1593  // Builtin function for OpaqueReference -- a JSValue-based object,
1594  // that keeps its field isolated from JavaScript code. It may store
1595  // objects, that JavaScript code may not access.
1596  Handle<JSFunction> opaque_reference_fun =
1597  InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1599  isolate()->initial_object_prototype(),
1600  Builtins::kIllegal, false);
1601  Handle<JSObject> prototype =
1602  factory()->NewJSObject(isolate()->object_function(), TENURED);
1603  SetPrototype(opaque_reference_fun, prototype);
1604  global_context()->set_opaque_reference_function(*opaque_reference_fun);
1605  }
1606 
1607  { // --- I n t e r n a l A r r a y ---
1608  // An array constructor on the builtins object that works like
1609  // the public Array constructor, except that its prototype
1610  // doesn't inherit from Object.prototype.
1611  // To be used only for internal work by builtins. Instances
1612  // must not be leaked to user code.
1613  Handle<JSFunction> array_function =
1614  InstallFunction(builtins,
1615  "InternalArray",
1616  JS_ARRAY_TYPE,
1618  isolate()->initial_object_prototype(),
1619  Builtins::kInternalArrayCode,
1620  true);
1621  Handle<JSObject> prototype =
1622  factory()->NewJSObject(isolate()->object_function(), TENURED);
1623  SetPrototype(array_function, prototype);
1624 
1625  array_function->shared()->set_construct_stub(
1626  isolate()->builtins()->builtin(Builtins::kArrayConstructCode));
1627  array_function->shared()->DontAdaptArguments();
1628 
1629  // InternalArrays should not use Smi-Only array optimizations. There are too
1630  // many places in the C++ runtime code (e.g. RegEx) that assume that
1631  // elements in InternalArrays can be set to non-Smi values without going
1632  // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
1633  // transition easy to trap. Moreover, they rarely are smi-only.
1634  MaybeObject* maybe_map =
1635  array_function->initial_map()->CopyDropTransitions(
1637  Map* new_map;
1638  if (!maybe_map->To(&new_map)) return false;
1639  new_map->set_elements_kind(FAST_HOLEY_ELEMENTS);
1640  array_function->set_initial_map(new_map);
1641 
1642  // Make "length" magic on instances.
1643  Handle<DescriptorArray> array_descriptors =
1644  factory()->CopyAppendForeignDescriptor(
1645  factory()->empty_descriptor_array(),
1646  factory()->length_symbol(),
1647  factory()->NewForeign(&Accessors::ArrayLength),
1648  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE));
1649 
1650  array_function->initial_map()->set_instance_descriptors(
1651  *array_descriptors);
1652 
1653  global_context()->set_internal_array_function(*array_function);
1654  }
1655 
1656  if (FLAG_disable_native_files) {
1657  PrintF("Warning: Running without installed natives!\n");
1658  return true;
1659  }
1660 
1661  // Install natives.
1662  for (int i = Natives::GetDebuggerCount();
1664  i++) {
1665  if (!CompileBuiltin(isolate(), i)) return false;
1666  // TODO(ager): We really only need to install the JS builtin
1667  // functions on the builtins object after compiling and running
1668  // runtime.js.
1669  if (!InstallJSBuiltins(builtins)) return false;
1670  }
1671 
1672  InstallNativeFunctions();
1673 
1674  // Store the map for the string prototype after the natives has been compiled
1675  // and the String function has been set up.
1676  Handle<JSFunction> string_function(global_context()->string_function());
1678  string_function->initial_map()->prototype())->HasFastProperties());
1679  global_context()->set_string_function_prototype_map(
1680  HeapObject::cast(string_function->initial_map()->prototype())->map());
1681 
1682  // Install Function.prototype.call and apply.
1683  { Handle<String> key = factory()->function_class_symbol();
1684  Handle<JSFunction> function =
1685  Handle<JSFunction>::cast(GetProperty(isolate()->global(), key));
1686  Handle<JSObject> proto =
1687  Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1688 
1689  // Install the call and the apply functions.
1690  Handle<JSFunction> call =
1691  InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1692  Handle<JSObject>::null(),
1693  Builtins::kFunctionCall,
1694  false);
1695  Handle<JSFunction> apply =
1696  InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1697  Handle<JSObject>::null(),
1698  Builtins::kFunctionApply,
1699  false);
1700 
1701  // Make sure that Function.prototype.call appears to be compiled.
1702  // The code will never be called, but inline caching for call will
1703  // only work if it appears to be compiled.
1704  call->shared()->DontAdaptArguments();
1705  ASSERT(call->is_compiled());
1706 
1707  // Set the expected parameters for apply to 2; required by builtin.
1708  apply->shared()->set_formal_parameter_count(2);
1709 
1710  // Set the lengths for the functions to satisfy ECMA-262.
1711  call->shared()->set_length(1);
1712  apply->shared()->set_length(2);
1713  }
1714 
1715  InstallBuiltinFunctionIds();
1716 
1717  // Create a constructor for RegExp results (a variant of Array that
1718  // predefines the two properties index and match).
1719  {
1720  // RegExpResult initial map.
1721 
1722  // Find global.Array.prototype to inherit from.
1723  Handle<JSFunction> array_constructor(global_context()->array_function());
1724  Handle<JSObject> array_prototype(
1725  JSObject::cast(array_constructor->instance_prototype()));
1726 
1727  // Add initial map.
1728  Handle<Map> initial_map =
1729  factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1730  initial_map->set_constructor(*array_constructor);
1731 
1732  // Set prototype on map.
1733  initial_map->set_non_instance_prototype(false);
1734  initial_map->set_prototype(*array_prototype);
1735 
1736  // Update map with length accessor from Array and add "index" and "input".
1737  Handle<DescriptorArray> reresult_descriptors =
1738  factory()->NewDescriptorArray(3);
1739  DescriptorArray::WhitenessWitness witness(*reresult_descriptors);
1740 
1741  JSFunction* array_function = global_context()->array_function();
1742  Handle<DescriptorArray> array_descriptors(
1743  array_function->initial_map()->instance_descriptors());
1744  int index = array_descriptors->SearchWithCache(heap()->length_symbol());
1745  MaybeObject* copy_result =
1746  reresult_descriptors->CopyFrom(0, *array_descriptors, index, witness);
1747  if (copy_result->IsFailure()) return false;
1748 
1749  int enum_index = 0;
1750  {
1751  FieldDescriptor index_field(heap()->index_symbol(),
1753  NONE,
1754  enum_index++);
1755  reresult_descriptors->Set(1, &index_field, witness);
1756  }
1757 
1758  {
1759  FieldDescriptor input_field(heap()->input_symbol(),
1761  NONE,
1762  enum_index++);
1763  reresult_descriptors->Set(2, &input_field, witness);
1764  }
1765  reresult_descriptors->Sort(witness);
1766 
1767  initial_map->set_inobject_properties(2);
1768  initial_map->set_pre_allocated_property_fields(2);
1769  initial_map->set_unused_property_fields(0);
1770  initial_map->set_instance_descriptors(*reresult_descriptors);
1771 
1772  global_context()->set_regexp_result_map(*initial_map);
1773  }
1774 
1775 #ifdef DEBUG
1776  builtins->Verify();
1777 #endif
1778 
1779  return true;
1780 }
1781 
1782 
1783 bool Genesis::InstallExperimentalNatives() {
1786  i++) {
1787  if (FLAG_harmony_proxies &&
1788  strcmp(ExperimentalNatives::GetScriptName(i).start(),
1789  "native proxy.js") == 0) {
1790  if (!CompileExperimentalBuiltin(isolate(), i)) return false;
1791  }
1792  if (FLAG_harmony_collections &&
1793  strcmp(ExperimentalNatives::GetScriptName(i).start(),
1794  "native collection.js") == 0) {
1795  if (!CompileExperimentalBuiltin(isolate(), i)) return false;
1796  }
1797  }
1798 
1799  InstallExperimentalNativeFunctions();
1800 
1801  return true;
1802 }
1803 
1804 
1805 static Handle<JSObject> ResolveBuiltinIdHolder(
1806  Handle<Context> global_context,
1807  const char* holder_expr) {
1808  Factory* factory = global_context->GetIsolate()->factory();
1809  Handle<GlobalObject> global(global_context->global());
1810  const char* period_pos = strchr(holder_expr, '.');
1811  if (period_pos == NULL) {
1812  return Handle<JSObject>::cast(
1813  GetProperty(global, factory->LookupAsciiSymbol(holder_expr)));
1814  }
1815  ASSERT_EQ(".prototype", period_pos);
1816  Vector<const char> property(holder_expr,
1817  static_cast<int>(period_pos - holder_expr));
1818  Handle<JSFunction> function = Handle<JSFunction>::cast(
1819  GetProperty(global, factory->LookupSymbol(property)));
1820  return Handle<JSObject>(JSObject::cast(function->prototype()));
1821 }
1822 
1823 
1824 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
1825  const char* function_name,
1826  BuiltinFunctionId id) {
1827  Factory* factory = holder->GetIsolate()->factory();
1828  Handle<String> name = factory->LookupAsciiSymbol(function_name);
1829  Object* function_object = holder->GetProperty(*name)->ToObjectUnchecked();
1830  Handle<JSFunction> function(JSFunction::cast(function_object));
1831  function->shared()->set_function_data(Smi::FromInt(id));
1832 }
1833 
1834 
1835 void Genesis::InstallBuiltinFunctionIds() {
1836  HandleScope scope;
1837 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
1838  { \
1839  Handle<JSObject> holder = ResolveBuiltinIdHolder( \
1840  global_context(), #holder_expr); \
1841  BuiltinFunctionId id = k##name; \
1842  InstallBuiltinFunctionId(holder, #fun_name, id); \
1843  }
1845 #undef INSTALL_BUILTIN_ID
1846 }
1847 
1848 
1849 // Do not forget to update macros.py with named constant
1850 // of cache id.
1851 #define JSFUNCTION_RESULT_CACHE_LIST(F) \
1852  F(16, global_context()->regexp_function())
1853 
1854 
1855 static FixedArray* CreateCache(int size, Handle<JSFunction> factory_function) {
1856  Factory* factory = factory_function->GetIsolate()->factory();
1857  // Caches are supposed to live for a long time, allocate in old space.
1858  int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
1859  // Cannot use cast as object is not fully initialized yet.
1860  JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
1861  *factory->NewFixedArrayWithHoles(array_size, TENURED));
1862  cache->set(JSFunctionResultCache::kFactoryIndex, *factory_function);
1863  cache->MakeZeroSize();
1864  return cache;
1865 }
1866 
1867 
1868 void Genesis::InstallJSFunctionResultCaches() {
1869  const int kNumberOfCaches = 0 +
1870 #define F(size, func) + 1
1872 #undef F
1873  ;
1874 
1875  Handle<FixedArray> caches = FACTORY->NewFixedArray(kNumberOfCaches, TENURED);
1876 
1877  int index = 0;
1878 
1879 #define F(size, func) do { \
1880  FixedArray* cache = CreateCache((size), Handle<JSFunction>(func)); \
1881  caches->set(index++, cache); \
1882  } while (false)
1883 
1885 
1886 #undef F
1887 
1888  global_context()->set_jsfunction_result_caches(*caches);
1889 }
1890 
1891 
1892 void Genesis::InitializeNormalizedMapCaches() {
1893  Handle<FixedArray> array(
1894  FACTORY->NewFixedArray(NormalizedMapCache::kEntries, TENURED));
1895  global_context()->set_normalized_map_cache(NormalizedMapCache::cast(*array));
1896 }
1897 
1898 
1900  v8::ExtensionConfiguration* extensions) {
1901  Isolate* isolate = global_context->GetIsolate();
1902  BootstrapperActive active;
1903  SaveContext saved_context(isolate);
1904  isolate->set_context(*global_context);
1905  if (!Genesis::InstallExtensions(global_context, extensions)) return false;
1906  Genesis::InstallSpecialObjects(global_context);
1907  return true;
1908 }
1909 
1910 
1911 void Genesis::InstallSpecialObjects(Handle<Context> global_context) {
1912  Isolate* isolate = global_context->GetIsolate();
1913  Factory* factory = isolate->factory();
1914  HandleScope scope;
1915  Handle<JSGlobalObject> global(JSGlobalObject::cast(global_context->global()));
1916  // Expose the natives in global if a name for it is specified.
1917  if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
1918  Handle<String> natives = factory->LookupAsciiSymbol(FLAG_expose_natives_as);
1919  CHECK_NOT_EMPTY_HANDLE(isolate,
1921  global, natives,
1922  Handle<JSObject>(global->builtins()),
1923  DONT_ENUM));
1924  }
1925 
1926  Handle<Object> Error = GetProperty(global, "Error");
1927  if (Error->IsJSObject()) {
1928  Handle<String> name = factory->LookupAsciiSymbol("stackTraceLimit");
1929  Handle<Smi> stack_trace_limit(Smi::FromInt(FLAG_stack_trace_limit));
1930  CHECK_NOT_EMPTY_HANDLE(isolate,
1932  Handle<JSObject>::cast(Error), name,
1933  stack_trace_limit, NONE));
1934  }
1935 
1936 #ifdef ENABLE_DEBUGGER_SUPPORT
1937  // Expose the debug global object in global if a name for it is specified.
1938  if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
1939  Debug* debug = Isolate::Current()->debug();
1940  // If loading fails we just bail out without installing the
1941  // debugger but without tanking the whole context.
1942  if (!debug->Load()) return;
1943  // Set the security token for the debugger context to the same as
1944  // the shell global context to allow calling between these (otherwise
1945  // exposing debug global object doesn't make much sense).
1946  debug->debug_context()->set_security_token(
1947  global_context->security_token());
1948 
1949  Handle<String> debug_string =
1950  factory->LookupAsciiSymbol(FLAG_expose_debug_as);
1951  Handle<Object> global_proxy(debug->debug_context()->global_proxy());
1952  CHECK_NOT_EMPTY_HANDLE(isolate,
1954  global, debug_string, global_proxy, DONT_ENUM));
1955  }
1956 #endif
1957 }
1958 
1959 static uint32_t Hash(RegisteredExtension* extension) {
1960  return v8::internal::ComputePointerHash(extension);
1961 }
1962 
1963 static bool MatchRegisteredExtensions(void* key1, void* key2) {
1964  return key1 == key2;
1965 }
1966 
1967 Genesis::ExtensionStates::ExtensionStates()
1968  : map_(MatchRegisteredExtensions, 8) { }
1969 
1970 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
1971  RegisteredExtension* extension) {
1972  i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension), false);
1973  if (entry == NULL) {
1974  return UNVISITED;
1975  }
1976  return static_cast<ExtensionTraversalState>(
1977  reinterpret_cast<intptr_t>(entry->value));
1978 }
1979 
1980 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
1981  ExtensionTraversalState state) {
1982  map_.Lookup(extension, Hash(extension), true)->value =
1983  reinterpret_cast<void*>(static_cast<intptr_t>(state));
1984 }
1985 
1986 bool Genesis::InstallExtensions(Handle<Context> global_context,
1987  v8::ExtensionConfiguration* extensions) {
1988  // TODO(isolates): Extensions on multiple isolates may take a little more
1989  // effort. (The external API reads 'ignore'-- does that mean
1990  // we can break the interface?)
1991 
1992 
1993  ExtensionStates extension_states; // All extensions have state UNVISITED.
1994  // Install auto extensions.
1996  while (current != NULL) {
1997  if (current->extension()->auto_enable())
1998  InstallExtension(current, &extension_states);
1999  current = current->next();
2000  }
2001 
2002  if (FLAG_expose_gc) InstallExtension("v8/gc", &extension_states);
2003  if (FLAG_expose_externalize_string) {
2004  InstallExtension("v8/externalize", &extension_states);
2005  }
2006 
2007  if (extensions == NULL) return true;
2008  // Install required extensions
2009  int count = v8::ImplementationUtilities::GetNameCount(extensions);
2010  const char** names = v8::ImplementationUtilities::GetNames(extensions);
2011  for (int i = 0; i < count; i++) {
2012  if (!InstallExtension(names[i], &extension_states))
2013  return false;
2014  }
2015 
2016  return true;
2017 }
2018 
2019 
2020 // Installs a named extension. This methods is unoptimized and does
2021 // not scale well if we want to support a large number of extensions.
2022 bool Genesis::InstallExtension(const char* name,
2023  ExtensionStates* extension_states) {
2025  // Loop until we find the relevant extension
2026  while (current != NULL) {
2027  if (strcmp(name, current->extension()->name()) == 0) break;
2028  current = current->next();
2029  }
2030  // Didn't find the extension; fail.
2031  if (current == NULL) {
2033  "v8::Context::New()", "Cannot find required extension");
2034  return false;
2035  }
2036  return InstallExtension(current, extension_states);
2037 }
2038 
2039 
2040 bool Genesis::InstallExtension(v8::RegisteredExtension* current,
2041  ExtensionStates* extension_states) {
2042  HandleScope scope;
2043 
2044  if (extension_states->get_state(current) == INSTALLED) return true;
2045  // The current node has already been visited so there must be a
2046  // cycle in the dependency graph; fail.
2047  if (extension_states->get_state(current) == VISITED) {
2049  "v8::Context::New()", "Circular extension dependency");
2050  return false;
2051  }
2052  ASSERT(extension_states->get_state(current) == UNVISITED);
2053  extension_states->set_state(current, VISITED);
2054  v8::Extension* extension = current->extension();
2055  // Install the extension's dependencies
2056  for (int i = 0; i < extension->dependency_count(); i++) {
2057  if (!InstallExtension(extension->dependencies()[i], extension_states))
2058  return false;
2059  }
2060  Isolate* isolate = Isolate::Current();
2061  Handle<String> source_code =
2062  isolate->factory()->NewExternalStringFromAscii(extension->source());
2063  bool result = CompileScriptCached(
2064  CStrVector(extension->name()),
2065  source_code,
2066  isolate->bootstrapper()->extensions_cache(),
2067  extension,
2068  Handle<Context>(isolate->context()),
2069  false);
2070  ASSERT(isolate->has_pending_exception() != result);
2071  if (!result) {
2072  // We print out the name of the extension that fail to install.
2073  // When an error is thrown during bootstrapping we automatically print
2074  // the line number at which this happened to the console in the isolate
2075  // error throwing functionality.
2076  OS::PrintError("Error installing extension '%s'.\n",
2077  current->extension()->name());
2078  isolate->clear_pending_exception();
2079  }
2080  extension_states->set_state(current, INSTALLED);
2081  isolate->NotifyExtensionInstalled();
2082  return result;
2083 }
2084 
2085 
2086 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2087  HandleScope scope;
2088  Factory* factory = builtins->GetIsolate()->factory();
2089  for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2090  Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2091  Handle<String> name = factory->LookupAsciiSymbol(Builtins::GetName(id));
2092  Object* function_object = builtins->GetPropertyNoExceptionThrown(*name);
2093  Handle<JSFunction> function
2094  = Handle<JSFunction>(JSFunction::cast(function_object));
2095  builtins->set_javascript_builtin(id, *function);
2096  if (!JSFunction::CompileLazy(function, CLEAR_EXCEPTION)) {
2097  return false;
2098  }
2099  builtins->set_javascript_builtin_code(id, function->shared()->code());
2100  }
2101  return true;
2102 }
2103 
2104 
2105 bool Genesis::ConfigureGlobalObjects(
2106  v8::Handle<v8::ObjectTemplate> global_proxy_template) {
2107  Handle<JSObject> global_proxy(
2108  JSObject::cast(global_context()->global_proxy()));
2109  Handle<JSObject> inner_global(JSObject::cast(global_context()->global()));
2110 
2111  if (!global_proxy_template.IsEmpty()) {
2112  // Configure the global proxy object.
2113  Handle<ObjectTemplateInfo> proxy_data =
2114  v8::Utils::OpenHandle(*global_proxy_template);
2115  if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
2116 
2117  // Configure the inner global object.
2118  Handle<FunctionTemplateInfo> proxy_constructor(
2119  FunctionTemplateInfo::cast(proxy_data->constructor()));
2120  if (!proxy_constructor->prototype_template()->IsUndefined()) {
2121  Handle<ObjectTemplateInfo> inner_data(
2122  ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2123  if (!ConfigureApiObject(inner_global, inner_data)) return false;
2124  }
2125  }
2126 
2127  SetObjectPrototype(global_proxy, inner_global);
2128  return true;
2129 }
2130 
2131 
2132 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
2133  Handle<ObjectTemplateInfo> object_template) {
2134  ASSERT(!object_template.is_null());
2135  ASSERT(object->IsInstanceOf(
2136  FunctionTemplateInfo::cast(object_template->constructor())));
2137 
2138  bool pending_exception = false;
2139  Handle<JSObject> obj =
2140  Execution::InstantiateObject(object_template, &pending_exception);
2141  if (pending_exception) {
2142  ASSERT(isolate()->has_pending_exception());
2143  isolate()->clear_pending_exception();
2144  return false;
2145  }
2146  TransferObject(obj, object);
2147  return true;
2148 }
2149 
2150 
2151 void Genesis::TransferNamedProperties(Handle<JSObject> from,
2152  Handle<JSObject> to) {
2153  if (from->HasFastProperties()) {
2154  Handle<DescriptorArray> descs =
2155  Handle<DescriptorArray>(from->map()->instance_descriptors());
2156  for (int i = 0; i < descs->number_of_descriptors(); i++) {
2157  PropertyDetails details = descs->GetDetails(i);
2158  switch (details.type()) {
2159  case FIELD: {
2160  HandleScope inner;
2161  Handle<String> key = Handle<String>(descs->GetKey(i));
2162  int index = descs->GetFieldIndex(i);
2163  Handle<Object> value = Handle<Object>(from->FastPropertyAt(index));
2164  CHECK_NOT_EMPTY_HANDLE(to->GetIsolate(),
2166  to, key, value, details.attributes()));
2167  break;
2168  }
2169  case CONSTANT_FUNCTION: {
2170  HandleScope inner;
2171  Handle<String> key = Handle<String>(descs->GetKey(i));
2172  Handle<JSFunction> fun =
2173  Handle<JSFunction>(descs->GetConstantFunction(i));
2174  CHECK_NOT_EMPTY_HANDLE(to->GetIsolate(),
2176  to, key, fun, details.attributes()));
2177  break;
2178  }
2179  case CALLBACKS: {
2180  LookupResult result(isolate());
2181  to->LocalLookup(descs->GetKey(i), &result);
2182  // If the property is already there we skip it
2183  if (result.IsProperty()) continue;
2184  HandleScope inner;
2185  ASSERT(!to->HasFastProperties());
2186  // Add to dictionary.
2187  Handle<String> key = Handle<String>(descs->GetKey(i));
2188  Handle<Object> callbacks(descs->GetCallbacksObject(i));
2189  PropertyDetails d =
2190  PropertyDetails(details.attributes(), CALLBACKS, details.index());
2191  JSObject::SetNormalizedProperty(to, key, callbacks, d);
2192  break;
2193  }
2194  case MAP_TRANSITION:
2195  case CONSTANT_TRANSITION:
2196  case NULL_DESCRIPTOR:
2197  // Ignore non-properties.
2198  break;
2199  case NORMAL:
2200  // Do not occur since the from object has fast properties.
2201  case HANDLER:
2202  case INTERCEPTOR:
2203  // No element in instance descriptors have proxy or interceptor type.
2204  UNREACHABLE();
2205  break;
2206  }
2207  }
2208  } else {
2209  Handle<StringDictionary> properties =
2210  Handle<StringDictionary>(from->property_dictionary());
2211  int capacity = properties->Capacity();
2212  for (int i = 0; i < capacity; i++) {
2213  Object* raw_key(properties->KeyAt(i));
2214  if (properties->IsKey(raw_key)) {
2215  ASSERT(raw_key->IsString());
2216  // If the property is already there we skip it.
2217  LookupResult result(isolate());
2218  to->LocalLookup(String::cast(raw_key), &result);
2219  if (result.IsProperty()) continue;
2220  // Set the property.
2221  Handle<String> key = Handle<String>(String::cast(raw_key));
2222  Handle<Object> value = Handle<Object>(properties->ValueAt(i));
2223  if (value->IsJSGlobalPropertyCell()) {
2224  value = Handle<Object>(JSGlobalPropertyCell::cast(*value)->value());
2225  }
2226  PropertyDetails details = properties->DetailsAt(i);
2227  CHECK_NOT_EMPTY_HANDLE(to->GetIsolate(),
2229  to, key, value, details.attributes()));
2230  }
2231  }
2232  }
2233 }
2234 
2235 
2236 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
2237  Handle<JSObject> to) {
2238  // Cloning the elements array is sufficient.
2239  Handle<FixedArray> from_elements =
2240  Handle<FixedArray>(FixedArray::cast(from->elements()));
2241  Handle<FixedArray> to_elements = FACTORY->CopyFixedArray(from_elements);
2242  to->set_elements(*to_elements);
2243 }
2244 
2245 
2246 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
2247  HandleScope outer;
2248  Factory* factory = from->GetIsolate()->factory();
2249 
2250  ASSERT(!from->IsJSArray());
2251  ASSERT(!to->IsJSArray());
2252 
2253  TransferNamedProperties(from, to);
2254  TransferIndexedProperties(from, to);
2255 
2256  // Transfer the prototype (new map is needed).
2257  Handle<Map> old_to_map = Handle<Map>(to->map());
2258  Handle<Map> new_to_map = factory->CopyMapDropTransitions(old_to_map);
2259  new_to_map->set_prototype(from->map()->prototype());
2260  to->set_map(*new_to_map);
2261 }
2262 
2263 
2264 void Genesis::MakeFunctionInstancePrototypeWritable() {
2265  // The maps with writable prototype are created in CreateEmptyFunction
2266  // and CreateStrictModeFunctionMaps respectively. Initially the maps are
2267  // created with read-only prototype for JS builtins processing.
2268  ASSERT(!function_instance_map_writable_prototype_.is_null());
2269  ASSERT(!strict_mode_function_instance_map_writable_prototype_.is_null());
2270 
2271  // Replace function instance maps to make prototype writable.
2272  global_context()->set_function_map(
2273  *function_instance_map_writable_prototype_);
2274  global_context()->set_strict_mode_function_map(
2275  *strict_mode_function_instance_map_writable_prototype_);
2276 }
2277 
2278 
2279 Genesis::Genesis(Isolate* isolate,
2280  Handle<Object> global_object,
2281  v8::Handle<v8::ObjectTemplate> global_template,
2282  v8::ExtensionConfiguration* extensions) : isolate_(isolate) {
2283  result_ = Handle<Context>::null();
2284  // If V8 isn't running and cannot be initialized, just return.
2285  if (!V8::IsRunning() && !V8::Initialize(NULL)) return;
2286 
2287  // Before creating the roots we must save the context and restore it
2288  // on all function exits.
2289  HandleScope scope;
2290  SaveContext saved_context(isolate);
2291 
2292  // During genesis, the boilerplate for stack overflow won't work until the
2293  // environment has been at least partially initialized. Add a stack check
2294  // before entering JS code to catch overflow early.
2295  StackLimitCheck check(Isolate::Current());
2296  if (check.HasOverflowed()) return;
2297 
2298  Handle<Context> new_context = Snapshot::NewContextFromSnapshot();
2299  if (!new_context.is_null()) {
2300  global_context_ =
2301  Handle<Context>::cast(isolate->global_handles()->Create(*new_context));
2302  AddToWeakGlobalContextList(*global_context_);
2303  isolate->set_context(*global_context_);
2304  isolate->counters()->contexts_created_by_snapshot()->Increment();
2305  Handle<GlobalObject> inner_global;
2306  Handle<JSGlobalProxy> global_proxy =
2307  CreateNewGlobals(global_template,
2308  global_object,
2309  &inner_global);
2310 
2311  HookUpGlobalProxy(inner_global, global_proxy);
2312  HookUpInnerGlobal(inner_global);
2313 
2314  if (!ConfigureGlobalObjects(global_template)) return;
2315  } else {
2316  // We get here if there was no context snapshot.
2317  CreateRoots();
2318  Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
2319  CreateStrictModeFunctionMaps(empty_function);
2320  Handle<GlobalObject> inner_global;
2321  Handle<JSGlobalProxy> global_proxy =
2322  CreateNewGlobals(global_template, global_object, &inner_global);
2323  HookUpGlobalProxy(inner_global, global_proxy);
2324  if (!InitializeGlobal(inner_global, empty_function)) return;
2325  InstallJSFunctionResultCaches();
2326  InitializeNormalizedMapCaches();
2327  if (!InstallNatives()) return;
2328 
2329  MakeFunctionInstancePrototypeWritable();
2330 
2331  if (!ConfigureGlobalObjects(global_template)) return;
2332  isolate->counters()->contexts_created_from_scratch()->Increment();
2333  }
2334 
2335  // Initialize experimental globals and install experimental natives.
2336  InitializeExperimentalGlobal();
2337  if (!InstallExperimentalNatives()) return;
2338 
2339  result_ = global_context_;
2340 }
2341 
2342 
2343 // Support for thread preemption.
2344 
2345 // Reserve space for statics needing saving and restoring.
2347  return sizeof(NestingCounterType);
2348 }
2349 
2350 
2351 // Archive statics that are thread local.
2353  *reinterpret_cast<NestingCounterType*>(to) = nesting_;
2354  nesting_ = 0;
2355  return to + sizeof(NestingCounterType);
2356 }
2357 
2358 
2359 // Restore statics that are thread local.
2360 char* Bootstrapper::RestoreState(char* from) {
2361  nesting_ = *reinterpret_cast<NestingCounterType*>(from);
2362  return from + sizeof(NestingCounterType);
2363 }
2364 
2365 
2366 // Called when the top-level V8 mutex is destroyed.
2368  ASSERT(!IsActive());
2369 }
2370 
2371 } } // namespace v8::internal
#define CHECK_NOT_EMPTY_HANDLE(isolate, call)
Definition: isolate.h:127
RegisteredExtension * next()
Definition: api.h:151
static bool Initialize(Deserializer *des)
Definition: v8.cc:64
Code * builtin(Name name)
Definition: builtins.h:312
static bool CompileLazy(Handle< JSFunction > function, ClearExceptionFlag flag)
Definition: objects.cc:7465
char * ArchiveState(char *to)
Handle< String > NewExternalStringFromAscii(const ExternalAsciiString::Resource *resource)
Definition: factory.cc:270
static const int kGlobalFieldIndex
Definition: objects.h:6483
void PrintF(const char *format,...)
Definition: v8utils.cc:40
void Initialize(bool create_heap_objects)
Definition: bootstrapper.cc:94
static const int kSize
Definition: objects.h:6151
char * AllocateAutoDeletedArray(int bytes)
static String * cast(Object *obj)
GlobalObject * global()
Definition: contexts.h:319
v8::internal::Handle< v8::internal::JSObject > value()
Definition: api.h:77
Handle< Context > result()
static Smi * FromInt(int value)
Definition: objects-inl.h:973
static ObjectTemplateInfo * cast(Object *obj)
static Vector< const char > GetRawScriptSource(int index)
value format" "after each garbage collection") DEFINE_bool(print_cumulative_gc_stat, false, "print cumulative GC statistics in name=value format on exit") DEFINE_bool(trace_gc_verbose, false, "print more details following each garbage collection") DEFINE_bool(trace_fragmentation, false, "report fragmentation for old pointer and data pages") DEFINE_bool(collect_maps, true, "garbage collect maps from which no objects can be reached") DEFINE_bool(flush_code, true, "flush code that we expect not to use again before full gc") DEFINE_bool(incremental_marking, true, "use incremental marking") DEFINE_bool(incremental_marking_steps, true, "do incremental marking steps") DEFINE_bool(trace_incremental_marking, false, "trace progress of the incremental marking") DEFINE_bool(use_idle_notification, true, "Use idle notification to reduce memory footprint.") DEFINE_bool(send_idle_notification, false, "Send idle notifcation between stress runs.") DEFINE_bool(use_ic, true, "use inline caching") DEFINE_bool(native_code_counters, false, "generate extra code for manipulating stats counters") DEFINE_bool(always_compact, false, "Perform compaction on every full GC") DEFINE_bool(lazy_sweeping, true, "Use lazy sweeping for old pointer and data spaces") DEFINE_bool(never_compact, false, "Never perform compaction on full GC-testing only") DEFINE_bool(compact_code_space, true, "Compact code space on full non-incremental collections") DEFINE_bool(cleanup_code_caches_at_gc, true, "Flush inline caches prior to mark compact collection and" "flush code caches in maps during mark compact cycle.") DEFINE_int(random_seed, 0, "Default seed for initializing random generator" "(0, the default, means to use system random).") DEFINE_bool(use_verbose_printer, true, "allows verbose printing") DEFINE_bool(allow_natives_syntax, false, "allow natives syntax") DEFINE_bool(trace_sim, false, "Trace simulator execution") DEFINE_bool(check_icache, false, "Check icache flushes in ARM and MIPS simulator") DEFINE_int(stop_sim_at, 0, "Simulator stop after x number of instructions") DEFINE_int(sim_stack_alignment, 8, "Stack alingment in bytes in simulator(4 or 8, 8 is default)") DEFINE_bool(trace_exception, false, "print stack trace when throwing exceptions") DEFINE_bool(preallocate_message_memory, false, "preallocate some memory to build stack traces.") DEFINE_bool(randomize_hashes, true, "randomize hashes to avoid predictable hash collisions" "(with snapshots this option cannot override the baked-in seed)") DEFINE_int(hash_seed, 0, "Fixed seed to use to hash property keys(0 means random)" "(with snapshots this option cannot override the baked-in seed)") DEFINE_bool(preemption, false, "activate a 100ms timer that switches between V8 threads") DEFINE_bool(regexp_optimization, true, "generate optimized regexp code") DEFINE_bool(testing_bool_flag, true, "testing_bool_flag") DEFINE_int(testing_int_flag, 13, "testing_int_flag") DEFINE_float(testing_float_flag, 2.5, "float-flag") DEFINE_string(testing_string_flag, "Hello, world!", "string-flag") DEFINE_int(testing_prng_seed, 42, "Seed used for threading test randomness") DEFINE_string(testing_serialization_file, "/tmp/serdes", "file in which to serialize heap") DEFINE_bool(help, false, "Print usage message, including flags, on console") DEFINE_bool(dump_counters, false, "Dump counters on exit") DEFINE_string(map_counters, "", "Map counters to a file") DEFINE_args(js_arguments, JSARGUMENTS_INIT, "Pass all remaining arguments to the script.Alias for\"--\".") DEFINE_bool(debug_compile_events, true,"Enable debugger compile events") DEFINE_bool(debug_script_collected_events, true,"Enable debugger script collected events") DEFINE_bool(gdbjit, false,"enable GDBJIT interface (disables compacting GC)") DEFINE_bool(gdbjit_full, false,"enable GDBJIT interface for all code objects") DEFINE_bool(gdbjit_dump, false,"dump elf objects with debug info to disk") DEFINE_string(gdbjit_dump_filter,"","dump only objects containing this substring") DEFINE_bool(force_marking_deque_overflows, false,"force overflows of marking deque by reducing it's size ""to 64 words") DEFINE_bool(stress_compaction, false,"stress the GC compactor to flush out bugs (implies ""--force_marking_deque_overflows)")#define FLAG DEFINE_bool(enable_slow_asserts, false,"enable asserts that are slow to execute") DEFINE_bool(trace_codegen, false,"print name of functions for which code is generated") DEFINE_bool(print_source, false,"pretty print source code") DEFINE_bool(print_builtin_source, false,"pretty print source code for builtins") DEFINE_bool(print_ast, false,"print source AST") DEFINE_bool(print_builtin_ast, false,"print source AST for builtins") DEFINE_string(stop_at,"","function name where to insert a breakpoint") DEFINE_bool(print_builtin_scopes, false,"print scopes for builtins") DEFINE_bool(print_scopes, false,"print scopes") DEFINE_bool(trace_contexts, false,"trace contexts operations") DEFINE_bool(gc_greedy, false,"perform GC prior to some allocations") DEFINE_bool(gc_verbose, false,"print stuff during garbage collection") DEFINE_bool(heap_stats, false,"report heap statistics before and after GC") DEFINE_bool(code_stats, false,"report code statistics after GC") DEFINE_bool(verify_heap, false,"verify heap pointers before and after GC") DEFINE_bool(print_handles, false,"report handles after GC") DEFINE_bool(print_global_handles, false,"report global handles after GC") DEFINE_bool(trace_ic, false,"trace inline cache state transitions") DEFINE_bool(print_interfaces, false,"print interfaces") DEFINE_bool(print_interface_details, false,"print interface inference details") DEFINE_int(print_interface_depth, 5,"depth for printing interfaces") DEFINE_bool(trace_normalization, false,"prints when objects are turned into dictionaries.") DEFINE_bool(trace_lazy, false,"trace lazy compilation") DEFINE_bool(collect_heap_spill_statistics, false,"report heap spill statistics along with heap_stats ""(requires heap_stats)") DEFINE_bool(trace_isolates, false,"trace isolate state changes") DEFINE_bool(log_state_changes, false,"Log state changes.") DEFINE_bool(regexp_possessive_quantifier, false,"enable possessive quantifier syntax for testing") DEFINE_bool(trace_regexp_bytecodes, false,"trace regexp bytecode execution") DEFINE_bool(trace_regexp_assembler, false,"trace regexp macro assembler calls.")#define FLAG DEFINE_bool(log, false,"Minimal logging (no API, code, GC, suspect, or handles samples).") DEFINE_bool(log_all, false,"Log all events to the log file.") DEFINE_bool(log_runtime, false,"Activate runtime system %Log call.") DEFINE_bool(log_api, false,"Log API events to the log file.") DEFINE_bool(log_code, false,"Log code events to the log file without profiling.") DEFINE_bool(log_gc, false,"Log heap samples on garbage collection for the hp2ps tool.") DEFINE_bool(log_handles, false,"Log global handle events.") DEFINE_bool(log_snapshot_positions, false,"log positions of (de)serialized objects in the snapshot.") DEFINE_bool(log_suspect, false,"Log suspect operations.") DEFINE_bool(prof, false,"Log statistical profiling information (implies --log-code).") DEFINE_bool(prof_auto, true,"Used with --prof, starts profiling automatically") DEFINE_bool(prof_lazy, false,"Used with --prof, only does sampling and logging"" when profiler is active (implies --noprof_auto).") DEFINE_bool(prof_browser_mode, true,"Used with --prof, turns on browser-compatible mode for profiling.") DEFINE_bool(log_regexp, false,"Log regular expression execution.") DEFINE_bool(sliding_state_window, false,"Update sliding state window counters.") DEFINE_string(logfile,"v8.log","Specify the name of the log file.") DEFINE_bool(ll_prof, false,"Enable low-level linux profiler.")#define FLAG DEFINE_bool(trace_elements_transitions, false,"trace elements transitions") DEFINE_bool(print_code_stubs, false,"print code stubs") DEFINE_bool(test_secondary_stub_cache, false,"test secondary stub cache by disabling the primary one") DEFINE_bool(test_primary_stub_cache, false,"test primary stub cache by disabling the secondary one") DEFINE_bool(print_code, false,"print generated code") DEFINE_bool(print_opt_code, false,"print optimized code") DEFINE_bool(print_unopt_code, false,"print unoptimized code before ""printing optimized code based on it") DEFINE_bool(print_code_verbose, false,"print more information for code") DEFINE_bool(print_builtin_code, false,"print generated code for builtins")#43"/Users/thlorenz/dev/dx/v8-perf/build/v8/src/flags.cc"2#define FLAG_MODE_DEFINE_DEFAULTS#1"/Users/thlorenz/dev/dx/v8-perf/build/v8/src/flag-definitions.h"1#define FLAG_FULL(ftype, ctype, nam, def, cmt)#define FLAG_READONLY(ftype, ctype, nam, def, cmt)#define DEFINE_implication(whenflag, thenflag)#define DEFINE_bool(nam, def, cmt)#define DEFINE_int(nam, def, cmt)#define DEFINE_float(nam, def, cmt)#define DEFINE_string(nam, def, cmt)#define DEFINE_args(nam, def, cmt)#define FLAG DEFINE_bool(use_strict, false,"enforce strict mode") DEFINE_bool(es5_readonly, false,"activate correct semantics for inheriting readonliness") DEFINE_bool(es52_globals, false,"activate new semantics for global var declarations") DEFINE_bool(harmony_typeof, false,"enable harmony semantics for typeof") DEFINE_bool(harmony_scoping, false,"enable harmony block scoping") DEFINE_bool(harmony_modules, false,"enable harmony modules (implies block scoping)") DEFINE_bool(harmony_proxies, false,"enable harmony proxies") DEFINE_bool(harmony_collections, false,"enable harmony collections (sets, maps, and weak maps)") DEFINE_bool(harmony, false,"enable all harmony features (except typeof)") DEFINE_implication(harmony, harmony_scoping) DEFINE_implication(harmony, harmony_modules) DEFINE_implication(harmony, harmony_proxies) DEFINE_implication(harmony, harmony_collections) DEFINE_implication(harmony_modules, harmony_scoping) DEFINE_bool(packed_arrays, false,"optimizes arrays that have no holes") DEFINE_bool(smi_only_arrays, true,"tracks arrays with only smi values") DEFINE_bool(clever_optimizations, true,"Optimize object size, Array shift, DOM strings and string +") DEFINE_bool(unbox_double_arrays, true,"automatically unbox arrays of doubles") DEFINE_bool(string_slices, true,"use string slices") DEFINE_bool(crankshaft, true,"use crankshaft") DEFINE_string(hydrogen_filter,"","optimization filter") DEFINE_bool(use_range, true,"use hydrogen range analysis") DEFINE_bool(eliminate_dead_phis, true,"eliminate dead phis") DEFINE_bool(use_gvn, true,"use hydrogen global value numbering") DEFINE_bool(use_canonicalizing, true,"use hydrogen instruction canonicalizing") DEFINE_bool(use_inlining, true,"use function inlining") DEFINE_int(max_inlined_source_size, 600,"maximum source size in bytes considered for a single inlining") DEFINE_int(max_inlined_nodes, 196,"maximum number of AST nodes considered for a single inlining") DEFINE_int(max_inlined_nodes_cumulative, 196,"maximum cumulative number of AST nodes considered for inlining") DEFINE_bool(loop_invariant_code_motion, true,"loop invariant code motion") DEFINE_bool(collect_megamorphic_maps_from_stub_cache, true,"crankshaft harvests type feedback from stub cache") DEFINE_bool(hydrogen_stats, false,"print statistics for hydrogen") DEFINE_bool(trace_hydrogen, false,"trace generated hydrogen to file") DEFINE_string(trace_phase,"Z","trace generated IR for specified phases") DEFINE_bool(trace_inlining, false,"trace inlining decisions") DEFINE_bool(trace_alloc, false,"trace register allocator") DEFINE_bool(trace_all_uses, false,"trace all use positions") DEFINE_bool(trace_range, false,"trace range analysis") DEFINE_bool(trace_gvn, false,"trace global value numbering") DEFINE_bool(trace_representation, false,"trace representation types") DEFINE_bool(stress_pointer_maps, false,"pointer map for every instruction") DEFINE_bool(stress_environments, false,"environment for every instruction") DEFINE_int(deopt_every_n_times, 0,"deoptimize every n times a deopt point is passed") DEFINE_bool(trap_on_deopt, false,"put a break point before deoptimizing") DEFINE_bool(deoptimize_uncommon_cases, true,"deoptimize uncommon cases") DEFINE_bool(polymorphic_inlining, true,"polymorphic inlining") DEFINE_bool(use_osr, true,"use on-stack replacement") DEFINE_bool(array_bounds_checks_elimination, false,"perform array bounds checks elimination") DEFINE_bool(array_index_dehoisting, false,"perform array index dehoisting") DEFINE_bool(trace_osr, false,"trace on-stack replacement") DEFINE_int(stress_runs, 0,"number of stress runs") DEFINE_bool(optimize_closures, true,"optimize closures") DEFINE_bool(inline_construct, true,"inline constructor calls") DEFINE_bool(inline_arguments, true,"inline functions with arguments object") DEFINE_int(loop_weight, 1,"loop weight for representation inference") DEFINE_bool(optimize_for_in, true,"optimize functions containing for-in loops") DEFINE_bool(experimental_profiler, true,"enable all profiler experiments") DEFINE_bool(watch_ic_patching, false,"profiler considers IC stability") DEFINE_int(frame_count, 1,"number of stack frames inspected by the profiler") DEFINE_bool(self_optimization, false,"primitive functions trigger their own optimization") DEFINE_bool(direct_self_opt, false,"call recompile stub directly when self-optimizing") DEFINE_bool(retry_self_opt, false,"re-try self-optimization if it failed") DEFINE_bool(count_based_interrupts, false,"trigger profiler ticks based on counting instead of timing") DEFINE_bool(interrupt_at_exit, false,"insert an interrupt check at function exit") DEFINE_bool(weighted_back_edges, false,"weight back edges by jump distance for interrupt triggering") DEFINE_int(interrupt_budget, 5900,"execution budget before interrupt is triggered") DEFINE_int(type_info_threshold, 15,"percentage of ICs that must have type info to allow optimization") DEFINE_int(self_opt_count, 130,"call count before self-optimization") DEFINE_implication(experimental_profiler, watch_ic_patching) DEFINE_implication(experimental_profiler, self_optimization) DEFINE_implication(experimental_profiler, retry_self_opt) DEFINE_implication(experimental_profiler, count_based_interrupts) DEFINE_implication(experimental_profiler, interrupt_at_exit) DEFINE_implication(experimental_profiler, weighted_back_edges) DEFINE_bool(trace_opt_verbose, false,"extra verbose compilation tracing") DEFINE_implication(trace_opt_verbose, trace_opt) DEFINE_bool(debug_code, false,"generate extra code (assertions) for debugging") DEFINE_bool(code_comments, false,"emit comments in code disassembly") DEFINE_bool(enable_sse2, true,"enable use of SSE2 instructions if available") DEFINE_bool(enable_sse3, true,"enable use of SSE3 instructions if available") DEFINE_bool(enable_sse4_1, true,"enable use of SSE4.1 instructions if available") DEFINE_bool(enable_cmov, true,"enable use of CMOV instruction if available") DEFINE_bool(enable_rdtsc, true,"enable use of RDTSC instruction if available") DEFINE_bool(enable_sahf, true,"enable use of SAHF instruction if available (X64 only)") DEFINE_bool(enable_vfp3, true,"enable use of VFP3 instructions if available - this implies ""enabling ARMv7 instructions (ARM only)") DEFINE_bool(enable_armv7, true,"enable use of ARMv7 instructions if available (ARM only)") DEFINE_bool(enable_fpu, true,"enable use of MIPS FPU instructions if available (MIPS only)") DEFINE_string(expose_natives_as, NULL,"expose natives in global object") DEFINE_string(expose_debug_as, NULL,"expose debug in global object") DEFINE_bool(expose_gc, false,"expose gc extension") DEFINE_bool(expose_externalize_string, false,"expose externalize string extension") DEFINE_int(stack_trace_limit, 10,"number of stack frames to capture") DEFINE_bool(builtins_in_stack_traces, false,"show built-in functions in stack traces") DEFINE_bool(disable_native_files, false,"disable builtin natives files") DEFINE_bool(inline_new, true,"use fast inline allocation") DEFINE_bool(stack_trace_on_abort, true,"print a stack trace if an assertion failure occurs") DEFINE_bool(trace, false,"trace function calls") DEFINE_bool(mask_constants_with_cookie, true,"use random jit cookie to mask large constants") DEFINE_bool(lazy, true,"use lazy compilation") DEFINE_bool(trace_opt, false,"trace lazy optimization") DEFINE_bool(trace_opt_stats, false,"trace lazy optimization statistics") DEFINE_bool(opt, true,"use adaptive optimizations") DEFINE_bool(always_opt, false,"always try to optimize functions") DEFINE_bool(prepare_always_opt, false,"prepare for turning on always opt") DEFINE_bool(trace_deopt, false,"trace deoptimization") DEFINE_int(min_preparse_length, 1024,"minimum length for automatic enable preparsing") DEFINE_bool(always_full_compiler, false,"try to use the dedicated run-once backend for all code") DEFINE_bool(trace_bailout, false,"print reasons for falling back to using the classic V8 backend") DEFINE_bool(compilation_cache, true,"enable compilation cache") DEFINE_bool(cache_prototype_transitions, true,"cache prototype transitions") DEFINE_bool(trace_debug_json, false,"trace debugging JSON request/response") DEFINE_bool(debugger_auto_break, true,"automatically set the debug break flag when debugger commands are ""in the queue") DEFINE_bool(enable_liveedit, true,"enable liveedit experimental feature") DEFINE_bool(break_on_abort, true,"always cause a debug break before aborting") DEFINE_int(stack_size, kPointerSize *123,"default size of stack region v8 is allowed to use (in kBytes)") DEFINE_int(max_stack_trace_source_length, 300,"maximum length of function source code printed in a stack trace.") DEFINE_bool(always_inline_smi_code, false,"always inline smi code in non-opt code") DEFINE_int(max_new_space_size, 0,"max size of the new generation (in kBytes)") DEFINE_int(max_old_space_size, 0,"max size of the old generation (in Mbytes)") DEFINE_int(max_executable_size, 0,"max size of executable memory (in Mbytes)") DEFINE_bool(gc_global, false,"always perform global GCs") DEFINE_int(gc_interval,-1,"garbage collect after <n> allocations") DEFINE_bool(trace_gc, false,"print one trace line following each garbage collection") DEFINE_bool(trace_gc_nvp, false,"print one detailed trace line in name=value format ""after each garbage collection") DEFINE_bool(print_cumulative_gc_stat, false,"print cumulative GC statistics in name=value format on exit") DEFINE_bool(trace_gc_verbose, false,"print more details following each garbage collection") DEFINE_bool(trace_fragmentation, false,"report fragmentation for old pointer and data pages") DEFINE_bool(collect_maps, true,"garbage collect maps from which no objects can be reached") DEFINE_bool(flush_code, true,"flush code that we expect not to use again before full gc") DEFINE_bool(incremental_marking, true,"use incremental marking") DEFINE_bool(incremental_marking_steps, true,"do incremental marking steps") DEFINE_bool(trace_incremental_marking, false,"trace progress of the incremental marking") DEFINE_bool(use_idle_notification, true,"Use idle notification to reduce memory footprint.") DEFINE_bool(send_idle_notification, false,"Send idle notifcation between stress runs.") DEFINE_bool(use_ic, true,"use inline caching") DEFINE_bool(native_code_counters, false,"generate extra code for manipulating stats counters") DEFINE_bool(always_compact, false,"Perform compaction on every full GC") DEFINE_bool(lazy_sweeping, true,"Use lazy sweeping for old pointer and data spaces") DEFINE_bool(never_compact, false,"Never perform compaction on full GC - testing only") DEFINE_bool(compact_code_space, true,"Compact code space on full non-incremental collections") DEFINE_bool(cleanup_code_caches_at_gc, true,"Flush inline caches prior to mark compact collection and ""flush code caches in maps during mark compact cycle.") DEFINE_int(random_seed, 0,"Default seed for initializing random generator ""(0, the default, means to use system random).") DEFINE_bool(use_verbose_printer, true,"allows verbose printing") DEFINE_bool(allow_natives_syntax, false,"allow natives syntax") DEFINE_bool(trace_sim, false,"Trace simulator execution") DEFINE_bool(check_icache, false,"Check icache flushes in ARM and MIPS simulator") DEFINE_int(stop_sim_at, 0,"Simulator stop after x number of instructions") DEFINE_int(sim_stack_alignment, 8,"Stack alingment in bytes in simulator (4 or 8, 8 is default)") DEFINE_bool(trace_exception, false,"print stack trace when throwing exceptions") DEFINE_bool(preallocate_message_memory, false,"preallocate some memory to build stack traces.") DEFINE_bool(randomize_hashes, true,"randomize hashes to avoid predictable hash collisions ""(with snapshots this option cannot override the baked-in seed)") DEFINE_int(hash_seed, 0,"Fixed seed to use to hash property keys (0 means random)""(with snapshots this option cannot override the baked-in seed)") DEFINE_bool(preemption, false,"activate a 100ms timer that switches between V8 threads") DEFINE_bool(regexp_optimization, true,"generate optimized regexp code") DEFINE_bool(testing_bool_flag, true,"testing_bool_flag") DEFINE_int(testing_int_flag, 13,"testing_int_flag") DEFINE_float(testing_float_flag, 2.5,"float-flag") DEFINE_string(testing_string_flag,"Hello, world!","string-flag") DEFINE_int(testing_prng_seed, 42,"Seed used for threading test randomness") DEFINE_string(testing_serialization_file,"/tmp/serdes","file in which to serialize heap") DEFINE_bool(help, false,"Print usage message, including flags, on console") DEFINE_bool(dump_counters, false,"Dump counters on exit") DEFINE_string(map_counters,"","Map counters to a file") DEFINE_args(js_arguments, JSARGUMENTS_INIT,"Pass all remaining arguments to the script. Alias for \"--\".") DEFINE_bool(debug_compile_events, true,"Enable debugger compile events") DEFINE_bool(debug_script_collected_events, true,"Enable debugger script collected events") DEFINE_bool(gdbjit, false,"enable GDBJIT interface (disables compacting GC)") DEFINE_bool(gdbjit_full, false,"enable GDBJIT interface for all code objects") DEFINE_bool(gdbjit_dump, false,"dump elf objects with debug info to disk") DEFINE_string(gdbjit_dump_filter,"","dump only objects containing this substring") DEFINE_bool(force_marking_deque_overflows, false,"force overflows of marking deque by reducing it's size ""to 64 words") DEFINE_bool(stress_compaction, false,"stress the GC compactor to flush out bugs (implies ""--force_marking_deque_overflows)")#define FLAG DEFINE_bool(enable_slow_asserts, false,"enable asserts that are slow to execute") DEFINE_bool(trace_codegen, false,"print name of functions for which code is generated") DEFINE_bool(print_source, false,"pretty print source code") DEFINE_bool(print_builtin_source, false,"pretty print source code for builtins") DEFINE_bool(print_ast, false,"print source AST") DEFINE_bool(print_builtin_ast, false,"print source AST for builtins") DEFINE_string(stop_at,"","function name where to insert a breakpoint") DEFINE_bool(print_builtin_scopes, false,"print scopes for builtins") DEFINE_bool(print_scopes, false,"print scopes") DEFINE_bool(trace_contexts, false,"trace contexts operations") DEFINE_bool(gc_greedy, false,"perform GC prior to some allocations") DEFINE_bool(gc_verbose, false,"print stuff during garbage collection") DEFINE_bool(heap_stats, false,"report heap statistics before and after GC") DEFINE_bool(code_stats, false,"report code statistics after GC") DEFINE_bool(verify_heap, false,"verify heap pointers before and after GC") DEFINE_bool(print_handles, false,"report handles after GC") DEFINE_bool(print_global_handles, false,"report global handles after GC") DEFINE_bool(trace_ic, false,"trace inline cache state transitions") DEFINE_bool(print_interfaces, false,"print interfaces") DEFINE_bool(print_interface_details, false,"print interface inference details") DEFINE_int(print_interface_depth, 5,"depth for printing interfaces") DEFINE_bool(trace_normalization, false,"prints when objects are turned into dictionaries.") DEFINE_bool(trace_lazy, false,"trace lazy compilation") DEFINE_bool(collect_heap_spill_statistics, false,"report heap spill statistics along with heap_stats ""(requires heap_stats)") DEFINE_bool(trace_isolates, false,"trace isolate state changes") DEFINE_bool(log_state_changes, false,"Log state changes.") DEFINE_bool(regexp_possessive_quantifier, false,"enable possessive quantifier syntax for testing") DEFINE_bool(trace_regexp_bytecodes, false,"trace regexp bytecode execution") DEFINE_bool(trace_regexp_assembler, false,"trace regexp macro assembler calls.")#define FLAG DEFINE_bool(log, false,"Minimal logging (no API, code, GC, suspect, or handles samples).") DEFINE_bool(log_all, false,"Log all events to the log file.") DEFINE_bool(log_runtime, false,"Activate runtime system %Log call.") DEFINE_bool(log_api, false,"Log API events to the log file.") DEFINE_bool(log_code, false,"Log code events to the log file without profiling.") DEFINE_bool(log_gc, false,"Log heap samples on garbage collection for the hp2ps tool.") DEFINE_bool(log_handles, false,"Log global handle events.") DEFINE_bool(log_snapshot_positions, false,"log positions of (de)serialized objects in the snapshot.") DEFINE_bool(log_suspect, false,"Log suspect operations.") DEFINE_bool(prof, false,"Log statistical profiling information (implies --log-code).") DEFINE_bool(prof_auto, true,"Used with --prof, starts profiling automatically") DEFINE_bool(prof_lazy, false,"Used with --prof, only does sampling and logging"" when profiler is active (implies --noprof_auto).") DEFINE_bool(prof_browser_mode, true,"Used with --prof, turns on browser-compatible mode for profiling.") DEFINE_bool(log_regexp, false,"Log regular expression execution.") DEFINE_bool(sliding_state_window, false,"Update sliding state window counters.") DEFINE_string(logfile,"v8.log","Specify the name of the log file.") DEFINE_bool(ll_prof, false,"Enable low-level linux profiler.")#define FLAG DEFINE_bool(trace_elements_transitions, false,"trace elements transitions") DEFINE_bool(print_code_stubs, false,"print code stubs") DEFINE_bool(test_secondary_stub_cache, false,"test secondary stub cache by disabling the primary one") DEFINE_bool(test_primary_stub_cache, false,"test primary stub cache by disabling the secondary one") DEFINE_bool(print_code, false,"print generated code") DEFINE_bool(print_opt_code, false,"print optimized code") DEFINE_bool(print_unopt_code, false,"print unoptimized code before ""printing optimized code based on it") DEFINE_bool(print_code_verbose, false,"print more information for code") DEFINE_bool(print_builtin_code, false,"print generated code for builtins")#47"/Users/thlorenz/dev/dx/v8-perf/build/v8/src/flags.cc"2 namespace{struct Flag{enum FlagType{TYPE_BOOL, TYPE_INT, TYPE_FLOAT, TYPE_STRING, TYPE_ARGS} name
Definition: flags.cc:1349
static HeapObject * cast(Object *obj)
bool auto_enable()
Definition: v8.h:2551
static Handle< T > cast(Handle< S > that)
Definition: handles.h:81
static const int kSourceFieldIndex
Definition: objects.h:6482
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:85
Builtins * builtins()
Definition: isolate.h:909
static const int kSize
Definition: objects.h:6036
static Handle< Context > NewContextFromSnapshot()
static const int kSize
Definition: objects.h:6433
#define ASSERT(condition)
Definition: checks.h:270
MUST_USE_RESULT MaybeObject * PreventExtensions()
Definition: objects.cc:4044
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:801
static const char * GetName(JavaScript id)
Definition: builtins.h:326
static Context * cast(Object *context)
Definition: contexts.h:207
static const int kSize
Definition: objects.h:7982
static const int kSize
Definition: objects.h:8134
Handle< Object > GetProperty(Handle< JSReceiver > obj, const char *name)
Definition: handles.cc:282
Factory * factory()
Definition: isolate.h:977
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:6485
static const int kSize
Definition: objects.h:8112
friend class NativesExternalStringResource
Definition: bootstrapper.h:145
uint32_t ComputePointerHash(void *ptr)
Definition: utils.h:310
#define UNREACHABLE()
Definition: checks.h:50
static const int kArgumentsObjectSizeStrict
Definition: heap.h:866
T * start() const
Definition: utils.h:389
static JSGlobalProxy * cast(Object *obj)
static const int kInputIndex
Definition: objects.h:8137
#define INSTALL_BUILTIN_ID(holder_expr, fun_name, name)
friend class BootstrapperActive
Definition: bootstrapper.h:143
Handle< Map > CopyMapDropTransitions(Handle< Map > map)
Definition: factory.cc:499
void set_context(Context *context)
Definition: isolate.h:519
const int kPointerSize
Definition: globals.h:234
const char * name() const
Definition: v8.h:2544
static int GetNameCount(ExtensionConfiguration *that)
Definition: apiutils.h:34
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: globals.h:321
static Handle< Object > SetLocalPropertyIgnoreAttributes(Handle< JSObject > object, Handle< String > key, Handle< Object > value, PropertyAttributes attributes)
Definition: objects.cc:2924
static FunctionTemplateInfo * cast(Object *obj)
Handle< String > NativesSourceLookup(int index)
Definition: bootstrapper.cc:73
int length() const
Definition: utils.h:383
static int NumberOfJavaScriptBuiltins()
Definition: builtins.h:329
static const int kIgnoreCaseFieldIndex
Definition: objects.h:6484
Definition: v8.h:104
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:144
Vector< const char > CStrVector(const char *data)
Definition: utils.h:525
static const int kSize
Definition: objects.h:7955
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:2548
Handle< JSFunction > NewFunctionWithoutPrototype(Handle< String > name, LanguageMode language_mode)
Definition: factory.cc:1212
static const int kSize
Definition: objects.h:6189
#define INSTALL_NATIVE(Type, name, var)
bool is_null() const
Definition: handles.h:87
#define JSFUNCTION_RESULT_CACHE_LIST(F)
static const int kArgumentsLengthIndex
Definition: heap.h:869
void DetachGlobal(Handle< Context > env)
const String::ExternalAsciiStringResource * source() const
Definition: v8.h:2546
void ReattachGlobal(Handle< Context > env, Handle< Object > global_object)
static JSGlobalPropertyCell * cast(Object *obj)
static RegisteredExtension * first_extension()
Definition: api.h:153
static Handle< SharedFunctionInfo > Compile(Handle< String > source, Handle< Object > script_name, int line_offset, int column_offset, v8::Extension *extension, ScriptDataImpl *pre_data, Handle< Object > script_data, NativesFlag is_natives_code)
Definition: compiler.cc:473
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:112
static const int kSize
Definition: objects.h:6281
#define ASSERT_EQ(v1, v2)
Definition: checks.h:271
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 trace on stack replacement optimize closures functions with arguments object optimize functions containing for in loops profiler considers IC stability primitive functions trigger their own optimization re try self optimization if it failed insert an interrupt check at function exit execution budget before interrupt is triggered call count before self optimization self_optimization count_based_interrupts weighted_back_edges trace_opt 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 enable use of ARMv7 instructions if enable use of MIPS FPU instructions if NULL
Definition: flags.cc:274
static const int kIndexIndex
Definition: objects.h:8136
const int kRandomStateSize
Definition: globals.h:239
static Handle< JSObject > InstantiateObject(Handle< ObjectTemplateInfo > data, bool *exc)
Definition: execution.cc:719
static const int kArgumentsCalleeIndex
Definition: heap.h:871
static FixedArray * cast(Object *obj)
static const int kHeaderSize
Definition: objects.h:2115
Object * SetNormalizedProperty(LookupResult *result, Object *value)
Definition: objects.cc:439
static bool ReportApiFailure(const char *location, const char *message)
Definition: api.cc:219
void Add(const T &element, AllocationPolicy allocator=AllocationPolicy())
Definition: list-inl.h:38
bool IsEmpty() const
Definition: v8.h:208
#define FACTORY
Definition: isolate.h:1409
Object * get(int index)
Definition: objects-inl.h:1675
static VisitorId GetVisitorId(int instance_type, int instance_size)
static const int kSize
Definition: objects.h:5990
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:8013
static NormalizedMapCache * cast(Object *obj)
Handle< Object > SetPrototype(Handle< JSFunction > function, Handle< Object > prototype)
Definition: handles.cc:221
static const int kLastIndexFieldIndex
Definition: objects.h:6486
static GlobalObject * cast(Object *obj)
static const int kSize
Definition: objects.h:6111
#define FUNCTIONS_WITH_ID_LIST(V)
Definition: objects.h:5175
NativesExternalStringResource(Bootstrapper *bootstrapper, const char *source, size_t length)
Definition: bootstrapper.cc:50
Handle< Map > NewMap(InstanceType type, int instance_size, ElementsKind elements_kind=TERMINAL_FAST_ELEMENTS_KIND)
Definition: factory.cc:451
Factory * factory() const
const char ** dependencies()
Definition: v8.h:2549
void check(i::Vector< const char > string)
static int ArchiveSpacePerThread()
static JSObject * cast(Object *obj)
FlagType type() const
Definition: flags.cc:1358
static bool IsRunning()
Definition: v8.h:85
static v8::internal::Handle< v8::internal::TemplateInfo > OpenHandle(const Template *that)
static JSGlobalObject * cast(Object *obj)
bool InstallExtensions(Handle< Context > global_context, v8::ExtensionConfiguration *extensions)
static JSFunction * cast(Object *obj)