-
Notifications
You must be signed in to change notification settings - Fork 30.9k
/
Copy pathstring.cc
2059 lines (1840 loc) Β· 72.9 KB
/
string.cc
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 2019 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/objects/string.h"
#include "src/base/small-vector.h"
#include "src/common/assert-scope.h"
#include "src/common/globals.h"
#include "src/execution/isolate-utils.h"
#include "src/execution/thread-id.h"
#include "src/handles/handles-inl.h"
#include "src/heap/heap-inl.h"
#include "src/heap/local-factory-inl.h"
#include "src/heap/local-heap-inl.h"
#include "src/heap/mutable-page-metadata.h"
#include "src/heap/read-only-heap.h"
#include "src/numbers/conversions.h"
#include "src/objects/instance-type.h"
#include "src/objects/map.h"
#include "src/objects/oddball.h"
#include "src/objects/string-comparator.h"
#include "src/objects/string-inl.h"
#include "src/strings/char-predicates.h"
#include "src/strings/string-builder-inl.h"
#include "src/strings/string-hasher.h"
#include "src/strings/string-search.h"
#include "src/strings/string-stream.h"
#include "src/strings/unicode-inl.h"
#include "src/utils/ostreams.h"
namespace v8 {
namespace internal {
Handle<String> String::SlowFlatten(Isolate* isolate, Handle<ConsString> cons,
AllocationType allocation) {
DCHECK_NE(cons->second()->length(), 0);
DCHECK(!InAnySharedSpace(*cons));
// TurboFan can create cons strings with empty first parts.
while (cons->first()->length() == 0) {
// We do not want to call this function recursively. Therefore we call
// String::Flatten only in those cases where String::SlowFlatten is not
// called again.
if (IsConsString(cons->second()) && !cons->second()->IsFlat()) {
cons = handle(Cast<ConsString>(cons->second()), isolate);
} else {
return String::Flatten(isolate, handle(cons->second(), isolate),
allocation);
}
}
DCHECK(AllowGarbageCollection::IsAllowed());
int length = cons->length();
if (allocation != AllocationType::kSharedOld) {
allocation =
ObjectInYoungGeneration(*cons) ? allocation : AllocationType::kOld;
}
Handle<SeqString> result;
if (cons->IsOneByteRepresentation()) {
Handle<SeqOneByteString> flat =
isolate->factory()
->NewRawOneByteString(length, allocation)
.ToHandleChecked();
// When the ConsString had a forwarding index, it is possible that it was
// transitioned to a ThinString (and eventually shortcutted to
// InternalizedString) during GC.
if (V8_UNLIKELY(v8_flags.always_use_string_forwarding_table &&
!IsConsString(*cons))) {
DCHECK(IsInternalizedString(*cons) || IsThinString(*cons));
return String::Flatten(isolate, cons, allocation);
}
DisallowGarbageCollection no_gc;
WriteToFlat(*cons, flat->GetChars(no_gc), 0, length);
result = flat;
} else {
Handle<SeqTwoByteString> flat =
isolate->factory()
->NewRawTwoByteString(length, allocation)
.ToHandleChecked();
// When the ConsString had a forwarding index, it is possible that it was
// transitioned to a ThinString (and eventually shortcutted to
// InternalizedString) during GC.
if (V8_UNLIKELY(v8_flags.always_use_string_forwarding_table &&
!IsConsString(*cons))) {
DCHECK(IsInternalizedString(*cons) || IsThinString(*cons));
return String::Flatten(isolate, cons, allocation);
}
DisallowGarbageCollection no_gc;
WriteToFlat(*cons, flat->GetChars(no_gc), 0, length);
result = flat;
}
{
DisallowGarbageCollection no_gc;
Tagged<ConsString> raw_cons = *cons;
raw_cons->set_first(*result);
raw_cons->set_second(ReadOnlyRoots(isolate).empty_string());
}
DCHECK(result->IsFlat());
return result;
}
Handle<String> String::SlowShare(Isolate* isolate, Handle<String> source) {
DCHECK(v8_flags.shared_string_table);
Handle<String> flat = Flatten(isolate, source, AllocationType::kSharedOld);
// Do not recursively call Share, so directly compute the sharing strategy for
// the flat string, which could already be a copy or an existing string from
// e.g. a shortcut ConsString.
MaybeDirectHandle<Map> new_map;
switch (isolate->factory()->ComputeSharingStrategyForString(flat, &new_map)) {
case StringTransitionStrategy::kCopy:
break;
case StringTransitionStrategy::kInPlace:
// A relaxed write is sufficient here, because at this point the string
// has not yet escaped the current thread.
DCHECK(InAnySharedSpace(*flat));
flat->set_map_no_write_barrier(*new_map.ToHandleChecked());
return flat;
case StringTransitionStrategy::kAlreadyTransitioned:
return flat;
}
int length = flat->length();
if (flat->IsOneByteRepresentation()) {
Handle<SeqOneByteString> copy =
isolate->factory()->NewRawSharedOneByteString(length).ToHandleChecked();
DisallowGarbageCollection no_gc;
WriteToFlat(*flat, copy->GetChars(no_gc), 0, length);
return copy;
}
Handle<SeqTwoByteString> copy =
isolate->factory()->NewRawSharedTwoByteString(length).ToHandleChecked();
DisallowGarbageCollection no_gc;
WriteToFlat(*flat, copy->GetChars(no_gc), 0, length);
return copy;
}
namespace {
template <class StringClass>
void MigrateExternalStringResource(Isolate* isolate,
Tagged<ExternalString> from,
Tagged<StringClass> to) {
Address to_resource_address = to->resource_as_address();
if (to_resource_address == kNullAddress) {
Tagged<StringClass> cast_from = Cast<StringClass>(from);
// |to| is a just-created internalized copy of |from|. Migrate the resource.
to->SetResource(isolate, cast_from->resource());
// Zap |from|'s resource pointer to reflect the fact that |from| has
// relinquished ownership of its resource.
isolate->heap()->UpdateExternalString(
from, Cast<ExternalString>(from)->ExternalPayloadSize(), 0);
cast_from->SetResource(isolate, nullptr);
} else if (to_resource_address != from->resource_as_address()) {
// |to| already existed and has its own resource. Finalize |from|.
isolate->heap()->FinalizeExternalString(from);
}
}
void MigrateExternalString(Isolate* isolate, Tagged<String> string,
Tagged<String> internalized) {
if (IsExternalOneByteString(internalized)) {
MigrateExternalStringResource(isolate, Cast<ExternalString>(string),
Cast<ExternalOneByteString>(internalized));
} else if (IsExternalTwoByteString(internalized)) {
MigrateExternalStringResource(isolate, Cast<ExternalString>(string),
Cast<ExternalTwoByteString>(internalized));
} else {
// If the external string is duped into an existing non-external
// internalized string, free its resource (it's about to be rewritten
// into a ThinString below).
isolate->heap()->FinalizeExternalString(string);
}
}
} // namespace
void ExternalString::InitExternalPointerFieldsDuringExternalization(
Tagged<Map> new_map, Isolate* isolate) {
resource_.Init(address(), isolate, kNullAddress);
bool is_uncached = (new_map->instance_type() & kUncachedExternalStringMask) ==
kUncachedExternalStringTag;
if (!is_uncached) {
resource_data_.Init(address(), isolate, kNullAddress);
}
}
template <typename IsolateT>
void String::MakeThin(IsolateT* isolate, Tagged<String> internalized) {
DisallowGarbageCollection no_gc;
DCHECK_NE(this, internalized);
DCHECK(IsInternalizedString(internalized));
Tagged<Map> initial_map = map(kAcquireLoad);
StringShape initial_shape(initial_map);
DCHECK(!initial_shape.IsThin());
#ifdef DEBUG
// Check that shared strings can only transition to ThinStrings on the main
// thread when no other thread is active.
// The exception is during serialization, as no strings have escaped the
// thread yet.
if (initial_shape.IsShared() && !isolate->has_active_deserializer()) {
isolate->AsIsolate()->global_safepoint()->AssertActive();
}
#endif
bool may_contain_recorded_slots = initial_shape.IsIndirect();
int old_size = SizeFromMap(initial_map);
ReadOnlyRoots roots(isolate);
Tagged<Map> target_map = internalized->IsOneByteRepresentation()
? roots.thin_one_byte_string_map()
: roots.thin_two_byte_string_map();
if (initial_shape.IsExternal()) {
// Notify GC about the layout change before the transition to avoid
// concurrent marking from observing any in-between state (e.g.
// ExternalString map where the resource external pointer is overwritten
// with a tagged pointer).
// ExternalString -> ThinString transitions can only happen on the
// main-thread.
isolate->AsIsolate()->heap()->NotifyObjectLayoutChange(
Tagged(this), no_gc, InvalidateRecordedSlots::kYes,
InvalidateExternalPointerSlots::kYes, sizeof(ThinString));
MigrateExternalString(isolate->AsIsolate(), this, internalized);
}
// Update actual first and then do release store on the map word. This ensures
// that the concurrent marker will read the pointer when visiting a
// ThinString.
Tagged<ThinString> thin = UncheckedCast<ThinString>(Tagged(this));
thin->set_actual(internalized);
DCHECK_GE(old_size, sizeof(ThinString));
int size_delta = old_size - sizeof(ThinString);
if (size_delta != 0) {
if (!Heap::IsLargeObject(thin)) {
isolate->heap()->NotifyObjectSizeChange(
thin, old_size, sizeof(ThinString),
may_contain_recorded_slots ? ClearRecordedSlots::kYes
: ClearRecordedSlots::kNo);
} else {
// We don't need special handling for the combination IsLargeObject &&
// may_contain_recorded_slots, because indirect strings never get that
// large.
DCHECK(!may_contain_recorded_slots);
}
}
if (initial_shape.IsExternal()) {
set_map(target_map, kReleaseStore);
} else {
set_map_safe_transition(target_map, kReleaseStore);
}
}
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE) void String::MakeThin(
Isolate* isolate, Tagged<String> internalized);
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE) void String::MakeThin(
LocalIsolate* isolate, Tagged<String> internalized);
template <typename T>
bool String::MarkForExternalizationDuringGC(Isolate* isolate, T* resource) {
uint32_t raw_hash = raw_hash_field(kAcquireLoad);
if (IsExternalForwardingIndex(raw_hash)) return false;
if (IsInternalizedForwardingIndex(raw_hash)) {
const int forwarding_index = ForwardingIndexValueBits::decode(raw_hash);
if (!isolate->string_forwarding_table()->TryUpdateExternalResource(
forwarding_index, resource)) {
// The external resource was concurrently updated by another thread.
return false;
}
raw_hash = Name::IsExternalForwardingIndexBit::update(raw_hash, true);
set_raw_hash_field(raw_hash, kReleaseStore);
return true;
}
// We need to store the hash in the forwarding table, as all non-external
// shared strings are in-place internalizable. In case the string gets
// internalized, we have to ensure that we can get the hash from the
// forwarding table to satisfy the invariant that all internalized strings
// have a computed hash value.
if (!IsHashFieldComputed(raw_hash)) {
raw_hash = EnsureRawHash();
}
DCHECK(IsHashFieldComputed(raw_hash));
int forwarding_index =
isolate->string_forwarding_table()->AddExternalResourceAndHash(
this, resource, raw_hash);
set_raw_hash_field(String::CreateExternalForwardingIndex(forwarding_index),
kReleaseStore);
return true;
}
namespace {
template <bool is_one_byte>
Tagged<Map> ComputeExternalStringMap(Isolate* isolate, Tagged<String> string,
int size) {
ReadOnlyRoots roots(isolate);
StringShape shape(string, isolate);
const bool is_internalized = shape.IsInternalized();
const bool is_shared = shape.IsShared();
if constexpr (is_one_byte) {
if (size < static_cast<int>(sizeof(ExternalString))) {
if (is_internalized) {
return roots.uncached_external_internalized_one_byte_string_map();
} else {
return is_shared ? roots.shared_uncached_external_one_byte_string_map()
: roots.uncached_external_one_byte_string_map();
}
} else {
if (is_internalized) {
return roots.external_internalized_one_byte_string_map();
} else {
return is_shared ? roots.shared_external_one_byte_string_map()
: roots.external_one_byte_string_map();
}
}
} else {
if (size < static_cast<int>(sizeof(ExternalString))) {
if (is_internalized) {
return roots.uncached_external_internalized_two_byte_string_map();
} else {
return is_shared ? roots.shared_uncached_external_two_byte_string_map()
: roots.uncached_external_two_byte_string_map();
}
} else {
if (is_internalized) {
return roots.external_internalized_two_byte_string_map();
} else {
return is_shared ? roots.shared_external_two_byte_string_map()
: roots.external_two_byte_string_map();
}
}
}
}
} // namespace
template <typename T>
void String::MakeExternalDuringGC(Isolate* isolate, T* resource) {
isolate->heap()->safepoint()->AssertActive();
DCHECK_NE(isolate->heap()->gc_state(), Heap::NOT_IN_GC);
constexpr bool is_one_byte =
std::is_base_of_v<v8::String::ExternalOneByteStringResource, T>;
int size = this->Size(); // Byte size of the original string.
DCHECK_GE(size, sizeof(UncachedExternalString));
// Morph the string to an external string by replacing the map and
// reinitializing the fields. This won't work if the space the existing
// string occupies is too small for a regular external string. Instead, we
// resort to an uncached external string instead, omitting the field caching
// the address of the backing store. When we encounter uncached external
// strings in generated code, we need to bailout to runtime.
Tagged<Map> new_map =
ComputeExternalStringMap<is_one_byte>(isolate, this, size);
// Byte size of the external String object.
int new_size = this->SizeFromMap(new_map);
// Shared strings are never indirect.
DCHECK(!StringShape(this).IsIndirect());
if (!isolate->heap()->IsLargeObject(this)) {
isolate->heap()->NotifyObjectSizeChange(this, size, new_size,
ClearRecordedSlots::kNo);
}
// The external pointer slots must be initialized before the new map is
// installed. Otherwise, a GC marking thread may see the new map before the
// slots are initialized and attempt to mark the (invalid) external pointers
// table entries as alive.
static_cast<ExternalString*>(this)
->InitExternalPointerFieldsDuringExternalization(new_map, isolate);
// We are storing the new map using release store after creating a filler in
// the NotifyObjectSizeChange call for the left-over space to avoid races with
// the sweeper thread.
this->set_map(new_map, kReleaseStore);
if constexpr (is_one_byte) {
Tagged<ExternalOneByteString> self = Cast<ExternalOneByteString>(this);
self->SetResource(isolate, resource);
} else {
Tagged<ExternalTwoByteString> self = Cast<ExternalTwoByteString>(this);
self->SetResource(isolate, resource);
}
isolate->heap()->RegisterExternalString(this);
}
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE) void String::
MakeExternalDuringGC(Isolate* isolate,
v8::String::ExternalOneByteStringResource*);
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE) void String::
MakeExternalDuringGC(Isolate* isolate, v8::String::ExternalStringResource*);
bool String::MakeExternal(v8::String::ExternalStringResource* resource) {
// Disallow garbage collection to avoid possible GC vs string access deadlock.
DisallowGarbageCollection no_gc;
// Externalizing twice leaks the external resource, so it's
// prohibited by the API.
DCHECK(
this->SupportsExternalization(v8::String::Encoding::TWO_BYTE_ENCODING));
DCHECK(resource->IsCacheable());
#ifdef ENABLE_SLOW_DCHECKS
if (v8_flags.enable_slow_asserts) {
// Assert that the resource and the string are equivalent.
DCHECK(static_cast<size_t>(this->length()) == resource->length());
base::ScopedVector<base::uc16> smart_chars(this->length());
String::WriteToFlat(this, smart_chars.begin(), 0, this->length());
DCHECK_EQ(0, memcmp(smart_chars.begin(), resource->data(),
resource->length() * sizeof(smart_chars[0])));
}
#endif // DEBUG
int size = this->Size(); // Byte size of the original string.
// Abort if size does not allow in-place conversion.
if (size < static_cast<int>(sizeof(UncachedExternalString))) return false;
// Read-only strings cannot be made external, since that would mutate the
// string.
if (IsReadOnlyHeapObject(this)) return false;
Isolate* isolate = GetIsolateFromWritableObject(this);
if (IsShared()) {
DCHECK(isolate->is_shared_space_isolate());
return MarkForExternalizationDuringGC(isolate, resource);
}
DCHECK_IMPLIES(InWritableSharedSpace(this),
isolate->is_shared_space_isolate());
bool is_internalized = IsInternalizedString(this);
bool has_pointers = StringShape(this).IsIndirect();
base::SharedMutexGuardIf<base::kExclusive> shared_mutex_guard(
isolate->internalized_string_access(), is_internalized);
// Morph the string to an external string by replacing the map and
// reinitializing the fields. This won't work if the space the existing
// string occupies is too small for a regular external string. Instead, we
// resort to an uncached external string instead, omitting the field caching
// the address of the backing store. When we encounter uncached external
// strings in generated code, we need to bailout to runtime.
constexpr bool is_one_byte = false;
Tagged<Map> new_map =
ComputeExternalStringMap<is_one_byte>(isolate, this, size);
// Byte size of the external String object.
int new_size = this->SizeFromMap(new_map);
if (has_pointers) {
isolate->heap()->NotifyObjectLayoutChange(
this, no_gc, InvalidateRecordedSlots::kYes,
InvalidateExternalPointerSlots::kNo, new_size);
}
if (!isolate->heap()->IsLargeObject(this)) {
isolate->heap()->NotifyObjectSizeChange(
this, size, new_size,
has_pointers ? ClearRecordedSlots::kYes : ClearRecordedSlots::kNo);
} else {
// We don't need special handling for the combination IsLargeObject &&
// has_pointers, because indirect strings never get that large.
DCHECK(!has_pointers);
}
// The external pointer slots must be initialized before the new map is
// installed. Otherwise, a GC marking thread may see the new map before the
// slots are initialized and attempt to mark the (invalid) external pointers
// table entries as alive.
static_cast<ExternalString*>(this)
->InitExternalPointerFieldsDuringExternalization(new_map, isolate);
// We are storing the new map using release store after creating a filler in
// the NotifyObjectSizeChange call for the left-over space to avoid races with
// the sweeper thread.
this->set_map(new_map, kReleaseStore);
Tagged<ExternalTwoByteString> self = Cast<ExternalTwoByteString>(this);
self->SetResource(isolate, resource);
isolate->heap()->RegisterExternalString(this);
// Force regeneration of the hash value.
if (is_internalized) self->EnsureHash();
return true;
}
bool String::MakeExternal(v8::String::ExternalOneByteStringResource* resource) {
// Disallow garbage collection to avoid possible GC vs string access deadlock.
DisallowGarbageCollection no_gc;
// Externalizing twice leaks the external resource, so it's
// prohibited by the API.
DCHECK(
this->SupportsExternalization(v8::String::Encoding::ONE_BYTE_ENCODING));
DCHECK(resource->IsCacheable());
#ifdef ENABLE_SLOW_DCHECKS
if (v8_flags.enable_slow_asserts) {
// Assert that the resource and the string are equivalent.
DCHECK(static_cast<size_t>(this->length()) == resource->length());
if (this->IsTwoByteRepresentation()) {
base::ScopedVector<uint16_t> smart_chars(this->length());
String::WriteToFlat(this, smart_chars.begin(), 0, this->length());
DCHECK(String::IsOneByte(smart_chars.begin(), this->length()));
}
base::ScopedVector<char> smart_chars(this->length());
String::WriteToFlat(this, smart_chars.begin(), 0, this->length());
DCHECK_EQ(0, memcmp(smart_chars.begin(), resource->data(),
resource->length() * sizeof(smart_chars[0])));
}
#endif // DEBUG
int size = this->Size(); // Byte size of the original string.
// Abort if size does not allow in-place conversion.
if (size < static_cast<int>(sizeof(UncachedExternalString))) return false;
// Read-only strings cannot be made external, since that would mutate the
// string.
if (IsReadOnlyHeapObject(this)) return false;
Isolate* isolate = GetIsolateFromWritableObject(this);
if (IsShared()) {
DCHECK(isolate->is_shared_space_isolate());
return MarkForExternalizationDuringGC(isolate, resource);
}
DCHECK_IMPLIES(InWritableSharedSpace(this),
isolate->is_shared_space_isolate());
bool is_internalized = IsInternalizedString(this);
bool has_pointers = StringShape(this).IsIndirect();
base::SharedMutexGuardIf<base::kExclusive> shared_mutex_guard(
isolate->internalized_string_access(), is_internalized);
// Morph the string to an external string by replacing the map and
// reinitializing the fields. This won't work if the space the existing
// string occupies is too small for a regular external string. Instead, we
// resort to an uncached external string instead, omitting the field caching
// the address of the backing store. When we encounter uncached external
// strings in generated code, we need to bailout to runtime.
constexpr bool is_one_byte = true;
Tagged<Map> new_map =
ComputeExternalStringMap<is_one_byte>(isolate, this, size);
if (!isolate->heap()->IsLargeObject(this)) {
// Byte size of the external String object.
int new_size = this->SizeFromMap(new_map);
if (has_pointers) {
DCHECK(!InWritableSharedSpace(this));
isolate->heap()->NotifyObjectLayoutChange(
this, no_gc, InvalidateRecordedSlots::kYes,
InvalidateExternalPointerSlots::kNo, new_size);
}
isolate->heap()->NotifyObjectSizeChange(
this, size, new_size,
has_pointers ? ClearRecordedSlots::kYes : ClearRecordedSlots::kNo);
} else {
// We don't need special handling for the combination IsLargeObject &&
// has_pointers, because indirect strings never get that large.
DCHECK(!has_pointers);
}
// The external pointer slots must be initialized before the new map is
// installed. Otherwise, a GC marking thread may see the new map before the
// slots are initialized and attempt to mark the (invalid) external pointers
// table entries as alive.
static_cast<ExternalString*>(this)
->InitExternalPointerFieldsDuringExternalization(new_map, isolate);
// We are storing the new map using release store after creating a filler in
// the NotifyObjectSizeChange call for the left-over space to avoid races with
// the sweeper thread.
this->set_map(new_map, kReleaseStore);
Tagged<ExternalOneByteString> self = Cast<ExternalOneByteString>(this);
self->SetResource(isolate, resource);
isolate->heap()->RegisterExternalString(this);
// Force regeneration of the hash value.
if (is_internalized) self->EnsureHash();
return true;
}
bool String::SupportsExternalization(v8::String::Encoding encoding) {
if (IsThinString(this)) {
return i::Cast<i::ThinString>(this)->actual()->SupportsExternalization(
encoding);
}
// RO_SPACE strings cannot be externalized.
if (IsReadOnlyHeapObject(this)) {
return false;
}
#ifdef V8_COMPRESS_POINTERS
// Small strings may not be in-place externalizable.
if (this->Size() < static_cast<int>(sizeof(UncachedExternalString))) {
return false;
}
#else
DCHECK_LE(sizeof(UncachedExternalString), this->Size());
#endif
StringShape shape(this);
// Already an external string.
if (shape.IsExternal()) {
return false;
}
// Only strings in old space can be externalized.
if (Heap::InYoungGeneration(Tagged(this))) {
return false;
}
// Encoding changes are not supported.
static_assert(kStringEncodingMask == 1 << 3);
static_assert(v8::String::Encoding::ONE_BYTE_ENCODING == 1 << 3);
static_assert(v8::String::Encoding::TWO_BYTE_ENCODING == 0);
return shape.encoding_tag() == static_cast<uint32_t>(encoding);
}
const char* String::PrefixForDebugPrint() const {
StringShape shape(this);
if (IsTwoByteRepresentation()) {
if (shape.IsInternalized()) {
return "u#";
} else if (shape.IsCons()) {
return "uc\"";
} else if (shape.IsThin()) {
return "u>\"";
} else if (shape.IsExternal()) {
return "ue\"";
} else {
return "u\"";
}
} else {
if (shape.IsInternalized()) {
return "#";
} else if (shape.IsCons()) {
return "c\"";
} else if (shape.IsThin()) {
return ">\"";
} else if (shape.IsExternal()) {
return "e\"";
} else {
return "\"";
}
}
UNREACHABLE();
}
const char* String::SuffixForDebugPrint() const {
StringShape shape(this);
if (shape.IsInternalized()) return "";
return "\"";
}
void String::StringShortPrint(StringStream* accumulator) {
if (!LooksValid()) {
accumulator->Add("<Invalid String>");
return;
}
const int len = length();
accumulator->Add("<String[%u]: ", len);
accumulator->Add(PrefixForDebugPrint());
if (len > kMaxShortPrintLength) {
accumulator->Add("...<truncated>>");
accumulator->Add(SuffixForDebugPrint());
accumulator->Put('>');
return;
}
PrintUC16(accumulator, 0, len);
accumulator->Add(SuffixForDebugPrint());
accumulator->Put('>');
}
void String::PrintUC16(std::ostream& os, int start, int end) {
if (end < 0) end = length();
StringCharacterStream stream(this, start);
for (int i = start; i < end && stream.HasMore(); i++) {
os << AsUC16(stream.GetNext());
}
}
void String::PrintUC16(StringStream* accumulator, int start, int end) {
if (end < 0) end = length();
StringCharacterStream stream(this, start);
for (int i = start; i < end && stream.HasMore(); i++) {
uint16_t c = stream.GetNext();
if (c == '\n') {
accumulator->Add("\\n");
} else if (c == '\r') {
accumulator->Add("\\r");
} else if (c == '\\') {
accumulator->Add("\\\\");
} else if (!std::isprint(c)) {
accumulator->Add("\\x%02x", c);
} else {
accumulator->Put(static_cast<char>(c));
}
}
}
int32_t String::ToArrayIndex(Address addr) {
DisallowGarbageCollection no_gc;
Tagged<String> key(addr);
uint32_t index;
if (!key->AsArrayIndex(&index)) return -1;
if (index <= INT_MAX) return index;
return -1;
}
bool String::LooksValid() {
// TODO(leszeks): Maybe remove this check entirely, Heap::Contains uses
// basically the same logic as the way we access the heap in the first place.
// RO_SPACE objects should always be valid.
if (V8_ENABLE_THIRD_PARTY_HEAP_BOOL) return true;
if (ReadOnlyHeap::Contains(this)) return true;
MemoryChunkMetadata* chunk = MemoryChunkMetadata::FromHeapObject(this);
if (chunk->heap() == nullptr) return false;
return chunk->heap()->Contains(this);
}
// static
Handle<Number> String::ToNumber(Isolate* isolate, Handle<String> subject) {
return isolate->factory()->NewNumber(
StringToDouble(isolate, subject, ALLOW_NON_DECIMAL_PREFIX));
}
String::FlatContent String::SlowGetFlatContent(
const DisallowGarbageCollection& no_gc,
const SharedStringAccessGuardIfNeeded& access_guard) {
USE(no_gc);
Tagged<String> string = this;
StringShape shape(string);
int offset = 0;
// Extract cons- and sliced strings.
if (shape.IsCons()) {
Tagged<ConsString> cons = Cast<ConsString>(string);
if (!cons->IsFlat()) return FlatContent(no_gc);
string = cons->first();
shape = StringShape(string);
} else if (shape.IsSliced()) {
Tagged<SlicedString> slice = Cast<SlicedString>(string);
offset = slice->offset();
string = slice->parent();
shape = StringShape(string);
}
DCHECK(!shape.IsCons());
DCHECK(!shape.IsSliced());
// Extract thin strings.
if (shape.IsThin()) {
Tagged<ThinString> thin = Cast<ThinString>(string);
string = thin->actual();
shape = StringShape(string);
}
DCHECK(shape.IsDirect());
return TryGetFlatContentFromDirectString(no_gc, string, offset, length(),
access_guard)
.value();
}
std::unique_ptr<char[]> String::ToCString(AllowNullsFlag allow_nulls,
RobustnessFlag robust_flag,
int offset, int length,
int* length_return) {
if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
return std::unique_ptr<char[]>();
}
// Negative length means the to the end of the string.
if (length < 0) length = kMaxInt - offset;
// Compute the size of the UTF-8 string. Start at the specified offset.
StringCharacterStream stream(this, offset);
int character_position = offset;
int utf8_bytes = 0;
int last = unibrow::Utf16::kNoPreviousCharacter;
while (stream.HasMore() && character_position++ < offset + length) {
uint16_t character = stream.GetNext();
utf8_bytes += unibrow::Utf8::Length(character, last);
last = character;
}
if (length_return) {
*length_return = utf8_bytes;
}
char* result = NewArray<char>(utf8_bytes + 1);
// Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
stream.Reset(this, offset);
character_position = offset;
int utf8_byte_position = 0;
last = unibrow::Utf16::kNoPreviousCharacter;
while (stream.HasMore() && character_position++ < offset + length) {
uint16_t character = stream.GetNext();
if (allow_nulls == DISALLOW_NULLS && character == 0) {
character = ' ';
}
utf8_byte_position +=
unibrow::Utf8::Encode(result + utf8_byte_position, character, last);
last = character;
}
result[utf8_byte_position] = 0;
return std::unique_ptr<char[]>(result);
}
std::unique_ptr<char[]> String::ToCString(AllowNullsFlag allow_nulls,
RobustnessFlag robust_flag,
int* length_return) {
return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
}
// static
template <typename sinkchar>
void String::WriteToFlat(Tagged<String> source, sinkchar* sink, int start,
int length) {
DCHECK(!SharedStringAccessGuardIfNeeded::IsNeeded(source));
return WriteToFlat(source, sink, start, length,
SharedStringAccessGuardIfNeeded::NotNeeded());
}
// static
template <typename sinkchar>
void String::WriteToFlat(Tagged<String> source, sinkchar* sink, int start,
int length,
const SharedStringAccessGuardIfNeeded& access_guard) {
DisallowGarbageCollection no_gc;
if (length == 0) return;
while (true) {
DCHECK_LT(0, length);
DCHECK_LE(0, start);
DCHECK_LE(length, source->length());
switch (StringShape(source).representation_and_encoding_tag()) {
case kOneByteStringTag | kExternalStringTag:
CopyChars(sink, Cast<ExternalOneByteString>(source)->GetChars() + start,
length);
return;
case kTwoByteStringTag | kExternalStringTag:
CopyChars(sink, Cast<ExternalTwoByteString>(source)->GetChars() + start,
length);
return;
case kOneByteStringTag | kSeqStringTag:
CopyChars(
sink,
Cast<SeqOneByteString>(source)->GetChars(no_gc, access_guard) +
start,
length);
return;
case kTwoByteStringTag | kSeqStringTag:
CopyChars(
sink,
Cast<SeqTwoByteString>(source)->GetChars(no_gc, access_guard) +
start,
length);
return;
case kOneByteStringTag | kConsStringTag:
case kTwoByteStringTag | kConsStringTag: {
Tagged<ConsString> cons_string = Cast<ConsString>(source);
Tagged<String> first = cons_string->first();
int boundary = first->length();
int first_length = boundary - start;
int second_length = start + length - boundary;
if (second_length >= first_length) {
// Right hand side is longer. Recurse over left.
if (first_length > 0) {
WriteToFlat(first, sink, start, first_length, access_guard);
if (start == 0 && cons_string->second() == first) {
CopyChars(sink + boundary, sink, boundary);
return;
}
sink += boundary - start;
start = 0;
length -= first_length;
} else {
start -= boundary;
}
source = cons_string->second();
} else {
// Left hand side is longer. Recurse over right.
if (second_length > 0) {
Tagged<String> second = cons_string->second();
// When repeatedly appending to a string, we get a cons string that
// is unbalanced to the left, a list, essentially. We inline the
// common case of sequential one-byte right child.
if (second_length == 1) {
sink[boundary - start] =
static_cast<sinkchar>(second->Get(0, access_guard));
} else if (IsSeqOneByteString(second)) {
CopyChars(
sink + boundary - start,
Cast<SeqOneByteString>(second)->GetChars(no_gc, access_guard),
second_length);
} else {
WriteToFlat(second, sink + boundary - start, 0, second_length,
access_guard);
}
length -= second_length;
}
source = first;
}
if (length == 0) return;
continue;
}
case kOneByteStringTag | kSlicedStringTag:
case kTwoByteStringTag | kSlicedStringTag: {
Tagged<SlicedString> slice = Cast<SlicedString>(source);
unsigned offset = slice->offset();
source = slice->parent();
start += offset;
continue;
}
case kOneByteStringTag | kThinStringTag:
case kTwoByteStringTag | kThinStringTag:
source = Cast<ThinString>(source)->actual();
continue;
}
UNREACHABLE();
}
UNREACHABLE();
}
template <typename SourceChar>
static void CalculateLineEndsImpl(String::LineEndsVector* line_ends,
base::Vector<const SourceChar> src,
bool include_ending_line) {
const int src_len = src.length();
for (int i = 0; i < src_len - 1; i++) {
SourceChar current = src[i];
SourceChar next = src[i + 1];
if (IsLineTerminatorSequence(current, next)) line_ends->push_back(i);
}
if (src_len > 0 && IsLineTerminatorSequence(src[src_len - 1], 0)) {
line_ends->push_back(src_len - 1);
}
if (include_ending_line) {
// Include one character beyond the end of script. The rewriter uses that
// position for the implicit return statement.
line_ends->push_back(src_len);
}
}
template <typename IsolateT>
String::LineEndsVector String::CalculateLineEndsVector(
IsolateT* isolate, Handle<String> src, bool include_ending_line) {
src = Flatten(isolate, src);
// Rough estimate of line count based on a roughly estimated average
// length of packed code. Most scripts have < 32 lines.
int line_count_estimate = (src->length() >> 6) + 16;
LineEndsVector line_ends;
line_ends.reserve(line_count_estimate);
{
DisallowGarbageCollection no_gc;
// Dispatch on type of strings.
String::FlatContent content = src->GetFlatContent(no_gc);
DCHECK(content.IsFlat());
if (content.IsOneByte()) {
CalculateLineEndsImpl(&line_ends, content.ToOneByteVector(),
include_ending_line);
} else {
CalculateLineEndsImpl(&line_ends, content.ToUC16Vector(),
include_ending_line);
}
}
return line_ends;
}
template String::LineEndsVector String::CalculateLineEndsVector(
Isolate* isolate, Handle<String> src, bool include_ending_line);
template String::LineEndsVector String::CalculateLineEndsVector(
LocalIsolate* isolate, Handle<String> src, bool include_ending_line);
template <typename IsolateT>
Handle<FixedArray> String::CalculateLineEnds(IsolateT* isolate,
Handle<String> src,
bool include_ending_line) {
LineEndsVector line_ends =
CalculateLineEndsVector(isolate, src, include_ending_line);
int line_count = static_cast<int>(line_ends.size());
Handle<FixedArray> array =
isolate->factory()->NewFixedArray(line_count, AllocationType::kOld);
{
DisallowGarbageCollection no_gc;
Tagged<FixedArray> raw_array = *array;
for (int i = 0; i < line_count; i++) {
raw_array->set(i, Smi::FromInt(line_ends[i]));
}
}
return array;
}
template Handle<FixedArray> String::CalculateLineEnds(Isolate* isolate,
Handle<String> src,
bool include_ending_line);
template Handle<FixedArray> String::CalculateLineEnds(LocalIsolate* isolate,
Handle<String> src,
bool include_ending_line);