-
Notifications
You must be signed in to change notification settings - Fork 2k
/
StringType.cpp
3192 lines (2729 loc) · 103 KB
/
StringType.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "vm/StringType-inl.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/Latin1.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PodOperations.h"
#include "mozilla/RangedPtr.h"
#include "mozilla/StringBuffer.h"
#include "mozilla/TextUtils.h"
#include "mozilla/Utf8.h"
#include "mozilla/Vector.h"
#include <algorithm> // std::{all_of,copy_n,enable_if,is_const,move}
#include <iterator> // std::size
#include <type_traits> // std::is_same, std::is_unsigned
#include "jsfriendapi.h"
#include "jsnum.h"
#include "builtin/Boolean.h"
#ifdef ENABLE_RECORD_TUPLE
# include "builtin/RecordObject.h"
#endif
#include "gc/AllocKind.h"
#include "gc/MaybeRooted.h"
#include "gc/Nursery.h"
#include "js/CharacterEncoding.h"
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/Printer.h" // js::GenericPrinter
#include "js/PropertyAndElement.h" // JS_DefineElement
#include "js/SourceText.h" // JS::SourceText
#include "js/StableStringChars.h"
#include "js/UbiNode.h"
#include "util/Identifier.h" // js::IsIdentifierNameOrPrivateName
#include "util/Unicode.h"
#include "vm/GeckoProfiler.h"
#include "vm/JSONPrinter.h" // js::JSONPrinter
#include "vm/StaticStrings.h"
#include "vm/ToSource.h" // js::ValueToSource
#include "gc/Marking-inl.h"
#include "vm/GeckoProfiler-inl.h"
#ifdef ENABLE_RECORD_TUPLE
# include "vm/RecordType.h"
# include "vm/TupleType.h"
#endif
using namespace js;
using mozilla::AsWritableChars;
using mozilla::ConvertLatin1toUtf16;
using mozilla::IsAsciiDigit;
using mozilla::IsUtf16Latin1;
using mozilla::LossyConvertUtf16toLatin1;
using mozilla::PodCopy;
using mozilla::RangedPtr;
using mozilla::RoundUpPow2;
using mozilla::Span;
using JS::AutoCheckCannotGC;
using JS::AutoStableStringChars;
using UniqueLatin1Chars = UniquePtr<Latin1Char[], JS::FreePolicy>;
size_t JSString::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) {
// JSRope: do nothing, we'll count all children chars when we hit the leaf
// strings.
if (isRope()) {
return 0;
}
MOZ_ASSERT(isLinear());
// JSDependentString: do nothing, we'll count the chars when we hit the base
// string.
if (isDependent()) {
return 0;
}
// JSExternalString: Ask the embedding to tell us what's going on.
if (isExternal()) {
// Our callback isn't supposed to cause GC.
JS::AutoSuppressGCAnalysis nogc;
JSExternalString& external = asExternal();
if (external.hasLatin1Chars()) {
return asExternal().callbacks()->sizeOfBuffer(external.latin1Chars(),
mallocSizeOf);
} else {
return asExternal().callbacks()->sizeOfBuffer(external.twoByteChars(),
mallocSizeOf);
}
}
// JSInlineString, JSFatInlineString, js::ThinInlineAtom, js::FatInlineAtom:
// the chars are inline.
if (isInline()) {
return 0;
}
JSLinearString& linear = asLinear();
if (hasStringBuffer()) {
return linear.stringBuffer()->SizeOfIncludingThisIfUnshared(mallocSizeOf);
}
// Chars in the nursery are owned by the nursery.
if (!ownsMallocedChars()) {
return 0;
}
// Everything else: measure the space for the chars.
return linear.hasLatin1Chars() ? mallocSizeOf(linear.rawLatin1Chars())
: mallocSizeOf(linear.rawTwoByteChars());
}
JS::ubi::Node::Size JS::ubi::Concrete<JSString>::size(
mozilla::MallocSizeOf mallocSizeOf) const {
JSString& str = get();
size_t size;
if (str.isAtom()) {
if (str.isInline()) {
size = str.isFatInline() ? sizeof(js::FatInlineAtom)
: sizeof(js::ThinInlineAtom);
} else {
size = sizeof(js::NormalAtom);
}
} else {
size = str.isFatInline() ? sizeof(JSFatInlineString) : sizeof(JSString);
}
if (IsInsideNursery(&str)) {
size += Nursery::nurseryCellHeaderSize();
}
size += str.sizeOfExcludingThis(mallocSizeOf);
return size;
}
const char16_t JS::ubi::Concrete<JSString>::concreteTypeName[] = u"JSString";
mozilla::Maybe<std::tuple<size_t, size_t>> JSString::encodeUTF8Partial(
const JS::AutoRequireNoGC& nogc, mozilla::Span<char> buffer) const {
mozilla::Vector<const JSString*, 16, SystemAllocPolicy> stack;
const JSString* current = this;
char16_t pendingLeadSurrogate = 0; // U+0000 means no pending lead surrogate
size_t totalRead = 0;
size_t totalWritten = 0;
for (;;) {
if (current->isRope()) {
JSRope& rope = current->asRope();
if (!stack.append(rope.rightChild())) {
// OOM
return mozilla::Nothing();
}
current = rope.leftChild();
continue;
}
JSLinearString& linear = current->asLinear();
if (MOZ_LIKELY(linear.hasLatin1Chars())) {
if (MOZ_UNLIKELY(pendingLeadSurrogate)) {
if (buffer.Length() < 3) {
return mozilla::Some(std::make_tuple(totalRead, totalWritten));
}
buffer[0] = '\xEF';
buffer[1] = '\xBF';
buffer[2] = '\xBD';
buffer = buffer.From(3);
totalRead += 1; // pendingLeadSurrogate
totalWritten += 3;
pendingLeadSurrogate = 0;
}
auto src = mozilla::AsChars(
mozilla::Span(linear.latin1Chars(nogc), linear.length()));
size_t read;
size_t written;
std::tie(read, written) =
mozilla::ConvertLatin1toUtf8Partial(src, buffer);
buffer = buffer.From(written);
totalRead += read;
totalWritten += written;
if (read < src.Length()) {
return mozilla::Some(std::make_tuple(totalRead, totalWritten));
}
} else {
auto src = mozilla::Span(linear.twoByteChars(nogc), linear.length());
if (MOZ_UNLIKELY(pendingLeadSurrogate)) {
char16_t first = 0;
if (!src.IsEmpty()) {
first = src[0];
}
if (unicode::IsTrailSurrogate(first)) {
// Got a surrogate pair
if (buffer.Length() < 4) {
return mozilla::Some(std::make_tuple(totalRead, totalWritten));
}
uint32_t astral = unicode::UTF16Decode(pendingLeadSurrogate, first);
buffer[0] = char(0b1111'0000 | (astral >> 18));
buffer[1] = char(0b1000'0000 | ((astral >> 12) & 0b11'1111));
buffer[2] = char(0b1000'0000 | ((astral >> 6) & 0b11'1111));
buffer[3] = char(0b1000'0000 | (astral & 0b11'1111));
src = src.From(1);
buffer = buffer.From(4);
totalRead += 2; // both pendingLeadSurrogate and first!
totalWritten += 4;
} else {
// unpaired surrogate
if (buffer.Length() < 3) {
return mozilla::Some(std::make_tuple(totalRead, totalWritten));
}
buffer[0] = '\xEF';
buffer[1] = '\xBF';
buffer[2] = '\xBD';
buffer = buffer.From(3);
totalRead += 1; // pendingLeadSurrogate
totalWritten += 3;
}
pendingLeadSurrogate = 0;
}
if (!src.IsEmpty()) {
char16_t last = src[src.Length() - 1];
if (unicode::IsLeadSurrogate(last)) {
src = src.To(src.Length() - 1);
pendingLeadSurrogate = last;
} else {
MOZ_ASSERT(!pendingLeadSurrogate);
}
size_t read;
size_t written;
std::tie(read, written) =
mozilla::ConvertUtf16toUtf8Partial(src, buffer);
buffer = buffer.From(written);
totalRead += read;
totalWritten += written;
if (read < src.Length()) {
return mozilla::Some(std::make_tuple(totalRead, totalWritten));
}
}
}
if (stack.empty()) {
break;
}
current = stack.popCopy();
}
if (MOZ_UNLIKELY(pendingLeadSurrogate)) {
if (buffer.Length() < 3) {
return mozilla::Some(std::make_tuple(totalRead, totalWritten));
}
buffer[0] = '\xEF';
buffer[1] = '\xBF';
buffer[2] = '\xBD';
// No need to update buffer and pendingLeadSurrogate anymore
totalRead += 1;
totalWritten += 3;
}
return mozilla::Some(std::make_tuple(totalRead, totalWritten));
}
#if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
template <typename CharT>
/*static */
void JSString::dumpCharsNoQuote(const CharT* s, size_t n,
js::GenericPrinter& out) {
for (size_t i = 0; i < n; i++) {
char16_t c = s[i];
if (c == '"') {
out.put("\\\"");
} else if (c == '\'') {
out.put("\\'");
} else if (c == '`') {
out.put("\\`");
} else if (c == '\\') {
out.put("\\\\");
} else if (c == '\r') {
out.put("\\r");
} else if (c == '\n') {
out.put("\\n");
} else if (c == '\t') {
out.put("\\t");
} else if (c >= 32 && c < 127) {
out.putChar((char)s[i]);
} else if (c <= 255) {
out.printf("\\x%02x", unsigned(c));
} else {
out.printf("\\u%04x", unsigned(c));
}
}
}
/* static */
template void JSString::dumpCharsNoQuote(const Latin1Char* s, size_t n,
js::GenericPrinter& out);
/* static */
template void JSString::dumpCharsNoQuote(const char16_t* s, size_t n,
js::GenericPrinter& out);
void JSString::dump() const {
js::Fprinter out(stderr);
dump(out);
}
void JSString::dump(js::GenericPrinter& out) const {
js::JSONPrinter json(out);
dump(json);
out.put("\n");
}
void JSString::dump(js::JSONPrinter& json) const {
json.beginObject();
dumpFields(json);
json.endObject();
}
const char* RepresentationToString(const JSString* s) {
if (s->isAtom()) {
return "JSAtom";
}
if (s->isLinear()) {
if (s->isDependent()) {
return "JSDependentString";
}
if (s->isExternal()) {
return "JSExternalString";
}
if (s->isExtensible()) {
return "JSExtensibleString";
}
if (s->isInline()) {
if (s->isFatInline()) {
return "JSFatInlineString";
}
return "JSThinInlineString";
}
return "JSLinearString";
}
if (s->isRope()) {
return "JSRope";
}
return "JSString";
}
template <typename KnownF, typename UnknownF>
void ForEachStringFlag(const JSString* str, uint32_t flags, KnownF known,
UnknownF unknown) {
for (uint32_t i = js::Bit(3); i < js::Bit(17); i = i << 1) {
if (!(flags & i)) {
continue;
}
switch (i) {
case JSString::ATOM_BIT:
known("ATOM_BIT");
break;
case JSString::LINEAR_BIT:
known("LINEAR_BIT");
break;
case JSString::DEPENDENT_BIT:
known("DEPENDENT_BIT");
break;
case JSString::INLINE_CHARS_BIT:
known("INLINE_BIT");
break;
case JSString::LINEAR_IS_EXTENSIBLE_BIT:
static_assert(JSString::LINEAR_IS_EXTENSIBLE_BIT ==
JSString::INLINE_IS_FAT_BIT);
if (str->isLinear()) {
if (str->isInline()) {
known("FAT");
} else if (!str->isAtom()) {
known("EXTENSIBLE");
} else {
unknown(i);
}
} else {
unknown(i);
}
break;
case JSString::LINEAR_IS_EXTERNAL_BIT:
static_assert(JSString::LINEAR_IS_EXTERNAL_BIT ==
JSString::ATOM_IS_PERMANENT_BIT);
if (str->isAtom()) {
known("PERMANENT");
} else if (str->isLinear()) {
known("EXTERNAL");
} else {
unknown(i);
}
break;
case JSString::LATIN1_CHARS_BIT:
known("LATIN1_CHARS_BIT");
break;
case JSString::HAS_STRING_BUFFER_BIT:
known("HAS_STRING_BUFFER_BIT");
break;
case JSString::ATOM_IS_INDEX_BIT:
if (str->isAtom()) {
known("ATOM_IS_INDEX_BIT");
} else {
known("ATOM_REF_BIT");
}
break;
case JSString::INDEX_VALUE_BIT:
known("INDEX_VALUE_BIT");
break;
case JSString::IN_STRING_TO_ATOM_CACHE:
known("IN_STRING_TO_ATOM_CACHE");
break;
case JSString::FLATTEN_VISIT_RIGHT:
if (str->isRope()) {
known("FLATTEN_VISIT_RIGHT");
} else {
known("DEPENDED_ON_BIT");
}
break;
case JSString::FLATTEN_FINISH_NODE:
static_assert(JSString::FLATTEN_FINISH_NODE ==
JSString::PINNED_ATOM_BIT);
if (str->isRope()) {
known("FLATTEN_FINISH_NODE");
} else if (str->isAtom()) {
known("PINNED_ATOM_BIT");
} else {
known("NON_DEDUP_BIT");
}
break;
default:
unknown(i);
break;
}
}
}
void JSString::dumpFields(js::JSONPrinter& json) const {
dumpCommonFields(json);
dumpCharsFields(json);
}
void JSString::dumpCommonFields(js::JSONPrinter& json) const {
json.formatProperty("address", "(%s*)0x%p", RepresentationToString(this),
this);
json.beginInlineListProperty("flags");
ForEachStringFlag(
this, flags(), [&](const char* name) { json.value("%s", name); },
[&](uint32_t value) { json.value("Unknown(%08x)", value); });
json.endInlineList();
if (hasIndexValue()) {
json.property("indexValue", getIndexValue());
}
json.boolProperty("isTenured", isTenured());
json.property("length", length());
}
void JSString::dumpCharsFields(js::JSONPrinter& json) const {
if (isLinear()) {
const JSLinearString* linear = &asLinear();
AutoCheckCannotGC nogc;
if (hasLatin1Chars()) {
const Latin1Char* chars = linear->latin1Chars(nogc);
json.formatProperty("chars", "(JS::Latin1Char*)0x%p", chars);
js::GenericPrinter& out = json.beginStringProperty("value");
dumpCharsNoQuote(chars, length(), out);
json.endStringProperty();
} else {
const char16_t* chars = linear->twoByteChars(nogc);
json.formatProperty("chars", "(char16_t*)0x%p", chars);
js::GenericPrinter& out = json.beginStringProperty("value");
dumpCharsNoQuote(chars, length(), out);
json.endStringProperty();
}
} else {
js::GenericPrinter& out = json.beginStringProperty("value");
dumpCharsNoQuote(out);
json.endStringProperty();
}
}
void JSString::dumpRepresentation() const {
js::Fprinter out(stderr);
dumpRepresentation(out);
}
void JSString::dumpRepresentation(js::GenericPrinter& out) const {
js::JSONPrinter json(out);
dumpRepresentation(json);
out.put("\n");
}
void JSString::dumpRepresentation(js::JSONPrinter& json) const {
json.beginObject();
dumpRepresentationFields(json);
json.endObject();
}
void JSString::dumpRepresentationFields(js::JSONPrinter& json) const {
dumpCommonFields(json);
if (isAtom()) {
asAtom().dumpOwnRepresentationFields(json);
} else if (isLinear()) {
asLinear().dumpOwnRepresentationFields(json);
if (isDependent()) {
asDependent().dumpOwnRepresentationFields(json);
} else if (isExternal()) {
asExternal().dumpOwnRepresentationFields(json);
} else if (isExtensible()) {
asExtensible().dumpOwnRepresentationFields(json);
} else if (isInline()) {
asInline().dumpOwnRepresentationFields(json);
}
} else if (isRope()) {
asRope().dumpOwnRepresentationFields(json);
// Rope already shows the chars.
return;
}
dumpCharsFields(json);
}
void JSString::dumpStringContent(js::GenericPrinter& out) const {
dumpCharsSingleQuote(out);
out.printf(" @ (%s*)0x%p", RepresentationToString(this), this);
}
void JSString::dumpPropertyName(js::GenericPrinter& out) const {
dumpCharsNoQuote(out);
}
void JSString::dumpChars(js::GenericPrinter& out) const {
out.putChar('"');
dumpCharsNoQuote(out);
out.putChar('"');
}
void JSString::dumpCharsSingleQuote(js::GenericPrinter& out) const {
out.putChar('\'');
dumpCharsNoQuote(out);
out.putChar('\'');
}
void JSString::dumpCharsNoQuote(js::GenericPrinter& out) const {
if (isLinear()) {
const JSLinearString* linear = &asLinear();
AutoCheckCannotGC nogc;
if (hasLatin1Chars()) {
dumpCharsNoQuote(linear->latin1Chars(nogc), length(), out);
} else {
dumpCharsNoQuote(linear->twoByteChars(nogc), length(), out);
}
} else if (isRope()) {
JSRope* rope = &asRope();
rope->leftChild()->dumpCharsNoQuote(out);
rope->rightChild()->dumpCharsNoQuote(out);
}
}
bool JSString::equals(const char* s) {
JSLinearString* linear = ensureLinear(nullptr);
if (!linear) {
// This is DEBUG-only code.
fprintf(stderr, "OOM in JSString::equals!\n");
return false;
}
return StringEqualsAscii(linear, s);
}
#endif /* defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW) */
JSExtensibleString& JSLinearString::makeExtensible(size_t capacity) {
MOZ_ASSERT(!isDependent());
MOZ_ASSERT(!isInline());
MOZ_ASSERT(!isAtom());
MOZ_ASSERT(!isExternal());
MOZ_ASSERT(capacity >= length());
js::RemoveCellMemory(this, allocSize(), js::MemoryUse::StringContents);
setLengthAndFlags(length(), flags() | EXTENSIBLE_FLAGS);
d.s.u3.capacity = capacity;
js::AddCellMemory(this, allocSize(), js::MemoryUse::StringContents);
return asExtensible();
}
template <typename CharT>
static MOZ_ALWAYS_INLINE bool AllocCharsForFlatten(Nursery& nursery,
JSString* str, size_t length,
CharT** chars,
size_t* capacity,
bool* hasStringBuffer) {
/*
* Grow by 12.5% if the buffer is very large. Otherwise, round up to the
* next power of 2. This is similar to what we do with arrays; see
* JSObject::ensureDenseArrayElements.
*/
auto calcCapacity = [](size_t length, size_t maxCapacity) {
static const size_t DOUBLING_MAX = 1024 * 1024;
if (length > DOUBLING_MAX) {
return std::min<size_t>(maxCapacity, length + (length / 8));
}
size_t capacity = RoundUpPow2(length);
MOZ_ASSERT(capacity <= maxCapacity);
return capacity;
};
if (length < JSString::MIN_BYTES_FOR_BUFFER / sizeof(CharT)) {
*capacity = calcCapacity(length, JSString::MAX_LENGTH);
MOZ_ASSERT(length <= *capacity);
MOZ_ASSERT(*capacity <= JSString::MAX_LENGTH);
auto buffer = str->zone()->make_pod_arena_array<CharT>(
js::StringBufferArena, *capacity);
if (!buffer) {
return false;
}
if (!str->isTenured()) {
if (!nursery.registerMallocedBuffer(buffer.get(),
*capacity * sizeof(CharT))) {
return false;
}
}
*chars = buffer.release();
*hasStringBuffer = false;
return true;
}
using mozilla::StringBuffer;
static_assert(StringBuffer::IsValidLength<CharT>(JSString::MAX_LENGTH),
"JSString length must be valid for StringBuffer");
// Include extra space for the header and the null-terminator before
// calculating the capacity. This ensures we make good use of jemalloc's
// bucket sizes. For example, for a Latin1 string with length 2000 we want to
// get a capacity of 2039 (chars). With the StringBuffer header (8 bytes) and
// the null-terminator this results in an allocation of 2048 bytes.
//
// Note: the null-terminator will not be included in the extensible string's
// capacity field.
static_assert(sizeof(StringBuffer) % sizeof(CharT) == 0);
static constexpr size_t ExtraChars = sizeof(StringBuffer) / sizeof(CharT) + 1;
size_t fullCapacity =
calcCapacity(length + ExtraChars, JSString::MAX_LENGTH + ExtraChars);
*capacity = fullCapacity - ExtraChars;
MOZ_ASSERT(length <= *capacity);
MOZ_ASSERT(*capacity <= JSString::MAX_LENGTH);
RefPtr<StringBuffer> buffer = StringBuffer::Alloc(
(*capacity + 1) * sizeof(CharT), mozilla::Some(js::StringBufferArena));
if (!buffer) {
return false;
}
if (!str->isTenured()) {
auto* linear = static_cast<JSLinearString*>(str); // True when we're done.
if (!nursery.addExtensibleStringBuffer(linear, buffer)) {
return false;
}
}
// Transfer ownership to the caller, where the buffer will be used for the
// extensible string.
// Note: the null-terminator will be stored in flattenInternal.
StringBuffer* buf;
buffer.forget(&buf);
*chars = static_cast<CharT*>(buf->Data());
*hasStringBuffer = true;
return true;
}
UniqueLatin1Chars JSRope::copyLatin1Chars(JSContext* maybecx,
arena_id_t destArenaId) const {
return copyCharsInternal<Latin1Char>(maybecx, destArenaId);
}
UniqueTwoByteChars JSRope::copyTwoByteChars(JSContext* maybecx,
arena_id_t destArenaId) const {
return copyCharsInternal<char16_t>(maybecx, destArenaId);
}
// Allocate chars for a string. If parameters and conditions allow, this will
// try to allocate in the nursery, but this may always fall back to a malloc
// allocation. The return value will record where the allocation happened.
template <typename CharT>
static MOZ_ALWAYS_INLINE JSString::OwnedChars<CharT> AllocChars(JSContext* cx,
size_t length,
gc::Heap heap) {
if (heap == gc::Heap::Default && cx->zone()->allocNurseryStrings()) {
MOZ_ASSERT(cx->nursery().isEnabled());
void* buffer = cx->nursery().tryAllocateNurseryBuffer(
cx->zone(), length * sizeof(CharT), js::StringBufferArena);
if (buffer) {
using Kind = typename JSString::OwnedChars<CharT>::Kind;
return {static_cast<CharT*>(buffer), length, Kind::Nursery};
}
}
static_assert(JSString::MIN_BYTES_FOR_BUFFER % sizeof(CharT) == 0);
if (length < JSString::MIN_BYTES_FOR_BUFFER / sizeof(CharT)) {
auto buffer =
cx->make_pod_arena_array<CharT>(js::StringBufferArena, length);
if (!buffer) {
return {};
}
return {std::move(buffer), length};
}
if (MOZ_UNLIKELY(!mozilla::StringBuffer::IsValidLength<CharT>(length))) {
ReportOversizedAllocation(cx, JSMSG_ALLOC_OVERFLOW);
return {};
}
// Note: StringBuffers must be null-terminated.
RefPtr<mozilla::StringBuffer> buffer = mozilla::StringBuffer::Alloc(
(length + 1) * sizeof(CharT), mozilla::Some(js::StringBufferArena));
if (!buffer) {
ReportOutOfMemory(cx);
return {};
}
static_cast<CharT*>(buffer->Data())[length] = '\0';
return {std::move(buffer), length};
}
// Like AllocChars but for atom characters. Does not report an exception on OOM.
template <typename CharT>
JSString::OwnedChars<CharT> js::AllocAtomCharsValidLength(JSContext* cx,
size_t length) {
MOZ_ASSERT(cx->zone()->isAtomsZone());
MOZ_ASSERT(JSAtom::validateLength(cx, length));
MOZ_ASSERT(mozilla::StringBuffer::IsValidLength<CharT>(length));
static_assert(JSString::MIN_BYTES_FOR_BUFFER % sizeof(CharT) == 0);
if (length < JSString::MIN_BYTES_FOR_BUFFER / sizeof(CharT)) {
auto buffer =
cx->make_pod_arena_array<CharT>(js::StringBufferArena, length);
if (!buffer) {
cx->recoverFromOutOfMemory();
return {};
}
return {std::move(buffer), length};
}
// Note: StringBuffers must be null-terminated.
RefPtr<mozilla::StringBuffer> buffer = mozilla::StringBuffer::Alloc(
(length + 1) * sizeof(CharT), mozilla::Some(js::StringBufferArena));
if (!buffer) {
return {};
}
static_cast<CharT*>(buffer->Data())[length] = '\0';
return {std::move(buffer), length};
}
template JSString::OwnedChars<Latin1Char> js::AllocAtomCharsValidLength(
JSContext* cx, size_t length);
template JSString::OwnedChars<char16_t> js::AllocAtomCharsValidLength(
JSContext* cx, size_t length);
template <typename CharT>
UniquePtr<CharT[], JS::FreePolicy> JSRope::copyCharsInternal(
JSContext* maybecx, arena_id_t destArenaId) const {
// Left-leaning ropes are far more common than right-leaning ropes, so
// perform a non-destructive traversal of the rope, right node first,
// splatting each node's characters into a contiguous buffer.
size_t n = length();
UniquePtr<CharT[], JS::FreePolicy> out;
if (maybecx) {
out.reset(maybecx->pod_arena_malloc<CharT>(destArenaId, n));
} else {
out.reset(js_pod_arena_malloc<CharT>(destArenaId, n));
}
if (!out) {
return nullptr;
}
Vector<const JSString*, 8, SystemAllocPolicy> nodeStack;
const JSString* str = this;
CharT* end = out.get() + str->length();
while (true) {
if (str->isRope()) {
if (!nodeStack.append(str->asRope().leftChild())) {
if (maybecx) {
ReportOutOfMemory(maybecx);
}
return nullptr;
}
str = str->asRope().rightChild();
} else {
end -= str->length();
CopyChars(end, str->asLinear());
if (nodeStack.empty()) {
break;
}
str = nodeStack.popCopy();
}
}
MOZ_ASSERT(end == out.get());
return out;
}
template <typename CharT>
void AddStringToHash(uint32_t* hash, const CharT* chars, size_t len) {
// It's tempting to use |HashString| instead of this loop, but that's
// slightly different than our existing implementation for non-ropes. We
// want to pretend we have a contiguous set of chars so we need to
// accumulate char by char rather than generate a new hash for substring
// and then accumulate that.
for (size_t i = 0; i < len; i++) {
*hash = mozilla::AddToHash(*hash, chars[i]);
}
}
void AddStringToHash(uint32_t* hash, const JSString* str) {
AutoCheckCannotGC nogc;
const auto& s = str->asLinear();
if (s.hasLatin1Chars()) {
AddStringToHash(hash, s.latin1Chars(nogc), s.length());
} else {
AddStringToHash(hash, s.twoByteChars(nogc), s.length());
}
}
bool JSRope::hash(uint32_t* outHash) const {
Vector<const JSString*, 8, SystemAllocPolicy> nodeStack;
const JSString* str = this;
*outHash = 0;
while (true) {
if (str->isRope()) {
if (!nodeStack.append(str->asRope().rightChild())) {
return false;
}
str = str->asRope().leftChild();
} else {
AddStringToHash(outHash, str);
if (nodeStack.empty()) {
break;
}
str = nodeStack.popCopy();
}
}
return true;
}
#if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
void JSRope::dumpOwnRepresentationFields(js::JSONPrinter& json) const {
json.beginObjectProperty("leftChild");
leftChild()->dumpRepresentationFields(json);
json.endObject();
json.beginObjectProperty("rightChild");
rightChild()->dumpRepresentationFields(json);
json.endObject();
}
#endif
namespace js {
template <>
void CopyChars(char16_t* dest, const JSLinearString& str) {
AutoCheckCannotGC nogc;
if (str.hasTwoByteChars()) {
PodCopy(dest, str.twoByteChars(nogc), str.length());
} else {
CopyAndInflateChars(dest, str.latin1Chars(nogc), str.length());
}
}
template <>
void CopyChars(Latin1Char* dest, const JSLinearString& str) {
AutoCheckCannotGC nogc;
if (str.hasLatin1Chars()) {
PodCopy(dest, str.latin1Chars(nogc), str.length());
} else {
/*
* When we flatten a TwoByte rope, we turn child ropes (including Latin1
* ropes) into TwoByte dependent strings. If one of these strings is
* also part of another Latin1 rope tree, we can have a Latin1 rope with
* a TwoByte descendent and we end up here when we flatten it. Although
* the chars are stored as TwoByte, we know they must be in the Latin1
* range, so we can safely deflate here.
*/
size_t len = str.length();
const char16_t* chars = str.twoByteChars(nogc);
auto src = Span(chars, len);
MOZ_ASSERT(IsUtf16Latin1(src));
LossyConvertUtf16toLatin1(src, AsWritableChars(Span(dest, len)));
}
}
} /* namespace js */
template <typename CharT>
static constexpr uint32_t StringFlagsForCharType(uint32_t baseFlags) {
if constexpr (std::is_same_v<CharT, char16_t>) {
return baseFlags;
}
return baseFlags | JSString::LATIN1_CHARS_BIT;
}
static bool UpdateNurseryBuffersOnTransfer(js::Nursery& nursery,
JSExtensibleString* from,
JSString* to, void* chars,
size_t size) {
// Update the list of buffers associated with nursery cells when |buffer| is
// moved from string |from| to string |to|, depending on whether those strings
// are in the nursery or not.
if (from->hasStringBuffer()) {
// Note: addExtensibleStringBuffer is fallible so we have to call it before
// removeExtensibleStringBuffer.
// If both strings are in the nursery, avoid updating mallocedBufferBytes to
// not trigger an unnecessary minor GC in addMallocedBufferBytes.
bool updateMallocBytes = from->isTenured() || to->isTenured();
if (!to->isTenured()) {
auto* linear = static_cast<JSLinearString*>(to);
if (!nursery.addExtensibleStringBuffer(linear, from->stringBuffer(),
updateMallocBytes)) {
return false;
}
}
if (!from->isTenured()) {
nursery.removeExtensibleStringBuffer(from, updateMallocBytes);
}
return true;
}
if (from->isTenured() && !to->isTenured()) {
// Tenured leftmost child is giving its chars buffer to the
// nursery-allocated root node.
if (!nursery.registerMallocedBuffer(chars, size)) {
return false;
}
} else if (!from->isTenured() && to->isTenured()) {
// Leftmost child is giving its nursery-held chars buffer to a
// tenured string.
nursery.removeMallocedBuffer(chars, size);
}
return true;
}
static bool CanReuseLeftmostBuffer(JSString* leftmostChild, size_t wholeLength,
bool hasTwoByteChars) {
if (!leftmostChild->isExtensible()) {
return false;
}
JSExtensibleString& str = leftmostChild->asExtensible();
// Don't mutate the StringBuffer if there are other references to it, possibly
// on other threads.
if (str.hasStringBuffer() && str.stringBuffer()->IsReadonly()) {
return false;
}
return str.capacity() >= wholeLength &&
str.hasTwoByteChars() == hasTwoByteChars;
}
JSLinearString* JSRope::flatten(JSContext* maybecx) {
mozilla::Maybe<AutoGeckoProfilerEntry> entry;
if (maybecx) {
entry.emplace(maybecx, "JSRope::flatten");
}
JSLinearString* str = flattenInternal();
if (!str && maybecx) {
ReportOutOfMemory(maybecx);
}