1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef vm_SharedImmutableStringsCache_h
#define vm_SharedImmutableStringsCache_h
#include "mozilla/Maybe.h"
#include "mozilla/UniquePtr.h"
#include <cstring>
#include <new> // for placement new
#include <utility> // std::move
#include "js/AllocPolicy.h"
#include "js/HashTable.h"
#include "js/UniquePtr.h"
#include "js/Utility.h"
#include "threading/ExclusiveData.h"
namespace js {
class SharedImmutableString;
class SharedImmutableTwoByteString;
/**
* The `SharedImmutableStringsCache` allows safely sharing and deduplicating
* immutable strings (either `const char*` [any encoding, not restricted to
* only Latin-1 or only UTF-8] or `const char16_t*`) between threads.
*
* The locking mechanism is dead-simple and coarse grained: a single lock guards
* all of the internal table itself, the table's entries, and the entries'
* reference counts. It is only safe to perform any mutation on the cache or any
* data stored within the cache when this lock is acquired.
*/
class SharedImmutableStringsCache {
static SharedImmutableStringsCache singleton_;
friend class SharedImmutableString;
friend class SharedImmutableTwoByteString;
struct Hasher;
public:
using OwnedChars = JS::UniqueChars;
using OwnedTwoByteChars = JS::UniqueTwoByteChars;
/**
* Get the canonical, shared, and de-duplicated version of the given `const
* char*` string. If such a string does not exist, call `intoOwnedChars` and
* add the string it returns to the cache.
*
* `intoOwnedChars` must create an owned version of the given string, and
* must have one of the following types:
*
* JS::UniqueChars intoOwnedChars();
* JS::UniqueChars&& intoOwnedChars();
*
* It can be used by callers to elide a copy of the string when it is safe
* to give up ownership of the lookup string to the cache. It must return a
* `nullptr` on failure.
*
* On success, `Some` is returned. In the case of OOM failure, `Nothing` is
* returned.
*/
template <typename IntoOwnedChars>
[[nodiscard]] SharedImmutableString getOrCreate(
const char* chars, size_t length, IntoOwnedChars intoOwnedChars);
/**
* Take ownership of the given `chars` and return the canonical, shared and
* de-duplicated version.
*
* On success, `Some` is returned. In the case of OOM failure, `Nothing` is
* returned.
*/
[[nodiscard]] SharedImmutableString getOrCreate(OwnedChars&& chars,
size_t length);
/**
* Do not take ownership of the given `chars`. Return the canonical, shared
* and de-duplicated version. If there is no extant shared version of
* `chars`, make a copy and insert it into the cache.
*
* On success, `Some` is returned. In the case of OOM failure, `Nothing` is
* returned.
*/
[[nodiscard]] SharedImmutableString getOrCreate(const char* chars,
size_t length);
/**
* Get the canonical, shared, and de-duplicated version of the given `const
* char16_t*` string. If such a string does not exist, call `intoOwnedChars`
* and add the string it returns to the cache.
*
* `intoOwnedTwoByteChars` must create an owned version of the given string,
* and must have one of the following types:
*
* JS::UniqueTwoByteChars intoOwnedTwoByteChars();
* JS::UniqueTwoByteChars&& intoOwnedTwoByteChars();
*
* It can be used by callers to elide a copy of the string when it is safe
* to give up ownership of the lookup string to the cache. It must return a
* `nullptr` on failure.
*
* On success, `Some` is returned. In the case of OOM failure, `Nothing` is
* returned.
*/
template <typename IntoOwnedTwoByteChars>
[[nodiscard]] SharedImmutableTwoByteString getOrCreate(
const char16_t* chars, size_t length,
IntoOwnedTwoByteChars intoOwnedTwoByteChars);
/**
* Take ownership of the given `chars` and return the canonical, shared and
* de-duplicated version.
*
* On success, `Some` is returned. In the case of OOM failure, `Nothing` is
* returned.
*/
[[nodiscard]] SharedImmutableTwoByteString getOrCreate(
OwnedTwoByteChars&& chars, size_t length);
/**
* Do not take ownership of the given `chars`. Return the canonical, shared
* and de-duplicated version. If there is no extant shared version of
* `chars`, then make a copy and insert it into the cache.
*
* On success, `Some` is returned. In the case of OOM failure, `Nothing` is
* returned.
*/
[[nodiscard]] SharedImmutableTwoByteString getOrCreate(const char16_t* chars,
size_t length);
size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
MOZ_ASSERT(inner_);
size_t n = mallocSizeOf(inner_);
auto locked = inner_->lock();
// Size of the table.
n += locked->set.shallowSizeOfExcludingThis(mallocSizeOf);
// Sizes of the strings and their boxes.
for (auto r = locked->set.all(); !r.empty(); r.popFront()) {
n += mallocSizeOf(r.front().get());
if (const char* chars = r.front()->chars()) {
n += mallocSizeOf(chars);
}
}
return n;
}
private:
bool init();
void free();
public:
static bool initSingleton();
static void freeSingleton();
static SharedImmutableStringsCache& getSingleton() {
MOZ_ASSERT(singleton_.inner_);
return singleton_;
}
private:
SharedImmutableStringsCache() = default;
~SharedImmutableStringsCache() = default;
public:
SharedImmutableStringsCache(const SharedImmutableStringsCache& rhs) = delete;
SharedImmutableStringsCache(SharedImmutableStringsCache&& rhs) = delete;
SharedImmutableStringsCache& operator=(SharedImmutableStringsCache&& rhs) =
delete;
SharedImmutableStringsCache& operator=(const SharedImmutableStringsCache&) =
delete;
/**
* Purge the cache of all refcount == 0 entries.
*/
void purge() {
auto locked = inner_->lock();
for (Inner::Set::Enum e(locked->set); !e.empty(); e.popFront()) {
if (e.front()->refcount == 0) {
// The chars should be eagerly freed when refcount reaches zero.
MOZ_ASSERT(!e.front()->chars());
e.removeFront();
} else {
// The chars should exist as long as the refcount is non-zero.
MOZ_ASSERT(e.front()->chars());
}
}
}
private:
struct Inner;
class StringBox {
friend class SharedImmutableString;
OwnedChars chars_;
size_t length_;
const ExclusiveData<Inner>* cache_;
public:
mutable size_t refcount;
using Ptr = js::UniquePtr<StringBox>;
StringBox(OwnedChars&& chars, size_t length,
const ExclusiveData<Inner>* cache)
: chars_(std::move(chars)),
length_(length),
cache_(cache),
refcount(0) {
MOZ_ASSERT(chars_);
}
static Ptr Create(OwnedChars&& chars, size_t length,
const ExclusiveData<Inner>* cache) {
return js::MakeUnique<StringBox>(std::move(chars), length, cache);
}
StringBox(const StringBox&) = delete;
StringBox& operator=(const StringBox&) = delete;
~StringBox() {
MOZ_RELEASE_ASSERT(
refcount == 0,
"There are `SharedImmutable[TwoByte]String`s outliving their "
"associated cache! This always leads to use-after-free in the "
"`~SharedImmutableString` destructor!");
}
const char* chars() const { return chars_.get(); }
size_t length() const { return length_; }
};
struct Hasher {
/**
* A structure used when querying for a `const char*` string in the cache.
*/
class Lookup {
friend struct Hasher;
HashNumber hash_;
const char* chars_;
size_t length_;
public:
Lookup(HashNumber hash, const char* chars, size_t length)
: hash_(hash), chars_(chars), length_(length) {
MOZ_ASSERT(chars_);
MOZ_ASSERT(hash == Hasher::hashLongString(chars, length));
}
Lookup(HashNumber hash, const char16_t* chars, size_t length)
: Lookup(hash, reinterpret_cast<const char*>(chars),
length * sizeof(char16_t)) {}
};
static const size_t SHORT_STRING_MAX_LENGTH = 8192;
static const size_t HASH_CHUNK_LENGTH = SHORT_STRING_MAX_LENGTH / 2;
// For strings longer than SHORT_STRING_MAX_LENGTH, we only hash the
// first HASH_CHUNK_LENGTH and last HASH_CHUNK_LENGTH characters in the
// string. This increases the risk of collisions, but in practice it
// should be rare, and it yields a large speedup for hashing long
// strings.
static HashNumber hashLongString(const char* chars, size_t length) {
MOZ_ASSERT(chars);
return length <= SHORT_STRING_MAX_LENGTH
? mozilla::HashString(chars, length)
: mozilla::AddToHash(
mozilla::HashString(chars, HASH_CHUNK_LENGTH),
mozilla::HashString(chars + length - HASH_CHUNK_LENGTH,
HASH_CHUNK_LENGTH));
}
static HashNumber hash(const Lookup& lookup) { return lookup.hash_; }
static bool match(const StringBox::Ptr& key, const Lookup& lookup) {
MOZ_ASSERT(lookup.chars_);
if (!key->chars() || key->length() != lookup.length_) {
return false;
}
if (key->chars() == lookup.chars_) {
return true;
}
return memcmp(key->chars(), lookup.chars_, key->length()) == 0;
}
};
// The `Inner` struct contains the actual cached contents and shared between
// the `SharedImmutableStringsCache` singleton and all
// `SharedImmutable[TwoByte]String` holders.
struct Inner {
using Set = HashSet<StringBox::Ptr, Hasher, SystemAllocPolicy>;
Set set;
Inner() : set() {}
Inner(const Inner&) = delete;
Inner& operator=(const Inner&) = delete;
};
const ExclusiveData<Inner>* inner_ = nullptr;
};
/**
* The `SharedImmutableString` class holds a reference to a `const char*` string
* from the `SharedImmutableStringsCache` and releases the reference upon
* destruction.
*/
class SharedImmutableString {
friend class SharedImmutableStringsCache;
friend class SharedImmutableTwoByteString;
mutable SharedImmutableStringsCache::StringBox* box_;
explicit SharedImmutableString(SharedImmutableStringsCache::StringBox* box);
public:
/**
* `SharedImmutableString`s are move-able. It is an error to use a
* `SharedImmutableString` after it has been moved.
*/
SharedImmutableString(SharedImmutableString&& rhs);
SharedImmutableString& operator=(SharedImmutableString&& rhs);
SharedImmutableString() { box_ = nullptr; }
/**
* Create another shared reference to the underlying string.
*/
SharedImmutableString clone() const;
// If you want a copy, take one explicitly with `clone`!
SharedImmutableString& operator=(const SharedImmutableString&) = delete;
explicit operator bool() const { return box_ != nullptr; }
~SharedImmutableString();
/**
* Get a raw pointer to the underlying string. It is only safe to use the
* resulting pointer while this `SharedImmutableString` exists.
*/
const char* chars() const {
MOZ_ASSERT(box_);
MOZ_ASSERT(box_->refcount > 0);
MOZ_ASSERT(box_->chars());
return box_->chars();
}
/**
* Get the length of the underlying string.
*/
size_t length() const {
MOZ_ASSERT(box_);
MOZ_ASSERT(box_->refcount > 0);
MOZ_ASSERT(box_->chars());
return box_->length();
}
};
/**
* The `SharedImmutableTwoByteString` class holds a reference to a `const
* char16_t*` string from the `SharedImmutableStringsCache` and releases the
* reference upon destruction.
*/
class SharedImmutableTwoByteString {
friend class SharedImmutableStringsCache;
// If a `char*` string and `char16_t*` string happen to have the same bytes,
// the bytes will be shared but handed out as different types.
SharedImmutableString string_;
explicit SharedImmutableTwoByteString(SharedImmutableString&& string);
explicit SharedImmutableTwoByteString(
SharedImmutableStringsCache::StringBox* box);
public:
/**
* `SharedImmutableTwoByteString`s are move-able. It is an error to use a
* `SharedImmutableTwoByteString` after it has been moved.
*/
SharedImmutableTwoByteString(SharedImmutableTwoByteString&& rhs);
SharedImmutableTwoByteString& operator=(SharedImmutableTwoByteString&& rhs);
SharedImmutableTwoByteString() { string_.box_ = nullptr; }
/**
* Create another shared reference to the underlying string.
*/
SharedImmutableTwoByteString clone() const;
// If you want a copy, take one explicitly with `clone`!
SharedImmutableTwoByteString& operator=(const SharedImmutableTwoByteString&) =
delete;
explicit operator bool() const { return string_.box_ != nullptr; }
/**
* Get a raw pointer to the underlying string. It is only safe to use the
* resulting pointer while this `SharedImmutableTwoByteString` exists.
*/
const char16_t* chars() const {
return reinterpret_cast<const char16_t*>(string_.chars());
}
/**
* Get the length of the underlying string.
*/
size_t length() const { return string_.length() / sizeof(char16_t); }
};
} // namespace js
#endif // vm_SharedImmutableStringsCache_h
|