• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/heap/factory.h"
6 
7 #include <algorithm>  // For copy
8 #include <memory>     // For shared_ptr<>
9 #include <string>
10 #include <utility>  // For move
11 
12 #include "src/ast/ast-source-ranges.h"
13 #include "src/base/bits.h"
14 #include "src/builtins/accessors.h"
15 #include "src/builtins/constants-table-builder.h"
16 #include "src/codegen/compilation-cache.h"
17 #include "src/codegen/compiler.h"
18 #include "src/common/globals.h"
19 #include "src/diagnostics/basic-block-profiler.h"
20 #include "src/execution/isolate-inl.h"
21 #include "src/execution/protectors-inl.h"
22 #include "src/heap/basic-memory-chunk.h"
23 #include "src/heap/heap-inl.h"
24 #include "src/heap/incremental-marking.h"
25 #include "src/heap/mark-compact-inl.h"
26 #include "src/heap/memory-chunk.h"
27 #include "src/heap/read-only-heap.h"
28 #include "src/ic/handler-configuration-inl.h"
29 #include "src/init/bootstrapper.h"
30 #include "src/interpreter/interpreter.h"
31 #include "src/logging/counters.h"
32 #include "src/logging/log.h"
33 #include "src/numbers/conversions.h"
34 #include "src/numbers/hash-seed-inl.h"
35 #include "src/objects/allocation-site-inl.h"
36 #include "src/objects/allocation-site-scopes.h"
37 #include "src/objects/api-callbacks.h"
38 #include "src/objects/arguments-inl.h"
39 #include "src/objects/bigint.h"
40 #include "src/objects/cell-inl.h"
41 #include "src/objects/debug-objects-inl.h"
42 #include "src/objects/embedder-data-array-inl.h"
43 #include "src/objects/feedback-cell-inl.h"
44 #include "src/objects/fixed-array-inl.h"
45 #include "src/objects/foreign-inl.h"
46 #include "src/objects/frame-array-inl.h"
47 #include "src/objects/instance-type-inl.h"
48 #include "src/objects/js-array-inl.h"
49 #include "src/objects/js-collection-inl.h"
50 #include "src/objects/js-generator-inl.h"
51 #include "src/objects/js-regexp-inl.h"
52 #include "src/objects/js-weak-refs-inl.h"
53 #include "src/objects/literal-objects-inl.h"
54 #include "src/objects/microtask-inl.h"
55 #include "src/objects/module-inl.h"
56 #include "src/objects/promise-inl.h"
57 #include "src/objects/property-descriptor-object-inl.h"
58 #include "src/objects/scope-info.h"
59 #include "src/objects/stack-frame-info-inl.h"
60 #include "src/objects/string-set-inl.h"
61 #include "src/objects/struct-inl.h"
62 #include "src/objects/synthetic-module-inl.h"
63 #include "src/objects/template-objects-inl.h"
64 #include "src/objects/transitions-inl.h"
65 #include "src/roots/roots.h"
66 #include "src/strings/unicode-inl.h"
67 
68 namespace v8 {
69 namespace internal {
70 
CodeBuilder(Isolate * isolate,const CodeDesc & desc,CodeKind kind)71 Factory::CodeBuilder::CodeBuilder(Isolate* isolate, const CodeDesc& desc,
72                                   CodeKind kind)
73     : isolate_(isolate),
74       code_desc_(desc),
75       kind_(kind),
76       source_position_table_(isolate_->factory()->empty_byte_array()) {}
77 
BuildInternal(bool retry_allocation_or_fail)78 MaybeHandle<Code> Factory::CodeBuilder::BuildInternal(
79     bool retry_allocation_or_fail) {
80   const auto factory = isolate_->factory();
81   // Allocate objects needed for code initialization.
82   Handle<ByteArray> reloc_info =
83       factory->NewByteArray(code_desc_.reloc_size, AllocationType::kOld);
84   Handle<CodeDataContainer> data_container;
85 
86   // Use a canonical off-heap trampoline CodeDataContainer if possible.
87   const int32_t promise_rejection_flag =
88       Code::IsPromiseRejectionField::encode(true);
89   if (read_only_data_container_ &&
90       (kind_specific_flags_ == 0 ||
91        kind_specific_flags_ == promise_rejection_flag)) {
92     const ReadOnlyRoots roots(isolate_);
93     const auto canonical_code_data_container =
94         kind_specific_flags_ == 0
95             ? roots.trampoline_trivial_code_data_container_handle()
96             : roots.trampoline_promise_rejection_code_data_container_handle();
97     DCHECK_EQ(canonical_code_data_container->kind_specific_flags(),
98               kind_specific_flags_);
99     data_container = canonical_code_data_container;
100   } else {
101     data_container = factory->NewCodeDataContainer(
102         0, read_only_data_container_ ? AllocationType::kReadOnly
103                                      : AllocationType::kOld);
104     data_container->set_kind_specific_flags(kind_specific_flags_);
105   }
106 
107   // Basic block profiling data for builtins is stored in the JS heap rather
108   // than in separately-allocated C++ objects. Allocate that data now if
109   // appropriate.
110   Handle<OnHeapBasicBlockProfilerData> on_heap_profiler_data;
111   if (profiler_data_ && isolate_->IsGeneratingEmbeddedBuiltins()) {
112     on_heap_profiler_data = profiler_data_->CopyToJSHeap(isolate_);
113 
114     // Add the on-heap data to a global list, which keeps it alive and allows
115     // iteration.
116     Handle<ArrayList> list(isolate_->heap()->basic_block_profiling_data(),
117                            isolate_);
118     Handle<ArrayList> new_list =
119         ArrayList::Add(isolate_, list, on_heap_profiler_data);
120     isolate_->heap()->SetBasicBlockProfilingData(new_list);
121   }
122 
123   STATIC_ASSERT(Code::kOnHeapBodyIsContiguous);
124   const int object_size = Code::SizeFor(code_desc_.body_size());
125 
126   Handle<Code> code;
127   {
128     Heap* heap = isolate_->heap();
129 
130     CodePageCollectionMemoryModificationScope code_allocation(heap);
131     HeapObject result;
132     AllocationType allocation_type =
133         is_executable_ ? AllocationType::kCode : AllocationType::kReadOnly;
134     if (retry_allocation_or_fail) {
135       result = heap->AllocateRawWith<Heap::kRetryOrFail>(
136           object_size, allocation_type, AllocationOrigin::kRuntime);
137     } else {
138       result = heap->AllocateRawWith<Heap::kLightRetry>(
139           object_size, allocation_type, AllocationOrigin::kRuntime);
140       // Return an empty handle if we cannot allocate the code object.
141       if (result.is_null()) return MaybeHandle<Code>();
142     }
143 
144     // The code object has not been fully initialized yet.  We rely on the
145     // fact that no allocation will happen from this point on.
146     DisallowHeapAllocation no_gc;
147 
148     result.set_map_after_allocation(*factory->code_map(), SKIP_WRITE_BARRIER);
149     code = handle(Code::cast(result), isolate_);
150     if (is_executable_) {
151       DCHECK(IsAligned(code->address(), kCodeAlignment));
152       DCHECK_IMPLIES(
153           !V8_ENABLE_THIRD_PARTY_HEAP_BOOL &&
154               !heap->memory_allocator()->code_range().is_empty(),
155           heap->memory_allocator()->code_range().contains(code->address()));
156     }
157 
158     constexpr bool kIsNotOffHeapTrampoline = false;
159 
160     code->set_raw_instruction_size(code_desc_.instruction_size());
161     code->set_raw_metadata_size(code_desc_.metadata_size());
162     code->set_relocation_info(*reloc_info);
163     code->initialize_flags(kind_, is_turbofanned_, stack_slots_,
164                            kIsNotOffHeapTrampoline);
165     code->set_builtin_index(builtin_index_);
166     code->set_inlined_bytecode_size(inlined_bytecode_size_);
167     code->set_code_data_container(*data_container, kReleaseStore);
168     code->set_deoptimization_data(*deoptimization_data_);
169     code->set_source_position_table(*source_position_table_);
170     code->set_handler_table_offset(code_desc_.handler_table_offset_relative());
171     code->set_constant_pool_offset(code_desc_.constant_pool_offset_relative());
172     code->set_code_comments_offset(code_desc_.code_comments_offset_relative());
173     code->set_unwinding_info_offset(
174         code_desc_.unwinding_info_offset_relative());
175 
176     // Allow self references to created code object by patching the handle to
177     // point to the newly allocated Code object.
178     Handle<Object> self_reference;
179     if (self_reference_.ToHandle(&self_reference)) {
180       DCHECK(self_reference->IsOddball());
181       DCHECK(Oddball::cast(*self_reference).kind() ==
182              Oddball::kSelfReferenceMarker);
183       if (isolate_->IsGeneratingEmbeddedBuiltins()) {
184         isolate_->builtins_constants_table_builder()->PatchSelfReference(
185             self_reference, code);
186       }
187       self_reference.PatchValue(*code);
188     }
189 
190     // Likewise, any references to the basic block counters marker need to be
191     // updated to point to the newly-allocated counters array.
192     if (!on_heap_profiler_data.is_null()) {
193       isolate_->builtins_constants_table_builder()
194           ->PatchBasicBlockCountersReference(
195               handle(on_heap_profiler_data->counts(), isolate_));
196     }
197 
198     // Migrate generated code.
199     // The generated code can contain embedded objects (typically from handles)
200     // in a pointer-to-tagged-value format (i.e. with indirection like a handle)
201     // that are dereferenced during the copy to point directly to the actual
202     // heap objects. These pointers can include references to the code object
203     // itself, through the self_reference parameter.
204     code->CopyFromNoFlush(heap, code_desc_);
205 
206     code->clear_padding();
207 
208 #ifdef VERIFY_HEAP
209     if (FLAG_verify_heap) code->ObjectVerify(isolate_);
210 #endif
211 
212     // Flush the instruction cache before changing the permissions.
213     // Note: we do this before setting permissions to ReadExecute because on
214     // some older ARM kernels there is a bug which causes an access error on
215     // cache flush instructions to trigger access error on non-writable memory.
216     // See https://bugs.chromium.org/p/v8/issues/detail?id=8157
217     code->FlushICache();
218   }
219 
220   if (profiler_data_ && FLAG_turbo_profiling_verbose) {
221 #ifdef ENABLE_DISASSEMBLER
222     std::ostringstream os;
223     code->Disassemble(nullptr, os, isolate_);
224     if (!on_heap_profiler_data.is_null()) {
225       Handle<String> disassembly =
226           isolate_->factory()->NewStringFromAsciiChecked(os.str().c_str(),
227                                                          AllocationType::kOld);
228       on_heap_profiler_data->set_code(*disassembly);
229     } else {
230       profiler_data_->SetCode(os);
231     }
232 #endif  // ENABLE_DISASSEMBLER
233   }
234 
235   return code;
236 }
237 
TryBuild()238 MaybeHandle<Code> Factory::CodeBuilder::TryBuild() {
239   return BuildInternal(false);
240 }
241 
Build()242 Handle<Code> Factory::CodeBuilder::Build() {
243   return BuildInternal(true).ToHandleChecked();
244 }
245 
AllocateRaw(int size,AllocationType allocation,AllocationAlignment alignment)246 HeapObject Factory::AllocateRaw(int size, AllocationType allocation,
247                                 AllocationAlignment alignment) {
248   return isolate()->heap()->AllocateRawWith<Heap::kRetryOrFail>(
249       size, allocation, AllocationOrigin::kRuntime, alignment);
250 }
251 
AllocateRawWithAllocationSite(Handle<Map> map,AllocationType allocation,Handle<AllocationSite> allocation_site)252 HeapObject Factory::AllocateRawWithAllocationSite(
253     Handle<Map> map, AllocationType allocation,
254     Handle<AllocationSite> allocation_site) {
255   DCHECK(map->instance_type() != MAP_TYPE);
256   int size = map->instance_size();
257   if (!allocation_site.is_null()) size += AllocationMemento::kSize;
258   HeapObject result =
259       isolate()->heap()->AllocateRawWith<Heap::kRetryOrFail>(size, allocation);
260   WriteBarrierMode write_barrier_mode = allocation == AllocationType::kYoung
261                                             ? SKIP_WRITE_BARRIER
262                                             : UPDATE_WRITE_BARRIER;
263   result.set_map_after_allocation(*map, write_barrier_mode);
264   if (!allocation_site.is_null()) {
265     AllocationMemento alloc_memento = AllocationMemento::unchecked_cast(
266         Object(result.ptr() + map->instance_size()));
267     InitializeAllocationMemento(alloc_memento, *allocation_site);
268   }
269   return result;
270 }
271 
InitializeAllocationMemento(AllocationMemento memento,AllocationSite allocation_site)272 void Factory::InitializeAllocationMemento(AllocationMemento memento,
273                                           AllocationSite allocation_site) {
274   memento.set_map_after_allocation(*allocation_memento_map(),
275                                    SKIP_WRITE_BARRIER);
276   memento.set_allocation_site(allocation_site, SKIP_WRITE_BARRIER);
277   if (FLAG_allocation_site_pretenuring) {
278     allocation_site.IncrementMementoCreateCount();
279   }
280 }
281 
New(Handle<Map> map,AllocationType allocation)282 HeapObject Factory::New(Handle<Map> map, AllocationType allocation) {
283   DCHECK(map->instance_type() != MAP_TYPE);
284   int size = map->instance_size();
285   HeapObject result =
286       isolate()->heap()->AllocateRawWith<Heap::kRetryOrFail>(size, allocation);
287   // New space objects are allocated white.
288   WriteBarrierMode write_barrier_mode = allocation == AllocationType::kYoung
289                                             ? SKIP_WRITE_BARRIER
290                                             : UPDATE_WRITE_BARRIER;
291   result.set_map_after_allocation(*map, write_barrier_mode);
292   return result;
293 }
294 
NewFillerObject(int size,bool double_align,AllocationType allocation,AllocationOrigin origin)295 Handle<HeapObject> Factory::NewFillerObject(int size, bool double_align,
296                                             AllocationType allocation,
297                                             AllocationOrigin origin) {
298   AllocationAlignment alignment = double_align ? kDoubleAligned : kWordAligned;
299   Heap* heap = isolate()->heap();
300   HeapObject result = heap->AllocateRawWith<Heap::kRetryOrFail>(
301       size, allocation, origin, alignment);
302   heap->CreateFillerObjectAt(result.address(), size, ClearRecordedSlots::kNo);
303   return Handle<HeapObject>(result, isolate());
304 }
305 
NewPrototypeInfo()306 Handle<PrototypeInfo> Factory::NewPrototypeInfo() {
307   Handle<PrototypeInfo> result = Handle<PrototypeInfo>::cast(
308       NewStruct(PROTOTYPE_INFO_TYPE, AllocationType::kOld));
309   result->set_prototype_users(Smi::zero());
310   result->set_registry_slot(PrototypeInfo::UNREGISTERED);
311   result->set_bit_field(0);
312   result->set_module_namespace(*undefined_value());
313   return result;
314 }
315 
NewEnumCache(Handle<FixedArray> keys,Handle<FixedArray> indices)316 Handle<EnumCache> Factory::NewEnumCache(Handle<FixedArray> keys,
317                                         Handle<FixedArray> indices) {
318   Handle<EnumCache> result =
319       Handle<EnumCache>::cast(NewStruct(ENUM_CACHE_TYPE, AllocationType::kOld));
320   result->set_keys(*keys);
321   result->set_indices(*indices);
322   return result;
323 }
324 
NewTuple2(Handle<Object> value1,Handle<Object> value2,AllocationType allocation)325 Handle<Tuple2> Factory::NewTuple2(Handle<Object> value1, Handle<Object> value2,
326                                   AllocationType allocation) {
327   Handle<Tuple2> result =
328       Handle<Tuple2>::cast(NewStruct(TUPLE2_TYPE, allocation));
329   result->set_value1(*value1);
330   result->set_value2(*value2);
331   return result;
332 }
333 
NewOddball(Handle<Map> map,const char * to_string,Handle<Object> to_number,const char * type_of,byte kind)334 Handle<Oddball> Factory::NewOddball(Handle<Map> map, const char* to_string,
335                                     Handle<Object> to_number,
336                                     const char* type_of, byte kind) {
337   Handle<Oddball> oddball(Oddball::cast(New(map, AllocationType::kReadOnly)),
338                           isolate());
339   Oddball::Initialize(isolate(), oddball, to_string, to_number, type_of, kind);
340   return oddball;
341 }
342 
NewSelfReferenceMarker()343 Handle<Oddball> Factory::NewSelfReferenceMarker() {
344   return NewOddball(self_reference_marker_map(), "self_reference_marker",
345                     handle(Smi::FromInt(-1), isolate()), "undefined",
346                     Oddball::kSelfReferenceMarker);
347 }
348 
NewBasicBlockCountersMarker()349 Handle<Oddball> Factory::NewBasicBlockCountersMarker() {
350   return NewOddball(basic_block_counters_marker_map(),
351                     "basic_block_counters_marker",
352                     handle(Smi::FromInt(-1), isolate()), "undefined",
353                     Oddball::kBasicBlockCountersMarker);
354 }
355 
NewPropertyArray(int length)356 Handle<PropertyArray> Factory::NewPropertyArray(int length) {
357   DCHECK_LE(0, length);
358   if (length == 0) return empty_property_array();
359   HeapObject result = AllocateRawFixedArray(length, AllocationType::kYoung);
360   result.set_map_after_allocation(*property_array_map(), SKIP_WRITE_BARRIER);
361   Handle<PropertyArray> array(PropertyArray::cast(result), isolate());
362   array->initialize_length(length);
363   MemsetTagged(array->data_start(), *undefined_value(), length);
364   return array;
365 }
366 
TryNewFixedArray(int length,AllocationType allocation_type)367 MaybeHandle<FixedArray> Factory::TryNewFixedArray(
368     int length, AllocationType allocation_type) {
369   DCHECK_LE(0, length);
370   if (length == 0) return empty_fixed_array();
371 
372   int size = FixedArray::SizeFor(length);
373   Heap* heap = isolate()->heap();
374   AllocationResult allocation = heap->AllocateRaw(size, allocation_type);
375   HeapObject result;
376   if (!allocation.To(&result)) return MaybeHandle<FixedArray>();
377   if ((size > Heap::MaxRegularHeapObjectSize(allocation_type)) &&
378       FLAG_use_marking_progress_bar) {
379     BasicMemoryChunk* chunk = BasicMemoryChunk::FromHeapObject(result);
380     chunk->SetFlag<AccessMode::ATOMIC>(MemoryChunk::HAS_PROGRESS_BAR);
381   }
382   result.set_map_after_allocation(*fixed_array_map(), SKIP_WRITE_BARRIER);
383   Handle<FixedArray> array(FixedArray::cast(result), isolate());
384   array->set_length(length);
385   MemsetTagged(array->data_start(), ReadOnlyRoots(heap).undefined_value(),
386                length);
387   return array;
388 }
389 
NewUninitializedFixedArray(int length)390 Handle<FixedArray> Factory::NewUninitializedFixedArray(int length) {
391   if (length == 0) return empty_fixed_array();
392   if (length < 0 || length > FixedArray::kMaxLength) {
393     isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
394   }
395 
396   // TODO(ulan): As an experiment this temporarily returns an initialized fixed
397   // array. After getting canary/performance coverage, either remove the
398   // function or revert to returning uninitilized array.
399   return NewFixedArrayWithFiller(read_only_roots().fixed_array_map_handle(),
400                                  length, undefined_value(),
401                                  AllocationType::kYoung);
402 }
403 
NewClosureFeedbackCellArray(int length)404 Handle<ClosureFeedbackCellArray> Factory::NewClosureFeedbackCellArray(
405     int length) {
406   if (length == 0) return empty_closure_feedback_cell_array();
407 
408   Handle<ClosureFeedbackCellArray> feedback_cell_array =
409       Handle<ClosureFeedbackCellArray>::cast(NewFixedArrayWithMap(
410           read_only_roots().closure_feedback_cell_array_map_handle(), length,
411           AllocationType::kOld));
412 
413   return feedback_cell_array;
414 }
415 
NewFeedbackVector(Handle<SharedFunctionInfo> shared,Handle<ClosureFeedbackCellArray> closure_feedback_cell_array)416 Handle<FeedbackVector> Factory::NewFeedbackVector(
417     Handle<SharedFunctionInfo> shared,
418     Handle<ClosureFeedbackCellArray> closure_feedback_cell_array) {
419   int length = shared->feedback_metadata().slot_count();
420   DCHECK_LE(0, length);
421   int size = FeedbackVector::SizeFor(length);
422 
423   HeapObject result = AllocateRawWithImmortalMap(size, AllocationType::kOld,
424                                                  *feedback_vector_map());
425   Handle<FeedbackVector> vector(FeedbackVector::cast(result), isolate());
426   vector->set_shared_function_info(*shared);
427   vector->set_maybe_optimized_code(
428       HeapObjectReference::ClearedValue(isolate()));
429   vector->set_length(length);
430   vector->set_invocation_count(0);
431   vector->set_profiler_ticks(0);
432   vector->InitializeOptimizationState();
433   vector->set_closure_feedback_cell_array(*closure_feedback_cell_array);
434 
435   // TODO(leszeks): Initialize based on the feedback metadata.
436   MemsetTagged(ObjectSlot(vector->slots_start()), *undefined_value(), length);
437   return vector;
438 }
439 
NewEmbedderDataArray(int length)440 Handle<EmbedderDataArray> Factory::NewEmbedderDataArray(int length) {
441   DCHECK_LE(0, length);
442   int size = EmbedderDataArray::SizeFor(length);
443 
444   HeapObject result = AllocateRawWithImmortalMap(size, AllocationType::kYoung,
445                                                  *embedder_data_array_map());
446   Handle<EmbedderDataArray> array(EmbedderDataArray::cast(result), isolate());
447   array->set_length(length);
448 
449   if (length > 0) {
450     ObjectSlot start(array->slots_start());
451     ObjectSlot end(array->slots_end());
452     size_t slot_count = end - start;
453     MemsetTagged(start, *undefined_value(), slot_count);
454     for (int i = 0; i < length; i++) {
455       // TODO(v8:10391, saelo): Handle external pointers in EmbedderDataSlot
456       EmbedderDataSlot(*array, i).AllocateExternalPointerEntry(isolate());
457     }
458   }
459   return array;
460 }
461 
NewFixedDoubleArrayWithHoles(int length)462 Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(int length) {
463   DCHECK_LE(0, length);
464   Handle<FixedArrayBase> array = NewFixedDoubleArray(length);
465   if (length > 0) {
466     Handle<FixedDoubleArray>::cast(array)->FillWithHoles(0, length);
467   }
468   return array;
469 }
470 
NewFrameArray(int number_of_frames)471 Handle<FrameArray> Factory::NewFrameArray(int number_of_frames) {
472   DCHECK_LE(0, number_of_frames);
473   Handle<FixedArray> result =
474       NewFixedArrayWithHoles(FrameArray::LengthFor(number_of_frames));
475   result->set(FrameArray::kFrameCountIndex, Smi::zero());
476   return Handle<FrameArray>::cast(result);
477 }
478 
479 template <typename T>
AllocateSmallOrderedHashTable(Handle<Map> map,int capacity,AllocationType allocation)480 Handle<T> Factory::AllocateSmallOrderedHashTable(Handle<Map> map, int capacity,
481                                                  AllocationType allocation) {
482   // Capacity must be a power of two, since we depend on being able
483   // to divide and multiple by 2 (kLoadFactor) to derive capacity
484   // from number of buckets. If we decide to change kLoadFactor
485   // to something other than 2, capacity should be stored as another
486   // field of this object.
487   DCHECK_EQ(T::kLoadFactor, 2);
488   capacity = base::bits::RoundUpToPowerOfTwo32(Max(T::kMinCapacity, capacity));
489   capacity = Min(capacity, T::kMaxCapacity);
490 
491   DCHECK_LT(0, capacity);
492   DCHECK_EQ(0, capacity % T::kLoadFactor);
493 
494   int size = T::SizeFor(capacity);
495   HeapObject result = AllocateRawWithImmortalMap(size, allocation, *map);
496   Handle<T> table(T::cast(result), isolate());
497   table->Initialize(isolate(), capacity);
498   return table;
499 }
500 
NewSmallOrderedHashSet(int capacity,AllocationType allocation)501 Handle<SmallOrderedHashSet> Factory::NewSmallOrderedHashSet(
502     int capacity, AllocationType allocation) {
503   return AllocateSmallOrderedHashTable<SmallOrderedHashSet>(
504       small_ordered_hash_set_map(), capacity, allocation);
505 }
506 
NewSmallOrderedHashMap(int capacity,AllocationType allocation)507 Handle<SmallOrderedHashMap> Factory::NewSmallOrderedHashMap(
508     int capacity, AllocationType allocation) {
509   return AllocateSmallOrderedHashTable<SmallOrderedHashMap>(
510       small_ordered_hash_map_map(), capacity, allocation);
511 }
512 
NewSmallOrderedNameDictionary(int capacity,AllocationType allocation)513 Handle<SmallOrderedNameDictionary> Factory::NewSmallOrderedNameDictionary(
514     int capacity, AllocationType allocation) {
515   Handle<SmallOrderedNameDictionary> dict =
516       AllocateSmallOrderedHashTable<SmallOrderedNameDictionary>(
517           small_ordered_name_dictionary_map(), capacity, allocation);
518   dict->SetHash(PropertyArray::kNoHashSentinel);
519   return dict;
520 }
521 
NewOrderedHashSet()522 Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
523   return OrderedHashSet::Allocate(isolate(), OrderedHashSet::kInitialCapacity,
524                                   AllocationType::kYoung)
525       .ToHandleChecked();
526 }
527 
NewOrderedHashMap()528 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
529   return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kInitialCapacity,
530                                   AllocationType::kYoung)
531       .ToHandleChecked();
532 }
533 
NewOrderedNameDictionary(int capacity)534 Handle<OrderedNameDictionary> Factory::NewOrderedNameDictionary(int capacity) {
535   return OrderedNameDictionary::Allocate(isolate(), capacity,
536                                          AllocationType::kYoung)
537       .ToHandleChecked();
538 }
539 
NewNameDictionary(int at_least_space_for)540 Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
541   return NameDictionary::New(isolate(), at_least_space_for);
542 }
543 
NewPropertyDescriptorObject()544 Handle<PropertyDescriptorObject> Factory::NewPropertyDescriptorObject() {
545   Handle<PropertyDescriptorObject> object =
546       Handle<PropertyDescriptorObject>::cast(
547           NewStruct(PROPERTY_DESCRIPTOR_OBJECT_TYPE, AllocationType::kYoung));
548   object->set_flags(0);
549   object->set_value(*the_hole_value(), SKIP_WRITE_BARRIER);
550   object->set_get(*the_hole_value(), SKIP_WRITE_BARRIER);
551   object->set_set(*the_hole_value(), SKIP_WRITE_BARRIER);
552   return object;
553 }
554 
555 // Internalized strings are created in the old generation (data space).
InternalizeUtf8String(const Vector<const char> & string)556 Handle<String> Factory::InternalizeUtf8String(
557     const Vector<const char>& string) {
558   Vector<const uint8_t> utf8_data = Vector<const uint8_t>::cast(string);
559   Utf8Decoder decoder(utf8_data);
560   if (decoder.is_ascii()) return InternalizeString(utf8_data);
561   if (decoder.is_one_byte()) {
562     std::unique_ptr<uint8_t[]> buffer(new uint8_t[decoder.utf16_length()]);
563     decoder.Decode(buffer.get(), utf8_data);
564     return InternalizeString(
565         Vector<const uint8_t>(buffer.get(), decoder.utf16_length()));
566   }
567   std::unique_ptr<uint16_t[]> buffer(new uint16_t[decoder.utf16_length()]);
568   decoder.Decode(buffer.get(), utf8_data);
569   return InternalizeString(
570       Vector<const uc16>(buffer.get(), decoder.utf16_length()));
571 }
572 
573 template <typename SeqString>
InternalizeString(Handle<SeqString> string,int from,int length,bool convert_encoding)574 Handle<String> Factory::InternalizeString(Handle<SeqString> string, int from,
575                                           int length, bool convert_encoding) {
576   SeqSubStringKey<SeqString> key(isolate(), string, from, length,
577                                  convert_encoding);
578   return InternalizeStringWithKey(&key);
579 }
580 
581 template Handle<String> Factory::InternalizeString(
582     Handle<SeqOneByteString> string, int from, int length,
583     bool convert_encoding);
584 template Handle<String> Factory::InternalizeString(
585     Handle<SeqTwoByteString> string, int from, int length,
586     bool convert_encoding);
587 
NewStringFromOneByte(const Vector<const uint8_t> & string,AllocationType allocation)588 MaybeHandle<String> Factory::NewStringFromOneByte(
589     const Vector<const uint8_t>& string, AllocationType allocation) {
590   DCHECK_NE(allocation, AllocationType::kReadOnly);
591   int length = string.length();
592   if (length == 0) return empty_string();
593   if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
594   Handle<SeqOneByteString> result;
595   ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
596                              NewRawOneByteString(string.length(), allocation),
597                              String);
598 
599   DisallowHeapAllocation no_gc;
600   // Copy the characters into the new object.
601   CopyChars(SeqOneByteString::cast(*result).GetChars(no_gc), string.begin(),
602             length);
603   return result;
604 }
605 
NewStringFromUtf8(const Vector<const char> & string,AllocationType allocation)606 MaybeHandle<String> Factory::NewStringFromUtf8(const Vector<const char>& string,
607                                                AllocationType allocation) {
608   Vector<const uint8_t> utf8_data = Vector<const uint8_t>::cast(string);
609   Utf8Decoder decoder(utf8_data);
610 
611   if (decoder.utf16_length() == 0) return empty_string();
612 
613   if (decoder.is_one_byte()) {
614     // Allocate string.
615     Handle<SeqOneByteString> result;
616     ASSIGN_RETURN_ON_EXCEPTION(
617         isolate(), result,
618         NewRawOneByteString(decoder.utf16_length(), allocation), String);
619 
620     DisallowHeapAllocation no_gc;
621     decoder.Decode(result->GetChars(no_gc), utf8_data);
622     return result;
623   }
624 
625   // Allocate string.
626   Handle<SeqTwoByteString> result;
627   ASSIGN_RETURN_ON_EXCEPTION(
628       isolate(), result,
629       NewRawTwoByteString(decoder.utf16_length(), allocation), String);
630 
631   DisallowHeapAllocation no_gc;
632   decoder.Decode(result->GetChars(no_gc), utf8_data);
633   return result;
634 }
635 
NewStringFromUtf8SubString(Handle<SeqOneByteString> str,int begin,int length,AllocationType allocation)636 MaybeHandle<String> Factory::NewStringFromUtf8SubString(
637     Handle<SeqOneByteString> str, int begin, int length,
638     AllocationType allocation) {
639   Vector<const uint8_t> utf8_data;
640   {
641     DisallowHeapAllocation no_gc;
642     utf8_data = Vector<const uint8_t>(str->GetChars(no_gc) + begin, length);
643   }
644   Utf8Decoder decoder(utf8_data);
645 
646   if (length == 1) {
647     uint16_t t;
648     // Decode even in the case of length 1 since it can be a bad character.
649     decoder.Decode(&t, utf8_data);
650     return LookupSingleCharacterStringFromCode(t);
651   }
652 
653   if (decoder.is_ascii()) {
654     // If the string is ASCII, we can just make a substring.
655     // TODO(v8): the allocation flag is ignored in this case.
656     return NewSubString(str, begin, begin + length);
657   }
658 
659   DCHECK_GT(decoder.utf16_length(), 0);
660 
661   if (decoder.is_one_byte()) {
662     // Allocate string.
663     Handle<SeqOneByteString> result;
664     ASSIGN_RETURN_ON_EXCEPTION(
665         isolate(), result,
666         NewRawOneByteString(decoder.utf16_length(), allocation), String);
667     DisallowHeapAllocation no_gc;
668     // Update pointer references, since the original string may have moved after
669     // allocation.
670     utf8_data = Vector<const uint8_t>(str->GetChars(no_gc) + begin, length);
671     decoder.Decode(result->GetChars(no_gc), utf8_data);
672     return result;
673   }
674 
675   // Allocate string.
676   Handle<SeqTwoByteString> result;
677   ASSIGN_RETURN_ON_EXCEPTION(
678       isolate(), result,
679       NewRawTwoByteString(decoder.utf16_length(), allocation), String);
680 
681   DisallowHeapAllocation no_gc;
682   // Update pointer references, since the original string may have moved after
683   // allocation.
684   utf8_data = Vector<const uint8_t>(str->GetChars(no_gc) + begin, length);
685   decoder.Decode(result->GetChars(no_gc), utf8_data);
686   return result;
687 }
688 
NewStringFromTwoByte(const uc16 * string,int length,AllocationType allocation)689 MaybeHandle<String> Factory::NewStringFromTwoByte(const uc16* string,
690                                                   int length,
691                                                   AllocationType allocation) {
692   DCHECK_NE(allocation, AllocationType::kReadOnly);
693   if (length == 0) return empty_string();
694   if (String::IsOneByte(string, length)) {
695     if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
696     Handle<SeqOneByteString> result;
697     ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
698                                NewRawOneByteString(length, allocation), String);
699     DisallowHeapAllocation no_gc;
700     CopyChars(result->GetChars(no_gc), string, length);
701     return result;
702   } else {
703     Handle<SeqTwoByteString> result;
704     ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
705                                NewRawTwoByteString(length, allocation), String);
706     DisallowHeapAllocation no_gc;
707     CopyChars(result->GetChars(no_gc), string, length);
708     return result;
709   }
710 }
711 
NewStringFromTwoByte(const Vector<const uc16> & string,AllocationType allocation)712 MaybeHandle<String> Factory::NewStringFromTwoByte(
713     const Vector<const uc16>& string, AllocationType allocation) {
714   return NewStringFromTwoByte(string.begin(), string.length(), allocation);
715 }
716 
NewStringFromTwoByte(const ZoneVector<uc16> * string,AllocationType allocation)717 MaybeHandle<String> Factory::NewStringFromTwoByte(
718     const ZoneVector<uc16>* string, AllocationType allocation) {
719   return NewStringFromTwoByte(string->data(), static_cast<int>(string->size()),
720                               allocation);
721 }
722 
723 namespace {
724 
IsOneByte(Handle<String> str)725 bool inline IsOneByte(Handle<String> str) {
726   return str->IsOneByteRepresentation();
727 }
728 
WriteOneByteData(Handle<String> s,uint8_t * chars,int len)729 inline void WriteOneByteData(Handle<String> s, uint8_t* chars, int len) {
730   DCHECK(s->length() == len);
731   String::WriteToFlat(*s, chars, 0, len);
732 }
733 
WriteTwoByteData(Handle<String> s,uint16_t * chars,int len)734 inline void WriteTwoByteData(Handle<String> s, uint16_t* chars, int len) {
735   DCHECK(s->length() == len);
736   String::WriteToFlat(*s, chars, 0, len);
737 }
738 
739 }  // namespace
740 
741 template <bool is_one_byte, typename T>
AllocateInternalizedStringImpl(T t,int chars,uint32_t hash_field)742 Handle<String> Factory::AllocateInternalizedStringImpl(T t, int chars,
743                                                        uint32_t hash_field) {
744   DCHECK_LE(0, chars);
745   DCHECK_GE(String::kMaxLength, chars);
746 
747   // Compute map and object size.
748   int size;
749   Map map;
750   if (is_one_byte) {
751     map = *one_byte_internalized_string_map();
752     size = SeqOneByteString::SizeFor(chars);
753   } else {
754     map = *internalized_string_map();
755     size = SeqTwoByteString::SizeFor(chars);
756   }
757 
758   HeapObject result =
759       AllocateRawWithImmortalMap(size,
760                                  isolate()->heap()->CanAllocateInReadOnlySpace()
761                                      ? AllocationType::kReadOnly
762                                      : AllocationType::kOld,
763                                  map);
764   Handle<String> answer(String::cast(result), isolate());
765   answer->set_length(chars);
766   answer->set_hash_field(hash_field);
767   DCHECK_EQ(size, answer->Size());
768   DisallowHeapAllocation no_gc;
769 
770   if (is_one_byte) {
771     WriteOneByteData(t, SeqOneByteString::cast(*answer).GetChars(no_gc), chars);
772   } else {
773     WriteTwoByteData(t, SeqTwoByteString::cast(*answer).GetChars(no_gc), chars);
774   }
775   return answer;
776 }
777 
NewInternalizedStringImpl(Handle<String> string,int chars,uint32_t hash_field)778 Handle<String> Factory::NewInternalizedStringImpl(Handle<String> string,
779                                                   int chars,
780                                                   uint32_t hash_field) {
781   if (IsOneByte(string)) {
782     return AllocateInternalizedStringImpl<true>(string, chars, hash_field);
783   }
784   return AllocateInternalizedStringImpl<false>(string, chars, hash_field);
785 }
786 
787 namespace {
788 
GetInternalizedStringMap(Factory * f,Handle<String> string)789 MaybeHandle<Map> GetInternalizedStringMap(Factory* f, Handle<String> string) {
790   switch (string->map().instance_type()) {
791     case STRING_TYPE:
792       return f->internalized_string_map();
793     case ONE_BYTE_STRING_TYPE:
794       return f->one_byte_internalized_string_map();
795     case EXTERNAL_STRING_TYPE:
796       return f->external_internalized_string_map();
797     case EXTERNAL_ONE_BYTE_STRING_TYPE:
798       return f->external_one_byte_internalized_string_map();
799     case UNCACHED_EXTERNAL_STRING_TYPE:
800       return f->uncached_external_internalized_string_map();
801     case UNCACHED_EXTERNAL_ONE_BYTE_STRING_TYPE:
802       return f->uncached_external_one_byte_internalized_string_map();
803     default:
804       return MaybeHandle<Map>();  // No match found.
805   }
806 }
807 
808 }  // namespace
809 
InternalizedStringMapForString(Handle<String> string)810 MaybeHandle<Map> Factory::InternalizedStringMapForString(
811     Handle<String> string) {
812   // If the string is in the young generation, it cannot be used as
813   // internalized.
814   if (Heap::InYoungGeneration(*string)) return MaybeHandle<Map>();
815 
816   return GetInternalizedStringMap(this, string);
817 }
818 
819 template <class StringClass>
InternalizeExternalString(Handle<String> string)820 Handle<StringClass> Factory::InternalizeExternalString(Handle<String> string) {
821   Handle<StringClass> cast_string = Handle<StringClass>::cast(string);
822   Handle<Map> map = GetInternalizedStringMap(this, string).ToHandleChecked();
823   Handle<StringClass> external_string(
824       StringClass::cast(New(map, AllocationType::kOld)), isolate());
825   external_string->AllocateExternalPointerEntries(isolate());
826   external_string->set_length(cast_string->length());
827   external_string->set_hash_field(cast_string->hash_field());
828   external_string->SetResource(isolate(), nullptr);
829   isolate()->heap()->RegisterExternalString(*external_string);
830   return external_string;
831 }
832 
833 template Handle<ExternalOneByteString>
834     Factory::InternalizeExternalString<ExternalOneByteString>(Handle<String>);
835 template Handle<ExternalTwoByteString>
836     Factory::InternalizeExternalString<ExternalTwoByteString>(Handle<String>);
837 
LookupSingleCharacterStringFromCode(uint16_t code)838 Handle<String> Factory::LookupSingleCharacterStringFromCode(uint16_t code) {
839   if (code <= unibrow::Latin1::kMaxChar) {
840     {
841       DisallowHeapAllocation no_allocation;
842       Object value = single_character_string_cache()->get(code);
843       if (value != *undefined_value()) {
844         return handle(String::cast(value), isolate());
845       }
846     }
847     uint8_t buffer[] = {static_cast<uint8_t>(code)};
848     Handle<String> result = InternalizeString(Vector<const uint8_t>(buffer, 1));
849     single_character_string_cache()->set(code, *result);
850     return result;
851   }
852   uint16_t buffer[] = {code};
853   return InternalizeString(Vector<const uint16_t>(buffer, 1));
854 }
855 
NewSurrogatePairString(uint16_t lead,uint16_t trail)856 Handle<String> Factory::NewSurrogatePairString(uint16_t lead, uint16_t trail) {
857   DCHECK_GE(lead, 0xD800);
858   DCHECK_LE(lead, 0xDBFF);
859   DCHECK_GE(trail, 0xDC00);
860   DCHECK_LE(trail, 0xDFFF);
861 
862   Handle<SeqTwoByteString> str =
863       isolate()->factory()->NewRawTwoByteString(2).ToHandleChecked();
864   DisallowHeapAllocation no_allocation;
865   uc16* dest = str->GetChars(no_allocation);
866   dest[0] = lead;
867   dest[1] = trail;
868   return str;
869 }
870 
NewProperSubString(Handle<String> str,int begin,int end)871 Handle<String> Factory::NewProperSubString(Handle<String> str, int begin,
872                                            int end) {
873 #if VERIFY_HEAP
874   if (FLAG_verify_heap) str->StringVerify(isolate());
875 #endif
876   DCHECK(begin > 0 || end < str->length());
877 
878   str = String::Flatten(isolate(), str);
879 
880   int length = end - begin;
881   if (length <= 0) return empty_string();
882   if (length == 1) {
883     return LookupSingleCharacterStringFromCode(str->Get(begin));
884   }
885   if (length == 2) {
886     // Optimization for 2-byte strings often used as keys in a decompression
887     // dictionary.  Check whether we already have the string in the string
888     // table to prevent creation of many unnecessary strings.
889     uint16_t c1 = str->Get(begin);
890     uint16_t c2 = str->Get(begin + 1);
891     return MakeOrFindTwoCharacterString(c1, c2);
892   }
893 
894   if (!FLAG_string_slices || length < SlicedString::kMinLength) {
895     if (str->IsOneByteRepresentation()) {
896       Handle<SeqOneByteString> result =
897           NewRawOneByteString(length).ToHandleChecked();
898       DisallowHeapAllocation no_gc;
899       uint8_t* dest = result->GetChars(no_gc);
900       String::WriteToFlat(*str, dest, begin, end);
901       return result;
902     } else {
903       Handle<SeqTwoByteString> result =
904           NewRawTwoByteString(length).ToHandleChecked();
905       DisallowHeapAllocation no_gc;
906       uc16* dest = result->GetChars(no_gc);
907       String::WriteToFlat(*str, dest, begin, end);
908       return result;
909     }
910   }
911 
912   int offset = begin;
913 
914   if (str->IsSlicedString()) {
915     Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
916     str = Handle<String>(slice->parent(), isolate());
917     offset += slice->offset();
918   }
919   if (str->IsThinString()) {
920     Handle<ThinString> thin = Handle<ThinString>::cast(str);
921     str = handle(thin->actual(), isolate());
922   }
923 
924   DCHECK(str->IsSeqString() || str->IsExternalString());
925   Handle<Map> map = str->IsOneByteRepresentation()
926                         ? sliced_one_byte_string_map()
927                         : sliced_string_map();
928   Handle<SlicedString> slice(
929       SlicedString::cast(New(map, AllocationType::kYoung)), isolate());
930 
931   slice->set_hash_field(String::kEmptyHashField);
932   slice->set_length(length);
933   slice->set_parent(*str);
934   slice->set_offset(offset);
935   return slice;
936 }
937 
NewExternalStringFromOneByte(const ExternalOneByteString::Resource * resource)938 MaybeHandle<String> Factory::NewExternalStringFromOneByte(
939     const ExternalOneByteString::Resource* resource) {
940   size_t length = resource->length();
941   if (length > static_cast<size_t>(String::kMaxLength)) {
942     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
943   }
944   if (length == 0) return empty_string();
945 
946   Handle<Map> map = resource->IsCacheable()
947                         ? external_one_byte_string_map()
948                         : uncached_external_one_byte_string_map();
949   Handle<ExternalOneByteString> external_string(
950       ExternalOneByteString::cast(New(map, AllocationType::kOld)), isolate());
951   external_string->AllocateExternalPointerEntries(isolate());
952   external_string->set_length(static_cast<int>(length));
953   external_string->set_hash_field(String::kEmptyHashField);
954   external_string->SetResource(isolate(), resource);
955   isolate()->heap()->RegisterExternalString(*external_string);
956 
957   return external_string;
958 }
959 
NewExternalStringFromTwoByte(const ExternalTwoByteString::Resource * resource)960 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
961     const ExternalTwoByteString::Resource* resource) {
962   size_t length = resource->length();
963   if (length > static_cast<size_t>(String::kMaxLength)) {
964     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
965   }
966   if (length == 0) return empty_string();
967 
968   Handle<Map> map = resource->IsCacheable() ? external_string_map()
969                                             : uncached_external_string_map();
970   Handle<ExternalTwoByteString> external_string(
971       ExternalTwoByteString::cast(New(map, AllocationType::kOld)), isolate());
972   external_string->AllocateExternalPointerEntries(isolate());
973   external_string->set_length(static_cast<int>(length));
974   external_string->set_hash_field(String::kEmptyHashField);
975   external_string->SetResource(isolate(), resource);
976   isolate()->heap()->RegisterExternalString(*external_string);
977 
978   return external_string;
979 }
980 
NewJSStringIterator(Handle<String> string)981 Handle<JSStringIterator> Factory::NewJSStringIterator(Handle<String> string) {
982   Handle<Map> map(isolate()->native_context()->initial_string_iterator_map(),
983                   isolate());
984   Handle<String> flat_string = String::Flatten(isolate(), string);
985   Handle<JSStringIterator> iterator =
986       Handle<JSStringIterator>::cast(NewJSObjectFromMap(map));
987   iterator->set_string(*flat_string);
988   iterator->set_index(0);
989 
990   return iterator;
991 }
992 
NewSymbol(AllocationType allocation)993 Handle<Symbol> Factory::NewSymbol(AllocationType allocation) {
994   DCHECK(allocation != AllocationType::kYoung);
995   // Statically ensure that it is safe to allocate symbols in paged spaces.
996   STATIC_ASSERT(Symbol::kSize <= kMaxRegularHeapObjectSize);
997 
998   HeapObject result =
999       AllocateRawWithImmortalMap(Symbol::kSize, allocation, *symbol_map());
1000 
1001   // Generate a random hash value.
1002   int hash = isolate()->GenerateIdentityHash(Name::kHashBitMask);
1003 
1004   Handle<Symbol> symbol(Symbol::cast(result), isolate());
1005   symbol->set_hash_field(Name::kIsNotIntegerIndexMask |
1006                          (hash << Name::kHashShift));
1007   symbol->set_description(*undefined_value());
1008   symbol->set_flags(0);
1009   DCHECK(!symbol->is_private());
1010   return symbol;
1011 }
1012 
NewPrivateSymbol(AllocationType allocation)1013 Handle<Symbol> Factory::NewPrivateSymbol(AllocationType allocation) {
1014   DCHECK(allocation != AllocationType::kYoung);
1015   Handle<Symbol> symbol = NewSymbol(allocation);
1016   symbol->set_is_private(true);
1017   return symbol;
1018 }
1019 
NewPrivateNameSymbol(Handle<String> name)1020 Handle<Symbol> Factory::NewPrivateNameSymbol(Handle<String> name) {
1021   Handle<Symbol> symbol = NewSymbol();
1022   symbol->set_is_private_name();
1023   symbol->set_description(*name);
1024   return symbol;
1025 }
1026 
NewContext(Handle<Map> map,int size,int variadic_part_length,AllocationType allocation)1027 Handle<Context> Factory::NewContext(Handle<Map> map, int size,
1028                                     int variadic_part_length,
1029                                     AllocationType allocation) {
1030   DCHECK_LE(Context::kTodoHeaderSize, size);
1031   DCHECK(IsAligned(size, kTaggedSize));
1032   DCHECK_LE(Context::MIN_CONTEXT_SLOTS, variadic_part_length);
1033   DCHECK_LE(Context::SizeFor(variadic_part_length), size);
1034 
1035   HeapObject result =
1036       isolate()->heap()->AllocateRawWith<Heap::kRetryOrFail>(size, allocation);
1037   result.set_map_after_allocation(*map);
1038   Handle<Context> context(Context::cast(result), isolate());
1039   context->set_length(variadic_part_length);
1040   DCHECK_EQ(context->SizeFromMap(*map), size);
1041   if (size > Context::kTodoHeaderSize) {
1042     ObjectSlot start = context->RawField(Context::kTodoHeaderSize);
1043     ObjectSlot end = context->RawField(size);
1044     size_t slot_count = end - start;
1045     MemsetTagged(start, *undefined_value(), slot_count);
1046   }
1047   return context;
1048 }
1049 
NewNativeContext()1050 Handle<NativeContext> Factory::NewNativeContext() {
1051   Handle<Map> map = NewMap(NATIVE_CONTEXT_TYPE, kVariableSizeSentinel);
1052   Handle<NativeContext> context = Handle<NativeContext>::cast(
1053       NewContext(map, NativeContext::kSize, NativeContext::NATIVE_CONTEXT_SLOTS,
1054                  AllocationType::kOld));
1055   context->set_native_context_map(*map);
1056   map->set_native_context(*context);
1057   context->AllocateExternalPointerEntries(isolate());
1058   context->set_scope_info(ReadOnlyRoots(isolate()).native_scope_info());
1059   context->set_previous(Context::unchecked_cast(Smi::zero()));
1060   context->set_extension(*undefined_value());
1061   context->set_errors_thrown(Smi::zero());
1062   context->set_math_random_index(Smi::zero());
1063   context->set_serialized_objects(*empty_fixed_array());
1064   context->set_microtask_queue(isolate(), nullptr);
1065   context->set_osr_code_cache(*empty_weak_fixed_array());
1066   context->set_retained_maps(*empty_weak_array_list());
1067   return context;
1068 }
1069 
NewScriptContext(Handle<NativeContext> outer,Handle<ScopeInfo> scope_info)1070 Handle<Context> Factory::NewScriptContext(Handle<NativeContext> outer,
1071                                           Handle<ScopeInfo> scope_info) {
1072   DCHECK_EQ(scope_info->scope_type(), SCRIPT_SCOPE);
1073   int variadic_part_length = scope_info->ContextLength();
1074   Handle<Context> context =
1075       NewContext(handle(outer->script_context_map(), isolate()),
1076                  Context::SizeFor(variadic_part_length), variadic_part_length,
1077                  AllocationType::kOld);
1078   context->set_scope_info(*scope_info);
1079   context->set_previous(*outer);
1080   DCHECK(context->IsScriptContext());
1081   return context;
1082 }
1083 
NewScriptContextTable()1084 Handle<ScriptContextTable> Factory::NewScriptContextTable() {
1085   Handle<ScriptContextTable> context_table = Handle<ScriptContextTable>::cast(
1086       NewFixedArrayWithMap(read_only_roots().script_context_table_map_handle(),
1087                            ScriptContextTable::kMinLength));
1088   context_table->synchronized_set_used(0);
1089   return context_table;
1090 }
1091 
NewModuleContext(Handle<SourceTextModule> module,Handle<NativeContext> outer,Handle<ScopeInfo> scope_info)1092 Handle<Context> Factory::NewModuleContext(Handle<SourceTextModule> module,
1093                                           Handle<NativeContext> outer,
1094                                           Handle<ScopeInfo> scope_info) {
1095   DCHECK_EQ(scope_info->scope_type(), MODULE_SCOPE);
1096   int variadic_part_length = scope_info->ContextLength();
1097   Handle<Context> context = NewContext(
1098       isolate()->module_context_map(), Context::SizeFor(variadic_part_length),
1099       variadic_part_length, AllocationType::kOld);
1100   context->set_scope_info(*scope_info);
1101   context->set_previous(*outer);
1102   context->set_extension(*module);
1103   DCHECK(context->IsModuleContext());
1104   return context;
1105 }
1106 
NewFunctionContext(Handle<Context> outer,Handle<ScopeInfo> scope_info)1107 Handle<Context> Factory::NewFunctionContext(Handle<Context> outer,
1108                                             Handle<ScopeInfo> scope_info) {
1109   Handle<Map> map;
1110   switch (scope_info->scope_type()) {
1111     case EVAL_SCOPE:
1112       map = isolate()->eval_context_map();
1113       break;
1114     case FUNCTION_SCOPE:
1115       map = isolate()->function_context_map();
1116       break;
1117     default:
1118       UNREACHABLE();
1119   }
1120   int variadic_part_length = scope_info->ContextLength();
1121   Handle<Context> context =
1122       NewContext(map, Context::SizeFor(variadic_part_length),
1123                  variadic_part_length, AllocationType::kYoung);
1124   context->set_scope_info(*scope_info);
1125   context->set_previous(*outer);
1126   return context;
1127 }
1128 
NewCatchContext(Handle<Context> previous,Handle<ScopeInfo> scope_info,Handle<Object> thrown_object)1129 Handle<Context> Factory::NewCatchContext(Handle<Context> previous,
1130                                          Handle<ScopeInfo> scope_info,
1131                                          Handle<Object> thrown_object) {
1132   DCHECK_EQ(scope_info->scope_type(), CATCH_SCOPE);
1133   STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
1134   // TODO(ishell): Take the details from CatchContext class.
1135   int variadic_part_length = Context::MIN_CONTEXT_SLOTS + 1;
1136   Handle<Context> context = NewContext(
1137       isolate()->catch_context_map(), Context::SizeFor(variadic_part_length),
1138       variadic_part_length, AllocationType::kYoung);
1139   context->set_scope_info(*scope_info);
1140   context->set_previous(*previous);
1141   context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
1142   return context;
1143 }
1144 
NewDebugEvaluateContext(Handle<Context> previous,Handle<ScopeInfo> scope_info,Handle<JSReceiver> extension,Handle<Context> wrapped,Handle<StringSet> blocklist)1145 Handle<Context> Factory::NewDebugEvaluateContext(Handle<Context> previous,
1146                                                  Handle<ScopeInfo> scope_info,
1147                                                  Handle<JSReceiver> extension,
1148                                                  Handle<Context> wrapped,
1149                                                  Handle<StringSet> blocklist) {
1150   STATIC_ASSERT(Context::BLOCK_LIST_INDEX ==
1151                 Context::MIN_CONTEXT_EXTENDED_SLOTS + 1);
1152   DCHECK(scope_info->IsDebugEvaluateScope());
1153   Handle<HeapObject> ext = extension.is_null()
1154                                ? Handle<HeapObject>::cast(undefined_value())
1155                                : Handle<HeapObject>::cast(extension);
1156   // TODO(ishell): Take the details from DebugEvaluateContextContext class.
1157   int variadic_part_length = Context::MIN_CONTEXT_EXTENDED_SLOTS + 2;
1158   Handle<Context> c = NewContext(isolate()->debug_evaluate_context_map(),
1159                                  Context::SizeFor(variadic_part_length),
1160                                  variadic_part_length, AllocationType::kYoung);
1161   c->set_scope_info(*scope_info);
1162   c->set_previous(*previous);
1163   c->set_extension(*ext);
1164   if (!wrapped.is_null()) c->set(Context::WRAPPED_CONTEXT_INDEX, *wrapped);
1165   if (!blocklist.is_null()) c->set(Context::BLOCK_LIST_INDEX, *blocklist);
1166   return c;
1167 }
1168 
NewWithContext(Handle<Context> previous,Handle<ScopeInfo> scope_info,Handle<JSReceiver> extension)1169 Handle<Context> Factory::NewWithContext(Handle<Context> previous,
1170                                         Handle<ScopeInfo> scope_info,
1171                                         Handle<JSReceiver> extension) {
1172   DCHECK_EQ(scope_info->scope_type(), WITH_SCOPE);
1173   // TODO(ishell): Take the details from WithContext class.
1174   int variadic_part_length = Context::MIN_CONTEXT_EXTENDED_SLOTS;
1175   Handle<Context> context = NewContext(
1176       isolate()->with_context_map(), Context::SizeFor(variadic_part_length),
1177       variadic_part_length, AllocationType::kYoung);
1178   context->set_scope_info(*scope_info);
1179   context->set_previous(*previous);
1180   context->set_extension(*extension);
1181   return context;
1182 }
1183 
NewBlockContext(Handle<Context> previous,Handle<ScopeInfo> scope_info)1184 Handle<Context> Factory::NewBlockContext(Handle<Context> previous,
1185                                          Handle<ScopeInfo> scope_info) {
1186   DCHECK_IMPLIES(scope_info->scope_type() != BLOCK_SCOPE,
1187                  scope_info->scope_type() == CLASS_SCOPE);
1188   int variadic_part_length = scope_info->ContextLength();
1189   Handle<Context> context = NewContext(
1190       isolate()->block_context_map(), Context::SizeFor(variadic_part_length),
1191       variadic_part_length, AllocationType::kYoung);
1192   context->set_scope_info(*scope_info);
1193   context->set_previous(*previous);
1194   return context;
1195 }
1196 
NewBuiltinContext(Handle<NativeContext> native_context,int variadic_part_length)1197 Handle<Context> Factory::NewBuiltinContext(Handle<NativeContext> native_context,
1198                                            int variadic_part_length) {
1199   DCHECK_LE(Context::MIN_CONTEXT_SLOTS, variadic_part_length);
1200   Handle<Context> context = NewContext(
1201       isolate()->function_context_map(), Context::SizeFor(variadic_part_length),
1202       variadic_part_length, AllocationType::kYoung);
1203   context->set_scope_info(ReadOnlyRoots(isolate()).empty_scope_info());
1204   context->set_previous(*native_context);
1205   return context;
1206 }
1207 
NewAliasedArgumentsEntry(int aliased_context_slot)1208 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
1209     int aliased_context_slot) {
1210   Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
1211       NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE, AllocationType::kYoung));
1212   entry->set_aliased_context_slot(aliased_context_slot);
1213   return entry;
1214 }
1215 
NewAccessorInfo()1216 Handle<AccessorInfo> Factory::NewAccessorInfo() {
1217   Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(
1218       NewStruct(ACCESSOR_INFO_TYPE, AllocationType::kOld));
1219   DisallowHeapAllocation no_gc;
1220   info->set_name(*empty_string());
1221   info->set_flags(0);  // Must clear the flags, it was initialized as undefined.
1222   info->set_is_sloppy(true);
1223   info->set_initial_property_attributes(NONE);
1224 
1225   // Clear some other fields that should not be undefined.
1226   info->set_getter(Smi::zero());
1227   info->set_setter(Smi::zero());
1228   info->set_js_getter(Smi::zero());
1229 
1230   return info;
1231 }
1232 
AddToScriptList(Handle<Script> script)1233 void Factory::AddToScriptList(Handle<Script> script) {
1234   Handle<WeakArrayList> scripts = script_list();
1235   scripts = WeakArrayList::Append(isolate(), scripts,
1236                                   MaybeObjectHandle::Weak(script));
1237   isolate()->heap()->set_script_list(*scripts);
1238 }
1239 
CloneScript(Handle<Script> script)1240 Handle<Script> Factory::CloneScript(Handle<Script> script) {
1241   Heap* heap = isolate()->heap();
1242   int script_id = isolate()->GetNextScriptId();
1243   Handle<Script> new_script =
1244       Handle<Script>::cast(NewStruct(SCRIPT_TYPE, AllocationType::kOld));
1245   new_script->set_source(script->source());
1246   new_script->set_name(script->name());
1247   new_script->set_id(script_id);
1248   new_script->set_line_offset(script->line_offset());
1249   new_script->set_column_offset(script->column_offset());
1250   new_script->set_context_data(script->context_data());
1251   new_script->set_type(script->type());
1252   new_script->set_line_ends(ReadOnlyRoots(heap).undefined_value());
1253   new_script->set_eval_from_shared_or_wrapped_arguments(
1254       script->eval_from_shared_or_wrapped_arguments());
1255   new_script->set_shared_function_infos(*empty_weak_fixed_array(),
1256                                         SKIP_WRITE_BARRIER);
1257   new_script->set_eval_from_position(script->eval_from_position());
1258   new_script->set_flags(script->flags());
1259   new_script->set_host_defined_options(script->host_defined_options());
1260   Handle<WeakArrayList> scripts = script_list();
1261   scripts = WeakArrayList::AddToEnd(isolate(), scripts,
1262                                     MaybeObjectHandle::Weak(new_script));
1263   heap->set_script_list(*scripts);
1264   LOG(isolate(), ScriptEvent(Logger::ScriptEventType::kCreate, script_id));
1265   return new_script;
1266 }
1267 
NewCallableTask(Handle<JSReceiver> callable,Handle<Context> context)1268 Handle<CallableTask> Factory::NewCallableTask(Handle<JSReceiver> callable,
1269                                               Handle<Context> context) {
1270   DCHECK(callable->IsCallable());
1271   Handle<CallableTask> microtask =
1272       Handle<CallableTask>::cast(NewStruct(CALLABLE_TASK_TYPE));
1273   microtask->set_callable(*callable);
1274   microtask->set_context(*context);
1275   return microtask;
1276 }
1277 
NewCallbackTask(Handle<Foreign> callback,Handle<Foreign> data)1278 Handle<CallbackTask> Factory::NewCallbackTask(Handle<Foreign> callback,
1279                                               Handle<Foreign> data) {
1280   Handle<CallbackTask> microtask =
1281       Handle<CallbackTask>::cast(NewStruct(CALLBACK_TASK_TYPE));
1282   microtask->set_callback(*callback);
1283   microtask->set_data(*data);
1284   return microtask;
1285 }
1286 
NewPromiseResolveThenableJobTask(Handle<JSPromise> promise_to_resolve,Handle<JSReceiver> thenable,Handle<JSReceiver> then,Handle<Context> context)1287 Handle<PromiseResolveThenableJobTask> Factory::NewPromiseResolveThenableJobTask(
1288     Handle<JSPromise> promise_to_resolve, Handle<JSReceiver> thenable,
1289     Handle<JSReceiver> then, Handle<Context> context) {
1290   DCHECK(then->IsCallable());
1291   Handle<PromiseResolveThenableJobTask> microtask =
1292       Handle<PromiseResolveThenableJobTask>::cast(
1293           NewStruct(PROMISE_RESOLVE_THENABLE_JOB_TASK_TYPE));
1294   microtask->set_promise_to_resolve(*promise_to_resolve);
1295   microtask->set_thenable(*thenable);
1296   microtask->set_then(*then);
1297   microtask->set_context(*context);
1298   return microtask;
1299 }
1300 
NewForeign(Address addr)1301 Handle<Foreign> Factory::NewForeign(Address addr) {
1302   // Statically ensure that it is safe to allocate foreigns in paged spaces.
1303   STATIC_ASSERT(Foreign::kSize <= kMaxRegularHeapObjectSize);
1304   Map map = *foreign_map();
1305   HeapObject result = AllocateRawWithImmortalMap(map.instance_size(),
1306                                                  AllocationType::kYoung, map);
1307   Handle<Foreign> foreign(Foreign::cast(result), isolate());
1308   foreign->AllocateExternalPointerEntries(isolate());
1309   foreign->set_foreign_address(isolate(), addr);
1310   return foreign;
1311 }
1312 
NewWasmTypeInfo(Address type_address,Handle<Map> parent)1313 Handle<WasmTypeInfo> Factory::NewWasmTypeInfo(Address type_address,
1314                                               Handle<Map> parent) {
1315   Handle<ArrayList> subtypes = ArrayList::New(isolate(), 0);
1316   Map map = *wasm_type_info_map();
1317   HeapObject result = AllocateRawWithImmortalMap(map.instance_size(),
1318                                                  AllocationType::kYoung, map);
1319   Handle<WasmTypeInfo> info(WasmTypeInfo::cast(result), isolate());
1320   info->AllocateExternalPointerEntries(isolate());
1321   info->set_foreign_address(isolate(), type_address);
1322   info->set_parent(*parent);
1323   info->set_subtypes(*subtypes);
1324   return info;
1325 }
1326 
NewCell(Handle<Object> value)1327 Handle<Cell> Factory::NewCell(Handle<Object> value) {
1328   STATIC_ASSERT(Cell::kSize <= kMaxRegularHeapObjectSize);
1329   HeapObject result = AllocateRawWithImmortalMap(
1330       Cell::kSize, AllocationType::kOld, *cell_map());
1331   Handle<Cell> cell(Cell::cast(result), isolate());
1332   cell->set_value(*value);
1333   return cell;
1334 }
1335 
NewNoClosuresCell(Handle<HeapObject> value)1336 Handle<FeedbackCell> Factory::NewNoClosuresCell(Handle<HeapObject> value) {
1337   HeapObject result =
1338       AllocateRawWithImmortalMap(FeedbackCell::kAlignedSize,
1339                                  AllocationType::kOld, *no_closures_cell_map());
1340   Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
1341   cell->set_value(*value);
1342   cell->SetInitialInterruptBudget();
1343   cell->clear_padding();
1344   return cell;
1345 }
1346 
NewOneClosureCell(Handle<HeapObject> value)1347 Handle<FeedbackCell> Factory::NewOneClosureCell(Handle<HeapObject> value) {
1348   HeapObject result =
1349       AllocateRawWithImmortalMap(FeedbackCell::kAlignedSize,
1350                                  AllocationType::kOld, *one_closure_cell_map());
1351   Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
1352   cell->set_value(*value);
1353   cell->SetInitialInterruptBudget();
1354   cell->clear_padding();
1355   return cell;
1356 }
1357 
NewManyClosuresCell(Handle<HeapObject> value)1358 Handle<FeedbackCell> Factory::NewManyClosuresCell(Handle<HeapObject> value) {
1359   HeapObject result = AllocateRawWithImmortalMap(FeedbackCell::kAlignedSize,
1360                                                  AllocationType::kOld,
1361                                                  *many_closures_cell_map());
1362   Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
1363   cell->set_value(*value);
1364   cell->SetInitialInterruptBudget();
1365   cell->clear_padding();
1366   return cell;
1367 }
1368 
NewPropertyCell(Handle<Name> name,AllocationType allocation)1369 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Name> name,
1370                                               AllocationType allocation) {
1371   DCHECK(name->IsUniqueName());
1372   STATIC_ASSERT(PropertyCell::kSize <= kMaxRegularHeapObjectSize);
1373   HeapObject result = AllocateRawWithImmortalMap(
1374       PropertyCell::kSize, allocation, *global_property_cell_map());
1375   Handle<PropertyCell> cell(PropertyCell::cast(result), isolate());
1376   cell->set_dependent_code(DependentCode::cast(*empty_weak_fixed_array()),
1377                            SKIP_WRITE_BARRIER);
1378   cell->set_property_details(PropertyDetails(Smi::zero()));
1379   cell->set_name(*name);
1380   cell->set_value(*the_hole_value());
1381   return cell;
1382 }
1383 
NewTransitionArray(int number_of_transitions,int slack)1384 Handle<TransitionArray> Factory::NewTransitionArray(int number_of_transitions,
1385                                                     int slack) {
1386   int capacity = TransitionArray::LengthFor(number_of_transitions + slack);
1387   Handle<TransitionArray> array = Handle<TransitionArray>::cast(
1388       NewWeakFixedArrayWithMap(read_only_roots().transition_array_map(),
1389                                capacity, AllocationType::kOld));
1390   // Transition arrays are AllocationType::kOld. When black allocation is on we
1391   // have to add the transition array to the list of
1392   // encountered_transition_arrays.
1393   Heap* heap = isolate()->heap();
1394   if (heap->incremental_marking()->black_allocation()) {
1395     heap->mark_compact_collector()->AddTransitionArray(*array);
1396   }
1397   array->WeakFixedArray::Set(TransitionArray::kPrototypeTransitionsIndex,
1398                              MaybeObject::FromObject(Smi::zero()));
1399   array->WeakFixedArray::Set(
1400       TransitionArray::kTransitionLengthIndex,
1401       MaybeObject::FromObject(Smi::FromInt(number_of_transitions)));
1402   return array;
1403 }
1404 
NewAllocationSite(bool with_weak_next)1405 Handle<AllocationSite> Factory::NewAllocationSite(bool with_weak_next) {
1406   Handle<Map> map = with_weak_next ? allocation_site_map()
1407                                    : allocation_site_without_weaknext_map();
1408   Handle<AllocationSite> site(
1409       AllocationSite::cast(New(map, AllocationType::kOld)), isolate());
1410   site->Initialize();
1411 
1412   if (with_weak_next) {
1413     // Link the site
1414     site->set_weak_next(isolate()->heap()->allocation_sites_list());
1415     isolate()->heap()->set_allocation_sites_list(*site);
1416   }
1417   return site;
1418 }
1419 
NewMap(InstanceType type,int instance_size,ElementsKind elements_kind,int inobject_properties)1420 Handle<Map> Factory::NewMap(InstanceType type, int instance_size,
1421                             ElementsKind elements_kind,
1422                             int inobject_properties) {
1423   STATIC_ASSERT(LAST_JS_OBJECT_TYPE == LAST_TYPE);
1424   DCHECK_IMPLIES(InstanceTypeChecker::IsJSObject(type) &&
1425                      !Map::CanHaveFastTransitionableElementsKind(type),
1426                  IsDictionaryElementsKind(elements_kind) ||
1427                      IsTerminalElementsKind(elements_kind));
1428   HeapObject result = isolate()->heap()->AllocateRawWith<Heap::kRetryOrFail>(
1429       Map::kSize, AllocationType::kMap);
1430   result.set_map_after_allocation(*meta_map(), SKIP_WRITE_BARRIER);
1431   return handle(InitializeMap(Map::cast(result), type, instance_size,
1432                               elements_kind, inobject_properties),
1433                 isolate());
1434 }
1435 
InitializeMap(Map map,InstanceType type,int instance_size,ElementsKind elements_kind,int inobject_properties)1436 Map Factory::InitializeMap(Map map, InstanceType type, int instance_size,
1437                            ElementsKind elements_kind,
1438                            int inobject_properties) {
1439   map.set_instance_type(type);
1440   map.set_prototype(*null_value(), SKIP_WRITE_BARRIER);
1441   map.set_constructor_or_backpointer(*null_value(), SKIP_WRITE_BARRIER);
1442   map.set_instance_size(instance_size);
1443   if (map.IsJSObjectMap()) {
1444     DCHECK(!ReadOnlyHeap::Contains(map));
1445     map.SetInObjectPropertiesStartInWords(instance_size / kTaggedSize -
1446                                           inobject_properties);
1447     DCHECK_EQ(map.GetInObjectProperties(), inobject_properties);
1448     map.set_prototype_validity_cell(*invalid_prototype_validity_cell());
1449   } else {
1450     DCHECK_EQ(inobject_properties, 0);
1451     map.set_inobject_properties_start_or_constructor_function_index(0);
1452     map.set_prototype_validity_cell(Smi::FromInt(Map::kPrototypeChainValid));
1453   }
1454   map.set_dependent_code(DependentCode::cast(*empty_weak_fixed_array()),
1455                          SKIP_WRITE_BARRIER);
1456   map.set_raw_transitions(MaybeObject::FromSmi(Smi::zero()));
1457   map.SetInObjectUnusedPropertyFields(inobject_properties);
1458   map.SetInstanceDescriptors(isolate(), *empty_descriptor_array(), 0);
1459   if (FLAG_unbox_double_fields) {
1460     map.set_layout_descriptor(LayoutDescriptor::FastPointerLayout(),
1461                               kReleaseStore);
1462   }
1463   // Must be called only after |instance_type|, |instance_size| and
1464   // |layout_descriptor| are set.
1465   map.set_visitor_id(Map::GetVisitorId(map));
1466   map.set_relaxed_bit_field(0);
1467   map.set_bit_field2(Map::Bits2::NewTargetIsBaseBit::encode(true));
1468   int bit_field3 =
1469       Map::Bits3::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
1470       Map::Bits3::OwnsDescriptorsBit::encode(true) |
1471       Map::Bits3::ConstructionCounterBits::encode(Map::kNoSlackTracking) |
1472       Map::Bits3::IsExtensibleBit::encode(true);
1473   map.set_bit_field3(bit_field3);
1474   DCHECK(!map.is_in_retained_map_list());
1475   map.clear_padding();
1476   map.set_elements_kind(elements_kind);
1477   isolate()->counters()->maps_created()->Increment();
1478   if (FLAG_trace_maps) LOG(isolate(), MapCreate(map));
1479   return map;
1480 }
1481 
CopyJSObject(Handle<JSObject> source)1482 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> source) {
1483   return CopyJSObjectWithAllocationSite(source, Handle<AllocationSite>());
1484 }
1485 
CopyJSObjectWithAllocationSite(Handle<JSObject> source,Handle<AllocationSite> site)1486 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
1487     Handle<JSObject> source, Handle<AllocationSite> site) {
1488   Handle<Map> map(source->map(), isolate());
1489 
1490   // We can only clone regexps, normal objects, api objects, errors or arrays.
1491   // Copying anything else will break invariants.
1492   CHECK(map->instance_type() == JS_REG_EXP_TYPE ||
1493         map->instance_type() == JS_OBJECT_TYPE ||
1494         map->instance_type() == JS_ERROR_TYPE ||
1495         map->instance_type() == JS_ARRAY_TYPE ||
1496         map->instance_type() == JS_API_OBJECT_TYPE ||
1497         map->instance_type() == WASM_GLOBAL_OBJECT_TYPE ||
1498         map->instance_type() == WASM_INSTANCE_OBJECT_TYPE ||
1499         map->instance_type() == WASM_MEMORY_OBJECT_TYPE ||
1500         map->instance_type() == WASM_MODULE_OBJECT_TYPE ||
1501         map->instance_type() == WASM_TABLE_OBJECT_TYPE ||
1502         map->instance_type() == JS_SPECIAL_API_OBJECT_TYPE);
1503   DCHECK(site.is_null() || AllocationSite::CanTrack(map->instance_type()));
1504 
1505   int object_size = map->instance_size();
1506   int adjusted_object_size =
1507       site.is_null() ? object_size : object_size + AllocationMemento::kSize;
1508   HeapObject raw_clone = isolate()->heap()->AllocateRawWith<Heap::kRetryOrFail>(
1509       adjusted_object_size, AllocationType::kYoung);
1510 
1511   DCHECK(Heap::InYoungGeneration(raw_clone) || FLAG_single_generation);
1512 
1513   Heap::CopyBlock(raw_clone.address(), source->address(), object_size);
1514   Handle<JSObject> clone(JSObject::cast(raw_clone), isolate());
1515 
1516   if (FLAG_enable_unconditional_write_barriers) {
1517     // By default, we shouldn't need to update the write barrier here, as the
1518     // clone will be allocated in new space.
1519     const ObjectSlot start(raw_clone.address());
1520     const ObjectSlot end(raw_clone.address() + object_size);
1521     isolate()->heap()->WriteBarrierForRange(raw_clone, start, end);
1522   }
1523   if (!site.is_null()) {
1524     AllocationMemento alloc_memento = AllocationMemento::unchecked_cast(
1525         Object(raw_clone.ptr() + object_size));
1526     InitializeAllocationMemento(alloc_memento, *site);
1527   }
1528 
1529   SLOW_DCHECK(clone->GetElementsKind() == source->GetElementsKind());
1530   FixedArrayBase elements = source->elements();
1531   // Update elements if necessary.
1532   if (elements.length() > 0) {
1533     FixedArrayBase elem;
1534     if (elements.map() == *fixed_cow_array_map()) {
1535       elem = elements;
1536     } else if (source->HasDoubleElements()) {
1537       elem = *CopyFixedDoubleArray(
1538           handle(FixedDoubleArray::cast(elements), isolate()));
1539     } else {
1540       elem = *CopyFixedArray(handle(FixedArray::cast(elements), isolate()));
1541     }
1542     clone->set_elements(elem);
1543   }
1544 
1545   // Update properties if necessary.
1546   if (source->HasFastProperties()) {
1547     PropertyArray properties = source->property_array();
1548     if (properties.length() > 0) {
1549       // TODO(gsathya): Do not copy hash code.
1550       Handle<PropertyArray> prop = CopyArrayWithMap(
1551           handle(properties, isolate()), handle(properties.map(), isolate()));
1552       clone->set_raw_properties_or_hash(*prop);
1553     }
1554   } else {
1555     Handle<FixedArray> properties(
1556         FixedArray::cast(source->property_dictionary()), isolate());
1557     Handle<FixedArray> prop = CopyFixedArray(properties);
1558     clone->set_raw_properties_or_hash(*prop);
1559   }
1560   return clone;
1561 }
1562 
1563 namespace {
1564 template <typename T>
initialize_length(Handle<T> array,int length)1565 void initialize_length(Handle<T> array, int length) {
1566   array->set_length(length);
1567 }
1568 
1569 template <>
initialize_length(Handle<PropertyArray> array,int length)1570 void initialize_length<PropertyArray>(Handle<PropertyArray> array, int length) {
1571   array->initialize_length(length);
1572 }
1573 
ZeroEmbedderFields(i::Handle<i::JSObject> obj)1574 inline void ZeroEmbedderFields(i::Handle<i::JSObject> obj) {
1575   auto count = obj->GetEmbedderFieldCount();
1576   for (int i = 0; i < count; i++) {
1577     obj->SetEmbedderField(i, Smi::zero());
1578   }
1579 }
1580 
1581 }  // namespace
1582 
1583 template <typename T>
CopyArrayWithMap(Handle<T> src,Handle<Map> map)1584 Handle<T> Factory::CopyArrayWithMap(Handle<T> src, Handle<Map> map) {
1585   int len = src->length();
1586   HeapObject obj = AllocateRawFixedArray(len, AllocationType::kYoung);
1587   obj.set_map_after_allocation(*map, SKIP_WRITE_BARRIER);
1588 
1589   Handle<T> result(T::cast(obj), isolate());
1590   initialize_length(result, len);
1591 
1592   DisallowHeapAllocation no_gc;
1593   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
1594   result->CopyElements(isolate(), 0, *src, 0, len, mode);
1595   return result;
1596 }
1597 
1598 template <typename T>
CopyArrayAndGrow(Handle<T> src,int grow_by,AllocationType allocation)1599 Handle<T> Factory::CopyArrayAndGrow(Handle<T> src, int grow_by,
1600                                     AllocationType allocation) {
1601   DCHECK_LT(0, grow_by);
1602   DCHECK_LE(grow_by, kMaxInt - src->length());
1603   int old_len = src->length();
1604   int new_len = old_len + grow_by;
1605   HeapObject obj = AllocateRawFixedArray(new_len, allocation);
1606   obj.set_map_after_allocation(src->map(), SKIP_WRITE_BARRIER);
1607 
1608   Handle<T> result(T::cast(obj), isolate());
1609   initialize_length(result, new_len);
1610 
1611   // Copy the content.
1612   DisallowHeapAllocation no_gc;
1613   WriteBarrierMode mode = obj.GetWriteBarrierMode(no_gc);
1614   result->CopyElements(isolate(), 0, *src, 0, old_len, mode);
1615   MemsetTagged(ObjectSlot(result->data_start() + old_len),
1616                ReadOnlyRoots(isolate()).undefined_value(), grow_by);
1617   return result;
1618 }
1619 
CopyFixedArrayWithMap(Handle<FixedArray> array,Handle<Map> map)1620 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
1621                                                   Handle<Map> map) {
1622   return CopyArrayWithMap(array, map);
1623 }
1624 
CopyFixedArrayAndGrow(Handle<FixedArray> array,int grow_by)1625 Handle<FixedArray> Factory::CopyFixedArrayAndGrow(Handle<FixedArray> array,
1626                                                   int grow_by) {
1627   return CopyArrayAndGrow(array, grow_by, AllocationType::kYoung);
1628 }
1629 
NewUninitializedWeakArrayList(int capacity,AllocationType allocation)1630 Handle<WeakArrayList> Factory::NewUninitializedWeakArrayList(
1631     int capacity, AllocationType allocation) {
1632   DCHECK_LE(0, capacity);
1633   if (capacity == 0) return empty_weak_array_list();
1634 
1635   HeapObject obj = AllocateRawWeakArrayList(capacity, allocation);
1636   obj.set_map_after_allocation(*weak_array_list_map(), SKIP_WRITE_BARRIER);
1637 
1638   Handle<WeakArrayList> result(WeakArrayList::cast(obj), isolate());
1639   result->set_length(0);
1640   result->set_capacity(capacity);
1641   return result;
1642 }
1643 
NewWeakArrayList(int capacity,AllocationType allocation)1644 Handle<WeakArrayList> Factory::NewWeakArrayList(int capacity,
1645                                                 AllocationType allocation) {
1646   Handle<WeakArrayList> result =
1647       NewUninitializedWeakArrayList(capacity, allocation);
1648   MemsetTagged(ObjectSlot(result->data_start()),
1649                ReadOnlyRoots(isolate()).undefined_value(), capacity);
1650   return result;
1651 }
1652 
CopyWeakFixedArrayAndGrow(Handle<WeakFixedArray> src,int grow_by)1653 Handle<WeakFixedArray> Factory::CopyWeakFixedArrayAndGrow(
1654     Handle<WeakFixedArray> src, int grow_by) {
1655   DCHECK(!src->IsTransitionArray());  // Compacted by GC, this code doesn't work
1656   return CopyArrayAndGrow(src, grow_by, AllocationType::kOld);
1657 }
1658 
CopyWeakArrayListAndGrow(Handle<WeakArrayList> src,int grow_by,AllocationType allocation)1659 Handle<WeakArrayList> Factory::CopyWeakArrayListAndGrow(
1660     Handle<WeakArrayList> src, int grow_by, AllocationType allocation) {
1661   int old_capacity = src->capacity();
1662   int new_capacity = old_capacity + grow_by;
1663   DCHECK_GE(new_capacity, old_capacity);
1664   Handle<WeakArrayList> result =
1665       NewUninitializedWeakArrayList(new_capacity, allocation);
1666   int old_len = src->length();
1667   result->set_length(old_len);
1668 
1669   // Copy the content.
1670   DisallowHeapAllocation no_gc;
1671   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
1672   result->CopyElements(isolate(), 0, *src, 0, old_len, mode);
1673   MemsetTagged(ObjectSlot(result->data_start() + old_len),
1674                ReadOnlyRoots(isolate()).undefined_value(),
1675                new_capacity - old_len);
1676   return result;
1677 }
1678 
CompactWeakArrayList(Handle<WeakArrayList> src,int new_capacity,AllocationType allocation)1679 Handle<WeakArrayList> Factory::CompactWeakArrayList(Handle<WeakArrayList> src,
1680                                                     int new_capacity,
1681                                                     AllocationType allocation) {
1682   Handle<WeakArrayList> result =
1683       NewUninitializedWeakArrayList(new_capacity, allocation);
1684 
1685   // Copy the content.
1686   DisallowHeapAllocation no_gc;
1687   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
1688   int copy_to = 0, length = src->length();
1689   for (int i = 0; i < length; i++) {
1690     MaybeObject element = src->Get(i);
1691     if (element->IsCleared()) continue;
1692     result->Set(copy_to++, element, mode);
1693   }
1694   result->set_length(copy_to);
1695 
1696   MemsetTagged(ObjectSlot(result->data_start() + copy_to),
1697                ReadOnlyRoots(isolate()).undefined_value(),
1698                new_capacity - copy_to);
1699   return result;
1700 }
1701 
CopyPropertyArrayAndGrow(Handle<PropertyArray> array,int grow_by)1702 Handle<PropertyArray> Factory::CopyPropertyArrayAndGrow(
1703     Handle<PropertyArray> array, int grow_by) {
1704   return CopyArrayAndGrow(array, grow_by, AllocationType::kYoung);
1705 }
1706 
CopyFixedArrayUpTo(Handle<FixedArray> array,int new_len,AllocationType allocation)1707 Handle<FixedArray> Factory::CopyFixedArrayUpTo(Handle<FixedArray> array,
1708                                                int new_len,
1709                                                AllocationType allocation) {
1710   DCHECK_LE(0, new_len);
1711   DCHECK_LE(new_len, array->length());
1712   if (new_len == 0) return empty_fixed_array();
1713 
1714   HeapObject obj = AllocateRawFixedArray(new_len, allocation);
1715   obj.set_map_after_allocation(*fixed_array_map(), SKIP_WRITE_BARRIER);
1716   Handle<FixedArray> result(FixedArray::cast(obj), isolate());
1717   result->set_length(new_len);
1718 
1719   // Copy the content.
1720   DisallowHeapAllocation no_gc;
1721   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
1722   result->CopyElements(isolate(), 0, *array, 0, new_len, mode);
1723   return result;
1724 }
1725 
CopyFixedArray(Handle<FixedArray> array)1726 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
1727   if (array->length() == 0) return array;
1728   return CopyArrayWithMap(array, handle(array->map(), isolate()));
1729 }
1730 
CopyAndTenureFixedCOWArray(Handle<FixedArray> array)1731 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
1732     Handle<FixedArray> array) {
1733   DCHECK(Heap::InYoungGeneration(*array));
1734   Handle<FixedArray> result =
1735       CopyFixedArrayUpTo(array, array->length(), AllocationType::kOld);
1736 
1737   // TODO(mvstanton): The map is set twice because of protection against calling
1738   // set() on a COW FixedArray. Issue v8:3221 created to track this, and
1739   // we might then be able to remove this whole method.
1740   result->set_map_after_allocation(*fixed_cow_array_map(), SKIP_WRITE_BARRIER);
1741   return result;
1742 }
1743 
CopyFixedDoubleArray(Handle<FixedDoubleArray> array)1744 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
1745     Handle<FixedDoubleArray> array) {
1746   int len = array->length();
1747   if (len == 0) return array;
1748   Handle<FixedDoubleArray> result =
1749       Handle<FixedDoubleArray>::cast(NewFixedDoubleArray(len));
1750   Heap::CopyBlock(
1751       result->address() + FixedDoubleArray::kLengthOffset,
1752       array->address() + FixedDoubleArray::kLengthOffset,
1753       FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
1754   return result;
1755 }
1756 
NewHeapNumberForCodeAssembler(double value)1757 Handle<HeapNumber> Factory::NewHeapNumberForCodeAssembler(double value) {
1758   return isolate()->heap()->CanAllocateInReadOnlySpace()
1759              ? NewHeapNumber<AllocationType::kReadOnly>(value)
1760              : NewHeapNumber<AllocationType::kOld>(value);
1761 }
1762 
NewError(Handle<JSFunction> constructor,MessageTemplate template_index,Handle<Object> arg0,Handle<Object> arg1,Handle<Object> arg2)1763 Handle<JSObject> Factory::NewError(Handle<JSFunction> constructor,
1764                                    MessageTemplate template_index,
1765                                    Handle<Object> arg0, Handle<Object> arg1,
1766                                    Handle<Object> arg2) {
1767   HandleScope scope(isolate());
1768 
1769   if (arg0.is_null()) arg0 = undefined_value();
1770   if (arg1.is_null()) arg1 = undefined_value();
1771   if (arg2.is_null()) arg2 = undefined_value();
1772 
1773   return scope.CloseAndEscape(ErrorUtils::MakeGenericError(
1774       isolate(), constructor, template_index, arg0, arg1, arg2, SKIP_NONE));
1775 }
1776 
NewError(Handle<JSFunction> constructor,Handle<String> message)1777 Handle<JSObject> Factory::NewError(Handle<JSFunction> constructor,
1778                                    Handle<String> message) {
1779   // Construct a new error object. If an exception is thrown, use the exception
1780   // as the result.
1781 
1782   Handle<Object> no_caller;
1783   return ErrorUtils::Construct(isolate(), constructor, constructor, message,
1784                                SKIP_NONE, no_caller,
1785                                ErrorUtils::StackTraceCollection::kDetailed)
1786       .ToHandleChecked();
1787 }
1788 
NewInvalidStringLengthError()1789 Handle<Object> Factory::NewInvalidStringLengthError() {
1790   if (FLAG_correctness_fuzzer_suppressions) {
1791     FATAL("Aborting on invalid string length");
1792   }
1793   // Invalidate the "string length" protector.
1794   if (Protectors::IsStringLengthOverflowLookupChainIntact(isolate())) {
1795     Protectors::InvalidateStringLengthOverflowLookupChain(isolate());
1796   }
1797   return NewRangeError(MessageTemplate::kInvalidStringLength);
1798 }
1799 
1800 #define DEFINE_ERROR(NAME, name)                                              \
1801   Handle<JSObject> Factory::New##NAME(                                        \
1802       MessageTemplate template_index, Handle<Object> arg0,                    \
1803       Handle<Object> arg1, Handle<Object> arg2) {                             \
1804     return NewError(isolate()->name##_function(), template_index, arg0, arg1, \
1805                     arg2);                                                    \
1806   }
DEFINE_ERROR(Error,error)1807 DEFINE_ERROR(Error, error)
1808 DEFINE_ERROR(EvalError, eval_error)
1809 DEFINE_ERROR(RangeError, range_error)
1810 DEFINE_ERROR(ReferenceError, reference_error)
1811 DEFINE_ERROR(SyntaxError, syntax_error)
1812 DEFINE_ERROR(TypeError, type_error)
1813 DEFINE_ERROR(WasmCompileError, wasm_compile_error)
1814 DEFINE_ERROR(WasmLinkError, wasm_link_error)
1815 DEFINE_ERROR(WasmRuntimeError, wasm_runtime_error)
1816 #undef DEFINE_ERROR
1817 
1818 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1819   // Make sure to use globals from the function's context, since the function
1820   // can be from a different context.
1821   Handle<NativeContext> native_context(function->context().native_context(),
1822                                        isolate());
1823   Handle<Map> new_map;
1824   if (V8_UNLIKELY(IsAsyncGeneratorFunction(function->shared().kind()))) {
1825     new_map = handle(native_context->async_generator_object_prototype_map(),
1826                      isolate());
1827   } else if (IsResumableFunction(function->shared().kind())) {
1828     // Generator and async function prototypes can share maps since they
1829     // don't have "constructor" properties.
1830     new_map =
1831         handle(native_context->generator_object_prototype_map(), isolate());
1832   } else {
1833     // Each function prototype gets a fresh map to avoid unwanted sharing of
1834     // maps between prototypes of different constructors.
1835     Handle<JSFunction> object_function(native_context->object_function(),
1836                                        isolate());
1837     DCHECK(object_function->has_initial_map());
1838     new_map = handle(object_function->initial_map(), isolate());
1839   }
1840 
1841   DCHECK(!new_map->is_prototype_map());
1842   Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1843 
1844   if (!IsResumableFunction(function->shared().kind())) {
1845     JSObject::AddProperty(isolate(), prototype, constructor_string(), function,
1846                           DONT_ENUM);
1847   }
1848 
1849   return prototype;
1850 }
1851 
NewExternal(void * value)1852 Handle<JSObject> Factory::NewExternal(void* value) {
1853   Handle<Foreign> foreign = NewForeign(reinterpret_cast<Address>(value));
1854   Handle<JSObject> external = NewJSObjectFromMap(external_map());
1855   external->SetEmbedderField(0, *foreign);
1856   return external;
1857 }
1858 
NewCodeDataContainer(int flags,AllocationType allocation)1859 Handle<CodeDataContainer> Factory::NewCodeDataContainer(
1860     int flags, AllocationType allocation) {
1861   Handle<CodeDataContainer> data_container(
1862       CodeDataContainer::cast(New(code_data_container_map(), allocation)),
1863       isolate());
1864   data_container->set_next_code_link(*undefined_value(), SKIP_WRITE_BARRIER);
1865   data_container->set_kind_specific_flags(flags);
1866   data_container->clear_padding();
1867   return data_container;
1868 }
1869 
NewOffHeapTrampolineFor(Handle<Code> code,Address off_heap_entry)1870 Handle<Code> Factory::NewOffHeapTrampolineFor(Handle<Code> code,
1871                                               Address off_heap_entry) {
1872   CHECK_NOT_NULL(isolate()->embedded_blob_code());
1873   CHECK_NE(0, isolate()->embedded_blob_code_size());
1874   CHECK(Builtins::IsIsolateIndependentBuiltin(*code));
1875 
1876   bool generate_jump_to_instruction_stream =
1877       Builtins::CodeObjectIsExecutable(code->builtin_index());
1878   Handle<Code> result = Builtins::GenerateOffHeapTrampolineFor(
1879       isolate(), off_heap_entry,
1880       code->code_data_container(kAcquireLoad).kind_specific_flags(),
1881       generate_jump_to_instruction_stream);
1882 
1883   // Trampolines may not contain any metadata since all metadata offsets,
1884   // stored on the Code object, refer to the off-heap metadata area.
1885   CHECK_EQ(result->raw_metadata_size(), 0);
1886 
1887   // The CodeDataContainer should not be modified beyond this point since it's
1888   // now possibly canonicalized.
1889 
1890   // The trampoline code object must inherit specific flags from the original
1891   // builtin (e.g. the safepoint-table offset). We set them manually here.
1892   {
1893     CodePageMemoryModificationScope code_allocation(*result);
1894 
1895     const bool set_is_off_heap_trampoline = true;
1896     const int stack_slots =
1897         code->has_safepoint_info() ? code->stack_slots() : 0;
1898     result->initialize_flags(code->kind(), code->is_turbofanned(), stack_slots,
1899                              set_is_off_heap_trampoline);
1900     result->set_builtin_index(code->builtin_index());
1901     result->set_handler_table_offset(code->handler_table_offset());
1902     result->set_constant_pool_offset(code->constant_pool_offset());
1903     result->set_code_comments_offset(code->code_comments_offset());
1904     result->set_unwinding_info_offset(code->unwinding_info_offset());
1905 
1906     // Replace the newly generated trampoline's RelocInfo ByteArray with the
1907     // canonical one stored in the roots to avoid duplicating it for every
1908     // single builtin.
1909     ByteArray canonical_reloc_info =
1910         generate_jump_to_instruction_stream
1911             ? ReadOnlyRoots(isolate()).off_heap_trampoline_relocation_info()
1912             : ReadOnlyRoots(isolate()).empty_byte_array();
1913 #ifdef DEBUG
1914     // Verify that the contents are the same.
1915     ByteArray reloc_info = result->relocation_info();
1916     DCHECK_EQ(reloc_info.length(), canonical_reloc_info.length());
1917     for (int i = 0; i < reloc_info.length(); ++i) {
1918       DCHECK_EQ(reloc_info.get(i), canonical_reloc_info.get(i));
1919     }
1920 #endif
1921     result->set_relocation_info(canonical_reloc_info);
1922   }
1923 
1924   return result;
1925 }
1926 
CopyCode(Handle<Code> code)1927 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1928   Handle<CodeDataContainer> data_container = NewCodeDataContainer(
1929       code->code_data_container(kAcquireLoad).kind_specific_flags(),
1930       AllocationType::kOld);
1931 
1932   Heap* heap = isolate()->heap();
1933   Handle<Code> new_code;
1934   {
1935     int obj_size = code->Size();
1936     CodePageCollectionMemoryModificationScope code_allocation(heap);
1937     HeapObject result = heap->AllocateRawWith<Heap::kRetryOrFail>(
1938         obj_size, AllocationType::kCode, AllocationOrigin::kRuntime);
1939 
1940     // Copy code object.
1941     Address old_addr = code->address();
1942     Address new_addr = result.address();
1943     Heap::CopyBlock(new_addr, old_addr, obj_size);
1944     new_code = handle(Code::cast(result), isolate());
1945 
1946     // Set the {CodeDataContainer}, it cannot be shared.
1947     new_code->set_code_data_container(*data_container, kReleaseStore);
1948 
1949     new_code->Relocate(new_addr - old_addr);
1950     // We have to iterate over the object and process its pointers when black
1951     // allocation is on.
1952     heap->incremental_marking()->ProcessBlackAllocatedObject(*new_code);
1953     // Record all references to embedded objects in the new code object.
1954 #ifndef V8_DISABLE_WRITE_BARRIERS
1955     WriteBarrierForCode(*new_code);
1956 #endif
1957   }
1958 
1959 #ifdef VERIFY_HEAP
1960   if (FLAG_verify_heap) new_code->ObjectVerify(isolate());
1961 #endif
1962   DCHECK(IsAligned(new_code->address(), kCodeAlignment));
1963   DCHECK_IMPLIES(
1964       !V8_ENABLE_THIRD_PARTY_HEAP_BOOL &&
1965       !heap->memory_allocator()->code_range().is_empty(),
1966       heap->memory_allocator()->code_range().contains(new_code->address()));
1967   return new_code;
1968 }
1969 
CopyBytecodeArray(Handle<BytecodeArray> bytecode_array)1970 Handle<BytecodeArray> Factory::CopyBytecodeArray(
1971     Handle<BytecodeArray> bytecode_array) {
1972   int size = BytecodeArray::SizeFor(bytecode_array->length());
1973   HeapObject result = AllocateRawWithImmortalMap(size, AllocationType::kOld,
1974                                                  *bytecode_array_map());
1975 
1976   Handle<BytecodeArray> copy(BytecodeArray::cast(result), isolate());
1977   copy->set_length(bytecode_array->length());
1978   copy->set_frame_size(bytecode_array->frame_size());
1979   copy->set_parameter_count(bytecode_array->parameter_count());
1980   copy->set_incoming_new_target_or_generator_register(
1981       bytecode_array->incoming_new_target_or_generator_register());
1982   copy->set_constant_pool(bytecode_array->constant_pool());
1983   copy->set_handler_table(bytecode_array->handler_table());
1984   copy->set_source_position_table(
1985       bytecode_array->source_position_table(kAcquireLoad), kReleaseStore);
1986   copy->set_osr_loop_nesting_level(bytecode_array->osr_loop_nesting_level());
1987   copy->set_bytecode_age(bytecode_array->bytecode_age());
1988   bytecode_array->CopyBytecodesTo(*copy);
1989   return copy;
1990 }
1991 
NewJSObject(Handle<JSFunction> constructor,AllocationType allocation)1992 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1993                                       AllocationType allocation) {
1994   JSFunction::EnsureHasInitialMap(constructor);
1995   Handle<Map> map(constructor->initial_map(), isolate());
1996   return NewJSObjectFromMap(map, allocation);
1997 }
1998 
NewJSObjectWithNullProto()1999 Handle<JSObject> Factory::NewJSObjectWithNullProto() {
2000   Handle<JSObject> result = NewJSObject(isolate()->object_function());
2001   Handle<Map> new_map = Map::Copy(
2002       isolate(), Handle<Map>(result->map(), isolate()), "ObjectWithNullProto");
2003   Map::SetPrototype(isolate(), new_map, null_value());
2004   JSObject::MigrateToMap(isolate(), result, new_map);
2005   return result;
2006 }
2007 
NewJSGlobalObject(Handle<JSFunction> constructor)2008 Handle<JSGlobalObject> Factory::NewJSGlobalObject(
2009     Handle<JSFunction> constructor) {
2010   DCHECK(constructor->has_initial_map());
2011   Handle<Map> map(constructor->initial_map(), isolate());
2012   DCHECK(map->is_dictionary_map());
2013 
2014   // Make sure no field properties are described in the initial map.
2015   // This guarantees us that normalizing the properties does not
2016   // require us to change property values to PropertyCells.
2017   DCHECK_EQ(map->NextFreePropertyIndex(), 0);
2018 
2019   // Make sure we don't have a ton of pre-allocated slots in the
2020   // global objects. They will be unused once we normalize the object.
2021   DCHECK_EQ(map->UnusedPropertyFields(), 0);
2022   DCHECK_EQ(map->GetInObjectProperties(), 0);
2023 
2024   // Initial size of the backing store to avoid resize of the storage during
2025   // bootstrapping. The size differs between the JS global object ad the
2026   // builtins object.
2027   int initial_size = 64;
2028 
2029   // Allocate a dictionary object for backing storage.
2030   int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
2031   Handle<GlobalDictionary> dictionary =
2032       GlobalDictionary::New(isolate(), at_least_space_for);
2033 
2034   // The global object might be created from an object template with accessors.
2035   // Fill these accessors into the dictionary.
2036   Handle<DescriptorArray> descs(map->instance_descriptors(kRelaxedLoad),
2037                                 isolate());
2038   for (InternalIndex i : map->IterateOwnDescriptors()) {
2039     PropertyDetails details = descs->GetDetails(i);
2040     // Only accessors are expected.
2041     DCHECK_EQ(kAccessor, details.kind());
2042     PropertyDetails d(kAccessor, details.attributes(),
2043                       PropertyCellType::kMutable);
2044     Handle<Name> name(descs->GetKey(i), isolate());
2045     Handle<PropertyCell> cell = NewPropertyCell(name);
2046     cell->set_value(descs->GetStrongValue(i));
2047     // |dictionary| already contains enough space for all properties.
2048     USE(GlobalDictionary::Add(isolate(), dictionary, name, cell, d));
2049   }
2050 
2051   // Allocate the global object and initialize it with the backing store.
2052   Handle<JSGlobalObject> global(
2053       JSGlobalObject::cast(New(map, AllocationType::kOld)), isolate());
2054   InitializeJSObjectFromMap(global, dictionary, map);
2055 
2056   // Create a new map for the global object.
2057   Handle<Map> new_map = Map::CopyDropDescriptors(isolate(), map);
2058   new_map->set_may_have_interesting_symbols(true);
2059   new_map->set_is_dictionary_map(true);
2060   LOG(isolate(), MapDetails(*new_map));
2061 
2062   // Set up the global object as a normalized object.
2063   global->set_global_dictionary(*dictionary);
2064   global->synchronized_set_map(*new_map);
2065 
2066   // Make sure result is a global object with properties in dictionary.
2067   DCHECK(global->IsJSGlobalObject() && !global->HasFastProperties());
2068   return global;
2069 }
2070 
InitializeJSObjectFromMap(Handle<JSObject> obj,Handle<Object> properties,Handle<Map> map)2071 void Factory::InitializeJSObjectFromMap(Handle<JSObject> obj,
2072                                         Handle<Object> properties,
2073                                         Handle<Map> map) {
2074   obj->set_raw_properties_or_hash(*properties);
2075   obj->initialize_elements();
2076   // TODO(1240798): Initialize the object's body using valid initial values
2077   // according to the object's initial map.  For example, if the map's
2078   // instance type is JS_ARRAY_TYPE, the length field should be initialized
2079   // to a number (e.g. Smi::zero()) and the elements initialized to a
2080   // fixed array (e.g. Heap::empty_fixed_array()).  Currently, the object
2081   // verification code has to cope with (temporarily) invalid objects.  See
2082   // for example, JSArray::JSArrayVerify).
2083   InitializeJSObjectBody(obj, map, JSObject::kHeaderSize);
2084 }
2085 
InitializeJSObjectBody(Handle<JSObject> obj,Handle<Map> map,int start_offset)2086 void Factory::InitializeJSObjectBody(Handle<JSObject> obj, Handle<Map> map,
2087                                      int start_offset) {
2088   if (start_offset == map->instance_size()) return;
2089   DCHECK_LT(start_offset, map->instance_size());
2090 
2091   // We cannot always fill with one_pointer_filler_map because objects
2092   // created from API functions expect their embedder fields to be initialized
2093   // with undefined_value.
2094   // Pre-allocated fields need to be initialized with undefined_value as well
2095   // so that object accesses before the constructor completes (e.g. in the
2096   // debugger) will not cause a crash.
2097 
2098   // In case of Array subclassing the |map| could already be transitioned
2099   // to different elements kind from the initial map on which we track slack.
2100   bool in_progress = map->IsInobjectSlackTrackingInProgress();
2101   Object filler;
2102   if (in_progress) {
2103     filler = *one_pointer_filler_map();
2104   } else {
2105     filler = *undefined_value();
2106   }
2107   obj->InitializeBody(*map, start_offset, *undefined_value(), filler);
2108   if (in_progress) {
2109     map->FindRootMap(isolate()).InobjectSlackTrackingStep(isolate());
2110   }
2111 }
2112 
NewJSObjectFromMap(Handle<Map> map,AllocationType allocation,Handle<AllocationSite> allocation_site)2113 Handle<JSObject> Factory::NewJSObjectFromMap(
2114     Handle<Map> map, AllocationType allocation,
2115     Handle<AllocationSite> allocation_site) {
2116   // JSFunctions should be allocated using AllocateFunction to be
2117   // properly initialized.
2118   DCHECK(map->instance_type() != JS_FUNCTION_TYPE);
2119 
2120   // Both types of global objects should be allocated using
2121   // AllocateGlobalObject to be properly initialized.
2122   DCHECK(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
2123 
2124   HeapObject obj =
2125       AllocateRawWithAllocationSite(map, allocation, allocation_site);
2126   Handle<JSObject> js_obj(JSObject::cast(obj), isolate());
2127 
2128   InitializeJSObjectFromMap(js_obj, empty_fixed_array(), map);
2129 
2130   DCHECK(js_obj->HasFastElements() || js_obj->HasTypedArrayElements() ||
2131          js_obj->HasFastStringWrapperElements() ||
2132          js_obj->HasFastArgumentsElements() || js_obj->HasDictionaryElements());
2133   return js_obj;
2134 }
2135 
NewSlowJSObjectFromMap(Handle<Map> map,int capacity,AllocationType allocation,Handle<AllocationSite> allocation_site)2136 Handle<JSObject> Factory::NewSlowJSObjectFromMap(
2137     Handle<Map> map, int capacity, AllocationType allocation,
2138     Handle<AllocationSite> allocation_site) {
2139   DCHECK(map->is_dictionary_map());
2140   Handle<NameDictionary> object_properties =
2141       NameDictionary::New(isolate(), capacity);
2142   Handle<JSObject> js_object =
2143       NewJSObjectFromMap(map, allocation, allocation_site);
2144   js_object->set_raw_properties_or_hash(*object_properties);
2145   return js_object;
2146 }
2147 
NewSlowJSObjectWithPropertiesAndElements(Handle<HeapObject> prototype,Handle<NameDictionary> properties,Handle<FixedArrayBase> elements)2148 Handle<JSObject> Factory::NewSlowJSObjectWithPropertiesAndElements(
2149     Handle<HeapObject> prototype, Handle<NameDictionary> properties,
2150     Handle<FixedArrayBase> elements) {
2151   Handle<Map> object_map = isolate()->slow_object_with_object_prototype_map();
2152   if (object_map->prototype() != *prototype) {
2153     object_map = Map::TransitionToPrototype(isolate(), object_map, prototype);
2154   }
2155   DCHECK(object_map->is_dictionary_map());
2156   Handle<JSObject> object =
2157       NewJSObjectFromMap(object_map, AllocationType::kYoung);
2158   object->set_raw_properties_or_hash(*properties);
2159   if (*elements != ReadOnlyRoots(isolate()).empty_fixed_array()) {
2160     DCHECK(elements->IsNumberDictionary());
2161     object_map =
2162         JSObject::GetElementsTransitionMap(object, DICTIONARY_ELEMENTS);
2163     JSObject::MigrateToMap(isolate(), object, object_map);
2164     object->set_elements(*elements);
2165   }
2166   return object;
2167 }
2168 
NewJSArray(ElementsKind elements_kind,int length,int capacity,ArrayStorageAllocationMode mode,AllocationType allocation)2169 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind, int length,
2170                                     int capacity,
2171                                     ArrayStorageAllocationMode mode,
2172                                     AllocationType allocation) {
2173   DCHECK(capacity >= length);
2174   if (capacity == 0) {
2175     return NewJSArrayWithElements(empty_fixed_array(), elements_kind, length,
2176                                   allocation);
2177   }
2178 
2179   HandleScope inner_scope(isolate());
2180   Handle<FixedArrayBase> elms =
2181       NewJSArrayStorage(elements_kind, capacity, mode);
2182   return inner_scope.CloseAndEscape(NewJSArrayWithUnverifiedElements(
2183       elms, elements_kind, length, allocation));
2184 }
2185 
NewJSArrayWithElements(Handle<FixedArrayBase> elements,ElementsKind elements_kind,int length,AllocationType allocation)2186 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
2187                                                 ElementsKind elements_kind,
2188                                                 int length,
2189                                                 AllocationType allocation) {
2190   Handle<JSArray> array = NewJSArrayWithUnverifiedElements(
2191       elements, elements_kind, length, allocation);
2192   JSObject::ValidateElements(*array);
2193   return array;
2194 }
2195 
NewJSArrayWithUnverifiedElements(Handle<FixedArrayBase> elements,ElementsKind elements_kind,int length,AllocationType allocation)2196 Handle<JSArray> Factory::NewJSArrayWithUnverifiedElements(
2197     Handle<FixedArrayBase> elements, ElementsKind elements_kind, int length,
2198     AllocationType allocation) {
2199   DCHECK(length <= elements->length());
2200   NativeContext native_context = isolate()->raw_native_context();
2201   Map map = native_context.GetInitialJSArrayMap(elements_kind);
2202   if (map.is_null()) {
2203     JSFunction array_function = native_context.array_function();
2204     map = array_function.initial_map();
2205   }
2206   Handle<JSArray> array = Handle<JSArray>::cast(
2207       NewJSObjectFromMap(handle(map, isolate()), allocation));
2208   DisallowHeapAllocation no_gc;
2209   array->set_elements(*elements);
2210   array->set_length(Smi::FromInt(length));
2211   return array;
2212 }
2213 
NewJSArrayStorage(Handle<JSArray> array,int length,int capacity,ArrayStorageAllocationMode mode)2214 void Factory::NewJSArrayStorage(Handle<JSArray> array, int length, int capacity,
2215                                 ArrayStorageAllocationMode mode) {
2216   DCHECK(capacity >= length);
2217 
2218   if (capacity == 0) {
2219     array->set_length(Smi::zero());
2220     array->set_elements(*empty_fixed_array());
2221     return;
2222   }
2223 
2224   HandleScope inner_scope(isolate());
2225   Handle<FixedArrayBase> elms =
2226       NewJSArrayStorage(array->GetElementsKind(), capacity, mode);
2227 
2228   array->set_elements(*elms);
2229   array->set_length(Smi::FromInt(length));
2230 }
2231 
NewJSArrayStorage(ElementsKind elements_kind,int capacity,ArrayStorageAllocationMode mode)2232 Handle<FixedArrayBase> Factory::NewJSArrayStorage(
2233     ElementsKind elements_kind, int capacity, ArrayStorageAllocationMode mode) {
2234   DCHECK_GT(capacity, 0);
2235   Handle<FixedArrayBase> elms;
2236   if (IsDoubleElementsKind(elements_kind)) {
2237     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
2238       elms = NewFixedDoubleArray(capacity);
2239     } else {
2240       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
2241       elms = NewFixedDoubleArrayWithHoles(capacity);
2242     }
2243   } else {
2244     DCHECK(IsSmiOrObjectElementsKind(elements_kind));
2245     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
2246       elms = NewUninitializedFixedArray(capacity);
2247     } else {
2248       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
2249       elms = NewFixedArrayWithHoles(capacity);
2250     }
2251   }
2252   return elms;
2253 }
2254 
NewJSWeakMap()2255 Handle<JSWeakMap> Factory::NewJSWeakMap() {
2256   NativeContext native_context = isolate()->raw_native_context();
2257   Handle<Map> map(native_context.js_weak_map_fun().initial_map(), isolate());
2258   Handle<JSWeakMap> weakmap(JSWeakMap::cast(*NewJSObjectFromMap(map)),
2259                             isolate());
2260   {
2261     // Do not leak handles for the hash table, it would make entries strong.
2262     HandleScope scope(isolate());
2263     JSWeakCollection::Initialize(weakmap, isolate());
2264   }
2265   return weakmap;
2266 }
2267 
NewJSModuleNamespace()2268 Handle<JSModuleNamespace> Factory::NewJSModuleNamespace() {
2269   Handle<Map> map = isolate()->js_module_namespace_map();
2270   Handle<JSModuleNamespace> module_namespace(
2271       Handle<JSModuleNamespace>::cast(NewJSObjectFromMap(map)));
2272   FieldIndex index = FieldIndex::ForDescriptor(
2273       *map, InternalIndex(JSModuleNamespace::kToStringTagFieldIndex));
2274   module_namespace->FastPropertyAtPut(index,
2275                                       ReadOnlyRoots(isolate()).Module_string());
2276   return module_namespace;
2277 }
2278 
NewJSGeneratorObject(Handle<JSFunction> function)2279 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
2280     Handle<JSFunction> function) {
2281   DCHECK(IsResumableFunction(function->shared().kind()));
2282   JSFunction::EnsureHasInitialMap(function);
2283   Handle<Map> map(function->initial_map(), isolate());
2284 
2285   DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE ||
2286          map->instance_type() == JS_ASYNC_GENERATOR_OBJECT_TYPE);
2287 
2288   return Handle<JSGeneratorObject>::cast(NewJSObjectFromMap(map));
2289 }
2290 
NewSourceTextModule(Handle<SharedFunctionInfo> code)2291 Handle<SourceTextModule> Factory::NewSourceTextModule(
2292     Handle<SharedFunctionInfo> code) {
2293   Handle<SourceTextModuleInfo> module_info(
2294       code->scope_info().ModuleDescriptorInfo(), isolate());
2295   Handle<ObjectHashTable> exports =
2296       ObjectHashTable::New(isolate(), module_info->RegularExportCount());
2297   Handle<FixedArray> regular_exports =
2298       NewFixedArray(module_info->RegularExportCount());
2299   Handle<FixedArray> regular_imports =
2300       NewFixedArray(module_info->regular_imports().length());
2301   int requested_modules_length = module_info->module_requests().length();
2302   Handle<FixedArray> requested_modules =
2303       requested_modules_length > 0 ? NewFixedArray(requested_modules_length)
2304                                    : empty_fixed_array();
2305   Handle<ArrayList> async_parent_modules = ArrayList::New(isolate(), 0);
2306 
2307   ReadOnlyRoots roots(isolate());
2308   Handle<SourceTextModule> module(
2309       SourceTextModule::cast(
2310           New(source_text_module_map(), AllocationType::kOld)),
2311       isolate());
2312   module->set_code(*code);
2313   module->set_exports(*exports);
2314   module->set_regular_exports(*regular_exports);
2315   module->set_regular_imports(*regular_imports);
2316   module->set_hash(isolate()->GenerateIdentityHash(Smi::kMaxValue));
2317   module->set_module_namespace(roots.undefined_value());
2318   module->set_requested_modules(*requested_modules);
2319   module->set_script(Script::cast(code->script()));
2320   module->set_status(Module::kUninstantiated);
2321   module->set_exception(roots.the_hole_value());
2322   module->set_import_meta(roots.the_hole_value());
2323   module->set_dfs_index(-1);
2324   module->set_dfs_ancestor_index(-1);
2325   module->set_top_level_capability(roots.undefined_value());
2326   module->set_flags(0);
2327   module->set_async(IsAsyncModule(code->kind()));
2328   module->set_async_evaluating(false);
2329   module->set_async_parent_modules(*async_parent_modules);
2330   module->set_pending_async_dependencies(0);
2331   return module;
2332 }
2333 
NewSyntheticModule(Handle<String> module_name,Handle<FixedArray> export_names,v8::Module::SyntheticModuleEvaluationSteps evaluation_steps)2334 Handle<SyntheticModule> Factory::NewSyntheticModule(
2335     Handle<String> module_name, Handle<FixedArray> export_names,
2336     v8::Module::SyntheticModuleEvaluationSteps evaluation_steps) {
2337   ReadOnlyRoots roots(isolate());
2338 
2339   Handle<ObjectHashTable> exports =
2340       ObjectHashTable::New(isolate(), static_cast<int>(export_names->length()));
2341   Handle<Foreign> evaluation_steps_foreign =
2342       NewForeign(reinterpret_cast<i::Address>(evaluation_steps));
2343 
2344   Handle<SyntheticModule> module(
2345       SyntheticModule::cast(New(synthetic_module_map(), AllocationType::kOld)),
2346       isolate());
2347   module->set_hash(isolate()->GenerateIdentityHash(Smi::kMaxValue));
2348   module->set_module_namespace(roots.undefined_value());
2349   module->set_status(Module::kUninstantiated);
2350   module->set_exception(roots.the_hole_value());
2351   module->set_name(*module_name);
2352   module->set_export_names(*export_names);
2353   module->set_exports(*exports);
2354   module->set_evaluation_steps(*evaluation_steps_foreign);
2355   return module;
2356 }
2357 
NewJSArrayBuffer(std::shared_ptr<BackingStore> backing_store,AllocationType allocation)2358 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer(
2359     std::shared_ptr<BackingStore> backing_store, AllocationType allocation) {
2360   Handle<Map> map(isolate()->native_context()->array_buffer_fun().initial_map(),
2361                   isolate());
2362   auto result =
2363       Handle<JSArrayBuffer>::cast(NewJSObjectFromMap(map, allocation));
2364   result->Setup(SharedFlag::kNotShared, std::move(backing_store));
2365   return result;
2366 }
2367 
NewJSArrayBufferAndBackingStore(size_t byte_length,InitializedFlag initialized,AllocationType allocation)2368 MaybeHandle<JSArrayBuffer> Factory::NewJSArrayBufferAndBackingStore(
2369     size_t byte_length, InitializedFlag initialized,
2370     AllocationType allocation) {
2371   std::unique_ptr<BackingStore> backing_store = nullptr;
2372 
2373   if (byte_length > 0) {
2374     backing_store = BackingStore::Allocate(isolate(), byte_length,
2375                                            SharedFlag::kNotShared, initialized);
2376     if (!backing_store) return MaybeHandle<JSArrayBuffer>();
2377   }
2378   Handle<Map> map(isolate()->native_context()->array_buffer_fun().initial_map(),
2379                   isolate());
2380   auto array_buffer =
2381       Handle<JSArrayBuffer>::cast(NewJSObjectFromMap(map, allocation));
2382   array_buffer->Setup(SharedFlag::kNotShared, std::move(backing_store));
2383   return array_buffer;
2384 }
2385 
NewJSSharedArrayBuffer(std::shared_ptr<BackingStore> backing_store)2386 Handle<JSArrayBuffer> Factory::NewJSSharedArrayBuffer(
2387     std::shared_ptr<BackingStore> backing_store) {
2388   Handle<Map> map(
2389       isolate()->native_context()->shared_array_buffer_fun().initial_map(),
2390       isolate());
2391   auto result = Handle<JSArrayBuffer>::cast(
2392       NewJSObjectFromMap(map, AllocationType::kYoung));
2393   result->Setup(SharedFlag::kShared, std::move(backing_store));
2394   return result;
2395 }
2396 
NewJSIteratorResult(Handle<Object> value,bool done)2397 Handle<JSIteratorResult> Factory::NewJSIteratorResult(Handle<Object> value,
2398                                                       bool done) {
2399   Handle<Map> map(isolate()->native_context()->iterator_result_map(),
2400                   isolate());
2401   Handle<JSIteratorResult> js_iter_result =
2402       Handle<JSIteratorResult>::cast(NewJSObjectFromMap(map));
2403   js_iter_result->set_value(*value);
2404   js_iter_result->set_done(*ToBoolean(done));
2405   return js_iter_result;
2406 }
2407 
NewJSAsyncFromSyncIterator(Handle<JSReceiver> sync_iterator,Handle<Object> next)2408 Handle<JSAsyncFromSyncIterator> Factory::NewJSAsyncFromSyncIterator(
2409     Handle<JSReceiver> sync_iterator, Handle<Object> next) {
2410   Handle<Map> map(isolate()->native_context()->async_from_sync_iterator_map(),
2411                   isolate());
2412   Handle<JSAsyncFromSyncIterator> iterator =
2413       Handle<JSAsyncFromSyncIterator>::cast(NewJSObjectFromMap(map));
2414 
2415   iterator->set_sync_iterator(*sync_iterator);
2416   iterator->set_next(*next);
2417   return iterator;
2418 }
2419 
NewJSMap()2420 Handle<JSMap> Factory::NewJSMap() {
2421   Handle<Map> map(isolate()->native_context()->js_map_map(), isolate());
2422   Handle<JSMap> js_map = Handle<JSMap>::cast(NewJSObjectFromMap(map));
2423   JSMap::Initialize(js_map, isolate());
2424   return js_map;
2425 }
2426 
NewJSSet()2427 Handle<JSSet> Factory::NewJSSet() {
2428   Handle<Map> map(isolate()->native_context()->js_set_map(), isolate());
2429   Handle<JSSet> js_set = Handle<JSSet>::cast(NewJSObjectFromMap(map));
2430   JSSet::Initialize(js_set, isolate());
2431   return js_set;
2432 }
2433 
TypeAndSizeForElementsKind(ElementsKind kind,ExternalArrayType * array_type,size_t * element_size)2434 void Factory::TypeAndSizeForElementsKind(ElementsKind kind,
2435                                          ExternalArrayType* array_type,
2436                                          size_t* element_size) {
2437   switch (kind) {
2438 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
2439   case TYPE##_ELEMENTS:                           \
2440     *array_type = kExternal##Type##Array;         \
2441     *element_size = sizeof(ctype);                \
2442     break;
2443     TYPED_ARRAYS(TYPED_ARRAY_CASE)
2444 #undef TYPED_ARRAY_CASE
2445 
2446     default:
2447       UNREACHABLE();
2448   }
2449 }
2450 
2451 namespace {
2452 
ForFixedTypedArray(ExternalArrayType array_type,size_t * element_size,ElementsKind * element_kind)2453 void ForFixedTypedArray(ExternalArrayType array_type, size_t* element_size,
2454                         ElementsKind* element_kind) {
2455   switch (array_type) {
2456 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
2457   case kExternal##Type##Array:                    \
2458     *element_size = sizeof(ctype);                \
2459     *element_kind = TYPE##_ELEMENTS;              \
2460     return;
2461 
2462     TYPED_ARRAYS(TYPED_ARRAY_CASE)
2463 #undef TYPED_ARRAY_CASE
2464   }
2465   UNREACHABLE();
2466 }
2467 
2468 }  // namespace
2469 
NewJSArrayBufferView(Handle<Map> map,Handle<FixedArrayBase> elements,Handle<JSArrayBuffer> buffer,size_t byte_offset,size_t byte_length)2470 Handle<JSArrayBufferView> Factory::NewJSArrayBufferView(
2471     Handle<Map> map, Handle<FixedArrayBase> elements,
2472     Handle<JSArrayBuffer> buffer, size_t byte_offset, size_t byte_length) {
2473   CHECK_LE(byte_length, buffer->byte_length());
2474   CHECK_LE(byte_offset, buffer->byte_length());
2475   CHECK_LE(byte_offset + byte_length, buffer->byte_length());
2476   Handle<JSArrayBufferView> array_buffer_view = Handle<JSArrayBufferView>::cast(
2477       NewJSObjectFromMap(map, AllocationType::kYoung));
2478   array_buffer_view->set_elements(*elements);
2479   array_buffer_view->set_buffer(*buffer);
2480   array_buffer_view->set_byte_offset(byte_offset);
2481   array_buffer_view->set_byte_length(byte_length);
2482   ZeroEmbedderFields(array_buffer_view);
2483   DCHECK_EQ(array_buffer_view->GetEmbedderFieldCount(),
2484             v8::ArrayBufferView::kEmbedderFieldCount);
2485   return array_buffer_view;
2486 }
2487 
NewJSTypedArray(ExternalArrayType type,Handle<JSArrayBuffer> buffer,size_t byte_offset,size_t length)2488 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
2489                                               Handle<JSArrayBuffer> buffer,
2490                                               size_t byte_offset,
2491                                               size_t length) {
2492   size_t element_size;
2493   ElementsKind elements_kind;
2494   ForFixedTypedArray(type, &element_size, &elements_kind);
2495   size_t byte_length = length * element_size;
2496 
2497   CHECK_LE(length, JSTypedArray::kMaxLength);
2498   CHECK_EQ(length, byte_length / element_size);
2499   CHECK_EQ(0, byte_offset % ElementsKindToByteSize(elements_kind));
2500 
2501   Handle<Map> map;
2502   switch (elements_kind) {
2503 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype)                              \
2504   case TYPE##_ELEMENTS:                                                       \
2505     map =                                                                     \
2506         handle(isolate()->native_context()->type##_array_fun().initial_map(), \
2507                isolate());                                                    \
2508     break;
2509 
2510     TYPED_ARRAYS(TYPED_ARRAY_FUN)
2511 #undef TYPED_ARRAY_FUN
2512 
2513     default:
2514       UNREACHABLE();
2515   }
2516   Handle<JSTypedArray> typed_array =
2517       Handle<JSTypedArray>::cast(NewJSArrayBufferView(
2518           map, empty_byte_array(), buffer, byte_offset, byte_length));
2519   typed_array->AllocateExternalPointerEntries(isolate());
2520   typed_array->set_length(length);
2521   typed_array->SetOffHeapDataPtr(isolate(), buffer->backing_store(),
2522                                  byte_offset);
2523   return typed_array;
2524 }
2525 
NewJSDataView(Handle<JSArrayBuffer> buffer,size_t byte_offset,size_t byte_length)2526 Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
2527                                           size_t byte_offset,
2528                                           size_t byte_length) {
2529   Handle<Map> map(isolate()->native_context()->data_view_fun().initial_map(),
2530                   isolate());
2531   Handle<JSDataView> obj = Handle<JSDataView>::cast(NewJSArrayBufferView(
2532       map, empty_fixed_array(), buffer, byte_offset, byte_length));
2533   obj->AllocateExternalPointerEntries(isolate());
2534   obj->set_data_pointer(
2535       isolate(), static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
2536   return obj;
2537 }
2538 
NewJSBoundFunction(Handle<JSReceiver> target_function,Handle<Object> bound_this,Vector<Handle<Object>> bound_args)2539 MaybeHandle<JSBoundFunction> Factory::NewJSBoundFunction(
2540     Handle<JSReceiver> target_function, Handle<Object> bound_this,
2541     Vector<Handle<Object>> bound_args) {
2542   DCHECK(target_function->IsCallable());
2543   STATIC_ASSERT(Code::kMaxArguments <= FixedArray::kMaxLength);
2544   if (bound_args.length() >= Code::kMaxArguments) {
2545     THROW_NEW_ERROR(isolate(),
2546                     NewRangeError(MessageTemplate::kTooManyArguments),
2547                     JSBoundFunction);
2548   }
2549 
2550   // Determine the prototype of the {target_function}.
2551   Handle<HeapObject> prototype;
2552   ASSIGN_RETURN_ON_EXCEPTION(
2553       isolate(), prototype,
2554       JSReceiver::GetPrototype(isolate(), target_function), JSBoundFunction);
2555 
2556   SaveAndSwitchContext save(isolate(), *target_function->GetCreationContext());
2557 
2558   // Create the [[BoundArguments]] for the result.
2559   Handle<FixedArray> bound_arguments;
2560   if (bound_args.length() == 0) {
2561     bound_arguments = empty_fixed_array();
2562   } else {
2563     bound_arguments = NewFixedArray(bound_args.length());
2564     for (int i = 0; i < bound_args.length(); ++i) {
2565       bound_arguments->set(i, *bound_args[i]);
2566     }
2567   }
2568 
2569   // Setup the map for the JSBoundFunction instance.
2570   Handle<Map> map = target_function->IsConstructor()
2571                         ? isolate()->bound_function_with_constructor_map()
2572                         : isolate()->bound_function_without_constructor_map();
2573   if (map->prototype() != *prototype) {
2574     map = Map::TransitionToPrototype(isolate(), map, prototype);
2575   }
2576   DCHECK_EQ(target_function->IsConstructor(), map->is_constructor());
2577 
2578   // Setup the JSBoundFunction instance.
2579   Handle<JSBoundFunction> result =
2580       Handle<JSBoundFunction>::cast(NewJSObjectFromMap(map));
2581   result->set_bound_target_function(*target_function);
2582   result->set_bound_this(*bound_this);
2583   result->set_bound_arguments(*bound_arguments);
2584   return result;
2585 }
2586 
2587 // ES6 section 9.5.15 ProxyCreate (target, handler)
NewJSProxy(Handle<JSReceiver> target,Handle<JSReceiver> handler)2588 Handle<JSProxy> Factory::NewJSProxy(Handle<JSReceiver> target,
2589                                     Handle<JSReceiver> handler) {
2590   // Allocate the proxy object.
2591   Handle<Map> map;
2592   if (target->IsCallable()) {
2593     if (target->IsConstructor()) {
2594       map = Handle<Map>(isolate()->proxy_constructor_map());
2595     } else {
2596       map = Handle<Map>(isolate()->proxy_callable_map());
2597     }
2598   } else {
2599     map = Handle<Map>(isolate()->proxy_map());
2600   }
2601   DCHECK(map->prototype().IsNull(isolate()));
2602   Handle<JSProxy> result(JSProxy::cast(New(map, AllocationType::kYoung)),
2603                          isolate());
2604   result->initialize_properties(isolate());
2605   result->set_target(*target);
2606   result->set_handler(*handler);
2607   return result;
2608 }
2609 
NewUninitializedJSGlobalProxy(int size)2610 Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy(int size) {
2611   // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
2612   // via ReinitializeJSGlobalProxy later.
2613   Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, size);
2614   // Maintain invariant expected from any JSGlobalProxy.
2615   map->set_is_access_check_needed(true);
2616   map->set_may_have_interesting_symbols(true);
2617   LOG(isolate(), MapDetails(*map));
2618   Handle<JSGlobalProxy> proxy = Handle<JSGlobalProxy>::cast(
2619       NewJSObjectFromMap(map, AllocationType::kOld));
2620   // Create identity hash early in case there is any JS collection containing
2621   // a global proxy key and needs to be rehashed after deserialization.
2622   proxy->GetOrCreateIdentityHash(isolate());
2623   return proxy;
2624 }
2625 
ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,Handle<JSFunction> constructor)2626 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
2627                                         Handle<JSFunction> constructor) {
2628   DCHECK(constructor->has_initial_map());
2629   Handle<Map> map(constructor->initial_map(), isolate());
2630   Handle<Map> old_map(object->map(), isolate());
2631 
2632   // The proxy's hash should be retained across reinitialization.
2633   Handle<Object> raw_properties_or_hash(object->raw_properties_or_hash(),
2634                                         isolate());
2635 
2636   if (old_map->is_prototype_map()) {
2637     map = Map::Copy(isolate(), map, "CopyAsPrototypeForJSGlobalProxy");
2638     map->set_is_prototype_map(true);
2639   }
2640   JSObject::NotifyMapChange(old_map, map, isolate());
2641   old_map->NotifyLeafMapLayoutChange(isolate());
2642 
2643   // Check that the already allocated object has the same size and type as
2644   // objects allocated using the constructor.
2645   DCHECK(map->instance_size() == old_map->instance_size());
2646   DCHECK(map->instance_type() == old_map->instance_type());
2647 
2648   // In order to keep heap in consistent state there must be no allocations
2649   // before object re-initialization is finished.
2650   DisallowHeapAllocation no_allocation;
2651 
2652   // Reset the map for the object.
2653   object->synchronized_set_map(*map);
2654 
2655   // Reinitialize the object from the constructor map.
2656   InitializeJSObjectFromMap(object, raw_properties_or_hash, map);
2657 }
2658 
NewJSMessageObject(MessageTemplate message,Handle<Object> argument,int start_position,int end_position,Handle<SharedFunctionInfo> shared_info,int bytecode_offset,Handle<Script> script,Handle<Object> stack_frames)2659 Handle<JSMessageObject> Factory::NewJSMessageObject(
2660     MessageTemplate message, Handle<Object> argument, int start_position,
2661     int end_position, Handle<SharedFunctionInfo> shared_info,
2662     int bytecode_offset, Handle<Script> script, Handle<Object> stack_frames) {
2663   Handle<Map> map = message_object_map();
2664   Handle<JSMessageObject> message_obj(
2665       JSMessageObject::cast(New(map, AllocationType::kYoung)), isolate());
2666   message_obj->set_raw_properties_or_hash(*empty_fixed_array(),
2667                                           SKIP_WRITE_BARRIER);
2668   message_obj->initialize_elements();
2669   message_obj->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2670   message_obj->set_type(message);
2671   message_obj->set_argument(*argument);
2672   message_obj->set_start_position(start_position);
2673   message_obj->set_end_position(end_position);
2674   message_obj->set_script(*script);
2675   if (start_position >= 0) {
2676     // If there's a start_position, then there's no need to store the
2677     // SharedFunctionInfo as it will never be necessary to regenerate the
2678     // position.
2679     message_obj->set_shared_info(*undefined_value());
2680     message_obj->set_bytecode_offset(Smi::FromInt(0));
2681   } else {
2682     message_obj->set_bytecode_offset(Smi::FromInt(bytecode_offset));
2683     if (shared_info.is_null()) {
2684       message_obj->set_shared_info(*undefined_value());
2685       DCHECK_EQ(bytecode_offset, -1);
2686     } else {
2687       message_obj->set_shared_info(*shared_info);
2688       DCHECK_GE(bytecode_offset, kFunctionEntryBytecodeOffset);
2689     }
2690   }
2691 
2692   message_obj->set_stack_frames(*stack_frames);
2693   message_obj->set_error_level(v8::Isolate::kMessageError);
2694   return message_obj;
2695 }
2696 
NewSharedFunctionInfoForApiFunction(MaybeHandle<String> maybe_name,Handle<FunctionTemplateInfo> function_template_info,FunctionKind kind)2697 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForApiFunction(
2698     MaybeHandle<String> maybe_name,
2699     Handle<FunctionTemplateInfo> function_template_info, FunctionKind kind) {
2700   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(
2701       maybe_name, function_template_info, Builtins::kNoBuiltinId, kind);
2702   return shared;
2703 }
2704 
NewSharedFunctionInfoForWasmCapiFunction(Handle<WasmCapiFunctionData> data)2705 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForWasmCapiFunction(
2706     Handle<WasmCapiFunctionData> data) {
2707   return NewSharedFunctionInfo(MaybeHandle<String>(), data,
2708                                Builtins::kNoBuiltinId, kConciseMethod);
2709 }
2710 
NewSharedFunctionInfoForBuiltin(MaybeHandle<String> maybe_name,int builtin_index,FunctionKind kind)2711 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForBuiltin(
2712     MaybeHandle<String> maybe_name, int builtin_index, FunctionKind kind) {
2713   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(
2714       maybe_name, MaybeHandle<Code>(), builtin_index, kind);
2715   return shared;
2716 }
2717 
2718 namespace {
NumberToStringCacheHash(Handle<FixedArray> cache,Smi number)2719 V8_INLINE int NumberToStringCacheHash(Handle<FixedArray> cache, Smi number) {
2720   int mask = (cache->length() >> 1) - 1;
2721   return number.value() & mask;
2722 }
2723 
NumberToStringCacheHash(Handle<FixedArray> cache,double number)2724 V8_INLINE int NumberToStringCacheHash(Handle<FixedArray> cache, double number) {
2725   int mask = (cache->length() >> 1) - 1;
2726   int64_t bits = bit_cast<int64_t>(number);
2727   return (static_cast<int>(bits) ^ static_cast<int>(bits >> 32)) & mask;
2728 }
2729 
CharToString(Factory * factory,const char * string,NumberCacheMode mode)2730 V8_INLINE Handle<String> CharToString(Factory* factory, const char* string,
2731                                       NumberCacheMode mode) {
2732   // We tenure the allocated string since it is referenced from the
2733   // number-string cache which lives in the old space.
2734   AllocationType type = mode == NumberCacheMode::kIgnore
2735                             ? AllocationType::kYoung
2736                             : AllocationType::kOld;
2737   return factory->NewStringFromAsciiChecked(string, type);
2738 }
2739 
2740 }  // namespace
2741 
NumberToStringCacheSet(Handle<Object> number,int hash,Handle<String> js_string)2742 void Factory::NumberToStringCacheSet(Handle<Object> number, int hash,
2743                                      Handle<String> js_string) {
2744   if (!number_string_cache()->get(hash * 2).IsUndefined(isolate()) &&
2745       !FLAG_optimize_for_size) {
2746     int full_size = isolate()->heap()->MaxNumberToStringCacheSize();
2747     if (number_string_cache()->length() != full_size) {
2748       Handle<FixedArray> new_cache =
2749           NewFixedArray(full_size, AllocationType::kOld);
2750       isolate()->heap()->set_number_string_cache(*new_cache);
2751       return;
2752     }
2753   }
2754   number_string_cache()->set(hash * 2, *number);
2755   number_string_cache()->set(hash * 2 + 1, *js_string);
2756 }
2757 
NumberToStringCacheGet(Object number,int hash)2758 Handle<Object> Factory::NumberToStringCacheGet(Object number, int hash) {
2759   DisallowHeapAllocation no_gc;
2760   Object key = number_string_cache()->get(hash * 2);
2761   if (key == number || (key.IsHeapNumber() && number.IsHeapNumber() &&
2762                         key.Number() == number.Number())) {
2763     return Handle<String>(
2764         String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2765   }
2766   return undefined_value();
2767 }
2768 
NumberToString(Handle<Object> number,NumberCacheMode mode)2769 Handle<String> Factory::NumberToString(Handle<Object> number,
2770                                        NumberCacheMode mode) {
2771   if (number->IsSmi()) return SmiToString(Smi::cast(*number), mode);
2772 
2773   double double_value = Handle<HeapNumber>::cast(number)->value();
2774   // Try to canonicalize doubles.
2775   int smi_value;
2776   if (DoubleToSmiInteger(double_value, &smi_value)) {
2777     return SmiToString(Smi::FromInt(smi_value), mode);
2778   }
2779   return HeapNumberToString(Handle<HeapNumber>::cast(number), double_value,
2780                             mode);
2781 }
2782 
2783 // Must be large enough to fit any double, int, or size_t.
2784 static const int kNumberToStringBufferSize = 32;
2785 
HeapNumberToString(Handle<HeapNumber> number,double value,NumberCacheMode mode)2786 Handle<String> Factory::HeapNumberToString(Handle<HeapNumber> number,
2787                                            double value, NumberCacheMode mode) {
2788   int hash = 0;
2789   if (mode != NumberCacheMode::kIgnore) {
2790     hash = NumberToStringCacheHash(number_string_cache(), value);
2791   }
2792   if (mode == NumberCacheMode::kBoth) {
2793     Handle<Object> cached = NumberToStringCacheGet(*number, hash);
2794     if (!cached->IsUndefined(isolate())) return Handle<String>::cast(cached);
2795   }
2796 
2797   char arr[kNumberToStringBufferSize];
2798   Vector<char> buffer(arr, arraysize(arr));
2799   const char* string = DoubleToCString(value, buffer);
2800   Handle<String> result = CharToString(this, string, mode);
2801   if (mode != NumberCacheMode::kIgnore) {
2802     NumberToStringCacheSet(number, hash, result);
2803   }
2804   return result;
2805 }
2806 
SmiToString(Smi number,NumberCacheMode mode)2807 inline Handle<String> Factory::SmiToString(Smi number, NumberCacheMode mode) {
2808   int hash = NumberToStringCacheHash(number_string_cache(), number);
2809   if (mode == NumberCacheMode::kBoth) {
2810     Handle<Object> cached = NumberToStringCacheGet(number, hash);
2811     if (!cached->IsUndefined(isolate())) return Handle<String>::cast(cached);
2812   }
2813 
2814   char arr[kNumberToStringBufferSize];
2815   Vector<char> buffer(arr, arraysize(arr));
2816   const char* string = IntToCString(number.value(), buffer);
2817   Handle<String> result = CharToString(this, string, mode);
2818   if (mode != NumberCacheMode::kIgnore) {
2819     NumberToStringCacheSet(handle(number, isolate()), hash, result);
2820   }
2821 
2822   // Compute the hash here (rather than letting the caller take care of it) so
2823   // that the "cache hit" case above doesn't have to bother with it.
2824   STATIC_ASSERT(Smi::kMaxValue <= std::numeric_limits<uint32_t>::max());
2825   if (result->hash_field() == String::kEmptyHashField && number.value() >= 0) {
2826     uint32_t field = StringHasher::MakeArrayIndexHash(
2827         static_cast<uint32_t>(number.value()), result->length());
2828     result->set_hash_field(field);
2829   }
2830   return result;
2831 }
2832 
SizeToString(size_t value,bool check_cache)2833 Handle<String> Factory::SizeToString(size_t value, bool check_cache) {
2834   Handle<String> result;
2835   NumberCacheMode cache_mode =
2836       check_cache ? NumberCacheMode::kBoth : NumberCacheMode::kIgnore;
2837   if (value <= Smi::kMaxValue) {
2838     int32_t int32v = static_cast<int32_t>(static_cast<uint32_t>(value));
2839     // SmiToString sets the hash when needed, we can return immediately.
2840     return SmiToString(Smi::FromInt(int32v), cache_mode);
2841   } else if (value <= kMaxSafeInteger) {
2842     // TODO(jkummerow): Refactor the cache to not require Objects as keys.
2843     double double_value = static_cast<double>(value);
2844     result = HeapNumberToString(NewHeapNumber(double_value), value, cache_mode);
2845   } else {
2846     char arr[kNumberToStringBufferSize];
2847     Vector<char> buffer(arr, arraysize(arr));
2848     // Build the string backwards from the least significant digit.
2849     int i = buffer.length();
2850     size_t value_copy = value;
2851     buffer[--i] = '\0';
2852     do {
2853       buffer[--i] = '0' + (value_copy % 10);
2854       value_copy /= 10;
2855     } while (value_copy > 0);
2856     char* string = buffer.begin() + i;
2857     // No way to cache this; we'd need an {Object} to use as key.
2858     result = NewStringFromAsciiChecked(string);
2859   }
2860   if (value <= JSArray::kMaxArrayIndex &&
2861       result->hash_field() == String::kEmptyHashField) {
2862     uint32_t field = StringHasher::MakeArrayIndexHash(
2863         static_cast<uint32_t>(value), result->length());
2864     result->set_hash_field(field);
2865   }
2866   return result;
2867 }
2868 
NewDebugInfo(Handle<SharedFunctionInfo> shared)2869 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2870   DCHECK(!shared->HasDebugInfo());
2871   Heap* heap = isolate()->heap();
2872 
2873   Handle<DebugInfo> debug_info =
2874       Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE, AllocationType::kOld));
2875   debug_info->set_flags(DebugInfo::kNone);
2876   debug_info->set_shared(*shared);
2877   debug_info->set_debugger_hints(0);
2878   DCHECK_EQ(DebugInfo::kNoDebuggingId, debug_info->debugging_id());
2879   debug_info->set_script(shared->script_or_debug_info(kAcquireLoad));
2880   debug_info->set_original_bytecode_array(
2881       ReadOnlyRoots(heap).undefined_value());
2882   debug_info->set_debug_bytecode_array(ReadOnlyRoots(heap).undefined_value());
2883   debug_info->set_break_points(ReadOnlyRoots(heap).empty_fixed_array());
2884 
2885   // Link debug info to function.
2886   shared->SetDebugInfo(*debug_info);
2887 
2888   return debug_info;
2889 }
2890 
NewWasmValue(int value_type,Handle<Object> ref)2891 Handle<WasmValue> Factory::NewWasmValue(int value_type, Handle<Object> ref) {
2892   DCHECK(value_type == 6 || ref->IsByteArray());
2893   Handle<WasmValue> wasm_value =
2894       Handle<WasmValue>::cast(NewStruct(WASM_VALUE_TYPE, AllocationType::kOld));
2895   wasm_value->set_value_type(value_type);
2896   wasm_value->set_bytes_or_ref(*ref);
2897   return wasm_value;
2898 }
2899 
NewBreakPointInfo(int source_position)2900 Handle<BreakPointInfo> Factory::NewBreakPointInfo(int source_position) {
2901   Handle<BreakPointInfo> new_break_point_info = Handle<BreakPointInfo>::cast(
2902       NewStruct(BREAK_POINT_INFO_TYPE, AllocationType::kOld));
2903   new_break_point_info->set_source_position(source_position);
2904   new_break_point_info->set_break_points(*undefined_value());
2905   return new_break_point_info;
2906 }
2907 
NewBreakPoint(int id,Handle<String> condition)2908 Handle<BreakPoint> Factory::NewBreakPoint(int id, Handle<String> condition) {
2909   Handle<BreakPoint> new_break_point = Handle<BreakPoint>::cast(
2910       NewStruct(BREAK_POINT_TYPE, AllocationType::kOld));
2911   new_break_point->set_id(id);
2912   new_break_point->set_condition(*condition);
2913   return new_break_point;
2914 }
2915 
NewStackTraceFrame(Handle<FrameArray> frame_array,int index)2916 Handle<StackTraceFrame> Factory::NewStackTraceFrame(
2917     Handle<FrameArray> frame_array, int index) {
2918   Handle<StackTraceFrame> frame = Handle<StackTraceFrame>::cast(
2919       NewStruct(STACK_TRACE_FRAME_TYPE, AllocationType::kYoung));
2920   frame->set_frame_array(*frame_array);
2921   frame->set_frame_index(index);
2922   frame->set_frame_info(*undefined_value());
2923 
2924   return frame;
2925 }
2926 
NewStackFrameInfo(Handle<FrameArray> frame_array,int index)2927 Handle<StackFrameInfo> Factory::NewStackFrameInfo(
2928     Handle<FrameArray> frame_array, int index) {
2929   FrameArrayIterator it(isolate(), frame_array, index);
2930   DCHECK(it.HasFrame());
2931 
2932   const bool is_wasm = frame_array->IsAnyWasmFrame(index);
2933   StackFrameBase* frame = it.Frame();
2934 
2935   int line = frame->GetLineNumber();
2936   int column = frame->GetColumnNumber();
2937   int wasm_function_index = frame->GetWasmFunctionIndex();
2938 
2939   const int script_id = frame->GetScriptId();
2940 
2941   Handle<Object> script_name = frame->GetFileName();
2942   Handle<Object> script_or_url = frame->GetScriptNameOrSourceUrl();
2943 
2944   // TODO(szuend): Adjust this, once it is decided what name to use in both
2945   //               "simple" and "detailed" stack traces. This code is for
2946   //               backwards compatibility to fullfill test expectations.
2947   Handle<PrimitiveHeapObject> function_name = frame->GetFunctionName();
2948   bool is_user_java_script = false;
2949   if (!is_wasm) {
2950     Handle<Object> function = frame->GetFunction();
2951     if (function->IsJSFunction()) {
2952       Handle<JSFunction> fun = Handle<JSFunction>::cast(function);
2953 
2954       is_user_java_script = fun->shared().IsUserJavaScript();
2955     }
2956   }
2957 
2958   Handle<PrimitiveHeapObject> method_name = undefined_value();
2959   Handle<PrimitiveHeapObject> type_name = undefined_value();
2960   Handle<PrimitiveHeapObject> eval_origin = frame->GetEvalOrigin();
2961   Handle<PrimitiveHeapObject> wasm_module_name = frame->GetWasmModuleName();
2962   Handle<HeapObject> wasm_instance = frame->GetWasmInstance();
2963 
2964   // MethodName and TypeName are expensive to look up, so they are only
2965   // included when they are strictly needed by the stack trace
2966   // serialization code.
2967   // Note: The {is_method_call} predicate needs to be kept in sync with
2968   //       the corresponding predicate in the stack trace serialization code
2969   //       in stack-frame-info.cc.
2970   const bool is_toplevel = frame->IsToplevel();
2971   const bool is_constructor = frame->IsConstructor();
2972   const bool is_method_call = !(is_toplevel || is_constructor);
2973   if (is_method_call) {
2974     method_name = frame->GetMethodName();
2975     type_name = frame->GetTypeName();
2976   }
2977 
2978   Handle<StackFrameInfo> info = Handle<StackFrameInfo>::cast(
2979       NewStruct(STACK_FRAME_INFO_TYPE, AllocationType::kYoung));
2980 
2981   DisallowHeapAllocation no_gc;
2982 
2983   info->set_flag(0);
2984   info->set_is_wasm(is_wasm);
2985   info->set_is_asmjs_wasm(frame_array->IsAsmJsWasmFrame(index));
2986   info->set_is_user_java_script(is_user_java_script);
2987   info->set_line_number(line);
2988   info->set_column_number(column);
2989   info->set_wasm_function_index(wasm_function_index);
2990   info->set_script_id(script_id);
2991 
2992   info->set_script_name(*script_name);
2993   info->set_script_name_or_source_url(*script_or_url);
2994   info->set_function_name(*function_name);
2995   info->set_method_name(*method_name);
2996   info->set_type_name(*type_name);
2997   info->set_eval_origin(*eval_origin);
2998   info->set_wasm_module_name(*wasm_module_name);
2999   info->set_wasm_instance(*wasm_instance);
3000 
3001   info->set_is_eval(frame->IsEval());
3002   info->set_is_constructor(is_constructor);
3003   info->set_is_toplevel(is_toplevel);
3004   info->set_is_async(frame->IsAsync());
3005   info->set_is_promise_all(frame->IsPromiseAll());
3006   info->set_is_promise_any(frame->IsPromiseAny());
3007   info->set_promise_combinator_index(frame->GetPromiseIndex());
3008 
3009   return info;
3010 }
3011 
NewArgumentsObject(Handle<JSFunction> callee,int length)3012 Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
3013                                              int length) {
3014   bool strict_mode_callee = is_strict(callee->shared().language_mode()) ||
3015                             !callee->shared().has_simple_parameters();
3016   Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
3017                                        : isolate()->sloppy_arguments_map();
3018   AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
3019                                      false);
3020   DCHECK(!isolate()->has_pending_exception());
3021   Handle<JSObject> result = NewJSObjectFromMap(map);
3022   Handle<Smi> value(Smi::FromInt(length), isolate());
3023   Object::SetProperty(isolate(), result, length_string(), value,
3024                       StoreOrigin::kMaybeKeyed,
3025                       Just(ShouldThrow::kThrowOnError))
3026       .Assert();
3027   if (!strict_mode_callee) {
3028     Object::SetProperty(isolate(), result, callee_string(), callee,
3029                         StoreOrigin::kMaybeKeyed,
3030                         Just(ShouldThrow::kThrowOnError))
3031         .Assert();
3032   }
3033   return result;
3034 }
3035 
ObjectLiteralMapFromCache(Handle<NativeContext> context,int number_of_properties)3036 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<NativeContext> context,
3037                                                int number_of_properties) {
3038   if (number_of_properties == 0) {
3039     // Reuse the initial map of the Object function if the literal has no
3040     // predeclared properties.
3041     return handle(context->object_function().initial_map(), isolate());
3042   }
3043 
3044   // Use initial slow object proto map for too many properties.
3045   const int kMapCacheSize = 128;
3046   if (number_of_properties > kMapCacheSize) {
3047     return handle(context->slow_object_with_object_prototype_map(), isolate());
3048   }
3049 
3050   int cache_index = number_of_properties - 1;
3051   Handle<Object> maybe_cache(context->map_cache(), isolate());
3052   if (maybe_cache->IsUndefined(isolate())) {
3053     // Allocate the new map cache for the native context.
3054     maybe_cache = NewWeakFixedArray(kMapCacheSize, AllocationType::kOld);
3055     context->set_map_cache(*maybe_cache);
3056   } else {
3057     // Check to see whether there is a matching element in the cache.
3058     Handle<WeakFixedArray> cache = Handle<WeakFixedArray>::cast(maybe_cache);
3059     MaybeObject result = cache->Get(cache_index);
3060     HeapObject heap_object;
3061     if (result->GetHeapObjectIfWeak(&heap_object)) {
3062       Map map = Map::cast(heap_object);
3063       DCHECK(!map.is_dictionary_map());
3064       return handle(map, isolate());
3065     }
3066   }
3067 
3068   // Create a new map and add it to the cache.
3069   Handle<WeakFixedArray> cache = Handle<WeakFixedArray>::cast(maybe_cache);
3070   Handle<Map> map = Map::Create(isolate(), number_of_properties);
3071   DCHECK(!map->is_dictionary_map());
3072   cache->Set(cache_index, HeapObjectReference::Weak(*map));
3073   return map;
3074 }
3075 
NewLoadHandler(int data_count,AllocationType allocation)3076 Handle<LoadHandler> Factory::NewLoadHandler(int data_count,
3077                                             AllocationType allocation) {
3078   Handle<Map> map;
3079   switch (data_count) {
3080     case 1:
3081       map = load_handler1_map();
3082       break;
3083     case 2:
3084       map = load_handler2_map();
3085       break;
3086     case 3:
3087       map = load_handler3_map();
3088       break;
3089     default:
3090       UNREACHABLE();
3091   }
3092   return handle(LoadHandler::cast(New(map, allocation)), isolate());
3093 }
3094 
NewStoreHandler(int data_count)3095 Handle<StoreHandler> Factory::NewStoreHandler(int data_count) {
3096   Handle<Map> map;
3097   switch (data_count) {
3098     case 0:
3099       map = store_handler0_map();
3100       break;
3101     case 1:
3102       map = store_handler1_map();
3103       break;
3104     case 2:
3105       map = store_handler2_map();
3106       break;
3107     case 3:
3108       map = store_handler3_map();
3109       break;
3110     default:
3111       UNREACHABLE();
3112   }
3113   return handle(StoreHandler::cast(New(map, AllocationType::kOld)), isolate());
3114 }
3115 
SetRegExpAtomData(Handle<JSRegExp> regexp,Handle<String> source,JSRegExp::Flags flags,Handle<Object> data)3116 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp, Handle<String> source,
3117                                 JSRegExp::Flags flags, Handle<Object> data) {
3118   Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
3119 
3120   store->set(JSRegExp::kTagIndex, Smi::FromInt(JSRegExp::ATOM));
3121   store->set(JSRegExp::kSourceIndex, *source);
3122   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
3123   store->set(JSRegExp::kAtomPatternIndex, *data);
3124   regexp->set_data(*store);
3125 }
3126 
SetRegExpIrregexpData(Handle<JSRegExp> regexp,Handle<String> source,JSRegExp::Flags flags,int capture_count,uint32_t backtrack_limit)3127 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
3128                                     Handle<String> source,
3129                                     JSRegExp::Flags flags, int capture_count,
3130                                     uint32_t backtrack_limit) {
3131   DCHECK(Smi::IsValid(backtrack_limit));
3132   Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
3133   Smi uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
3134   Smi ticks_until_tier_up = FLAG_regexp_tier_up
3135                                 ? Smi::FromInt(FLAG_regexp_tier_up_ticks)
3136                                 : uninitialized;
3137   store->set(JSRegExp::kTagIndex, Smi::FromInt(JSRegExp::IRREGEXP));
3138   store->set(JSRegExp::kSourceIndex, *source);
3139   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
3140   store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
3141   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
3142   store->set(JSRegExp::kIrregexpLatin1BytecodeIndex, uninitialized);
3143   store->set(JSRegExp::kIrregexpUC16BytecodeIndex, uninitialized);
3144   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::zero());
3145   store->set(JSRegExp::kIrregexpCaptureCountIndex, Smi::FromInt(capture_count));
3146   store->set(JSRegExp::kIrregexpCaptureNameMapIndex, uninitialized);
3147   store->set(JSRegExp::kIrregexpTicksUntilTierUpIndex, ticks_until_tier_up);
3148   store->set(JSRegExp::kIrregexpBacktrackLimit, Smi::FromInt(backtrack_limit));
3149   regexp->set_data(*store);
3150 }
3151 
SetRegExpExperimentalData(Handle<JSRegExp> regexp,Handle<String> source,JSRegExp::Flags flags,int capture_count)3152 void Factory::SetRegExpExperimentalData(Handle<JSRegExp> regexp,
3153                                         Handle<String> source,
3154                                         JSRegExp::Flags flags,
3155                                         int capture_count) {
3156   Handle<FixedArray> store = NewFixedArray(JSRegExp::kExperimentalDataSize);
3157   Smi uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
3158 
3159   store->set(JSRegExp::kTagIndex, Smi::FromInt(JSRegExp::EXPERIMENTAL));
3160   store->set(JSRegExp::kSourceIndex, *source);
3161   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
3162   store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
3163   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
3164   store->set(JSRegExp::kIrregexpLatin1BytecodeIndex, uninitialized);
3165   store->set(JSRegExp::kIrregexpUC16BytecodeIndex, uninitialized);
3166   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, uninitialized);
3167   store->set(JSRegExp::kIrregexpCaptureCountIndex, Smi::FromInt(capture_count));
3168   store->set(JSRegExp::kIrregexpCaptureNameMapIndex, uninitialized);
3169   store->set(JSRegExp::kIrregexpTicksUntilTierUpIndex, uninitialized);
3170   store->set(JSRegExp::kIrregexpBacktrackLimit, uninitialized);
3171   regexp->set_data(*store);
3172 }
3173 
NewRegExpMatchInfo()3174 Handle<RegExpMatchInfo> Factory::NewRegExpMatchInfo() {
3175   // Initially, the last match info consists of all fixed fields plus space for
3176   // the match itself (i.e., 2 capture indices).
3177   static const int kInitialSize = RegExpMatchInfo::kFirstCaptureIndex +
3178                                   RegExpMatchInfo::kInitialCaptureIndices;
3179 
3180   Handle<FixedArray> elems = NewFixedArray(kInitialSize);
3181   Handle<RegExpMatchInfo> result = Handle<RegExpMatchInfo>::cast(elems);
3182 
3183   result->SetNumberOfCaptureRegisters(RegExpMatchInfo::kInitialCaptureIndices);
3184   result->SetLastSubject(*empty_string());
3185   result->SetLastInput(*undefined_value());
3186   result->SetCapture(0, 0);
3187   result->SetCapture(1, 0);
3188 
3189   return result;
3190 }
3191 
GlobalConstantFor(Handle<Name> name)3192 Handle<Object> Factory::GlobalConstantFor(Handle<Name> name) {
3193   if (Name::Equals(isolate(), name, undefined_string())) {
3194     return undefined_value();
3195   }
3196   if (Name::Equals(isolate(), name, NaN_string())) return nan_value();
3197   if (Name::Equals(isolate(), name, Infinity_string())) return infinity_value();
3198   return Handle<Object>::null();
3199 }
3200 
ToPrimitiveHintString(ToPrimitiveHint hint)3201 Handle<String> Factory::ToPrimitiveHintString(ToPrimitiveHint hint) {
3202   switch (hint) {
3203     case ToPrimitiveHint::kDefault:
3204       return default_string();
3205     case ToPrimitiveHint::kNumber:
3206       return number_string();
3207     case ToPrimitiveHint::kString:
3208       return string_string();
3209   }
3210   UNREACHABLE();
3211 }
3212 
CreateSloppyFunctionMap(FunctionMode function_mode,MaybeHandle<JSFunction> maybe_empty_function)3213 Handle<Map> Factory::CreateSloppyFunctionMap(
3214     FunctionMode function_mode, MaybeHandle<JSFunction> maybe_empty_function) {
3215   bool has_prototype = IsFunctionModeWithPrototype(function_mode);
3216   int header_size = has_prototype ? JSFunction::kSizeWithPrototype
3217                                   : JSFunction::kSizeWithoutPrototype;
3218   int descriptors_count = has_prototype ? 5 : 4;
3219   int inobject_properties_count = 0;
3220   if (IsFunctionModeWithName(function_mode)) ++inobject_properties_count;
3221 
3222   Handle<Map> map = NewMap(
3223       JS_FUNCTION_TYPE, header_size + inobject_properties_count * kTaggedSize,
3224       TERMINAL_FAST_ELEMENTS_KIND, inobject_properties_count);
3225   map->set_has_prototype_slot(has_prototype);
3226   map->set_is_constructor(has_prototype);
3227   map->set_is_callable(true);
3228   Handle<JSFunction> empty_function;
3229   if (maybe_empty_function.ToHandle(&empty_function)) {
3230     Map::SetPrototype(isolate(), map, empty_function);
3231   }
3232 
3233   //
3234   // Setup descriptors array.
3235   //
3236   Map::EnsureDescriptorSlack(isolate(), map, descriptors_count);
3237 
3238   PropertyAttributes ro_attribs =
3239       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
3240   PropertyAttributes rw_attribs =
3241       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
3242   PropertyAttributes roc_attribs =
3243       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
3244 
3245   int field_index = 0;
3246   STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
3247   {  // Add length accessor.
3248     Descriptor d = Descriptor::AccessorConstant(
3249         length_string(), function_length_accessor(), roc_attribs);
3250     map->AppendDescriptor(isolate(), &d);
3251   }
3252 
3253   STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
3254   if (IsFunctionModeWithName(function_mode)) {
3255     // Add name field.
3256     Handle<Name> name = isolate()->factory()->name_string();
3257     Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
3258                                          roc_attribs, Representation::Tagged());
3259     map->AppendDescriptor(isolate(), &d);
3260 
3261   } else {
3262     // Add name accessor.
3263     Descriptor d = Descriptor::AccessorConstant(
3264         name_string(), function_name_accessor(), roc_attribs);
3265     map->AppendDescriptor(isolate(), &d);
3266   }
3267   {  // Add arguments accessor.
3268     Descriptor d = Descriptor::AccessorConstant(
3269         arguments_string(), function_arguments_accessor(), ro_attribs);
3270     map->AppendDescriptor(isolate(), &d);
3271   }
3272   {  // Add caller accessor.
3273     Descriptor d = Descriptor::AccessorConstant(
3274         caller_string(), function_caller_accessor(), ro_attribs);
3275     map->AppendDescriptor(isolate(), &d);
3276   }
3277   if (IsFunctionModeWithPrototype(function_mode)) {
3278     // Add prototype accessor.
3279     PropertyAttributes attribs =
3280         IsFunctionModeWithWritablePrototype(function_mode) ? rw_attribs
3281                                                            : ro_attribs;
3282     Descriptor d = Descriptor::AccessorConstant(
3283         prototype_string(), function_prototype_accessor(), attribs);
3284     map->AppendDescriptor(isolate(), &d);
3285   }
3286   DCHECK_EQ(inobject_properties_count, field_index);
3287   DCHECK_EQ(
3288       0, map->instance_descriptors(kRelaxedLoad).number_of_slack_descriptors());
3289   LOG(isolate(), MapDetails(*map));
3290   return map;
3291 }
3292 
CreateStrictFunctionMap(FunctionMode function_mode,Handle<JSFunction> empty_function)3293 Handle<Map> Factory::CreateStrictFunctionMap(
3294     FunctionMode function_mode, Handle<JSFunction> empty_function) {
3295   bool has_prototype = IsFunctionModeWithPrototype(function_mode);
3296   int header_size = has_prototype ? JSFunction::kSizeWithPrototype
3297                                   : JSFunction::kSizeWithoutPrototype;
3298   int inobject_properties_count = 0;
3299   // length and prototype accessors or just length accessor.
3300   int descriptors_count = IsFunctionModeWithPrototype(function_mode) ? 2 : 1;
3301   if (IsFunctionModeWithName(function_mode)) {
3302     ++inobject_properties_count;  // name property.
3303   } else {
3304     ++descriptors_count;  // name accessor.
3305   }
3306   if (IsFunctionModeWithHomeObject(function_mode)) ++inobject_properties_count;
3307   descriptors_count += inobject_properties_count;
3308 
3309   Handle<Map> map = NewMap(
3310       JS_FUNCTION_TYPE, header_size + inobject_properties_count * kTaggedSize,
3311       TERMINAL_FAST_ELEMENTS_KIND, inobject_properties_count);
3312   map->set_has_prototype_slot(has_prototype);
3313   map->set_is_constructor(has_prototype);
3314   map->set_is_callable(true);
3315   Map::SetPrototype(isolate(), map, empty_function);
3316 
3317   //
3318   // Setup descriptors array.
3319   //
3320   Map::EnsureDescriptorSlack(isolate(), map, descriptors_count);
3321 
3322   PropertyAttributes rw_attribs =
3323       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
3324   PropertyAttributes ro_attribs =
3325       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
3326   PropertyAttributes roc_attribs =
3327       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
3328 
3329   int field_index = 0;
3330   STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
3331   {  // Add length accessor.
3332     Descriptor d = Descriptor::AccessorConstant(
3333         length_string(), function_length_accessor(), roc_attribs);
3334     map->AppendDescriptor(isolate(), &d);
3335   }
3336 
3337   STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
3338   if (IsFunctionModeWithName(function_mode)) {
3339     // Add name field.
3340     Handle<Name> name = isolate()->factory()->name_string();
3341     Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
3342                                          roc_attribs, Representation::Tagged());
3343     map->AppendDescriptor(isolate(), &d);
3344 
3345   } else {
3346     // Add name accessor.
3347     Descriptor d = Descriptor::AccessorConstant(
3348         name_string(), function_name_accessor(), roc_attribs);
3349     map->AppendDescriptor(isolate(), &d);
3350   }
3351 
3352   STATIC_ASSERT(JSFunction::kMaybeHomeObjectDescriptorIndex == 2);
3353   if (IsFunctionModeWithHomeObject(function_mode)) {
3354     // Add home object field.
3355     Handle<Name> name = isolate()->factory()->home_object_symbol();
3356     Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
3357                                          DONT_ENUM, Representation::Tagged());
3358     map->AppendDescriptor(isolate(), &d);
3359   }
3360 
3361   if (IsFunctionModeWithPrototype(function_mode)) {
3362     // Add prototype accessor.
3363     PropertyAttributes attribs =
3364         IsFunctionModeWithWritablePrototype(function_mode) ? rw_attribs
3365                                                            : ro_attribs;
3366     Descriptor d = Descriptor::AccessorConstant(
3367         prototype_string(), function_prototype_accessor(), attribs);
3368     map->AppendDescriptor(isolate(), &d);
3369   }
3370   DCHECK_EQ(inobject_properties_count, field_index);
3371   DCHECK_EQ(
3372       0, map->instance_descriptors(kRelaxedLoad).number_of_slack_descriptors());
3373   LOG(isolate(), MapDetails(*map));
3374   return map;
3375 }
3376 
CreateClassFunctionMap(Handle<JSFunction> empty_function)3377 Handle<Map> Factory::CreateClassFunctionMap(Handle<JSFunction> empty_function) {
3378   Handle<Map> map = NewMap(JS_FUNCTION_TYPE, JSFunction::kSizeWithPrototype);
3379   map->set_has_prototype_slot(true);
3380   map->set_is_constructor(true);
3381   map->set_is_prototype_map(true);
3382   map->set_is_callable(true);
3383   Map::SetPrototype(isolate(), map, empty_function);
3384 
3385   //
3386   // Setup descriptors array.
3387   //
3388   Map::EnsureDescriptorSlack(isolate(), map, 2);
3389 
3390   PropertyAttributes ro_attribs =
3391       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
3392   PropertyAttributes roc_attribs =
3393       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
3394 
3395   STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
3396   {  // Add length accessor.
3397     Descriptor d = Descriptor::AccessorConstant(
3398         length_string(), function_length_accessor(), roc_attribs);
3399     map->AppendDescriptor(isolate(), &d);
3400   }
3401 
3402   {
3403     // Add prototype accessor.
3404     Descriptor d = Descriptor::AccessorConstant(
3405         prototype_string(), function_prototype_accessor(), ro_attribs);
3406     map->AppendDescriptor(isolate(), &d);
3407   }
3408   LOG(isolate(), MapDetails(*map));
3409   return map;
3410 }
3411 
NewJSPromiseWithoutHook()3412 Handle<JSPromise> Factory::NewJSPromiseWithoutHook() {
3413   Handle<JSPromise> promise =
3414       Handle<JSPromise>::cast(NewJSObject(isolate()->promise_function()));
3415   promise->set_reactions_or_result(Smi::zero());
3416   promise->set_flags(0);
3417   ZeroEmbedderFields(promise);
3418   DCHECK_EQ(promise->GetEmbedderFieldCount(), v8::Promise::kEmbedderFieldCount);
3419   return promise;
3420 }
3421 
NewJSPromise()3422 Handle<JSPromise> Factory::NewJSPromise() {
3423   Handle<JSPromise> promise = NewJSPromiseWithoutHook();
3424   isolate()->RunPromiseHook(PromiseHookType::kInit, promise, undefined_value());
3425   return promise;
3426 }
3427 
NewCallHandlerInfo(bool has_no_side_effect)3428 Handle<CallHandlerInfo> Factory::NewCallHandlerInfo(bool has_no_side_effect) {
3429   Handle<Map> map = has_no_side_effect
3430                         ? side_effect_free_call_handler_info_map()
3431                         : side_effect_call_handler_info_map();
3432   Handle<CallHandlerInfo> info(
3433       CallHandlerInfo::cast(New(map, AllocationType::kOld)), isolate());
3434   Object undefined_value = ReadOnlyRoots(isolate()).undefined_value();
3435   info->set_callback(undefined_value);
3436   info->set_js_callback(undefined_value);
3437   info->set_data(undefined_value);
3438   return info;
3439 }
3440 
CanAllocateInReadOnlySpace()3441 bool Factory::CanAllocateInReadOnlySpace() {
3442   return isolate()->heap()->CanAllocateInReadOnlySpace();
3443 }
3444 
EmptyStringRootIsInitialized()3445 bool Factory::EmptyStringRootIsInitialized() {
3446   return isolate()->roots_table()[RootIndex::kempty_string] != kNullAddress;
3447 }
3448 
3449 // static
ForWasm(Handle<String> name,Handle<WasmExportedFunctionData> exported_function_data,Handle<Map> map)3450 NewFunctionArgs NewFunctionArgs::ForWasm(
3451     Handle<String> name,
3452     Handle<WasmExportedFunctionData> exported_function_data, Handle<Map> map) {
3453   DCHECK(name->IsFlat());
3454 
3455   NewFunctionArgs args;
3456   args.name_ = name;
3457   args.maybe_map_ = map;
3458   args.maybe_wasm_function_data_ = exported_function_data;
3459   args.language_mode_ = LanguageMode::kSloppy;
3460   args.prototype_mutability_ = MUTABLE;
3461 
3462   return args;
3463 }
3464 
3465 // static
ForWasm(Handle<String> name,Handle<WasmJSFunctionData> js_function_data,Handle<Map> map)3466 NewFunctionArgs NewFunctionArgs::ForWasm(
3467     Handle<String> name, Handle<WasmJSFunctionData> js_function_data,
3468     Handle<Map> map) {
3469   DCHECK(name->IsFlat());
3470 
3471   NewFunctionArgs args;
3472   args.name_ = name;
3473   args.maybe_map_ = map;
3474   args.maybe_wasm_function_data_ = js_function_data;
3475   args.language_mode_ = LanguageMode::kSloppy;
3476   args.prototype_mutability_ = MUTABLE;
3477 
3478   return args;
3479 }
3480 
3481 // static
ForBuiltin(Handle<String> name,Handle<Map> map,int builtin_id)3482 NewFunctionArgs NewFunctionArgs::ForBuiltin(Handle<String> name,
3483                                             Handle<Map> map, int builtin_id) {
3484   DCHECK(Builtins::IsBuiltinId(builtin_id));
3485   DCHECK(name->IsFlat());
3486 
3487   NewFunctionArgs args;
3488   args.name_ = name;
3489   args.maybe_map_ = map;
3490   args.maybe_builtin_id_ = builtin_id;
3491   args.language_mode_ = LanguageMode::kStrict;
3492   args.prototype_mutability_ = MUTABLE;
3493 
3494   args.SetShouldSetLanguageMode();
3495 
3496   return args;
3497 }
3498 
3499 // static
ForFunctionWithoutCode(Handle<String> name,Handle<Map> map,LanguageMode language_mode)3500 NewFunctionArgs NewFunctionArgs::ForFunctionWithoutCode(
3501     Handle<String> name, Handle<Map> map, LanguageMode language_mode) {
3502   DCHECK(name->IsFlat());
3503 
3504   NewFunctionArgs args;
3505   args.name_ = name;
3506   args.maybe_map_ = map;
3507   args.maybe_builtin_id_ = Builtins::kIllegal;
3508   args.language_mode_ = language_mode;
3509   args.prototype_mutability_ = MUTABLE;
3510 
3511   args.SetShouldSetLanguageMode();
3512 
3513   return args;
3514 }
3515 
3516 // static
ForBuiltinWithPrototype(Handle<String> name,Handle<HeapObject> prototype,InstanceType type,int instance_size,int inobject_properties,int builtin_id,MutableMode prototype_mutability)3517 NewFunctionArgs NewFunctionArgs::ForBuiltinWithPrototype(
3518     Handle<String> name, Handle<HeapObject> prototype, InstanceType type,
3519     int instance_size, int inobject_properties, int builtin_id,
3520     MutableMode prototype_mutability) {
3521   DCHECK(Builtins::IsBuiltinId(builtin_id));
3522   DCHECK(name->IsFlat());
3523 
3524   NewFunctionArgs args;
3525   args.name_ = name;
3526   args.type_ = type;
3527   args.instance_size_ = instance_size;
3528   args.inobject_properties_ = inobject_properties;
3529   args.maybe_prototype_ = prototype;
3530   args.maybe_builtin_id_ = builtin_id;
3531   args.language_mode_ = LanguageMode::kStrict;
3532   args.prototype_mutability_ = prototype_mutability;
3533 
3534   args.SetShouldCreateAndSetInitialMap();
3535   args.SetShouldSetPrototype();
3536   args.SetShouldSetLanguageMode();
3537 
3538   return args;
3539 }
3540 
3541 // static
ForBuiltinWithoutPrototype(Handle<String> name,int builtin_id,LanguageMode language_mode)3542 NewFunctionArgs NewFunctionArgs::ForBuiltinWithoutPrototype(
3543     Handle<String> name, int builtin_id, LanguageMode language_mode) {
3544   DCHECK(Builtins::IsBuiltinId(builtin_id));
3545   DCHECK(name->IsFlat());
3546 
3547   NewFunctionArgs args;
3548   args.name_ = name;
3549   args.maybe_builtin_id_ = builtin_id;
3550   args.language_mode_ = language_mode;
3551   args.prototype_mutability_ = MUTABLE;
3552 
3553   args.SetShouldSetLanguageMode();
3554 
3555   return args;
3556 }
3557 
SetShouldCreateAndSetInitialMap()3558 void NewFunctionArgs::SetShouldCreateAndSetInitialMap() {
3559   // Needed to create the initial map.
3560   maybe_prototype_.Assert();
3561   DCHECK_NE(kUninitialized, instance_size_);
3562   DCHECK_NE(kUninitialized, inobject_properties_);
3563 
3564   should_create_and_set_initial_map_ = true;
3565 }
3566 
SetShouldSetPrototype()3567 void NewFunctionArgs::SetShouldSetPrototype() {
3568   maybe_prototype_.Assert();
3569   should_set_prototype_ = true;
3570 }
3571 
SetShouldSetLanguageMode()3572 void NewFunctionArgs::SetShouldSetLanguageMode() {
3573   DCHECK(language_mode_ == LanguageMode::kStrict ||
3574          language_mode_ == LanguageMode::kSloppy);
3575   should_set_language_mode_ = true;
3576 }
3577 
GetMap(Isolate * isolate) const3578 Handle<Map> NewFunctionArgs::GetMap(Isolate* isolate) const {
3579   if (!maybe_map_.is_null()) {
3580     return maybe_map_.ToHandleChecked();
3581   } else if (maybe_prototype_.is_null()) {
3582     return is_strict(language_mode_)
3583                ? isolate->strict_function_without_prototype_map()
3584                : isolate->sloppy_function_without_prototype_map();
3585   } else {
3586     DCHECK(!maybe_prototype_.is_null());
3587     switch (prototype_mutability_) {
3588       case MUTABLE:
3589         return is_strict(language_mode_) ? isolate->strict_function_map()
3590                                          : isolate->sloppy_function_map();
3591       case IMMUTABLE:
3592         return is_strict(language_mode_)
3593                    ? isolate->strict_function_with_readonly_prototype_map()
3594                    : isolate->sloppy_function_with_readonly_prototype_map();
3595     }
3596   }
3597   UNREACHABLE();
3598 }
3599 
NewFunctionForTest(Handle<String> name)3600 Handle<JSFunction> Factory::NewFunctionForTest(Handle<String> name) {
3601   NewFunctionArgs args = NewFunctionArgs::ForFunctionWithoutCode(
3602       name, isolate()->sloppy_function_map(), LanguageMode::kSloppy);
3603   Handle<JSFunction> result = NewFunction(args);
3604   DCHECK(is_sloppy(result->shared().language_mode()));
3605   return result;
3606 }
3607 
NewFunction(const NewFunctionArgs & args)3608 Handle<JSFunction> Factory::NewFunction(const NewFunctionArgs& args) {
3609   DCHECK(!args.name_.is_null());
3610 
3611   // Create the SharedFunctionInfo.
3612   Handle<NativeContext> context(isolate()->native_context());
3613   Handle<Map> map = args.GetMap(isolate());
3614   Handle<SharedFunctionInfo> info =
3615       NewSharedFunctionInfo(args.name_, args.maybe_wasm_function_data_,
3616                             args.maybe_builtin_id_, kNormalFunction);
3617 
3618   // Proper language mode in shared function info will be set later.
3619   DCHECK(is_sloppy(info->language_mode()));
3620   DCHECK(!map->IsUndefined(isolate()));
3621 
3622   if (args.should_set_language_mode_) {
3623     info->set_language_mode(args.language_mode_);
3624   }
3625 
3626 #ifdef DEBUG
3627   if (isolate()->bootstrapper()->IsActive()) {
3628     Handle<Code> code;
3629     DCHECK(
3630         // During bootstrapping some of these maps could be not created yet.
3631         (*map == context->get(Context::STRICT_FUNCTION_MAP_INDEX)) ||
3632         (*map ==
3633          context->get(Context::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX)) ||
3634         (*map ==
3635          context->get(
3636              Context::STRICT_FUNCTION_WITH_READONLY_PROTOTYPE_MAP_INDEX)) ||
3637         // Check if it's a creation of an empty or Proxy function during
3638         // bootstrapping.
3639         (args.maybe_builtin_id_ == Builtins::kEmptyFunction ||
3640          args.maybe_builtin_id_ == Builtins::kProxyConstructor));
3641   }
3642 #endif
3643 
3644   Handle<JSFunction> result =
3645       JSFunctionBuilder{isolate(), info, context}.set_map(map).Build();
3646 
3647   // Both of these write to `prototype_or_initial_map`.
3648   // TODO(jgruber): Fix callsites and enable the DCHECK.
3649   // DCHECK(!args.should_set_prototype_ ||
3650   //        !args.should_create_and_set_initial_map_);
3651   if (args.should_set_prototype_) {
3652     result->set_prototype_or_initial_map(
3653         *args.maybe_prototype_.ToHandleChecked());
3654   }
3655 
3656   if (args.should_create_and_set_initial_map_) {
3657     ElementsKind elements_kind;
3658     switch (args.type_) {
3659       case JS_ARRAY_TYPE:
3660         elements_kind = PACKED_SMI_ELEMENTS;
3661         break;
3662       case JS_ARGUMENTS_OBJECT_TYPE:
3663         elements_kind = PACKED_ELEMENTS;
3664         break;
3665       default:
3666         elements_kind = TERMINAL_FAST_ELEMENTS_KIND;
3667         break;
3668     }
3669     Handle<Map> initial_map = NewMap(args.type_, args.instance_size_,
3670                                      elements_kind, args.inobject_properties_);
3671     result->shared().set_expected_nof_properties(args.inobject_properties_);
3672     // TODO(littledan): Why do we have this is_generator test when
3673     // NewFunctionPrototype already handles finding an appropriately
3674     // shared prototype?
3675     Handle<HeapObject> prototype = args.maybe_prototype_.ToHandleChecked();
3676     if (!IsResumableFunction(result->shared().kind())) {
3677       if (prototype->IsTheHole(isolate())) {
3678         prototype = NewFunctionPrototype(result);
3679       }
3680     }
3681     JSFunction::SetInitialMap(result, initial_map, prototype);
3682   }
3683 
3684   return result;
3685 }
3686 
NewFunction(Handle<Map> map,Handle<SharedFunctionInfo> info,Handle<Context> context,AllocationType allocation)3687 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
3688                                         Handle<SharedFunctionInfo> info,
3689                                         Handle<Context> context,
3690                                         AllocationType allocation) {
3691   // TODO(jgruber): Remove this function.
3692   return JSFunctionBuilder{isolate(), info, context}
3693       .set_map(map)
3694       .set_allocation_type(allocation)
3695       .Build();
3696 }
3697 
NewFunctionFromSharedFunctionInfo(Handle<SharedFunctionInfo> info,Handle<Context> context,AllocationType allocation)3698 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
3699     Handle<SharedFunctionInfo> info, Handle<Context> context,
3700     AllocationType allocation) {
3701   // TODO(jgruber): Remove this function.
3702   return JSFunctionBuilder{isolate(), info, context}
3703       .set_allocation_type(allocation)
3704       .Build();
3705 }
3706 
NewFunctionFromSharedFunctionInfo(Handle<SharedFunctionInfo> info,Handle<Context> context,Handle<FeedbackCell> feedback_cell,AllocationType allocation)3707 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
3708     Handle<SharedFunctionInfo> info, Handle<Context> context,
3709     Handle<FeedbackCell> feedback_cell, AllocationType allocation) {
3710   // TODO(jgruber): Remove this function.
3711   return JSFunctionBuilder{isolate(), info, context}
3712       .set_feedback_cell(feedback_cell)
3713       .Build();
3714 }
3715 
NewFunctionFromSharedFunctionInfo(Handle<Map> initial_map,Handle<SharedFunctionInfo> info,Handle<Context> context,AllocationType allocation)3716 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
3717     Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
3718     Handle<Context> context, AllocationType allocation) {
3719   // TODO(jgruber): Remove this function.
3720   return JSFunctionBuilder{isolate(), info, context}
3721       .set_map(initial_map)
3722       .set_allocation_type(allocation)
3723       .Build();
3724 }
3725 
JSFunctionBuilder(Isolate * isolate,Handle<SharedFunctionInfo> sfi,Handle<Context> context)3726 Factory::JSFunctionBuilder::JSFunctionBuilder(Isolate* isolate,
3727                                               Handle<SharedFunctionInfo> sfi,
3728                                               Handle<Context> context)
3729     : isolate_(isolate), sfi_(sfi), context_(context) {}
3730 
Build()3731 Handle<JSFunction> Factory::JSFunctionBuilder::Build() {
3732   PrepareMap();
3733   PrepareFeedbackCell();
3734 
3735   // Determine the associated Code object.
3736   Handle<Code> code;
3737   const bool have_cached_code =
3738       sfi_->TryGetCachedCode(isolate_).ToHandle(&code);
3739   if (!have_cached_code) code = handle(sfi_->GetCode(), isolate_);
3740 
3741   Handle<JSFunction> result = BuildRaw(code);
3742 
3743   if (have_cached_code) {
3744     IsCompiledScope is_compiled_scope(sfi_->is_compiled_scope(isolate_));
3745     JSFunction::EnsureFeedbackVector(result, &is_compiled_scope);
3746     if (FLAG_trace_turbo_nci) CompilationCacheCode::TraceHit(sfi_, code);
3747   }
3748 
3749   Compiler::PostInstantiation(result);
3750   return result;
3751 }
3752 
BuildRaw(Handle<Code> code)3753 Handle<JSFunction> Factory::JSFunctionBuilder::BuildRaw(Handle<Code> code) {
3754   Isolate* isolate = isolate_;
3755   Factory* factory = isolate_->factory();
3756 
3757   Handle<Map> map = maybe_map_.ToHandleChecked();
3758   Handle<FeedbackCell> feedback_cell = maybe_feedback_cell_.ToHandleChecked();
3759 
3760   DCHECK_EQ(JS_FUNCTION_TYPE, map->instance_type());
3761 
3762   // Allocation.
3763   Handle<JSFunction> function(
3764       JSFunction::cast(factory->New(map, allocation_type_)), isolate);
3765 
3766   // Header initialization.
3767   function->initialize_properties(isolate);
3768   function->initialize_elements();
3769   function->set_shared(*sfi_);
3770   function->set_context(*context_);
3771   function->set_raw_feedback_cell(*feedback_cell);
3772   function->set_code(*code);
3773   if (map->has_prototype_slot()) {
3774     function->set_prototype_or_initial_map(
3775         ReadOnlyRoots(isolate).the_hole_value());
3776   }
3777 
3778   // Potentially body initialization.
3779   factory->InitializeJSObjectBody(
3780       function, map, JSFunction::GetHeaderSize(map->has_prototype_slot()));
3781 
3782   return function;
3783 }
3784 
PrepareMap()3785 void Factory::JSFunctionBuilder::PrepareMap() {
3786   if (maybe_map_.is_null()) {
3787     // No specific map requested, use the default.
3788     maybe_map_ = handle(
3789         Map::cast(context_->native_context().get(sfi_->function_map_index())),
3790         isolate_);
3791   }
3792 }
3793 
PrepareFeedbackCell()3794 void Factory::JSFunctionBuilder::PrepareFeedbackCell() {
3795   Handle<FeedbackCell> feedback_cell;
3796   if (maybe_feedback_cell_.ToHandle(&feedback_cell)) {
3797     // Track the newly-created closure, and check that the optimized code in
3798     // the feedback cell wasn't marked for deoptimization while not pointed to
3799     // by any live JSFunction.
3800     feedback_cell->IncrementClosureCount(isolate_);
3801     if (feedback_cell->value().IsFeedbackVector()) {
3802       FeedbackVector::cast(feedback_cell->value())
3803           .EvictOptimizedCodeMarkedForDeoptimization(
3804               *sfi_, "new function from shared function info");
3805     }
3806   } else {
3807     // Fall back to the many_closures_cell.
3808     maybe_feedback_cell_ = isolate_->factory()->many_closures_cell();
3809   }
3810 }
3811 
3812 }  // namespace internal
3813 }  // namespace v8
3814