v8  3.25.30(node0.11.13)
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"
43 #include "trig-table.h"
49 #include "code-stubs.h"
50 
51 namespace v8 {
52 namespace internal {
53 
54 
56  Bootstrapper* bootstrapper,
57  const char* source,
58  size_t length)
59  : data_(source), length_(length) {
60  if (bootstrapper->delete_these_non_arrays_on_tear_down_ == NULL) {
61  bootstrapper->delete_these_non_arrays_on_tear_down_ = new List<char*>(2);
62  }
63  // The resources are small objects and we only make a fixed number of
64  // them, but let's clean them up on exit for neatness.
65  bootstrapper->delete_these_non_arrays_on_tear_down_->
66  Add(reinterpret_cast<char*>(this));
67 }
68 
69 
70 Bootstrapper::Bootstrapper(Isolate* isolate)
71  : isolate_(isolate),
72  nesting_(0),
73  extensions_cache_(Script::TYPE_EXTENSION),
74  delete_these_non_arrays_on_tear_down_(NULL),
75  delete_these_arrays_on_tear_down_(NULL) {
76 }
77 
78 
80  ASSERT(0 <= index && index < Natives::GetBuiltinsCount());
81  Heap* heap = isolate_->heap();
82  if (heap->natives_source_cache()->get(index)->IsUndefined()) {
83  // We can use external strings for the natives.
87  source.start(),
88  source.length());
89  Handle<String> source_code =
90  isolate_->factory()->NewExternalStringFromAscii(resource);
91  // We do not expect this to throw an exception. Change this if it does.
92  CHECK_NOT_EMPTY_HANDLE(isolate_, source_code);
93  heap->natives_source_cache()->set(index, *source_code);
94  }
95  Handle<Object> cached_source(heap->natives_source_cache()->get(index),
96  isolate_);
97  return Handle<String>::cast(cached_source);
98 }
99 
100 
101 void Bootstrapper::Initialize(bool create_heap_objects) {
102  extensions_cache_.Initialize(isolate_, create_heap_objects);
103 }
104 
105 
106 static const char* GCFunctionName() {
107  bool flag_given = FLAG_expose_gc_as != NULL && strlen(FLAG_expose_gc_as) != 0;
108  return flag_given ? FLAG_expose_gc_as : "gc";
109 }
110 
111 
112 v8::Extension* Bootstrapper::free_buffer_extension_ = NULL;
113 v8::Extension* Bootstrapper::gc_extension_ = NULL;
114 v8::Extension* Bootstrapper::externalize_string_extension_ = NULL;
115 v8::Extension* Bootstrapper::statistics_extension_ = NULL;
116 v8::Extension* Bootstrapper::trigger_failure_extension_ = NULL;
117 
118 
120  free_buffer_extension_ = new FreeBufferExtension;
121  v8::RegisterExtension(free_buffer_extension_);
122  gc_extension_ = new GCExtension(GCFunctionName());
123  v8::RegisterExtension(gc_extension_);
124  externalize_string_extension_ = new ExternalizeStringExtension;
125  v8::RegisterExtension(externalize_string_extension_);
126  statistics_extension_ = new StatisticsExtension;
127  v8::RegisterExtension(statistics_extension_);
128  trigger_failure_extension_ = new TriggerFailureExtension;
129  v8::RegisterExtension(trigger_failure_extension_);
130 }
131 
132 
134  delete free_buffer_extension_;
135  delete gc_extension_;
136  delete externalize_string_extension_;
137  delete statistics_extension_;
138  delete trigger_failure_extension_;
139 }
140 
141 
143  char* memory = new char[bytes];
144  if (memory != NULL) {
145  if (delete_these_arrays_on_tear_down_ == NULL) {
146  delete_these_arrays_on_tear_down_ = new List<char*>(2);
147  }
148  delete_these_arrays_on_tear_down_->Add(memory);
149  }
150  return memory;
151 }
152 
153 
155  if (delete_these_non_arrays_on_tear_down_ != NULL) {
156  int len = delete_these_non_arrays_on_tear_down_->length();
157  ASSERT(len < 24); // Don't use this mechanism for unbounded allocations.
158  for (int i = 0; i < len; i++) {
159  delete delete_these_non_arrays_on_tear_down_->at(i);
160  delete_these_non_arrays_on_tear_down_->at(i) = NULL;
161  }
162  delete delete_these_non_arrays_on_tear_down_;
163  delete_these_non_arrays_on_tear_down_ = NULL;
164  }
165 
166  if (delete_these_arrays_on_tear_down_ != NULL) {
167  int len = delete_these_arrays_on_tear_down_->length();
168  ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations.
169  for (int i = 0; i < len; i++) {
170  delete[] delete_these_arrays_on_tear_down_->at(i);
171  delete_these_arrays_on_tear_down_->at(i) = NULL;
172  }
173  delete delete_these_arrays_on_tear_down_;
174  delete_these_arrays_on_tear_down_ = NULL;
175  }
176 
177  extensions_cache_.Initialize(isolate_, false); // Yes, symmetrical
178 }
179 
180 
181 class Genesis BASE_EMBEDDED {
182  public:
183  Genesis(Isolate* isolate,
184  Handle<Object> global_object,
185  v8::Handle<v8::ObjectTemplate> global_template,
186  v8::ExtensionConfiguration* extensions);
187  ~Genesis() { }
188 
189  Isolate* isolate() const { return isolate_; }
190  Factory* factory() const { return isolate_->factory(); }
191  Heap* heap() const { return isolate_->heap(); }
192 
193  Handle<Context> result() { return result_; }
194 
195  private:
196  Handle<Context> native_context() { return native_context_; }
197 
198  // Creates some basic objects. Used for creating a context from scratch.
199  void CreateRoots();
200  // Creates the empty function. Used for creating a context from scratch.
201  Handle<JSFunction> CreateEmptyFunction(Isolate* isolate);
202  // Creates the ThrowTypeError function. ECMA 5th Ed. 13.2.3
203  Handle<JSFunction> GetThrowTypeErrorFunction();
204 
205  void CreateStrictModeFunctionMaps(Handle<JSFunction> empty);
206 
207  // Make the "arguments" and "caller" properties throw a TypeError on access.
208  void PoisonArgumentsAndCaller(Handle<Map> map);
209 
210  // Creates the global objects using the global and the template passed in
211  // through the API. We call this regardless of whether we are building a
212  // context from scratch or using a deserialized one from the partial snapshot
213  // but in the latter case we don't use the objects it produces directly, as
214  // we have to used the deserialized ones that are linked together with the
215  // rest of the context snapshot.
216  Handle<JSGlobalProxy> CreateNewGlobals(
217  v8::Handle<v8::ObjectTemplate> global_template,
218  Handle<Object> global_object,
219  Handle<GlobalObject>* global_proxy_out);
220  // Hooks the given global proxy into the context. If the context was created
221  // by deserialization then this will unhook the global proxy that was
222  // deserialized, leaving the GC to pick it up.
223  void HookUpGlobalProxy(Handle<GlobalObject> inner_global,
224  Handle<JSGlobalProxy> global_proxy);
225  // Similarly, we want to use the inner global that has been created by the
226  // templates passed through the API. The inner global from the snapshot is
227  // detached from the other objects in the snapshot.
228  void HookUpInnerGlobal(Handle<GlobalObject> inner_global);
229  // New context initialization. Used for creating a context from scratch.
230  void InitializeGlobal(Handle<GlobalObject> inner_global,
231  Handle<JSFunction> empty_function);
232  void InitializeExperimentalGlobal();
233  // Installs the contents of the native .js files on the global objects.
234  // Used for creating a context from scratch.
235  void InstallNativeFunctions();
236  void InstallExperimentalBuiltinFunctionIds();
237  void InstallExperimentalNativeFunctions();
238  Handle<JSFunction> InstallInternalArray(Handle<JSBuiltinsObject> builtins,
239  const char* name,
240  ElementsKind elements_kind);
241  bool InstallNatives();
242 
243  Handle<JSFunction> InstallTypedArray(const char* name,
244  ElementsKind elementsKind);
245  bool InstallExperimentalNatives();
246  void InstallBuiltinFunctionIds();
247  void InstallJSFunctionResultCaches();
248  void InitializeNormalizedMapCaches();
249 
250  enum ExtensionTraversalState {
251  UNVISITED, VISITED, INSTALLED
252  };
253 
254  class ExtensionStates {
255  public:
256  ExtensionStates();
257  ExtensionTraversalState get_state(RegisteredExtension* extension);
258  void set_state(RegisteredExtension* extension,
259  ExtensionTraversalState state);
260  private:
261  HashMap map_;
262  DISALLOW_COPY_AND_ASSIGN(ExtensionStates);
263  };
264 
265  // Used both for deserialized and from-scratch contexts to add the extensions
266  // provided.
267  static bool InstallExtensions(Handle<Context> native_context,
268  v8::ExtensionConfiguration* extensions);
269  static bool InstallAutoExtensions(Isolate* isolate,
270  ExtensionStates* extension_states);
271  static bool InstallRequestedExtensions(Isolate* isolate,
272  v8::ExtensionConfiguration* extensions,
273  ExtensionStates* extension_states);
274  static bool InstallExtension(Isolate* isolate,
275  const char* name,
276  ExtensionStates* extension_states);
277  static bool InstallExtension(Isolate* isolate,
278  v8::RegisteredExtension* current,
279  ExtensionStates* extension_states);
280  static bool InstallSpecialObjects(Handle<Context> native_context);
281  bool InstallJSBuiltins(Handle<JSBuiltinsObject> builtins);
282  bool ConfigureApiObject(Handle<JSObject> object,
283  Handle<ObjectTemplateInfo> object_template);
284  bool ConfigureGlobalObjects(v8::Handle<v8::ObjectTemplate> global_template);
285 
286  // Migrates all properties from the 'from' object to the 'to'
287  // object and overrides the prototype in 'to' with the one from
288  // 'from'.
289  void TransferObject(Handle<JSObject> from, Handle<JSObject> to);
290  void TransferNamedProperties(Handle<JSObject> from, Handle<JSObject> to);
291  void TransferIndexedProperties(Handle<JSObject> from, Handle<JSObject> to);
292 
293  enum PrototypePropertyMode {
294  DONT_ADD_PROTOTYPE,
295  ADD_READONLY_PROTOTYPE,
296  ADD_WRITEABLE_PROTOTYPE
297  };
298 
299  Handle<Map> CreateFunctionMap(PrototypePropertyMode prototype_mode);
300 
301  void SetFunctionInstanceDescriptor(Handle<Map> map,
302  PrototypePropertyMode prototypeMode);
303  void MakeFunctionInstancePrototypeWritable();
304 
305  Handle<Map> CreateStrictFunctionMap(
306  PrototypePropertyMode prototype_mode,
307  Handle<JSFunction> empty_function);
308 
309  void SetStrictFunctionInstanceDescriptor(Handle<Map> map,
310  PrototypePropertyMode propertyMode);
311 
312  static bool CompileBuiltin(Isolate* isolate, int index);
313  static bool CompileExperimentalBuiltin(Isolate* isolate, int index);
314  static bool CompileNative(Isolate* isolate,
315  Vector<const char> name,
316  Handle<String> source);
317  static bool CompileScriptCached(Isolate* isolate,
318  Vector<const char> name,
319  Handle<String> source,
320  SourceCodeCache* cache,
321  v8::Extension* extension,
322  Handle<Context> top_context,
323  bool use_runtime_context);
324 
325  Isolate* isolate_;
326  Handle<Context> result_;
327  Handle<Context> native_context_;
328 
329  // Function maps. Function maps are created initially with a read only
330  // prototype for the processing of JS builtins. Later the function maps are
331  // replaced in order to make prototype writable. These are the final, writable
332  // prototype, maps.
333  Handle<Map> sloppy_function_map_writable_prototype_;
334  Handle<Map> strict_function_map_writable_prototype_;
335  Handle<JSFunction> throw_type_error_function;
336 
337  BootstrapperActive active_;
338  friend class Bootstrapper;
339 };
340 
341 
342 void Bootstrapper::Iterate(ObjectVisitor* v) {
343  extensions_cache_.Iterate(v);
344  v->Synchronize(VisitorSynchronization::kExtensions);
345 }
346 
347 
349  Handle<Object> global_object,
350  v8::Handle<v8::ObjectTemplate> global_template,
351  v8::ExtensionConfiguration* extensions) {
352  HandleScope scope(isolate_);
353  Genesis genesis(isolate_, global_object, global_template, extensions);
354  Handle<Context> env = genesis.result();
355  if (env.is_null() || !InstallExtensions(env, extensions)) {
356  return Handle<Context>();
357  }
358  return scope.CloseAndEscape(env);
359 }
360 
361 
362 static void SetObjectPrototype(Handle<JSObject> object, Handle<Object> proto) {
363  // object.__proto__ = proto;
364  Factory* factory = object->GetIsolate()->factory();
365  Handle<Map> old_to_map = Handle<Map>(object->map());
366  Handle<Map> new_to_map = factory->CopyMap(old_to_map);
367  new_to_map->set_prototype(*proto);
368  object->set_map(*new_to_map);
369 }
370 
371 
373  Factory* factory = env->GetIsolate()->factory();
374  Handle<JSGlobalProxy> global_proxy(JSGlobalProxy::cast(env->global_proxy()));
375  global_proxy->set_native_context(*factory->null_value());
376  SetObjectPrototype(global_proxy, factory->null_value());
377 }
378 
379 
380 static Handle<JSFunction> InstallFunction(Handle<JSObject> target,
381  const char* name,
382  InstanceType type,
383  int instance_size,
384  Handle<JSObject> prototype,
385  Builtins::Name call,
386  bool install_initial_map,
387  bool set_instance_class_name) {
388  Isolate* isolate = target->GetIsolate();
389  Factory* factory = isolate->factory();
390  Handle<String> internalized_name = factory->InternalizeUtf8String(name);
391  Handle<Code> call_code = Handle<Code>(isolate->builtins()->builtin(call));
392  Handle<JSFunction> function = prototype.is_null() ?
393  factory->NewFunctionWithoutPrototype(internalized_name, call_code) :
394  factory->NewFunctionWithPrototype(internalized_name,
395  type,
396  instance_size,
397  prototype,
398  call_code,
399  install_initial_map);
400  PropertyAttributes attributes;
401  if (target->IsJSBuiltinsObject()) {
402  attributes =
404  } else {
405  attributes = DONT_ENUM;
406  }
407  CHECK_NOT_EMPTY_HANDLE(isolate,
409  target, internalized_name, function, attributes));
410  if (set_instance_class_name) {
411  function->shared()->set_instance_class_name(*internalized_name);
412  }
413  function->shared()->set_native(true);
414  return function;
415 }
416 
417 
418 void Genesis::SetFunctionInstanceDescriptor(
419  Handle<Map> map, PrototypePropertyMode prototypeMode) {
420  int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
421  Handle<DescriptorArray> descriptors(factory()->NewDescriptorArray(0, size));
422  DescriptorArray::WhitenessWitness witness(*descriptors);
423 
424  Handle<Foreign> length(factory()->NewForeign(&Accessors::FunctionLength));
425  Handle<Foreign> name(factory()->NewForeign(&Accessors::FunctionName));
426  Handle<Foreign> args(factory()->NewForeign(&Accessors::FunctionArguments));
427  Handle<Foreign> caller(factory()->NewForeign(&Accessors::FunctionCaller));
428  Handle<Foreign> prototype;
429  if (prototypeMode != DONT_ADD_PROTOTYPE) {
430  prototype = factory()->NewForeign(&Accessors::FunctionPrototype);
431  }
432  PropertyAttributes attribs = static_cast<PropertyAttributes>(
434  map->set_instance_descriptors(*descriptors);
435 
436  { // Add length.
437  CallbacksDescriptor d(*factory()->length_string(), *length, attribs);
438  map->AppendDescriptor(&d, witness);
439  }
440  { // Add name.
441  CallbacksDescriptor d(*factory()->name_string(), *name, attribs);
442  map->AppendDescriptor(&d, witness);
443  }
444  { // Add arguments.
445  CallbacksDescriptor d(*factory()->arguments_string(), *args, attribs);
446  map->AppendDescriptor(&d, witness);
447  }
448  { // Add caller.
449  CallbacksDescriptor d(*factory()->caller_string(), *caller, attribs);
450  map->AppendDescriptor(&d, witness);
451  }
452  if (prototypeMode != DONT_ADD_PROTOTYPE) {
453  // Add prototype.
454  if (prototypeMode == ADD_WRITEABLE_PROTOTYPE) {
455  attribs = static_cast<PropertyAttributes>(attribs & ~READ_ONLY);
456  }
457  CallbacksDescriptor d(*factory()->prototype_string(), *prototype, attribs);
458  map->AppendDescriptor(&d, witness);
459  }
460 }
461 
462 
463 Handle<Map> Genesis::CreateFunctionMap(PrototypePropertyMode prototype_mode) {
464  Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
465  SetFunctionInstanceDescriptor(map, prototype_mode);
466  map->set_function_with_prototype(prototype_mode != DONT_ADD_PROTOTYPE);
467  return map;
468 }
469 
470 
471 Handle<JSFunction> Genesis::CreateEmptyFunction(Isolate* isolate) {
472  // Allocate the map for function instances. Maps are allocated first and their
473  // prototypes patched later, once empty function is created.
474 
475  // Functions with this map will not have a 'prototype' property, and
476  // can not be used as constructors.
477  Handle<Map> function_without_prototype_map =
478  CreateFunctionMap(DONT_ADD_PROTOTYPE);
479  native_context()->set_sloppy_function_without_prototype_map(
480  *function_without_prototype_map);
481 
482  // Allocate the function map. This map is temporary, used only for processing
483  // of builtins.
484  // Later the map is replaced with writable prototype map, allocated below.
485  Handle<Map> function_map = CreateFunctionMap(ADD_READONLY_PROTOTYPE);
486  native_context()->set_sloppy_function_map(*function_map);
487 
488  // The final map for functions. Writeable prototype.
489  // This map is installed in MakeFunctionInstancePrototypeWritable.
490  sloppy_function_map_writable_prototype_ =
491  CreateFunctionMap(ADD_WRITEABLE_PROTOTYPE);
492 
493  Factory* factory = isolate->factory();
494 
495  Handle<String> object_name = factory->Object_string();
496 
497  { // --- O b j e c t ---
498  Handle<JSFunction> object_fun =
499  factory->NewFunction(object_name, factory->null_value());
500  Handle<Map> object_function_map =
501  factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
502  object_fun->set_initial_map(*object_function_map);
503  object_function_map->set_constructor(*object_fun);
504 
505  native_context()->set_object_function(*object_fun);
506 
507  // Allocate a new prototype for the object function.
508  Handle<JSObject> prototype = factory->NewJSObject(
509  isolate->object_function(),
510  TENURED);
511 
512  native_context()->set_initial_object_prototype(*prototype);
513  // For bootstrapping set the array prototype to be the same as the object
514  // prototype, otherwise the missing initial_array_prototype will cause
515  // assertions during startup.
516  native_context()->set_initial_array_prototype(*prototype);
517  Accessors::FunctionSetPrototype(object_fun, prototype);
518  }
519 
520  // Allocate the empty function as the prototype for function ECMAScript
521  // 262 15.3.4.
522  Handle<String> empty_string =
523  factory->InternalizeOneByteString(STATIC_ASCII_VECTOR("Empty"));
524  Handle<JSFunction> empty_function =
525  factory->NewFunctionWithoutPrototype(empty_string, SLOPPY);
526 
527  // --- E m p t y ---
528  Handle<Code> code =
529  Handle<Code>(isolate->builtins()->builtin(
530  Builtins::kEmptyFunction));
531  empty_function->set_code(*code);
532  empty_function->shared()->set_code(*code);
533  Handle<String> source =
534  factory->NewStringFromOneByte(STATIC_ASCII_VECTOR("() {}"));
535  Handle<Script> script = factory->NewScript(source);
536  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
537  empty_function->shared()->set_script(*script);
538  empty_function->shared()->set_start_position(0);
539  empty_function->shared()->set_end_position(source->length());
540  empty_function->shared()->DontAdaptArguments();
541 
542  // Set prototypes for the function maps.
543  native_context()->sloppy_function_map()->set_prototype(*empty_function);
544  native_context()->sloppy_function_without_prototype_map()->
545  set_prototype(*empty_function);
546  sloppy_function_map_writable_prototype_->set_prototype(*empty_function);
547 
548  // Allocate the function map first and then patch the prototype later
549  Handle<Map> empty_function_map = CreateFunctionMap(DONT_ADD_PROTOTYPE);
550  empty_function_map->set_prototype(
551  native_context()->object_function()->prototype());
552  empty_function->set_map(*empty_function_map);
553  return empty_function;
554 }
555 
556 
557 void Genesis::SetStrictFunctionInstanceDescriptor(
558  Handle<Map> map, PrototypePropertyMode prototypeMode) {
559  int size = (prototypeMode == DONT_ADD_PROTOTYPE) ? 4 : 5;
560  Handle<DescriptorArray> descriptors(factory()->NewDescriptorArray(0, size));
561  DescriptorArray::WhitenessWitness witness(*descriptors);
562 
563  Handle<Foreign> length(factory()->NewForeign(&Accessors::FunctionLength));
564  Handle<Foreign> name(factory()->NewForeign(&Accessors::FunctionName));
565  Handle<AccessorPair> arguments(factory()->NewAccessorPair());
566  Handle<AccessorPair> caller(factory()->NewAccessorPair());
567  Handle<Foreign> prototype;
568  if (prototypeMode != DONT_ADD_PROTOTYPE) {
569  prototype = factory()->NewForeign(&Accessors::FunctionPrototype);
570  }
571  PropertyAttributes rw_attribs =
572  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
573  PropertyAttributes ro_attribs =
575  map->set_instance_descriptors(*descriptors);
576 
577  { // Add length.
578  CallbacksDescriptor d(*factory()->length_string(), *length, ro_attribs);
579  map->AppendDescriptor(&d, witness);
580  }
581  { // Add name.
582  CallbacksDescriptor d(*factory()->name_string(), *name, ro_attribs);
583  map->AppendDescriptor(&d, witness);
584  }
585  { // Add arguments.
586  CallbacksDescriptor d(*factory()->arguments_string(), *arguments,
587  rw_attribs);
588  map->AppendDescriptor(&d, witness);
589  }
590  { // Add caller.
591  CallbacksDescriptor d(*factory()->caller_string(), *caller, rw_attribs);
592  map->AppendDescriptor(&d, witness);
593  }
594  if (prototypeMode != DONT_ADD_PROTOTYPE) {
595  // Add prototype.
596  PropertyAttributes attribs =
597  prototypeMode == ADD_WRITEABLE_PROTOTYPE ? rw_attribs : ro_attribs;
598  CallbacksDescriptor d(*factory()->prototype_string(), *prototype, attribs);
599  map->AppendDescriptor(&d, witness);
600  }
601 }
602 
603 
604 // ECMAScript 5th Edition, 13.2.3
605 Handle<JSFunction> Genesis::GetThrowTypeErrorFunction() {
606  if (throw_type_error_function.is_null()) {
607  Handle<String> name = factory()->InternalizeOneByteString(
608  STATIC_ASCII_VECTOR("ThrowTypeError"));
609  throw_type_error_function =
610  factory()->NewFunctionWithoutPrototype(name, SLOPPY);
611  Handle<Code> code(isolate()->builtins()->builtin(
612  Builtins::kStrictModePoisonPill));
613  throw_type_error_function->set_map(native_context()->sloppy_function_map());
614  throw_type_error_function->set_code(*code);
615  throw_type_error_function->shared()->set_code(*code);
616  throw_type_error_function->shared()->DontAdaptArguments();
617 
618  JSObject::PreventExtensions(throw_type_error_function);
619  }
620  return throw_type_error_function;
621 }
622 
623 
624 Handle<Map> Genesis::CreateStrictFunctionMap(
625  PrototypePropertyMode prototype_mode,
626  Handle<JSFunction> empty_function) {
627  Handle<Map> map = factory()->NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
628  SetStrictFunctionInstanceDescriptor(map, prototype_mode);
629  map->set_function_with_prototype(prototype_mode != DONT_ADD_PROTOTYPE);
630  map->set_prototype(*empty_function);
631  return map;
632 }
633 
634 
635 void Genesis::CreateStrictModeFunctionMaps(Handle<JSFunction> empty) {
636  // Allocate map for the prototype-less strict mode instances.
637  Handle<Map> strict_function_without_prototype_map =
638  CreateStrictFunctionMap(DONT_ADD_PROTOTYPE, empty);
639  native_context()->set_strict_function_without_prototype_map(
640  *strict_function_without_prototype_map);
641 
642  // Allocate map for the strict mode functions. This map is temporary, used
643  // only for processing of builtins.
644  // Later the map is replaced with writable prototype map, allocated below.
645  Handle<Map> strict_function_map =
646  CreateStrictFunctionMap(ADD_READONLY_PROTOTYPE, empty);
647  native_context()->set_strict_function_map(*strict_function_map);
648 
649  // The final map for the strict mode functions. Writeable prototype.
650  // This map is installed in MakeFunctionInstancePrototypeWritable.
651  strict_function_map_writable_prototype_ =
652  CreateStrictFunctionMap(ADD_WRITEABLE_PROTOTYPE, empty);
653 
654  // Complete the callbacks.
655  PoisonArgumentsAndCaller(strict_function_without_prototype_map);
656  PoisonArgumentsAndCaller(strict_function_map);
657  PoisonArgumentsAndCaller(strict_function_map_writable_prototype_);
658 }
659 
660 
661 static void SetAccessors(Handle<Map> map,
662  Handle<String> name,
663  Handle<JSFunction> func) {
664  DescriptorArray* descs = map->instance_descriptors();
665  int number = descs->SearchWithCache(*name, *map);
666  AccessorPair* accessors = AccessorPair::cast(descs->GetValue(number));
667  accessors->set_getter(*func);
668  accessors->set_setter(*func);
669 }
670 
671 
672 void Genesis::PoisonArgumentsAndCaller(Handle<Map> map) {
673  SetAccessors(map, factory()->arguments_string(), GetThrowTypeErrorFunction());
674  SetAccessors(map, factory()->caller_string(), GetThrowTypeErrorFunction());
675 }
676 
677 
678 static void AddToWeakNativeContextList(Context* context) {
679  ASSERT(context->IsNativeContext());
680  Heap* heap = context->GetIsolate()->heap();
681 #ifdef DEBUG
682  { // NOLINT
683  ASSERT(context->get(Context::NEXT_CONTEXT_LINK)->IsUndefined());
684  // Check that context is not in the list yet.
685  for (Object* current = heap->native_contexts_list();
686  !current->IsUndefined();
687  current = Context::cast(current)->get(Context::NEXT_CONTEXT_LINK)) {
688  ASSERT(current != context);
689  }
690  }
691 #endif
692  context->set(Context::NEXT_CONTEXT_LINK, heap->native_contexts_list());
693  heap->set_native_contexts_list(context);
694 }
695 
696 
697 void Genesis::CreateRoots() {
698  // Allocate the native context FixedArray first and then patch the
699  // closure and extension object later (we need the empty function
700  // and the global object, but in order to create those, we need the
701  // native context).
702  native_context_ = factory()->NewNativeContext();
703  AddToWeakNativeContextList(*native_context());
704  isolate()->set_context(*native_context());
705 
706  // Allocate the message listeners object.
707  {
708  v8::NeanderArray listeners(isolate());
709  native_context()->set_message_listeners(*listeners.value());
710  }
711 }
712 
713 
714 Handle<JSGlobalProxy> Genesis::CreateNewGlobals(
715  v8::Handle<v8::ObjectTemplate> global_template,
716  Handle<Object> global_object,
717  Handle<GlobalObject>* inner_global_out) {
718  // The argument global_template aka data is an ObjectTemplateInfo.
719  // It has a constructor pointer that points at global_constructor which is a
720  // FunctionTemplateInfo.
721  // The global_constructor is used to create or reinitialize the global_proxy.
722  // The global_constructor also has a prototype_template pointer that points at
723  // js_global_template which is an ObjectTemplateInfo.
724  // That in turn has a constructor pointer that points at
725  // js_global_constructor which is a FunctionTemplateInfo.
726  // js_global_constructor is used to make js_global_function
727  // js_global_function is used to make the new inner_global.
728  //
729  // --- G l o b a l ---
730  // Step 1: Create a fresh inner JSGlobalObject.
731  Handle<JSFunction> js_global_function;
732  Handle<ObjectTemplateInfo> js_global_template;
733  if (!global_template.IsEmpty()) {
734  // Get prototype template of the global_template.
735  Handle<ObjectTemplateInfo> data =
736  v8::Utils::OpenHandle(*global_template);
737  Handle<FunctionTemplateInfo> global_constructor =
738  Handle<FunctionTemplateInfo>(
739  FunctionTemplateInfo::cast(data->constructor()));
740  Handle<Object> proto_template(global_constructor->prototype_template(),
741  isolate());
742  if (!proto_template->IsUndefined()) {
743  js_global_template =
744  Handle<ObjectTemplateInfo>::cast(proto_template);
745  }
746  }
747 
748  if (js_global_template.is_null()) {
749  Handle<String> name = Handle<String>(heap()->empty_string());
750  Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
751  Builtins::kIllegal));
752  js_global_function =
753  factory()->NewFunction(name, JS_GLOBAL_OBJECT_TYPE,
754  JSGlobalObject::kSize, code, true);
755  // Change the constructor property of the prototype of the
756  // hidden global function to refer to the Object function.
757  Handle<JSObject> prototype =
758  Handle<JSObject>(
759  JSObject::cast(js_global_function->instance_prototype()));
760  CHECK_NOT_EMPTY_HANDLE(isolate(),
762  prototype, factory()->constructor_string(),
763  isolate()->object_function(), NONE));
764  } else {
765  Handle<FunctionTemplateInfo> js_global_constructor(
766  FunctionTemplateInfo::cast(js_global_template->constructor()));
767  js_global_function =
768  factory()->CreateApiFunction(js_global_constructor,
769  factory()->InnerGlobalObject);
770  }
771 
772  js_global_function->initial_map()->set_is_hidden_prototype();
773  js_global_function->initial_map()->set_dictionary_map(true);
774  Handle<GlobalObject> inner_global =
775  factory()->NewGlobalObject(js_global_function);
776  if (inner_global_out != NULL) {
777  *inner_global_out = inner_global;
778  }
779 
780  // Step 2: create or re-initialize the global proxy object.
781  Handle<JSFunction> global_proxy_function;
782  if (global_template.IsEmpty()) {
783  Handle<String> name = Handle<String>(heap()->empty_string());
784  Handle<Code> code = Handle<Code>(isolate()->builtins()->builtin(
785  Builtins::kIllegal));
786  global_proxy_function =
787  factory()->NewFunction(name, JS_GLOBAL_PROXY_TYPE,
788  JSGlobalProxy::kSize, code, true);
789  } else {
790  Handle<ObjectTemplateInfo> data =
791  v8::Utils::OpenHandle(*global_template);
792  Handle<FunctionTemplateInfo> global_constructor(
793  FunctionTemplateInfo::cast(data->constructor()));
794  global_proxy_function =
795  factory()->CreateApiFunction(global_constructor,
796  factory()->OuterGlobalObject);
797  }
798 
799  Handle<String> global_name = factory()->InternalizeOneByteString(
800  STATIC_ASCII_VECTOR("global"));
801  global_proxy_function->shared()->set_instance_class_name(*global_name);
802  global_proxy_function->initial_map()->set_is_access_check_needed(true);
803 
804  // Set global_proxy.__proto__ to js_global after ConfigureGlobalObjects
805  // Return the global proxy.
806 
807  if (global_object.location() != NULL) {
808  ASSERT(global_object->IsJSGlobalProxy());
810  global_proxy_function,
811  Handle<JSGlobalProxy>::cast(global_object));
812  } else {
814  factory()->NewJSObject(global_proxy_function, TENURED));
815  }
816 }
817 
818 
819 void Genesis::HookUpGlobalProxy(Handle<GlobalObject> inner_global,
820  Handle<JSGlobalProxy> global_proxy) {
821  // Set the native context for the global object.
822  inner_global->set_native_context(*native_context());
823  inner_global->set_global_context(*native_context());
824  inner_global->set_global_receiver(*global_proxy);
825  global_proxy->set_native_context(*native_context());
826  native_context()->set_global_proxy(*global_proxy);
827 }
828 
829 
830 void Genesis::HookUpInnerGlobal(Handle<GlobalObject> inner_global) {
831  Handle<GlobalObject> inner_global_from_snapshot(
832  GlobalObject::cast(native_context()->extension()));
833  Handle<JSBuiltinsObject> builtins_global(native_context()->builtins());
834  native_context()->set_extension(*inner_global);
835  native_context()->set_global_object(*inner_global);
836  native_context()->set_security_token(*inner_global);
837  static const PropertyAttributes attributes =
838  static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
839  ForceSetProperty(builtins_global,
840  factory()->InternalizeOneByteString(
841  STATIC_ASCII_VECTOR("global")),
842  inner_global,
843  attributes);
844  // Set up the reference from the global object to the builtins object.
845  JSGlobalObject::cast(*inner_global)->set_builtins(*builtins_global);
846  TransferNamedProperties(inner_global_from_snapshot, inner_global);
847  TransferIndexedProperties(inner_global_from_snapshot, inner_global);
848 }
849 
850 
851 // This is only called if we are not using snapshots. The equivalent
852 // work in the snapshot case is done in HookUpInnerGlobal.
853 void Genesis::InitializeGlobal(Handle<GlobalObject> inner_global,
854  Handle<JSFunction> empty_function) {
855  // --- N a t i v e C o n t e x t ---
856  // Use the empty function as closure (no scope info).
857  native_context()->set_closure(*empty_function);
858  native_context()->set_previous(NULL);
859  // Set extension and global object.
860  native_context()->set_extension(*inner_global);
861  native_context()->set_global_object(*inner_global);
862  // Security setup: Set the security token of the global object to
863  // its the inner global. This makes the security check between two
864  // different contexts fail by default even in case of global
865  // object reinitialization.
866  native_context()->set_security_token(*inner_global);
867 
868  Isolate* isolate = inner_global->GetIsolate();
869  Factory* factory = isolate->factory();
870  Heap* heap = isolate->heap();
871 
872  Handle<String> object_name = factory->Object_string();
873  CHECK_NOT_EMPTY_HANDLE(isolate,
875  inner_global, object_name,
876  isolate->object_function(), DONT_ENUM));
877 
878  Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
879 
880  // Install global Function object
881  InstallFunction(global, "Function", JS_FUNCTION_TYPE, JSFunction::kSize,
882  empty_function, Builtins::kIllegal, true, true);
883 
884  { // --- A r r a y ---
885  Handle<JSFunction> array_function =
886  InstallFunction(global, "Array", JS_ARRAY_TYPE, JSArray::kSize,
887  isolate->initial_object_prototype(),
888  Builtins::kArrayCode, true, true);
889  array_function->shared()->DontAdaptArguments();
890  array_function->shared()->set_function_data(Smi::FromInt(kArrayCode));
891 
892  // This seems a bit hackish, but we need to make sure Array.length
893  // is 1.
894  array_function->shared()->set_length(1);
895 
896  Handle<Map> initial_map(array_function->initial_map());
897 
898  // This assert protects an optimization in
899  // HGraphBuilder::JSArrayBuilder::EmitMapCode()
900  ASSERT(initial_map->elements_kind() == GetInitialFastElementsKind());
901 
902  Handle<DescriptorArray> array_descriptors(
903  factory->NewDescriptorArray(0, 1));
904  DescriptorArray::WhitenessWitness witness(*array_descriptors);
905 
906  Handle<Foreign> array_length(factory->NewForeign(&Accessors::ArrayLength));
907  PropertyAttributes attribs = static_cast<PropertyAttributes>(
909  initial_map->set_instance_descriptors(*array_descriptors);
910 
911  { // Add length.
912  CallbacksDescriptor d(*factory->length_string(), *array_length, attribs);
913  array_function->initial_map()->AppendDescriptor(&d, witness);
914  }
915 
916  // array_function is used internally. JS code creating array object should
917  // search for the 'Array' property on the global object and use that one
918  // as the constructor. 'Array' property on a global object can be
919  // overwritten by JS code.
920  native_context()->set_array_function(*array_function);
921 
922  // Cache the array maps, needed by ArrayConstructorStub
923  CacheInitialJSArrayMaps(native_context(), initial_map);
924  ArrayConstructorStub array_constructor_stub(isolate);
925  Handle<Code> code = array_constructor_stub.GetCode(isolate);
926  array_function->shared()->set_construct_stub(*code);
927  }
928 
929  { // --- N u m b e r ---
930  Handle<JSFunction> number_fun =
931  InstallFunction(global, "Number", JS_VALUE_TYPE, JSValue::kSize,
932  isolate->initial_object_prototype(),
933  Builtins::kIllegal, true, true);
934  native_context()->set_number_function(*number_fun);
935  }
936 
937  { // --- B o o l e a n ---
938  Handle<JSFunction> boolean_fun =
939  InstallFunction(global, "Boolean", JS_VALUE_TYPE, JSValue::kSize,
940  isolate->initial_object_prototype(),
941  Builtins::kIllegal, true, true);
942  native_context()->set_boolean_function(*boolean_fun);
943  }
944 
945  { // --- S t r i n g ---
946  Handle<JSFunction> string_fun =
947  InstallFunction(global, "String", JS_VALUE_TYPE, JSValue::kSize,
948  isolate->initial_object_prototype(),
949  Builtins::kIllegal, true, true);
950  string_fun->shared()->set_construct_stub(
951  isolate->builtins()->builtin(Builtins::kStringConstructCode));
952  native_context()->set_string_function(*string_fun);
953 
954  Handle<Map> string_map =
955  Handle<Map>(native_context()->string_function()->initial_map());
956  Handle<DescriptorArray> string_descriptors(
957  factory->NewDescriptorArray(0, 1));
958  DescriptorArray::WhitenessWitness witness(*string_descriptors);
959 
960  Handle<Foreign> string_length(
961  factory->NewForeign(&Accessors::StringLength));
962  PropertyAttributes attribs = static_cast<PropertyAttributes>(
964  string_map->set_instance_descriptors(*string_descriptors);
965 
966  { // Add length.
967  CallbacksDescriptor d(*factory->length_string(), *string_length, attribs);
968  string_map->AppendDescriptor(&d, witness);
969  }
970  }
971 
972  { // --- D a t e ---
973  // Builtin functions for Date.prototype.
974  Handle<JSFunction> date_fun =
975  InstallFunction(global, "Date", JS_DATE_TYPE, JSDate::kSize,
976  isolate->initial_object_prototype(),
977  Builtins::kIllegal, true, true);
978 
979  native_context()->set_date_function(*date_fun);
980  }
981 
982 
983  { // -- R e g E x p
984  // Builtin functions for RegExp.prototype.
985  Handle<JSFunction> regexp_fun =
986  InstallFunction(global, "RegExp", JS_REGEXP_TYPE, JSRegExp::kSize,
987  isolate->initial_object_prototype(),
988  Builtins::kIllegal, true, true);
989  native_context()->set_regexp_function(*regexp_fun);
990 
991  ASSERT(regexp_fun->has_initial_map());
992  Handle<Map> initial_map(regexp_fun->initial_map());
993 
994  ASSERT_EQ(0, initial_map->inobject_properties());
995 
996  PropertyAttributes final =
997  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
998  Handle<DescriptorArray> descriptors = factory->NewDescriptorArray(0, 5);
999  DescriptorArray::WhitenessWitness witness(*descriptors);
1000  initial_map->set_instance_descriptors(*descriptors);
1001 
1002  {
1003  // ECMA-262, section 15.10.7.1.
1004  FieldDescriptor field(heap->source_string(),
1006  final,
1008  initial_map->AppendDescriptor(&field, witness);
1009  }
1010  {
1011  // ECMA-262, section 15.10.7.2.
1012  FieldDescriptor field(heap->global_string(),
1014  final,
1016  initial_map->AppendDescriptor(&field, witness);
1017  }
1018  {
1019  // ECMA-262, section 15.10.7.3.
1020  FieldDescriptor field(heap->ignore_case_string(),
1022  final,
1024  initial_map->AppendDescriptor(&field, witness);
1025  }
1026  {
1027  // ECMA-262, section 15.10.7.4.
1028  FieldDescriptor field(heap->multiline_string(),
1030  final,
1032  initial_map->AppendDescriptor(&field, witness);
1033  }
1034  {
1035  // ECMA-262, section 15.10.7.5.
1036  PropertyAttributes writable =
1037  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
1038  FieldDescriptor field(heap->last_index_string(),
1040  writable,
1042  initial_map->AppendDescriptor(&field, witness);
1043  }
1044 
1045  initial_map->set_inobject_properties(5);
1046  initial_map->set_pre_allocated_property_fields(5);
1047  initial_map->set_unused_property_fields(0);
1048  initial_map->set_instance_size(
1049  initial_map->instance_size() + 5 * kPointerSize);
1050  initial_map->set_visitor_id(StaticVisitorBase::GetVisitorId(*initial_map));
1051 
1052  // RegExp prototype object is itself a RegExp.
1053  Handle<Map> proto_map = factory->CopyMap(initial_map);
1054  proto_map->set_prototype(native_context()->initial_object_prototype());
1055  Handle<JSObject> proto = factory->NewJSObjectFromMap(proto_map);
1056  proto->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex,
1057  heap->query_colon_string());
1058  proto->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex,
1059  heap->false_value());
1060  proto->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex,
1061  heap->false_value());
1062  proto->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex,
1063  heap->false_value());
1064  proto->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
1065  Smi::FromInt(0),
1066  SKIP_WRITE_BARRIER); // It's a Smi.
1067  initial_map->set_prototype(*proto);
1068  factory->SetRegExpIrregexpData(Handle<JSRegExp>::cast(proto),
1069  JSRegExp::IRREGEXP, factory->empty_string(),
1070  JSRegExp::Flags(0), 0);
1071  }
1072 
1073  { // -- J S O N
1074  Handle<String> name = factory->InternalizeUtf8String("JSON");
1075  Handle<JSFunction> cons = factory->NewFunction(name,
1076  factory->the_hole_value());
1078  Handle<Object>(native_context()->initial_object_prototype(), isolate));
1079  cons->SetInstanceClassName(*name);
1080  Handle<JSObject> json_object = factory->NewJSObject(cons, TENURED);
1081  ASSERT(json_object->IsJSObject());
1082  CHECK_NOT_EMPTY_HANDLE(isolate,
1084  global, name, json_object, DONT_ENUM));
1085  native_context()->set_json_object(*json_object);
1086  }
1087 
1088  { // -- A r r a y B u f f e r
1089  Handle<JSFunction> array_buffer_fun =
1090  InstallFunction(
1091  global, "ArrayBuffer", JS_ARRAY_BUFFER_TYPE,
1093  isolate->initial_object_prototype(),
1094  Builtins::kIllegal, true, true);
1095  native_context()->set_array_buffer_fun(*array_buffer_fun);
1096  }
1097 
1098  { // -- T y p e d A r r a y s
1099 #define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype, size) \
1100  { \
1101  Handle<JSFunction> fun = InstallTypedArray(#Type "Array", \
1102  TYPE##_ELEMENTS); \
1103  native_context()->set_##type##_array_fun(*fun); \
1104  }
1106 #undef INSTALL_TYPED_ARRAY
1107 
1108  Handle<JSFunction> data_view_fun =
1109  InstallFunction(
1110  global, "DataView", JS_DATA_VIEW_TYPE,
1112  isolate->initial_object_prototype(),
1113  Builtins::kIllegal, true, true);
1114  native_context()->set_data_view_fun(*data_view_fun);
1115  }
1116 
1117  { // -- W e a k M a p
1118  InstallFunction(global, "WeakMap", JS_WEAK_MAP_TYPE, JSWeakMap::kSize,
1119  isolate->initial_object_prototype(),
1120  Builtins::kIllegal, true, true);
1121  }
1122 
1123  { // -- W e a k S e t
1124  InstallFunction(global, "WeakSet", JS_WEAK_SET_TYPE, JSWeakSet::kSize,
1125  isolate->initial_object_prototype(),
1126  Builtins::kIllegal, true, true);
1127  }
1128 
1129  { // --- arguments_boilerplate_
1130  // Make sure we can recognize argument objects at runtime.
1131  // This is done by introducing an anonymous function with
1132  // class_name equals 'Arguments'.
1133  Handle<String> arguments_string = factory->InternalizeOneByteString(
1134  STATIC_ASCII_VECTOR("Arguments"));
1135  Handle<Code> code = Handle<Code>(
1136  isolate->builtins()->builtin(Builtins::kIllegal));
1137  Handle<JSObject> prototype =
1138  Handle<JSObject>(
1139  JSObject::cast(native_context()->object_function()->prototype()));
1140 
1141  Handle<JSFunction> function =
1142  factory->NewFunctionWithPrototype(arguments_string,
1145  prototype,
1146  code,
1147  false);
1148  ASSERT(!function->has_initial_map());
1149  function->shared()->set_instance_class_name(*arguments_string);
1150  function->shared()->set_expected_nof_properties(2);
1151  Handle<JSObject> result = factory->NewJSObject(function);
1152 
1153  native_context()->set_sloppy_arguments_boilerplate(*result);
1154  // Note: length must be added as the first property and
1155  // callee must be added as the second property.
1156  CHECK_NOT_EMPTY_HANDLE(isolate,
1158  result, factory->length_string(),
1159  factory->undefined_value(), DONT_ENUM,
1161  CHECK_NOT_EMPTY_HANDLE(isolate,
1163  result, factory->callee_string(),
1164  factory->undefined_value(), DONT_ENUM,
1166 
1167 #ifdef DEBUG
1168  LookupResult lookup(isolate);
1169  result->LocalLookup(heap->callee_string(), &lookup);
1170  ASSERT(lookup.IsField());
1171  ASSERT(lookup.GetFieldIndex().field_index() == Heap::kArgumentsCalleeIndex);
1172 
1173  result->LocalLookup(heap->length_string(), &lookup);
1174  ASSERT(lookup.IsField());
1175  ASSERT(lookup.GetFieldIndex().field_index() == Heap::kArgumentsLengthIndex);
1176 
1177  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsCalleeIndex);
1178  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1179 
1180  // Check the state of the object.
1181  ASSERT(result->HasFastProperties());
1182  ASSERT(result->HasFastObjectElements());
1183 #endif
1184  }
1185 
1186  { // --- aliased_arguments_boilerplate_
1187  // Set up a well-formed parameter map to make assertions happy.
1188  Handle<FixedArray> elements = factory->NewFixedArray(2);
1189  elements->set_map(heap->sloppy_arguments_elements_map());
1190  Handle<FixedArray> array;
1191  array = factory->NewFixedArray(0);
1192  elements->set(0, *array);
1193  array = factory->NewFixedArray(0);
1194  elements->set(1, *array);
1195 
1196  Handle<Map> old_map(
1197  native_context()->sloppy_arguments_boilerplate()->map());
1198  Handle<Map> new_map = factory->CopyMap(old_map);
1199  new_map->set_pre_allocated_property_fields(2);
1200  Handle<JSObject> result = factory->NewJSObjectFromMap(new_map);
1201  // Set elements kind after allocating the object because
1202  // NewJSObjectFromMap assumes a fast elements map.
1203  new_map->set_elements_kind(SLOPPY_ARGUMENTS_ELEMENTS);
1204  result->set_elements(*elements);
1205  ASSERT(result->HasSloppyArgumentsElements());
1206  native_context()->set_aliased_arguments_boilerplate(*result);
1207  }
1208 
1209  { // --- strict mode arguments boilerplate
1210  const PropertyAttributes attributes =
1211  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1212 
1213  // Create the ThrowTypeError functions.
1214  Handle<AccessorPair> callee = factory->NewAccessorPair();
1215  Handle<AccessorPair> caller = factory->NewAccessorPair();
1216 
1217  Handle<JSFunction> throw_function =
1218  GetThrowTypeErrorFunction();
1219 
1220  // Install the ThrowTypeError functions.
1221  callee->set_getter(*throw_function);
1222  callee->set_setter(*throw_function);
1223  caller->set_getter(*throw_function);
1224  caller->set_setter(*throw_function);
1225 
1226  // Create the map. Allocate one in-object field for length.
1227  Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE,
1229  // Create the descriptor array for the arguments object.
1230  Handle<DescriptorArray> descriptors = factory->NewDescriptorArray(0, 3);
1231  DescriptorArray::WhitenessWitness witness(*descriptors);
1232  map->set_instance_descriptors(*descriptors);
1233 
1234  { // length
1235  FieldDescriptor d(
1236  *factory->length_string(), 0, DONT_ENUM, Representation::Tagged());
1237  map->AppendDescriptor(&d, witness);
1238  }
1239  { // callee
1240  CallbacksDescriptor d(*factory->callee_string(),
1241  *callee,
1242  attributes);
1243  map->AppendDescriptor(&d, witness);
1244  }
1245  { // caller
1246  CallbacksDescriptor d(*factory->caller_string(),
1247  *caller,
1248  attributes);
1249  map->AppendDescriptor(&d, witness);
1250  }
1251 
1252  map->set_function_with_prototype(true);
1253  map->set_prototype(native_context()->object_function()->prototype());
1254  map->set_pre_allocated_property_fields(1);
1255  map->set_inobject_properties(1);
1256 
1257  // Copy constructor from the sloppy arguments boilerplate.
1258  map->set_constructor(
1259  native_context()->sloppy_arguments_boilerplate()->map()->constructor());
1260 
1261  // Allocate the arguments boilerplate object.
1262  Handle<JSObject> result = factory->NewJSObjectFromMap(map);
1263  native_context()->set_strict_arguments_boilerplate(*result);
1264 
1265  // Add length property only for strict mode boilerplate.
1266  CHECK_NOT_EMPTY_HANDLE(isolate,
1268  result, factory->length_string(),
1269  factory->undefined_value(), DONT_ENUM));
1270 
1271 #ifdef DEBUG
1272  LookupResult lookup(isolate);
1273  result->LocalLookup(heap->length_string(), &lookup);
1274  ASSERT(lookup.IsField());
1275  ASSERT(lookup.GetFieldIndex().field_index() == Heap::kArgumentsLengthIndex);
1276 
1277  ASSERT(result->map()->inobject_properties() > Heap::kArgumentsLengthIndex);
1278 
1279  // Check the state of the object.
1280  ASSERT(result->HasFastProperties());
1281  ASSERT(result->HasFastObjectElements());
1282 #endif
1283  }
1284 
1285  { // --- context extension
1286  // Create a function for the context extension objects.
1287  Handle<Code> code = Handle<Code>(
1288  isolate->builtins()->builtin(Builtins::kIllegal));
1289  Handle<JSFunction> context_extension_fun =
1290  factory->NewFunction(factory->empty_string(),
1293  code,
1294  true);
1295 
1296  Handle<String> name = factory->InternalizeOneByteString(
1297  STATIC_ASCII_VECTOR("context_extension"));
1298  context_extension_fun->shared()->set_instance_class_name(*name);
1299  native_context()->set_context_extension_function(*context_extension_fun);
1300  }
1301 
1302 
1303  {
1304  // Set up the call-as-function delegate.
1305  Handle<Code> code =
1306  Handle<Code>(isolate->builtins()->builtin(
1307  Builtins::kHandleApiCallAsFunction));
1308  Handle<JSFunction> delegate =
1309  factory->NewFunction(factory->empty_string(), JS_OBJECT_TYPE,
1310  JSObject::kHeaderSize, code, true);
1311  native_context()->set_call_as_function_delegate(*delegate);
1312  delegate->shared()->DontAdaptArguments();
1313  }
1314 
1315  {
1316  // Set up the call-as-constructor delegate.
1317  Handle<Code> code =
1318  Handle<Code>(isolate->builtins()->builtin(
1319  Builtins::kHandleApiCallAsConstructor));
1320  Handle<JSFunction> delegate =
1321  factory->NewFunction(factory->empty_string(), JS_OBJECT_TYPE,
1322  JSObject::kHeaderSize, code, true);
1323  native_context()->set_call_as_constructor_delegate(*delegate);
1324  delegate->shared()->DontAdaptArguments();
1325  }
1326 
1327  // Initialize the embedder data slot.
1328  Handle<FixedArray> embedder_data = factory->NewFixedArray(3);
1329  native_context()->set_embedder_data(*embedder_data);
1330 }
1331 
1332 
1333 Handle<JSFunction> Genesis::InstallTypedArray(
1334  const char* name, ElementsKind elementsKind) {
1335  Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1336  Handle<JSFunction> result = InstallFunction(global, name, JS_TYPED_ARRAY_TYPE,
1337  JSTypedArray::kSize, isolate()->initial_object_prototype(),
1338  Builtins::kIllegal, false, true);
1339 
1340  Handle<Map> initial_map = isolate()->factory()->NewMap(
1342  result->set_initial_map(*initial_map);
1343  initial_map->set_constructor(*result);
1344  return result;
1345 }
1346 
1347 
1348 void Genesis::InitializeExperimentalGlobal() {
1349  Handle<JSObject> global = Handle<JSObject>(native_context()->global_object());
1350 
1351  // TODO(mstarzinger): Move this into Genesis::InitializeGlobal once we no
1352  // longer need to live behind flags, so functions get added to the snapshot.
1353 
1354  if (FLAG_harmony_symbols) {
1355  // --- S y m b o l ---
1356  Handle<JSFunction> symbol_fun =
1357  InstallFunction(global, "Symbol", JS_VALUE_TYPE, JSValue::kSize,
1358  isolate()->initial_object_prototype(),
1359  Builtins::kIllegal, true, true);
1360  native_context()->set_symbol_function(*symbol_fun);
1361  }
1362 
1363  if (FLAG_harmony_collections) {
1364  { // -- M a p
1365  InstallFunction(global, "Map", JS_MAP_TYPE, JSMap::kSize,
1366  isolate()->initial_object_prototype(),
1367  Builtins::kIllegal, true, true);
1368  }
1369  { // -- S e t
1370  InstallFunction(global, "Set", JS_SET_TYPE, JSSet::kSize,
1371  isolate()->initial_object_prototype(),
1372  Builtins::kIllegal, true, true);
1373  }
1374  }
1375 
1376  if (FLAG_harmony_generators) {
1377  // Create generator meta-objects and install them on the builtins object.
1378  Handle<JSObject> builtins(native_context()->builtins());
1379  Handle<JSObject> generator_object_prototype =
1380  factory()->NewJSObject(isolate()->object_function(), TENURED);
1381  Handle<JSFunction> generator_function_prototype =
1382  InstallFunction(builtins, "GeneratorFunctionPrototype",
1384  generator_object_prototype, Builtins::kIllegal,
1385  false, false);
1386  InstallFunction(builtins, "GeneratorFunction",
1388  generator_function_prototype, Builtins::kIllegal,
1389  false, false);
1390 
1391  // Create maps for generator functions and their prototypes. Store those
1392  // maps in the native context.
1393  Handle<Map> function_map(native_context()->sloppy_function_map());
1394  Handle<Map> generator_function_map = factory()->CopyMap(function_map);
1395  generator_function_map->set_prototype(*generator_function_prototype);
1396  native_context()->set_sloppy_generator_function_map(
1397  *generator_function_map);
1398 
1399  Handle<Map> strict_mode_function_map(
1400  native_context()->strict_function_map());
1401  Handle<Map> strict_mode_generator_function_map = factory()->CopyMap(
1402  strict_mode_function_map);
1403  strict_mode_generator_function_map->set_prototype(
1404  *generator_function_prototype);
1405  native_context()->set_strict_generator_function_map(
1406  *strict_mode_generator_function_map);
1407 
1408  Handle<Map> object_map(native_context()->object_function()->initial_map());
1409  Handle<Map> generator_object_prototype_map = factory()->CopyMap(
1410  object_map, 0);
1411  generator_object_prototype_map->set_prototype(
1412  *generator_object_prototype);
1413  native_context()->set_generator_object_prototype_map(
1414  *generator_object_prototype_map);
1415 
1416  // Create a map for generator result objects.
1417  ASSERT(object_map->inobject_properties() == 0);
1419  Handle<Map> generator_result_map = factory()->CopyMap(object_map,
1421  ASSERT(generator_result_map->inobject_properties() ==
1423 
1424  Handle<DescriptorArray> descriptors = factory()->NewDescriptorArray(0,
1426  DescriptorArray::WhitenessWitness witness(*descriptors);
1427  generator_result_map->set_instance_descriptors(*descriptors);
1428 
1429  Handle<String> value_string = factory()->InternalizeOneByteString(
1430  STATIC_ASCII_VECTOR("value"));
1431  FieldDescriptor value_descr(*value_string,
1433  NONE,
1435  generator_result_map->AppendDescriptor(&value_descr, witness);
1436 
1437  Handle<String> done_string = factory()->InternalizeOneByteString(
1438  STATIC_ASCII_VECTOR("done"));
1439  FieldDescriptor done_descr(*done_string,
1441  NONE,
1443  generator_result_map->AppendDescriptor(&done_descr, witness);
1444 
1445  generator_result_map->set_unused_property_fields(0);
1447  generator_result_map->instance_size());
1448  native_context()->set_generator_result_map(*generator_result_map);
1449  }
1450 }
1451 
1452 
1453 bool Genesis::CompileBuiltin(Isolate* isolate, int index) {
1454  Vector<const char> name = Natives::GetScriptName(index);
1455  Handle<String> source_code =
1456  isolate->bootstrapper()->NativesSourceLookup(index);
1457  return CompileNative(isolate, name, source_code);
1458 }
1459 
1460 
1461 bool Genesis::CompileExperimentalBuiltin(Isolate* isolate, int index) {
1462  Vector<const char> name = ExperimentalNatives::GetScriptName(index);
1463  Factory* factory = isolate->factory();
1464  Handle<String> source_code =
1465  factory->NewStringFromAscii(
1467  RETURN_IF_EMPTY_HANDLE_VALUE(isolate, source_code, false);
1468  return CompileNative(isolate, name, source_code);
1469 }
1470 
1471 
1472 bool Genesis::CompileNative(Isolate* isolate,
1473  Vector<const char> name,
1474  Handle<String> source) {
1475  HandleScope scope(isolate);
1476 #ifdef ENABLE_DEBUGGER_SUPPORT
1477  isolate->debugger()->set_compiling_natives(true);
1478 #endif
1479  // During genesis, the boilerplate for stack overflow won't work until the
1480  // environment has been at least partially initialized. Add a stack check
1481  // before entering JS code to catch overflow early.
1482  StackLimitCheck check(isolate);
1483  if (check.HasOverflowed()) return false;
1484 
1485  bool result = CompileScriptCached(isolate,
1486  name,
1487  source,
1488  NULL,
1489  NULL,
1490  Handle<Context>(isolate->context()),
1491  true);
1492  ASSERT(isolate->has_pending_exception() != result);
1493  if (!result) isolate->clear_pending_exception();
1494 #ifdef ENABLE_DEBUGGER_SUPPORT
1495  isolate->debugger()->set_compiling_natives(false);
1496 #endif
1497  return result;
1498 }
1499 
1500 
1501 bool Genesis::CompileScriptCached(Isolate* isolate,
1502  Vector<const char> name,
1503  Handle<String> source,
1504  SourceCodeCache* cache,
1505  v8::Extension* extension,
1506  Handle<Context> top_context,
1507  bool use_runtime_context) {
1508  Factory* factory = isolate->factory();
1509  HandleScope scope(isolate);
1510  Handle<SharedFunctionInfo> function_info;
1511 
1512  // If we can't find the function in the cache, we compile a new
1513  // function and insert it into the cache.
1514  if (cache == NULL || !cache->Lookup(name, &function_info)) {
1515  ASSERT(source->IsOneByteRepresentation());
1516  Handle<String> script_name = factory->NewStringFromUtf8(name);
1517  ASSERT(!script_name.is_null());
1518  function_info = Compiler::CompileScript(
1519  source,
1520  script_name,
1521  0,
1522  0,
1523  false,
1524  top_context,
1525  extension,
1526  NULL,
1528  use_runtime_context ? NATIVES_CODE : NOT_NATIVES_CODE);
1529  if (function_info.is_null()) return false;
1530  if (cache != NULL) cache->Add(name, function_info);
1531  }
1532 
1533  // Set up the function context. Conceptually, we should clone the
1534  // function before overwriting the context but since we're in a
1535  // single-threaded environment it is not strictly necessary.
1536  ASSERT(top_context->IsNativeContext());
1537  Handle<Context> context =
1538  Handle<Context>(use_runtime_context
1539  ? Handle<Context>(top_context->runtime_context())
1540  : top_context);
1541  Handle<JSFunction> fun =
1542  factory->NewFunctionFromSharedFunctionInfo(function_info, context);
1543 
1544  // Call function using either the runtime object or the global
1545  // object as the receiver. Provide no parameters.
1546  Handle<Object> receiver =
1547  Handle<Object>(use_runtime_context
1548  ? top_context->builtins()
1549  : top_context->global_object(),
1550  isolate);
1551  bool has_pending_exception;
1552  Execution::Call(isolate, fun, receiver, 0, NULL, &has_pending_exception);
1553  if (has_pending_exception) return false;
1554  return true;
1555 }
1556 
1557 
1558 #define INSTALL_NATIVE(Type, name, var) \
1559  Handle<String> var##_name = \
1560  factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR(name)); \
1561  Object* var##_native = \
1562  native_context()->builtins()->GetPropertyNoExceptionThrown( \
1563  *var##_name); \
1564  native_context()->set_##var(Type::cast(var##_native));
1565 
1566 
1567 void Genesis::InstallNativeFunctions() {
1568  HandleScope scope(isolate());
1569  INSTALL_NATIVE(JSFunction, "CreateDate", create_date_fun);
1570 
1571  INSTALL_NATIVE(JSFunction, "ToNumber", to_number_fun);
1572  INSTALL_NATIVE(JSFunction, "ToString", to_string_fun);
1573  INSTALL_NATIVE(JSFunction, "ToDetailString", to_detail_string_fun);
1574  INSTALL_NATIVE(JSFunction, "ToObject", to_object_fun);
1575  INSTALL_NATIVE(JSFunction, "ToInteger", to_integer_fun);
1576  INSTALL_NATIVE(JSFunction, "ToUint32", to_uint32_fun);
1577  INSTALL_NATIVE(JSFunction, "ToInt32", to_int32_fun);
1578 
1579  INSTALL_NATIVE(JSFunction, "GlobalEval", global_eval_fun);
1580  INSTALL_NATIVE(JSFunction, "Instantiate", instantiate_fun);
1581  INSTALL_NATIVE(JSFunction, "ConfigureTemplateInstance",
1582  configure_instance_fun);
1583  INSTALL_NATIVE(JSFunction, "GetStackTraceLine", get_stack_trace_line_fun);
1584  INSTALL_NATIVE(JSObject, "functionCache", function_cache);
1585  INSTALL_NATIVE(JSFunction, "ToCompletePropertyDescriptor",
1586  to_complete_property_descriptor);
1587 
1588  INSTALL_NATIVE(JSFunction, "IsPromise", is_promise);
1589  INSTALL_NATIVE(JSFunction, "PromiseCreate", promise_create);
1590  INSTALL_NATIVE(JSFunction, "PromiseResolve", promise_resolve);
1591  INSTALL_NATIVE(JSFunction, "PromiseReject", promise_reject);
1592  INSTALL_NATIVE(JSFunction, "PromiseChain", promise_chain);
1593  INSTALL_NATIVE(JSFunction, "PromiseCatch", promise_catch);
1594 
1595  INSTALL_NATIVE(JSFunction, "NotifyChange", observers_notify_change);
1596  INSTALL_NATIVE(JSFunction, "EnqueueSpliceRecord", observers_enqueue_splice);
1597  INSTALL_NATIVE(JSFunction, "BeginPerformSplice",
1598  observers_begin_perform_splice);
1599  INSTALL_NATIVE(JSFunction, "EndPerformSplice",
1600  observers_end_perform_splice);
1601 }
1602 
1603 
1604 void Genesis::InstallExperimentalNativeFunctions() {
1605  INSTALL_NATIVE(JSFunction, "RunMicrotasks", run_microtasks);
1606  INSTALL_NATIVE(JSFunction, "EnqueueExternalMicrotask",
1607  enqueue_external_microtask);
1608 
1609  if (FLAG_harmony_proxies) {
1610  INSTALL_NATIVE(JSFunction, "DerivedHasTrap", derived_has_trap);
1611  INSTALL_NATIVE(JSFunction, "DerivedGetTrap", derived_get_trap);
1612  INSTALL_NATIVE(JSFunction, "DerivedSetTrap", derived_set_trap);
1613  INSTALL_NATIVE(JSFunction, "ProxyEnumerate", proxy_enumerate);
1614  }
1615 }
1616 
1617 #undef INSTALL_NATIVE
1618 
1619 
1620 Handle<JSFunction> Genesis::InstallInternalArray(
1621  Handle<JSBuiltinsObject> builtins,
1622  const char* name,
1623  ElementsKind elements_kind) {
1624  // --- I n t e r n a l A r r a y ---
1625  // An array constructor on the builtins object that works like
1626  // the public Array constructor, except that its prototype
1627  // doesn't inherit from Object.prototype.
1628  // To be used only for internal work by builtins. Instances
1629  // must not be leaked to user code.
1630  Handle<JSFunction> array_function =
1631  InstallFunction(builtins,
1632  name,
1633  JS_ARRAY_TYPE,
1635  isolate()->initial_object_prototype(),
1636  Builtins::kInternalArrayCode,
1637  true, true);
1638  Handle<JSObject> prototype =
1639  factory()->NewJSObject(isolate()->object_function(), TENURED);
1640  Accessors::FunctionSetPrototype(array_function, prototype);
1641 
1642  InternalArrayConstructorStub internal_array_constructor_stub(isolate());
1643  Handle<Code> code = internal_array_constructor_stub.GetCode(isolate());
1644  array_function->shared()->set_construct_stub(*code);
1645  array_function->shared()->DontAdaptArguments();
1646 
1647  Handle<Map> original_map(array_function->initial_map());
1648  Handle<Map> initial_map = factory()->CopyMap(original_map);
1649  initial_map->set_elements_kind(elements_kind);
1650  array_function->set_initial_map(*initial_map);
1651 
1652  // Make "length" magic on instances.
1653  Handle<DescriptorArray> array_descriptors(
1654  factory()->NewDescriptorArray(0, 1));
1655  DescriptorArray::WhitenessWitness witness(*array_descriptors);
1656 
1657  Handle<Foreign> array_length(factory()->NewForeign(
1658  &Accessors::ArrayLength));
1659  PropertyAttributes attribs = static_cast<PropertyAttributes>(
1661  initial_map->set_instance_descriptors(*array_descriptors);
1662 
1663  { // Add length.
1664  CallbacksDescriptor d(
1665  *factory()->length_string(), *array_length, attribs);
1666  array_function->initial_map()->AppendDescriptor(&d, witness);
1667  }
1668 
1669  return array_function;
1670 }
1671 
1672 
1673 bool Genesis::InstallNatives() {
1674  HandleScope scope(isolate());
1675 
1676  // Create a function for the builtins object. Allocate space for the
1677  // JavaScript builtins, a reference to the builtins object
1678  // (itself) and a reference to the native_context directly in the object.
1679  Handle<Code> code = Handle<Code>(
1680  isolate()->builtins()->builtin(Builtins::kIllegal));
1681  Handle<JSFunction> builtins_fun =
1682  factory()->NewFunction(factory()->empty_string(),
1684  JSBuiltinsObject::kSize, code, true);
1685 
1686  Handle<String> name =
1687  factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("builtins"));
1688  builtins_fun->shared()->set_instance_class_name(*name);
1689  builtins_fun->initial_map()->set_dictionary_map(true);
1690  builtins_fun->initial_map()->set_prototype(heap()->null_value());
1691 
1692  // Allocate the builtins object.
1693  Handle<JSBuiltinsObject> builtins =
1694  Handle<JSBuiltinsObject>::cast(factory()->NewGlobalObject(builtins_fun));
1695  builtins->set_builtins(*builtins);
1696  builtins->set_native_context(*native_context());
1697  builtins->set_global_context(*native_context());
1698  builtins->set_global_receiver(*builtins);
1699  builtins->set_global_receiver(native_context()->global_proxy());
1700 
1701 
1702  // Set up the 'global' properties of the builtins object. The
1703  // 'global' property that refers to the global object is the only
1704  // way to get from code running in the builtins context to the
1705  // global object.
1706  static const PropertyAttributes attributes =
1707  static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
1708  Handle<String> global_string =
1709  factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("global"));
1710  Handle<Object> global_obj(native_context()->global_object(), isolate());
1711  CHECK_NOT_EMPTY_HANDLE(isolate(),
1713  builtins, global_string, global_obj, attributes));
1714  Handle<String> builtins_string =
1715  factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("builtins"));
1716  CHECK_NOT_EMPTY_HANDLE(isolate(),
1718  builtins, builtins_string, builtins, attributes));
1719 
1720  // Set up the reference from the global object to the builtins object.
1721  JSGlobalObject::cast(native_context()->global_object())->
1722  set_builtins(*builtins);
1723 
1724  // Create a bridge function that has context in the native context.
1725  Handle<JSFunction> bridge =
1726  factory()->NewFunction(factory()->empty_string(),
1727  factory()->undefined_value());
1728  ASSERT(bridge->context() == *isolate()->native_context());
1729 
1730  // Allocate the builtins context.
1731  Handle<Context> context =
1732  factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS, bridge);
1733  context->set_global_object(*builtins); // override builtins global object
1734 
1735  native_context()->set_runtime_context(*context);
1736 
1737  { // -- S c r i p t
1738  // Builtin functions for Script.
1739  Handle<JSFunction> script_fun =
1740  InstallFunction(builtins, "Script", JS_VALUE_TYPE, JSValue::kSize,
1741  isolate()->initial_object_prototype(),
1742  Builtins::kIllegal, false, false);
1743  Handle<JSObject> prototype =
1744  factory()->NewJSObject(isolate()->object_function(), TENURED);
1745  Accessors::FunctionSetPrototype(script_fun, prototype);
1746  native_context()->set_script_function(*script_fun);
1747 
1748  Handle<Map> script_map = Handle<Map>(script_fun->initial_map());
1749 
1750  Handle<DescriptorArray> script_descriptors(
1751  factory()->NewDescriptorArray(0, 13));
1752  DescriptorArray::WhitenessWitness witness(*script_descriptors);
1753 
1754  Handle<Foreign> script_source(
1755  factory()->NewForeign(&Accessors::ScriptSource));
1756  Handle<Foreign> script_name(factory()->NewForeign(&Accessors::ScriptName));
1757  Handle<String> id_string(factory()->InternalizeOneByteString(
1758  STATIC_ASCII_VECTOR("id")));
1759  Handle<Foreign> script_id(factory()->NewForeign(&Accessors::ScriptId));
1760  Handle<String> line_offset_string(
1761  factory()->InternalizeOneByteString(
1762  STATIC_ASCII_VECTOR("line_offset")));
1763  Handle<Foreign> script_line_offset(
1764  factory()->NewForeign(&Accessors::ScriptLineOffset));
1765  Handle<String> column_offset_string(
1766  factory()->InternalizeOneByteString(
1767  STATIC_ASCII_VECTOR("column_offset")));
1768  Handle<Foreign> script_column_offset(
1769  factory()->NewForeign(&Accessors::ScriptColumnOffset));
1770  Handle<String> type_string(factory()->InternalizeOneByteString(
1771  STATIC_ASCII_VECTOR("type")));
1772  Handle<Foreign> script_type(factory()->NewForeign(&Accessors::ScriptType));
1773  Handle<String> compilation_type_string(
1774  factory()->InternalizeOneByteString(
1775  STATIC_ASCII_VECTOR("compilation_type")));
1776  Handle<Foreign> script_compilation_type(
1777  factory()->NewForeign(&Accessors::ScriptCompilationType));
1778  Handle<String> line_ends_string(factory()->InternalizeOneByteString(
1779  STATIC_ASCII_VECTOR("line_ends")));
1780  Handle<Foreign> script_line_ends(
1781  factory()->NewForeign(&Accessors::ScriptLineEnds));
1782  Handle<String> context_data_string(
1783  factory()->InternalizeOneByteString(
1784  STATIC_ASCII_VECTOR("context_data")));
1785  Handle<Foreign> script_context_data(
1786  factory()->NewForeign(&Accessors::ScriptContextData));
1787  Handle<String> eval_from_script_string(
1788  factory()->InternalizeOneByteString(
1789  STATIC_ASCII_VECTOR("eval_from_script")));
1790  Handle<Foreign> script_eval_from_script(
1791  factory()->NewForeign(&Accessors::ScriptEvalFromScript));
1792  Handle<String> eval_from_script_position_string(
1793  factory()->InternalizeOneByteString(
1794  STATIC_ASCII_VECTOR("eval_from_script_position")));
1795  Handle<Foreign> script_eval_from_script_position(
1796  factory()->NewForeign(&Accessors::ScriptEvalFromScriptPosition));
1797  Handle<String> eval_from_function_name_string(
1798  factory()->InternalizeOneByteString(
1799  STATIC_ASCII_VECTOR("eval_from_function_name")));
1800  Handle<Foreign> script_eval_from_function_name(
1801  factory()->NewForeign(&Accessors::ScriptEvalFromFunctionName));
1802  PropertyAttributes attribs =
1803  static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
1804  script_map->set_instance_descriptors(*script_descriptors);
1805 
1806  {
1807  CallbacksDescriptor d(
1808  *factory()->source_string(), *script_source, attribs);
1809  script_map->AppendDescriptor(&d, witness);
1810  }
1811 
1812  {
1813  CallbacksDescriptor d(*factory()->name_string(), *script_name, attribs);
1814  script_map->AppendDescriptor(&d, witness);
1815  }
1816 
1817  {
1818  CallbacksDescriptor d(*id_string, *script_id, attribs);
1819  script_map->AppendDescriptor(&d, witness);
1820  }
1821 
1822  {
1823  CallbacksDescriptor d(*line_offset_string, *script_line_offset, attribs);
1824  script_map->AppendDescriptor(&d, witness);
1825  }
1826 
1827  {
1828  CallbacksDescriptor d(
1829  *column_offset_string, *script_column_offset, attribs);
1830  script_map->AppendDescriptor(&d, witness);
1831  }
1832 
1833  {
1834  CallbacksDescriptor d(*type_string, *script_type, attribs);
1835  script_map->AppendDescriptor(&d, witness);
1836  }
1837 
1838  {
1839  CallbacksDescriptor d(
1840  *compilation_type_string, *script_compilation_type, attribs);
1841  script_map->AppendDescriptor(&d, witness);
1842  }
1843 
1844  {
1845  CallbacksDescriptor d(*line_ends_string, *script_line_ends, attribs);
1846  script_map->AppendDescriptor(&d, witness);
1847  }
1848 
1849  {
1850  CallbacksDescriptor d(
1851  *context_data_string, *script_context_data, attribs);
1852  script_map->AppendDescriptor(&d, witness);
1853  }
1854 
1855  {
1856  CallbacksDescriptor d(
1857  *eval_from_script_string, *script_eval_from_script, attribs);
1858  script_map->AppendDescriptor(&d, witness);
1859  }
1860 
1861  {
1862  CallbacksDescriptor d(
1863  *eval_from_script_position_string,
1864  *script_eval_from_script_position,
1865  attribs);
1866  script_map->AppendDescriptor(&d, witness);
1867  }
1868 
1869  {
1870  CallbacksDescriptor d(
1871  *eval_from_function_name_string,
1872  *script_eval_from_function_name,
1873  attribs);
1874  script_map->AppendDescriptor(&d, witness);
1875  }
1876 
1877  // Allocate the empty script.
1878  Handle<Script> script = factory()->NewScript(factory()->empty_string());
1879  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
1880  heap()->public_set_empty_script(*script);
1881  }
1882  {
1883  // Builtin function for OpaqueReference -- a JSValue-based object,
1884  // that keeps its field isolated from JavaScript code. It may store
1885  // objects, that JavaScript code may not access.
1886  Handle<JSFunction> opaque_reference_fun =
1887  InstallFunction(builtins, "OpaqueReference", JS_VALUE_TYPE,
1889  isolate()->initial_object_prototype(),
1890  Builtins::kIllegal, false, false);
1891  Handle<JSObject> prototype =
1892  factory()->NewJSObject(isolate()->object_function(), TENURED);
1893  Accessors::FunctionSetPrototype(opaque_reference_fun, prototype);
1894  native_context()->set_opaque_reference_function(*opaque_reference_fun);
1895  }
1896 
1897  // InternalArrays should not use Smi-Only array optimizations. There are too
1898  // many places in the C++ runtime code (e.g. RegEx) that assume that
1899  // elements in InternalArrays can be set to non-Smi values without going
1900  // through a common bottleneck that would make the SMI_ONLY -> FAST_ELEMENT
1901  // transition easy to trap. Moreover, they rarely are smi-only.
1902  {
1903  Handle<JSFunction> array_function =
1904  InstallInternalArray(builtins, "InternalArray", FAST_HOLEY_ELEMENTS);
1905  native_context()->set_internal_array_function(*array_function);
1906  }
1907 
1908  {
1909  InstallInternalArray(builtins, "InternalPackedArray", FAST_ELEMENTS);
1910  }
1911 
1912  if (FLAG_disable_native_files) {
1913  PrintF("Warning: Running without installed natives!\n");
1914  return true;
1915  }
1916 
1917  // Install natives.
1918  for (int i = Natives::GetDebuggerCount();
1920  i++) {
1921  if (!CompileBuiltin(isolate(), i)) return false;
1922  // TODO(ager): We really only need to install the JS builtin
1923  // functions on the builtins object after compiling and running
1924  // runtime.js.
1925  if (!InstallJSBuiltins(builtins)) return false;
1926  }
1927 
1928  InstallNativeFunctions();
1929 
1930  // Store the map for the string prototype after the natives has been compiled
1931  // and the String function has been set up.
1932  Handle<JSFunction> string_function(native_context()->string_function());
1934  string_function->initial_map()->prototype())->HasFastProperties());
1935  native_context()->set_string_function_prototype_map(
1936  HeapObject::cast(string_function->initial_map()->prototype())->map());
1937 
1938  // Install Function.prototype.call and apply.
1939  { Handle<String> key = factory()->function_class_string();
1940  Handle<JSFunction> function =
1942  GetProperty(isolate(), isolate()->global_object(), key));
1943  Handle<JSObject> proto =
1944  Handle<JSObject>(JSObject::cast(function->instance_prototype()));
1945 
1946  // Install the call and the apply functions.
1947  Handle<JSFunction> call =
1948  InstallFunction(proto, "call", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1949  Handle<JSObject>::null(),
1950  Builtins::kFunctionCall,
1951  false, false);
1952  Handle<JSFunction> apply =
1953  InstallFunction(proto, "apply", JS_OBJECT_TYPE, JSObject::kHeaderSize,
1954  Handle<JSObject>::null(),
1955  Builtins::kFunctionApply,
1956  false, false);
1957 
1958  // Make sure that Function.prototype.call appears to be compiled.
1959  // The code will never be called, but inline caching for call will
1960  // only work if it appears to be compiled.
1961  call->shared()->DontAdaptArguments();
1962  ASSERT(call->is_compiled());
1963 
1964  // Set the expected parameters for apply to 2; required by builtin.
1965  apply->shared()->set_formal_parameter_count(2);
1966 
1967  // Set the lengths for the functions to satisfy ECMA-262.
1968  call->shared()->set_length(1);
1969  apply->shared()->set_length(2);
1970  }
1971 
1972  InstallBuiltinFunctionIds();
1973 
1974  // Create a constructor for RegExp results (a variant of Array that
1975  // predefines the two properties index and match).
1976  {
1977  // RegExpResult initial map.
1978 
1979  // Find global.Array.prototype to inherit from.
1980  Handle<JSFunction> array_constructor(native_context()->array_function());
1981  Handle<JSObject> array_prototype(
1982  JSObject::cast(array_constructor->instance_prototype()));
1983 
1984  // Add initial map.
1985  Handle<Map> initial_map =
1986  factory()->NewMap(JS_ARRAY_TYPE, JSRegExpResult::kSize);
1987  initial_map->set_constructor(*array_constructor);
1988 
1989  // Set prototype on map.
1990  initial_map->set_non_instance_prototype(false);
1991  initial_map->set_prototype(*array_prototype);
1992 
1993  // Update map with length accessor from Array and add "index" and "input".
1994  Handle<DescriptorArray> reresult_descriptors =
1995  factory()->NewDescriptorArray(0, 3);
1996  DescriptorArray::WhitenessWitness witness(*reresult_descriptors);
1997  initial_map->set_instance_descriptors(*reresult_descriptors);
1998 
1999  {
2000  JSFunction* array_function = native_context()->array_function();
2001  Handle<DescriptorArray> array_descriptors(
2002  array_function->initial_map()->instance_descriptors());
2003  String* length = heap()->length_string();
2004  int old = array_descriptors->SearchWithCache(
2005  length, array_function->initial_map());
2007  CallbacksDescriptor desc(length,
2008  array_descriptors->GetValue(old),
2009  array_descriptors->GetDetails(old).attributes());
2010  initial_map->AppendDescriptor(&desc, witness);
2011  }
2012  {
2013  FieldDescriptor index_field(heap()->index_string(),
2015  NONE,
2017  initial_map->AppendDescriptor(&index_field, witness);
2018  }
2019 
2020  {
2021  FieldDescriptor input_field(heap()->input_string(),
2023  NONE,
2025  initial_map->AppendDescriptor(&input_field, witness);
2026  }
2027 
2028  initial_map->set_inobject_properties(2);
2029  initial_map->set_pre_allocated_property_fields(2);
2030  initial_map->set_unused_property_fields(0);
2031 
2032  native_context()->set_regexp_result_map(*initial_map);
2033  }
2034 
2035 #ifdef VERIFY_HEAP
2036  builtins->Verify();
2037 #endif
2038 
2039  return true;
2040 }
2041 
2042 
2043 #define INSTALL_EXPERIMENTAL_NATIVE(i, flag, file) \
2044  if (FLAG_harmony_##flag && \
2045  strcmp(ExperimentalNatives::GetScriptName(i).start(), \
2046  "native " file) == 0) { \
2047  if (!CompileExperimentalBuiltin(isolate(), i)) return false; \
2048  }
2049 
2050 
2051 bool Genesis::InstallExperimentalNatives() {
2054  i++) {
2055  INSTALL_EXPERIMENTAL_NATIVE(i, symbols, "symbol.js")
2056  INSTALL_EXPERIMENTAL_NATIVE(i, proxies, "proxy.js")
2057  INSTALL_EXPERIMENTAL_NATIVE(i, collections, "collection.js")
2058  INSTALL_EXPERIMENTAL_NATIVE(i, generators, "generator.js")
2059  INSTALL_EXPERIMENTAL_NATIVE(i, iteration, "array-iterator.js")
2060  INSTALL_EXPERIMENTAL_NATIVE(i, strings, "harmony-string.js")
2061  INSTALL_EXPERIMENTAL_NATIVE(i, arrays, "harmony-array.js")
2062  INSTALL_EXPERIMENTAL_NATIVE(i, maths, "harmony-math.js")
2063  }
2064 
2065  InstallExperimentalNativeFunctions();
2066  InstallExperimentalBuiltinFunctionIds();
2067  return true;
2068 }
2069 
2070 
2071 static Handle<JSObject> ResolveBuiltinIdHolder(
2072  Handle<Context> native_context,
2073  const char* holder_expr) {
2074  Isolate* isolate = native_context->GetIsolate();
2075  Factory* factory = isolate->factory();
2076  Handle<GlobalObject> global(native_context->global_object());
2077  const char* period_pos = strchr(holder_expr, '.');
2078  if (period_pos == NULL) {
2080  isolate, global, factory->InternalizeUtf8String(holder_expr)));
2081  }
2082  ASSERT_EQ(".prototype", period_pos);
2083  Vector<const char> property(holder_expr,
2084  static_cast<int>(period_pos - holder_expr));
2085  Handle<String> property_string = factory->InternalizeUtf8String(property);
2086  ASSERT(!property_string.is_null());
2087  Handle<JSFunction> function = Handle<JSFunction>::cast(
2088  GetProperty(isolate, global, property_string));
2089  return Handle<JSObject>(JSObject::cast(function->prototype()));
2090 }
2091 
2092 
2093 static void InstallBuiltinFunctionId(Handle<JSObject> holder,
2094  const char* function_name,
2095  BuiltinFunctionId id) {
2096  Factory* factory = holder->GetIsolate()->factory();
2097  Handle<String> name = factory->InternalizeUtf8String(function_name);
2098  Object* function_object = holder->GetProperty(*name)->ToObjectUnchecked();
2099  Handle<JSFunction> function(JSFunction::cast(function_object));
2100  function->shared()->set_function_data(Smi::FromInt(id));
2101 }
2102 
2103 
2104 void Genesis::InstallBuiltinFunctionIds() {
2105  HandleScope scope(isolate());
2106 #define INSTALL_BUILTIN_ID(holder_expr, fun_name, name) \
2107  { \
2108  Handle<JSObject> holder = ResolveBuiltinIdHolder( \
2109  native_context(), #holder_expr); \
2110  BuiltinFunctionId id = k##name; \
2111  InstallBuiltinFunctionId(holder, #fun_name, id); \
2112  }
2114 #undef INSTALL_BUILTIN_ID
2115 }
2116 
2117 
2118 void Genesis::InstallExperimentalBuiltinFunctionIds() {
2119  HandleScope scope(isolate());
2120  if (FLAG_harmony_maths) {
2121  Handle<JSObject> holder = ResolveBuiltinIdHolder(native_context(), "Math");
2122  InstallBuiltinFunctionId(holder, "clz32", kMathClz32);
2123  }
2124 }
2125 
2126 
2127 // Do not forget to update macros.py with named constant
2128 // of cache id.
2129 #define JSFUNCTION_RESULT_CACHE_LIST(F) \
2130  F(16, native_context()->regexp_function())
2131 
2132 
2133 static FixedArray* CreateCache(int size, Handle<JSFunction> factory_function) {
2134  Factory* factory = factory_function->GetIsolate()->factory();
2135  // Caches are supposed to live for a long time, allocate in old space.
2136  int array_size = JSFunctionResultCache::kEntriesIndex + 2 * size;
2137  // Cannot use cast as object is not fully initialized yet.
2138  JSFunctionResultCache* cache = reinterpret_cast<JSFunctionResultCache*>(
2139  *factory->NewFixedArrayWithHoles(array_size, TENURED));
2140  cache->set(JSFunctionResultCache::kFactoryIndex, *factory_function);
2141  cache->MakeZeroSize();
2142  return cache;
2143 }
2144 
2145 
2146 void Genesis::InstallJSFunctionResultCaches() {
2147  const int kNumberOfCaches = 0 +
2148 #define F(size, func) + 1
2150 #undef F
2151  ;
2152 
2153  Handle<FixedArray> caches =
2154  factory()->NewFixedArray(kNumberOfCaches, TENURED);
2155 
2156  int index = 0;
2157 
2158 #define F(size, func) do { \
2159  FixedArray* cache = CreateCache((size), Handle<JSFunction>(func)); \
2160  caches->set(index++, cache); \
2161  } while (false)
2162 
2164 
2165 #undef F
2166 
2167  native_context()->set_jsfunction_result_caches(*caches);
2168 }
2169 
2170 
2171 void Genesis::InitializeNormalizedMapCaches() {
2172  Handle<FixedArray> array(
2173  factory()->NewFixedArray(NormalizedMapCache::kEntries, TENURED));
2174  native_context()->set_normalized_map_cache(NormalizedMapCache::cast(*array));
2175 }
2176 
2177 
2179  v8::ExtensionConfiguration* extensions) {
2180  BootstrapperActive active(this);
2181  SaveContext saved_context(isolate_);
2182  isolate_->set_context(*native_context);
2183  return Genesis::InstallExtensions(native_context, extensions) &&
2184  Genesis::InstallSpecialObjects(native_context);
2185 }
2186 
2187 
2188 bool Genesis::InstallSpecialObjects(Handle<Context> native_context) {
2189  Isolate* isolate = native_context->GetIsolate();
2190  Factory* factory = isolate->factory();
2191  HandleScope scope(isolate);
2193  native_context->global_object()));
2194  // Expose the natives in global if a name for it is specified.
2195  if (FLAG_expose_natives_as != NULL && strlen(FLAG_expose_natives_as) != 0) {
2196  Handle<String> natives =
2197  factory->InternalizeUtf8String(FLAG_expose_natives_as);
2199  global, natives, Handle<JSObject>(global->builtins()), DONT_ENUM);
2200  if (isolate->has_pending_exception()) return false;
2201  }
2202 
2203  Handle<Object> Error = GetProperty(global, "Error");
2204  if (Error->IsJSObject()) {
2205  Handle<String> name = factory->InternalizeOneByteString(
2206  STATIC_ASCII_VECTOR("stackTraceLimit"));
2207  Handle<Smi> stack_trace_limit(
2208  Smi::FromInt(FLAG_stack_trace_limit), isolate);
2210  Handle<JSObject>::cast(Error), name, stack_trace_limit, NONE);
2211  if (isolate->has_pending_exception()) return false;
2212  }
2213 
2214 #ifdef ENABLE_DEBUGGER_SUPPORT
2215  // Expose the debug global object in global if a name for it is specified.
2216  if (FLAG_expose_debug_as != NULL && strlen(FLAG_expose_debug_as) != 0) {
2217  Debug* debug = isolate->debug();
2218  // If loading fails we just bail out without installing the
2219  // debugger but without tanking the whole context.
2220  if (!debug->Load()) return true;
2221  // Set the security token for the debugger context to the same as
2222  // the shell native context to allow calling between these (otherwise
2223  // exposing debug global object doesn't make much sense).
2224  debug->debug_context()->set_security_token(
2225  native_context->security_token());
2226 
2227  Handle<String> debug_string =
2228  factory->InternalizeUtf8String(FLAG_expose_debug_as);
2229  Handle<Object> global_proxy(
2230  debug->debug_context()->global_proxy(), isolate);
2232  global, debug_string, global_proxy, DONT_ENUM);
2233  if (isolate->has_pending_exception()) return false;
2234  }
2235 #endif
2236  return true;
2237 }
2238 
2239 
2240 static uint32_t Hash(RegisteredExtension* extension) {
2241  return v8::internal::ComputePointerHash(extension);
2242 }
2243 
2244 
2245 static bool MatchRegisteredExtensions(void* key1, void* key2) {
2246  return key1 == key2;
2247 }
2248 
2249 Genesis::ExtensionStates::ExtensionStates()
2250  : map_(MatchRegisteredExtensions, 8) { }
2251 
2252 Genesis::ExtensionTraversalState Genesis::ExtensionStates::get_state(
2253  RegisteredExtension* extension) {
2254  i::HashMap::Entry* entry = map_.Lookup(extension, Hash(extension), false);
2255  if (entry == NULL) {
2256  return UNVISITED;
2257  }
2258  return static_cast<ExtensionTraversalState>(
2259  reinterpret_cast<intptr_t>(entry->value));
2260 }
2261 
2262 void Genesis::ExtensionStates::set_state(RegisteredExtension* extension,
2263  ExtensionTraversalState state) {
2264  map_.Lookup(extension, Hash(extension), true)->value =
2265  reinterpret_cast<void*>(static_cast<intptr_t>(state));
2266 }
2267 
2268 
2269 bool Genesis::InstallExtensions(Handle<Context> native_context,
2270  v8::ExtensionConfiguration* extensions) {
2271  Isolate* isolate = native_context->GetIsolate();
2272  ExtensionStates extension_states; // All extensions have state UNVISITED.
2273  return InstallAutoExtensions(isolate, &extension_states) &&
2274  (!FLAG_expose_free_buffer ||
2275  InstallExtension(isolate, "v8/free-buffer", &extension_states)) &&
2276  (!FLAG_expose_gc ||
2277  InstallExtension(isolate, "v8/gc", &extension_states)) &&
2278  (!FLAG_expose_externalize_string ||
2279  InstallExtension(isolate, "v8/externalize", &extension_states)) &&
2280  (!FLAG_track_gc_object_stats ||
2281  InstallExtension(isolate, "v8/statistics", &extension_states)) &&
2282  (!FLAG_expose_trigger_failure ||
2283  InstallExtension(isolate, "v8/trigger-failure", &extension_states)) &&
2284  InstallRequestedExtensions(isolate, extensions, &extension_states);
2285 }
2286 
2287 
2288 bool Genesis::InstallAutoExtensions(Isolate* isolate,
2289  ExtensionStates* extension_states) {
2291  it != NULL;
2292  it = it->next()) {
2293  if (it->extension()->auto_enable() &&
2294  !InstallExtension(isolate, it, extension_states)) {
2295  return false;
2296  }
2297  }
2298  return true;
2299 }
2300 
2301 
2302 bool Genesis::InstallRequestedExtensions(Isolate* isolate,
2303  v8::ExtensionConfiguration* extensions,
2304  ExtensionStates* extension_states) {
2305  for (const char** it = extensions->begin(); it != extensions->end(); ++it) {
2306  if (!InstallExtension(isolate, *it, extension_states)) return false;
2307  }
2308  return true;
2309 }
2310 
2311 
2312 // Installs a named extension. This methods is unoptimized and does
2313 // not scale well if we want to support a large number of extensions.
2314 bool Genesis::InstallExtension(Isolate* isolate,
2315  const char* name,
2316  ExtensionStates* extension_states) {
2318  it != NULL;
2319  it = it->next()) {
2320  if (strcmp(name, it->extension()->name()) == 0) {
2321  return InstallExtension(isolate, it, extension_states);
2322  }
2323  }
2324  return Utils::ApiCheck(false,
2325  "v8::Context::New()",
2326  "Cannot find required extension");
2327 }
2328 
2329 
2330 bool Genesis::InstallExtension(Isolate* isolate,
2331  v8::RegisteredExtension* current,
2332  ExtensionStates* extension_states) {
2333  HandleScope scope(isolate);
2334 
2335  if (extension_states->get_state(current) == INSTALLED) return true;
2336  // The current node has already been visited so there must be a
2337  // cycle in the dependency graph; fail.
2338  if (!Utils::ApiCheck(extension_states->get_state(current) != VISITED,
2339  "v8::Context::New()",
2340  "Circular extension dependency")) {
2341  return false;
2342  }
2343  ASSERT(extension_states->get_state(current) == UNVISITED);
2344  extension_states->set_state(current, VISITED);
2345  v8::Extension* extension = current->extension();
2346  // Install the extension's dependencies
2347  for (int i = 0; i < extension->dependency_count(); i++) {
2348  if (!InstallExtension(isolate,
2349  extension->dependencies()[i],
2350  extension_states)) {
2351  return false;
2352  }
2353  }
2354  Handle<String> source_code =
2355  isolate->factory()->NewExternalStringFromAscii(extension->source());
2356  // We do not expect this to throw an exception. Change this if it does.
2357  CHECK_NOT_EMPTY_HANDLE(isolate, source_code);
2358  bool result = CompileScriptCached(isolate,
2359  CStrVector(extension->name()),
2360  source_code,
2361  isolate->bootstrapper()->extensions_cache(),
2362  extension,
2363  Handle<Context>(isolate->context()),
2364  false);
2365  ASSERT(isolate->has_pending_exception() != result);
2366  if (!result) {
2367  // We print out the name of the extension that fail to install.
2368  // When an error is thrown during bootstrapping we automatically print
2369  // the line number at which this happened to the console in the isolate
2370  // error throwing functionality.
2371  OS::PrintError("Error installing extension '%s'.\n",
2372  current->extension()->name());
2373  isolate->clear_pending_exception();
2374  }
2375  extension_states->set_state(current, INSTALLED);
2376  isolate->NotifyExtensionInstalled();
2377  return result;
2378 }
2379 
2380 
2381 bool Genesis::InstallJSBuiltins(Handle<JSBuiltinsObject> builtins) {
2382  HandleScope scope(isolate());
2383  for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) {
2384  Builtins::JavaScript id = static_cast<Builtins::JavaScript>(i);
2385  Handle<String> name =
2386  factory()->InternalizeUtf8String(Builtins::GetName(id));
2387  Object* function_object = builtins->GetPropertyNoExceptionThrown(*name);
2388  Handle<JSFunction> function
2389  = Handle<JSFunction>(JSFunction::cast(function_object));
2390  builtins->set_javascript_builtin(id, *function);
2391  if (!Compiler::EnsureCompiled(function, CLEAR_EXCEPTION)) {
2392  return false;
2393  }
2394  builtins->set_javascript_builtin_code(id, function->shared()->code());
2395  }
2396  return true;
2397 }
2398 
2399 
2400 bool Genesis::ConfigureGlobalObjects(
2401  v8::Handle<v8::ObjectTemplate> global_proxy_template) {
2402  Handle<JSObject> global_proxy(
2403  JSObject::cast(native_context()->global_proxy()));
2404  Handle<JSObject> inner_global(
2405  JSObject::cast(native_context()->global_object()));
2406 
2407  if (!global_proxy_template.IsEmpty()) {
2408  // Configure the global proxy object.
2409  Handle<ObjectTemplateInfo> proxy_data =
2410  v8::Utils::OpenHandle(*global_proxy_template);
2411  if (!ConfigureApiObject(global_proxy, proxy_data)) return false;
2412 
2413  // Configure the inner global object.
2414  Handle<FunctionTemplateInfo> proxy_constructor(
2415  FunctionTemplateInfo::cast(proxy_data->constructor()));
2416  if (!proxy_constructor->prototype_template()->IsUndefined()) {
2417  Handle<ObjectTemplateInfo> inner_data(
2418  ObjectTemplateInfo::cast(proxy_constructor->prototype_template()));
2419  if (!ConfigureApiObject(inner_global, inner_data)) return false;
2420  }
2421  }
2422 
2423  SetObjectPrototype(global_proxy, inner_global);
2424 
2425  native_context()->set_initial_array_prototype(
2426  JSArray::cast(native_context()->array_function()->prototype()));
2427 
2428  return true;
2429 }
2430 
2431 
2432 bool Genesis::ConfigureApiObject(Handle<JSObject> object,
2433  Handle<ObjectTemplateInfo> object_template) {
2434  ASSERT(!object_template.is_null());
2435  ASSERT(FunctionTemplateInfo::cast(object_template->constructor())
2436  ->IsTemplateFor(object->map()));;
2437 
2438  bool pending_exception = false;
2439  Handle<JSObject> obj =
2440  Execution::InstantiateObject(object_template, &pending_exception);
2441  if (pending_exception) {
2442  ASSERT(isolate()->has_pending_exception());
2443  isolate()->clear_pending_exception();
2444  return false;
2445  }
2446  TransferObject(obj, object);
2447  return true;
2448 }
2449 
2450 
2451 void Genesis::TransferNamedProperties(Handle<JSObject> from,
2452  Handle<JSObject> to) {
2453  if (from->HasFastProperties()) {
2454  Handle<DescriptorArray> descs =
2455  Handle<DescriptorArray>(from->map()->instance_descriptors());
2456  for (int i = 0; i < from->map()->NumberOfOwnDescriptors(); i++) {
2457  PropertyDetails details = descs->GetDetails(i);
2458  switch (details.type()) {
2459  case FIELD: {
2460  HandleScope inner(isolate());
2461  Handle<Name> key = Handle<Name>(descs->GetKey(i));
2462  int index = descs->GetFieldIndex(i);
2463  ASSERT(!descs->GetDetails(i).representation().IsDouble());
2464  Handle<Object> value = Handle<Object>(from->RawFastPropertyAt(index),
2465  isolate());
2466  CHECK_NOT_EMPTY_HANDLE(isolate(),
2468  to, key, value, details.attributes()));
2469  break;
2470  }
2471  case CONSTANT: {
2472  HandleScope inner(isolate());
2473  Handle<Name> key = Handle<Name>(descs->GetKey(i));
2474  Handle<Object> constant(descs->GetConstant(i), isolate());
2475  CHECK_NOT_EMPTY_HANDLE(isolate(),
2477  to, key, constant, details.attributes()));
2478  break;
2479  }
2480  case CALLBACKS: {
2481  LookupResult result(isolate());
2482  to->LocalLookup(descs->GetKey(i), &result);
2483  // If the property is already there we skip it
2484  if (result.IsFound()) continue;
2485  HandleScope inner(isolate());
2486  ASSERT(!to->HasFastProperties());
2487  // Add to dictionary.
2488  Handle<Name> key = Handle<Name>(descs->GetKey(i));
2489  Handle<Object> callbacks(descs->GetCallbacksObject(i), isolate());
2490  PropertyDetails d = PropertyDetails(
2491  details.attributes(), CALLBACKS, i + 1);
2492  JSObject::SetNormalizedProperty(to, key, callbacks, d);
2493  break;
2494  }
2495  case NORMAL:
2496  // Do not occur since the from object has fast properties.
2497  case HANDLER:
2498  case INTERCEPTOR:
2499  case TRANSITION:
2500  case NONEXISTENT:
2501  // No element in instance descriptors have proxy or interceptor type.
2502  UNREACHABLE();
2503  break;
2504  }
2505  }
2506  } else {
2507  Handle<NameDictionary> properties =
2508  Handle<NameDictionary>(from->property_dictionary());
2509  int capacity = properties->Capacity();
2510  for (int i = 0; i < capacity; i++) {
2511  Object* raw_key(properties->KeyAt(i));
2512  if (properties->IsKey(raw_key)) {
2513  ASSERT(raw_key->IsName());
2514  // If the property is already there we skip it.
2515  LookupResult result(isolate());
2516  to->LocalLookup(Name::cast(raw_key), &result);
2517  if (result.IsFound()) continue;
2518  // Set the property.
2519  Handle<Name> key = Handle<Name>(Name::cast(raw_key));
2520  Handle<Object> value = Handle<Object>(properties->ValueAt(i),
2521  isolate());
2522  ASSERT(!value->IsCell());
2523  if (value->IsPropertyCell()) {
2524  value = Handle<Object>(PropertyCell::cast(*value)->value(),
2525  isolate());
2526  }
2527  PropertyDetails details = properties->DetailsAt(i);
2528  CHECK_NOT_EMPTY_HANDLE(isolate(),
2530  to, key, value, details.attributes()));
2531  }
2532  }
2533  }
2534 }
2535 
2536 
2537 void Genesis::TransferIndexedProperties(Handle<JSObject> from,
2538  Handle<JSObject> to) {
2539  // Cloning the elements array is sufficient.
2540  Handle<FixedArray> from_elements =
2541  Handle<FixedArray>(FixedArray::cast(from->elements()));
2542  Handle<FixedArray> to_elements = factory()->CopyFixedArray(from_elements);
2543  to->set_elements(*to_elements);
2544 }
2545 
2546 
2547 void Genesis::TransferObject(Handle<JSObject> from, Handle<JSObject> to) {
2548  HandleScope outer(isolate());
2549 
2550  ASSERT(!from->IsJSArray());
2551  ASSERT(!to->IsJSArray());
2552 
2553  TransferNamedProperties(from, to);
2554  TransferIndexedProperties(from, to);
2555 
2556  // Transfer the prototype (new map is needed).
2557  Handle<Map> old_to_map = Handle<Map>(to->map());
2558  Handle<Map> new_to_map = factory()->CopyMap(old_to_map);
2559  new_to_map->set_prototype(from->map()->prototype());
2560  to->set_map(*new_to_map);
2561 }
2562 
2563 
2564 void Genesis::MakeFunctionInstancePrototypeWritable() {
2565  // The maps with writable prototype are created in CreateEmptyFunction
2566  // and CreateStrictModeFunctionMaps respectively. Initially the maps are
2567  // created with read-only prototype for JS builtins processing.
2568  ASSERT(!sloppy_function_map_writable_prototype_.is_null());
2569  ASSERT(!strict_function_map_writable_prototype_.is_null());
2570 
2571  // Replace function instance maps to make prototype writable.
2572  native_context()->set_sloppy_function_map(
2573  *sloppy_function_map_writable_prototype_);
2574  native_context()->set_strict_function_map(
2575  *strict_function_map_writable_prototype_);
2576 }
2577 
2578 
2580  public:
2581  NoTrackDoubleFieldsForSerializerScope() : flag_(FLAG_track_double_fields) {
2582  if (Serializer::enabled()) {
2583  // Disable tracking double fields because heap numbers treated as
2584  // immutable by the serializer.
2585  FLAG_track_double_fields = false;
2586  }
2587  }
2589  if (Serializer::enabled()) {
2590  FLAG_track_double_fields = flag_;
2591  }
2592  }
2593 
2594  private:
2595  bool flag_;
2596 };
2597 
2598 
2599 Genesis::Genesis(Isolate* isolate,
2600  Handle<Object> global_object,
2601  v8::Handle<v8::ObjectTemplate> global_template,
2602  v8::ExtensionConfiguration* extensions)
2603  : isolate_(isolate),
2604  active_(isolate->bootstrapper()) {
2605  NoTrackDoubleFieldsForSerializerScope disable_double_tracking_for_serializer;
2606  result_ = Handle<Context>::null();
2607  // If V8 cannot be initialized, just return.
2608  if (!V8::Initialize(NULL)) return;
2609 
2610  // Before creating the roots we must save the context and restore it
2611  // on all function exits.
2612  SaveContext saved_context(isolate);
2613 
2614  // During genesis, the boilerplate for stack overflow won't work until the
2615  // environment has been at least partially initialized. Add a stack check
2616  // before entering JS code to catch overflow early.
2617  StackLimitCheck check(isolate);
2618  if (check.HasOverflowed()) return;
2619 
2620  // We can only de-serialize a context if the isolate was initialized from
2621  // a snapshot. Otherwise we have to build the context from scratch.
2622  if (isolate->initialized_from_snapshot()) {
2623  native_context_ = Snapshot::NewContextFromSnapshot(isolate);
2624  } else {
2625  native_context_ = Handle<Context>();
2626  }
2627 
2628  if (!native_context().is_null()) {
2629  AddToWeakNativeContextList(*native_context());
2630  isolate->set_context(*native_context());
2631  isolate->counters()->contexts_created_by_snapshot()->Increment();
2632  Handle<GlobalObject> inner_global;
2633  Handle<JSGlobalProxy> global_proxy =
2634  CreateNewGlobals(global_template,
2635  global_object,
2636  &inner_global);
2637 
2638  HookUpGlobalProxy(inner_global, global_proxy);
2639  HookUpInnerGlobal(inner_global);
2640  native_context()->builtins()->set_global_receiver(
2641  native_context()->global_proxy());
2642 
2643  if (!ConfigureGlobalObjects(global_template)) return;
2644  } else {
2645  // We get here if there was no context snapshot.
2646  CreateRoots();
2647  Handle<JSFunction> empty_function = CreateEmptyFunction(isolate);
2648  CreateStrictModeFunctionMaps(empty_function);
2649  Handle<GlobalObject> inner_global;
2650  Handle<JSGlobalProxy> global_proxy =
2651  CreateNewGlobals(global_template, global_object, &inner_global);
2652  HookUpGlobalProxy(inner_global, global_proxy);
2653  InitializeGlobal(inner_global, empty_function);
2654  InstallJSFunctionResultCaches();
2655  InitializeNormalizedMapCaches();
2656  if (!InstallNatives()) return;
2657 
2658  MakeFunctionInstancePrototypeWritable();
2659 
2660  if (!ConfigureGlobalObjects(global_template)) return;
2661  isolate->counters()->contexts_created_from_scratch()->Increment();
2662  }
2663 
2664  // Initialize experimental globals and install experimental natives.
2665  InitializeExperimentalGlobal();
2666  if (!InstallExperimentalNatives()) return;
2667 
2668  // We can't (de-)serialize typed arrays currently, but we are lucky: The state
2669  // of the random number generator needs no initialization during snapshot
2670  // creation time and we don't need trigonometric functions then.
2671  if (!Serializer::enabled()) {
2672  // Initially seed the per-context random number generator using the
2673  // per-isolate random number generator.
2674  const int num_elems = 2;
2675  const int num_bytes = num_elems * sizeof(uint32_t);
2676  uint32_t* state = reinterpret_cast<uint32_t*>(malloc(num_bytes));
2677 
2678  do {
2679  isolate->random_number_generator()->NextBytes(state, num_bytes);
2680  } while (state[0] == 0 || state[1] == 0);
2681 
2683  reinterpret_cast<v8::Isolate*>(isolate), state, num_bytes);
2684  Utils::OpenHandle(*buffer)->set_should_be_freed(true);
2685  v8::Local<v8::Uint32Array> ta = v8::Uint32Array::New(buffer, 0, num_elems);
2686  Handle<JSBuiltinsObject> builtins(native_context()->builtins());
2687  ForceSetProperty(builtins,
2688  factory()->InternalizeOneByteString(
2689  STATIC_ASCII_VECTOR("rngstate")),
2690  Utils::OpenHandle(*ta),
2691  NONE);
2692 
2693  // Initialize trigonometric lookup tables and constants.
2694  const int table_num_bytes = TrigonometricLookupTable::table_num_bytes();
2696  reinterpret_cast<v8::Isolate*>(isolate),
2697  TrigonometricLookupTable::sin_table(), table_num_bytes);
2699  reinterpret_cast<v8::Isolate*>(isolate),
2702  sin_buffer, 0, TrigonometricLookupTable::table_size());
2704  cos_buffer, 0, TrigonometricLookupTable::table_size());
2705 
2706  ForceSetProperty(builtins,
2707  factory()->InternalizeOneByteString(
2708  STATIC_ASCII_VECTOR("kSinTable")),
2709  Utils::OpenHandle(*sin_table),
2710  NONE);
2711  ForceSetProperty(builtins,
2712  factory()->InternalizeOneByteString(
2713  STATIC_ASCII_VECTOR("kCosXIntervalTable")),
2714  Utils::OpenHandle(*cos_table),
2715  NONE);
2716  ForceSetProperty(builtins,
2717  factory()->InternalizeOneByteString(
2718  STATIC_ASCII_VECTOR("kSamples")),
2719  factory()->NewHeapNumber(
2721  NONE);
2722  ForceSetProperty(builtins,
2723  factory()->InternalizeOneByteString(
2724  STATIC_ASCII_VECTOR("kIndexConvert")),
2725  factory()->NewHeapNumber(
2727  NONE);
2728  }
2729 
2730  result_ = native_context();
2731 }
2732 
2733 
2734 // Support for thread preemption.
2735 
2736 // Reserve space for statics needing saving and restoring.
2738  return sizeof(NestingCounterType);
2739 }
2740 
2741 
2742 // Archive statics that are thread local.
2744  *reinterpret_cast<NestingCounterType*>(to) = nesting_;
2745  nesting_ = 0;
2746  return to + sizeof(NestingCounterType);
2747 }
2748 
2749 
2750 // Restore statics that are thread local.
2751 char* Bootstrapper::RestoreState(char* from) {
2752  nesting_ = *reinterpret_cast<NestingCounterType*>(from);
2753  return from + sizeof(NestingCounterType);
2754 }
2755 
2756 
2757 // Called when the top-level V8 mutex is destroyed.
2759  ASSERT(!IsActive());
2760 }
2761 
2762 } } // namespace v8::internal
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter NULL
Definition: flags.cc:269
#define CHECK_NOT_EMPTY_HANDLE(isolate, call)
Definition: isolate.h:145
static bool Initialize(Deserializer *des)
Definition: v8.cc:61
Code * builtin(Name name)
Definition: builtins.h:322
#define INSTALL_TYPED_ARRAY(Type, type, TYPE, ctype, size)
char * ArchiveState(char *to)
Handle< String > NewExternalStringFromAscii(const ExternalAsciiString::Resource *resource)
Definition: factory.cc:554
static const int kResultPropertyCount
Definition: objects.h:7340
static Handle< SharedFunctionInfo > CompileScript(Handle< String > source, Handle< Object > script_name, int line_offset, int column_offset, bool is_shared_cross_origin, Handle< Context > context, v8::Extension *extension, ScriptDataImpl **cached_data, CachedDataMode cached_data_mode, NativesFlag is_natives_code)
Definition: compiler.cc:917
static const int kGlobalFieldIndex
Definition: objects.h:7972
Handle< Object > CacheInitialJSArrayMaps(Handle< Context > native_context, Handle< Map > initial_map)
Definition: objects.cc:9694
void PrintF(const char *format,...)
Definition: v8utils.cc:40
void Initialize(bool create_heap_objects)
static const int kSize
Definition: objects.h:7671
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf map
Definition: flags.cc:350
static const int kResultValuePropertyIndex
Definition: objects.h:7338
char * AllocateAutoDeletedArray(int bytes)
Handle< Context > result()
static Smi * FromInt(int value)
Definition: objects-inl.h:1209
void V8_EXPORT RegisterExtension(Extension *extension)
Definition: api.cc:439
static ObjectTemplateInfo * cast(Object *obj)
const char ** begin() const
Definition: v8.h:5164
static Vector< const char > GetRawScriptSource(int index)
static void SetInstancePrototype(Handle< JSFunction > function, Handle< Object > value)
Definition: objects.cc:9702
static HeapObject * cast(Object *obj)
static Handle< T > cast(Handle< S > that)
Definition: handles.h:75
static const int kSourceFieldIndex
Definition: objects.h:7971
static Vector< const char > GetScriptName(int index)
enable upcoming ES6 features enable harmony block scoping enable harmony symbols(a.k.a.private names)") DEFINE_bool(harmony_proxies
static AccessorPair * cast(Object *obj)
static const int kSize
Definition: objects.h:9950
kSerializedDataOffset Object
Definition: objects-inl.h:5016
T & at(int i) const
Definition: list.h:90
Builtins * builtins()
Definition: isolate.h:948
static const int kSize
Definition: objects.h:7568
static bool enabled()
Definition: serialize.h:485
static bool EnsureCompiled(Handle< JSFunction > function, ClearExceptionFlag flag)
Definition: compiler.cc:687
static const int kSize
Definition: objects.h:7922
#define ASSERT(condition)
Definition: checks.h:329
static Handle< Object > SetLocalPropertyIgnoreAttributes(Handle< JSObject > object, Handle< Name > key, Handle< Object > value, PropertyAttributes attributes, ValueType value_type=OPTIMAL_REPRESENTATION, StoreMode mode=ALLOW_AS_CONSTANT, ExtensibilityCheck extensibility_check=PERFORM_EXTENSIBILITY_CHECK)
Definition: objects.cc:4141
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:1236
bool InstallExtensions(Handle< Context > native_context, v8::ExtensionConfiguration *extensions)
static const char * GetName(JavaScript id)
Definition: builtins.h:336
static Context * cast(Object *context)
Definition: contexts.h:244
static Handle< Object > FunctionSetPrototype(Handle< JSFunction > object, Handle< Object > value)
Definition: accessors.cc:546
static const int kSize
Definition: objects.h:9789
Handle< Context > CreateEnvironment(Handle< Object > global_object, v8::Handle< v8::ObjectTemplate > global_template, v8::ExtensionConfiguration *extensions)
static const int kSize
Definition: objects.h:10099
Handle< Object > GetProperty(Handle< JSReceiver > obj, const char *name)
Definition: handles.cc:196
Factory * factory()
Definition: isolate.h:995
PropertyAttributes
#define INSTALL_EXPERIMENTAL_NATIVE(i, flag, file)
#define RETURN_IF_EMPTY_HANDLE_VALUE(isolate, call, value)
Definition: isolate.h:137
Extension * extension()
Definition: api.h:150
v8::Isolate * GetIsolate()
Definition: api.cc:5233
static const int kMultilineFieldIndex
Definition: objects.h:7974
static const int kSize
Definition: objects.h:10077
GlobalObject * global_object()
Definition: contexts.h:388
friend class NativesExternalStringResource
Definition: bootstrapper.h:147
uint32_t ComputePointerHash(void *ptr)
Definition: utils.h:347
static const int kResultSize
Definition: objects.h:7345
#define UNREACHABLE()
Definition: checks.h:52
Handle< Map > CopyMap(Handle< Map > map, int extra_inobject_props)
Definition: factory.cc:855
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object size
Definition: flags.cc:211
T * start() const
Definition: utils.h:426
static JSGlobalProxy * cast(Object *obj)
Handle< JSFunction > NewFunctionWithoutPrototype(Handle< String > name, StrictMode strict_mode)
Definition: factory.cc:1687
STATIC_ASSERT(sizeof(CPURegister)==sizeof(Register))
static const int kInputIndex
Definition: objects.h:10102
#define INSTALL_BUILTIN_ID(holder_expr, fun_name, name)
friend class BootstrapperActive
Definition: bootstrapper.h:145
static Handle< Context > NewContextFromSnapshot(Isolate *isolate)
void set_context(Context *context)
Definition: isolate.h:558
const int kPointerSize
Definition: globals.h:268
void check(i::Vector< const uint8_t > string)
const char * name() const
Definition: v8.h:3891
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra code(assertions) for debugging") DEFINE_bool(code_comments
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: globals.h:359
static FunctionTemplateInfo * cast(Object *obj)
static Local< ArrayBuffer > New(Isolate *isolate, size_t byte_length)
Definition: api.cc:5994
Handle< String > NativesSourceLookup(int index)
Definition: bootstrapper.cc:79
int length() const
Definition: utils.h:420
static int NumberOfJavaScriptBuiltins()
Definition: builtins.h:344
static Local< Float64Array > New(Handle< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
bool has_pending_exception()
Definition: isolate.h:587
static const int kIgnoreCaseFieldIndex
Definition: objects.h:7973
static PropertyCell * cast(Object *obj)
#define STATIC_ASCII_VECTOR(x)
Definition: utils.h:570
static const int kSize
Definition: objects.h:9807
static v8::internal::Handle< To > OpenHandle(v8::Local< From > handle)
Definition: api.h:308
Handle< FixedArray > CopyFixedArray(Handle< FixedArray > array)
Definition: factory.cc:886
Vector< const char > CStrVector(const char *data)
Definition: utils.h:574
static const int kSize
Definition: objects.h:9768
static JSArray * cast(Object *obj)
static const int kSizeWithInternalFields
Definition: objects.h:9884
void Iterate(ObjectVisitor *v)
Isolate * isolate() const
int dependency_count()
Definition: v8.h:3895
static const int kSize
Definition: objects.h:7702
static Local< Uint32Array > New(Handle< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
#define INSTALL_NATIVE(Type, name, var)
static const int kSizeWithInternalFields
Definition: objects.h:9952
Handle< String > InternalizeOneByteString(Vector< const uint8_t > str)
Definition: factory.cc:232
static Handle< Object > Call(Isolate *isolate, Handle< Object > callable, Handle< Object > receiver, int argc, Handle< Object > argv[], bool *pending_exception, bool convert_receiver=false)
Definition: execution.cc:153
bool is_null() const
Definition: handles.h:81
#define JSFUNCTION_RESULT_CACHE_LIST(F)
static const int kResultDonePropertyIndex
Definition: objects.h:7339
V8_INLINE bool IsEmpty() const
Definition: v8.h:248
static void SetNormalizedProperty(Handle< JSObject > object, const LookupResult *result, Handle< Object > value)
Definition: objects.cc:691
static void InitializeOncePerProcess()
static const int kArgumentsLengthIndex
Definition: heap.h:1104
void DetachGlobal(Handle< Context > env)
const String::ExternalAsciiStringResource * source() const
Definition: v8.h:3893
static RegisteredExtension * first_extension()
Definition: api.h:152
ElementsKind GetInitialFastElementsKind()
Handle< String > InternalizeUtf8String(Vector< const char > str)
Definition: factory.cc:218
static const int kSizeWithInternalFields
Definition: objects.h:9977
static void PrintError(const char *format,...)
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable memory(in Mbytes)") DEFINE_bool(gc_global
Handle< JSGlobalProxy > ReinitializeJSGlobalProxy(Handle< JSFunction > constructor, Handle< JSGlobalProxy > global)
Definition: handles.cc:141
#define TYPED_ARRAYS(V)
Definition: objects.h:4663
static Handle< T > null()
Definition: handles.h:80
TemplateHashMapImpl< FreeStoreAllocationPolicy > HashMap
Definition: hashmap.h:113
Handle< Foreign > NewForeign(Address addr, PretenureFlag pretenure=NOT_TENURED)
Definition: factory.cc:726
static const int kSize
Definition: objects.h:7788
#define ASSERT_EQ(v1, v2)
Definition: checks.h:330
static const int kIndexIndex
Definition: objects.h:10101
static Handle< JSObject > InstantiateObject(Handle< ObjectTemplateInfo > data, bool *exc)
Definition: execution.cc:832
static const int kArgumentsCalleeIndex
Definition: heap.h:1106
static FixedArray * cast(Object *obj)
static const int kHeaderSize
Definition: objects.h:2757
static Handle< Object > PreventExtensions(Handle< JSObject > object)
Definition: objects.cc:5420
void Add(const T &element, AllocationPolicy allocator=AllocationPolicy())
Definition: list-inl.h:39
static bool ApiCheck(bool condition, const char *location, const char *message)
Definition: api.h:199
Object * get(int index)
Definition: objects-inl.h:2127
static VisitorId GetVisitorId(int instance_type, int instance_size)
static const int kSize
Definition: objects.h:7527
HeapObject * obj
Handle< Object > ForceSetProperty(Handle< JSObject > object, Handle< Object > key, Handle< Object > value, PropertyAttributes attributes)
Definition: handles.cc:161
static Name * cast(Object *obj)
static NormalizedMapCache * cast(Object *obj)
const char ** end() const
Definition: v8.h:5165
static Representation Tagged()
static const int kLastIndexFieldIndex
Definition: objects.h:7975
static GlobalObject * cast(Object *obj)
static const int kSize
Definition: objects.h:7638
#define FUNCTIONS_WITH_ID_LIST(V)
Definition: objects.h:6661
NativesExternalStringResource(Bootstrapper *bootstrapper, const char *source, size_t length)
Definition: bootstrapper.cc:55
Handle< Map > NewMap(InstanceType type, int instance_size, ElementsKind elements_kind=TERMINAL_FAST_ELEMENTS_KIND)
Definition: factory.cc:809
Factory * factory() const
const char ** dependencies()
Definition: v8.h:3896
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print statistics of the maximum memory committed for the heap in name
Definition: flags.cc:505
static const int kNotFound
Definition: objects.h:3486
Definition: v8.h:124
static int ArchiveSpacePerThread()
static JSObject * cast(Object *obj)
static const int kStrictArgumentsObjectSize
Definition: heap.h:1101
Handle< T > CloseAndEscape(Handle< T > handle_value)
Definition: handles-inl.h:146
static void TearDownExtensions()
static JSGlobalObject * cast(Object *obj)
static JSFunction * cast(Object *obj)