Debian Codegraph @

js/src/vm/StringType.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "vm/StringType-inl.h"
8
9 #include "mozilla/DebugOnly.h"
10 #include "mozilla/HashFunctions.h"
11 #include "mozilla/Latin1.h"
12 #include "mozilla/MathAlgorithms.h"
13 #include "mozilla/MemoryReporting.h"
14 #include "mozilla/PodOperations.h"
15 #include "mozilla/RangedPtr.h"
16 #include "mozilla/StringBuffer.h"
17 #include "mozilla/TextUtils.h"
18 #include "mozilla/Utf8.h"
19 #include "mozilla/Vector.h"
20
21 #include <algorithm> // std::{all_of,copy_n,enable_if,is_const,move}
22 #include <iterator> // std::size
23 #include <type_traits> // std::is_same, std::is_unsigned
24
25 #include "jsfriendapi.h"
26 #include "jsnum.h"
27
28 #include "builtin/Boolean.h"
29 #include "gc/AllocKind.h"
30 #include "gc/MaybeRooted.h"
31 #include "gc/Nursery.h"
32 #include "js/CharacterEncoding.h"
33 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
34 #include "js/Printer.h" // js::GenericPrinter
35 #include "js/PropertyAndElement.h" // JS_DefineElement
36 #include "js/SourceText.h" // JS::SourceText
37 #include "js/StableStringChars.h"
38 #include "js/UbiNode.h"
39 #include "util/Identifier.h" // js::IsIdentifierNameOrPrivateName
40 #include "util/Unicode.h"
41 #include "vm/GeckoProfiler.h"
42 #include "vm/JSONPrinter.h" // js::JSONPrinter
43 #include "vm/StaticStrings.h"
44 #include "vm/ToSource.h" // js::ValueToSource
45
46 #include "gc/Marking-inl.h"
47 #include "vm/GeckoProfiler-inl.h"
48
49 using namespace js;
50
51 using mozilla::AsWritableChars;
52 using mozilla::ConvertLatin1toUtf16;
53 using mozilla::IsAsciiDigit;
54 using mozilla::IsUtf16Latin1;
55 using mozilla::LossyConvertUtf16toLatin1;
56 using mozilla::PodCopy;
57 using mozilla::RangedPtr;
58 using mozilla::RoundUpPow2;
59 using mozilla::Span;
60
61 using JS::AutoCheckCannotGC;
62 using JS::AutoStableStringChars;
63
64 using UniqueLatin1Chars = UniquePtr<Latin1Char[], JS::FreePolicy>;
65
66 size_t JSString::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) {
67 // JSRope: do nothing, we'll count all children chars when we hit the leaf
68 // strings.
69 if (isRope()) {
70 return 0;
71 }
72
73 MOZ_ASSERT(isLinear());
74
75 // JSDependentString: do nothing, we'll count the chars when we hit the base
76 // string.
77 if (isDependent()) {
78 return 0;
79 }
80
81 // JSExternalString: Ask the embedding to tell us what's going on.
82 if (isExternal()) {
83 // Our callback isn't supposed to cause GC.
84 JS::AutoSuppressGCAnalysis nogc;
85 JSExternalString& external = asExternal();
86 if (external.hasLatin1Chars()) {
87 return asExternal().callbacks()->sizeOfBuffer(external.latin1Chars(),
88 mallocSizeOf);
89 } else {
90 return asExternal().callbacks()->sizeOfBuffer(external.twoByteChars(),
91 mallocSizeOf);
92 }
93 }
94
95 // JSInlineString, JSFatInlineString, js::ThinInlineAtom, js::FatInlineAtom:
96 // the chars are inline.
97 if (isInline()) {
98 return 0;
99 }
100
101 JSLinearString& linear = asLinear();
102
103 if (hasStringBuffer()) {
104 return linear.stringBuffer()->SizeOfIncludingThisIfUnshared(mallocSizeOf);
105 }
106
107 // Chars in the nursery are owned by the nursery.
108 if (!ownsMallocedChars()) {
109 return 0;
110 }
111
112 // Everything else: measure the space for the chars.
113 return linear.hasLatin1Chars() ? mallocSizeOf(linear.rawLatin1Chars())
114 : mallocSizeOf(linear.rawTwoByteChars());
115 }
116
117 JS::ubi::Node::Size JS::ubi::Concrete<JSString>::size(
118 mozilla::MallocSizeOf mallocSizeOf) const {
119 JSString& str = get();
120 size_t size;
121 if (str.isAtom()) {
122 if (str.isInline()) {
123 size = str.isFatInline() ? sizeof(js::FatInlineAtom)
124 : sizeof(js::ThinInlineAtom);
125 } else {
126 size = sizeof(js::NormalAtom);
127 }
128 } else {
129 size = str.isFatInline() ? sizeof(JSFatInlineString) : sizeof(JSString);
130 }
131
132 if (IsInsideNursery(&str)) {
133 size += Nursery::nurseryCellHeaderSize();
134 }
135
136 size += str.sizeOfExcludingThis(mallocSizeOf);
137
138 return size;
139 }
140
141 const char16_t JS::ubi::Concrete<JSString>::concreteTypeName[] = u"JSString";
142
143 mozilla::Maybe<std::tuple<size_t, size_t>> JSString::encodeUTF8Partial(
144 const JS::AutoRequireNoGC& nogc, mozilla::Span<char> buffer) const {
145 mozilla::Vector<const JSString*, 16, SystemAllocPolicy> stack;
146 const JSString* current = this;
147 char16_t pendingLeadSurrogate = 0; // U+0000 means no pending lead surrogate
148 size_t totalRead = 0;
149 size_t totalWritten = 0;
150 for (;;) {
151 if (current->isRope()) {
152 JSRope& rope = current->asRope();
153 if (!stack.append(rope.rightChild())) {
154 // OOM
155 return mozilla::Nothing();
156 }
157 current = rope.leftChild();
158 continue;
159 }
160
161 JSLinearString& linear = current->asLinear();
162 if (MOZ_LIKELY(linear.hasLatin1Chars())) {
163 if (MOZ_UNLIKELY(pendingLeadSurrogate)) {
164 if (buffer.Length() < 3) {
165 return mozilla::Some(std::make_tuple(totalRead, totalWritten));
166 }
167 buffer[0] = '\xEF';
168 buffer[1] = '\xBF';
169 buffer[2] = '\xBD';
170 buffer = buffer.From(3);
171 totalRead += 1; // pendingLeadSurrogate
172 totalWritten += 3;
173 pendingLeadSurrogate = 0;
174 }
175 auto src = mozilla::AsChars(
176 mozilla::Span(linear.latin1Chars(nogc), linear.length()));
177 size_t read;
178 size_t written;
179 std::tie(read, written) =
180 mozilla::ConvertLatin1toUtf8Partial(src, buffer);
181 buffer = buffer.From(written);
182 totalRead += read;
183 totalWritten += written;
184 if (read < src.Length()) {
185 return mozilla::Some(std::make_tuple(totalRead, totalWritten));
186 }
187 } else {
188 auto src = mozilla::Span(linear.twoByteChars(nogc), linear.length());
189 if (MOZ_UNLIKELY(pendingLeadSurrogate)) {
190 char16_t first = 0;
191 if (!src.IsEmpty()) {
192 first = src[0];
193 }
194 if (unicode::IsTrailSurrogate(first)) {
195 // Got a surrogate pair
196 if (buffer.Length() < 4) {
197 return mozilla::Some(std::make_tuple(totalRead, totalWritten));
198 }
199 uint32_t astral = unicode::UTF16Decode(pendingLeadSurrogate, first);
200 buffer[0] = char(0b1111'0000 | (astral >> 18));
201 buffer[1] = char(0b1000'0000 | ((astral >> 12) & 0b11'1111));
202 buffer[2] = char(0b1000'0000 | ((astral >> 6) & 0b11'1111));
203 buffer[3] = char(0b1000'0000 | (astral & 0b11'1111));
204 src = src.From(1);
205 buffer = buffer.From(4);
206 totalRead += 2; // both pendingLeadSurrogate and first!
207 totalWritten += 4;
208 } else {
209 // unpaired surrogate
210 if (buffer.Length() < 3) {
211 return mozilla::Some(std::make_tuple(totalRead, totalWritten));
212 }
213 buffer[0] = '\xEF';
214 buffer[1] = '\xBF';
215 buffer[2] = '\xBD';
216 buffer = buffer.From(3);
217 totalRead += 1; // pendingLeadSurrogate
218 totalWritten += 3;
219 }
220 pendingLeadSurrogate = 0;
221 }
222 if (!src.IsEmpty()) {
223 char16_t last = src[src.Length() - 1];
224 if (unicode::IsLeadSurrogate(last)) {
225 src = src.To(src.Length() - 1);
226 pendingLeadSurrogate = last;
227 } else {
228 MOZ_ASSERT(!pendingLeadSurrogate);
229 }
230 size_t read;
231 size_t written;
232 std::tie(read, written) =
233 mozilla::ConvertUtf16toUtf8Partial(src, buffer);
234 buffer = buffer.From(written);
235 totalRead += read;
236 totalWritten += written;
237 if (read < src.Length()) {
238 return mozilla::Some(std::make_tuple(totalRead, totalWritten));
239 }
240 }
241 }
242 if (stack.empty()) {
243 break;
244 }
245 current = stack.popCopy();
246 }
247 if (MOZ_UNLIKELY(pendingLeadSurrogate)) {
248 if (buffer.Length() < 3) {
249 return mozilla::Some(std::make_tuple(totalRead, totalWritten));
250 }
251 buffer[0] = '\xEF';
252 buffer[1] = '\xBF';
253 buffer[2] = '\xBD';
254 // No need to update buffer and pendingLeadSurrogate anymore
255 totalRead += 1;
256 totalWritten += 3;
257 }
258 return mozilla::Some(std::make_tuple(totalRead, totalWritten));
259 }
260
261 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
262 template <typename CharT>
263 /*static */
264 void JSString::dumpCharsNoQuote(const CharT* s, size_t n,
265 js::GenericPrinter& out) {
266 for (size_t i = 0; i < n; i++) {
267 char16_t c = s[i];
268 if (c == '"') {
269 out.put("\\\"");
270 } else if (c == '\'') {
271 out.put("\\'");
272 } else if (c == '`') {
273 out.put("\\`");
274 } else if (c == '\\') {
275 out.put("\\\\");
276 } else if (c == '\r') {
277 out.put("\\r");
278 } else if (c == '\n') {
279 out.put("\\n");
280 } else if (c == '\t') {
281 out.put("\\t");
282 } else if (c >= 32 && c < 127) {
283 out.putChar((char)s[i]);
284 } else if (c <= 255) {
285 out.printf("\\x%02x", unsigned(c));
286 } else {
287 out.printf("\\u%04x", unsigned(c));
288 }
289 }
290 }
291
292 /* static */
293 template void JSString::dumpCharsNoQuote(const Latin1Char* s, size_t n,
294 js::GenericPrinter& out);
295
296 /* static */
297 template void JSString::dumpCharsNoQuote(const char16_t* s, size_t n,
298 js::GenericPrinter& out);
299
300 void JSString::dump() const {
301 js::Fprinter out(stderr);
302 dump(out);
303 }
304
305 void JSString::dump(js::GenericPrinter& out) const {
306 js::JSONPrinter json(out);
307 dump(json);
308 out.put("\n");
309 }
310
311 void JSString::dump(js::JSONPrinter& json) const {
312 json.beginObject();
313 dumpFields(json);
314 json.endObject();
315 }
316
317 const char* RepresentationToString(const JSString* s) {
318 if (s->isAtom()) {
319 return "JSAtom";
320 }
321
322 if (s->isLinear()) {
323 if (s->isDependent()) {
324 return "JSDependentString";
325 }
326 if (s->isExternal()) {
327 return "JSExternalString";
328 }
329 if (s->isExtensible()) {
330 return "JSExtensibleString";
331 }
332
333 if (s->isInline()) {
334 if (s->isFatInline()) {
335 return "JSFatInlineString";
336 }
337 return "JSThinInlineString";
338 }
339
340 return "JSLinearString";
341 }
342
343 if (s->isRope()) {
344 return "JSRope";
345 }
346
347 return "JSString";
348 }
349
350 template <typename KnownF, typename UnknownF>
351 void ForEachStringFlag(const JSString* str, uint32_t flags, KnownF known,
352 UnknownF unknown) {
353 for (uint32_t i = js::Bit(3); i < js::Bit(17); i = i << 1) {
354 if (!(flags & i)) {
355 continue;
356 }
357 switch (i) {
358 case JSString::ATOM_BIT:
359 known("ATOM_BIT");
360 break;
361 case JSString::LINEAR_BIT:
362 known("LINEAR_BIT");
363 break;
364 case JSString::DEPENDENT_BIT:
365 known("DEPENDENT_BIT");
366 break;
367 case JSString::INLINE_CHARS_BIT:
368 known("INLINE_BIT");
369 break;
370 case JSString::LINEAR_IS_EXTENSIBLE_BIT:
371 static_assert(JSString::LINEAR_IS_EXTENSIBLE_BIT ==
372 JSString::INLINE_IS_FAT_BIT);
373 if (str->isLinear()) {
374 if (str->isInline()) {
375 known("FAT");
376 } else if (!str->isAtom()) {
377 known("EXTENSIBLE");
378 } else {
379 unknown(i);
380 }
381 } else {
382 unknown(i);
383 }
384 break;
385 case JSString::LINEAR_IS_EXTERNAL_BIT:
386 static_assert(JSString::LINEAR_IS_EXTERNAL_BIT ==
387 JSString::ATOM_IS_PERMANENT_BIT);
388 if (str->isAtom()) {
389 known("PERMANENT");
390 } else if (str->isLinear()) {
391 known("EXTERNAL");
392 } else {
393 unknown(i);
394 }
395 break;
396 case JSString::LATIN1_CHARS_BIT:
397 known("LATIN1_CHARS_BIT");
398 break;
399 case JSString::HAS_STRING_BUFFER_BIT:
400 known("HAS_STRING_BUFFER_BIT");
401 break;
402 case JSString::ATOM_IS_INDEX_BIT:
403 if (str->isAtom()) {
404 known("ATOM_IS_INDEX_BIT");
405 } else {
406 known("ATOM_REF_BIT");
407 }
408 break;
409 case JSString::INDEX_VALUE_BIT:
410 known("INDEX_VALUE_BIT");
411 break;
412 case JSString::IN_STRING_TO_ATOM_CACHE:
413 known("IN_STRING_TO_ATOM_CACHE");
414 break;
415 case JSString::FLATTEN_VISIT_RIGHT:
416 if (str->isRope()) {
417 known("FLATTEN_VISIT_RIGHT");
418 } else {
419 known("DEPENDED_ON_BIT");
420 }
421 break;
422 case JSString::FLATTEN_FINISH_NODE:
423 static_assert(JSString::FLATTEN_FINISH_NODE ==
424 JSString::PINNED_ATOM_BIT);
425 if (str->isRope()) {
426 known("FLATTEN_FINISH_NODE");
427 } else if (str->isAtom()) {
428 known("PINNED_ATOM_BIT");
429 } else {
430 known("NON_DEDUP_BIT");
431 }
432 break;
433 default:
434 unknown(i);
435 break;
436 }
437 }
438 }
439
440 void JSString::dumpFields(js::JSONPrinter& json) const {
441 dumpCommonFields(json);
442 dumpCharsFields(json);
443 }
444
445 void JSString::dumpCommonFields(js::JSONPrinter& json) const {
446 json.formatProperty("address", "(%s*)0x%p", RepresentationToString(this),
447 this);
448
449 json.beginInlineListProperty("flags");
450 ForEachStringFlag(
451 this, flags(), [&](const char* name) { json.value("%s", name); },
452 [&](uint32_t value) { json.value("Unknown(%08x)", value); });
453 json.endInlineList();
454
455 if (hasIndexValue()) {
456 json.property("indexValue", getIndexValue());
457 }
458
459 json.boolProperty("isTenured", isTenured());
460
461 json.property("length", length());
462 }
463
464 void JSString::dumpCharsFields(js::JSONPrinter& json) const {
465 if (isLinear()) {
466 const JSLinearString* linear = &asLinear();
467
468 AutoCheckCannotGC nogc;
469 if (hasLatin1Chars()) {
470 const Latin1Char* chars = linear->latin1Chars(nogc);
471
472 json.formatProperty("chars", "(JS::Latin1Char*)0x%p", chars);
473
474 js::GenericPrinter& out = json.beginStringProperty("value");
475 dumpCharsNoQuote(chars, length(), out);
476 json.endStringProperty();
477 } else {
478 const char16_t* chars = linear->twoByteChars(nogc);
479
480 json.formatProperty("chars", "(char16_t*)0x%p", chars);
481
482 js::GenericPrinter& out = json.beginStringProperty("value");
483 dumpCharsNoQuote(chars, length(), out);
484 json.endStringProperty();
485 }
486 } else {
487 js::GenericPrinter& out = json.beginStringProperty("value");
488 dumpCharsNoQuote(out);
489 json.endStringProperty();
490 }
491 }
492
493 void JSString::dumpRepresentation() const {
494 js::Fprinter out(stderr);
495 dumpRepresentation(out);
496 }
497
498 void JSString::dumpRepresentation(js::GenericPrinter& out) const {
499 js::JSONPrinter json(out);
500 dumpRepresentation(json);
501 out.put("\n");
502 }
503
504 void JSString::dumpRepresentation(js::JSONPrinter& json) const {
505 json.beginObject();
506 dumpRepresentationFields(json);
507 json.endObject();
508 }
509
510 void JSString::dumpRepresentationFields(js::JSONPrinter& json) const {
511 dumpCommonFields(json);
512
513 if (isAtom()) {
514 asAtom().dumpOwnRepresentationFields(json);
515 } else if (isLinear()) {
516 asLinear().dumpOwnRepresentationFields(json);
517
518 if (isDependent()) {
519 asDependent().dumpOwnRepresentationFields(json);
520 } else if (isExternal()) {
521 asExternal().dumpOwnRepresentationFields(json);
522 } else if (isExtensible()) {
523 asExtensible().dumpOwnRepresentationFields(json);
524 } else if (isInline()) {
525 asInline().dumpOwnRepresentationFields(json);
526 }
527 } else if (isRope()) {
528 asRope().dumpOwnRepresentationFields(json);
529 // Rope already shows the chars.
530 return;
531 }
532
533 dumpCharsFields(json);
534 }
535
536 void JSString::dumpStringContent(js::GenericPrinter& out) const {
537 dumpCharsSingleQuote(out);
538
539 out.printf(" @ (%s*)0x%p", RepresentationToString(this), this);
540 }
541
542 void JSString::dumpPropertyName(js::GenericPrinter& out) const {
543 dumpCharsNoQuote(out);
544 }
545
546 void JSString::dumpChars(js::GenericPrinter& out) const {
547 out.putChar('"');
548 dumpCharsNoQuote(out);
549 out.putChar('"');
550 }
551
552 void JSString::dumpCharsSingleQuote(js::GenericPrinter& out) const {
553 out.putChar('\'');
554 dumpCharsNoQuote(out);
555 out.putChar('\'');
556 }
557
558 void JSString::dumpCharsNoQuote(js::GenericPrinter& out) const {
559 if (isLinear()) {
560 const JSLinearString* linear = &asLinear();
561
562 AutoCheckCannotGC nogc;
563 if (hasLatin1Chars()) {
564 dumpCharsNoQuote(linear->latin1Chars(nogc), length(), out);
565 } else {
566 dumpCharsNoQuote(linear->twoByteChars(nogc), length(), out);
567 }
568 } else if (isRope()) {
569 JSRope* rope = &asRope();
570 rope->leftChild()->dumpCharsNoQuote(out);
571 rope->rightChild()->dumpCharsNoQuote(out);
572 }
573 }
574
575 bool JSString::equals(const char* s) {
576 JSLinearString* linear = ensureLinear(nullptr);
577 if (!linear) {
578 // This is DEBUG-only code.
579 fprintf(stderr, "OOM in JSString::equals!\n");
580 return false;
581 }
582
583 return StringEqualsAscii(linear, s);
584 }
585 #endif /* defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW) */
586
587 JSExtensibleString& JSLinearString::makeExtensible(size_t capacity) {
588 MOZ_ASSERT(!isDependent());
589 MOZ_ASSERT(!isInline());
590 MOZ_ASSERT(!isAtom());
591 MOZ_ASSERT(!isExternal());
592 MOZ_ASSERT(capacity >= length());
593 size_t oldSize = allocSize();
594 js::RemoveCellMemory(this, oldSize, js::MemoryUse::StringContents);
595 setLengthAndFlags(length(), flags() | EXTENSIBLE_FLAGS);
596 d.s.u3.capacity = capacity;
597 size_t newSize = allocSize();
598 js::AddCellMemory(this, newSize, js::MemoryUse::StringContents);
599 MOZ_ASSERT(newSize >= oldSize);
600 if (!isTenured() && newSize > oldSize) {
601 auto& nursery = runtimeFromMainThread()->gc.nursery();
602 nursery.addMallocedBufferBytes(newSize - oldSize);
603 }
604 return asExtensible();
605 }
606
607 template <typename CharT>
608 static MOZ_ALWAYS_INLINE bool AllocCharsForFlatten(Nursery& nursery,
609 JSString* str, size_t length,
610 CharT** chars,
611 size_t* capacity,
612 bool* hasStringBuffer) {
613 /*
614 * Grow by 12.5% if the buffer is very large. Otherwise, round up to the
615 * next power of 2. This is similar to what we do with object elements; see
616 * NativeObject::goodElementsAllocationAmount.
617 */
618 auto calcCapacity = [](size_t length, size_t maxCapacity) {
619 static const size_t DOUBLING_MAX = 1024 * 1024;
620 if (length > DOUBLING_MAX) {
621 return std::min<size_t>(maxCapacity, length + (length / 8));
622 }
623 size_t capacity = RoundUpPow2(length);
624 MOZ_ASSERT(capacity <= maxCapacity);
625 return capacity;
626 };
627
628 if (length < JSString::MIN_BYTES_FOR_BUFFER / sizeof(CharT)) {
629 *capacity = calcCapacity(length, JSString::MAX_LENGTH);
630 MOZ_ASSERT(length <= *capacity);
631 MOZ_ASSERT(*capacity <= JSString::MAX_LENGTH);
632
633 size_t allocSize = *capacity * sizeof(CharT);
634 void* buffer = nursery.allocNurseryOrMallocBuffer(
635 str->zone(), str, allocSize, js::StringBufferArena);
636 if (!buffer) {
637 return false;
638 }
639
640 *chars = static_cast<CharT*>(buffer);
641 *hasStringBuffer = false;
642 return true;
643 }
644
645 using mozilla::StringBuffer;
646
647 static_assert(StringBuffer::IsValidLength<CharT>(JSString::MAX_LENGTH),
648 "JSString length must be valid for StringBuffer");
649
650 // Include extra space for the header and the null-terminator before
651 // calculating the capacity. This ensures we make good use of jemalloc's
652 // bucket sizes. For example, for a Latin1 string with length 2000 we want to
653 // get a capacity of 2039 (chars). With the StringBuffer header (8 bytes) and
654 // the null-terminator this results in an allocation of 2048 bytes.
655 //
656 // Note: the null-terminator will not be included in the extensible string's
657 // capacity field.
658 static_assert(sizeof(StringBuffer) % sizeof(CharT) == 0);
659 static constexpr size_t ExtraChars = sizeof(StringBuffer) / sizeof(CharT) + 1;
660
661 size_t fullCapacity =
662 calcCapacity(length + ExtraChars, JSString::MAX_LENGTH + ExtraChars);
663 *capacity = fullCapacity - ExtraChars;
664 MOZ_ASSERT(length <= *capacity);
665 MOZ_ASSERT(*capacity <= JSString::MAX_LENGTH);
666
667 RefPtr<StringBuffer> buffer = StringBuffer::Alloc(
668 (*capacity + 1) * sizeof(CharT), mozilla::Some(js::StringBufferArena));
669 if (!buffer) {
670 return false;
671 }
672 if (!str->isTenured()) {
673 auto* linear = static_cast<JSLinearString*>(str); // True when we're done.
674 if (!nursery.addExtensibleStringBuffer(linear, buffer)) {
675 return false;
676 }
677 }
678 // Transfer ownership to the caller, where the buffer will be used for the
679 // extensible string.
680 // Note: the null-terminator will be stored in flattenInternal.
681 StringBuffer* buf;
682 buffer.forget(&buf);
683 *chars = static_cast<CharT*>(buf->Data());
684 *hasStringBuffer = true;
685 return true;
686 }
687
688 UniqueLatin1Chars JSRope::copyLatin1Chars(JSContext* maybecx,
689 arena_id_t destArenaId) const {
690 return copyCharsInternal<Latin1Char>(maybecx, destArenaId);
691 }
692
693 UniqueTwoByteChars JSRope::copyTwoByteChars(JSContext* maybecx,
694 arena_id_t destArenaId) const {
695 return copyCharsInternal<char16_t>(maybecx, destArenaId);
696 }
697
698 // Allocate chars for a string. If parameters and conditions allow, this will
699 // try to allocate in the nursery, but this may always fall back to a malloc
700 // allocation. The return value will record where the allocation happened.
701 template <typename CharT>
702 static MOZ_ALWAYS_INLINE JSString::OwnedChars<CharT> AllocChars(JSContext* cx,
703 size_t length,
704 gc::Heap heap) {
705 if (heap == gc::Heap::Default && cx->zone()->allocNurseryStrings()) {
706 MOZ_ASSERT(cx->nursery().isEnabled());
707 void* buffer = cx->nursery().tryAllocateNurseryBuffer(
708 cx->zone(), length * sizeof(CharT), js::StringBufferArena);
709 if (buffer) {
710 using Kind = typename JSString::OwnedChars<CharT>::Kind;
711 return {static_cast<CharT*>(buffer), length, Kind::Nursery};
712 }
713 }
714
715 static_assert(JSString::MIN_BYTES_FOR_BUFFER % sizeof(CharT) == 0);
716
717 if (length < JSString::MIN_BYTES_FOR_BUFFER / sizeof(CharT)) {
718 auto buffer =
719 cx->make_pod_arena_array<CharT>(js::StringBufferArena, length);
720 if (!buffer) {
721 return {};
722 }
723 return {std::move(buffer), length};
724 }
725
726 if (MOZ_UNLIKELY(!mozilla::StringBuffer::IsValidLength<CharT>(length))) {
727 ReportOversizedAllocation(cx, JSMSG_ALLOC_OVERFLOW);
728 return {};
729 }
730
731 // Note: StringBuffers must be null-terminated.
732 RefPtr<mozilla::StringBuffer> buffer = mozilla::StringBuffer::Alloc(
733 (length + 1) * sizeof(CharT), mozilla::Some(js::StringBufferArena));
734 if (!buffer) {
735 ReportOutOfMemory(cx);
736 return {};
737 }
738 static_cast<CharT*>(buffer->Data())[length] = '\0';
739 return {std::move(buffer), length};
740 }
741
742 // Like AllocChars but for atom characters. Does not report an exception on OOM.
743 template <typename CharT>
744 JSString::OwnedChars<CharT> js::AllocAtomCharsValidLength(JSContext* cx,
745 size_t length) {
746 MOZ_ASSERT(cx->zone()->isAtomsZone());
747 MOZ_ASSERT(JSAtom::validateLength(cx, length));
748 MOZ_ASSERT(mozilla::StringBuffer::IsValidLength<CharT>(length));
749
750 static_assert(JSString::MIN_BYTES_FOR_BUFFER % sizeof(CharT) == 0);
751
752 if (length < JSString::MIN_BYTES_FOR_BUFFER / sizeof(CharT)) {
753 auto buffer =
754 cx->make_pod_arena_array<CharT>(js::StringBufferArena, length);
755 if (!buffer) {
756 cx->recoverFromOutOfMemory();
757 return {};
758 }
759 return {std::move(buffer), length};
760 }
761
762 // Note: StringBuffers must be null-terminated.
763 RefPtr<mozilla::StringBuffer> buffer = mozilla::StringBuffer::Alloc(
764 (length + 1) * sizeof(CharT), mozilla::Some(js::StringBufferArena));
765 if (!buffer) {
766 return {};
767 }
768 static_cast<CharT*>(buffer->Data())[length] = '\0';
769 return {std::move(buffer), length};
770 }
771
772 template JSString::OwnedChars<Latin1Char> js::AllocAtomCharsValidLength(
773 JSContext* cx, size_t length);
774 template JSString::OwnedChars<char16_t> js::AllocAtomCharsValidLength(
775 JSContext* cx, size_t length);
776
777 template <typename CharT>
778 UniquePtr<CharT[], JS::FreePolicy> JSRope::copyCharsInternal(
779 JSContext* maybecx, arena_id_t destArenaId) const {
780 // Left-leaning ropes are far more common than right-leaning ropes, so
781 // perform a non-destructive traversal of the rope, right node first,
782 // splatting each node's characters into a contiguous buffer.
783
784 size_t n = length();
785
786 UniquePtr<CharT[], JS::FreePolicy> out;
787 if (maybecx) {
788 out.reset(maybecx->pod_arena_malloc<CharT>(destArenaId, n));
789 } else {
790 out.reset(js_pod_arena_malloc<CharT>(destArenaId, n));
791 }
792
793 if (!out) {
794 return nullptr;
795 }
796
797 Vector<const JSString*, 8, SystemAllocPolicy> nodeStack;
798 const JSString* str = this;
799 CharT* end = out.get() + str->length();
800 while (true) {
801 if (str->isRope()) {
802 if (!nodeStack.append(str->asRope().leftChild())) {
803 if (maybecx) {
804 ReportOutOfMemory(maybecx);
805 }
806 return nullptr;
807 }
808 str = str->asRope().rightChild();
809 } else {
810 end -= str->length();
811 CopyChars(end, str->asLinear());
812 if (nodeStack.empty()) {
813 break;
814 }
815 str = nodeStack.popCopy();
816 }
817 }
818 MOZ_ASSERT(end == out.get());
819
820 return out;
821 }
822
823 template <typename CharT>
824 void AddStringToHash(uint32_t* hash, const CharT* chars, size_t len) {
825 // It's tempting to use |HashString| instead of this loop, but that's
826 // slightly different than our existing implementation for non-ropes. We
827 // want to pretend we have a contiguous set of chars so we need to
828 // accumulate char by char rather than generate a new hash for substring
829 // and then accumulate that.
830 for (size_t i = 0; i < len; i++) {
831 *hash = mozilla::AddToHash(*hash, chars[i]);
832 }
833 }
834
835 void AddStringToHash(uint32_t* hash, const JSString* str) {
836 AutoCheckCannotGC nogc;
837 const auto& s = str->asLinear();
838 if (s.hasLatin1Chars()) {
839 AddStringToHash(hash, s.latin1Chars(nogc), s.length());
840 } else {
841 AddStringToHash(hash, s.twoByteChars(nogc), s.length());
842 }
843 }
844
845 bool JSRope::hash(uint32_t* outHash) const {
846 Vector<const JSString*, 8, SystemAllocPolicy> nodeStack;
847 const JSString* str = this;
848
849 *outHash = 0;
850
851 while (true) {
852 if (str->isRope()) {
853 if (!nodeStack.append(str->asRope().rightChild())) {
854 return false;
855 }
856 str = str->asRope().leftChild();
857 } else {
858 AddStringToHash(outHash, str);
859 if (nodeStack.empty()) {
860 break;
861 }
862 str = nodeStack.popCopy();
863 }
864 }
865
866 return true;
867 }
868
869 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
870 void JSRope::dumpOwnRepresentationFields(js::JSONPrinter& json) const {
871 json.beginObjectProperty("leftChild");
872 leftChild()->dumpRepresentationFields(json);
873 json.endObject();
874
875 json.beginObjectProperty("rightChild");
876 rightChild()->dumpRepresentationFields(json);
877 json.endObject();
878 }
879 #endif
880
881 namespace js {
882
883 template <>
884 void CopyChars(char16_t* dest, const JSLinearString& str) {
885 AutoCheckCannotGC nogc;
886 if (str.hasTwoByteChars()) {
887 PodCopy(dest, str.twoByteChars(nogc), str.length());
888 } else {
889 CopyAndInflateChars(dest, str.latin1Chars(nogc), str.length());
890 }
891 }
892
893 template <>
894 void CopyChars(Latin1Char* dest, const JSLinearString& str) {
895 AutoCheckCannotGC nogc;
896 if (str.hasLatin1Chars()) {
897 PodCopy(dest, str.latin1Chars(nogc), str.length());
898 } else {
899 /*
900 * When we flatten a TwoByte rope, we turn child ropes (including Latin1
901 * ropes) into TwoByte dependent strings. If one of these strings is
902 * also part of another Latin1 rope tree, we can have a Latin1 rope with
903 * a TwoByte descendent and we end up here when we flatten it. Although
904 * the chars are stored as TwoByte, we know they must be in the Latin1
905 * range, so we can safely deflate here.
906 */
907 size_t len = str.length();
908 const char16_t* chars = str.twoByteChars(nogc);
909 auto src = Span(chars, len);
910 MOZ_ASSERT(IsUtf16Latin1(src));
911 LossyConvertUtf16toLatin1(src, AsWritableChars(Span(dest, len)));
912 }
913 }
914
915 } /* namespace js */
916
917 template <typename CharT>
918 static constexpr uint32_t StringFlagsForCharType(uint32_t baseFlags) {
919 if constexpr (std::is_same_v<CharT, char16_t>) {
920 return baseFlags;
921 }
922
923 return baseFlags | JSString::LATIN1_CHARS_BIT;
924 }
925
926 static bool UpdateNurseryBuffersOnTransfer(js::Nursery& nursery,
927 JSExtensibleString* from,
928 JSString* to, void* chars,
929 size_t size) {
930 // Update the list of buffers associated with nursery cells when |buffer| is
931 // moved from string |from| to string |to|, depending on whether those strings
932 // are in the nursery or not.
933
934 if (from->hasStringBuffer()) {
935 // Note: addExtensibleStringBuffer is fallible so we have to call it before
936 // removeExtensibleStringBuffer.
937 // If both strings are in the nursery, avoid updating mallocedBufferBytes to
938 // not trigger an unnecessary minor GC in addMallocedBufferBytes.
939 bool updateMallocBytes = from->isTenured() || to->isTenured();
940 if (!to->isTenured()) {
941 auto* linear = static_cast<JSLinearString*>(to);
942 if (!nursery.addExtensibleStringBuffer(linear, from->stringBuffer(),
943 updateMallocBytes)) {
944 return false;
945 }
946 }
947 if (!from->isTenured()) {
948 nursery.removeExtensibleStringBuffer(from, updateMallocBytes);
949 }
950 return true;
951 }
952
953 if (from->isTenured() && !to->isTenured()) {
954 // Tenured leftmost child is giving its chars buffer to the
955 // nursery-allocated root node.
956 if (!nursery.registerMallocedBuffer(chars, size)) {
957 return false;
958 }
959 } else if (!from->isTenured() && to->isTenured()) {
960 // Leftmost child is giving its nursery-held chars buffer to a
961 // tenured string.
962 nursery.removeMallocedBuffer(chars, size);
963 }
964
965 return true;
966 }
967
968 static bool CanReuseLeftmostBuffer(JSString* leftmostChild, size_t wholeLength,
969 bool hasTwoByteChars, bool isTenured) {
970 if (!leftmostChild->isExtensible()) {
971 return false;
972 }
973
974 JSExtensibleString& str = leftmostChild->asExtensible();
975
976 // Don't mutate the StringBuffer if there are other references to it, possibly
977 // on other threads.
978 if (str.hasStringBuffer() && str.stringBuffer()->IsReadonly()) {
979 return false;
980 }
981
982 if (str.capacity() < wholeLength ||
983 str.hasTwoByteChars() != hasTwoByteChars) {
984 return false;
985 }
986
987 // Don't try to reuse the buffer if the extensible string's characters are in
988 // the nursery and the (root) rope is tenured.
989 if (isTenured && !str.hasStringBuffer() && !str.ownsMallocedChars()) {
990 MOZ_ASSERT(IsInsideNursery(&str));
991 return false;
992 }
993
994 return true;
995 }
996
997 JSLinearString* JSRope::flatten(JSContext* maybecx) {
998 mozilla::Maybe<AutoGeckoProfilerEntry> entry;
999 if (maybecx) {
1000 entry.emplace(maybecx, "JSRope::flatten");
1001 }
1002
1003 JSLinearString* str = flattenInternal();
1004 if (!str && maybecx) {
1005 ReportOutOfMemory(maybecx);
1006 }
1007
1008 return str;
1009 }
1010
1011 JSLinearString* JSRope::flattenInternal() {
1012 if (zone()->needsIncrementalBarrier()) {
1013 return flattenInternal<WithIncrementalBarrier>();
1014 }
1015
1016 return flattenInternal<NoBarrier>();
1017 }
1018
1019 template <JSRope::UsingBarrier usingBarrier>
1020 JSLinearString* JSRope::flattenInternal() {
1021 if (hasTwoByteChars()) {
1022 return flattenInternal<usingBarrier, char16_t>(this);
1023 }
1024
1025 return flattenInternal<usingBarrier, Latin1Char>(this);
1026 }
1027
1028 template <JSRope::UsingBarrier usingBarrier, typename CharT>
1029 /* static */
1030 JSLinearString* JSRope::flattenInternal(JSRope* root) {
1031 /*
1032 * Consider the DAG of JSRopes rooted at |root|, with non-JSRopes as
1033 * its leaves. Mutate the root JSRope into a JSExtensibleString containing
1034 * the full flattened text that the root represents, and mutate all other
1035 * JSRopes in the interior of the DAG into JSDependentStrings that refer to
1036 * this new JSExtensibleString.
1037 *
1038 * If the leftmost leaf of our DAG is a JSExtensibleString, consider
1039 * stealing its buffer for use in our new root, and transforming it into a
1040 * JSDependentString too. Do not mutate any of the other leaves.
1041 *
1042 * Perform a depth-first dag traversal, splatting each node's characters
1043 * into a contiguous buffer. Visit each rope node three times:
1044 * 1. record position in the buffer and recurse into left child;
1045 * 2. recurse into the right child;
1046 * 3. transform the node into a dependent string.
1047 * To avoid maintaining a stack, tree nodes are mutated to indicate how many
1048 * times they have been visited. Since ropes can be dags, a node may be
1049 * encountered multiple times during traversal. However, step 3 above leaves
1050 * a valid dependent string, so everything works out.
1051 *
1052 * While ropes avoid all sorts of quadratic cases with string concatenation,
1053 * they can't help when ropes are immediately flattened. One idiomatic case
1054 * that we'd like to keep linear (and has traditionally been linear in SM
1055 * and other JS engines) is:
1056 *
1057 * while (...) {
1058 * s += ...
1059 * s.flatten
1060 * }
1061 *
1062 * Two behaviors accomplish this:
1063 *
1064 * - When the leftmost non-rope in the DAG we're flattening is a
1065 * JSExtensibleString with sufficient capacity to hold the entire
1066 * flattened string, we just flatten the DAG into its buffer. Then, when
1067 * we transform the root of the DAG from a JSRope into a
1068 * JSExtensibleString, we steal that buffer, and change the victim from a
1069 * JSExtensibleString to a JSDependentString. In this case, the left-hand
1070 * side of the string never needs to be copied.
1071 *
1072 * - Otherwise, we round up the total flattened size and create a fresh
1073 * JSExtensibleString with that much capacity. If this in turn becomes the
1074 * leftmost leaf of a subsequent flatten, we will hopefully be able to
1075 * fill it, as in the case above.
1076 *
1077 * Note that, even though the code for creating JSDependentStrings avoids
1078 * creating dependents of dependents, we can create that situation here: the
1079 * JSExtensibleStrings we transform into JSDependentStrings might have
1080 * JSDependentStrings pointing to them already. Stealing the buffer doesn't
1081 * change its address, only its owning JSExtensibleString, so all chars()
1082 * pointers in the JSDependentStrings are still valid.
1083 *
1084 * This chain of dependent strings could be problematic if the base string
1085 * moves, either because it was initially allocated in the nursery or it
1086 * gets deduplicated, because you might have a dependent ->
1087 * tenured dependent -> nursery base string, and the store buffer would
1088 * only capture the latter edge. Prevent this case from happening by
1089 * marking the root as nondeduplicatable if the extensible string
1090 * optimization applied.
1091 */
1092 const size_t wholeLength = root->length();
1093 size_t wholeCapacity;
1094 CharT* wholeChars;
1095 uint32_t newRootFlags = 0;
1096
1097 AutoCheckCannotGC nogc;
1098
1099 Nursery& nursery = root->runtimeFromMainThread()->gc.nursery();
1100
1101 /* Find the left most string, containing the first string. */
1102 JSRope* leftmostRope = root;
1103 while (leftmostRope->leftChild()->isRope()) {
1104 leftmostRope = &leftmostRope->leftChild()->asRope();
1105 }
1106 JSString* leftmostChild = leftmostRope->leftChild();
1107
1108 bool reuseLeftmostBuffer = CanReuseLeftmostBuffer(
1109 leftmostChild, wholeLength, std::is_same_v<CharT, char16_t>,
1110 root->isTenured());
1111
1112 bool hasStringBuffer = false;
1113 if (reuseLeftmostBuffer) {
1114 JSExtensibleString& left = leftmostChild->asExtensible();
1115 wholeCapacity = left.capacity();
1116 wholeChars = const_cast<CharT*>(left.nonInlineChars<CharT>(nogc));
1117 hasStringBuffer = left.hasStringBuffer();
1118
1119 // Nursery::registerMallocedBuffer is fallible, so attempt it first before
1120 // doing anything irreversible.
1121 if (!UpdateNurseryBuffersOnTransfer(nursery, &left, root, wholeChars,
1122 wholeCapacity * sizeof(CharT))) {
1123 return nullptr;
1124 }
1125 } else {
1126 // If we can't reuse the leftmost child's buffer, allocate a new one.
1127 if (!AllocCharsForFlatten(nursery, root, wholeLength, &wholeChars,
1128 &wholeCapacity, &hasStringBuffer)) {
1129 return nullptr;
1130 }
1131 }
1132
1133 JSRope* str = root;
1134 CharT* pos = wholeChars;
1135
1136 JSRope* parent = nullptr;
1137 uint32_t parentFlag = 0;
1138
1139 first_visit_node: {
1140 MOZ_ASSERT_IF(str != root, parent && parentFlag);
1141 MOZ_ASSERT(!str->asRope().isBeingFlattened());
1142
1143 ropeBarrierDuringFlattening<usingBarrier>(str);
1144
1145 JSString& left = *str->d.s.u2.left;
1146 str->d.s.u2.parent = parent;
1147 str->setFlagBit(parentFlag);
1148 parent = nullptr;
1149 parentFlag = 0;
1150
1151 if (left.isRope()) {
1152 /* Return to this node when 'left' done, then goto visit_right_child. */
1153 parent = str;
1154 parentFlag = FLATTEN_VISIT_RIGHT;
1155 str = &left.asRope();
1156 goto first_visit_node;
1157 }
1158 if (!(reuseLeftmostBuffer && pos == wholeChars)) {
1159 CopyChars(pos, left.asLinear());
1160 }
1161 pos += left.length();
1162 }
1163
1164 visit_right_child: {
1165 JSString& right = *str->d.s.u3.right;
1166 if (right.isRope()) {
1167 /* Return to this node when 'right' done, then goto finish_node. */
1168 parent = str;
1169 parentFlag = FLATTEN_FINISH_NODE;
1170 str = &right.asRope();
1171 goto first_visit_node;
1172 }
1173 CopyChars(pos, right.asLinear());
1174 pos += right.length();
1175 }
1176
1177 finish_node: {
1178 if (str == root) {
1179 goto finish_root;
1180 }
1181
1182 MOZ_ASSERT(pos >= wholeChars);
1183 CharT* chars = pos - str->length();
1184 JSRope* strParent = str->d.s.u2.parent;
1185 str->setNonInlineChars(chars, /* usesStringBuffer = */ false);
1186
1187 MOZ_ASSERT(str->asRope().isBeingFlattened());
1188 mozilla::DebugOnly<bool> visitRight = str->flags() & FLATTEN_VISIT_RIGHT;
1189 bool finishNode = str->flags() & FLATTEN_FINISH_NODE;
1190 MOZ_ASSERT(visitRight != finishNode);
1191
1192 // This also clears the flags related to flattening.
1193 str->setLengthAndFlags(str->length(),
1194 StringFlagsForCharType<CharT>(INIT_DEPENDENT_FLAGS));
1195 str->d.s.u3.base =
1196 reinterpret_cast<JSLinearString*>(root); /* will be true on exit */
1197 newRootFlags |= DEPENDED_ON_BIT;
1198
1199 // Every interior (rope) node in the rope's tree will be visited during
1200 // the traversal and post-barriered here, so earlier additions of
1201 // dependent.base -> root pointers are handled by this barrier as well.
1202 //
1203 // The only time post-barriers need do anything is when the root is in
1204 // the nursery. Note that the root was a rope but will be an extensible
1205 // string when we return, so it will not point to any strings and need
1206 // not be barriered.
1207 if (str->isTenured() && !root->isTenured()) {
1208 root->storeBuffer()->putWholeCell(str);
1209 }
1210
1211 str = strParent;
1212 if (finishNode) {
1213 goto finish_node;
1214 }
1215 MOZ_ASSERT(visitRight);
1216 goto visit_right_child;
1217 }
1218
1219 finish_root:
1220 // We traversed all the way back up to the root so we're finished.
1221 MOZ_ASSERT(str == root);
1222 MOZ_ASSERT(pos == wholeChars + wholeLength);
1223
1224 uint32_t flags = StringFlagsForCharType<CharT>(EXTENSIBLE_FLAGS);
1225 if (hasStringBuffer) {
1226 flags |= HAS_STRING_BUFFER_BIT;
1227 wholeChars[wholeLength] = '\0';
1228 }
1229 root->setLengthAndFlags(wholeLength, flags);
1230 root->setNonInlineChars(wholeChars, hasStringBuffer);
1231 root->d.s.u3.capacity = wholeCapacity;
1232 AddCellMemory(root, wholeCapacity * sizeof(CharT), MemoryUse::StringContents);
1233
1234 if (reuseLeftmostBuffer) {
1235 // Remove memory association for left node we're about to make into a
1236 // dependent string.
1237 JSString& left = *leftmostChild;
1238 RemoveCellMemory(&left, left.allocSize(), MemoryUse::StringContents);
1239
1240 // Inherit NON_DEDUP_BIT from the leftmost string.
1241 newRootFlags |= left.flags() & NON_DEDUP_BIT;
1242
1243 // Set root's DEPENDED_ON_BIT because the leftmost string is now a
1244 // dependent.
1245 newRootFlags |= DEPENDED_ON_BIT;
1246
1247 uint32_t flags = INIT_DEPENDENT_FLAGS;
1248 if (left.inStringToAtomCache()) {
1249 flags |= IN_STRING_TO_ATOM_CACHE;
1250 }
1251 // If left was depended on, we need to make sure we preserve that. Even
1252 // though the string that depended on left's buffer will now depend on
1253 // root's buffer, if left is the only edge to root, replacing left with an
1254 // atom ref would break that edge and allow root's buffer to be freed.
1255 if (left.isDependedOn()) {
1256 flags |= DEPENDED_ON_BIT;
1257 }
1258 left.setLengthAndFlags(left.length(), StringFlagsForCharType<CharT>(flags));
1259 left.d.s.u3.base = &root->asLinear();
1260 if (left.isTenured() && !root->isTenured()) {
1261 // leftmost child -> root is a tenured -> nursery edge. Put the leftmost
1262 // child in the store buffer and prevent the root's chars from moving or
1263 // being freed (because the leftmost child may have a tenured dependent
1264 // string that cannot be updated.)
1265 root->storeBuffer()->putWholeCell(&left);
1266 newRootFlags |= NON_DEDUP_BIT;
1267 }
1268 }
1269
1270 root->setHeaderFlagBit(newRootFlags);
1271
1272 return &root->asLinear();
1273 }
1274
1275 template <JSRope::UsingBarrier usingBarrier>
1276 /* static */
1277 inline void JSRope::ropeBarrierDuringFlattening(JSRope* rope) {
1278 MOZ_ASSERT(!rope->isBeingFlattened());
1279 if constexpr (usingBarrier) {
1280 gc::PreWriteBarrierDuringFlattening(rope->leftChild());
1281 gc::PreWriteBarrierDuringFlattening(rope->rightChild());
1282 }
1283 }
1284
1285 template <AllowGC allowGC>
1286 static JSLinearString* EnsureLinear(
1287 JSContext* cx,
1288 typename MaybeRooted<JSString*, allowGC>::HandleType string) {
1289 JSLinearString* linear = string->ensureLinear(cx);
1290 // Don't report an exception if GC is not allowed, just return nullptr.
1291 if (!linear && !allowGC) {
1292 cx->recoverFromOutOfMemory();
1293 }
1294 return linear;
1295 }
1296
1297 template <AllowGC allowGC>
1298 JSString* js::ConcatStrings(
1299 JSContext* cx, typename MaybeRooted<JSString*, allowGC>::HandleType left,
1300 typename MaybeRooted<JSString*, allowGC>::HandleType right, gc::Heap heap) {
1301 MOZ_ASSERT_IF(!left->isAtom(), cx->isInsideCurrentZone(left));
1302 MOZ_ASSERT_IF(!right->isAtom(), cx->isInsideCurrentZone(right));
1303
1304 size_t leftLen = left->length();
1305 if (leftLen == 0) {
1306 return right;
1307 }
1308
1309 size_t rightLen = right->length();
1310 if (rightLen == 0) {
1311 return left;
1312 }
1313
1314 size_t wholeLength = leftLen + rightLen;
1315 if (MOZ_UNLIKELY(wholeLength > JSString::MAX_LENGTH)) {
1316 // Don't report an exception if GC is not allowed, just return nullptr.
1317 if (allowGC) {
1318 js::ReportOversizedAllocation(cx, JSMSG_ALLOC_OVERFLOW);
1319 }
1320 return nullptr;
1321 }
1322
1323 bool isLatin1 = left->hasLatin1Chars() && right->hasLatin1Chars();
1324 bool canUseInline = isLatin1
1325 ? JSInlineString::lengthFits<Latin1Char>(wholeLength)
1326 : JSInlineString::lengthFits<char16_t>(wholeLength);
1327 if (canUseInline) {
1328 Latin1Char* latin1Buf = nullptr; // initialize to silence GCC warning
1329 char16_t* twoByteBuf = nullptr; // initialize to silence GCC warning
1330 JSInlineString* str =
1331 isLatin1
1332 ? AllocateInlineString<allowGC>(cx, wholeLength, &latin1Buf, heap)
1333 : AllocateInlineString<allowGC>(cx, wholeLength, &twoByteBuf, heap);
1334 if (!str) {
1335 return nullptr;
1336 }
1337
1338 AutoCheckCannotGC nogc;
1339 JSLinearString* leftLinear = EnsureLinear<allowGC>(cx, left);
1340 if (!leftLinear) {
1341 return nullptr;
1342 }
1343 JSLinearString* rightLinear = EnsureLinear<allowGC>(cx, right);
1344 if (!rightLinear) {
1345 return nullptr;
1346 }
1347
1348 if (isLatin1) {
1349 PodCopy(latin1Buf, leftLinear->latin1Chars(nogc), leftLen);
1350 PodCopy(latin1Buf + leftLen, rightLinear->latin1Chars(nogc), rightLen);
1351 } else {
1352 if (leftLinear->hasTwoByteChars()) {
1353 PodCopy(twoByteBuf, leftLinear->twoByteChars(nogc), leftLen);
1354 } else {
1355 CopyAndInflateChars(twoByteBuf, leftLinear->latin1Chars(nogc), leftLen);
1356 }
1357 if (rightLinear->hasTwoByteChars()) {
1358 PodCopy(twoByteBuf + leftLen, rightLinear->twoByteChars(nogc),
1359 rightLen);
1360 } else {
1361 CopyAndInflateChars(twoByteBuf + leftLen,
1362 rightLinear->latin1Chars(nogc), rightLen);
1363 }
1364 }
1365
1366 return str;
1367 }
1368
1369 return JSRope::new_<allowGC>(cx, left, right, wholeLength, heap);
1370 }
1371
1372 template JSString* js::ConcatStrings<CanGC>(JSContext* cx, HandleString left,
1373 HandleString right, gc::Heap heap);
1374
1375 template JSString* js::ConcatStrings<NoGC>(JSContext* cx, JSString* const& left,
1376 JSString* const& right,
1377 gc::Heap heap);
1378
1379 bool JSLinearString::hasCharsInCollectedNurseryRegion() const {
1380 if (isPermanentAtom()) {
1381 // Nursery::inCollectedRegion(void*) should only be called on the nursery's
1382 // main thread to avoid races. Permanent atoms can be shared with worker
1383 // threads but atoms are never allocated in the nursery.
1384 MOZ_ASSERT(isTenured());
1385 return false;
1386 }
1387 auto& nursery = runtimeFromMainThread()->gc.nursery();
1388 if (isInline()) {
1389 return nursery.inCollectedRegion(this);
1390 }
1391 return nursery.inCollectedRegion(nonInlineCharsRaw());
1392 }
1393
1394 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1395 void JSDependentString::dumpOwnRepresentationFields(
1396 js::JSONPrinter& json) const {
1397 json.property("baseOffset", baseOffset());
1398 json.beginObjectProperty("base");
1399 base()->dumpRepresentationFields(json);
1400 json.endObject();
1401 }
1402 #endif
1403
1404 bool js::EqualChars(const JSLinearString* str1, const JSLinearString* str2) {
1405 // Assert this isn't called for strings the caller should handle with a fast
1406 // path.
1407 MOZ_ASSERT(str1->length() == str2->length());
1408 MOZ_ASSERT(str1 != str2);
1409 MOZ_ASSERT(!str1->isAtom() || !str2->isAtom());
1410
1411 size_t len = str1->length();
1412
1413 AutoCheckCannotGC nogc;
1414 if (str1->hasTwoByteChars()) {
1415 if (str2->hasTwoByteChars()) {
1416 return EqualChars(str1->twoByteChars(nogc), str2->twoByteChars(nogc),
1417 len);
1418 }
1419
1420 return EqualChars(str2->latin1Chars(nogc), str1->twoByteChars(nogc), len);
1421 }
1422
1423 if (str2->hasLatin1Chars()) {
1424 return EqualChars(str1->latin1Chars(nogc), str2->latin1Chars(nogc), len);
1425 }
1426
1427 return EqualChars(str1->latin1Chars(nogc), str2->twoByteChars(nogc), len);
1428 }
1429
1430 bool js::HasSubstringAt(const JSLinearString* text, const JSLinearString* pat,
1431 size_t start) {
1432 MOZ_ASSERT(start + pat->length() <= text->length());
1433
1434 size_t patLen = pat->length();
1435
1436 AutoCheckCannotGC nogc;
1437 if (text->hasLatin1Chars()) {
1438 const Latin1Char* textChars = text->latin1Chars(nogc) + start;
1439 if (pat->hasLatin1Chars()) {
1440 return EqualChars(textChars, pat->latin1Chars(nogc), patLen);
1441 }
1442
1443 return EqualChars(textChars, pat->twoByteChars(nogc), patLen);
1444 }
1445
1446 const char16_t* textChars = text->twoByteChars(nogc) + start;
1447 if (pat->hasTwoByteChars()) {
1448 return EqualChars(textChars, pat->twoByteChars(nogc), patLen);
1449 }
1450
1451 return EqualChars(pat->latin1Chars(nogc), textChars, patLen);
1452 }
1453
1454 bool js::EqualStrings(JSContext* cx, JSString* str1, JSString* str2,
1455 bool* result) {
1456 if (str1 == str2) {
1457 *result = true;
1458 return true;
1459 }
1460 if (str1->length() != str2->length()) {
1461 *result = false;
1462 return true;
1463 }
1464 if (str1->isAtom() && str2->isAtom()) {
1465 *result = false;
1466 return true;
1467 }
1468
1469 JSLinearString* linear1 = str1->ensureLinear(cx);
1470 if (!linear1) {
1471 return false;
1472 }
1473 JSLinearString* linear2 = str2->ensureLinear(cx);
1474 if (!linear2) {
1475 return false;
1476 }
1477
1478 *result = EqualChars(linear1, linear2);
1479 return true;
1480 }
1481
1482 bool js::EqualStrings(const JSLinearString* str1, const JSLinearString* str2) {
1483 if (str1 == str2) {
1484 return true;
1485 }
1486 if (str1->length() != str2->length()) {
1487 return false;
1488 }
1489 if (str1->isAtom() && str2->isAtom()) {
1490 return false;
1491 }
1492 return EqualChars(str1, str2);
1493 }
1494
1495 int32_t js::CompareChars(const char16_t* s1, size_t len1,
1496 const JSLinearString* s2) {
1497 AutoCheckCannotGC nogc;
1498 return s2->hasLatin1Chars()
1499 ? CompareChars(s1, len1, s2->latin1Chars(nogc), s2->length())
1500 : CompareChars(s1, len1, s2->twoByteChars(nogc), s2->length());
1501 }
1502
1503 static int32_t CompareStringsImpl(const JSLinearString* str1,
1504 const JSLinearString* str2) {
1505 size_t len1 = str1->length();
1506 size_t len2 = str2->length();
1507
1508 AutoCheckCannotGC nogc;
1509 if (str1->hasLatin1Chars()) {
1510 const Latin1Char* chars1 = str1->latin1Chars(nogc);
1511 return str2->hasLatin1Chars()
1512 ? CompareChars(chars1, len1, str2->latin1Chars(nogc), len2)
1513 : CompareChars(chars1, len1, str2->twoByteChars(nogc), len2);
1514 }
1515
1516 const char16_t* chars1 = str1->twoByteChars(nogc);
1517 return str2->hasLatin1Chars()
1518 ? CompareChars(chars1, len1, str2->latin1Chars(nogc), len2)
1519 : CompareChars(chars1, len1, str2->twoByteChars(nogc), len2);
1520 }
1521
1522 bool js::CompareStrings(JSContext* cx, JSString* str1, JSString* str2,
1523 int32_t* result) {
1524 MOZ_ASSERT(str1);
1525 MOZ_ASSERT(str2);
1526
1527 if (str1 == str2) {
1528 *result = 0;
1529 return true;
1530 }
1531
1532 JSLinearString* linear1 = str1->ensureLinear(cx);
1533 if (!linear1) {
1534 return false;
1535 }
1536
1537 JSLinearString* linear2 = str2->ensureLinear(cx);
1538 if (!linear2) {
1539 return false;
1540 }
1541
1542 *result = CompareStringsImpl(linear1, linear2);
1543 return true;
1544 }
1545
1546 int32_t js::CompareStrings(const JSLinearString* str1,
1547 const JSLinearString* str2) {
1548 MOZ_ASSERT(str1);
1549 MOZ_ASSERT(str2);
1550
1551 if (str1 == str2) {
1552 return 0;
1553 }
1554 return CompareStringsImpl(str1, str2);
1555 }
1556
1557 bool js::StringIsAscii(const JSLinearString* str) {
1558 JS::AutoCheckCannotGC nogc;
1559 if (str->hasLatin1Chars()) {
1560 return mozilla::IsAscii(
1561 AsChars(Span(str->latin1Chars(nogc), str->length())));
1562 }
1563 return mozilla::IsAscii(Span(str->twoByteChars(nogc), str->length()));
1564 }
1565
1566 bool js::StringEqualsAscii(const JSLinearString* str, const char* asciiBytes) {
1567 return StringEqualsAscii(str, asciiBytes, strlen(asciiBytes));
1568 }
1569
1570 bool js::StringEqualsAscii(const JSLinearString* str, const char* asciiBytes,
1571 size_t length) {
1572 MOZ_ASSERT(JS::StringIsASCII(Span(asciiBytes, length)));
1573
1574 if (length != str->length()) {
1575 return false;
1576 }
1577
1578 const Latin1Char* latin1 = reinterpret_cast<const Latin1Char*>(asciiBytes);
1579
1580 AutoCheckCannotGC nogc;
1581 return str->hasLatin1Chars()
1582 ? EqualChars(latin1, str->latin1Chars(nogc), length)
1583 : EqualChars(latin1, str->twoByteChars(nogc), length);
1584 }
1585
1586 template <typename CharT>
1587 bool js::CheckStringIsIndex(const CharT* s, size_t length, uint32_t* indexp) {
1588 MOZ_ASSERT(length > 0);
1589 MOZ_ASSERT(length <= UINT32_CHAR_BUFFER_LENGTH);
1590 MOZ_ASSERT(IsAsciiDigit(*s),
1591 "caller's fast path must have checked first char");
1592
1593 RangedPtr<const CharT> cp(s, length);
1594 const RangedPtr<const CharT> end(s + length, s, length);
1595
1596 uint32_t index = AsciiDigitToNumber(*cp++);
1597 uint32_t oldIndex = 0;
1598 uint32_t c = 0;
1599
1600 if (index != 0) {
1601 // Consume remaining characters only if the first character isn't '0'.
1602 while (cp < end && IsAsciiDigit(*cp)) {
1603 oldIndex = index;
1604 c = AsciiDigitToNumber(*cp);
1605 index = 10 * index + c;
1606 cp++;
1607 }
1608 }
1609
1610 // It's not an integer index if there are characters after the number.
1611 if (cp != end) {
1612 return false;
1613 }
1614
1615 // Look out for "4294967295" and larger-number strings that fit in
1616 // UINT32_CHAR_BUFFER_LENGTH: only unsigned 32-bit integers less than or equal
1617 // to MAX_ARRAY_INDEX shall pass.
1618 if (oldIndex < MAX_ARRAY_INDEX / 10 ||
1619 (oldIndex == MAX_ARRAY_INDEX / 10 && c <= (MAX_ARRAY_INDEX % 10))) {
1620 MOZ_ASSERT(index <= MAX_ARRAY_INDEX);
1621 *indexp = index;
1622 return true;
1623 }
1624
1625 return false;
1626 }
1627
1628 template bool js::CheckStringIsIndex(const Latin1Char* s, size_t length,
1629 uint32_t* indexp);
1630 template bool js::CheckStringIsIndex(const char16_t* s, size_t length,
1631 uint32_t* indexp);
1632
1633 template <typename CharT>
1634 static uint32_t AtomCharsToIndex(const CharT* s, size_t length) {
1635 // Chars are known to be a valid index value (as determined by
1636 // CheckStringIsIndex) that didn't fit in the "index value" bits in the
1637 // header.
1638
1639 MOZ_ASSERT(length > 0);
1640 MOZ_ASSERT(length <= UINT32_CHAR_BUFFER_LENGTH);
1641
1642 RangedPtr<const CharT> cp(s, length);
1643 const RangedPtr<const CharT> end(s + length, s, length);
1644
1645 MOZ_ASSERT(IsAsciiDigit(*cp));
1646 uint32_t index = AsciiDigitToNumber(*cp++);
1647 MOZ_ASSERT(index != 0);
1648
1649 while (cp < end) {
1650 MOZ_ASSERT(IsAsciiDigit(*cp));
1651 index = 10 * index + AsciiDigitToNumber(*cp);
1652 cp++;
1653 }
1654
1655 MOZ_ASSERT(index <= MAX_ARRAY_INDEX);
1656 return index;
1657 }
1658
1659 uint32_t JSAtom::getIndexSlow() const {
1660 MOZ_ASSERT(isIndex());
1661 MOZ_ASSERT(!hasIndexValue());
1662
1663 size_t len = length();
1664
1665 AutoCheckCannotGC nogc;
1666 return hasLatin1Chars() ? AtomCharsToIndex(latin1Chars(nogc), len)
1667 : AtomCharsToIndex(twoByteChars(nogc), len);
1668 }
1669
1670 // Ensure that the incoming s.chars pointer is stable, as in, it cannot be
1671 // changed even across a GC. That requires that the string that owns the chars
1672 // not be collected or deduplicated.
1673 void AutoStableStringChars::holdStableChars(JSLinearString* s) {
1674 while (s->hasBase()) {
1675 s = s->base();
1676 }
1677 if (!s->isTenured()) {
1678 s->setNonDeduplicatable();
1679 }
1680 s_ = s;
1681 }
1682
1683 bool AutoStableStringChars::init(JSContext* cx, JSString* s) {
1684 Rooted<JSLinearString*> linearString(cx, s->ensureLinear(cx));
1685 if (!linearString) {
1686 return false;
1687 }
1688
1689 linearString->setDependedOn();
1690
1691 MOZ_ASSERT(state_ == Uninitialized);
1692 length_ = linearString->length();
1693
1694 // Inline and nursery-allocated chars may move during a GC, so copy them
1695 // out into a temporary malloced buffer. Note that we cannot update the
1696 // string itself with a malloced buffer, because there may be dependent
1697 // strings that are using the original chars.
1698 if (linearString->hasMovableChars()) {
1699 return linearString->hasTwoByteChars() ? copyTwoByteChars(cx, linearString)
1700 : copyLatin1Chars(cx, linearString);
1701 }
1702
1703 if (linearString->hasLatin1Chars()) {
1704 state_ = Latin1;
1705 latin1Chars_ = linearString->rawLatin1Chars();
1706 } else {
1707 state_ = TwoByte;
1708 twoByteChars_ = linearString->rawTwoByteChars();
1709 }
1710
1711 holdStableChars(linearString);
1712 return true;
1713 }
1714
1715 bool AutoStableStringChars::initTwoByte(JSContext* cx, JSString* s) {
1716 Rooted<JSLinearString*> linearString(cx, s->ensureLinear(cx));
1717 if (!linearString) {
1718 return false;
1719 }
1720
1721 linearString->setDependedOn();
1722
1723 MOZ_ASSERT(state_ == Uninitialized);
1724 length_ = linearString->length();
1725
1726 if (linearString->hasLatin1Chars()) {
1727 return copyAndInflateLatin1Chars(cx, linearString);
1728 }
1729
1730 // Copy movable chars since they may be moved by GC (see above).
1731 if (linearString->hasMovableChars()) {
1732 return copyTwoByteChars(cx, linearString);
1733 }
1734
1735 state_ = TwoByte;
1736 twoByteChars_ = linearString->rawTwoByteChars();
1737
1738 holdStableChars(linearString);
1739 return true;
1740 }
1741
1742 template <typename T>
1743 T* AutoStableStringChars::allocOwnChars(JSContext* cx, size_t count) {
1744 static_assert(
1745 InlineCapacity >=
1746 sizeof(JS::Latin1Char) * JSFatInlineString::MAX_LENGTH_LATIN1 &&
1747 InlineCapacity >=
1748 sizeof(char16_t) * JSFatInlineString::MAX_LENGTH_TWO_BYTE,
1749 "InlineCapacity too small to hold fat inline strings");
1750
1751 static_assert((JSString::MAX_LENGTH &
1752 mozilla::tl::MulOverflowMask<sizeof(T)>::value) == 0,
1753 "Size calculation can overflow");
1754 MOZ_ASSERT(count <= JSString::MAX_LENGTH);
1755 size_t size = sizeof(T) * count;
1756
1757 ownChars_.emplace(cx);
1758 if (!ownChars_->resize(size)) {
1759 ownChars_.reset();
1760 return nullptr;
1761 }
1762
1763 return reinterpret_cast<T*>(ownChars_->begin());
1764 }
1765
1766 bool AutoStableStringChars::copyAndInflateLatin1Chars(
1767 JSContext* cx, Handle<JSLinearString*> linearString) {
1768 MOZ_ASSERT(state_ == Uninitialized);
1769 MOZ_ASSERT(s_ == nullptr);
1770
1771 char16_t* chars = allocOwnChars<char16_t>(cx, length_);
1772 if (!chars) {
1773 return false;
1774 }
1775
1776 // Copy |src[0..length]| to |dest[0..length]| when copying doesn't narrow and
1777 // therefore can't lose information.
1778 auto src = AsChars(Span(linearString->rawLatin1Chars(), length_));
1779 auto dest = Span(chars, length_);
1780 ConvertLatin1toUtf16(src, dest);
1781
1782 state_ = TwoByte;
1783 twoByteChars_ = chars;
1784 s_ = linearString;
1785 return true;
1786 }
1787
1788 bool AutoStableStringChars::copyLatin1Chars(
1789 JSContext* cx, Handle<JSLinearString*> linearString) {
1790 MOZ_ASSERT(state_ == Uninitialized);
1791 MOZ_ASSERT(s_ == nullptr);
1792
1793 JS::Latin1Char* chars = allocOwnChars<JS::Latin1Char>(cx, length_);
1794 if (!chars) {
1795 return false;
1796 }
1797
1798 PodCopy(chars, linearString->rawLatin1Chars(), length_);
1799
1800 state_ = Latin1;
1801 latin1Chars_ = chars;
1802 s_ = linearString;
1803 return true;
1804 }
1805
1806 bool AutoStableStringChars::copyTwoByteChars(
1807 JSContext* cx, Handle<JSLinearString*> linearString) {
1808 MOZ_ASSERT(state_ == Uninitialized);
1809 MOZ_ASSERT(s_ == nullptr);
1810
1811 char16_t* chars = allocOwnChars<char16_t>(cx, length_);
1812 if (!chars) {
1813 return false;
1814 }
1815
1816 PodCopy(chars, linearString->rawTwoByteChars(), length_);
1817
1818 state_ = TwoByte;
1819 twoByteChars_ = chars;
1820 s_ = linearString;
1821 return true;
1822 }
1823
1824 template <>
1825 bool JS::SourceText<char16_t>::initMaybeBorrowed(
1826 JSContext* cx, JS::AutoStableStringChars& linearChars) {
1827 MOZ_ASSERT(linearChars.isTwoByte(),
1828 "AutoStableStringChars must be initialized with char16_t");
1829
1830 const char16_t* chars = linearChars.twoByteChars();
1831 size_t length = linearChars.length();
1832 JS::SourceOwnership ownership = linearChars.maybeGiveOwnershipToCaller()
1833 ? JS::SourceOwnership::TakeOwnership
1834 : JS::SourceOwnership::Borrowed;
1835 return initImpl(cx, chars, length, ownership);
1836 }
1837
1838 template <>
1839 bool JS::SourceText<char16_t>::initMaybeBorrowed(
1840 JS::FrontendContext* fc, JS::AutoStableStringChars& linearChars) {
1841 MOZ_ASSERT(linearChars.isTwoByte(),
1842 "AutoStableStringChars must be initialized with char16_t");
1843
1844 const char16_t* chars = linearChars.twoByteChars();
1845 size_t length = linearChars.length();
1846 JS::SourceOwnership ownership = linearChars.maybeGiveOwnershipToCaller()
1847 ? JS::SourceOwnership::TakeOwnership
1848 : JS::SourceOwnership::Borrowed;
1849 return initImpl(fc, chars, length, ownership);
1850 }
1851
1852 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1853 void JSAtom::dump(js::GenericPrinter& out) {
1854 out.printf("JSAtom* (%p) = ", (void*)this);
1855 this->JSString::dump(out);
1856 }
1857
1858 void JSAtom::dump() {
1859 Fprinter out(stderr);
1860 dump(out);
1861 }
1862
1863 void JSExternalString::dumpOwnRepresentationFields(
1864 js::JSONPrinter& json) const {
1865 json.formatProperty("callbacks", "(JSExternalStringCallbacks*)0x%p",
1866 callbacks());
1867 }
1868 #endif /* defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW) */
1869
1870 template <JS::ContractBaseChain contract>
1871 static JSLinearString* NewDependentStringHelper(JSContext* cx,
1872 JSString* baseArg, size_t start,
1873 size_t length, gc::Heap heap) {
1874 if (length == 0) {
1875 return cx->emptyString();
1876 }
1877
1878 JSLinearString* base = baseArg->ensureLinear(cx);
1879 if (!base) {
1880 return nullptr;
1881 }
1882
1883 if (start == 0 && length == base->length()) {
1884 return base;
1885 }
1886
1887 bool useInline;
1888 if (base->hasTwoByteChars()) {
1889 AutoCheckCannotGC nogc;
1890 const char16_t* chars = base->twoByteChars(nogc) + start;
1891 if (JSLinearString* staticStr = cx->staticStrings().lookup(chars, length)) {
1892 return staticStr;
1893 }
1894 useInline = JSInlineString::lengthFits<char16_t>(length);
1895 } else {
1896 AutoCheckCannotGC nogc;
1897 const Latin1Char* chars = base->latin1Chars(nogc) + start;
1898 if (JSLinearString* staticStr = cx->staticStrings().lookup(chars, length)) {
1899 return staticStr;
1900 }
1901 useInline = JSInlineString::lengthFits<Latin1Char>(length);
1902 }
1903
1904 if (useInline) {
1905 Rooted<JSLinearString*> rootedBase(cx, base);
1906
1907 // Do not create a dependent string that would fit into an inline string.
1908 // First, that could create a string dependent on an inline base string's
1909 // chars, which would be an awkward moving-GC hazard. Second, this makes
1910 // it more likely to have a very short string keep a very long string alive.
1911 if (base->hasTwoByteChars()) {
1912 return NewInlineString<char16_t>(cx, rootedBase, start, length, heap);
1913 }
1914 return NewInlineString<Latin1Char>(cx, rootedBase, start, length, heap);
1915 }
1916
1917 return JSDependentString::newImpl_<contract>(cx, base, start, length, heap);
1918 }
1919
1920 JSLinearString* js::NewDependentString(JSContext* cx, JSString* baseArg,
1921 size_t start, size_t length,
1922 gc::Heap heap) {
1923 return NewDependentStringHelper<JS::ContractBaseChain::Contract>(
1924 cx, baseArg, start, length, heap);
1925 }
1926
1927 JSLinearString* js::NewDependentStringForTesting(JSContext* cx,
1928 JSString* baseArg,
1929 size_t start, size_t length,
1930 JS::ContractBaseChain contract,
1931 gc::Heap heap) {
1932 if (contract == JS::ContractBaseChain::Contract) {
1933 return NewDependentStringHelper<JS::ContractBaseChain::Contract>(
1934 cx, baseArg, start, length, heap);
1935 }
1936 return NewDependentStringHelper<JS::ContractBaseChain::AllowLong>(
1937 cx, baseArg, start, length, heap);
1938 }
1939
1940 static constexpr bool CanStoreCharsAsLatin1(const JS::Latin1Char* s,
1941 size_t length) {
1942 return true;
1943 }
1944
1945 static inline bool CanStoreCharsAsLatin1(const char16_t* s, size_t length) {
1946 return IsUtf16Latin1(Span(s, length));
1947 }
1948
1949 /**
1950 * Copy |src[0..length]| to |dest[0..length]| when copying *does* narrow, but
1951 * the user guarantees every runtime |src[i]| value can be stored without change
1952 * of value in |dest[i]|.
1953 */
1954 static inline void FillFromCompatible(unsigned char* dest, const char16_t* src,
1955 size_t length) {
1956 LossyConvertUtf16toLatin1(Span(src, length),
1957 AsWritableChars(Span(dest, length)));
1958 }
1959
1960 template <AllowGC allowGC>
1961 static MOZ_ALWAYS_INLINE JSInlineString* NewInlineStringDeflated(
1962 JSContext* cx, const mozilla::Range<const char16_t>& chars,
1963 gc::Heap heap = gc::Heap::Default) {
1964 size_t len = chars.length();
1965 Latin1Char* storage;
1966 JSInlineString* str = AllocateInlineString<allowGC>(cx, len, &storage, heap);
1967 if (!str) {
1968 return nullptr;
1969 }
1970
1971 MOZ_ASSERT(CanStoreCharsAsLatin1(chars.begin().get(), len));
1972 FillFromCompatible(storage, chars.begin().get(), len);
1973 return str;
1974 }
1975
1976 template <AllowGC allowGC>
1977 static JSLinearString* NewStringDeflated(JSContext* cx, const char16_t* s,
1978 size_t n, gc::Heap heap) {
1979 if (JSLinearString* str = TryEmptyOrStaticString(cx, s, n)) {
1980 return str;
1981 }
1982
1983 if (JSInlineString::lengthFits<Latin1Char>(n)) {
1984 return NewInlineStringDeflated<allowGC>(
1985 cx, mozilla::Range<const char16_t>(s, n), heap);
1986 }
1987
1988 JS::Rooted<JSString::OwnedChars<Latin1Char>> news(
1989 cx, AllocChars<Latin1Char>(cx, n, heap));
1990 if (!news) {
1991 if (!allowGC) {
1992 cx->recoverFromOutOfMemory();
1993 }
1994 return nullptr;
1995 }
1996
1997 MOZ_ASSERT(CanStoreCharsAsLatin1(s, n));
1998 FillFromCompatible(news.data(), s, n);
1999
2000 return JSLinearString::new_<allowGC, Latin1Char>(cx, &news, heap);
2001 }
2002
2003 static MOZ_ALWAYS_INLINE JSAtom* NewInlineAtomDeflated(JSContext* cx,
2004 const char16_t* chars,
2005 size_t length,
2006 js::HashNumber hash) {
2007 Latin1Char* storage;
2008 JSAtom* str = AllocateInlineAtom(cx, length, &storage, hash);
2009 if (!str) {
2010 return nullptr;
2011 }
2012
2013 MOZ_ASSERT(CanStoreCharsAsLatin1(chars, length));
2014 FillFromCompatible(storage, chars, length);
2015 return str;
2016 }
2017
2018 static JSAtom* NewAtomDeflatedValidLength(JSContext* cx, const char16_t* s,
2019 size_t n, js::HashNumber hash) {
2020 if (JSAtom::lengthFitsInline<Latin1Char>(n)) {
2021 return NewInlineAtomDeflated(cx, s, n, hash);
2022 }
2023
2024 JSString::OwnedChars<Latin1Char> newChars(
2025 AllocAtomCharsValidLength<Latin1Char>(cx, n));
2026 if (!newChars) {
2027 return nullptr;
2028 }
2029
2030 MOZ_ASSERT(CanStoreCharsAsLatin1(s, n));
2031 FillFromCompatible(newChars.data(), s, n);
2032
2033 return JSAtom::newValidLength<Latin1Char>(cx, newChars, hash);
2034 }
2035
2036 template <AllowGC allowGC, typename CharT>
2037 JSLinearString* js::NewStringDontDeflate(
2038 JSContext* cx, UniquePtr<CharT[], JS::FreePolicy> chars, size_t length,
2039 gc::Heap heap) {
2040 if (JSLinearString* str = TryEmptyOrStaticString(cx, chars.get(), length)) {
2041 return str;
2042 }
2043
2044 if (JSInlineString::lengthFits<CharT>(length)) {
2045 // |chars.get()| is safe because 1) |NewInlineString| necessarily *copies*,
2046 // and 2) |chars| frees its contents only when this function returns.
2047 return NewInlineString<allowGC>(
2048 cx, mozilla::Range<const CharT>(chars.get(), length), heap);
2049 }
2050
2051 JS::Rooted<JSString::OwnedChars<CharT>> ownedChars(cx, std::move(chars),
2052 length);
2053 return JSLinearString::new_<allowGC, CharT>(cx, &ownedChars, heap);
2054 }
2055
2056 template JSLinearString* js::NewStringDontDeflate<CanGC>(
2057 JSContext* cx, UniqueTwoByteChars chars, size_t length, gc::Heap heap);
2058
2059 template JSLinearString* js::NewStringDontDeflate<NoGC>(
2060 JSContext* cx, UniqueTwoByteChars chars, size_t length, gc::Heap heap);
2061
2062 template JSLinearString* js::NewStringDontDeflate<CanGC>(
2063 JSContext* cx, UniqueLatin1Chars chars, size_t length, gc::Heap heap);
2064
2065 template JSLinearString* js::NewStringDontDeflate<NoGC>(JSContext* cx,
2066 UniqueLatin1Chars chars,
2067 size_t length,
2068 gc::Heap heap);
2069
2070 template <AllowGC allowGC, typename CharT>
2071 JSLinearString* js::NewString(JSContext* cx,
2072 UniquePtr<CharT[], JS::FreePolicy> chars,
2073 size_t length, gc::Heap heap) {
2074 if constexpr (std::is_same_v<CharT, char16_t>) {
2075 if (CanStoreCharsAsLatin1(chars.get(), length)) {
2076 // Deflating copies from |chars.get()| and lets |chars| be freed on
2077 // return.
2078 return NewStringDeflated<allowGC>(cx, chars.get(), length, heap);
2079 }
2080 }
2081
2082 return NewStringDontDeflate<allowGC>(cx, std::move(chars), length, heap);
2083 }
2084
2085 template JSLinearString* js::NewString<CanGC>(JSContext* cx,
2086 UniqueTwoByteChars chars,
2087 size_t length, gc::Heap heap);
2088
2089 template JSLinearString* js::NewString<NoGC>(JSContext* cx,
2090 UniqueTwoByteChars chars,
2091 size_t length, gc::Heap heap);
2092
2093 template JSLinearString* js::NewString<CanGC>(JSContext* cx,
2094 UniqueLatin1Chars chars,
2095 size_t length, gc::Heap heap);
2096
2097 template JSLinearString* js::NewString<NoGC>(JSContext* cx,
2098 UniqueLatin1Chars chars,
2099 size_t length, gc::Heap heap);
2100
2101 namespace js {
2102
2103 template <AllowGC allowGC, typename CharT>
2104 JSLinearString* NewStringCopyNDontDeflateNonStaticValidLength(JSContext* cx,
2105 const CharT* s,
2106 size_t n,
2107 gc::Heap heap) {
2108 if (JSInlineString::lengthFits<CharT>(n)) {
2109 return NewInlineString<allowGC>(cx, mozilla::Range<const CharT>(s, n),
2110 heap);
2111 }
2112
2113 Rooted<JSString::OwnedChars<CharT>> news(cx,
2114 ::AllocChars<CharT>(cx, n, heap));
2115 if (!news) {
2116 if (!allowGC) {
2117 cx->recoverFromOutOfMemory();
2118 }
2119 return nullptr;
2120 }
2121
2122 PodCopy(news.data(), s, n);
2123
2124 return JSLinearString::newValidLength<allowGC, CharT>(cx, &news, heap);
2125 }
2126
2127 template JSLinearString* NewStringCopyNDontDeflateNonStaticValidLength<CanGC>(
2128 JSContext* cx, const char16_t* s, size_t n, gc::Heap heap);
2129
2130 template JSLinearString* NewStringCopyNDontDeflateNonStaticValidLength<NoGC>(
2131 JSContext* cx, const char16_t* s, size_t n, gc::Heap heap);
2132
2133 template JSLinearString* NewStringCopyNDontDeflateNonStaticValidLength<CanGC>(
2134 JSContext* cx, const Latin1Char* s, size_t n, gc::Heap heap);
2135
2136 template JSLinearString* NewStringCopyNDontDeflateNonStaticValidLength<NoGC>(
2137 JSContext* cx, const Latin1Char* s, size_t n, gc::Heap heap);
2138
2139 template <AllowGC allowGC, typename CharT>
2140 JSLinearString* NewStringCopyNDontDeflate(JSContext* cx, const CharT* s,
2141 size_t n, gc::Heap heap) {
2142 if (JSLinearString* str = TryEmptyOrStaticString(cx, s, n)) {
2143 return str;
2144 }
2145
2146 if (MOZ_UNLIKELY(!JSLinearString::validateLength(cx, n))) {
2147 return nullptr;
2148 }
2149
2150 return NewStringCopyNDontDeflateNonStaticValidLength<allowGC>(cx, s, n, heap);
2151 }
2152
2153 template JSLinearString* NewStringCopyNDontDeflate<CanGC>(JSContext* cx,
2154 const char16_t* s,
2155 size_t n,
2156 gc::Heap heap);
2157
2158 template JSLinearString* NewStringCopyNDontDeflate<NoGC>(JSContext* cx,
2159 const char16_t* s,
2160 size_t n,
2161 gc::Heap heap);
2162
2163 template JSLinearString* NewStringCopyNDontDeflate<CanGC>(JSContext* cx,
2164 const Latin1Char* s,
2165 size_t n,
2166 gc::Heap heap);
2167
2168 template JSLinearString* NewStringCopyNDontDeflate<NoGC>(JSContext* cx,
2169 const Latin1Char* s,
2170 size_t n,
2171 gc::Heap heap);
2172
2173 JSLinearString* NewLatin1StringZ(JSContext* cx, UniqueChars chars,
2174 gc::Heap heap) {
2175 size_t length = strlen(chars.get());
2176 UniqueLatin1Chars latin1(reinterpret_cast<Latin1Char*>(chars.release()));
2177 return NewString<CanGC>(cx, std::move(latin1), length, heap);
2178 }
2179
2180 template <AllowGC allowGC, typename CharT>
2181 JSLinearString* NewStringCopyN(JSContext* cx, const CharT* s, size_t n,
2182 gc::Heap heap) {
2183 if constexpr (std::is_same_v<CharT, char16_t>) {
2184 if (CanStoreCharsAsLatin1(s, n)) {
2185 return NewStringDeflated<allowGC>(cx, s, n, heap);
2186 }
2187 }
2188
2189 return NewStringCopyNDontDeflate<allowGC>(cx, s, n, heap);
2190 }
2191
2192 template JSLinearString* NewStringCopyN<CanGC>(JSContext* cx, const char16_t* s,
2193 size_t n, gc::Heap heap);
2194
2195 template JSLinearString* NewStringCopyN<NoGC>(JSContext* cx, const char16_t* s,
2196 size_t n, gc::Heap heap);
2197
2198 template JSLinearString* NewStringCopyN<CanGC>(JSContext* cx,
2199 const Latin1Char* s, size_t n,
2200 gc::Heap heap);
2201
2202 template JSLinearString* NewStringCopyN<NoGC>(JSContext* cx,
2203 const Latin1Char* s, size_t n,
2204 gc::Heap heap);
2205
2206 template <typename CharT>
2207 JSAtom* NewAtomCopyNDontDeflateValidLength(JSContext* cx, const CharT* s,
2208 size_t n, js::HashNumber hash) {
2209 if constexpr (std::is_same_v<CharT, char16_t>) {
2210 MOZ_ASSERT(!CanStoreCharsAsLatin1(s, n));
2211 }
2212
2213 if (JSAtom::lengthFitsInline<CharT>(n)) {
2214 return NewInlineAtom(cx, s, n, hash);
2215 }
2216
2217 JSString::OwnedChars<CharT> newChars(AllocAtomCharsValidLength<CharT>(cx, n));
2218 if (!newChars) {
2219 return nullptr;
2220 }
2221
2222 PodCopy(newChars.data(), s, n);
2223
2224 return JSAtom::newValidLength<CharT>(cx, newChars, hash);
2225 }
2226
2227 template JSAtom* NewAtomCopyNDontDeflateValidLength(JSContext* cx,
2228 const char16_t* s, size_t n,
2229 js::HashNumber hash);
2230
2231 template JSAtom* NewAtomCopyNDontDeflateValidLength(JSContext* cx,
2232 const Latin1Char* s,
2233 size_t n,
2234 js::HashNumber hash);
2235
2236 template <typename CharT>
2237 JSAtom* NewAtomCopyNMaybeDeflateValidLength(JSContext* cx, const CharT* s,
2238 size_t n, js::HashNumber hash) {
2239 if constexpr (std::is_same_v<CharT, char16_t>) {
2240 if (CanStoreCharsAsLatin1(s, n)) {
2241 return NewAtomDeflatedValidLength(cx, s, n, hash);
2242 }
2243 }
2244
2245 return NewAtomCopyNDontDeflateValidLength(cx, s, n, hash);
2246 }
2247
2248 template JSAtom* NewAtomCopyNMaybeDeflateValidLength(JSContext* cx,
2249 const char16_t* s,
2250 size_t n,
2251 js::HashNumber hash);
2252
2253 template JSAtom* NewAtomCopyNMaybeDeflateValidLength(JSContext* cx,
2254 const Latin1Char* s,
2255 size_t n,
2256 js::HashNumber hash);
2257
2258 JSLinearString* NewStringCopyUTF8N(JSContext* cx, const JS::UTF8Chars& utf8,
2259 JS::SmallestEncoding encoding,
2260 gc::Heap heap) {
2261 if (encoding == JS::SmallestEncoding::ASCII) {
2262 return NewStringCopyN<js::CanGC>(cx, utf8.begin().get(), utf8.length(),
2263 heap);
2264 }
2265
2266 size_t length;
2267 if (encoding == JS::SmallestEncoding::Latin1) {
2268 UniqueLatin1Chars latin1(
2269 UTF8CharsToNewLatin1CharsZ(cx, utf8, &length, js::StringBufferArena)
2270 .get());
2271 if (!latin1) {
2272 return nullptr;
2273 }
2274
2275 return NewString<js::CanGC>(cx, std::move(latin1), length, heap);
2276 }
2277
2278 MOZ_ASSERT(encoding == JS::SmallestEncoding::UTF16);
2279
2280 UniqueTwoByteChars utf16(
2281 UTF8CharsToNewTwoByteCharsZ(cx, utf8, &length, js::StringBufferArena)
2282 .get());
2283 if (!utf16) {
2284 return nullptr;
2285 }
2286
2287 return NewString<js::CanGC>(cx, std::move(utf16), length, heap);
2288 }
2289
2290 JSLinearString* NewStringCopyUTF8N(JSContext* cx, const JS::UTF8Chars& utf8,
2291 gc::Heap heap) {
2292 JS::SmallestEncoding encoding = JS::FindSmallestEncoding(utf8);
2293 return NewStringCopyUTF8N(cx, utf8, encoding, heap);
2294 }
2295
2296 template <typename CharT>
2297 MOZ_ALWAYS_INLINE JSLinearString* ExternalStringCache::lookupImpl(
2298 const CharT* chars, size_t len) const {
2299 AutoCheckCannotGC nogc;
2300
2301 for (size_t i = 0; i < NumEntries; i++) {
2302 JSLinearString* str = entries_[i];
2303 if (!str || str->length() != len) {
2304 continue;
2305 }
2306
2307 if constexpr (std::is_same_v<CharT, JS::Latin1Char>) {
2308 if (!str->hasLatin1Chars()) {
2309 continue;
2310 }
2311 } else {
2312 if (!str->hasTwoByteChars()) {
2313 continue;
2314 }
2315 }
2316
2317 const CharT* strChars = str->chars<CharT>(nogc);
2318 if (chars == strChars) {
2319 // Note that we don't need an incremental barrier here or below.
2320 // The cache is purged on GC so any string we get from the cache
2321 // must have been allocated after the GC started.
2322 MOZ_ASSERT(!str->isInline());
2323 return str;
2324 }
2325
2326 // Compare the chars. Don't do this for long strings as it will be
2327 // faster to allocate a new external string.
2328 static const size_t MaxLengthForCharComparison = 100;
2329 if (len <= MaxLengthForCharComparison && EqualChars(chars, strChars, len)) {
2330 return str;
2331 }
2332 }
2333
2334 return nullptr;
2335 }
2336
2337 MOZ_ALWAYS_INLINE JSLinearString* ExternalStringCache::lookup(
2338 const JS::Latin1Char* chars, size_t len) const {
2339 return lookupImpl(chars, len);
2340 }
2341 MOZ_ALWAYS_INLINE JSLinearString* ExternalStringCache::lookup(
2342 const char16_t* chars, size_t len) const {
2343 return lookupImpl(chars, len);
2344 }
2345
2346 MOZ_ALWAYS_INLINE void ExternalStringCache::put(JSLinearString* str) {
2347 for (size_t i = NumEntries - 1; i > 0; i--) {
2348 entries_[i] = entries_[i - 1];
2349 }
2350 entries_[0] = str;
2351 }
2352
2353 template <typename CharT>
2354 MOZ_ALWAYS_INLINE JSInlineString* ExternalStringCache::lookupInlineLatin1Impl(
2355 const CharT* chars, size_t len) const {
2356 MOZ_ASSERT(CanStoreCharsAsLatin1(chars, len));
2357 MOZ_ASSERT(JSThinInlineString::lengthFits<Latin1Char>(len));
2358
2359 AutoCheckCannotGC nogc;
2360
2361 for (size_t i = 0; i < NumEntries; i++) {
2362 JSInlineString* str = inlineLatin1Entries_[i];
2363 if (!str || str->length() != len) {
2364 continue;
2365 }
2366
2367 const JS::Latin1Char* strChars = str->latin1Chars(nogc);
2368 if (EqualChars(chars, strChars, len)) {
2369 return str;
2370 }
2371 }
2372
2373 return nullptr;
2374 }
2375
2376 MOZ_ALWAYS_INLINE JSInlineString* ExternalStringCache::lookupInlineLatin1(
2377 const JS::Latin1Char* chars, size_t len) const {
2378 return lookupInlineLatin1Impl(chars, len);
2379 }
2380 MOZ_ALWAYS_INLINE JSInlineString* ExternalStringCache::lookupInlineLatin1(
2381 const char16_t* chars, size_t len) const {
2382 return lookupInlineLatin1Impl(chars, len);
2383 }
2384
2385 MOZ_ALWAYS_INLINE void ExternalStringCache::putInlineLatin1(
2386 JSInlineString* str) {
2387 MOZ_ASSERT(str->hasLatin1Chars());
2388
2389 for (size_t i = NumEntries - 1; i > 0; i--) {
2390 inlineLatin1Entries_[i] = inlineLatin1Entries_[i - 1];
2391 }
2392 inlineLatin1Entries_[0] = str;
2393 }
2394
2395 } /* namespace js */
2396
2397 template <AllowGC allowGC>
2398 static MOZ_ALWAYS_INLINE JSInlineString* NewInlineStringMaybeDeflated(
2399 JSContext* cx, const mozilla::Range<const JS::Latin1Char>& chars,
2400 gc::Heap heap = gc::Heap::Default) {
2401 return NewInlineString<allowGC>(cx, chars, heap);
2402 }
2403
2404 template <AllowGC allowGC>
2405 static MOZ_ALWAYS_INLINE JSInlineString* NewInlineStringMaybeDeflated(
2406 JSContext* cx, const mozilla::Range<const char16_t>& chars,
2407 gc::Heap heap = gc::Heap::Default) {
2408 return NewInlineStringDeflated<allowGC>(cx, chars, heap);
2409 }
2410
2411 namespace js {
2412
2413 template <typename CharT>
2414 JSString* NewMaybeExternalString(JSContext* cx, const CharT* s, size_t n,
2415 const JSExternalStringCallbacks* callbacks,
2416 bool* allocatedExternal, gc::Heap heap) {
2417 if (JSString* str = TryEmptyOrStaticString(cx, s, n)) {
2418 *allocatedExternal = false;
2419 return str;
2420 }
2421
2422 ExternalStringCache& cache = cx->zone()->externalStringCache();
2423
2424 if (JSThinInlineString::lengthFits<Latin1Char>(n) &&
2425 CanStoreCharsAsLatin1(s, n)) {
2426 *allocatedExternal = false;
2427 if (JSInlineString* str = cache.lookupInlineLatin1(s, n)) {
2428 return str;
2429 }
2430 JSInlineString* str = NewInlineStringMaybeDeflated<AllowGC::CanGC>(
2431 cx, mozilla::Range<const CharT>(s, n), heap);
2432 if (!str) {
2433 return nullptr;
2434 }
2435 cache.putInlineLatin1(str);
2436 return str;
2437 }
2438
2439 if (auto* str = cache.lookup(s, n)) {
2440 *allocatedExternal = false;
2441 return str;
2442 }
2443
2444 JSExternalString* str = JSExternalString::new_(cx, s, n, callbacks);
2445 if (!str) {
2446 return nullptr;
2447 }
2448
2449 *allocatedExternal = true;
2450 cache.put(str);
2451 return str;
2452 }
2453
2454 template JSString* NewMaybeExternalString(
2455 JSContext* cx, const JS::Latin1Char* s, size_t n,
2456 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal,
2457 gc::Heap heap);
2458
2459 template JSString* NewMaybeExternalString(
2460 JSContext* cx, const char16_t* s, size_t n,
2461 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal,
2462 gc::Heap heap);
2463
2464 } /* namespace js */
2465
2466 template <typename CharT, typename BufferT>
2467 static JSString* NewStringFromBuffer(JSContext* cx, BufferT&& buffer,
2468 size_t length) {
2469 AssertHeapIsIdle();
2470 CHECK_THREAD(cx);
2471
2472 const auto* s = static_cast<const CharT*>(buffer->Data());
2473
2474 if (JSString* str = TryEmptyOrStaticString(cx, s, length)) {
2475 return str;
2476 }
2477
2478 ExternalStringCache& cache = cx->zone()->externalStringCache();
2479
2480 // Use the inline-string cache that we also use for external strings.
2481 if (JSThinInlineString::lengthFits<Latin1Char>(length) &&
2482 CanStoreCharsAsLatin1(s, length)) {
2483 if (JSInlineString* str = cache.lookupInlineLatin1(s, length)) {
2484 return str;
2485 }
2486 JSInlineString* str = NewInlineStringMaybeDeflated<AllowGC::CanGC>(
2487 cx, mozilla::Range(s, length), gc::Heap::Default);
2488 if (!str) {
2489 return nullptr;
2490 }
2491 cache.putInlineLatin1(str);
2492 return str;
2493 }
2494
2495 if (auto* str = cache.lookup(s, length)) {
2496 return str;
2497 }
2498
2499 JSLinearString* str;
2500 if (JSInlineString::lengthFits<CharT>(length)) {
2501 str = NewInlineString<CanGC>(cx, mozilla::Range(s, length),
2502 gc::Heap::Default);
2503 } else {
2504 // Note: |buffer| is either a StringBuffer* or a RefPtr<StringBuffer>, so
2505 // ensure we have a RefPtr.
2506 RefPtr<mozilla::StringBuffer> bufferRef(std::move(buffer));
2507 Rooted<JSString::OwnedChars<CharT>> owned(cx, std::move(bufferRef), length);
2508 str = JSLinearString::new_<CanGC, CharT>(cx, &owned, gc::Heap::Default);
2509 }
2510 if (!str) {
2511 return nullptr;
2512 }
2513 cache.put(str);
2514 return str;
2515 }
2516
2517 JS_PUBLIC_API JSString* JS::NewStringFromLatin1Buffer(
2518 JSContext* cx, RefPtr<mozilla::StringBuffer> buffer, size_t length) {
2519 return NewStringFromBuffer<Latin1Char>(cx, std::move(buffer), length);
2520 }
2521
2522 JS_PUBLIC_API JSString* JS::NewStringFromKnownLiveLatin1Buffer(
2523 JSContext* cx, mozilla::StringBuffer* buffer, size_t length) {
2524 return NewStringFromBuffer<Latin1Char>(cx, buffer, length);
2525 }
2526
2527 JS_PUBLIC_API JSString* JS::NewStringFromTwoByteBuffer(
2528 JSContext* cx, RefPtr<mozilla::StringBuffer> buffer, size_t length) {
2529 return NewStringFromBuffer<char16_t>(cx, std::move(buffer), length);
2530 }
2531
2532 JS_PUBLIC_API JSString* JS::NewStringFromKnownLiveTwoByteBuffer(
2533 JSContext* cx, mozilla::StringBuffer* buffer, size_t length) {
2534 return NewStringFromBuffer<char16_t>(cx, buffer, length);
2535 }
2536
2537 template <typename BufferT>
2538 static JSString* NewStringFromUTF8Buffer(JSContext* cx, BufferT&& buffer,
2539 size_t length) {
2540 AssertHeapIsIdle();
2541 CHECK_THREAD(cx);
2542
2543 const JS::UTF8Chars utf8(static_cast<const char*>(buffer->Data()), length);
2544
2545 JS::SmallestEncoding encoding = JS::FindSmallestEncoding(utf8);
2546 if (encoding == JS::SmallestEncoding::ASCII) {
2547 // ASCII case can use the string buffer as Latin1 buffer.
2548 return NewStringFromBuffer<Latin1Char>(cx, std::move(buffer), length);
2549 }
2550
2551 // Non-ASCII case cannot use the string buffer.
2552 return NewStringCopyUTF8N(cx, utf8, encoding);
2553 }
2554
2555 JS_PUBLIC_API JSString* JS::NewStringFromUTF8Buffer(
2556 JSContext* cx, RefPtr<mozilla::StringBuffer> buffer, size_t length) {
2557 return ::NewStringFromUTF8Buffer(cx, std::move(buffer), length);
2558 }
2559
2560 JS_PUBLIC_API JSString* JS::NewStringFromKnownLiveUTF8Buffer(
2561 JSContext* cx, mozilla::StringBuffer* buffer, size_t length) {
2562 return ::NewStringFromUTF8Buffer(cx, buffer, length);
2563 }
2564
2565 template <typename CharT>
2566 static bool PtrIsWithinRange(const CharT* ptr,
2567 const mozilla::Range<const CharT>& valid) {
2568 return size_t(ptr - valid.begin().get()) <= valid.length();
2569 }
2570
2571 /* static */
2572 template <typename CharT>
2573 void JSLinearString::maybeCloneCharsOnPromotionTyped(JSLinearString* str) {
2574 MOZ_ASSERT(!InCollectedNurseryRegion(str), "str should have been promoted");
2575 MOZ_ASSERT(str->isDependent());
2576 JSLinearString* root = str->asDependent().rootBaseDuringMinorGC();
2577 if (InCollectedNurseryRegion(root)) {
2578 // Can still fixup the original chars pointer.
2579 return;
2580 }
2581
2582 // If the base has not moved its chars, continue using them.
2583 JS::AutoCheckCannotGC nogc;
2584 const CharT* chars = str->chars<CharT>(nogc);
2585 if (PtrIsWithinRange(chars, root->range<CharT>(nogc))) {
2586 return;
2587 }
2588
2589 // Clone the chars.
2590 js::AutoEnterOOMUnsafeRegion oomUnsafe;
2591 size_t len = str->length();
2592 size_t nbytes = len * sizeof(CharT);
2593 CharT* data =
2594 str->zone()->pod_arena_malloc<CharT>(js::StringBufferArena, len);
2595 if (!data) {
2596 oomUnsafe.crash("cloning at-risk dependent string");
2597 }
2598 js_memcpy(data, chars, nbytes);
2599
2600 // Overwrite the dest string with a new linear string.
2601 new (str) JSLinearString(data, len, false /* hasBuffer */);
2602 if (str->isTenured()) {
2603 str->zone()->addCellMemory(str, nbytes, js::MemoryUse::StringContents);
2604 } else {
2605 AutoEnterOOMUnsafeRegion oomUnsafe;
2606 JSRuntime* rt = str->runtimeFromAnyThread();
2607 if (!rt->gc.nursery().registerMallocedBuffer(data, nbytes)) {
2608 oomUnsafe.crash("maybeCloneCharsOnPromotionTyped");
2609 }
2610 }
2611 }
2612
2613 template void JSLinearString::maybeCloneCharsOnPromotionTyped<JS::Latin1Char>(
2614 JSLinearString* str);
2615 template void JSLinearString::maybeCloneCharsOnPromotionTyped<char16_t>(
2616 JSLinearString* str);
2617
2618 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
2619 void JSExtensibleString::dumpOwnRepresentationFields(
2620 js::JSONPrinter& json) const {
2621 json.property("capacity", capacity());
2622 }
2623
2624 void JSInlineString::dumpOwnRepresentationFields(js::JSONPrinter& json) const {}
2625
2626 void JSLinearString::dumpOwnRepresentationFields(js::JSONPrinter& json) const {
2627 if (hasStringBuffer()) {
2628 # ifdef DEBUG
2629 json.property("bufferRefCount", stringBuffer()->RefCount());
2630 # endif
2631 return;
2632 }
2633 if (!isInline()) {
2634 // Include whether the chars are in the nursery even for tenured
2635 // strings, which should always be false. For investigating bugs, it's
2636 // better to not assume that.
2637 js::Nursery& nursery = runtimeFromMainThread()->gc.nursery();
2638 bool inNursery = nursery.isInside(nonInlineCharsRaw());
2639 json.boolProperty("charsInNursery", inNursery);
2640 }
2641 }
2642 #endif
2643
2644 struct RepresentativeExternalString : public JSExternalStringCallbacks {
2645 void finalize(JS::Latin1Char* chars) const override {
2646 // Constant chars, nothing to do.
2647 }
2648 void finalize(char16_t* chars) const override {
2649 // Constant chars, nothing to do.
2650 }
2651 size_t sizeOfBuffer(const JS::Latin1Char* chars,
2652 mozilla::MallocSizeOf mallocSizeOf) const override {
2653 // This string's buffer is not heap-allocated, so its malloc size is 0.
2654 return 0;
2655 }
2656 size_t sizeOfBuffer(const char16_t* chars,
2657 mozilla::MallocSizeOf mallocSizeOf) const override {
2658 // This string's buffer is not heap-allocated, so its malloc size is 0.
2659 return 0;
2660 }
2661 };
2662
2663 static const RepresentativeExternalString RepresentativeExternalStringCallbacks;
2664
2665 template <typename CheckString, typename CharT>
2666 static bool FillWithRepresentatives(JSContext* cx, Handle<ArrayObject*> array,
2667 uint32_t* index, const CharT* chars,
2668 size_t len, size_t inlineStringMaxLength,
2669 size_t inlineAtomMaxLength,
2670 const CheckString& check, gc::Heap heap) {
2671 auto AppendString = [&check](JSContext* cx, Handle<ArrayObject*> array,
2672 uint32_t* index, HandleString s) {
2673 MOZ_ASSERT(check(s));
2674 (void)check; // silence clang -Wunused-lambda-capture in opt builds
2675 RootedValue val(cx, StringValue(s));
2676 return JS_DefineElement(cx, array, (*index)++, val, 0);
2677 };
2678
2679 MOZ_ASSERT(len > inlineStringMaxLength);
2680 MOZ_ASSERT(len > inlineAtomMaxLength);
2681
2682 // Normal atom.
2683 RootedString atom1(cx, AtomizeChars(cx, chars, len));
2684 if (!atom1 || !AppendString(cx, array, index, atom1)) {
2685 return false;
2686 }
2687 MOZ_ASSERT(atom1->isAtom());
2688
2689 // Thin inline atom.
2690 RootedString atom2(cx, AtomizeChars(cx, chars, 2));
2691 if (!atom2 || !AppendString(cx, array, index, atom2)) {
2692 return false;
2693 }
2694 MOZ_ASSERT(atom2->isAtom());
2695 MOZ_ASSERT(atom2->isInline());
2696
2697 // Fat inline atom.
2698 RootedString atom3(cx, AtomizeChars(cx, chars, inlineAtomMaxLength));
2699 if (!atom3 || !AppendString(cx, array, index, atom3)) {
2700 return false;
2701 }
2702 MOZ_ASSERT(atom3->isAtom());
2703 MOZ_ASSERT_IF(inlineStringMaxLength < inlineAtomMaxLength,
2704 atom3->isFatInline());
2705
2706 // Normal linear string; maybe nursery.
2707 RootedString linear1(cx, NewStringCopyN<CanGC>(cx, chars, len, heap));
2708 if (!linear1 || !AppendString(cx, array, index, linear1)) {
2709 return false;
2710 }
2711 MOZ_ASSERT(linear1->isLinear());
2712
2713 // Inline string; maybe nursery.
2714 RootedString linear2(cx, NewStringCopyN<CanGC>(cx, chars, 3, heap));
2715 if (!linear2 || !AppendString(cx, array, index, linear2)) {
2716 return false;
2717 }
2718 MOZ_ASSERT(linear2->isLinear());
2719 MOZ_ASSERT(linear2->isInline());
2720
2721 // Fat inline string; maybe nursery.
2722 RootedString linear3(
2723 cx, NewStringCopyN<CanGC>(cx, chars, inlineStringMaxLength, heap));
2724 if (!linear3 || !AppendString(cx, array, index, linear3)) {
2725 return false;
2726 }
2727 MOZ_ASSERT(linear3->isLinear());
2728 MOZ_ASSERT(linear3->isFatInline());
2729
2730 // Rope; maybe nursery.
2731 RootedString rope(cx, ConcatStrings<CanGC>(cx, atom1, atom3, heap));
2732 if (!rope || !AppendString(cx, array, index, rope)) {
2733 return false;
2734 }
2735 MOZ_ASSERT(rope->isRope());
2736
2737 // Dependent; maybe nursery.
2738 RootedString dep(cx, NewDependentString(cx, atom1, 0, len - 2, heap));
2739 if (!dep || !AppendString(cx, array, index, dep)) {
2740 return false;
2741 }
2742 MOZ_ASSERT(dep->isDependent());
2743
2744 // Extensible; maybe nursery.
2745 RootedString temp1(cx, NewStringCopyN<CanGC>(cx, chars, len, heap));
2746 if (!temp1) {
2747 return false;
2748 }
2749 RootedString extensible(cx, ConcatStrings<CanGC>(cx, temp1, atom3, heap));
2750 if (!extensible || !extensible->ensureLinear(cx)) {
2751 return false;
2752 }
2753 if (!AppendString(cx, array, index, extensible)) {
2754 return false;
2755 }
2756 MOZ_ASSERT(extensible->isExtensible());
2757
2758 RootedString external1(cx), external2(cx);
2759 if constexpr (std::is_same_v<CharT, char16_t>) {
2760 external1 = JS_NewExternalUCString(cx, (const char16_t*)chars, len,
2761 &RepresentativeExternalStringCallbacks);
2762 if (!external1 || !AppendString(cx, array, index, external1)) {
2763 return false;
2764 }
2765 MOZ_ASSERT(external1->isExternal());
2766
2767 external2 = JS_NewExternalUCString(cx, (const char16_t*)chars, 2,
2768 &RepresentativeExternalStringCallbacks);
2769 if (!external2 || !AppendString(cx, array, index, external2)) {
2770 return false;
2771 }
2772 MOZ_ASSERT(external2->isExternal());
2773 } else {
2774 external1 =
2775 JS_NewExternalStringLatin1(cx, (const Latin1Char*)chars, len,
2776 &RepresentativeExternalStringCallbacks);
2777 if (!external1 || !AppendString(cx, array, index, external1)) {
2778 return false;
2779 }
2780 MOZ_ASSERT(external1->isExternal());
2781
2782 external2 =
2783 JS_NewExternalStringLatin1(cx, (const Latin1Char*)chars, 2,
2784 &RepresentativeExternalStringCallbacks);
2785 if (!external2 || !AppendString(cx, array, index, external2)) {
2786 return false;
2787 }
2788 MOZ_ASSERT(external2->isExternal());
2789 }
2790
2791 // Assert the strings still have the types we expect after creating the
2792 // other strings.
2793
2794 MOZ_ASSERT(atom1->isAtom());
2795 MOZ_ASSERT(atom2->isAtom());
2796 MOZ_ASSERT(atom3->isAtom());
2797 MOZ_ASSERT(atom2->isInline());
2798 MOZ_ASSERT_IF(inlineStringMaxLength < inlineAtomMaxLength,
2799 atom3->isFatInline());
2800
2801 MOZ_ASSERT(linear1->isLinear());
2802 MOZ_ASSERT(linear2->isLinear());
2803 MOZ_ASSERT(linear3->isLinear());
2804 MOZ_ASSERT(linear2->isInline());
2805 MOZ_ASSERT(linear3->isFatInline());
2806
2807 MOZ_ASSERT(rope->isRope());
2808 MOZ_ASSERT(dep->isDependent());
2809 MOZ_ASSERT(extensible->isExtensible());
2810 MOZ_ASSERT(external1->isExternal());
2811 MOZ_ASSERT(external2->isExternal());
2812 return true;
2813 }
2814
2815 /* static */
2816 bool JSString::fillWithRepresentatives(JSContext* cx,
2817 Handle<ArrayObject*> array) {
2818 uint32_t index = 0;
2819
2820 auto CheckTwoByte = [](JSString* str) { return str->hasTwoByteChars(); };
2821 auto CheckLatin1 = [](JSString* str) { return str->hasLatin1Chars(); };
2822
2823 static const char16_t twoByteChars[] =
2824 u"\u1234abc\0def\u5678ghijklmasdfa\0xyz0123456789";
2825 static const Latin1Char latin1Chars[] = "abc\0defghijklmasdfa\0xyz0123456789";
2826
2827 // Create strings using both the default heap and forcing the tenured heap. If
2828 // nursery strings are available, this is a best effort at creating them in
2829 // the default heap case. Since nursery strings may be disabled or a GC may
2830 // occur during this process, there may be duplicate representatives in the
2831 // final list.
2832
2833 if (!FillWithRepresentatives(cx, array, &index, twoByteChars,
2834 std::size(twoByteChars) - 1,
2835 JSFatInlineString::MAX_LENGTH_TWO_BYTE,
2836 js::FatInlineAtom::MAX_LENGTH_TWO_BYTE,
2837 CheckTwoByte, gc::Heap::Tenured)) {
2838 return false;
2839 }
2840 if (!FillWithRepresentatives(cx, array, &index, latin1Chars,
2841 std::size(latin1Chars) - 1,
2842 JSFatInlineString::MAX_LENGTH_LATIN1,
2843 js::FatInlineAtom::MAX_LENGTH_LATIN1,
2844 CheckLatin1, gc::Heap::Tenured)) {
2845 return false;
2846 }
2847 if (!FillWithRepresentatives(cx, array, &index, twoByteChars,
2848 std::size(twoByteChars) - 1,
2849 JSFatInlineString::MAX_LENGTH_TWO_BYTE,
2850 js::FatInlineAtom::MAX_LENGTH_TWO_BYTE,
2851 CheckTwoByte, gc::Heap::Default)) {
2852 return false;
2853 }
2854 if (!FillWithRepresentatives(cx, array, &index, latin1Chars,
2855 std::size(latin1Chars) - 1,
2856 JSFatInlineString::MAX_LENGTH_LATIN1,
2857 js::FatInlineAtom::MAX_LENGTH_LATIN1,
2858 CheckLatin1, gc::Heap::Default)) {
2859 return false;
2860 }
2861
2862 #ifdef DEBUG
2863 // * Normal atom
2864 // * Inline atom.
2865 // * Fat inline atom.
2866 // * Normal linear string
2867 // * Inline string
2868 // * Fat inline string
2869 // * Rope; maybe nursery.
2870 // * Dependent
2871 // * Extensible
2872 // * External with original len
2873 // * External with len==2
2874 static constexpr uint32_t StringTypes = 11;
2875 // * Latin1
2876 // * TwoByte
2877 static constexpr uint32_t CharTypes = 2;
2878 // * Tenured
2879 // * Default
2880 static constexpr uint32_t HeapType = 2;
2881 MOZ_ASSERT(index == StringTypes * CharTypes * HeapType);
2882 #endif
2883
2884 return true;
2885 }
2886
2887 bool JSString::tryReplaceWithAtomRef(JSAtom* atom) {
2888 MOZ_ASSERT(!isAtomRef());
2889
2890 if (isDependedOn() || isInline() || isExternal()) {
2891 return false;
2892 }
2893
2894 AutoCheckCannotGC nogc;
2895 if (hasOutOfLineChars()) {
2896 if (asLinear().hasStringBuffer()) {
2897 // If the string is in the nursery, the reference to the buffer will be
2898 // released during the next minor GC (in Nursery::sweep). If the string is
2899 // tenured, we have to release this reference here.
2900 if (isTenured()) {
2901 RemoveCellMemory(this, allocSize(), MemoryUse::StringContents);
2902 asLinear().stringBuffer()->Release();
2903 }
2904 } else {
2905 void* buffer = asLinear().nonInlineCharsRaw();
2906 // This is a little cheeky and so deserves a comment. If the string is
2907 // not tenured, then either its buffer lives purely in the nursery, in
2908 // which case it will just be forgotten and blown away in the next
2909 // minor GC, or it is tracked in the nursery's mallocedBuffers hashtable,
2910 // in which case it will be freed for us in the next minor GC. We opt
2911 // to let the GC take care of it since there's a chance it will run
2912 // during idle time.
2913 if (isTenured()) {
2914 RemoveCellMemory(this, allocSize(), MemoryUse::StringContents);
2915 js_free(buffer);
2916 }
2917 }
2918 }
2919
2920 // Pre-barrier for d.s.u3 which is overwritten and d.s.u2 which is ignored
2921 // for atom refs.
2922 MOZ_ASSERT(isRope() || isLinear());
2923 if (isRope()) {
2924 PreWriteBarrier(d.s.u2.left);
2925 PreWriteBarrier(d.s.u3.right);
2926 } else if (isDependent()) {
2927 PreWriteBarrier(d.s.u3.base);
2928 }
2929
2930 uint32_t flags = INIT_ATOM_REF_FLAGS;
2931 d.s.u3.atom = atom;
2932 if (atom->hasLatin1Chars()) {
2933 flags |= LATIN1_CHARS_BIT;
2934 setLengthAndFlags(length(), flags);
2935 setNonInlineChars(atom->chars<Latin1Char>(nogc), atom->hasStringBuffer());
2936 } else {
2937 setLengthAndFlags(length(), flags);
2938 setNonInlineChars(atom->chars<char16_t>(nogc), atom->hasStringBuffer());
2939 }
2940 // Redundant, but just a reminder that this needs to be true or else we need
2941 // to check and conditionally put ourselves in the store buffer
2942 MOZ_ASSERT(atom->isTenured());
2943 return true;
2944 }
2945
2946 template <typename CharT>
2947 bool js::StringChars<CharT>::maybeAlloc(JSContext* cx, size_t length,
2948 gc::Heap heap) {
2949 assertValidRequest(0, length);
2950
2951 if (JSInlineString::lengthFits<CharT>(length)) {
2952 return true;
2953 }
2954
2955 if (MOZ_UNLIKELY(!JSString::validateLength(cx, length))) {
2956 return false;
2957 }
2958
2959 auto chars = AllocChars<CharT>(cx, length, heap);
2960 if (!chars) {
2961 return false;
2962 }
2963
2964 ownedChars_.set(std::move(chars));
2965 return true;
2966 }
2967
2968 template bool js::StringChars<JS::Latin1Char>::maybeAlloc(JSContext*, size_t,
2969 gc::Heap);
2970 template bool js::StringChars<char16_t>::maybeAlloc(JSContext*, size_t,
2971 gc::Heap);
2972
2973 template <typename CharT>
2974 bool js::StringChars<CharT>::maybeRealloc(JSContext* cx, size_t oldLength,
2975 size_t newLength, gc::Heap heap) {
2976 assertValidRequest(oldLength, newLength);
2977
2978 // Nothing to do if new length still fits into inline storage.
2979 if (JSInlineString::lengthFits<CharT>(newLength)) {
2980 return true;
2981 }
2982
2983 if (MOZ_UNLIKELY(!JSString::validateLength(cx, newLength))) {
2984 return false;
2985 }
2986
2987 // Unused |ownedChars_| means we were previously using inlining storage.
2988 if (!ownedChars_) {
2989 auto chars = AllocChars<CharT>(cx, newLength, heap);
2990 if (!chars) {
2991 return false;
2992 }
2993 std::memcpy(chars.data(), inlineChars_, InlineLength * sizeof(CharT));
2994
2995 ownedChars_.set(std::move(chars));
2996 return true;
2997 }
2998
2999 // Use |realloc| for malloc'ed characters.
3000 if (ownedChars_.isMalloced()) {
3001 CharT* oldChars = ownedChars_.release();
3002 CharT* newChars = cx->pod_arena_realloc(js::StringBufferArena, oldChars,
3003 oldLength, newLength);
3004 if (!newChars) {
3005 js_free(oldChars);
3006 return false;
3007 }
3008
3009 using Kind = typename JSString::OwnedChars<CharT>::Kind;
3010 ownedChars_.set({newChars, newLength, Kind::Malloc});
3011 return true;
3012 }
3013
3014 // Use |StringBuffer::Realloc| for string buffers.
3015 if (ownedChars_.hasStringBuffer()) {
3016 static_assert(
3017 mozilla::StringBuffer::IsValidLength<CharT>(JSString::MAX_LENGTH),
3018 "JSString length must be valid for StringBuffer");
3019
3020 auto* oldBuffer = mozilla::StringBuffer::FromData(ownedChars_.release());
3021
3022 // Note: StringBuffers must be null-terminated.
3023 auto* newBuffer = mozilla::StringBuffer::Realloc(
3024 oldBuffer, (newLength + 1) * sizeof(CharT),
3025 mozilla::Some(js::StringBufferArena));
3026 if (!newBuffer) {
3027 oldBuffer->Release();
3028 ReportOutOfMemory(cx);
3029 return false;
3030 }
3031 auto* newChars = static_cast<CharT*>(newBuffer->Data());
3032 newChars[newLength] = '\0';
3033
3034 using Kind = typename JSString::OwnedChars<CharT>::Kind;
3035 ownedChars_.set({newChars, newLength, Kind::StringBuffer});
3036
3037 MOZ_ASSERT(newBuffer->RefCount() == 1);
3038 return true;
3039 }
3040
3041 // Keep the previous nursery allocated chars alive.
3042 Rooted<JSString::OwnedChars<CharT>> oldOwnedChars(
3043 cx, std::move(ownedChars_.get()));
3044
3045 // Nursery allocated characters can't be reallocated, so perform a new
3046 // allocation instead.
3047 auto chars = AllocChars<CharT>(cx, newLength, heap);
3048 if (!chars) {
3049 return false;
3050 }
3051 mozilla::PodCopy(chars.data(), oldOwnedChars.data(), oldLength);
3052
3053 ownedChars_.set(std::move(chars));
3054 return true;
3055 }
3056
3057 template bool js::StringChars<JS::Latin1Char>::maybeRealloc(JSContext*, size_t,
3058 size_t, gc::Heap);
3059 template bool js::StringChars<char16_t>::maybeRealloc(JSContext*, size_t,
3060 size_t, gc::Heap);
3061
3062 template <typename CharT>
3063 template <AllowGC allowGC>
3064 JSLinearString* js::StringChars<CharT>::toStringDontDeflate(JSContext* cx,
3065 size_t length,
3066 gc::Heap heap) {
3067 MOZ_ASSERT(length == lastRequestedLength_);
3068
3069 if (JSInlineString::lengthFits<CharT>(length)) {
3070 MOZ_ASSERT(!ownedChars_,
3071 "unexpected OwnedChars allocation for inline strings");
3072 if (auto* str = TryEmptyOrStaticString(cx, inlineChars_, length)) {
3073 return str;
3074 }
3075 return NewInlineString<CanGC>(cx, inlineChars_, length, heap);
3076 }
3077
3078 MOZ_ASSERT(ownedChars_,
3079 "missing OwnedChars allocation for non-inline strings");
3080 MOZ_ASSERT(length == ownedChars_.length(),
3081 "requested length doesn't match allocation");
3082 return JSLinearString::newValidLength<allowGC, CharT>(cx, &ownedChars_, heap);
3083 }
3084
3085 template JSLinearString*
3086 js::StringChars<JS::Latin1Char>::toStringDontDeflate<CanGC>(JSContext*, size_t,
3087 gc::Heap);
3088 template JSLinearString* js::StringChars<char16_t>::toStringDontDeflate<CanGC>(
3089 JSContext*, size_t, gc::Heap);
3090 template JSLinearString*
3091 js::StringChars<JS::Latin1Char>::toStringDontDeflate<NoGC>(JSContext*, size_t,
3092 gc::Heap);
3093 template JSLinearString* js::StringChars<char16_t>::toStringDontDeflate<NoGC>(
3094 JSContext*, size_t, gc::Heap);
3095
3096 template <typename CharT>
3097 template <AllowGC allowGC>
3098 JSLinearString* js::StringChars<CharT>::toStringDontDeflateNonStatic(
3099 JSContext* cx, size_t length, gc::Heap heap) {
3100 MOZ_ASSERT(length == lastRequestedLength_);
3101
3102 if (JSInlineString::lengthFits<CharT>(length)) {
3103 MOZ_ASSERT(!ownedChars_,
3104 "unexpected OwnedChars allocation for inline strings");
3105 MOZ_ASSERT(!TryEmptyOrStaticString(cx, inlineChars_, length),
3106 "unexpected static string found");
3107 return NewInlineString<allowGC>(cx, inlineChars_, length, heap);
3108 }
3109
3110 MOZ_ASSERT(ownedChars_,
3111 "missing OwnedChars allocation for non-inline strings");
3112 MOZ_ASSERT(length == ownedChars_.length(),
3113 "requested length doesn't match allocation");
3114 return JSLinearString::newValidLength<allowGC, CharT>(cx, &ownedChars_, heap);
3115 }
3116
3117 template JSLinearString*
3118 js::StringChars<JS::Latin1Char>::toStringDontDeflateNonStatic<CanGC>(JSContext*,
3119 size_t,
3120 gc::Heap);
3121 template JSLinearString*
3122 js::StringChars<char16_t>::toStringDontDeflateNonStatic<CanGC>(JSContext*,
3123 size_t,
3124 gc::Heap);
3125 template JSLinearString*
3126 js::StringChars<JS::Latin1Char>::toStringDontDeflateNonStatic<NoGC>(JSContext*,
3127 size_t,
3128 gc::Heap);
3129 template JSLinearString*
3130 js::StringChars<char16_t>::toStringDontDeflateNonStatic<NoGC>(JSContext*,
3131 size_t, gc::Heap);
3132
3133 template <typename CharT>
3134 bool js::AtomStringChars<CharT>::maybeAlloc(JSContext* cx, size_t length) {
3135 assertValidRequest(0, length);
3136
3137 if (JSInlineString::lengthFits<CharT>(length)) {
3138 return true;
3139 }
3140
3141 if (MOZ_UNLIKELY(!JSString::validateLength(cx, length))) {
3142 return false;
3143 }
3144
3145 mallocChars_ = cx->make_pod_arena_array<CharT>(js::StringBufferArena, length);
3146 return !!mallocChars_;
3147 }
3148
3149 template bool js::AtomStringChars<JS::Latin1Char>::maybeAlloc(JSContext*,
3150 size_t);
3151 template bool js::AtomStringChars<char16_t>::maybeAlloc(JSContext*, size_t);
3152
3153 template <typename CharT>
3154 JSAtom* js::AtomStringChars<CharT>::toAtom(JSContext* cx, size_t length) {
3155 MOZ_ASSERT(length == lastRequestedLength_);
3156 return AtomizeChars(cx, data(), length);
3157 }
3158
3159 template JSAtom* js::AtomStringChars<JS::Latin1Char>::toAtom(JSContext*,
3160 size_t);
3161 template JSAtom* js::AtomStringChars<char16_t>::toAtom(JSContext*, size_t);
3162
3163 /*** Conversions ************************************************************/
3164
3165 UniqueChars js::EncodeLatin1(JSContext* cx, JSString* str) {
3166 JSLinearString* linear = str->ensureLinear(cx);
3167 if (!linear) {
3168 return nullptr;
3169 }
3170
3171 JS::AutoCheckCannotGC nogc;
3172 if (linear->hasTwoByteChars()) {
3173 JS::Latin1CharsZ chars =
3174 JS::LossyTwoByteCharsToNewLatin1CharsZ(cx, linear->twoByteRange(nogc));
3175 return UniqueChars(chars.c_str());
3176 }
3177
3178 size_t len = str->length();
3179 Latin1Char* buf = cx->pod_malloc<Latin1Char>(len + 1);
3180 if (!buf) {
3181 return nullptr;
3182 }
3183
3184 PodCopy(buf, linear->latin1Chars(nogc), len);
3185 buf[len] = '\0';
3186
3187 return UniqueChars(reinterpret_cast<char*>(buf));
3188 }
3189
3190 UniqueChars js::EncodeAscii(JSContext* cx, JSString* str) {
3191 JSLinearString* linear = str->ensureLinear(cx);
3192 if (!linear) {
3193 return nullptr;
3194 }
3195
3196 MOZ_ASSERT(StringIsAscii(linear));
3197 return EncodeLatin1(cx, linear);
3198 }
3199
3200 UniqueChars js::IdToPrintableUTF8(JSContext* cx, HandleId id,
3201 IdToPrintableBehavior behavior) {
3202 // ToString(<symbol>) throws a TypeError, therefore require that callers
3203 // request source representation when |id| is a property key.
3204 MOZ_ASSERT_IF(behavior == IdToPrintableBehavior::IdIsIdentifier,
3205 id.isAtom() && IsIdentifierNameOrPrivateName(id.toAtom()));
3206
3207 RootedValue v(cx, IdToValue(id));
3208 JSString* str;
3209 if (behavior == IdToPrintableBehavior::IdIsPropertyKey) {
3210 str = ValueToSource(cx, v);
3211 } else {
3212 str = ToString<CanGC>(cx, v);
3213 }
3214 if (!str) {
3215 return nullptr;
3216 }
3217 return StringToNewUTF8CharsZ(cx, *str);
3218 }
3219
3220 template <AllowGC allowGC>
3221 JSString* js::ToStringSlow(
3222 JSContext* cx, typename MaybeRooted<Value, allowGC>::HandleType arg) {
3223 /* As with ToObjectSlow, callers must verify that |arg| isn't a string. */
3224 MOZ_ASSERT(!arg.isString());
3225
3226 Value v = arg;
3227 if (!v.isPrimitive()) {
3228 if (!allowGC) {
3229 return nullptr;
3230 }
3231 RootedValue v2(cx, v);
3232 if (!ToPrimitive(cx, JSTYPE_STRING, &v2)) {
3233 return nullptr;
3234 }
3235 v = v2;
3236 }
3237
3238 JSString* str;
3239 if (v.isString()) {
3240 str = v.toString();
3241 } else if (v.isInt32()) {
3242 str = Int32ToString<allowGC>(cx, v.toInt32());
3243 } else if (v.isDouble()) {
3244 str = NumberToString<allowGC>(cx, v.toDouble());
3245 } else if (v.isBoolean()) {
3246 str = BooleanToString(cx, v.toBoolean());
3247 } else if (v.isNull()) {
3248 str = cx->names().null;
3249 } else if (v.isSymbol()) {
3250 if (allowGC) {
3251 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3252 JSMSG_SYMBOL_TO_STRING);
3253 }
3254 return nullptr;
3255 } else if (v.isBigInt()) {
3256 if (!allowGC) {
3257 return nullptr;
3258 }
3259 RootedBigInt i(cx, v.toBigInt());
3260 str = BigInt::toString<CanGC>(cx, i, 10);
3261 } else {
3262 MOZ_ASSERT(v.isUndefined());
3263 str = cx->names().undefined;
3264 }
3265 return str;
3266 }
3267
3268 template JSString* js::ToStringSlow<CanGC>(JSContext* cx, HandleValue arg);
3269
3270 template JSString* js::ToStringSlow<NoGC>(JSContext* cx, const Value& arg);
3271
3272 JS_PUBLIC_API JSString* js::ToStringSlow(JSContext* cx, HandleValue v) {
3273 return ToStringSlow<CanGC>(cx, v);
3274 }