factory.cc revision 1e0659c275bb392c045087af4f6b0d7565cb3d77
1// Copyright 2010 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 "api.h"
31#include "debug.h"
32#include "execution.h"
33#include "factory.h"
34#include "macro-assembler.h"
35#include "objects.h"
36#include "objects-visiting.h"
37
38namespace v8 {
39namespace internal {
40
41
42Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
43  ASSERT(0 <= size);
44  CALL_HEAP_FUNCTION(Heap::AllocateFixedArray(size, pretenure), FixedArray);
45}
46
47
48Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
49                                                   PretenureFlag pretenure) {
50  ASSERT(0 <= size);
51  CALL_HEAP_FUNCTION(Heap::AllocateFixedArrayWithHoles(size, pretenure),
52                     FixedArray);
53}
54
55
56Handle<StringDictionary> Factory::NewStringDictionary(int at_least_space_for) {
57  ASSERT(0 <= at_least_space_for);
58  CALL_HEAP_FUNCTION(StringDictionary::Allocate(at_least_space_for),
59                     StringDictionary);
60}
61
62
63Handle<NumberDictionary> Factory::NewNumberDictionary(int at_least_space_for) {
64  ASSERT(0 <= at_least_space_for);
65  CALL_HEAP_FUNCTION(NumberDictionary::Allocate(at_least_space_for),
66                     NumberDictionary);
67}
68
69
70Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors) {
71  ASSERT(0 <= number_of_descriptors);
72  CALL_HEAP_FUNCTION(DescriptorArray::Allocate(number_of_descriptors),
73                     DescriptorArray);
74}
75
76
77Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
78    int deopt_entry_count,
79    PretenureFlag pretenure) {
80  ASSERT(deopt_entry_count > 0);
81  CALL_HEAP_FUNCTION(DeoptimizationInputData::Allocate(deopt_entry_count,
82                                                       pretenure),
83                     DeoptimizationInputData);
84}
85
86
87Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
88    int deopt_entry_count,
89    PretenureFlag pretenure) {
90  ASSERT(deopt_entry_count > 0);
91  CALL_HEAP_FUNCTION(DeoptimizationOutputData::Allocate(deopt_entry_count,
92                                                        pretenure),
93                     DeoptimizationOutputData);
94}
95
96
97// Symbols are created in the old generation (data space).
98Handle<String> Factory::LookupSymbol(Vector<const char> string) {
99  CALL_HEAP_FUNCTION(Heap::LookupSymbol(string), String);
100}
101
102Handle<String> Factory::LookupAsciiSymbol(Vector<const char> string) {
103  CALL_HEAP_FUNCTION(Heap::LookupAsciiSymbol(string), String);
104}
105
106Handle<String> Factory::LookupTwoByteSymbol(Vector<const uc16> string) {
107  CALL_HEAP_FUNCTION(Heap::LookupTwoByteSymbol(string), String);
108}
109
110
111Handle<String> Factory::NewStringFromAscii(Vector<const char> string,
112                                           PretenureFlag pretenure) {
113  CALL_HEAP_FUNCTION(Heap::AllocateStringFromAscii(string, pretenure), String);
114}
115
116Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
117                                          PretenureFlag pretenure) {
118  CALL_HEAP_FUNCTION(Heap::AllocateStringFromUtf8(string, pretenure), String);
119}
120
121
122Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
123                                             PretenureFlag pretenure) {
124  CALL_HEAP_FUNCTION(Heap::AllocateStringFromTwoByte(string, pretenure),
125                     String);
126}
127
128
129Handle<String> Factory::NewRawAsciiString(int length,
130                                          PretenureFlag pretenure) {
131  CALL_HEAP_FUNCTION(Heap::AllocateRawAsciiString(length, pretenure), String);
132}
133
134
135Handle<String> Factory::NewRawTwoByteString(int length,
136                                            PretenureFlag pretenure) {
137  CALL_HEAP_FUNCTION(Heap::AllocateRawTwoByteString(length, pretenure), String);
138}
139
140
141Handle<String> Factory::NewConsString(Handle<String> first,
142                                      Handle<String> second) {
143  CALL_HEAP_FUNCTION(Heap::AllocateConsString(*first, *second), String);
144}
145
146
147Handle<String> Factory::NewSubString(Handle<String> str,
148                                     int begin,
149                                     int end) {
150  CALL_HEAP_FUNCTION(str->SubString(begin, end), String);
151}
152
153
154Handle<String> Factory::NewExternalStringFromAscii(
155    ExternalAsciiString::Resource* resource) {
156  CALL_HEAP_FUNCTION(Heap::AllocateExternalStringFromAscii(resource), String);
157}
158
159
160Handle<String> Factory::NewExternalStringFromTwoByte(
161    ExternalTwoByteString::Resource* resource) {
162  CALL_HEAP_FUNCTION(Heap::AllocateExternalStringFromTwoByte(resource), String);
163}
164
165
166Handle<Context> Factory::NewGlobalContext() {
167  CALL_HEAP_FUNCTION(Heap::AllocateGlobalContext(), Context);
168}
169
170
171Handle<Context> Factory::NewFunctionContext(int length,
172                                            Handle<JSFunction> closure) {
173  CALL_HEAP_FUNCTION(Heap::AllocateFunctionContext(length, *closure), Context);
174}
175
176
177Handle<Context> Factory::NewWithContext(Handle<Context> previous,
178                                        Handle<JSObject> extension,
179                                        bool is_catch_context) {
180  CALL_HEAP_FUNCTION(Heap::AllocateWithContext(*previous,
181                                               *extension,
182                                               is_catch_context),
183                     Context);
184}
185
186
187Handle<Struct> Factory::NewStruct(InstanceType type) {
188  CALL_HEAP_FUNCTION(Heap::AllocateStruct(type), Struct);
189}
190
191
192Handle<AccessorInfo> Factory::NewAccessorInfo() {
193  Handle<AccessorInfo> info =
194      Handle<AccessorInfo>::cast(NewStruct(ACCESSOR_INFO_TYPE));
195  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
196  return info;
197}
198
199
200Handle<Script> Factory::NewScript(Handle<String> source) {
201  // Generate id for this script.
202  int id;
203  if (Heap::last_script_id()->IsUndefined()) {
204    // Script ids start from one.
205    id = 1;
206  } else {
207    // Increment id, wrap when positive smi is exhausted.
208    id = Smi::cast(Heap::last_script_id())->value();
209    id++;
210    if (!Smi::IsValid(id)) {
211      id = 0;
212    }
213  }
214  Heap::SetLastScriptId(Smi::FromInt(id));
215
216  // Create and initialize script object.
217  Handle<Proxy> wrapper = Factory::NewProxy(0, TENURED);
218  Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
219  script->set_source(*source);
220  script->set_name(Heap::undefined_value());
221  script->set_id(Heap::last_script_id());
222  script->set_line_offset(Smi::FromInt(0));
223  script->set_column_offset(Smi::FromInt(0));
224  script->set_data(Heap::undefined_value());
225  script->set_context_data(Heap::undefined_value());
226  script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
227  script->set_compilation_type(Smi::FromInt(Script::COMPILATION_TYPE_HOST));
228  script->set_wrapper(*wrapper);
229  script->set_line_ends(Heap::undefined_value());
230  script->set_eval_from_shared(Heap::undefined_value());
231  script->set_eval_from_instructions_offset(Smi::FromInt(0));
232
233  return script;
234}
235
236
237Handle<Proxy> Factory::NewProxy(Address addr, PretenureFlag pretenure) {
238  CALL_HEAP_FUNCTION(Heap::AllocateProxy(addr, pretenure), Proxy);
239}
240
241
242Handle<Proxy> Factory::NewProxy(const AccessorDescriptor* desc) {
243  return NewProxy((Address) desc, TENURED);
244}
245
246
247Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
248  ASSERT(0 <= length);
249  CALL_HEAP_FUNCTION(Heap::AllocateByteArray(length, pretenure), ByteArray);
250}
251
252
253Handle<PixelArray> Factory::NewPixelArray(int length,
254                                          uint8_t* external_pointer,
255                                          PretenureFlag pretenure) {
256  ASSERT(0 <= length);
257  CALL_HEAP_FUNCTION(Heap::AllocatePixelArray(length,
258                                              external_pointer,
259                                              pretenure), PixelArray);
260}
261
262
263Handle<ExternalArray> Factory::NewExternalArray(int length,
264                                                ExternalArrayType array_type,
265                                                void* external_pointer,
266                                                PretenureFlag pretenure) {
267  ASSERT(0 <= length);
268  CALL_HEAP_FUNCTION(Heap::AllocateExternalArray(length,
269                                                 array_type,
270                                                 external_pointer,
271                                                 pretenure), ExternalArray);
272}
273
274
275Handle<JSGlobalPropertyCell> Factory::NewJSGlobalPropertyCell(
276    Handle<Object> value) {
277  CALL_HEAP_FUNCTION(Heap::AllocateJSGlobalPropertyCell(*value),
278                     JSGlobalPropertyCell);
279}
280
281
282Handle<Map> Factory::NewMap(InstanceType type, int instance_size) {
283  CALL_HEAP_FUNCTION(Heap::AllocateMap(type, instance_size), Map);
284}
285
286
287Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
288  CALL_HEAP_FUNCTION(Heap::AllocateFunctionPrototype(*function), JSObject);
289}
290
291
292Handle<Map> Factory::CopyMapDropDescriptors(Handle<Map> src) {
293  CALL_HEAP_FUNCTION(src->CopyDropDescriptors(), Map);
294}
295
296
297Handle<Map> Factory::CopyMap(Handle<Map> src,
298                             int extra_inobject_properties) {
299  Handle<Map> copy = CopyMapDropDescriptors(src);
300  // Check that we do not overflow the instance size when adding the
301  // extra inobject properties.
302  int instance_size_delta = extra_inobject_properties * kPointerSize;
303  int max_instance_size_delta =
304      JSObject::kMaxInstanceSize - copy->instance_size();
305  if (instance_size_delta > max_instance_size_delta) {
306    // If the instance size overflows, we allocate as many properties
307    // as we can as inobject properties.
308    instance_size_delta = max_instance_size_delta;
309    extra_inobject_properties = max_instance_size_delta >> kPointerSizeLog2;
310  }
311  // Adjust the map with the extra inobject properties.
312  int inobject_properties =
313      copy->inobject_properties() + extra_inobject_properties;
314  copy->set_inobject_properties(inobject_properties);
315  copy->set_unused_property_fields(inobject_properties);
316  copy->set_instance_size(copy->instance_size() + instance_size_delta);
317  copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
318  return copy;
319}
320
321
322Handle<Map> Factory::CopyMapDropTransitions(Handle<Map> src) {
323  CALL_HEAP_FUNCTION(src->CopyDropTransitions(), Map);
324}
325
326
327Handle<Map> Factory::GetFastElementsMap(Handle<Map> src) {
328  CALL_HEAP_FUNCTION(src->GetFastElementsMap(), Map);
329}
330
331
332Handle<Map> Factory::GetSlowElementsMap(Handle<Map> src) {
333  CALL_HEAP_FUNCTION(src->GetSlowElementsMap(), Map);
334}
335
336
337Handle<Map> Factory::GetPixelArrayElementsMap(Handle<Map> src) {
338  CALL_HEAP_FUNCTION(src->GetPixelArrayElementsMap(), Map);
339}
340
341
342Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
343  CALL_HEAP_FUNCTION(array->Copy(), FixedArray);
344}
345
346
347Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
348    Handle<SharedFunctionInfo> function_info,
349    Handle<Map> function_map,
350    PretenureFlag pretenure) {
351  CALL_HEAP_FUNCTION(Heap::AllocateFunction(*function_map,
352                                            *function_info,
353                                            Heap::the_hole_value(),
354                                            pretenure),
355                     JSFunction);
356}
357
358
359Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
360    Handle<SharedFunctionInfo> function_info,
361    Handle<Context> context,
362    PretenureFlag pretenure) {
363  Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
364      function_info, Top::function_map(), pretenure);
365  result->set_context(*context);
366  int number_of_literals = function_info->num_literals();
367  Handle<FixedArray> literals =
368      Factory::NewFixedArray(number_of_literals, pretenure);
369  if (number_of_literals > 0) {
370    // Store the object, regexp and array functions in the literals
371    // array prefix.  These functions will be used when creating
372    // object, regexp and array literals in this function.
373    literals->set(JSFunction::kLiteralGlobalContextIndex,
374                  context->global_context());
375  }
376  result->set_literals(*literals);
377  result->set_next_function_link(Heap::undefined_value());
378
379  if (V8::UseCrankshaft() &&
380      FLAG_always_opt &&
381      result->is_compiled() &&
382      !function_info->is_toplevel() &&
383      function_info->allows_lazy_compilation()) {
384    result->MarkForLazyRecompilation();
385  }
386  return result;
387}
388
389
390Handle<Object> Factory::NewNumber(double value,
391                                  PretenureFlag pretenure) {
392  CALL_HEAP_FUNCTION(Heap::NumberFromDouble(value, pretenure), Object);
393}
394
395
396Handle<Object> Factory::NewNumberFromInt(int value) {
397  CALL_HEAP_FUNCTION(Heap::NumberFromInt32(value), Object);
398}
399
400
401Handle<Object> Factory::NewNumberFromUint(uint32_t value) {
402  CALL_HEAP_FUNCTION(Heap::NumberFromUint32(value), Object);
403}
404
405
406Handle<JSObject> Factory::NewNeanderObject() {
407  CALL_HEAP_FUNCTION(Heap::AllocateJSObjectFromMap(Heap::neander_map()),
408                     JSObject);
409}
410
411
412Handle<Object> Factory::NewTypeError(const char* type,
413                                     Vector< Handle<Object> > args) {
414  return NewError("MakeTypeError", type, args);
415}
416
417
418Handle<Object> Factory::NewTypeError(Handle<String> message) {
419  return NewError("$TypeError", message);
420}
421
422
423Handle<Object> Factory::NewRangeError(const char* type,
424                                      Vector< Handle<Object> > args) {
425  return NewError("MakeRangeError", type, args);
426}
427
428
429Handle<Object> Factory::NewRangeError(Handle<String> message) {
430  return NewError("$RangeError", message);
431}
432
433
434Handle<Object> Factory::NewSyntaxError(const char* type, Handle<JSArray> args) {
435  return NewError("MakeSyntaxError", type, args);
436}
437
438
439Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
440  return NewError("$SyntaxError", message);
441}
442
443
444Handle<Object> Factory::NewReferenceError(const char* type,
445                                          Vector< Handle<Object> > args) {
446  return NewError("MakeReferenceError", type, args);
447}
448
449
450Handle<Object> Factory::NewReferenceError(Handle<String> message) {
451  return NewError("$ReferenceError", message);
452}
453
454
455Handle<Object> Factory::NewError(const char* maker, const char* type,
456    Vector< Handle<Object> > args) {
457  v8::HandleScope scope;  // Instantiate a closeable HandleScope for EscapeFrom.
458  Handle<FixedArray> array = Factory::NewFixedArray(args.length());
459  for (int i = 0; i < args.length(); i++) {
460    array->set(i, *args[i]);
461  }
462  Handle<JSArray> object = Factory::NewJSArrayWithElements(array);
463  Handle<Object> result = NewError(maker, type, object);
464  return result.EscapeFrom(&scope);
465}
466
467
468Handle<Object> Factory::NewEvalError(const char* type,
469                                     Vector< Handle<Object> > args) {
470  return NewError("MakeEvalError", type, args);
471}
472
473
474Handle<Object> Factory::NewError(const char* type,
475                                 Vector< Handle<Object> > args) {
476  return NewError("MakeError", type, args);
477}
478
479
480Handle<Object> Factory::NewError(const char* maker,
481                                 const char* type,
482                                 Handle<JSArray> args) {
483  Handle<String> make_str = Factory::LookupAsciiSymbol(maker);
484  Handle<Object> fun_obj(Top::builtins()->GetPropertyNoExceptionThrown(
485      *make_str));
486  // If the builtins haven't been properly configured yet this error
487  // constructor may not have been defined.  Bail out.
488  if (!fun_obj->IsJSFunction())
489    return Factory::undefined_value();
490  Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
491  Handle<Object> type_obj = Factory::LookupAsciiSymbol(type);
492  Object** argv[2] = { type_obj.location(),
493                       Handle<Object>::cast(args).location() };
494
495  // Invoke the JavaScript factory method. If an exception is thrown while
496  // running the factory method, use the exception as the result.
497  bool caught_exception;
498  Handle<Object> result = Execution::TryCall(fun,
499                                             Top::builtins(),
500                                             2,
501                                             argv,
502                                             &caught_exception);
503  return result;
504}
505
506
507Handle<Object> Factory::NewError(Handle<String> message) {
508  return NewError("$Error", message);
509}
510
511
512Handle<Object> Factory::NewError(const char* constructor,
513                                 Handle<String> message) {
514  Handle<String> constr = Factory::LookupAsciiSymbol(constructor);
515  Handle<JSFunction> fun =
516      Handle<JSFunction>(
517          JSFunction::cast(
518              Top::builtins()->GetPropertyNoExceptionThrown(*constr)));
519  Object** argv[1] = { Handle<Object>::cast(message).location() };
520
521  // Invoke the JavaScript factory method. If an exception is thrown while
522  // running the factory method, use the exception as the result.
523  bool caught_exception;
524  Handle<Object> result = Execution::TryCall(fun,
525                                             Top::builtins(),
526                                             1,
527                                             argv,
528                                             &caught_exception);
529  return result;
530}
531
532
533Handle<JSFunction> Factory::NewFunction(Handle<String> name,
534                                        InstanceType type,
535                                        int instance_size,
536                                        Handle<Code> code,
537                                        bool force_initial_map) {
538  // Allocate the function
539  Handle<JSFunction> function = NewFunction(name, the_hole_value());
540
541  // Setup the code pointer in both the shared function info and in
542  // the function itself.
543  function->shared()->set_code(*code);
544  function->set_code(*code);
545
546  if (force_initial_map ||
547      type != JS_OBJECT_TYPE ||
548      instance_size != JSObject::kHeaderSize) {
549    Handle<Map> initial_map = NewMap(type, instance_size);
550    Handle<JSObject> prototype = NewFunctionPrototype(function);
551    initial_map->set_prototype(*prototype);
552    function->set_initial_map(*initial_map);
553    initial_map->set_constructor(*function);
554  } else {
555    ASSERT(!function->has_initial_map());
556    ASSERT(!function->has_prototype());
557  }
558
559  return function;
560}
561
562
563Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
564                                                     InstanceType type,
565                                                     int instance_size,
566                                                     Handle<JSObject> prototype,
567                                                     Handle<Code> code,
568                                                     bool force_initial_map) {
569  // Allocate the function.
570  Handle<JSFunction> function = NewFunction(name, prototype);
571
572  // Setup the code pointer in both the shared function info and in
573  // the function itself.
574  function->shared()->set_code(*code);
575  function->set_code(*code);
576
577  if (force_initial_map ||
578      type != JS_OBJECT_TYPE ||
579      instance_size != JSObject::kHeaderSize) {
580    Handle<Map> initial_map = NewMap(type, instance_size);
581    function->set_initial_map(*initial_map);
582    initial_map->set_constructor(*function);
583  }
584
585  // Set function.prototype and give the prototype a constructor
586  // property that refers to the function.
587  SetPrototypeProperty(function, prototype);
588  // Currently safe because it is only invoked from Genesis.
589  SetLocalPropertyNoThrow(
590      prototype, Factory::constructor_symbol(), function, DONT_ENUM);
591  return function;
592}
593
594
595Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
596                                                        Handle<Code> code) {
597  Handle<JSFunction> function = NewFunctionWithoutPrototype(name);
598  function->shared()->set_code(*code);
599  function->set_code(*code);
600  ASSERT(!function->has_initial_map());
601  ASSERT(!function->has_prototype());
602  return function;
603}
604
605
606Handle<Code> Factory::NewCode(const CodeDesc& desc,
607                              Code::Flags flags,
608                              Handle<Object> self_ref) {
609  CALL_HEAP_FUNCTION(Heap::CreateCode(desc, flags, self_ref), Code);
610}
611
612
613Handle<Code> Factory::CopyCode(Handle<Code> code) {
614  CALL_HEAP_FUNCTION(Heap::CopyCode(*code), Code);
615}
616
617
618Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
619  CALL_HEAP_FUNCTION(Heap::CopyCode(*code, reloc_info), Code);
620}
621
622
623MUST_USE_RESULT static inline MaybeObject* DoCopyInsert(
624    DescriptorArray* array,
625    String* key,
626    Object* value,
627    PropertyAttributes attributes) {
628  CallbacksDescriptor desc(key, value, attributes);
629  MaybeObject* obj = array->CopyInsert(&desc, REMOVE_TRANSITIONS);
630  return obj;
631}
632
633
634// Allocate the new array.
635Handle<DescriptorArray> Factory::CopyAppendProxyDescriptor(
636    Handle<DescriptorArray> array,
637    Handle<String> key,
638    Handle<Object> value,
639    PropertyAttributes attributes) {
640  CALL_HEAP_FUNCTION(DoCopyInsert(*array, *key, *value, attributes),
641                     DescriptorArray);
642}
643
644
645Handle<String> Factory::SymbolFromString(Handle<String> value) {
646  CALL_HEAP_FUNCTION(Heap::LookupSymbol(*value), String);
647}
648
649
650Handle<DescriptorArray> Factory::CopyAppendCallbackDescriptors(
651    Handle<DescriptorArray> array,
652    Handle<Object> descriptors) {
653  v8::NeanderArray callbacks(descriptors);
654  int nof_callbacks = callbacks.length();
655  Handle<DescriptorArray> result =
656      NewDescriptorArray(array->number_of_descriptors() + nof_callbacks);
657
658  // Number of descriptors added to the result so far.
659  int descriptor_count = 0;
660
661  // Copy the descriptors from the array.
662  for (int i = 0; i < array->number_of_descriptors(); i++) {
663    if (array->GetType(i) != NULL_DESCRIPTOR) {
664      result->CopyFrom(descriptor_count++, *array, i);
665    }
666  }
667
668  // Number of duplicates detected.
669  int duplicates = 0;
670
671  // Fill in new callback descriptors.  Process the callbacks from
672  // back to front so that the last callback with a given name takes
673  // precedence over previously added callbacks with that name.
674  for (int i = nof_callbacks - 1; i >= 0; i--) {
675    Handle<AccessorInfo> entry =
676        Handle<AccessorInfo>(AccessorInfo::cast(callbacks.get(i)));
677    // Ensure the key is a symbol before writing into the instance descriptor.
678    Handle<String> key =
679        SymbolFromString(Handle<String>(String::cast(entry->name())));
680    // Check if a descriptor with this name already exists before writing.
681    if (result->LinearSearch(*key, descriptor_count) ==
682        DescriptorArray::kNotFound) {
683      CallbacksDescriptor desc(*key, *entry, entry->property_attributes());
684      result->Set(descriptor_count, &desc);
685      descriptor_count++;
686    } else {
687      duplicates++;
688    }
689  }
690
691  // If duplicates were detected, allocate a result of the right size
692  // and transfer the elements.
693  if (duplicates > 0) {
694    int number_of_descriptors = result->number_of_descriptors() - duplicates;
695    Handle<DescriptorArray> new_result =
696        NewDescriptorArray(number_of_descriptors);
697    for (int i = 0; i < number_of_descriptors; i++) {
698      new_result->CopyFrom(i, *result, i);
699    }
700    result = new_result;
701  }
702
703  // Sort the result before returning.
704  result->Sort();
705  return result;
706}
707
708
709Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
710                                      PretenureFlag pretenure) {
711  CALL_HEAP_FUNCTION(Heap::AllocateJSObject(*constructor, pretenure), JSObject);
712}
713
714
715Handle<GlobalObject> Factory::NewGlobalObject(
716    Handle<JSFunction> constructor) {
717  CALL_HEAP_FUNCTION(Heap::AllocateGlobalObject(*constructor),
718                     GlobalObject);
719}
720
721
722
723Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map) {
724  CALL_HEAP_FUNCTION(Heap::AllocateJSObjectFromMap(*map, NOT_TENURED),
725                     JSObject);
726}
727
728
729Handle<JSArray> Factory::NewJSArray(int length,
730                                    PretenureFlag pretenure) {
731  Handle<JSObject> obj = NewJSObject(Top::array_function(), pretenure);
732  CALL_HEAP_FUNCTION(Handle<JSArray>::cast(obj)->Initialize(length), JSArray);
733}
734
735
736Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArray> elements,
737                                                PretenureFlag pretenure) {
738  Handle<JSArray> result =
739      Handle<JSArray>::cast(NewJSObject(Top::array_function(), pretenure));
740  result->SetContent(*elements);
741  return result;
742}
743
744
745Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
746    Handle<String> name,
747    int number_of_literals,
748    Handle<Code> code,
749    Handle<SerializedScopeInfo> scope_info) {
750  Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
751  shared->set_code(*code);
752  shared->set_scope_info(*scope_info);
753  int literals_array_size = number_of_literals;
754  // If the function contains object, regexp or array literals,
755  // allocate extra space for a literals array prefix containing the
756  // context.
757  if (number_of_literals > 0) {
758    literals_array_size += JSFunction::kLiteralsPrefixSize;
759  }
760  shared->set_num_literals(literals_array_size);
761  return shared;
762}
763
764
765Handle<JSMessageObject> Factory::NewJSMessageObject(
766    Handle<String> type,
767    Handle<JSArray> arguments,
768    int start_position,
769    int end_position,
770    Handle<Object> script,
771    Handle<Object> stack_trace,
772    Handle<Object> stack_frames) {
773  CALL_HEAP_FUNCTION(Heap::AllocateJSMessageObject(*type,
774                                                   *arguments,
775                                                   start_position,
776                                                   end_position,
777                                                   *script,
778                                                   *stack_trace,
779                                                   *stack_frames),
780                     JSMessageObject);
781}
782
783Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
784  CALL_HEAP_FUNCTION(Heap::AllocateSharedFunctionInfo(*name),
785                     SharedFunctionInfo);
786}
787
788
789Handle<String> Factory::NumberToString(Handle<Object> number) {
790  CALL_HEAP_FUNCTION(Heap::NumberToString(*number), String);
791}
792
793
794Handle<NumberDictionary> Factory::DictionaryAtNumberPut(
795    Handle<NumberDictionary> dictionary,
796    uint32_t key,
797    Handle<Object> value) {
798  CALL_HEAP_FUNCTION(dictionary->AtNumberPut(key, *value), NumberDictionary);
799}
800
801
802Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
803                                              Handle<Object> prototype) {
804  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
805  CALL_HEAP_FUNCTION(Heap::AllocateFunction(*Top::function_map(),
806                                            *function_share,
807                                            *prototype),
808                     JSFunction);
809}
810
811
812Handle<JSFunction> Factory::NewFunction(Handle<String> name,
813                                        Handle<Object> prototype) {
814  Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
815  fun->set_context(Top::context()->global_context());
816  return fun;
817}
818
819
820Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
821    Handle<String> name) {
822  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
823  CALL_HEAP_FUNCTION(Heap::AllocateFunction(
824                         *Top::function_without_prototype_map(),
825                         *function_share,
826                         *the_hole_value()),
827                     JSFunction);
828}
829
830
831Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name) {
832  Handle<JSFunction> fun = NewFunctionWithoutPrototypeHelper(name);
833  fun->set_context(Top::context()->global_context());
834  return fun;
835}
836
837
838Handle<Object> Factory::ToObject(Handle<Object> object) {
839  CALL_HEAP_FUNCTION(object->ToObject(), Object);
840}
841
842
843Handle<Object> Factory::ToObject(Handle<Object> object,
844                                 Handle<Context> global_context) {
845  CALL_HEAP_FUNCTION(object->ToObject(*global_context), Object);
846}
847
848
849#ifdef ENABLE_DEBUGGER_SUPPORT
850Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
851  // Get the original code of the function.
852  Handle<Code> code(shared->code());
853
854  // Create a copy of the code before allocating the debug info object to avoid
855  // allocation while setting up the debug info object.
856  Handle<Code> original_code(*Factory::CopyCode(code));
857
858  // Allocate initial fixed array for active break points before allocating the
859  // debug info object to avoid allocation while setting up the debug info
860  // object.
861  Handle<FixedArray> break_points(
862      Factory::NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
863
864  // Create and set up the debug info object. Debug info contains function, a
865  // copy of the original code, the executing code and initial fixed array for
866  // active break points.
867  Handle<DebugInfo> debug_info =
868      Handle<DebugInfo>::cast(Factory::NewStruct(DEBUG_INFO_TYPE));
869  debug_info->set_shared(*shared);
870  debug_info->set_original_code(*original_code);
871  debug_info->set_code(*code);
872  debug_info->set_break_points(*break_points);
873
874  // Link debug info to function.
875  shared->set_debug_info(*debug_info);
876
877  return debug_info;
878}
879#endif
880
881
882Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
883                                             int length) {
884  CALL_HEAP_FUNCTION(Heap::AllocateArgumentsObject(*callee, length), JSObject);
885}
886
887
888Handle<JSFunction> Factory::CreateApiFunction(
889    Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
890  Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::HandleApiCall));
891  Handle<Code> construct_stub =
892      Handle<Code>(Builtins::builtin(Builtins::JSConstructStubApi));
893
894  int internal_field_count = 0;
895  if (!obj->instance_template()->IsUndefined()) {
896    Handle<ObjectTemplateInfo> instance_template =
897        Handle<ObjectTemplateInfo>(
898            ObjectTemplateInfo::cast(obj->instance_template()));
899    internal_field_count =
900        Smi::cast(instance_template->internal_field_count())->value();
901  }
902
903  int instance_size = kPointerSize * internal_field_count;
904  InstanceType type = INVALID_TYPE;
905  switch (instance_type) {
906    case JavaScriptObject:
907      type = JS_OBJECT_TYPE;
908      instance_size += JSObject::kHeaderSize;
909      break;
910    case InnerGlobalObject:
911      type = JS_GLOBAL_OBJECT_TYPE;
912      instance_size += JSGlobalObject::kSize;
913      break;
914    case OuterGlobalObject:
915      type = JS_GLOBAL_PROXY_TYPE;
916      instance_size += JSGlobalProxy::kSize;
917      break;
918    default:
919      break;
920  }
921  ASSERT(type != INVALID_TYPE);
922
923  Handle<JSFunction> result =
924      Factory::NewFunction(Factory::empty_symbol(),
925                           type,
926                           instance_size,
927                           code,
928                           true);
929  // Set class name.
930  Handle<Object> class_name = Handle<Object>(obj->class_name());
931  if (class_name->IsString()) {
932    result->shared()->set_instance_class_name(*class_name);
933    result->shared()->set_name(*class_name);
934  }
935
936  Handle<Map> map = Handle<Map>(result->initial_map());
937
938  // Mark as undetectable if needed.
939  if (obj->undetectable()) {
940    map->set_is_undetectable();
941  }
942
943  // Mark as hidden for the __proto__ accessor if needed.
944  if (obj->hidden_prototype()) {
945    map->set_is_hidden_prototype();
946  }
947
948  // Mark as needs_access_check if needed.
949  if (obj->needs_access_check()) {
950    map->set_is_access_check_needed(true);
951  }
952
953  // Set interceptor information in the map.
954  if (!obj->named_property_handler()->IsUndefined()) {
955    map->set_has_named_interceptor();
956  }
957  if (!obj->indexed_property_handler()->IsUndefined()) {
958    map->set_has_indexed_interceptor();
959  }
960
961  // Set instance call-as-function information in the map.
962  if (!obj->instance_call_handler()->IsUndefined()) {
963    map->set_has_instance_call_handler();
964  }
965
966  result->shared()->set_function_data(*obj);
967  result->shared()->set_construct_stub(*construct_stub);
968  result->shared()->DontAdaptArguments();
969
970  // Recursively copy parent templates' accessors, 'data' may be modified.
971  Handle<DescriptorArray> array =
972      Handle<DescriptorArray>(map->instance_descriptors());
973  while (true) {
974    Handle<Object> props = Handle<Object>(obj->property_accessors());
975    if (!props->IsUndefined()) {
976      array = Factory::CopyAppendCallbackDescriptors(array, props);
977    }
978    Handle<Object> parent = Handle<Object>(obj->parent_template());
979    if (parent->IsUndefined()) break;
980    obj = Handle<FunctionTemplateInfo>::cast(parent);
981  }
982  if (!array->IsEmpty()) {
983    map->set_instance_descriptors(*array);
984  }
985
986  ASSERT(result->shared()->IsApiFunction());
987  return result;
988}
989
990
991Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
992  CALL_HEAP_FUNCTION(MapCache::Allocate(at_least_space_for), MapCache);
993}
994
995
996MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
997                                                       FixedArray* keys,
998                                                       Map* map) {
999  Object* result;
1000  { MaybeObject* maybe_result =
1001        MapCache::cast(context->map_cache())->Put(keys, map);
1002    if (!maybe_result->ToObject(&result)) return maybe_result;
1003  }
1004  context->set_map_cache(MapCache::cast(result));
1005  return result;
1006}
1007
1008
1009Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1010                                        Handle<FixedArray> keys,
1011                                        Handle<Map> map) {
1012  CALL_HEAP_FUNCTION(UpdateMapCacheWith(*context, *keys, *map), MapCache);
1013}
1014
1015
1016Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1017                                               Handle<FixedArray> keys) {
1018  if (context->map_cache()->IsUndefined()) {
1019    // Allocate the new map cache for the global context.
1020    Handle<MapCache> new_cache = NewMapCache(24);
1021    context->set_map_cache(*new_cache);
1022  }
1023  // Check to see whether there is a matching element in the cache.
1024  Handle<MapCache> cache =
1025      Handle<MapCache>(MapCache::cast(context->map_cache()));
1026  Handle<Object> result = Handle<Object>(cache->Lookup(*keys));
1027  if (result->IsMap()) return Handle<Map>::cast(result);
1028  // Create a new map and add it to the cache.
1029  Handle<Map> map =
1030      CopyMap(Handle<Map>(context->object_function()->initial_map()),
1031              keys->length());
1032  AddToMapCache(context, keys, map);
1033  return Handle<Map>(map);
1034}
1035
1036
1037void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1038                                JSRegExp::Type type,
1039                                Handle<String> source,
1040                                JSRegExp::Flags flags,
1041                                Handle<Object> data) {
1042  Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1043
1044  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1045  store->set(JSRegExp::kSourceIndex, *source);
1046  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1047  store->set(JSRegExp::kAtomPatternIndex, *data);
1048  regexp->set_data(*store);
1049}
1050
1051void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1052                                    JSRegExp::Type type,
1053                                    Handle<String> source,
1054                                    JSRegExp::Flags flags,
1055                                    int capture_count) {
1056  Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1057
1058  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1059  store->set(JSRegExp::kSourceIndex, *source);
1060  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1061  store->set(JSRegExp::kIrregexpASCIICodeIndex, Heap::the_hole_value());
1062  store->set(JSRegExp::kIrregexpUC16CodeIndex, Heap::the_hole_value());
1063  store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
1064  store->set(JSRegExp::kIrregexpCaptureCountIndex,
1065             Smi::FromInt(capture_count));
1066  regexp->set_data(*store);
1067}
1068
1069
1070
1071void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
1072                                Handle<JSObject> instance,
1073                                bool* pending_exception) {
1074  // Configure the instance by adding the properties specified by the
1075  // instance template.
1076  Handle<Object> instance_template = Handle<Object>(desc->instance_template());
1077  if (!instance_template->IsUndefined()) {
1078    Execution::ConfigureInstance(instance,
1079                                 instance_template,
1080                                 pending_exception);
1081  } else {
1082    *pending_exception = false;
1083  }
1084}
1085
1086
1087} }  // namespace v8::internal
1088