Debian Codegraph @

js/src/vm/StringType.h

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 #ifndef vm_StringType_h
8 #define vm_StringType_h
9
10 #include "mozilla/Maybe.h"
11 #include "mozilla/MemoryReporting.h"
12 #include "mozilla/Range.h"
13 #include "mozilla/RefPtr.h"
14 #include "mozilla/Span.h"
15 #include "mozilla/StringBuffer.h"
16 #include "mozilla/TextUtils.h"
17
18 #include <string_view> // std::basic_string_view
19
20 #include "jstypes.h" // js::Bit
21
22 #include "gc/Cell.h"
23 #include "gc/MaybeRooted.h"
24 #include "gc/Nursery.h"
25 #include "gc/RelocationOverlay.h"
26 #include "gc/StoreBuffer.h"
27 #include "js/CharacterEncoding.h"
28 #include "js/RootingAPI.h"
29 #include "js/shadow/String.h" // JS::shadow::String
30 #include "js/String.h" // JS::MaxStringLength
31 #include "js/UniquePtr.h"
32 #include "util/Text.h"
33
34 class JSDependentString;
35 class JSExtensibleString;
36 class JSExternalString;
37 class JSInlineString;
38 class JSRope;
39
40 namespace JS {
41 class JS_PUBLIC_API AutoStableStringChars;
42 } // namespace JS
43
44 namespace js {
45
46 class ArrayObject;
47 class JS_PUBLIC_API GenericPrinter;
48 class JSONPrinter;
49 class PropertyName;
50 class StringBuilder;
51
52 namespace frontend {
53 class ParserAtomsTable;
54 class TaggedParserAtomIndex;
55 class WellKnownParserAtoms;
56 struct CompilationAtomCache;
57 } // namespace frontend
58
59 namespace jit {
60 class MacroAssembler;
61 } // namespace jit
62
63 /* The buffer length required to contain any unsigned 32-bit integer. */
64 static const size_t UINT32_CHAR_BUFFER_LENGTH = sizeof("4294967295") - 1;
65
66 // Maximum array index. This value is defined in the spec (ES2021 draft, 6.1.7):
67 //
68 // An array index is an integer index whose numeric value i is in the range
69 // +0𝔽 ≤ i < 𝔽(2^32 - 1).
70 const uint32_t MAX_ARRAY_INDEX = 4294967294u; // 2^32-2 (= UINT32_MAX-1)
71
72 // Returns true if the characters of `s` store an unsigned 32-bit integer value
73 // less than or equal to MAX_ARRAY_INDEX, initializing `*indexp` to that value
74 // if so. Leading '0' isn't allowed except 0 itself.
75 template <typename CharT>
76 bool CheckStringIsIndex(const CharT* s, size_t length, uint32_t* indexp);
77
78 } /* namespace js */
79
80 // clang-format off
81 /*
82 * [SMDOC] JavaScript Strings
83 *
84 * Conceptually, a JS string is just an array of chars and a length. This array
85 * of chars may or may not be null-terminated and, if it is, the null character
86 * is not included in the length.
87 *
88 * To improve performance of common operations, the following optimizations are
89 * made which affect the engine's representation of strings:
90 *
91 * - The plain vanilla representation is a "linear" string which consists of a
92 * string header in the GC heap and a malloc'd char array.
93 *
94 * - To avoid copying a substring of an existing "base" string , a "dependent"
95 * string (JSDependentString) can be created which points into the base
96 * string's char array.
97 *
98 * - To avoid O(n^2) char buffer copying, a "rope" node (JSRope) can be created
99 * to represent a delayed string concatenation. Concatenation (called
100 * flattening) is performed if and when a linear char array is requested. In
101 * general, ropes form a binary dag whose internal nodes are JSRope string
102 * headers with no associated char array and whose leaf nodes are linear
103 * strings.
104 *
105 * - To avoid copying the leftmost string when flattening, we may produce an
106 * "extensible" string, which tracks not only its actual length but also its
107 * buffer's overall size. If such an "extensible" string appears as the
108 * leftmost string in a subsequent flatten, and its buffer has enough unused
109 * space, we can simply flatten the rest of the ropes into its buffer,
110 * leaving its text in place. We then transfer ownership of its buffer to the
111 * flattened rope, and mutate the donor extensible string into a dependent
112 * string referencing its original buffer.
113 *
114 * (The term "extensible" does not imply that we ever 'realloc' the buffer.
115 * Extensible strings may have dependent strings pointing into them, and the
116 * JSAPI hands out pointers to linear strings' buffers, so resizing with
117 * 'realloc' is generally not possible.)
118 *
119 * - To avoid allocating small char arrays, short strings can be stored inline
120 * in the string header (JSInlineString). These come in two flavours:
121 * JSThinInlineString, which is the same size as JSString; and
122 * JSFatInlineString, which has a larger header and so can fit more chars.
123 *
124 * - To avoid comparing O(n) string equality comparison, strings can be
125 * canonicalized to "atoms" (JSAtom) such that there is a single atom with a
126 * given (length,chars).
127 *
128 * - To avoid copying all strings created through the JSAPI, an "external"
129 * string (JSExternalString) can be created whose chars are managed by the
130 * JSAPI client.
131 *
132 * - To avoid using two bytes per character for every string, string
133 * characters are stored as Latin1 instead of TwoByte if all characters are
134 * representable in Latin1.
135 *
136 * - To avoid slow conversions from strings to integer indexes, we cache 16 bit
137 * unsigned indexes on strings representing such numbers.
138 *
139 * Although all strings share the same basic memory layout, we can conceptually
140 * arrange them into a hierarchy of operations/invariants and represent this
141 * hierarchy in C++ with classes:
142 *
143 * C++ type operations+fields / invariants+properties
144 * ========================== =========================================
145 * JSString (abstract) get(Latin1|TwoByte)CharsZ, get(Latin1|TwoByte)Chars, length / -
146 * | \
147 * | JSRope leftChild, rightChild / -
148 * |
149 * JSLinearString latin1Chars, twoByteChars / -
150 * |
151 * +-- JSDependentString base / -
152 * | |
153 * | +-- JSAtomRefString - / base points to an atom
154 * |
155 * +-- JSExternalString - / char array memory managed by embedding
156 * |
157 * +-- JSExtensibleString - / tracks total buffer capacity (including current text)
158 * |
159 * +-- JSInlineString (abstract) - / chars stored in header
160 * | |
161 * | +-- JSThinInlineString - / header is normal
162 * | |
163 * | +-- JSFatInlineString - / header is fat
164 * |
165 * JSAtom (abstract) - / string equality === pointer equality
166 * | |
167 * | +-- js::NormalAtom JSLinearString + atom hash code / -
168 * | | |
169 * | | +-- js::ThinInlineAtom
170 * | | possibly larger JSThinInlineString + atom hash code / -
171 * | |
172 * | +-- js::FatInlineAtom JSFatInlineString w/atom hash code / -
173 * |
174 * js::PropertyName - / chars don't contain an index (uint32_t)
175 *
176 * Classes marked with (abstract) above are not literally C++ Abstract Base
177 * Classes (since there are no virtual functions, pure or not, in this
178 * hierarchy), but have the same meaning: there are no strings with this type as
179 * its most-derived type.
180 *
181 * Atoms can additionally be permanent, i.e. unable to be collected, and can
182 * be combined with other string types to create additional most-derived types
183 * that satisfy the invariants of more than one of the abovementioned
184 * most-derived types. Furthermore, each atom stores a hash number (based on its
185 * chars). This hash number is used as key in the atoms table and when the atom
186 * is used as key in a JS Map/Set.
187 *
188 * Derived string types can be queried from ancestor types via isX() and
189 * retrieved with asX() debug-only-checked casts.
190 *
191 * The ensureX() operations mutate 'this' in place to effectively make the type
192 * be at least X (e.g., ensureLinear will change a JSRope to be a JSLinearString).
193 */
194 // clang-format on
195
196 class JSString : public js::gc::CellWithLengthAndFlags {
197 protected:
198 using Base = js::gc::CellWithLengthAndFlags;
199
200 static const size_t NUM_INLINE_CHARS_LATIN1 =
201 2 * sizeof(void*) / sizeof(JS::Latin1Char);
202 static const size_t NUM_INLINE_CHARS_TWO_BYTE =
203 2 * sizeof(void*) / sizeof(char16_t);
204
205 public:
206 // String length and flags are stored in the cell header.
207 MOZ_ALWAYS_INLINE
208 size_t length() const { return headerLengthField(); }
209 MOZ_ALWAYS_INLINE
210 uint32_t flags() const { return headerFlagsField(); }
211
212 // Class for temporarily holding character data that will be used for JSString
213 // contents. The data may be allocated in the nursery, the malloc heap, or as
214 // a StringBuffer. The class instance must be passed to the JSString
215 // constructor as a MutableHandle, so that if a GC occurs between the
216 // construction of the content and the construction of the JSString Cell to
217 // hold it, the contents can be transparently moved to the malloc heap before
218 // the nursery is reset.
219 template <typename CharT>
220 class OwnedChars {
221 public:
222 enum class Kind {
223 // Not owning any chars. chars_ should not be used.
224 Uninitialized,
225
226 // chars_ is a buffer allocated in the nursery.
227 Nursery,
228
229 // chars_ is a buffer allocated in the malloc heap. This pointer should be
230 // passed to js_free() if OwnedChars dies while still possessing
231 // ownership.
232 Malloc,
233
234 // chars_ is allocated as a refcounted StringBuffer. The reference must be
235 // released if OwnedChars dies while still possessing ownership.
236 StringBuffer,
237 };
238
239 private:
240 mozilla::Span<CharT> chars_;
241 Kind kind_ = Kind::Uninitialized;
242
243 public:
244 OwnedChars() = default;
245 OwnedChars(CharT* chars, size_t length, Kind kind);
246 OwnedChars(js::UniquePtr<CharT[], JS::FreePolicy>&& chars, size_t length);
247 OwnedChars(RefPtr<mozilla::StringBuffer>&& buffer, size_t length);
248 OwnedChars(OwnedChars&&);
249 OwnedChars(const OwnedChars&) = delete;
250 ~OwnedChars() { reset(); }
251
252 OwnedChars& operator=(OwnedChars&&);
253 OwnedChars& operator=(const OwnedChars&) = delete;
254
255 explicit operator bool() const {
256 MOZ_ASSERT_IF(kind_ != Kind::Uninitialized, !chars_.empty());
257 return kind_ != Kind::Uninitialized;
258 }
259 mozilla::Span<CharT> span() const {
260 MOZ_ASSERT(kind_ != Kind::Uninitialized);
261 return chars_;
262 }
263 CharT* data() const {
264 MOZ_ASSERT(kind_ != Kind::Uninitialized);
265 return chars_.data();
266 }
267 size_t length() const {
268 MOZ_ASSERT(kind_ != Kind::Uninitialized);
269 return chars_.Length();
270 }
271 size_t size() const { return length() * sizeof(CharT); }
272 bool isMalloced() const { return kind_ == Kind::Malloc; }
273 bool hasStringBuffer() const { return kind_ == Kind::StringBuffer; }
274
275 // Return the data and release ownership to the caller.
276 inline CharT* release();
277 // Discard any owned data.
278 inline void reset();
279 // Move any nursery data into the malloc heap.
280 inline void ensureNonNursery();
281
282 // If we GC with a live OwnedChars, copy the data out of the nursery to a
283 // safely malloced location.
284 void trace(JSTracer* trc) { ensureNonNursery(); }
285 };
286
287 protected:
288 /* Fields only apply to string types commented on the right. */
289 struct Data {
290 // Note: 32-bit length and flags fields are inherited from
291 // CellWithLengthAndFlags.
292
293 union {
294 union {
295 /* JS(Fat)InlineString */
296 JS::Latin1Char inlineStorageLatin1[NUM_INLINE_CHARS_LATIN1];
297 char16_t inlineStorageTwoByte[NUM_INLINE_CHARS_TWO_BYTE];
298 };
299 struct {
300 union {
301 const JS::Latin1Char* nonInlineCharsLatin1; /* JSLinearString, except
302 JS(Fat)InlineString */
303 const char16_t* nonInlineCharsTwoByte; /* JSLinearString, except
304 JS(Fat)InlineString */
305 JSString* left; /* JSRope */
306 JSRope* parent; /* Used in flattening */
307 } u2;
308 union {
309 JSLinearString* base; /* JSDependentString */
310 JSAtom* atom; /* JSAtomRefString */
311 JSString* right; /* JSRope */
312 size_t capacity; /* JSLinearString (extensible) */
313 const JSExternalStringCallbacks*
314 externalCallbacks; /* JSExternalString */
315 } u3;
316 } s;
317 };
318 } d;
319
320 public:
321 /* Flags exposed only for jits */
322
323 /*
324 * Flag Encoding
325 *
326 * The first word of a JSString stores flags, index, and (on some
327 * platforms) the length. The flags store both the string's type and its
328 * character encoding.
329 *
330 * If LATIN1_CHARS_BIT is set, the string's characters are stored as Latin1
331 * instead of TwoByte. This flag can also be set for ropes, if both the
332 * left and right nodes are Latin1. Flattening will result in a Latin1
333 * string in this case. When we flatten a TwoByte rope, we turn child ropes
334 * (including Latin1 ropes) into TwoByte dependent strings. If one of these
335 * strings is also part of another Latin1 rope tree, we can have a Latin1 rope
336 * with a TwoByte descendent.
337 *
338 * The other flags store the string's type. Instead of using a dense index
339 * to represent the most-derived type, string types are encoded to allow
340 * single-op tests for hot queries (isRope, isDependent, isAtom) which, in
341 * view of subtyping, would require slower (isX() || isY() || isZ()).
342 *
343 * The string type encoding can be summarized as follows. The "instance
344 * encoding" entry for a type specifies the flag bits used to create a
345 * string instance of that type. Abstract types have no instances and thus
346 * have no such entry. The "subtype predicate" entry for a type specifies
347 * the predicate used to query whether a JSString instance is subtype
348 * (reflexively) of that type.
349 *
350 * String Instance Subtype
351 * type encoding predicate
352 * -----------------------------------------
353 * Rope 0000000 000 xxxxx0x xxx
354 * Linear 0000010 000 xxxxx1x xxx
355 * Dependent 0000110 000 xxxx1xx xxx
356 * AtomRef 1000110 000 1xxxxxx xxx
357 * External 0100010 000 x100010 xxx
358 * Extensible 0010010 000 x010010 xxx
359 * Inline 0001010 000 xxx1xxx xxx
360 * FatInline 0011010 000 xx11xxx xxx
361 * JSAtom - xxxxxx1 xxx
362 * NormalAtom 0000011 000 xxx0xx1 xxx
363 * PermanentAtom 0100011 000 x1xxxx1 xxx
364 * ThinInlineAtom 0001011 000 xx01xx1 xxx
365 * FatInlineAtom 0011011 000 xx11xx1 xxx
366 * ||||||| |||
367 * ||||||| ||\- [0] reserved (FORWARD_BIT)
368 * ||||||| |\-- [1] reserved
369 * ||||||| \--- [2] reserved
370 * ||||||\----- [3] IsAtom
371 * |||||\------ [4] IsLinear
372 * ||||\------- [5] IsDependent
373 * |||\-------- [6] IsInline
374 * ||\--------- [7] FatInlineAtom/Extensible
375 * |\---------- [8] External/Permanent
376 * \----------- [9] AtomRef
377 *
378 * Bits 0..2 are reserved for use by the GC (see
379 * gc::CellFlagBitsReservedForGC). In particular, bit 0 is currently used for
380 * FORWARD_BIT for forwarded nursery cells. The other 2 bits are currently
381 * unused.
382 *
383 * Note that the first 4 flag bits 3..6 (from right to left in the previous
384 * table) have the following meaning and can be used for some hot queries:
385 *
386 * Bit 3: IsAtom (Atom, PermanentAtom)
387 * Bit 4: IsLinear
388 * Bit 5: IsDependent
389 * Bit 6: IsInline (Inline, FatInline, ThinInlineAtom, FatInlineAtom)
390 *
391 * If INDEX_VALUE_BIT is set, bits 16 and up will also hold an integer index.
392 */
393
394 // The low bits of flag word are reserved by GC.
395 static_assert(js::gc::CellFlagBitsReservedForGC <= 3,
396 "JSString::flags must reserve enough bits for Cell");
397
398 static const uint32_t ATOM_BIT = js::Bit(3);
399 static const uint32_t LINEAR_BIT = js::Bit(4);
400 static const uint32_t DEPENDENT_BIT = js::Bit(5);
401 static const uint32_t INLINE_CHARS_BIT = js::Bit(6);
402 // Indicates a dependent string pointing to an atom
403 static const uint32_t ATOM_REF_BIT = js::Bit(9);
404
405 static const uint32_t LINEAR_IS_EXTENSIBLE_BIT = js::Bit(7);
406 static const uint32_t INLINE_IS_FAT_BIT = js::Bit(7);
407
408 static const uint32_t LINEAR_IS_EXTERNAL_BIT = js::Bit(8);
409 static const uint32_t ATOM_IS_PERMANENT_BIT = js::Bit(8);
410
411 static const uint32_t EXTENSIBLE_FLAGS =
412 LINEAR_BIT | LINEAR_IS_EXTENSIBLE_BIT;
413 static const uint32_t EXTERNAL_FLAGS = LINEAR_BIT | LINEAR_IS_EXTERNAL_BIT;
414
415 static const uint32_t FAT_INLINE_MASK = INLINE_CHARS_BIT | INLINE_IS_FAT_BIT;
416
417 /* Initial flags for various types of strings. */
418 static const uint32_t INIT_THIN_INLINE_FLAGS = LINEAR_BIT | INLINE_CHARS_BIT;
419 static const uint32_t INIT_FAT_INLINE_FLAGS = LINEAR_BIT | FAT_INLINE_MASK;
420 static const uint32_t INIT_ROPE_FLAGS = 0;
421 static const uint32_t INIT_LINEAR_FLAGS = LINEAR_BIT;
422 static const uint32_t INIT_DEPENDENT_FLAGS = LINEAR_BIT | DEPENDENT_BIT;
423 static const uint32_t INIT_ATOM_REF_FLAGS =
424 INIT_DEPENDENT_FLAGS | ATOM_REF_BIT;
425
426 static const uint32_t TYPE_FLAGS_MASK = js::BitMask(10) - js::BitMask(3);
427 static_assert((TYPE_FLAGS_MASK & js::gc::HeaderWord::RESERVED_MASK) == 0,
428 "GC reserved bits must not be used for Strings");
429
430 // Whether this atom's characters store an uint32 index value less than or
431 // equal to MAX_ARRAY_INDEX. This bit means something different if the
432 // string is not an atom (see ATOM_REF_BIT)
433 // See JSLinearString::isIndex.
434 static const uint32_t ATOM_IS_INDEX_BIT = js::Bit(9);
435
436 // Linear strings:
437 // - Content and representation are Latin-1 characters.
438 // - Unmodifiable after construction.
439 //
440 // Ropes:
441 // - Content are Latin-1 characters.
442 // - Flag may be cleared when the rope is changed into a dependent string.
443 //
444 // Also see LATIN1_CHARS_BIT description under "Flag Encoding".
445 static const uint32_t LATIN1_CHARS_BIT = js::Bit(10);
446
447 static const uint32_t INDEX_VALUE_BIT = js::Bit(11);
448 static const uint32_t INDEX_VALUE_SHIFT = 16;
449
450 // Whether this is a non-inline linear string with a refcounted
451 // mozilla::StringBuffer.
452 //
453 // If set, d.s.u2.nonInlineChars* still points to the string's characters and
454 // the StringBuffer header is stored immediately before the characters. This
455 // allows recovering the StringBuffer from the chars pointer with
456 // StringBuffer::FromData.
457 static const uint32_t HAS_STRING_BUFFER_BIT = js::Bit(12);
458
459 // NON_DEDUP_BIT is used in string deduplication during tenuring. This bit is
460 // shared with both FLATTEN_FINISH_NODE and ATOM_IS_PERMANENT_BIT, since it
461 // only applies to linear non-atoms.
462 static const uint32_t NON_DEDUP_BIT = js::Bit(15);
463
464 // If IN_STRING_TO_ATOM_CACHE is set, this string had an entry in the
465 // StringToAtomCache at some point. Note that GC can purge the cache without
466 // clearing this bit.
467 static const uint32_t IN_STRING_TO_ATOM_CACHE = js::Bit(13);
468
469 // Flags used during rope flattening that indicate what action to perform when
470 // returning to the rope's parent rope.
471 static const uint32_t FLATTEN_VISIT_RIGHT = js::Bit(14);
472 static const uint32_t FLATTEN_FINISH_NODE = js::Bit(15);
473 static const uint32_t FLATTEN_MASK =
474 FLATTEN_VISIT_RIGHT | FLATTEN_FINISH_NODE;
475
476 // Indicates that this string is depended on by another string. A rope should
477 // never be depended on, and this should never be set during flattening, so
478 // we can reuse the FLATTEN_VISIT_RIGHT bit.
479 static const uint32_t DEPENDED_ON_BIT = FLATTEN_VISIT_RIGHT;
480
481 static const uint32_t PINNED_ATOM_BIT = js::Bit(15);
482 static const uint32_t PERMANENT_ATOM_MASK =
483 ATOM_BIT | PINNED_ATOM_BIT | ATOM_IS_PERMANENT_BIT;
484
485 static const uint32_t MAX_LENGTH = JS::MaxStringLength;
486
487 static const JS::Latin1Char MAX_LATIN1_CHAR = 0xff;
488
489 // Allocate a StringBuffer instead of using raw malloc for strings with
490 // length * sizeof(CharT) >= MIN_BYTES_FOR_BUFFER.
491 //
492 // StringBuffers can be shared more efficiently with DOM code, but have some
493 // additional overhead (StringBuffer header, null terminator) so for short
494 // strings we prefer malloc.
495 //
496 // Note that 514 was picked as a pretty conservative initial value. The value
497 // is just above 512 to ensure a Latin1 string of length 512 isn't bumped
498 // from jemalloc bucket size 512 to size 768. It's an even value because it's
499 // divided by 2 for char16_t strings.
500 static constexpr size_t MIN_BYTES_FOR_BUFFER = 514;
501
502 /*
503 * Helper function to validate that a string of a given length is
504 * representable by a JSString. An allocation overflow is reported if false
505 * is returned.
506 */
507 static inline bool validateLength(JSContext* cx, size_t length);
508
509 template <js::AllowGC allowGC>
510 static inline bool validateLengthInternal(JSContext* cx, size_t length);
511
512 static constexpr size_t offsetOfFlags() { return offsetOfHeaderFlags(); }
513 static constexpr size_t offsetOfLength() { return offsetOfHeaderLength(); }
514
515 bool sameLengthAndFlags(const JSString& other) const {
516 return length() == other.length() && flags() == other.flags();
517 }
518
519 static void staticAsserts() {
520 static_assert(JSString::MAX_LENGTH < UINT32_MAX,
521 "Length must fit in 32 bits");
522 static_assert(
523 sizeof(JSString) == (offsetof(JSString, d.inlineStorageLatin1) +
524 NUM_INLINE_CHARS_LATIN1 * sizeof(char)),
525 "Inline Latin1 chars must fit in a JSString");
526 static_assert(
527 sizeof(JSString) == (offsetof(JSString, d.inlineStorageTwoByte) +
528 NUM_INLINE_CHARS_TWO_BYTE * sizeof(char16_t)),
529 "Inline char16_t chars must fit in a JSString");
530
531 /* Ensure js::shadow::String has the same layout. */
532 using JS::shadow::String;
533 static_assert(
534 JSString::offsetOfRawHeaderFlagsField() == offsetof(String, flags_),
535 "shadow::String flags offset must match JSString");
536 #if JS_BITS_PER_WORD == 32
537 static_assert(JSString::offsetOfLength() == offsetof(String, length_),
538 "shadow::String length offset must match JSString");
539 #endif
540 static_assert(offsetof(JSString, d.s.u2.nonInlineCharsLatin1) ==
541 offsetof(String, nonInlineCharsLatin1),
542 "shadow::String nonInlineChars offset must match JSString");
543 static_assert(offsetof(JSString, d.s.u2.nonInlineCharsTwoByte) ==
544 offsetof(String, nonInlineCharsTwoByte),
545 "shadow::String nonInlineChars offset must match JSString");
546 static_assert(
547 offsetof(JSString, d.s.u3.externalCallbacks) ==
548 offsetof(String, externalCallbacks),
549 "shadow::String externalCallbacks offset must match JSString");
550 static_assert(offsetof(JSString, d.inlineStorageLatin1) ==
551 offsetof(String, inlineStorageLatin1),
552 "shadow::String inlineStorage offset must match JSString");
553 static_assert(offsetof(JSString, d.inlineStorageTwoByte) ==
554 offsetof(String, inlineStorageTwoByte),
555 "shadow::String inlineStorage offset must match JSString");
556 static_assert(ATOM_BIT == String::ATOM_BIT,
557 "shadow::String::ATOM_BIT must match JSString::ATOM_BIT");
558 static_assert(LINEAR_BIT == String::LINEAR_BIT,
559 "shadow::String::LINEAR_BIT must match JSString::LINEAR_BIT");
560 static_assert(INLINE_CHARS_BIT == String::INLINE_CHARS_BIT,
561 "shadow::String::INLINE_CHARS_BIT must match "
562 "JSString::INLINE_CHARS_BIT");
563 static_assert(LATIN1_CHARS_BIT == String::LATIN1_CHARS_BIT,
564 "shadow::String::LATIN1_CHARS_BIT must match "
565 "JSString::LATIN1_CHARS_BIT");
566 static_assert(
567 TYPE_FLAGS_MASK == String::TYPE_FLAGS_MASK,
568 "shadow::String::TYPE_FLAGS_MASK must match JSString::TYPE_FLAGS_MASK");
569 static_assert(
570 EXTERNAL_FLAGS == String::EXTERNAL_FLAGS,
571 "shadow::String::EXTERNAL_FLAGS must match JSString::EXTERNAL_FLAGS");
572 }
573
574 /* Avoid silly compile errors in JSRope::flatten */
575 friend class JSRope;
576
577 friend class js::gc::RelocationOverlay;
578
579 protected:
580 template <typename CharT>
581 MOZ_ALWAYS_INLINE void setNonInlineChars(const CharT* chars,
582 bool usesStringBuffer);
583
584 template <typename CharT>
585 static MOZ_ALWAYS_INLINE void checkStringCharsArena(const CharT* chars,
586 bool usesStringBuffer) {
587 #ifdef MOZ_DEBUG
588 // Check that the new buffer is located in the StringBufferArena.
589 // For now ignore this for StringBuffers because they can be allocated in
590 // the main jemalloc arena.
591 if (!usesStringBuffer) {
592 js::AssertJSStringBufferInCorrectArena(chars);
593 }
594 #endif
595 }
596
597 // Get correct non-inline chars enum arm for given type
598 template <typename CharT>
599 MOZ_ALWAYS_INLINE const CharT* nonInlineCharsRaw() const;
600
601 public:
602 MOZ_ALWAYS_INLINE
603 bool empty() const { return length() == 0; }
604
605 inline bool getChar(JSContext* cx, size_t index, char16_t* code);
606 inline bool getCodePoint(JSContext* cx, size_t index, char32_t* codePoint);
607
608 /* Strings have either Latin1 or TwoByte chars. */
609 bool hasLatin1Chars() const { return flags() & LATIN1_CHARS_BIT; }
610 bool hasTwoByteChars() const { return !(flags() & LATIN1_CHARS_BIT); }
611
612 /* Strings might contain cached indexes. */
613 bool hasIndexValue() const { return flags() & INDEX_VALUE_BIT; }
614 uint32_t getIndexValue() const {
615 MOZ_ASSERT(hasIndexValue());
616 MOZ_ASSERT(isLinear());
617 return flags() >> INDEX_VALUE_SHIFT;
618 }
619
620 /*
621 * Whether any dependent strings point to this string's chars. This is needed
622 * so that we don't replace the string with a forwarded atom and free its
623 * buffer.
624 *
625 * NOTE: we specifically do not set this for atoms, because they are accessed
626 * on many threads and we don't want to mess with their flags if we don't
627 * have to, and it is safe because atoms will never be replaced by an atom
628 * ref.
629 */
630 bool isDependedOn() const {
631 bool result = flags() & DEPENDED_ON_BIT;
632 MOZ_ASSERT_IF(result, !isRope() && !isAtom());
633 return result;
634 }
635
636 bool assertIsValidBase() const {
637 // See isDependedOn comment for why we're excluding atoms
638 return isAtom() || isDependedOn();
639 }
640
641 void setDependedOn() {
642 MOZ_ASSERT(!isRope());
643 if (isAtom()) {
644 return;
645 }
646 setFlagBit(DEPENDED_ON_BIT);
647 }
648
649 inline size_t allocSize() const;
650
651 /* Fallible conversions to more-derived string types. */
652
653 inline JSLinearString* ensureLinear(JSContext* cx);
654
655 /* Type query and debug-checked casts */
656
657 MOZ_ALWAYS_INLINE
658 bool isRope() const { return !(flags() & LINEAR_BIT); }
659
660 MOZ_ALWAYS_INLINE
661 JSRope& asRope() const {
662 MOZ_ASSERT(isRope());
663 return *(JSRope*)this;
664 }
665
666 MOZ_ALWAYS_INLINE
667 bool isLinear() const { return flags() & LINEAR_BIT; }
668
669 MOZ_ALWAYS_INLINE
670 JSLinearString& asLinear() const {
671 MOZ_ASSERT(JSString::isLinear());
672 return *(JSLinearString*)this;
673 }
674
675 MOZ_ALWAYS_INLINE
676 bool isDependent() const { return flags() & DEPENDENT_BIT; }
677
678 MOZ_ALWAYS_INLINE
679 bool isAtomRef() const {
680 return (flags() & ATOM_REF_BIT) && !(flags() & ATOM_BIT);
681 }
682
683 MOZ_ALWAYS_INLINE
684 JSDependentString& asDependent() const {
685 MOZ_ASSERT(isDependent());
686 return *(JSDependentString*)this;
687 }
688
689 MOZ_ALWAYS_INLINE
690 bool isExtensible() const {
691 return (flags() & TYPE_FLAGS_MASK) == EXTENSIBLE_FLAGS;
692 }
693
694 MOZ_ALWAYS_INLINE
695 JSExtensibleString& asExtensible() const {
696 MOZ_ASSERT(isExtensible());
697 return *(JSExtensibleString*)this;
698 }
699
700 MOZ_ALWAYS_INLINE
701 bool isInline() const { return flags() & INLINE_CHARS_BIT; }
702
703 MOZ_ALWAYS_INLINE
704 JSInlineString& asInline() const {
705 MOZ_ASSERT(isInline());
706 return *(JSInlineString*)this;
707 }
708
709 MOZ_ALWAYS_INLINE
710 bool isFatInline() const {
711 return (flags() & FAT_INLINE_MASK) == FAT_INLINE_MASK;
712 }
713
714 /* For hot code, prefer other type queries. */
715 bool isExternal() const {
716 return (flags() & TYPE_FLAGS_MASK) == EXTERNAL_FLAGS;
717 }
718
719 MOZ_ALWAYS_INLINE
720 JSExternalString& asExternal() const {
721 MOZ_ASSERT(isExternal());
722 return *(JSExternalString*)this;
723 }
724
725 MOZ_ALWAYS_INLINE
726 bool isAtom() const { return flags() & ATOM_BIT; }
727
728 MOZ_ALWAYS_INLINE
729 bool isPermanentAtom() const {
730 return (flags() & PERMANENT_ATOM_MASK) == PERMANENT_ATOM_MASK;
731 }
732
733 MOZ_ALWAYS_INLINE
734 JSAtom& asAtom() const {
735 MOZ_ASSERT(isAtom());
736 return *(JSAtom*)this;
737 }
738
739 MOZ_ALWAYS_INLINE
740 void setNonDeduplicatable() {
741 MOZ_ASSERT(isLinear());
742 MOZ_ASSERT(!isAtom());
743 setFlagBit(NON_DEDUP_BIT);
744 }
745
746 // After copying a string from the nursery to the tenured heap, adjust bits
747 // that no longer apply.
748 MOZ_ALWAYS_INLINE
749 void clearBitsOnTenure() {
750 MOZ_ASSERT(!isAtom());
751 clearFlagBit(NON_DEDUP_BIT | IN_STRING_TO_ATOM_CACHE);
752 }
753
754 // NON_DEDUP_BIT is only valid for linear non-atoms.
755 MOZ_ALWAYS_INLINE
756 bool isDeduplicatable() const {
757 MOZ_ASSERT(isLinear());
758 MOZ_ASSERT(!isAtom());
759 return !(flags() & NON_DEDUP_BIT);
760 }
761
762 void setInStringToAtomCache() {
763 MOZ_ASSERT(!isAtom());
764 setFlagBit(IN_STRING_TO_ATOM_CACHE);
765 }
766 bool inStringToAtomCache() const { return flags() & IN_STRING_TO_ATOM_CACHE; }
767
768 // Fills |array| with various strings that represent the different string
769 // kinds and character encodings.
770 static bool fillWithRepresentatives(JSContext* cx,
771 JS::Handle<js::ArrayObject*> array);
772
773 /* Only called by the GC for dependent strings. */
774
775 inline bool hasBase() const { return isDependent(); }
776
777 inline JSLinearString* base() const;
778
779 inline JSAtom* atom() const;
780
781 // The base may be forwarded and becomes a relocation overlay.
782 // The return value can be a relocation overlay when the base is forwarded,
783 // or the return value can be the actual base when it is not forwarded.
784 inline JSLinearString* nurseryBaseOrRelocOverlay() const;
785
786 inline bool canOwnDependentChars() const;
787
788 bool tryReplaceWithAtomRef(JSAtom* atom);
789
790 void traceBase(JSTracer* trc);
791
792 /* Only called by the GC for strings with the AllocKind::STRING kind. */
793
794 inline void finalize(JS::GCContext* gcx);
795
796 /* Gets the number of bytes that the chars take on the heap. */
797
798 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf);
799
800 bool hasOutOfLineChars() const {
801 return isLinear() && !isInline() && !isDependent() && !isExternal();
802 }
803
804 inline bool ownsMallocedChars() const;
805
806 bool hasStringBuffer() const {
807 MOZ_ASSERT_IF(flags() & HAS_STRING_BUFFER_BIT,
808 isLinear() && !isInline() && !isDependent() && !isExternal());
809 return flags() & HAS_STRING_BUFFER_BIT;
810 }
811
812 /* Encode as many scalar values of the string as UTF-8 as can fit
813 * into the caller-provided buffer replacing unpaired surrogates
814 * with the REPLACEMENT CHARACTER.
815 *
816 * Returns the number of code units read and the number of code units
817 * written.
818 *
819 * The semantics of this method match the semantics of
820 * TextEncoder.encodeInto().
821 *
822 * This function doesn't modify the representation -- rope, linear,
823 * flat, atom, etc. -- of this string. If this string is a rope,
824 * it also doesn't modify the representation of left or right halves
825 * of this string, or of those halves, and so on.
826 *
827 * Returns mozilla::Nothing on OOM.
828 */
829 mozilla::Maybe<std::tuple<size_t, size_t>> encodeUTF8Partial(
830 const JS::AutoRequireNoGC& nogc, mozilla::Span<char> buffer) const;
831
832 private:
833 // To help avoid writing Spectre-unsafe code, we only allow MacroAssembler
834 // to call the method below.
835 friend class js::jit::MacroAssembler;
836 static size_t offsetOfNonInlineChars() {
837 static_assert(
838 offsetof(JSString, d.s.u2.nonInlineCharsTwoByte) ==
839 offsetof(JSString, d.s.u2.nonInlineCharsLatin1),
840 "nonInlineCharsTwoByte and nonInlineCharsLatin1 must have same offset");
841 return offsetof(JSString, d.s.u2.nonInlineCharsTwoByte);
842 }
843
844 public:
845 static const JS::TraceKind TraceKind = JS::TraceKind::String;
846
847 JS::Zone* zone() const {
848 if (isTenured()) {
849 // Allow permanent atoms to be accessed across zones and runtimes.
850 if (isPermanentAtom()) {
851 return zoneFromAnyThread();
852 }
853 return asTenured().zone();
854 }
855 return nurseryZone();
856 }
857
858 void setLengthAndFlags(uint32_t len, uint32_t flags) {
859 setHeaderLengthAndFlags(len, flags);
860 }
861 void setFlagBit(uint32_t flag) { setHeaderFlagBit(flag); }
862 void clearFlagBit(uint32_t flag) { clearHeaderFlagBit(flag); }
863
864 void fixupAfterMovingGC() {}
865
866 js::gc::AllocKind getAllocKind() const {
867 using js::gc::AllocKind;
868 AllocKind kind;
869 if (isAtom()) {
870 if (isFatInline()) {
871 kind = AllocKind::FAT_INLINE_ATOM;
872 } else {
873 kind = AllocKind::ATOM;
874 }
875 } else if (isFatInline()) {
876 kind = AllocKind::FAT_INLINE_STRING;
877 } else if (isExternal()) {
878 kind = AllocKind::EXTERNAL_STRING;
879 } else {
880 kind = AllocKind::STRING;
881 }
882 MOZ_ASSERT_IF(isTenured(), kind == asTenured().getAllocKind());
883 return kind;
884 }
885
886 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
887 void dump() const;
888 void dump(js::GenericPrinter& out) const;
889 void dump(js::JSONPrinter& json) const;
890
891 void dumpCommonFields(js::JSONPrinter& json) const;
892 void dumpCharsFields(js::JSONPrinter& json) const;
893
894 void dumpFields(js::JSONPrinter& json) const;
895 void dumpStringContent(js::GenericPrinter& out) const;
896 void dumpPropertyName(js::GenericPrinter& out) const;
897
898 void dumpChars(js::GenericPrinter& out) const;
899 void dumpCharsSingleQuote(js::GenericPrinter& out) const;
900 void dumpCharsNoQuote(js::GenericPrinter& out) const;
901
902 template <typename CharT>
903 static void dumpCharsNoQuote(const CharT* s, size_t len,
904 js::GenericPrinter& out);
905
906 void dumpRepresentation() const;
907 void dumpRepresentation(js::GenericPrinter& out) const;
908 void dumpRepresentation(js::JSONPrinter& json) const;
909 void dumpRepresentationFields(js::JSONPrinter& json) const;
910
911 bool equals(const char* s);
912 #endif
913
914 void traceChildren(JSTracer* trc);
915
916 // Override base class implementation to tell GC about permanent atoms.
917 bool isPermanentAndMayBeShared() const { return isPermanentAtom(); }
918
919 static void addCellAddressToStoreBuffer(js::gc::StoreBuffer* buffer,
920 js::gc::Cell** cellp) {
921 buffer->putCell(reinterpret_cast<JSString**>(cellp));
922 }
923
924 static void removeCellAddressFromStoreBuffer(js::gc::StoreBuffer* buffer,
925 js::gc::Cell** cellp) {
926 buffer->unputCell(reinterpret_cast<JSString**>(cellp));
927 }
928
929 private:
930 JSString(const JSString& other) = delete;
931 void operator=(const JSString& other) = delete;
932
933 protected:
934 JSString() = default;
935 };
936
937 namespace js {
938
939 template <typename Wrapper, typename CharT>
940 class WrappedPtrOperations<JSString::OwnedChars<CharT>, Wrapper> {
941 const JSString::OwnedChars<CharT>& get() const {
942 return static_cast<const Wrapper*>(this)->get();
943 }
944
945 public:
946 explicit operator bool() const { return !!get(); }
947 mozilla::Span<CharT> span() const { return get().span(); }
948 CharT* data() const { return get().data(); }
949 size_t length() const { return get().length(); }
950 size_t size() const { return get().size(); }
951 bool isMalloced() const { return get().isMalloced(); }
952 bool hasStringBuffer() const { return get().hasStringBuffer(); }
953 };
954
955 template <typename Wrapper, typename CharT>
956 class MutableWrappedPtrOperations<JSString::OwnedChars<CharT>, Wrapper>
957 : public WrappedPtrOperations<JSString::OwnedChars<CharT>, Wrapper> {
958 JSString::OwnedChars<CharT>& get() {
959 return static_cast<Wrapper*>(this)->get();
960 }
961
962 public:
963 CharT* release() { return get().release(); }
964 void reset() { get().reset(); }
965 void ensureNonNursery() { get().ensureNonNursery(); }
966 };
967
968 } /* namespace js */
969
970 class JSRope : public JSString {
971 friend class js::gc::CellAllocator;
972
973 template <typename CharT>
974 js::UniquePtr<CharT[], JS::FreePolicy> copyCharsInternal(
975 JSContext* cx, arena_id_t destArenaId) const;
976
977 enum UsingBarrier : bool { NoBarrier = false, WithIncrementalBarrier = true };
978
979 friend class JSString;
980 JSLinearString* flatten(JSContext* maybecx);
981
982 JSLinearString* flattenInternal();
983 template <UsingBarrier usingBarrier>
984 JSLinearString* flattenInternal();
985
986 template <UsingBarrier usingBarrier, typename CharT>
987 static JSLinearString* flattenInternal(JSRope* root);
988
989 template <UsingBarrier usingBarrier>
990 static void ropeBarrierDuringFlattening(JSRope* rope);
991
992 JSRope(JSString* left, JSString* right, size_t length);
993
994 public:
995 template <js::AllowGC allowGC>
996 static inline JSRope* new_(
997 JSContext* cx,
998 typename js::MaybeRooted<JSString*, allowGC>::HandleType left,
999 typename js::MaybeRooted<JSString*, allowGC>::HandleType right,
1000 size_t length, js::gc::Heap = js::gc::Heap::Default);
1001
1002 js::UniquePtr<JS::Latin1Char[], JS::FreePolicy> copyLatin1Chars(
1003 JSContext* maybecx, arena_id_t destArenaId) const;
1004 JS::UniqueTwoByteChars copyTwoByteChars(JSContext* maybecx,
1005 arena_id_t destArenaId) const;
1006
1007 template <typename CharT>
1008 js::UniquePtr<CharT[], JS::FreePolicy> copyChars(
1009 JSContext* maybecx, arena_id_t destArenaId) const;
1010
1011 // Hash function specific for ropes that avoids allocating a temporary
1012 // string. There are still allocations internally so it's technically
1013 // fallible.
1014 //
1015 // Returns the same value as if this were a linear string being hashed.
1016 [[nodiscard]] bool hash(uint32_t* outhHash) const;
1017
1018 // The process of flattening a rope temporarily overwrites the left pointer of
1019 // interior nodes in the rope DAG with the parent pointer.
1020 bool isBeingFlattened() const { return flags() & FLATTEN_MASK; }
1021
1022 JSString* leftChild() const {
1023 MOZ_ASSERT(isRope());
1024 MOZ_ASSERT(!isBeingFlattened()); // Flattening overwrites this field.
1025 return d.s.u2.left;
1026 }
1027
1028 JSString* rightChild() const {
1029 MOZ_ASSERT(isRope());
1030 return d.s.u3.right;
1031 }
1032
1033 void traceChildren(JSTracer* trc);
1034
1035 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1036 void dumpOwnRepresentationFields(js::JSONPrinter& json) const;
1037 #endif
1038
1039 private:
1040 // To help avoid writing Spectre-unsafe code, we only allow MacroAssembler
1041 // to call the methods below.
1042 friend class js::jit::MacroAssembler;
1043
1044 static size_t offsetOfLeft() { return offsetof(JSRope, d.s.u2.left); }
1045 static size_t offsetOfRight() { return offsetof(JSRope, d.s.u3.right); }
1046 };
1047
1048 static_assert(sizeof(JSRope) == sizeof(JSString),
1049 "string subclasses must be binary-compatible with JSString");
1050
1051 /*
1052 * There are optimized entry points for some string allocation functions.
1053 *
1054 * The meaning of suffix:
1055 * * "MaybeDeflate": for char16_t variant, characters can fit Latin1
1056 * * "DontDeflate": for char16_t variant, characters don't fit Latin1
1057 * * "NonStatic": characters don't match StaticStrings
1058 * * "ValidLength": length fits JSString::MAX_LENGTH
1059 */
1060
1061 class JSLinearString : public JSString {
1062 friend class JSString;
1063 friend class JS::AutoStableStringChars;
1064 friend class js::gc::TenuringTracer;
1065 friend class js::gc::CellAllocator;
1066 friend class JSDependentString; // To allow access when used as base.
1067
1068 /* Vacuous and therefore unimplemented. */
1069 JSLinearString* ensureLinear(JSContext* cx) = delete;
1070 bool isLinear() const = delete;
1071 JSLinearString& asLinear() const = delete;
1072
1073 JSLinearString(const char16_t* chars, size_t length, bool hasBuffer);
1074 JSLinearString(const JS::Latin1Char* chars, size_t length, bool hasBuffer);
1075 template <typename CharT>
1076 explicit inline JSLinearString(JS::MutableHandle<OwnedChars<CharT>> chars);
1077
1078 protected:
1079 // Used to construct subclasses that do a full initialization themselves.
1080 JSLinearString() = default;
1081
1082 /* Returns void pointer to latin1/twoByte chars, for finalizers. */
1083 MOZ_ALWAYS_INLINE
1084 void* nonInlineCharsRaw() const {
1085 MOZ_ASSERT(!isInline());
1086 static_assert(
1087 offsetof(JSLinearString, d.s.u2.nonInlineCharsTwoByte) ==
1088 offsetof(JSLinearString, d.s.u2.nonInlineCharsLatin1),
1089 "nonInlineCharsTwoByte and nonInlineCharsLatin1 must have same offset");
1090 return (void*)d.s.u2.nonInlineCharsTwoByte;
1091 }
1092
1093 MOZ_ALWAYS_INLINE const JS::Latin1Char* rawLatin1Chars() const;
1094 MOZ_ALWAYS_INLINE const char16_t* rawTwoByteChars() const;
1095
1096 public:
1097 template <js::AllowGC allowGC, typename CharT>
1098 static inline JSLinearString* new_(JSContext* cx,
1099 JS::MutableHandle<OwnedChars<CharT>> chars,
1100 js::gc::Heap heap);
1101
1102 template <js::AllowGC allowGC, typename CharT>
1103 static inline JSLinearString* newValidLength(
1104 JSContext* cx, JS::MutableHandle<OwnedChars<CharT>> chars,
1105 js::gc::Heap heap);
1106
1107 // Convert a plain linear string to an extensible string. For testing. The
1108 // caller must ensure that it is a plain or extensible string already, and
1109 // that `capacity` is adequate.
1110 JSExtensibleString& makeExtensible(size_t capacity);
1111
1112 template <typename CharT>
1113 MOZ_ALWAYS_INLINE const CharT* nonInlineChars(
1114 const JS::AutoRequireNoGC& nogc) const;
1115
1116 MOZ_ALWAYS_INLINE
1117 const JS::Latin1Char* nonInlineLatin1Chars(
1118 const JS::AutoRequireNoGC& nogc) const {
1119 MOZ_ASSERT(!isInline());
1120 MOZ_ASSERT(hasLatin1Chars());
1121 return d.s.u2.nonInlineCharsLatin1;
1122 }
1123
1124 MOZ_ALWAYS_INLINE
1125 const char16_t* nonInlineTwoByteChars(const JS::AutoRequireNoGC& nogc) const {
1126 MOZ_ASSERT(!isInline());
1127 MOZ_ASSERT(hasTwoByteChars());
1128 return d.s.u2.nonInlineCharsTwoByte;
1129 }
1130
1131 template <typename CharT>
1132 MOZ_ALWAYS_INLINE const CharT* chars(const JS::AutoRequireNoGC& nogc) const;
1133
1134 MOZ_ALWAYS_INLINE
1135 const JS::Latin1Char* latin1Chars(const JS::AutoRequireNoGC& nogc) const {
1136 return rawLatin1Chars();
1137 }
1138
1139 MOZ_ALWAYS_INLINE
1140 const char16_t* twoByteChars(const JS::AutoRequireNoGC& nogc) const {
1141 return rawTwoByteChars();
1142 }
1143
1144 mozilla::Range<const JS::Latin1Char> latin1Range(
1145 const JS::AutoRequireNoGC& nogc) const {
1146 MOZ_ASSERT(JSString::isLinear());
1147 return mozilla::Range<const JS::Latin1Char>(latin1Chars(nogc), length());
1148 }
1149
1150 mozilla::Range<const char16_t> twoByteRange(
1151 const JS::AutoRequireNoGC& nogc) const {
1152 MOZ_ASSERT(JSString::isLinear());
1153 return mozilla::Range<const char16_t>(twoByteChars(nogc), length());
1154 }
1155
1156 template <typename CharT>
1157 mozilla::Range<const CharT> range(const JS::AutoRequireNoGC& nogc) const {
1158 if constexpr (std::is_same_v<CharT, JS::Latin1Char>) {
1159 return latin1Range(nogc);
1160 } else {
1161 return twoByteRange(nogc);
1162 }
1163 }
1164
1165 MOZ_ALWAYS_INLINE
1166 char16_t latin1OrTwoByteChar(size_t index) const {
1167 MOZ_ASSERT(JSString::isLinear());
1168 MOZ_ASSERT(index < length());
1169 JS::AutoCheckCannotGC nogc;
1170 return hasLatin1Chars() ? latin1Chars(nogc)[index]
1171 : twoByteChars(nogc)[index];
1172 }
1173
1174 bool isIndexSlow(uint32_t* indexp) const {
1175 MOZ_ASSERT(JSString::isLinear());
1176 size_t len = length();
1177 if (len == 0 || len > js::UINT32_CHAR_BUFFER_LENGTH) {
1178 return false;
1179 }
1180 JS::AutoCheckCannotGC nogc;
1181 if (hasLatin1Chars()) {
1182 const JS::Latin1Char* s = latin1Chars(nogc);
1183 return mozilla::IsAsciiDigit(*s) &&
1184 js::CheckStringIsIndex(s, len, indexp);
1185 }
1186 const char16_t* s = twoByteChars(nogc);
1187 return mozilla::IsAsciiDigit(*s) && js::CheckStringIsIndex(s, len, indexp);
1188 }
1189
1190 // Returns true if this string's characters store an unsigned 32-bit integer
1191 // value less than or equal to MAX_ARRAY_INDEX, initializing *indexp to that
1192 // value if so. Leading '0' isn't allowed except 0 itself.
1193 // (Thus if calling isIndex returns true, js::IndexToString(cx, *indexp) will
1194 // be a string equal to this string.)
1195 inline bool isIndex(uint32_t* indexp) const;
1196
1197 // Return whether the characters of this string can be moved by minor or
1198 // compacting GC.
1199 inline bool hasMovableChars() const;
1200
1201 bool hasCharsInCollectedNurseryRegion() const;
1202
1203 void maybeInitializeIndexValue(uint32_t index, bool allowAtom = false) {
1204 MOZ_ASSERT(JSString::isLinear());
1205 MOZ_ASSERT_IF(hasIndexValue(), getIndexValue() == index);
1206 MOZ_ASSERT_IF(!allowAtom, !isAtom());
1207
1208 if (hasIndexValue() || index > UINT16_MAX) {
1209 return;
1210 }
1211
1212 mozilla::DebugOnly<uint32_t> containedIndex;
1213 MOZ_ASSERT(isIndexSlow(&containedIndex));
1214 MOZ_ASSERT(index == containedIndex);
1215
1216 setFlagBit((index << INDEX_VALUE_SHIFT) | INDEX_VALUE_BIT);
1217 MOZ_ASSERT(getIndexValue() == index);
1218 }
1219
1220 mozilla::StringBuffer* stringBuffer() const {
1221 MOZ_ASSERT(hasStringBuffer());
1222 auto* chars = nonInlineCharsRaw();
1223 return mozilla::StringBuffer::FromData(const_cast<void*>(chars));
1224 }
1225
1226 /*
1227 * Returns a property name represented by this string, or null on failure.
1228 * You must verify that this is not an index per isIndex before calling
1229 * this method.
1230 */
1231 inline js::PropertyName* toPropertyName(JSContext* cx);
1232
1233 // Make sure chars are not in the nursery, mallocing and copying if necessary.
1234 // Should only be called during minor GC on a string that has been promoted
1235 // to the tenured heap and may still point to nursery-allocated chars.
1236 template <typename CharT>
1237 inline size_t maybeMallocCharsOnPromotion(js::Nursery* nursery);
1238
1239 // Handle an edge case where a dependent chain N1 -> T2 -> N3 cannot handle N3
1240 // moving its chars (or more specifically, updating N1 to the new chars.) When
1241 // this is detected, convert N1 to a regular string with its own storage.
1242 //
1243 // Returns whether the chars were cloned.
1244 template <typename CharT>
1245 static void maybeCloneCharsOnPromotionTyped(JSLinearString* str);
1246
1247 static void maybeCloneCharsOnPromotion(JSLinearString* str) {
1248 if (str->hasLatin1Chars()) {
1249 maybeCloneCharsOnPromotionTyped<JS::Latin1Char>(str);
1250 } else {
1251 maybeCloneCharsOnPromotionTyped<char16_t>(str);
1252 }
1253 }
1254
1255 inline void finalize(JS::GCContext* gcx);
1256 inline size_t allocSize() const;
1257
1258 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1259 void dumpOwnRepresentationFields(js::JSONPrinter& json) const;
1260 #endif
1261
1262 // Make a partially-initialized string safe for finalization.
1263 inline void disownCharsBecauseError();
1264 };
1265
1266 static_assert(sizeof(JSLinearString) == sizeof(JSString),
1267 "string subclasses must be binary-compatible with JSString");
1268
1269 namespace JS {
1270 enum class ContractBaseChain : bool { AllowLong = false, Contract = true };
1271 }
1272
1273 class JSDependentString : public JSLinearString {
1274 friend class JSString;
1275 friend class js::gc::CellAllocator;
1276
1277 JSDependentString(JSLinearString* base, size_t start, size_t length);
1278
1279 // For JIT string allocation.
1280 JSDependentString() = default;
1281
1282 /* Vacuous and therefore unimplemented. */
1283 bool isDependent() const = delete;
1284 JSDependentString& asDependent() const = delete;
1285
1286 /* The offset of this string's chars in base->chars(). */
1287 MOZ_ALWAYS_INLINE size_t baseOffset() const {
1288 MOZ_ASSERT(JSString::isDependent());
1289 JS::AutoCheckCannotGC nogc;
1290 size_t offset;
1291 if (hasTwoByteChars()) {
1292 offset = twoByteChars(nogc) - base()->twoByteChars(nogc);
1293 } else {
1294 offset = latin1Chars(nogc) - base()->latin1Chars(nogc);
1295 }
1296 MOZ_ASSERT(offset < base()->length());
1297 return offset;
1298 }
1299
1300 public:
1301 template <JS::ContractBaseChain contract>
1302 static inline JSLinearString* newImpl_(JSContext* cx, JSLinearString* base,
1303 size_t start, size_t length,
1304 js::gc::Heap heap);
1305
1306 // This will always return a dependent string, and will assert if the chars
1307 // could fit into an inline string.
1308 static inline JSLinearString* new_(JSContext* cx, JSLinearString* base,
1309 size_t start, size_t length,
1310 js::gc::Heap heap);
1311
1312 // Only called by the GC during nursery collection.
1313 void setBase(JSLinearString* newBase);
1314
1315 template <typename T>
1316 void relocateBaseAndChars(JSLinearString* base, T chars, size_t offset) {
1317 MOZ_ASSERT(base->assertIsValidBase());
1318 bool usesStringBuffer = base->hasStringBuffer();
1319 setNonInlineChars(chars + offset, usesStringBuffer);
1320 setBase(base);
1321 }
1322
1323 JSLinearString* rootBaseDuringMinorGC();
1324
1325 template <typename CharT>
1326 inline void updateToPromotedBaseImpl(JSLinearString* base);
1327
1328 inline void updateToPromotedBase(JSLinearString* base);
1329
1330 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1331 void dumpOwnRepresentationFields(js::JSONPrinter& json) const;
1332 #endif
1333
1334 private:
1335 // To help avoid writing Spectre-unsafe code, we only allow MacroAssembler
1336 // to call the method below.
1337 friend class js::jit::MacroAssembler;
1338
1339 inline static size_t offsetOfBase() {
1340 return offsetof(JSDependentString, d.s.u3.base);
1341 }
1342 };
1343
1344 static_assert(sizeof(JSDependentString) == sizeof(JSString),
1345 "string subclasses must be binary-compatible with JSString");
1346
1347 class JSAtomRefString : public JSDependentString {
1348 friend class JSString;
1349 friend class js::gc::CellAllocator;
1350 friend class js::jit::MacroAssembler;
1351
1352 public:
1353 inline static size_t offsetOfAtom() {
1354 return offsetof(JSAtomRefString, d.s.u3.atom);
1355 }
1356 };
1357
1358 static_assert(sizeof(JSAtomRefString) == sizeof(JSString),
1359 "string subclasses must be binary-compatible with JSString");
1360
1361 class JSExtensibleString : public JSLinearString {
1362 /* Vacuous and therefore unimplemented. */
1363 bool isExtensible() const = delete;
1364 JSExtensibleString& asExtensible() const = delete;
1365
1366 public:
1367 MOZ_ALWAYS_INLINE
1368 size_t capacity() const {
1369 MOZ_ASSERT(JSString::isExtensible());
1370 return d.s.u3.capacity;
1371 }
1372
1373 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1374 void dumpOwnRepresentationFields(js::JSONPrinter& json) const;
1375 #endif
1376 };
1377
1378 static_assert(sizeof(JSExtensibleString) == sizeof(JSString),
1379 "string subclasses must be binary-compatible with JSString");
1380
1381 class JSInlineString : public JSLinearString {
1382 public:
1383 MOZ_ALWAYS_INLINE
1384 const JS::Latin1Char* latin1Chars(const JS::AutoRequireNoGC& nogc) const {
1385 MOZ_ASSERT(JSString::isInline());
1386 MOZ_ASSERT(hasLatin1Chars());
1387 return d.inlineStorageLatin1;
1388 }
1389
1390 MOZ_ALWAYS_INLINE
1391 const char16_t* twoByteChars(const JS::AutoRequireNoGC& nogc) const {
1392 MOZ_ASSERT(JSString::isInline());
1393 MOZ_ASSERT(hasTwoByteChars());
1394 return d.inlineStorageTwoByte;
1395 }
1396
1397 template <typename CharT>
1398 static bool lengthFits(size_t length);
1399
1400 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1401 void dumpOwnRepresentationFields(js::JSONPrinter& json) const;
1402 #endif
1403
1404 private:
1405 // To help avoid writing Spectre-unsafe code, we only allow MacroAssembler
1406 // to call the method below.
1407 friend class js::jit::MacroAssembler;
1408 static size_t offsetOfInlineStorage() {
1409 return offsetof(JSInlineString, d.inlineStorageTwoByte);
1410 }
1411 };
1412
1413 static_assert(sizeof(JSInlineString) == sizeof(JSString),
1414 "string subclasses must be binary-compatible with JSString");
1415
1416 /*
1417 * On 32-bit platforms, JSThinInlineString can store 8 Latin1 characters or 4
1418 * TwoByte characters inline. On 64-bit platforms, these numbers are 16 and 8,
1419 * respectively.
1420 */
1421 class JSThinInlineString : public JSInlineString {
1422 friend class js::gc::CellAllocator;
1423
1424 // The constructors return a mutable pointer to the data, because the first
1425 // thing any creator will do is copy in the string value. This also
1426 // conveniently allows doing overload resolution on CharT.
1427 explicit JSThinInlineString(size_t length, JS::Latin1Char** chars);
1428 explicit JSThinInlineString(size_t length, char16_t** chars);
1429
1430 // For JIT string allocation.
1431 JSThinInlineString() = default;
1432
1433 public:
1434 static constexpr size_t InlineBytes = NUM_INLINE_CHARS_LATIN1;
1435
1436 static const size_t MAX_LENGTH_LATIN1 = NUM_INLINE_CHARS_LATIN1;
1437 static const size_t MAX_LENGTH_TWO_BYTE = NUM_INLINE_CHARS_TWO_BYTE;
1438
1439 template <js::AllowGC allowGC>
1440 static inline JSThinInlineString* new_(JSContext* cx, js::gc::Heap heap);
1441
1442 template <typename CharT>
1443 static bool lengthFits(size_t length);
1444 };
1445
1446 static_assert(sizeof(JSThinInlineString) == sizeof(JSString),
1447 "string subclasses must be binary-compatible with JSString");
1448
1449 /*
1450 * On both 32-bit and 64-bit platforms, MAX_LENGTH_TWO_BYTE is 12 and
1451 * MAX_LENGTH_LATIN1 is 24. This is deliberate, in order to minimize potential
1452 * performance differences between 32-bit and 64-bit platforms.
1453 *
1454 * There are still some differences due to NUM_INLINE_CHARS_* being different.
1455 * E.g. TwoByte strings of length 5--8 will be JSFatInlineStrings on 32-bit
1456 * platforms and JSThinInlineStrings on 64-bit platforms. But the more
1457 * significant transition from inline strings to non-inline strings occurs at
1458 * length 12 (for TwoByte strings) and 24 (Latin1 strings) on both 32-bit and
1459 * 64-bit platforms.
1460 */
1461 class JSFatInlineString : public JSInlineString {
1462 friend class js::gc::CellAllocator;
1463
1464 static const size_t INLINE_EXTENSION_CHARS_LATIN1 =
1465 24 - NUM_INLINE_CHARS_LATIN1;
1466 static const size_t INLINE_EXTENSION_CHARS_TWO_BYTE =
1467 12 - NUM_INLINE_CHARS_TWO_BYTE;
1468
1469 // The constructors return a mutable pointer to the data, because the first
1470 // thing any creator will do is copy in the string value. This also
1471 // conveniently allows doing overload resolution on CharT.
1472 explicit JSFatInlineString(size_t length, JS::Latin1Char** chars);
1473 explicit JSFatInlineString(size_t length, char16_t** chars);
1474
1475 // For JIT string allocation.
1476 JSFatInlineString() = default;
1477
1478 protected: /* to fool clang into not warning this is unused */
1479 union {
1480 char inlineStorageExtensionLatin1[INLINE_EXTENSION_CHARS_LATIN1];
1481 char16_t inlineStorageExtensionTwoByte[INLINE_EXTENSION_CHARS_TWO_BYTE];
1482 };
1483
1484 public:
1485 template <js::AllowGC allowGC>
1486 static inline JSFatInlineString* new_(JSContext* cx, js::gc::Heap heap);
1487
1488 static const size_t MAX_LENGTH_LATIN1 =
1489 JSString::NUM_INLINE_CHARS_LATIN1 + INLINE_EXTENSION_CHARS_LATIN1;
1490
1491 static const size_t MAX_LENGTH_TWO_BYTE =
1492 JSString::NUM_INLINE_CHARS_TWO_BYTE + INLINE_EXTENSION_CHARS_TWO_BYTE;
1493
1494 template <typename CharT>
1495 static bool lengthFits(size_t length);
1496
1497 // Only called by the GC for strings with the AllocKind::FAT_INLINE_STRING
1498 // kind.
1499 MOZ_ALWAYS_INLINE void finalize(JS::GCContext* gcx);
1500 };
1501
1502 static_assert(sizeof(JSFatInlineString) % js::gc::CellAlignBytes == 0,
1503 "fat inline strings shouldn't waste space up to the next cell "
1504 "boundary");
1505
1506 class JSExternalString : public JSLinearString {
1507 friend class js::gc::CellAllocator;
1508
1509 JSExternalString(const JS::Latin1Char* chars, size_t length,
1510 const JSExternalStringCallbacks* callbacks);
1511 JSExternalString(const char16_t* chars, size_t length,
1512 const JSExternalStringCallbacks* callbacks);
1513
1514 /* Vacuous and therefore unimplemented. */
1515 bool isExternal() const = delete;
1516 JSExternalString& asExternal() const = delete;
1517
1518 template <typename CharT>
1519 static inline JSExternalString* newImpl(
1520 JSContext* cx, const CharT* chars, size_t length,
1521 const JSExternalStringCallbacks* callbacks);
1522
1523 public:
1524 static inline JSExternalString* new_(
1525 JSContext* cx, const JS::Latin1Char* chars, size_t length,
1526 const JSExternalStringCallbacks* callbacks);
1527 static inline JSExternalString* new_(
1528 JSContext* cx, const char16_t* chars, size_t length,
1529 const JSExternalStringCallbacks* callbacks);
1530
1531 const JSExternalStringCallbacks* callbacks() const {
1532 MOZ_ASSERT(JSString::isExternal());
1533 return d.s.u3.externalCallbacks;
1534 }
1535
1536 // External chars are never allocated inline or in the nursery, so we can
1537 // safely expose this without requiring an AutoCheckCannotGC argument.
1538 const JS::Latin1Char* latin1Chars() const { return rawLatin1Chars(); }
1539 const char16_t* twoByteChars() const { return rawTwoByteChars(); }
1540
1541 // Only called by the GC for strings with the AllocKind::EXTERNAL_STRING
1542 // kind.
1543 inline void finalize(JS::GCContext* gcx);
1544
1545 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1546 void dumpOwnRepresentationFields(js::JSONPrinter& json) const;
1547 #endif
1548 };
1549
1550 static_assert(sizeof(JSExternalString) == sizeof(JSString),
1551 "string subclasses must be binary-compatible with JSString");
1552
1553 class JSAtom : public JSLinearString {
1554 /* Vacuous and therefore unimplemented. */
1555 bool isAtom() const = delete;
1556 JSAtom& asAtom() const = delete;
1557
1558 public:
1559 template <typename CharT>
1560 static inline JSAtom* newValidLength(JSContext* cx, OwnedChars<CharT>& chars,
1561 js::HashNumber hash);
1562
1563 /* Returns the PropertyName for this. isIndex() must be false. */
1564 inline js::PropertyName* asPropertyName();
1565
1566 MOZ_ALWAYS_INLINE
1567 bool isPermanent() const { return JSString::isPermanentAtom(); }
1568
1569 MOZ_ALWAYS_INLINE
1570 void makePermanent() {
1571 MOZ_ASSERT(JSString::isAtom());
1572 setFlagBit(PERMANENT_ATOM_MASK);
1573 }
1574
1575 MOZ_ALWAYS_INLINE bool isIndex() const {
1576 MOZ_ASSERT(JSString::isAtom());
1577 mozilla::DebugOnly<uint32_t> index;
1578 MOZ_ASSERT(!!(flags() & ATOM_IS_INDEX_BIT) == isIndexSlow(&index));
1579 return flags() & ATOM_IS_INDEX_BIT;
1580 }
1581 MOZ_ALWAYS_INLINE bool isIndex(uint32_t* index) const {
1582 MOZ_ASSERT(JSString::isAtom());
1583 if (!isIndex()) {
1584 return false;
1585 }
1586 *index = hasIndexValue() ? getIndexValue() : getIndexSlow();
1587 return true;
1588 }
1589
1590 uint32_t getIndexSlow() const;
1591
1592 void setIsIndex(uint32_t index) {
1593 MOZ_ASSERT(JSString::isAtom());
1594 setFlagBit(ATOM_IS_INDEX_BIT);
1595 maybeInitializeIndexValue(index, /* allowAtom = */ true);
1596 }
1597
1598 MOZ_ALWAYS_INLINE bool isPinned() const { return flags() & PINNED_ATOM_BIT; }
1599
1600 void setPinned() {
1601 MOZ_ASSERT(!isPinned());
1602 setFlagBit(PINNED_ATOM_BIT);
1603 }
1604
1605 inline js::HashNumber hash() const;
1606
1607 template <typename CharT>
1608 static bool lengthFitsInline(size_t length);
1609
1610 #if defined(DEBUG) || defined(JS_JITSPEW) || defined(JS_CACHEIR_SPEW)
1611 void dump(js::GenericPrinter& out);
1612 void dump();
1613 #endif
1614 };
1615
1616 namespace js {
1617
1618 class NormalAtom : public JSAtom {
1619 friend class gc::CellAllocator;
1620
1621 protected:
1622 static constexpr size_t ExtensionBytes =
1623 js::gc::CellAlignBytes - sizeof(js::HashNumber);
1624
1625 char inlineStorage_[ExtensionBytes];
1626 HashNumber hash_;
1627
1628 // For subclasses to call.
1629 explicit NormalAtom(js::HashNumber hash) : hash_(hash) {}
1630
1631 // Out of line atoms, mimicking JSLinearString constructor.
1632 template <typename CharT>
1633 NormalAtom(const OwnedChars<CharT>& chars, js::HashNumber hash);
1634
1635 public:
1636 HashNumber hash() const { return hash_; }
1637
1638 static constexpr size_t offsetOfHash() { return offsetof(NormalAtom, hash_); }
1639 };
1640
1641 static_assert(sizeof(NormalAtom) ==
1642 js::RoundUp(sizeof(JSString) + sizeof(js::HashNumber),
1643 js::gc::CellAlignBytes),
1644 "NormalAtom must have size of a string + HashNumber, "
1645 "aligned to gc::CellAlignBytes");
1646
1647 class ThinInlineAtom : public NormalAtom {
1648 friend class gc::CellAllocator;
1649
1650 public:
1651 static constexpr size_t MAX_LENGTH_LATIN1 =
1652 NUM_INLINE_CHARS_LATIN1 + ExtensionBytes / sizeof(JS::Latin1Char);
1653 static constexpr size_t MAX_LENGTH_TWO_BYTE =
1654 NUM_INLINE_CHARS_TWO_BYTE + ExtensionBytes / sizeof(char16_t);
1655
1656 #ifdef JS_64BIT
1657 // Fat and Thin inline atoms are the same size. Only use fat.
1658 static constexpr bool EverInstantiated = false;
1659 #else
1660 static constexpr bool EverInstantiated = true;
1661 #endif
1662
1663 protected:
1664 // Mimicking JSThinInlineString constructors.
1665 #ifdef JS_64BIT
1666 ThinInlineAtom(size_t length, JS::Latin1Char** chars,
1667 js::HashNumber hash) = delete;
1668 ThinInlineAtom(size_t length, char16_t** chars, js::HashNumber hash) = delete;
1669 #else
1670 ThinInlineAtom(size_t length, JS::Latin1Char** chars, js::HashNumber hash);
1671 ThinInlineAtom(size_t length, char16_t** chars, js::HashNumber hash);
1672 #endif
1673
1674 public:
1675 template <typename CharT>
1676 static bool lengthFits(size_t length) {
1677 if constexpr (sizeof(CharT) == sizeof(JS::Latin1Char)) {
1678 return length <= MAX_LENGTH_LATIN1;
1679 } else {
1680 return length <= MAX_LENGTH_TWO_BYTE;
1681 }
1682 }
1683 };
1684
1685 // FatInlineAtom is basically a JSFatInlineString, except it has a hash value in
1686 // the last word that reduces the inline char storage.
1687 class FatInlineAtom : public JSAtom {
1688 friend class gc::CellAllocator;
1689
1690 // The space available for storing inline characters. It's the same amount of
1691 // space as a JSFatInlineString, except we take the hash value out of it.
1692 static constexpr size_t InlineBytes = sizeof(JSFatInlineString) -
1693 sizeof(JSString::Base) -
1694 sizeof(js::HashNumber);
1695
1696 static constexpr size_t ExtensionBytes =
1697 InlineBytes - JSThinInlineString::InlineBytes;
1698
1699 public:
1700 static constexpr size_t MAX_LENGTH_LATIN1 =
1701 InlineBytes / sizeof(JS::Latin1Char);
1702 static constexpr size_t MAX_LENGTH_TWO_BYTE = InlineBytes / sizeof(char16_t);
1703
1704 protected: // Silence Clang unused-field warning.
1705 char inlineStorage_[ExtensionBytes];
1706 HashNumber hash_;
1707
1708 // Mimicking JSFatInlineString constructors.
1709 explicit FatInlineAtom(size_t length, JS::Latin1Char** chars,
1710 js::HashNumber hash);
1711 explicit FatInlineAtom(size_t length, char16_t** chars, js::HashNumber hash);
1712
1713 public:
1714 HashNumber hash() const { return hash_; }
1715
1716 inline void finalize(JS::GCContext* gcx);
1717
1718 static constexpr size_t offsetOfHash() {
1719 static_assert(
1720 sizeof(FatInlineAtom) ==
1721 js::RoundUp(sizeof(JSThinInlineString) +
1722 FatInlineAtom::ExtensionBytes + sizeof(HashNumber),
1723 gc::CellAlignBytes),
1724 "FatInlineAtom must have size of a thin inline string + "
1725 "extension bytes if any + HashNumber, "
1726 "aligned to gc::CellAlignBytes");
1727
1728 return offsetof(FatInlineAtom, hash_);
1729 }
1730
1731 template <typename CharT>
1732 static bool lengthFits(size_t length) {
1733 return length * sizeof(CharT) <= InlineBytes;
1734 }
1735 };
1736
1737 static_assert(sizeof(FatInlineAtom) == sizeof(JSFatInlineString),
1738 "FatInlineAtom must be the same size as a fat inline string");
1739
1740 // When an algorithm does not need a string represented as a single linear
1741 // array of characters, this range utility may be used to traverse the string a
1742 // sequence of linear arrays of characters. This avoids flattening ropes.
1743 template <size_t Size = 16>
1744 class StringSegmentRange {
1745 // If malloc() shows up in any profiles from this vector, we can add a new
1746 // StackAllocPolicy which stashes a reusable freed-at-gc buffer in the cx.
1747 using StackVector = JS::GCVector<JSString*, Size>;
1748 Rooted<StackVector> stack;
1749 Rooted<JSLinearString*> cur;
1750
1751 bool settle(JSString* str) {
1752 while (str->isRope()) {
1753 JSRope& rope = str->asRope();
1754 if (!stack.append(rope.rightChild())) {
1755 return false;
1756 }
1757 str = rope.leftChild();
1758 }
1759 cur = &str->asLinear();
1760 return true;
1761 }
1762
1763 public:
1764 explicit StringSegmentRange(JSContext* cx)
1765 : stack(cx, StackVector(cx)), cur(cx) {}
1766
1767 [[nodiscard]] bool init(JSString* str) {
1768 MOZ_ASSERT(stack.empty());
1769 return settle(str);
1770 }
1771
1772 bool empty() const { return cur == nullptr; }
1773
1774 JSLinearString* front() const {
1775 MOZ_ASSERT(!cur->isRope());
1776 return cur;
1777 }
1778
1779 [[nodiscard]] bool popFront() {
1780 MOZ_ASSERT(!empty());
1781 if (stack.empty()) {
1782 cur = nullptr;
1783 return true;
1784 }
1785 return settle(stack.popCopy());
1786 }
1787 };
1788
1789 } // namespace js
1790
1791 inline js::HashNumber JSAtom::hash() const {
1792 if (isFatInline()) {
1793 return static_cast<const js::FatInlineAtom*>(this)->hash();
1794 }
1795 return static_cast<const js::NormalAtom*>(this)->hash();
1796 }
1797
1798 namespace js {
1799
1800 /*
1801 * Represents an atomized string which does not contain an index (that is, an
1802 * unsigned 32-bit value). Thus for any PropertyName propname,
1803 * ToString(ToUint32(propname)) never equals propname.
1804 *
1805 * To more concretely illustrate the utility of PropertyName, consider that it
1806 * is used to partition, in a type-safe manner, the ways to refer to a
1807 * property, as follows:
1808 *
1809 * - uint32_t indexes,
1810 * - PropertyName strings which don't encode uint32_t indexes,
1811 * - Symbol, and
1812 * - JS::PropertyKey::isVoid.
1813 */
1814 class PropertyName : public JSAtom {
1815 private:
1816 /* Vacuous and therefore unimplemented. */
1817 PropertyName* asPropertyName() = delete;
1818 };
1819
1820 static_assert(sizeof(PropertyName) == sizeof(JSString),
1821 "string subclasses must be binary-compatible with JSString");
1822
1823 static MOZ_ALWAYS_INLINE jsid NameToId(PropertyName* name) {
1824 return JS::PropertyKey::NonIntAtom(name);
1825 }
1826
1827 using PropertyNameVector = JS::GCVector<PropertyName*>;
1828
1829 template <typename CharT>
1830 void CopyChars(CharT* dest, const JSLinearString& str);
1831
1832 static inline UniqueChars StringToNewUTF8CharsZ(JSContext* cx, JSString& str) {
1833 JS::AutoCheckCannotGC nogc;
1834
1835 JSLinearString* linear = str.ensureLinear(cx);
1836 if (!linear) {
1837 return nullptr;
1838 }
1839
1840 return UniqueChars(
1841 linear->hasLatin1Chars()
1842 ? JS::CharsToNewUTF8CharsZ(cx, linear->latin1Range(nogc)).c_str()
1843 : JS::CharsToNewUTF8CharsZ(cx, linear->twoByteRange(nogc)).c_str());
1844 }
1845
1846 template <typename CharT>
1847 extern JSString::OwnedChars<CharT> AllocAtomCharsValidLength(JSContext* cx,
1848 size_t length);
1849
1850 /**
1851 * Allocate a string with the given contents. If |allowGC == CanGC|, this may
1852 * trigger a GC.
1853 */
1854 template <js::AllowGC allowGC, typename CharT>
1855 extern JSLinearString* NewString(JSContext* cx,
1856 UniquePtr<CharT[], JS::FreePolicy> chars,
1857 size_t length,
1858 js::gc::Heap heap = js::gc::Heap::Default);
1859
1860 /* Like NewString, but doesn't try to deflate to Latin1. */
1861 template <js::AllowGC allowGC, typename CharT>
1862 extern JSLinearString* NewStringDontDeflate(
1863 JSContext* cx, UniquePtr<CharT[], JS::FreePolicy> chars, size_t length,
1864 js::gc::Heap heap = js::gc::Heap::Default);
1865
1866 /* This may return a static string/atom or an inline string. */
1867 extern JSLinearString* NewDependentString(
1868 JSContext* cx, JSString* base, size_t start, size_t length,
1869 js::gc::Heap heap = js::gc::Heap::Default);
1870
1871 /* As above, but give an option to not contract the chain of base strings, in
1872 order to create messier situations for testing (some of which may not be
1873 possible in practice). */
1874 extern JSLinearString* NewDependentStringForTesting(
1875 JSContext* cx, JSString* base, size_t start, size_t length,
1876 JS::ContractBaseChain contract, js::gc::Heap heap);
1877
1878 /* Take ownership of an array of Latin1Chars. */
1879 extern JSLinearString* NewLatin1StringZ(
1880 JSContext* cx, UniqueChars chars,
1881 js::gc::Heap heap = js::gc::Heap::Default);
1882
1883 /* Copy a counted string and GC-allocate a descriptor for it. */
1884 template <js::AllowGC allowGC, typename CharT>
1885 extern JSLinearString* NewStringCopyN(
1886 JSContext* cx, const CharT* s, size_t n,
1887 js::gc::Heap heap = js::gc::Heap::Default);
1888
1889 template <js::AllowGC allowGC>
1890 inline JSLinearString* NewStringCopyN(
1891 JSContext* cx, const char* s, size_t n,
1892 js::gc::Heap heap = js::gc::Heap::Default) {
1893 return NewStringCopyN<allowGC>(cx, reinterpret_cast<const Latin1Char*>(s), n,
1894 heap);
1895 }
1896
1897 template <typename CharT>
1898 extern JSAtom* NewAtomCopyNMaybeDeflateValidLength(JSContext* cx,
1899 const CharT* s, size_t n,
1900 js::HashNumber hash);
1901
1902 template <typename CharT>
1903 extern JSAtom* NewAtomCopyNDontDeflateValidLength(JSContext* cx, const CharT* s,
1904 size_t n,
1905 js::HashNumber hash);
1906
1907 /* Copy a counted string and GC-allocate a descriptor for it. */
1908 template <js::AllowGC allowGC, typename CharT>
1909 inline JSLinearString* NewStringCopy(
1910 JSContext* cx, mozilla::Span<const CharT> s,
1911 js::gc::Heap heap = js::gc::Heap::Default) {
1912 return NewStringCopyN<allowGC>(cx, s.data(), s.size(), heap);
1913 }
1914
1915 /* Copy a counted string and GC-allocate a descriptor for it. */
1916 template <
1917 js::AllowGC allowGC, typename CharT,
1918 typename std::enable_if_t<!std::is_same_v<CharT, unsigned char>>* = nullptr>
1919 inline JSLinearString* NewStringCopy(
1920 JSContext* cx, std::basic_string_view<CharT> s,
1921 js::gc::Heap heap = js::gc::Heap::Default) {
1922 return NewStringCopyN<allowGC>(cx, s.data(), s.size(), heap);
1923 }
1924
1925 /* Like NewStringCopyN, but doesn't try to deflate to Latin1. */
1926 template <js::AllowGC allowGC, typename CharT>
1927 extern JSLinearString* NewStringCopyNDontDeflate(
1928 JSContext* cx, const CharT* s, size_t n,
1929 js::gc::Heap heap = js::gc::Heap::Default);
1930
1931 template <js::AllowGC allowGC, typename CharT>
1932 extern JSLinearString* NewStringCopyNDontDeflateNonStaticValidLength(
1933 JSContext* cx, const CharT* s, size_t n,
1934 js::gc::Heap heap = js::gc::Heap::Default);
1935
1936 /* Copy a C string and GC-allocate a descriptor for it. */
1937 template <js::AllowGC allowGC>
1938 inline JSLinearString* NewStringCopyZ(
1939 JSContext* cx, const char16_t* s,
1940 js::gc::Heap heap = js::gc::Heap::Default) {
1941 return NewStringCopyN<allowGC>(cx, s, js_strlen(s), heap);
1942 }
1943
1944 template <js::AllowGC allowGC>
1945 inline JSLinearString* NewStringCopyZ(
1946 JSContext* cx, const char* s, js::gc::Heap heap = js::gc::Heap::Default) {
1947 return NewStringCopyN<allowGC>(cx, s, strlen(s), heap);
1948 }
1949
1950 extern JSLinearString* NewStringCopyUTF8N(
1951 JSContext* cx, const JS::UTF8Chars& utf8, JS::SmallestEncoding encoding,
1952 js::gc::Heap heap = js::gc::Heap::Default);
1953
1954 extern JSLinearString* NewStringCopyUTF8N(
1955 JSContext* cx, const JS::UTF8Chars& utf8,
1956 js::gc::Heap heap = js::gc::Heap::Default);
1957
1958 inline JSLinearString* NewStringCopyUTF8Z(
1959 JSContext* cx, const JS::ConstUTF8CharsZ utf8,
1960 js::gc::Heap heap = js::gc::Heap::Default) {
1961 return NewStringCopyUTF8N(
1962 cx, JS::UTF8Chars(utf8.c_str(), strlen(utf8.c_str())), heap);
1963 }
1964
1965 template <typename CharT>
1966 JSString* NewMaybeExternalString(JSContext* cx, const CharT* s, size_t n,
1967 const JSExternalStringCallbacks* callbacks,
1968 bool* allocatedExternal,
1969 js::gc::Heap heap = js::gc::Heap::Default);
1970
1971 static_assert(sizeof(HashNumber) == 4);
1972
1973 template <AllowGC allowGC>
1974 extern JSString* ConcatStrings(
1975 JSContext* cx, typename MaybeRooted<JSString*, allowGC>::HandleType left,
1976 typename MaybeRooted<JSString*, allowGC>::HandleType right,
1977 js::gc::Heap heap = js::gc::Heap::Default);
1978
1979 /*
1980 * Test if strings are equal. The caller can call the function even if str1
1981 * or str2 are not GC-allocated things.
1982 */
1983 extern bool EqualStrings(JSContext* cx, JSString* str1, JSString* str2,
1984 bool* result);
1985
1986 /* Use the infallible method instead! */
1987 extern bool EqualStrings(JSContext* cx, JSLinearString* str1,
1988 JSLinearString* str2, bool* result) = delete;
1989
1990 /* EqualStrings is infallible on linear strings. */
1991 extern bool EqualStrings(const JSLinearString* str1,
1992 const JSLinearString* str2);
1993
1994 /**
1995 * Compare two strings that are known to be the same length.
1996 * Exposed for the JITs; for ordinary uses, EqualStrings() is more sensible.
1997 *
1998 * The caller must have checked for the following cases that can be handled
1999 * efficiently without requiring a character comparison:
2000 * - str1 == str2
2001 * - str1->length() != str2->length()
2002 * - str1->isAtom() && str2->isAtom()
2003 */
2004 extern bool EqualChars(const JSLinearString* str1, const JSLinearString* str2);
2005
2006 /*
2007 * Return less than, equal to, or greater than zero depending on whether
2008 * `s1[0..len1]` is less than, equal to, or greater than `s2`.
2009 */
2010 extern int32_t CompareChars(const char16_t* s1, size_t len1,
2011 const JSLinearString* s2);
2012
2013 /*
2014 * Compare two strings, like CompareChars, but store the result in `*result`.
2015 * This flattens the strings and therefore can fail.
2016 */
2017 extern bool CompareStrings(JSContext* cx, JSString* str1, JSString* str2,
2018 int32_t* result);
2019
2020 /*
2021 * Compare two strings, like CompareChars.
2022 */
2023 extern int32_t CompareStrings(const JSLinearString* str1,
2024 const JSLinearString* str2);
2025
2026 /**
2027 * Return true if the string contains only ASCII characters.
2028 */
2029 extern bool StringIsAscii(const JSLinearString* str);
2030
2031 /*
2032 * Return true if the string matches the given sequence of ASCII bytes.
2033 */
2034 extern bool StringEqualsAscii(const JSLinearString* str,
2035 const char* asciiBytes);
2036 /*
2037 * Return true if the string matches the given sequence of ASCII
2038 * bytes. The sequence of ASCII bytes must have length "length". The
2039 * length should not include the trailing null, if any.
2040 */
2041 extern bool StringEqualsAscii(const JSLinearString* str, const char* asciiBytes,
2042 size_t length);
2043
2044 template <size_t N>
2045 bool StringEqualsLiteral(const JSLinearString* str,
2046 const char (&asciiBytes)[N]) {
2047 MOZ_ASSERT(asciiBytes[N - 1] == '\0');
2048 return StringEqualsAscii(str, asciiBytes, N - 1);
2049 }
2050
2051 extern int StringFindPattern(const JSLinearString* text,
2052 const JSLinearString* pat, size_t start);
2053
2054 /**
2055 * Return true if the string contains a pattern at |start|.
2056 *
2057 * Precondition: `text` is long enough that this might be true;
2058 * that is, it has at least `start + pat->length()` characters.
2059 */
2060 extern bool HasSubstringAt(const JSLinearString* text,
2061 const JSLinearString* pat, size_t start);
2062
2063 /*
2064 * Computes |str|'s substring for the range [beginInt, beginInt + lengthInt).
2065 * Negative, overlarge, swapped, etc. |beginInt| and |lengthInt| are forbidden
2066 * and constitute API misuse.
2067 */
2068 JSString* SubstringKernel(JSContext* cx, HandleString str, int32_t beginInt,
2069 int32_t lengthInt);
2070
2071 inline js::HashNumber HashStringChars(const JSLinearString* str) {
2072 JS::AutoCheckCannotGC nogc;
2073 size_t len = str->length();
2074 return str->hasLatin1Chars()
2075 ? mozilla::HashString(str->latin1Chars(nogc), len)
2076 : mozilla::HashString(str->twoByteChars(nogc), len);
2077 }
2078
2079 /**
2080 * Allocate string characters when the final string length is known in advance.
2081 */
2082 template <typename CharT>
2083 class MOZ_NON_PARAM StringChars {
2084 static constexpr size_t InlineLength =
2085 std::is_same_v<CharT, JS::Latin1Char>
2086 ? JSFatInlineString::MAX_LENGTH_LATIN1
2087 : JSFatInlineString::MAX_LENGTH_TWO_BYTE;
2088
2089 CharT inlineChars_[InlineLength];
2090 Rooted<JSString::OwnedChars<CharT>> ownedChars_;
2091
2092 #ifdef DEBUG
2093 // In debug mode, we keep track of the requested string lengths to ensure all
2094 // methods are called in the correct order and with the expected argument
2095 // values.
2096 size_t lastRequestedLength_ = 0;
2097
2098 void assertValidRequest(size_t expectedLastLength, size_t length) {
2099 MOZ_ASSERT(length >= expectedLastLength, "cannot shrink requested length");
2100 MOZ_ASSERT(lastRequestedLength_ == expectedLastLength);
2101 lastRequestedLength_ = length;
2102 }
2103 #else
2104 void assertValidRequest(size_t expectedLastLength, size_t length) {}
2105 #endif
2106
2107 public:
2108 explicit StringChars(JSContext* cx) : ownedChars_(cx) {}
2109
2110 /**
2111 * Return a raw pointer to the string characters. The pointer can point to
2112 * nursery allocated memory, so the caller should ensure no GC can happen
2113 * while using this pointer.
2114 */
2115 CharT* data(const JS::AutoRequireNoGC&) {
2116 return ownedChars_ ? ownedChars_.data() : inlineChars_;
2117 }
2118
2119 /**
2120 * Escape hatch when it's not possible to call `data(nogc)`. Use with caution!
2121 */
2122 CharT* unsafeData() {
2123 return ownedChars_ ? ownedChars_.data() : inlineChars_;
2124 }
2125
2126 /**
2127 * Prepare for writing |length| characters. Allocates iff `length` exceeds the
2128 * inline storage of this class.
2129 */
2130 bool maybeAlloc(JSContext* cx, size_t length,
2131 gc::Heap heap = gc::Heap::Default);
2132
2133 /**
2134 * Increase the string characters storage. Allocates iff `newLength` exceeds
2135 * the inline storage of this class.
2136 */
2137 bool maybeRealloc(JSContext* cx, size_t oldLength, size_t newLength,
2138 gc::Heap heap = gc::Heap::Default);
2139
2140 /**
2141 * Build the result string. Does not deflate two-byte characters if all
2142 * characters fit into Latin-1.
2143 */
2144 template <AllowGC allowGC>
2145 JSLinearString* toStringDontDeflate(JSContext* cx, size_t length,
2146 gc::Heap heap = gc::Heap::Default);
2147
2148 /**
2149 * Build the result string. Does not deflate two-byte characters if all
2150 * characters fit into Latin-1. And does not check static strings.
2151 */
2152 template <AllowGC allowGC>
2153 JSLinearString* toStringDontDeflateNonStatic(
2154 JSContext* cx, size_t length, gc::Heap heap = gc::Heap::Default);
2155 };
2156
2157 /**
2158 * Allocate atom characters when the final string length is known in advance.
2159 */
2160 template <typename CharT>
2161 class MOZ_NON_PARAM AtomStringChars {
2162 static constexpr size_t InlineLength =
2163 std::is_same_v<CharT, JS::Latin1Char>
2164 ? JSFatInlineString::MAX_LENGTH_LATIN1
2165 : JSFatInlineString::MAX_LENGTH_TWO_BYTE;
2166
2167 CharT inlineChars_[InlineLength];
2168 UniquePtr<CharT[], JS::FreePolicy> mallocChars_;
2169
2170 #ifdef DEBUG
2171 // In debug mode, we keep track of the requested string lengths to ensure all
2172 // methods are called in the correct order and with the expected argument
2173 // values.
2174 size_t lastRequestedLength_ = 0;
2175
2176 void assertValidRequest(size_t expectedLastLength, size_t length) {
2177 MOZ_ASSERT(length >= expectedLastLength, "cannot shrink requested length");
2178 MOZ_ASSERT(lastRequestedLength_ == expectedLastLength);
2179 lastRequestedLength_ = length;
2180 }
2181 #else
2182 void assertValidRequest(size_t expectedLastLength, size_t length) {}
2183 #endif
2184
2185 public:
2186 /**
2187 * Return a raw pointer to the string characters.
2188 */
2189 CharT* data() { return mallocChars_ ? mallocChars_.get() : inlineChars_; }
2190
2191 /**
2192 * Prepare for writing |length| characters. Allocates iff `length` exceeds the
2193 * inline storage of this class.
2194 */
2195 bool maybeAlloc(JSContext* cx, size_t length);
2196
2197 /**
2198 * Build the result atom string.
2199 */
2200 JSAtom* toAtom(JSContext* cx, size_t length);
2201 };
2202
2203 /*** Conversions ************************************************************/
2204
2205 /*
2206 * Convert a string to a printable C string.
2207 *
2208 * Asserts if the input contains any non-ASCII characters.
2209 */
2210 UniqueChars EncodeAscii(JSContext* cx, JSString* str);
2211
2212 /*
2213 * Convert a string to a printable C string.
2214 */
2215 UniqueChars EncodeLatin1(JSContext* cx, JSString* str);
2216
2217 enum class IdToPrintableBehavior : bool {
2218 /*
2219 * Request the printable representation of an identifier.
2220 */
2221 IdIsIdentifier,
2222
2223 /*
2224 * Request the printable representation of a property key.
2225 */
2226 IdIsPropertyKey
2227 };
2228
2229 /*
2230 * Convert a jsid to a printable C string encoded in UTF-8.
2231 */
2232 extern UniqueChars IdToPrintableUTF8(JSContext* cx, HandleId id,
2233 IdToPrintableBehavior behavior);
2234
2235 /*
2236 * Convert a non-string value to a string, returning null after reporting an
2237 * error, otherwise returning a new string reference.
2238 */
2239 template <AllowGC allowGC>
2240 extern JSString* ToStringSlow(
2241 JSContext* cx, typename MaybeRooted<Value, allowGC>::HandleType arg);
2242
2243 /*
2244 * Convert the given value to a string. This method includes an inline
2245 * fast-path for the case where the value is already a string; if the value is
2246 * known not to be a string, use ToStringSlow instead.
2247 */
2248 template <AllowGC allowGC>
2249 static MOZ_ALWAYS_INLINE JSString* ToString(JSContext* cx, JS::HandleValue v) {
2250 if (v.isString()) {
2251 return v.toString();
2252 }
2253 return ToStringSlow<allowGC>(cx, v);
2254 }
2255
2256 /*
2257 * This function implements E-262-3 section 9.8, toString. Convert the given
2258 * value to a string of characters appended to the given builder. On error, the
2259 * passed builder may have partial results appended.
2260 */
2261 inline bool ValueToStringBuilder(JSContext* cx, const Value& v,
2262 StringBuilder& sb);
2263
2264 } /* namespace js */
2265
2266 MOZ_ALWAYS_INLINE bool JSString::getChar(JSContext* cx, size_t index,
2267 char16_t* code) {
2268 MOZ_ASSERT(index < length());
2269
2270 /*
2271 * Optimization for one level deep ropes.
2272 * This is common for the following pattern:
2273 *
2274 * while() {
2275 * text = text.substr(0, x) + "bla" + text.substr(x)
2276 * test.charCodeAt(x + 1)
2277 * }
2278 *
2279 * Note: keep this in sync with MacroAssembler::loadStringChar and
2280 * CanAttachStringChar.
2281 */
2282 JSString* str;
2283 if (isRope()) {
2284 JSRope* rope = &asRope();
2285 if (uint32_t(index) < rope->leftChild()->length()) {
2286 str = rope->leftChild();
2287 } else {
2288 str = rope->rightChild();
2289 index -= rope->leftChild()->length();
2290 }
2291 } else {
2292 str = this;
2293 }
2294
2295 if (!str->ensureLinear(cx)) {
2296 return false;
2297 }
2298
2299 *code = str->asLinear().latin1OrTwoByteChar(index);
2300 return true;
2301 }
2302
2303 MOZ_ALWAYS_INLINE bool JSString::getCodePoint(JSContext* cx, size_t index,
2304 char32_t* code) {
2305 // C++ implementation of https://tc39.es/ecma262/#sec-codepointat
2306 size_t size = length();
2307 MOZ_ASSERT(index < size);
2308
2309 char16_t first;
2310 if (!getChar(cx, index, &first)) {
2311 return false;
2312 }
2313 if (!js::unicode::IsLeadSurrogate(first) || index + 1 == size) {
2314 *code = first;
2315 return true;
2316 }
2317
2318 char16_t second;
2319 if (!getChar(cx, index + 1, &second)) {
2320 return false;
2321 }
2322 if (!js::unicode::IsTrailSurrogate(second)) {
2323 *code = first;
2324 return true;
2325 }
2326
2327 *code = js::unicode::UTF16Decode(first, second);
2328 return true;
2329 }
2330
2331 MOZ_ALWAYS_INLINE JSLinearString* JSString::ensureLinear(JSContext* cx) {
2332 return isLinear() ? &asLinear() : asRope().flatten(cx);
2333 }
2334
2335 inline JSLinearString* JSString::base() const {
2336 MOZ_ASSERT(hasBase());
2337 MOZ_ASSERT_IF(!isAtomRef(), !d.s.u3.base->isInline());
2338 MOZ_ASSERT(d.s.u3.base->assertIsValidBase());
2339 if (isAtomRef()) {
2340 return static_cast<JSLinearString*>(d.s.u3.atom);
2341 }
2342 return d.s.u3.base;
2343 }
2344
2345 inline JSAtom* JSString::atom() const {
2346 MOZ_ASSERT(isAtomRef());
2347 return d.s.u3.atom;
2348 }
2349
2350 inline JSLinearString* JSString::nurseryBaseOrRelocOverlay() const {
2351 MOZ_ASSERT(hasBase());
2352 return d.s.u3.base;
2353 }
2354
2355 inline bool JSString::canOwnDependentChars() const {
2356 // A string that could own the malloced chars used by another (dependent)
2357 // string. It will not have a base and must be linear and non-inline.
2358 return isLinear() && !isInline() && !hasBase();
2359 }
2360
2361 template <>
2362 MOZ_ALWAYS_INLINE const char16_t* JSLinearString::nonInlineChars(
2363 const JS::AutoRequireNoGC& nogc) const {
2364 return nonInlineTwoByteChars(nogc);
2365 }
2366
2367 template <>
2368 MOZ_ALWAYS_INLINE const JS::Latin1Char* JSLinearString::nonInlineChars(
2369 const JS::AutoRequireNoGC& nogc) const {
2370 return nonInlineLatin1Chars(nogc);
2371 }
2372
2373 template <>
2374 MOZ_ALWAYS_INLINE const char16_t* JSLinearString::chars(
2375 const JS::AutoRequireNoGC& nogc) const {
2376 return rawTwoByteChars();
2377 }
2378
2379 template <>
2380 MOZ_ALWAYS_INLINE const JS::Latin1Char* JSLinearString::chars(
2381 const JS::AutoRequireNoGC& nogc) const {
2382 return rawLatin1Chars();
2383 }
2384
2385 template <>
2386 MOZ_ALWAYS_INLINE js::UniquePtr<JS::Latin1Char[], JS::FreePolicy>
2387 JSRope::copyChars<JS::Latin1Char>(JSContext* maybecx,
2388 arena_id_t destArenaId) const {
2389 return copyLatin1Chars(maybecx, destArenaId);
2390 }
2391
2392 template <>
2393 MOZ_ALWAYS_INLINE JS::UniqueTwoByteChars JSRope::copyChars<char16_t>(
2394 JSContext* maybecx, arena_id_t destArenaId) const {
2395 return copyTwoByteChars(maybecx, destArenaId);
2396 }
2397
2398 template <>
2399 MOZ_ALWAYS_INLINE bool JSThinInlineString::lengthFits<JS::Latin1Char>(
2400 size_t length) {
2401 return length <= MAX_LENGTH_LATIN1;
2402 }
2403
2404 template <>
2405 MOZ_ALWAYS_INLINE bool JSThinInlineString::lengthFits<char16_t>(size_t length) {
2406 return length <= MAX_LENGTH_TWO_BYTE;
2407 }
2408
2409 template <>
2410 MOZ_ALWAYS_INLINE bool JSFatInlineString::lengthFits<JS::Latin1Char>(
2411 size_t length) {
2412 static_assert(
2413 (INLINE_EXTENSION_CHARS_LATIN1 * sizeof(char)) % js::gc::CellAlignBytes ==
2414 0,
2415 "fat inline strings' Latin1 characters don't exactly "
2416 "fill subsequent cells and thus are wasteful");
2417 static_assert(MAX_LENGTH_LATIN1 ==
2418 (sizeof(JSFatInlineString) -
2419 offsetof(JSFatInlineString, d.inlineStorageLatin1)) /
2420 sizeof(char),
2421 "MAX_LENGTH_LATIN1 must be one less than inline Latin1 "
2422 "storage count");
2423
2424 return length <= MAX_LENGTH_LATIN1;
2425 }
2426
2427 template <>
2428 MOZ_ALWAYS_INLINE bool JSFatInlineString::lengthFits<char16_t>(size_t length) {
2429 static_assert((INLINE_EXTENSION_CHARS_TWO_BYTE * sizeof(char16_t)) %
2430 js::gc::CellAlignBytes ==
2431 0,
2432 "fat inline strings' char16_t characters don't exactly "
2433 "fill subsequent cells and thus are wasteful");
2434 static_assert(MAX_LENGTH_TWO_BYTE ==
2435 (sizeof(JSFatInlineString) -
2436 offsetof(JSFatInlineString, d.inlineStorageTwoByte)) /
2437 sizeof(char16_t),
2438 "MAX_LENGTH_TWO_BYTE must be one less than inline "
2439 "char16_t storage count");
2440
2441 return length <= MAX_LENGTH_TWO_BYTE;
2442 }
2443
2444 template <>
2445 MOZ_ALWAYS_INLINE bool JSInlineString::lengthFits<JS::Latin1Char>(
2446 size_t length) {
2447 // If it fits in a fat inline string, it fits in any inline string.
2448 return JSFatInlineString::lengthFits<JS::Latin1Char>(length);
2449 }
2450
2451 template <>
2452 MOZ_ALWAYS_INLINE bool JSInlineString::lengthFits<char16_t>(size_t length) {
2453 // If it fits in a fat inline string, it fits in any inline string.
2454 return JSFatInlineString::lengthFits<char16_t>(length);
2455 }
2456
2457 template <>
2458 MOZ_ALWAYS_INLINE bool js::ThinInlineAtom::lengthFits<JS::Latin1Char>(
2459 size_t length) {
2460 return length <= MAX_LENGTH_LATIN1;
2461 }
2462
2463 template <>
2464 MOZ_ALWAYS_INLINE bool js::ThinInlineAtom::lengthFits<char16_t>(size_t length) {
2465 return length <= MAX_LENGTH_TWO_BYTE;
2466 }
2467
2468 template <>
2469 MOZ_ALWAYS_INLINE bool js::FatInlineAtom::lengthFits<JS::Latin1Char>(
2470 size_t length) {
2471 return length <= MAX_LENGTH_LATIN1;
2472 }
2473
2474 template <>
2475 MOZ_ALWAYS_INLINE bool js::FatInlineAtom::lengthFits<char16_t>(size_t length) {
2476 return length <= MAX_LENGTH_TWO_BYTE;
2477 }
2478
2479 template <>
2480 MOZ_ALWAYS_INLINE bool JSAtom::lengthFitsInline<JS::Latin1Char>(size_t length) {
2481 // If it fits in a fat inline atom, it fits in any inline atom.
2482 return js::FatInlineAtom::lengthFits<JS::Latin1Char>(length);
2483 }
2484
2485 template <>
2486 MOZ_ALWAYS_INLINE bool JSAtom::lengthFitsInline<char16_t>(size_t length) {
2487 // If it fits in a fat inline atom, it fits in any inline atom.
2488 return js::FatInlineAtom::lengthFits<char16_t>(length);
2489 }
2490
2491 template <>
2492 MOZ_ALWAYS_INLINE void JSString::setNonInlineChars(const char16_t* chars,
2493 bool usesStringBuffer) {
2494 // Check that the new buffer is located in the StringBufferArena
2495 if (!(isAtomRef() && atom()->isInline())) {
2496 checkStringCharsArena(chars, usesStringBuffer);
2497 }
2498 d.s.u2.nonInlineCharsTwoByte = chars;
2499 }
2500
2501 template <>
2502 MOZ_ALWAYS_INLINE void JSString::setNonInlineChars(const JS::Latin1Char* chars,
2503 bool usesStringBuffer) {
2504 // Check that the new buffer is located in the StringBufferArena
2505 if (!(isAtomRef() && atom()->isInline())) {
2506 checkStringCharsArena(chars, usesStringBuffer);
2507 }
2508 d.s.u2.nonInlineCharsLatin1 = chars;
2509 }
2510
2511 MOZ_ALWAYS_INLINE const JS::Latin1Char* JSLinearString::rawLatin1Chars() const {
2512 MOZ_ASSERT(JSString::isLinear());
2513 MOZ_ASSERT(hasLatin1Chars());
2514 return isInline() ? d.inlineStorageLatin1 : d.s.u2.nonInlineCharsLatin1;
2515 }
2516
2517 MOZ_ALWAYS_INLINE const char16_t* JSLinearString::rawTwoByteChars() const {
2518 MOZ_ASSERT(JSString::isLinear());
2519 MOZ_ASSERT(hasTwoByteChars());
2520 return isInline() ? d.inlineStorageTwoByte : d.s.u2.nonInlineCharsTwoByte;
2521 }
2522
2523 inline js::PropertyName* JSAtom::asPropertyName() {
2524 MOZ_ASSERT(!isIndex());
2525 return static_cast<js::PropertyName*>(this);
2526 }
2527
2528 inline bool JSLinearString::isIndex(uint32_t* indexp) const {
2529 MOZ_ASSERT(JSString::isLinear());
2530
2531 if (isAtom()) {
2532 return asAtom().isIndex(indexp);
2533 }
2534
2535 if (JSString::hasIndexValue()) {
2536 *indexp = getIndexValue();
2537 return true;
2538 }
2539
2540 return isIndexSlow(indexp);
2541 }
2542
2543 namespace js {
2544 namespace gc {
2545 template <>
2546 inline JSString* Cell::as<JSString>() {
2547 MOZ_ASSERT(is<JSString>());
2548 return reinterpret_cast<JSString*>(this);
2549 }
2550
2551 template <>
2552 inline JSString* TenuredCell::as<JSString>() {
2553 MOZ_ASSERT(is<JSString>());
2554 return reinterpret_cast<JSString*>(this);
2555 }
2556
2557 } // namespace gc
2558 } // namespace js
2559
2560 #endif /* vm_StringType_h */