forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfactory.cc
More file actions
4454 lines (4040 loc) · 180 KB
/
factory.cc
File metadata and controls
4454 lines (4040 loc) · 180 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/heap/factory.h"
#include <algorithm> // For copy
#include <memory> // For shared_ptr<>
#include <string>
#include <utility> // For move
#include "src/ast/ast-source-ranges.h"
#include "src/base/bits.h"
#include "src/builtins/accessors.h"
#include "src/builtins/constants-table-builder.h"
#include "src/codegen/compilation-cache.h"
#include "src/codegen/compiler.h"
#include "src/common/assert-scope.h"
#include "src/common/globals.h"
#include "src/diagnostics/basic-block-profiler.h"
#include "src/execution/isolate-inl.h"
#include "src/execution/protectors-inl.h"
#include "src/flags/flags.h"
#include "src/heap/heap-allocator-inl.h"
#include "src/heap/heap-inl.h"
#include "src/heap/incremental-marking.h"
#include "src/heap/mark-compact-inl.h"
#include "src/heap/memory-chunk-metadata.h"
#include "src/heap/mutable-page.h"
#include "src/heap/read-only-heap.h"
#include "src/ic/handler-configuration-inl.h"
#include "src/init/bootstrapper.h"
#include "src/interpreter/interpreter.h"
#include "src/logging/counters.h"
#include "src/logging/log.h"
#include "src/numbers/conversions.h"
#include "src/numbers/hash-seed-inl.h"
#include "src/objects/allocation-site-inl.h"
#include "src/objects/allocation-site-scopes.h"
#include "src/objects/api-callbacks.h"
#include "src/objects/arguments-inl.h"
#include "src/objects/bigint.h"
#include "src/objects/call-site-info-inl.h"
#include "src/objects/cell-inl.h"
#include "src/objects/debug-objects-inl.h"
#include "src/objects/embedder-data-array-inl.h"
#include "src/objects/feedback-cell-inl.h"
#include "src/objects/fixed-array-inl.h"
#include "src/objects/foreign-inl.h"
#include "src/objects/instance-type-inl.h"
#include "src/objects/instance-type.h"
#include "src/objects/js-array-buffer-inl.h"
#include "src/objects/js-array-buffer.h"
#include "src/objects/js-array-inl.h"
#include "src/objects/js-atomics-synchronization-inl.h"
#include "src/objects/js-collection-inl.h"
#include "src/objects/js-generator-inl.h"
#include "src/objects/js-objects.h"
#include "src/objects/js-regexp-inl.h"
#include "src/objects/js-shared-array-inl.h"
#include "src/objects/js-struct-inl.h"
#include "src/objects/js-weak-refs-inl.h"
#include "src/objects/literal-objects-inl.h"
#include "src/objects/megadom-handler-inl.h"
#include "src/objects/microtask-inl.h"
#include "src/objects/module-inl.h"
#include "src/objects/objects.h"
#include "src/objects/promise-inl.h"
#include "src/objects/property-descriptor-object-inl.h"
#include "src/objects/scope-info.h"
#include "src/objects/string-set-inl.h"
#include "src/objects/struct-inl.h"
#include "src/objects/synthetic-module-inl.h"
#include "src/objects/template-objects-inl.h"
#include "src/objects/templates.h"
#include "src/objects/transitions-inl.h"
#include "src/roots/roots.h"
#include "src/strings/unicode-inl.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/module-decoder-impl.h"
#include "src/wasm/module-instantiate.h"
#include "src/wasm/wasm-opcodes-inl.h"
#include "src/wasm/wasm-result.h"
#include "src/wasm/wasm-value.h"
#endif
#include "src/heap/local-factory-inl.h"
#include "src/heap/local-heap-inl.h"
namespace v8 {
namespace internal {
Factory::CodeBuilder::CodeBuilder(Isolate* isolate, const CodeDesc& desc,
CodeKind kind)
: isolate_(isolate),
local_isolate_(isolate_->main_thread_local_isolate()),
code_desc_(desc),
kind_(kind) {}
Factory::CodeBuilder::CodeBuilder(LocalIsolate* local_isolate,
const CodeDesc& desc, CodeKind kind)
: isolate_(local_isolate->GetMainThreadIsolateUnsafe()),
local_isolate_(local_isolate),
code_desc_(desc),
kind_(kind) {}
Handle<ByteArray> Factory::CodeBuilder::NewByteArray(
int length, AllocationType allocation) {
return local_isolate_->factory()->NewByteArray(length, allocation);
}
Handle<Code> Factory::CodeBuilder::NewCode(const NewCodeOptions& options) {
return local_isolate_->factory()->NewCode(options);
}
MaybeHandle<Code> Factory::CodeBuilder::BuildInternal(
bool retry_allocation_or_fail) {
Handle<ByteArray> reloc_info =
NewByteArray(code_desc_.reloc_size, AllocationType::kOld);
CodePageHeaderModificationScope memory_write_scope(
"Write barriers need to access the IStreams' page headers.");
// Basic block profiling data for builtins is stored in the JS heap rather
// than in separately-allocated C++ objects. Allocate that data now if
// appropriate.
Handle<OnHeapBasicBlockProfilerData> on_heap_profiler_data;
if (V8_UNLIKELY(profiler_data_ && isolate_->IsGeneratingEmbeddedBuiltins())) {
on_heap_profiler_data = profiler_data_->CopyToJSHeap(isolate_);
// Add the on-heap data to a global list, which keeps it alive and allows
// iteration.
Handle<ArrayList> list(isolate_->heap()->basic_block_profiling_data(),
isolate_);
Handle<ArrayList> new_list = ArrayList::Add(
isolate_, list, on_heap_profiler_data, AllocationType::kOld);
isolate_->heap()->SetBasicBlockProfilingData(new_list);
}
Tagged<HeapObject> istream_allocation =
AllocateUninitializedInstructionStream(retry_allocation_or_fail);
if (istream_allocation.is_null()) {
return {};
}
Handle<InstructionStream> istream;
{
// The InstructionStream object has not been fully initialized yet. We
// rely on the fact that no allocation will happen from this point on.
DisallowGarbageCollection no_gc;
Tagged<InstructionStream> raw_istream = InstructionStream::Initialize(
istream_allocation,
ReadOnlyRoots(local_isolate_).instruction_stream_map(),
code_desc_.body_size(), code_desc_.constant_pool_offset, *reloc_info);
istream = handle(raw_istream, local_isolate_);
DCHECK(IsAligned(istream->instruction_start(), kCodeAlignment));
DCHECK_IMPLIES(
!V8_ENABLE_THIRD_PARTY_HEAP_BOOL &&
!local_isolate_->heap()->heap()->code_region().is_empty(),
local_isolate_->heap()->heap()->code_region().contains(
istream->address()));
}
Handle<Code> code;
{
static_assert(InstructionStream::kOnHeapBodyIsContiguous);
NewCodeOptions new_code_options = {
kind_,
builtin_,
is_turbofanned_,
stack_slots_,
code_desc_.instruction_size(),
code_desc_.metadata_size(),
inlined_bytecode_size_,
osr_offset_,
code_desc_.handler_table_offset_relative(),
code_desc_.constant_pool_offset_relative(),
code_desc_.code_comments_offset_relative(),
code_desc_.unwinding_info_offset_relative(),
interpreter_data_,
deoptimization_data_,
bytecode_offset_table_,
source_position_table_,
istream,
/*instruction_start=*/kNullAddress,
};
code = NewCode(new_code_options);
DCHECK_EQ(istream->body_size(), code->body_size());
{
DisallowGarbageCollection no_gc;
Tagged<InstructionStream> raw_istream = *istream;
// Allow self references to created code object by patching the handle to
// point to the newly allocated InstructionStream object.
Handle<Object> self_reference;
if (self_reference_.ToHandle(&self_reference)) {
DCHECK_EQ(*self_reference,
ReadOnlyRoots(isolate_).self_reference_marker());
DCHECK_NE(kind_, CodeKind::BASELINE);
if (isolate_->IsGeneratingEmbeddedBuiltins()) {
isolate_->builtins_constants_table_builder()->PatchSelfReference(
self_reference, istream);
}
self_reference.PatchValue(raw_istream);
}
// Likewise, any references to the basic block counters marker need to be
// updated to point to the newly-allocated counters array.
if (V8_UNLIKELY(!on_heap_profiler_data.is_null())) {
isolate_->builtins_constants_table_builder()
->PatchBasicBlockCountersReference(
handle(on_heap_profiler_data->counts(), isolate_));
}
// Migrate generated code.
// The generated code can contain embedded objects (typically from
// handles) in a pointer-to-tagged-value format (i.e. with indirection
// like a handle) that are dereferenced during the copy to point
// directly to the actual heap objects. These pointers can include
// references to the code object itself, through the self_reference
// parameter.
istream->Finalize(*code, *reloc_info, code_desc_, isolate_->heap());
#ifdef VERIFY_HEAP
if (v8_flags.verify_heap) {
HeapObject::VerifyCodePointer(isolate_, raw_istream);
}
#endif
}
}
#ifdef ENABLE_DISASSEMBLER
if (V8_UNLIKELY(profiler_data_ && v8_flags.turbo_profiling_verbose)) {
std::ostringstream os;
code->Disassemble(nullptr, os, isolate_);
if (!on_heap_profiler_data.is_null()) {
Handle<String> disassembly =
local_isolate_->factory()->NewStringFromAsciiChecked(
os.str().c_str(), AllocationType::kOld);
on_heap_profiler_data->set_code(*disassembly);
} else {
profiler_data_->SetCode(os);
}
}
#endif // ENABLE_DISASSEMBLER
return code;
}
Tagged<HeapObject> Factory::CodeBuilder::AllocateUninitializedInstructionStream(
bool retry_allocation_or_fail) {
LocalHeap* heap = local_isolate_->heap();
Tagged<HeapObject> result;
const int object_size = InstructionStream::SizeFor(code_desc_.body_size());
if (retry_allocation_or_fail) {
// Only allowed to do `retry_allocation_or_fail` from the main thread.
// TODO(leszeks): Remove the retrying allocation, always use TryBuild in
// the code builder.
DCHECK(local_isolate_->is_main_thread());
result =
heap->heap()->allocator()->AllocateRawWith<HeapAllocator::kRetryOrFail>(
object_size, AllocationType::kCode, AllocationOrigin::kRuntime);
CHECK(!result.is_null());
return result;
} else {
// Return null if we cannot allocate the code object.
return heap->AllocateRawWith<LocalHeap::kLightRetry>(object_size,
AllocationType::kCode);
}
}
MaybeHandle<Code> Factory::CodeBuilder::TryBuild() {
return BuildInternal(false);
}
Handle<Code> Factory::CodeBuilder::Build() {
return BuildInternal(true).ToHandleChecked();
}
Tagged<HeapObject> Factory::AllocateRaw(int size, AllocationType allocation,
AllocationAlignment alignment) {
return allocator()->AllocateRawWith<HeapAllocator::kRetryOrFail>(
size, allocation, AllocationOrigin::kRuntime, alignment);
}
Tagged<HeapObject> Factory::AllocateRawWithAllocationSite(
DirectHandle<Map> map, AllocationType allocation,
DirectHandle<AllocationSite> allocation_site) {
DCHECK(map->instance_type() != MAP_TYPE);
int size = map->instance_size();
if (!allocation_site.is_null()) {
DCHECK(V8_ALLOCATION_SITE_TRACKING_BOOL);
size += ALIGN_TO_ALLOCATION_ALIGNMENT(AllocationMemento::kSize);
}
Tagged<HeapObject> result =
allocator()->AllocateRawWith<HeapAllocator::kRetryOrFail>(size,
allocation);
WriteBarrierMode write_barrier_mode = allocation == AllocationType::kYoung
? SKIP_WRITE_BARRIER
: UPDATE_WRITE_BARRIER;
result->set_map_after_allocation(*map, write_barrier_mode);
if (!allocation_site.is_null()) {
int aligned_size = ALIGN_TO_ALLOCATION_ALIGNMENT(map->instance_size());
Tagged<AllocationMemento> alloc_memento =
Tagged<AllocationMemento>::unchecked_cast(
Tagged<Object>(result.ptr() + aligned_size));
InitializeAllocationMemento(alloc_memento, *allocation_site);
}
return result;
}
void Factory::InitializeAllocationMemento(
Tagged<AllocationMemento> memento, Tagged<AllocationSite> allocation_site) {
DCHECK(V8_ALLOCATION_SITE_TRACKING_BOOL);
memento->set_map_after_allocation(*allocation_memento_map(),
SKIP_WRITE_BARRIER);
memento->set_allocation_site(allocation_site, SKIP_WRITE_BARRIER);
if (v8_flags.allocation_site_pretenuring) {
allocation_site->IncrementMementoCreateCount();
}
}
Tagged<HeapObject> Factory::New(DirectHandle<Map> map,
AllocationType allocation) {
DCHECK(map->instance_type() != MAP_TYPE);
int size = map->instance_size();
Tagged<HeapObject> result =
allocator()->AllocateRawWith<HeapAllocator::kRetryOrFail>(size,
allocation);
// New space objects are allocated white.
WriteBarrierMode write_barrier_mode = allocation == AllocationType::kYoung
? SKIP_WRITE_BARRIER
: UPDATE_WRITE_BARRIER;
result->set_map_after_allocation(*map, write_barrier_mode);
return result;
}
Handle<HeapObject> Factory::NewFillerObject(int size,
AllocationAlignment alignment,
AllocationType allocation,
AllocationOrigin origin) {
Heap* heap = isolate()->heap();
Tagged<HeapObject> result =
allocator()->AllocateRawWith<HeapAllocator::kRetryOrFail>(
size, allocation, origin, alignment);
heap->CreateFillerObjectAt(result.address(), size);
return Handle<HeapObject>(result, isolate());
}
Handle<PrototypeInfo> Factory::NewPrototypeInfo() {
auto result = NewStructInternal<PrototypeInfo>(PROTOTYPE_INFO_TYPE,
AllocationType::kOld);
DisallowGarbageCollection no_gc;
result->set_prototype_users(Smi::zero());
result->set_registry_slot(MemoryChunk::UNREGISTERED);
result->set_bit_field(0);
result->set_module_namespace(*undefined_value(), SKIP_WRITE_BARRIER);
return handle(result, isolate());
}
Handle<EnumCache> Factory::NewEnumCache(DirectHandle<FixedArray> keys,
DirectHandle<FixedArray> indices,
AllocationType allocation) {
DCHECK(allocation == AllocationType::kOld ||
allocation == AllocationType::kSharedOld);
DCHECK_EQ(allocation == AllocationType::kSharedOld,
InAnySharedSpace(*keys) && InAnySharedSpace(*indices));
auto result = NewStructInternal<EnumCache>(ENUM_CACHE_TYPE, allocation);
DisallowGarbageCollection no_gc;
result->set_keys(*keys);
result->set_indices(*indices);
return handle(result, isolate());
}
Handle<Tuple2> Factory::NewTuple2Uninitialized(AllocationType allocation) {
auto result = NewStructInternal<Tuple2>(TUPLE2_TYPE, allocation);
return handle(result, isolate());
}
Handle<Tuple2> Factory::NewTuple2(DirectHandle<Object> value1,
DirectHandle<Object> value2,
AllocationType allocation) {
auto result = NewStructInternal<Tuple2>(TUPLE2_TYPE, allocation);
DisallowGarbageCollection no_gc;
result->set_value1(*value1);
result->set_value2(*value2);
return handle(result, isolate());
}
Handle<Hole> Factory::NewHole() {
Handle<Hole> hole(Hole::cast(New(hole_map(), AllocationType::kReadOnly)),
isolate());
Hole::Initialize(isolate(), hole, hole_nan_value());
return hole;
}
Handle<PropertyArray> Factory::NewPropertyArray(int length,
AllocationType allocation) {
DCHECK_LE(0, length);
if (length == 0) return empty_property_array();
Tagged<HeapObject> result = AllocateRawFixedArray(length, allocation);
DisallowGarbageCollection no_gc;
result->set_map_after_allocation(*property_array_map(), SKIP_WRITE_BARRIER);
Tagged<PropertyArray> array = Tagged<PropertyArray>::cast(result);
array->initialize_length(length);
MemsetTagged(array->data_start(), read_only_roots().undefined_value(),
length);
return handle(array, isolate());
}
MaybeHandle<FixedArray> Factory::TryNewFixedArray(
int length, AllocationType allocation_type) {
DCHECK_LE(0, length);
if (length == 0) return empty_fixed_array();
int size = FixedArray::SizeFor(length);
Heap* heap = isolate()->heap();
AllocationResult allocation = heap->AllocateRaw(size, allocation_type);
Tagged<HeapObject> result;
if (!allocation.To(&result)) return MaybeHandle<FixedArray>();
if ((size > heap->MaxRegularHeapObjectSize(allocation_type)) &&
v8_flags.use_marking_progress_bar) {
LargePageMetadata::FromHeapObject(result)->ProgressBar().Enable();
}
DisallowGarbageCollection no_gc;
result->set_map_after_allocation(*fixed_array_map(), SKIP_WRITE_BARRIER);
Tagged<FixedArray> array = Tagged<FixedArray>::cast(result);
array->set_length(length);
MemsetTagged(array->RawFieldOfFirstElement(), *undefined_value(), length);
return handle(array, isolate());
}
Handle<FeedbackVector> Factory::NewFeedbackVector(
DirectHandle<SharedFunctionInfo> shared,
DirectHandle<ClosureFeedbackCellArray> closure_feedback_cell_array,
DirectHandle<FeedbackCell> parent_feedback_cell) {
int length = shared->feedback_metadata()->slot_count();
DCHECK_LE(0, length);
int size = FeedbackVector::SizeFor(length);
Tagged<FeedbackVector> vector =
Tagged<FeedbackVector>::cast(AllocateRawWithImmortalMap(
size, AllocationType::kOld, *feedback_vector_map()));
DisallowGarbageCollection no_gc;
vector->set_shared_function_info(*shared);
vector->set_maybe_optimized_code(ClearedValue(isolate()));
vector->set_length(length);
vector->set_invocation_count(0);
vector->set_invocation_count_before_stable(0);
vector->reset_osr_state();
vector->reset_flags();
vector->set_log_next_execution(v8_flags.log_function_events);
vector->set_closure_feedback_cell_array(*closure_feedback_cell_array);
vector->set_parent_feedback_cell(*parent_feedback_cell);
// TODO(leszeks): Initialize based on the feedback metadata.
MemsetTagged(ObjectSlot(vector->slots_start()), *undefined_value(), length);
return handle(vector, isolate());
}
Handle<EmbedderDataArray> Factory::NewEmbedderDataArray(int length) {
DCHECK_LE(0, length);
int size = EmbedderDataArray::SizeFor(length);
Tagged<EmbedderDataArray> array =
Tagged<EmbedderDataArray>::cast(AllocateRawWithImmortalMap(
size, AllocationType::kYoung, *embedder_data_array_map()));
DisallowGarbageCollection no_gc;
array->set_length(length);
if (length > 0) {
for (int i = 0; i < length; i++) {
// TODO(v8): consider initializing embedded data array with Smi::zero().
EmbedderDataSlot(array, i).Initialize(*undefined_value());
}
}
return handle(array, isolate());
}
Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(int length) {
DCHECK_LE(0, length);
Handle<FixedArrayBase> array = NewFixedDoubleArray(length);
if (length > 0) {
Handle<FixedDoubleArray>::cast(array)->FillWithHoles(0, length);
}
return array;
}
template <typename T>
Handle<T> Factory::AllocateSmallOrderedHashTable(DirectHandle<Map> map,
int capacity,
AllocationType allocation) {
// Capacity must be a power of two, since we depend on being able
// to divide and multiple by 2 (kLoadFactor) to derive capacity
// from number of buckets. If we decide to change kLoadFactor
// to something other than 2, capacity should be stored as another
// field of this object.
DCHECK_EQ(T::kLoadFactor, 2);
capacity =
base::bits::RoundUpToPowerOfTwo32(std::max({T::kMinCapacity, capacity}));
capacity = std::min({capacity, T::kMaxCapacity});
DCHECK_LT(0, capacity);
DCHECK_EQ(0, capacity % T::kLoadFactor);
int size = T::SizeFor(capacity);
Tagged<HeapObject> result =
AllocateRawWithImmortalMap(size, allocation, *map);
Handle<T> table(T::cast(result), isolate());
table->Initialize(isolate(), capacity);
return table;
}
Handle<SmallOrderedHashSet> Factory::NewSmallOrderedHashSet(
int capacity, AllocationType allocation) {
return AllocateSmallOrderedHashTable<SmallOrderedHashSet>(
small_ordered_hash_set_map(), capacity, allocation);
}
Handle<SmallOrderedHashMap> Factory::NewSmallOrderedHashMap(
int capacity, AllocationType allocation) {
return AllocateSmallOrderedHashTable<SmallOrderedHashMap>(
small_ordered_hash_map_map(), capacity, allocation);
}
Handle<SmallOrderedNameDictionary> Factory::NewSmallOrderedNameDictionary(
int capacity, AllocationType allocation) {
Handle<SmallOrderedNameDictionary> dict =
AllocateSmallOrderedHashTable<SmallOrderedNameDictionary>(
small_ordered_name_dictionary_map(), capacity, allocation);
dict->SetHash(PropertyArray::kNoHashSentinel);
return dict;
}
Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
return OrderedHashSet::Allocate(isolate(), OrderedHashSet::kInitialCapacity,
AllocationType::kYoung)
.ToHandleChecked();
}
Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kInitialCapacity,
AllocationType::kYoung)
.ToHandleChecked();
}
Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
return NameDictionary::New(isolate(), at_least_space_for);
}
Handle<PropertyDescriptorObject> Factory::NewPropertyDescriptorObject() {
auto object = NewStructInternal<PropertyDescriptorObject>(
PROPERTY_DESCRIPTOR_OBJECT_TYPE, AllocationType::kYoung);
DisallowGarbageCollection no_gc;
object->set_flags(0);
Tagged<Hole> the_hole = read_only_roots().the_hole_value();
object->set_value(the_hole, SKIP_WRITE_BARRIER);
object->set_get(the_hole, SKIP_WRITE_BARRIER);
object->set_set(the_hole, SKIP_WRITE_BARRIER);
return handle(object, isolate());
}
Handle<SwissNameDictionary> Factory::CreateCanonicalEmptySwissNameDictionary() {
// This function is only supposed to be used to create the canonical empty
// version and should not be used afterwards.
DCHECK(!ReadOnlyRoots(isolate()).is_initialized(
RootIndex::kEmptySwissPropertyDictionary));
ReadOnlyRoots roots(isolate());
Handle<ByteArray> empty_meta_table =
NewByteArray(SwissNameDictionary::kMetaTableEnumerationDataStartIndex,
AllocationType::kReadOnly);
Tagged<Map> map = roots.swiss_name_dictionary_map();
int size = SwissNameDictionary::SizeFor(0);
Tagged<HeapObject> obj =
AllocateRawWithImmortalMap(size, AllocationType::kReadOnly, map);
Tagged<SwissNameDictionary> result = Tagged<SwissNameDictionary>::cast(obj);
result->Initialize(isolate(), *empty_meta_table, 0);
return handle(result, isolate());
}
// Internalized strings are created in the old generation (data space).
Handle<String> Factory::InternalizeUtf8String(base::Vector<const char> string) {
base::Vector<const uint8_t> utf8_data =
base::Vector<const uint8_t>::cast(string);
Utf8Decoder decoder(utf8_data);
if (decoder.is_ascii()) return InternalizeString(utf8_data);
if (decoder.is_one_byte()) {
std::unique_ptr<uint8_t[]> buffer(new uint8_t[decoder.utf16_length()]);
decoder.Decode(buffer.get(), utf8_data);
return InternalizeString(
base::Vector<const uint8_t>(buffer.get(), decoder.utf16_length()));
}
std::unique_ptr<uint16_t[]> buffer(new uint16_t[decoder.utf16_length()]);
decoder.Decode(buffer.get(), utf8_data);
return InternalizeString(
base::Vector<const base::uc16>(buffer.get(), decoder.utf16_length()));
}
template <typename SeqString>
Handle<String> Factory::InternalizeString(Handle<SeqString> string, int from,
int length, bool convert_encoding) {
SeqSubStringKey<SeqString> key(isolate(), string, from, length,
convert_encoding);
return InternalizeStringWithKey(&key);
}
template Handle<String> Factory::InternalizeString(
Handle<SeqOneByteString> string, int from, int length,
bool convert_encoding);
template Handle<String> Factory::InternalizeString(
Handle<SeqTwoByteString> string, int from, int length,
bool convert_encoding);
namespace {
void ThrowInvalidEncodedStringBytes(Isolate* isolate, MessageTemplate message) {
#if V8_ENABLE_WEBASSEMBLY
DCHECK(message == MessageTemplate::kWasmTrapStringInvalidWtf8 ||
message == MessageTemplate::kWasmTrapStringInvalidUtf8);
Handle<JSObject> error_obj = isolate->factory()->NewWasmRuntimeError(message);
JSObject::AddProperty(isolate, error_obj,
isolate->factory()->wasm_uncatchable_symbol(),
isolate->factory()->true_value(), NONE);
isolate->Throw(*error_obj);
#else
// The default in JS-land is to use Utf8Variant::kLossyUtf8, which never
// throws an error, so if there is no WebAssembly compiled in we'll never get
// here.
UNREACHABLE();
#endif // V8_ENABLE_WEBASSEMBLY
}
template <typename Decoder, typename PeekBytes>
MaybeHandle<String> NewStringFromBytes(Isolate* isolate, PeekBytes peek_bytes,
AllocationType allocation,
MessageTemplate message) {
Decoder decoder(peek_bytes());
if (decoder.is_invalid()) {
if (message != MessageTemplate::kNone) {
ThrowInvalidEncodedStringBytes(isolate, message);
}
return MaybeHandle<String>();
}
if (decoder.utf16_length() == 0) return isolate->factory()->empty_string();
if (decoder.is_one_byte()) {
if (decoder.utf16_length() == 1) {
uint8_t codepoint;
decoder.Decode(&codepoint, peek_bytes());
return isolate->factory()->LookupSingleCharacterStringFromCode(codepoint);
}
// Allocate string.
Handle<SeqOneByteString> result;
ASSIGN_RETURN_ON_EXCEPTION(isolate, result,
isolate->factory()->NewRawOneByteString(
decoder.utf16_length(), allocation),
String);
DisallowGarbageCollection no_gc;
decoder.Decode(result->GetChars(no_gc), peek_bytes());
return result;
}
// Allocate string.
Handle<SeqTwoByteString> result;
ASSIGN_RETURN_ON_EXCEPTION(isolate, result,
isolate->factory()->NewRawTwoByteString(
decoder.utf16_length(), allocation),
String);
DisallowGarbageCollection no_gc;
decoder.Decode(result->GetChars(no_gc), peek_bytes());
return result;
}
template <typename PeekBytes>
MaybeHandle<String> NewStringFromUtf8Variant(Isolate* isolate,
PeekBytes peek_bytes,
unibrow::Utf8Variant utf8_variant,
AllocationType allocation) {
switch (utf8_variant) {
case unibrow::Utf8Variant::kLossyUtf8:
return NewStringFromBytes<Utf8Decoder>(isolate, peek_bytes, allocation,
MessageTemplate::kNone);
#if V8_ENABLE_WEBASSEMBLY
case unibrow::Utf8Variant::kUtf8:
return NewStringFromBytes<StrictUtf8Decoder>(
isolate, peek_bytes, allocation,
MessageTemplate::kWasmTrapStringInvalidUtf8);
case unibrow::Utf8Variant::kUtf8NoTrap:
return NewStringFromBytes<StrictUtf8Decoder>(
isolate, peek_bytes, allocation, MessageTemplate::kNone);
case unibrow::Utf8Variant::kWtf8:
return NewStringFromBytes<Wtf8Decoder>(
isolate, peek_bytes, allocation,
MessageTemplate::kWasmTrapStringInvalidWtf8);
#endif
}
}
} // namespace
MaybeHandle<String> Factory::NewStringFromUtf8(
base::Vector<const uint8_t> string, unibrow::Utf8Variant utf8_variant,
AllocationType allocation) {
if (string.size() > kMaxInt) {
// The Utf8Decode can't handle longer inputs, and we couldn't create
// strings from them anyway.
THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
}
auto peek_bytes = [&]() -> base::Vector<const uint8_t> { return string; };
return NewStringFromUtf8Variant(isolate(), peek_bytes, utf8_variant,
allocation);
}
MaybeHandle<String> Factory::NewStringFromUtf8(base::Vector<const char> string,
AllocationType allocation) {
return NewStringFromUtf8(base::Vector<const uint8_t>::cast(string),
unibrow::Utf8Variant::kLossyUtf8, allocation);
}
#if V8_ENABLE_WEBASSEMBLY
MaybeHandle<String> Factory::NewStringFromUtf8(
DirectHandle<WasmArray> array, uint32_t start, uint32_t end,
unibrow::Utf8Variant utf8_variant, AllocationType allocation) {
DCHECK_EQ(sizeof(uint8_t), array->type()->element_type().value_kind_size());
DCHECK_LE(start, end);
DCHECK_LE(end, array->length());
// {end - start} can never be more than what the Utf8Decoder can handle.
static_assert(WasmArray::MaxLength(sizeof(uint8_t)) <= kMaxInt);
auto peek_bytes = [&]() -> base::Vector<const uint8_t> {
const uint8_t* contents =
reinterpret_cast<const uint8_t*>(array->ElementAddress(0));
return {contents + start, end - start};
};
return NewStringFromUtf8Variant(isolate(), peek_bytes, utf8_variant,
allocation);
}
MaybeHandle<String> Factory::NewStringFromUtf8(
DirectHandle<ByteArray> array, uint32_t start, uint32_t end,
unibrow::Utf8Variant utf8_variant, AllocationType allocation) {
DCHECK_LE(start, end);
DCHECK_LE(end, array->length());
// {end - start} can never be more than what the Utf8Decoder can handle.
static_assert(ByteArray::kMaxLength <= kMaxInt);
auto peek_bytes = [&]() -> base::Vector<const uint8_t> {
const uint8_t* contents = reinterpret_cast<const uint8_t*>(array->begin());
return {contents + start, end - start};
};
return NewStringFromUtf8Variant(isolate(), peek_bytes, utf8_variant,
allocation);
}
namespace {
struct Wtf16Decoder {
int length_;
bool is_one_byte_;
explicit Wtf16Decoder(base::Vector<const uint16_t> data)
: length_(data.length()),
is_one_byte_(String::IsOneByte(data.begin(), length_)) {}
bool is_invalid() const { return false; }
bool is_one_byte() const { return is_one_byte_; }
int utf16_length() const { return length_; }
template <typename Char>
void Decode(Char* out, base::Vector<const uint16_t> data) {
CopyChars(out, data.begin(), length_);
}
};
} // namespace
MaybeHandle<String> Factory::NewStringFromUtf16(DirectHandle<WasmArray> array,
uint32_t start, uint32_t end,
AllocationType allocation) {
DCHECK_EQ(sizeof(uint16_t), array->type()->element_type().value_kind_size());
DCHECK_LE(start, end);
DCHECK_LE(end, array->length());
// {end - start} can never be more than what the Utf8Decoder can handle.
static_assert(WasmArray::MaxLength(sizeof(uint16_t)) <= kMaxInt);
auto peek_bytes = [&]() -> base::Vector<const uint16_t> {
const uint16_t* contents =
reinterpret_cast<const uint16_t*>(array->ElementAddress(0));
return {contents + start, end - start};
};
return NewStringFromBytes<Wtf16Decoder>(isolate(), peek_bytes, allocation,
MessageTemplate::kNone);
}
#endif // V8_ENABLE_WEBASSEMBLY
MaybeHandle<String> Factory::NewStringFromUtf8SubString(
Handle<SeqOneByteString> str, int begin, int length,
AllocationType allocation) {
base::Vector<const uint8_t> utf8_data;
{
DisallowGarbageCollection no_gc;
utf8_data =
base::Vector<const uint8_t>(str->GetChars(no_gc) + begin, length);
}
Utf8Decoder decoder(utf8_data);
if (length == 1) {
uint16_t t;
// Decode even in the case of length 1 since it can be a bad character.
decoder.Decode(&t, utf8_data);
return LookupSingleCharacterStringFromCode(t);
}
if (decoder.is_ascii()) {
// If the string is ASCII, we can just make a substring.
// TODO(v8): the allocation flag is ignored in this case.
return NewSubString(str, begin, begin + length);
}
DCHECK_GT(decoder.utf16_length(), 0);
if (decoder.is_one_byte()) {
// Allocate string.
Handle<SeqOneByteString> result;
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result,
NewRawOneByteString(decoder.utf16_length(), allocation), String);
DisallowGarbageCollection no_gc;
// Update pointer references, since the original string may have moved after
// allocation.
utf8_data =
base::Vector<const uint8_t>(str->GetChars(no_gc) + begin, length);
decoder.Decode(result->GetChars(no_gc), utf8_data);
return result;
}
// Allocate string.
Handle<SeqTwoByteString> result;
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result,
NewRawTwoByteString(decoder.utf16_length(), allocation), String);
DisallowGarbageCollection no_gc;
// Update pointer references, since the original string may have moved after
// allocation.
utf8_data = base::Vector<const uint8_t>(str->GetChars(no_gc) + begin, length);
decoder.Decode(result->GetChars(no_gc), utf8_data);
return result;
}
MaybeHandle<String> Factory::NewStringFromTwoByte(const base::uc16* string,
int length,
AllocationType allocation) {
DCHECK_NE(allocation, AllocationType::kReadOnly);
if (length == 0) return empty_string();
if (String::IsOneByte(string, length)) {
if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
Handle<SeqOneByteString> result;
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
NewRawOneByteString(length, allocation), String);
DisallowGarbageCollection no_gc;
CopyChars(result->GetChars(no_gc), string, length);
return result;
} else {
Handle<SeqTwoByteString> result;
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
NewRawTwoByteString(length, allocation), String);
DisallowGarbageCollection no_gc;
CopyChars(result->GetChars(no_gc), string, length);
return result;
}
}
MaybeHandle<String> Factory::NewStringFromTwoByte(
base::Vector<const base::uc16> string, AllocationType allocation) {
return NewStringFromTwoByte(string.begin(), string.length(), allocation);
}
MaybeHandle<String> Factory::NewStringFromTwoByte(
const ZoneVector<base::uc16>* string, AllocationType allocation) {
return NewStringFromTwoByte(string->data(), static_cast<int>(string->size()),
allocation);
}
#if V8_ENABLE_WEBASSEMBLY
MaybeHandle<String> Factory::NewStringFromTwoByteLittleEndian(
base::Vector<const base::uc16> str, AllocationType allocation) {
#if defined(V8_TARGET_LITTLE_ENDIAN)
return NewStringFromTwoByte(str, allocation);
#elif defined(V8_TARGET_BIG_ENDIAN)
// TODO(12868): Duplicate the guts of NewStringFromTwoByte, so that
// copying and transcoding the data can be done in a single pass.
UNIMPLEMENTED();
#else
#error Unknown endianness
#endif
}
#endif // V8_ENABLE_WEBASSEMBLY
Handle<String> Factory::NewInternalizedStringImpl(DirectHandle<String> string,
int len,
uint32_t hash_field) {
if (string->IsOneByteRepresentation()) {
Handle<SeqOneByteString> result =
AllocateRawOneByteInternalizedString(len, hash_field);
DisallowGarbageCollection no_gc;
String::WriteToFlat(*string, result->GetChars(no_gc), 0, len);
return result;
}
Handle<SeqTwoByteString> result =
AllocateRawTwoByteInternalizedString(len, hash_field);
DisallowGarbageCollection no_gc;
String::WriteToFlat(*string, result->GetChars(no_gc), 0, len);
return result;
}
StringTransitionStrategy Factory::ComputeInternalizationStrategyForString(
DirectHandle<String> string, MaybeHandle<Map>* internalized_map) {
// The serializer requires internalized strings to be in ReadOnlySpace s.t.
// other objects referencing the string can be allocated in RO space
// themselves.
if (isolate()->enable_ro_allocation_for_snapshot() &&
isolate()->serializer_enabled()) {
return StringTransitionStrategy::kCopy;
}
// Do not internalize young strings in-place: This allows us to ignore both
// string table and stub cache on scavenges.
if (Heap::InYoungGeneration(*string)) {
return StringTransitionStrategy::kCopy;
}
// If the string table is shared, we need to copy if the string is not already
// in the shared heap.
if (v8_flags.shared_string_table && !InAnySharedSpace(*string)) {
return StringTransitionStrategy::kCopy;
}
DCHECK_NOT_NULL(internalized_map);
DisallowGarbageCollection no_gc;
// This method may be called concurrently, so snapshot the map from the input
// string instead of the calling IsType methods on HeapObject, which would
// reload the map each time.
Tagged<Map> map = string->map();
*internalized_map = GetInPlaceInternalizedStringMap(map);
if (!internalized_map->is_null()) {
return StringTransitionStrategy::kInPlace;
}
if (InstanceTypeChecker::IsInternalizedString(map)) {
return StringTransitionStrategy::kAlreadyTransitioned;
}
return StringTransitionStrategy::kCopy;
}
template <class StringClass>
Handle<StringClass> Factory::InternalizeExternalString(
DirectHandle<String> string) {
Handle<Map> map =
GetInPlaceInternalizedStringMap(string->map()).ToHandleChecked();
Tagged<StringClass> external_string =
Tagged<StringClass>::cast(New(map, AllocationType::kOld));
DisallowGarbageCollection no_gc;
external_string->InitExternalPointerFields(isolate());
Tagged<StringClass> cast_string = Tagged<StringClass>::cast(*string);
external_string->set_length(cast_string->length());
external_string->set_raw_hash_field(cast_string->raw_hash_field());
external_string->SetResource(isolate(), nullptr);
isolate()->heap()->RegisterExternalString(external_string);
return handle(external_string, isolate());
}
template Handle<ExternalOneByteString> Factory::InternalizeExternalString<
ExternalOneByteString>(DirectHandle<String>);
template Handle<ExternalTwoByteString> Factory::InternalizeExternalString<
ExternalTwoByteString>(DirectHandle<String>);
StringTransitionStrategy Factory::ComputeSharingStrategyForString(
DirectHandle<String> string, MaybeHandle<Map>* shared_map) {
DCHECK(v8_flags.shared_string_table);
// TODO(pthier): Avoid copying LO-space strings. Update page flags instead.
if (!InAnySharedSpace(*string)) {
return StringTransitionStrategy::kCopy;
}
DCHECK_NOT_NULL(shared_map);
DisallowGarbageCollection no_gc;
InstanceType instance_type = string->map()->instance_type();
if (StringShape(instance_type).IsShared()) {
return StringTransitionStrategy::kAlreadyTransitioned;
}
switch (instance_type) {
case SEQ_TWO_BYTE_STRING_TYPE:
*shared_map = read_only_roots().shared_seq_two_byte_string_map_handle();
return StringTransitionStrategy::kInPlace;
case SEQ_ONE_BYTE_STRING_TYPE:
*shared_map = read_only_roots().shared_seq_one_byte_string_map_handle();
return StringTransitionStrategy::kInPlace;
case EXTERNAL_TWO_BYTE_STRING_TYPE:
*shared_map =
read_only_roots().shared_external_two_byte_string_map_handle();
return StringTransitionStrategy::kInPlace;
case EXTERNAL_ONE_BYTE_STRING_TYPE:
*shared_map =
read_only_roots().shared_external_one_byte_string_map_handle();
return StringTransitionStrategy::kInPlace;