Bug 1854550 - pt 10. Allow LOG() with zero extra arguments r=glandium
[gecko.git] / xpcom / ds / nsAtomTable.cpp
blob8078e42076eab8b527bb39762dda062a39702ea6
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/. */
7 #include "mozilla/Assertions.h"
8 #include "mozilla/Attributes.h"
9 #include "mozilla/HashFunctions.h"
10 #include "mozilla/MemoryReporting.h"
11 #include "mozilla/MruCache.h"
12 #include "mozilla/RWLock.h"
13 #include "mozilla/TextUtils.h"
14 #include "nsThreadUtils.h"
16 #include "nsAtom.h"
17 #include "nsAtomTable.h"
18 #include "nsGkAtoms.h"
19 #include "nsPrintfCString.h"
20 #include "nsString.h"
21 #include "nsUnicharUtils.h"
22 #include "PLDHashTable.h"
23 #include "prenv.h"
25 // There are two kinds of atoms handled by this module.
27 // - Dynamic: the atom itself is heap allocated, as is the char buffer it
28 // points to. |gAtomTable| holds weak references to dynamic atoms. When the
29 // refcount of a dynamic atom drops to zero, we increment a static counter.
30 // When that counter reaches a certain threshold, we iterate over the atom
31 // table, removing and deleting dynamic atoms with refcount zero. This allows
32 // us to avoid acquiring the atom table lock during normal refcounting.
34 // - Static: both the atom and its chars are statically allocated and
35 // immutable, so it ignores all AddRef/Release calls.
37 // Note that gAtomTable is used on multiple threads, and has internal
38 // synchronization.
40 using namespace mozilla;
42 //----------------------------------------------------------------------
44 enum class GCKind {
45 RegularOperation,
46 Shutdown,
49 //----------------------------------------------------------------------
51 // gUnusedAtomCount is incremented when an atom loses its last reference
52 // (and thus turned into unused state), and decremented when an unused
53 // atom gets a reference again. The atom table relies on this value to
54 // schedule GC. This value can temporarily go below zero when multiple
55 // threads are operating the same atom, so it has to be signed so that
56 // we wouldn't use overflow value for comparison.
57 // See nsAtom::AddRef() and nsAtom::Release().
58 // This atomic can be accessed during the GC and other places where recorded
59 // events are not allowed, so its value is not preserved when recording or
60 // replaying.
61 Atomic<int32_t, ReleaseAcquire> nsDynamicAtom::gUnusedAtomCount;
63 nsDynamicAtom::nsDynamicAtom(already_AddRefed<nsStringBuffer> aBuffer,
64 uint32_t aLength, uint32_t aHash,
65 bool aIsAsciiLowercase)
66 : nsAtom(aLength, /* aIsStatic = */ false, aHash, aIsAsciiLowercase),
67 mRefCnt(1),
68 mStringBuffer(aBuffer) {}
70 // Returns true if ToLowercaseASCII would return the string unchanged.
71 static bool IsAsciiLowercase(const char16_t* aString, const uint32_t aLength) {
72 for (uint32_t i = 0; i < aLength; ++i) {
73 if (IS_ASCII_UPPER(aString[i])) {
74 return false;
77 return true;
80 nsDynamicAtom* nsDynamicAtom::Create(const nsAString& aString, uint32_t aHash) {
81 // We tack the chars onto the end of the nsDynamicAtom object.
82 const bool isAsciiLower =
83 ::IsAsciiLowercase(aString.Data(), aString.Length());
84 RefPtr<nsStringBuffer> buffer = nsStringBuffer::FromString(aString);
85 if (!buffer) {
86 buffer = nsStringBuffer::Create(aString.Data(), aString.Length());
87 if (MOZ_UNLIKELY(!buffer)) {
88 MOZ_CRASH("Out of memory atomizing");
90 } else {
91 MOZ_ASSERT(aString.IsTerminated(),
92 "String buffers are always null-terminated");
94 auto* atom =
95 new nsDynamicAtom(buffer.forget(), aString.Length(), aHash, isAsciiLower);
96 MOZ_ASSERT(atom->String()[atom->GetLength()] == char16_t(0));
97 MOZ_ASSERT(atom->Equals(aString));
98 MOZ_ASSERT(atom->mHash == HashString(atom->String(), atom->GetLength()));
99 MOZ_ASSERT(atom->mIsAsciiLowercase == isAsciiLower);
100 return atom;
103 void nsDynamicAtom::Destroy(nsDynamicAtom* aAtom) { delete aAtom; }
105 void nsAtom::ToString(nsAString& aString) const {
106 // See the comment on |mString|'s declaration.
107 if (IsStatic()) {
108 // AssignLiteral() lets us assign without copying. This isn't a string
109 // literal, but it's a static atom and thus has an unbounded lifetime,
110 // which is what's important.
111 aString.AssignLiteral(AsStatic()->String(), mLength);
112 } else {
113 AsDynamic()->StringBuffer()->ToString(mLength, aString);
117 void nsAtom::ToUTF8String(nsACString& aBuf) const {
118 CopyUTF16toUTF8(nsDependentString(GetUTF16String(), mLength), aBuf);
121 void nsAtom::AddSizeOfIncludingThis(MallocSizeOf aMallocSizeOf,
122 AtomsSizes& aSizes) const {
123 // Static atoms are in static memory, and so are not measured here.
124 if (IsDynamic()) {
125 aSizes.mDynamicAtoms += aMallocSizeOf(this);
129 char16ptr_t nsAtom::GetUTF16String() const {
130 return IsStatic() ? AsStatic()->String() : AsDynamic()->String();
133 //----------------------------------------------------------------------
135 struct AtomTableKey {
136 explicit AtomTableKey(const nsStaticAtom* aAtom)
137 : mUTF16String(aAtom->String()),
138 mUTF8String(nullptr),
139 mLength(aAtom->GetLength()),
140 mHash(aAtom->hash()) {
141 MOZ_ASSERT(HashString(mUTF16String, mLength) == mHash);
144 AtomTableKey(const char16_t* aUTF16String, uint32_t aLength)
145 : mUTF16String(aUTF16String), mUTF8String(nullptr), mLength(aLength) {
146 mHash = HashString(mUTF16String, mLength);
149 AtomTableKey(const char* aUTF8String, uint32_t aLength, bool* aErr)
150 : mUTF16String(nullptr), mUTF8String(aUTF8String), mLength(aLength) {
151 mHash = HashUTF8AsUTF16(mUTF8String, mLength, aErr);
154 const char16_t* mUTF16String;
155 const char* mUTF8String;
156 uint32_t mLength;
157 uint32_t mHash;
160 struct AtomTableEntry : public PLDHashEntryHdr {
161 // These references are either to dynamic atoms, in which case they are
162 // non-owning, or they are to static atoms, which aren't really refcounted.
163 // See the comment at the top of this file for more details.
164 nsAtom* MOZ_NON_OWNING_REF mAtom;
167 struct AtomCache : public MruCache<AtomTableKey, nsAtom*, AtomCache> {
168 static HashNumber Hash(const AtomTableKey& aKey) { return aKey.mHash; }
169 static bool Match(const AtomTableKey& aKey, const nsAtom* aVal) {
170 MOZ_ASSERT(aKey.mUTF16String);
171 return aVal->Equals(aKey.mUTF16String, aKey.mLength);
175 static AtomCache sRecentlyUsedMainThreadAtoms;
177 // In order to reduce locking contention for concurrent atomization, we segment
178 // the atom table into N subtables, each with a separate lock. If the hash
179 // values we use to select the subtable are evenly distributed, this reduces the
180 // probability of contention by a factor of N. See bug 1440824.
182 // NB: This is somewhat similar to the technique used by Java's
183 // ConcurrentHashTable.
184 class nsAtomSubTable {
185 friend class nsAtomTable;
186 mozilla::RWLock mLock;
187 PLDHashTable mTable;
188 nsAtomSubTable();
189 void GCLocked(GCKind aKind) MOZ_REQUIRES(mLock);
190 void AddSizeOfExcludingThisLocked(MallocSizeOf aMallocSizeOf,
191 AtomsSizes& aSizes)
192 MOZ_REQUIRES_SHARED(mLock);
194 AtomTableEntry* Search(AtomTableKey& aKey) const MOZ_REQUIRES_SHARED(mLock) {
195 // XXX There's no LockedForReadingByCurrentThread();
196 return static_cast<AtomTableEntry*>(mTable.Search(&aKey));
199 AtomTableEntry* Add(AtomTableKey& aKey) MOZ_REQUIRES(mLock) {
200 MOZ_ASSERT(mLock.LockedForWritingByCurrentThread());
201 return static_cast<AtomTableEntry*>(mTable.Add(&aKey)); // Infallible
205 // The outer atom table, which coordinates access to the inner array of
206 // subtables.
207 class nsAtomTable {
208 public:
209 nsAtomSubTable& SelectSubTable(AtomTableKey& aKey);
210 void AddSizeOfIncludingThis(MallocSizeOf aMallocSizeOf, AtomsSizes& aSizes);
211 void GC(GCKind aKind);
212 already_AddRefed<nsAtom> Atomize(const nsAString& aUTF16String);
213 already_AddRefed<nsAtom> Atomize(const nsACString& aUTF8String);
214 already_AddRefed<nsAtom> AtomizeMainThread(const nsAString& aUTF16String);
215 nsStaticAtom* GetStaticAtom(const nsAString& aUTF16String);
216 void RegisterStaticAtoms(const nsStaticAtom* aAtoms, size_t aAtomsLen);
218 // The result of this function may be imprecise if other threads are operating
219 // on atoms concurrently. It's also slow, since it triggers a GC before
220 // counting.
221 size_t RacySlowCount();
223 // This hash table op is a static member of this class so that it can take
224 // advantage of |friend| declarations.
225 static void AtomTableClearEntry(PLDHashTable* aTable,
226 PLDHashEntryHdr* aEntry);
228 // We achieve measurable reduction in locking contention in parallel CSS
229 // parsing by increasing the number of subtables up to 128. This has been
230 // measured to have neglible impact on the performance of initialization, GC,
231 // and shutdown.
233 // Another important consideration is memory, since we're adding fixed
234 // overhead per content process, which we try to avoid. Measuring a
235 // mostly-empty page [1] with various numbers of subtables, we get the
236 // following deep sizes for the atom table:
237 // 1 subtable: 278K
238 // 8 subtables: 279K
239 // 16 subtables: 282K
240 // 64 subtables: 286K
241 // 128 subtables: 290K
243 // So 128 subtables costs us 12K relative to a single table, and 4K relative
244 // to 64 subtables. Conversely, measuring parallel (6 thread) CSS parsing on
245 // tp6-facebook, a single table provides ~150ms of locking overhead per
246 // thread, 64 subtables provides ~2-3ms of overhead, and 128 subtables
247 // provides <1ms. And so while either 64 or 128 subtables would probably be
248 // acceptable, achieving a measurable reduction in contention for 4k of fixed
249 // memory overhead is probably worth it.
251 // [1] The numbers will look different for content processes with complex
252 // pages loaded, but in those cases the actual atoms will dominate memory
253 // usage and the overhead of extra tables will be negligible. We're mostly
254 // interested in the fixed cost for nearly-empty content processes.
255 constexpr static size_t kNumSubTables = 512; // Must be power of two.
257 // The atom table very quickly gets 10,000+ entries in it (or even 100,000+).
258 // But choosing the best initial subtable length has some subtleties: we add
259 // ~2700 static atoms at start-up, and then we start adding and removing
260 // dynamic atoms. If we make the tables too big to start with, when the first
261 // dynamic atom gets removed from a given table the load factor will be < 25%
262 // and we will shrink it.
264 // So we first make the simplifying assumption that the atoms are more or less
265 // evenly-distributed across the subtables (which is the case empirically).
266 // Then, we take the total atom count when the first dynamic atom is removed
267 // (~2700), divide that across the N subtables, and the largest capacity that
268 // will allow each subtable to be > 25% full with that count.
270 // So want an initial subtable capacity less than (2700 / N) * 4 = 10800 / N.
271 // Rounding down to the nearest power of two gives us 8192 / N. Since the
272 // capacity is double the initial length, we end up with (4096 / N) per
273 // subtable.
274 constexpr static size_t kInitialSubTableSize = 4096 / kNumSubTables;
276 private:
277 nsAtomSubTable mSubTables[kNumSubTables];
280 // Static singleton instance for the atom table.
281 static nsAtomTable* gAtomTable;
283 static PLDHashNumber AtomTableGetHash(const void* aKey) {
284 const AtomTableKey* k = static_cast<const AtomTableKey*>(aKey);
285 return k->mHash;
288 static bool AtomTableMatchKey(const PLDHashEntryHdr* aEntry, const void* aKey) {
289 const AtomTableEntry* he = static_cast<const AtomTableEntry*>(aEntry);
290 const AtomTableKey* k = static_cast<const AtomTableKey*>(aKey);
292 if (k->mUTF8String) {
293 bool err = false;
294 return (CompareUTF8toUTF16(nsDependentCSubstring(
295 k->mUTF8String, k->mUTF8String + k->mLength),
296 nsDependentAtomString(he->mAtom), &err) == 0) &&
297 !err;
300 return he->mAtom->Equals(k->mUTF16String, k->mLength);
303 void nsAtomTable::AtomTableClearEntry(PLDHashTable* aTable,
304 PLDHashEntryHdr* aEntry) {
305 auto* entry = static_cast<AtomTableEntry*>(aEntry);
306 entry->mAtom = nullptr;
309 static void AtomTableInitEntry(PLDHashEntryHdr* aEntry, const void* aKey) {
310 static_cast<AtomTableEntry*>(aEntry)->mAtom = nullptr;
313 static const PLDHashTableOps AtomTableOps = {
314 AtomTableGetHash, AtomTableMatchKey, PLDHashTable::MoveEntryStub,
315 nsAtomTable::AtomTableClearEntry, AtomTableInitEntry};
317 nsAtomSubTable& nsAtomTable::SelectSubTable(AtomTableKey& aKey) {
318 // There are a few considerations around how we select subtables.
320 // First, we want entries to be evenly distributed across the subtables. This
321 // can be achieved by using any bits in the hash key, assuming the key itself
322 // is evenly-distributed. Empirical measurements indicate that this method
323 // produces a roughly-even distribution across subtables.
325 // Second, we want to use the hash bits that are least likely to influence an
326 // entry's position within the subtable. If we used the exact same bits used
327 // by the subtables, then each subtable would compute the same position for
328 // every entry it observes, leading to pessimal performance. In this case,
329 // we're using PLDHashTable, whose primary hash function uses the N leftmost
330 // bits of the hash value (where N is the log2 capacity of the table). This
331 // means we should prefer the rightmost bits here.
333 // Note that the below is equivalent to mHash % kNumSubTables, a replacement
334 // which an optimizing compiler should make, but let's avoid any doubt.
335 static_assert((kNumSubTables & (kNumSubTables - 1)) == 0,
336 "must be power of two");
337 return mSubTables[aKey.mHash & (kNumSubTables - 1)];
340 void nsAtomTable::AddSizeOfIncludingThis(MallocSizeOf aMallocSizeOf,
341 AtomsSizes& aSizes) {
342 MOZ_ASSERT(NS_IsMainThread());
343 aSizes.mTable += aMallocSizeOf(this);
344 for (auto& table : mSubTables) {
345 AutoReadLock lock(table.mLock);
346 table.AddSizeOfExcludingThisLocked(aMallocSizeOf, aSizes);
350 void nsAtomTable::GC(GCKind aKind) {
351 MOZ_ASSERT(NS_IsMainThread());
352 sRecentlyUsedMainThreadAtoms.Clear();
354 // Note that this is effectively an incremental GC, since only one subtable
355 // is locked at a time.
356 for (auto& table : mSubTables) {
357 AutoWriteLock lock(table.mLock);
358 table.GCLocked(aKind);
361 // We would like to assert that gUnusedAtomCount matches the number of atoms
362 // we found in the table which we removed. However, there are two problems
363 // with this:
364 // * We have multiple subtables, each with their own lock. For optimal
365 // performance we only want to hold one lock at a time, but this means
366 // that atoms can be added and removed between GC slices.
367 // * Even if we held all the locks and performed all GC slices atomically,
368 // the locks are not acquired for AddRef() and Release() calls. This means
369 // we might see a gUnusedAtomCount value in between, say, AddRef()
370 // incrementing mRefCnt and it decrementing gUnusedAtomCount.
372 // So, we don't bother asserting that there are no unused atoms at the end of
373 // a regular GC. But we can (and do) assert this just after the last GC at
374 // shutdown.
376 // Note that, barring refcounting bugs, an atom can only go from a zero
377 // refcount to a non-zero refcount while the atom table lock is held, so
378 // so we won't try to resurrect a zero refcount atom while trying to delete
379 // it.
381 MOZ_ASSERT_IF(aKind == GCKind::Shutdown,
382 nsDynamicAtom::gUnusedAtomCount == 0);
385 size_t nsAtomTable::RacySlowCount() {
386 // Trigger a GC so that the result is deterministic modulo other threads.
387 GC(GCKind::RegularOperation);
388 size_t count = 0;
389 for (auto& table : mSubTables) {
390 AutoReadLock lock(table.mLock);
391 count += table.mTable.EntryCount();
394 return count;
397 nsAtomSubTable::nsAtomSubTable()
398 : mLock("Atom Sub-Table Lock"),
399 mTable(&AtomTableOps, sizeof(AtomTableEntry),
400 nsAtomTable::kInitialSubTableSize) {}
402 void nsAtomSubTable::GCLocked(GCKind aKind) {
403 MOZ_ASSERT(NS_IsMainThread());
404 MOZ_ASSERT(mLock.LockedForWritingByCurrentThread());
406 int32_t removedCount = 0; // A non-atomic temporary for cheaper increments.
407 nsAutoCString nonZeroRefcountAtoms;
408 uint32_t nonZeroRefcountAtomsCount = 0;
409 for (auto i = mTable.Iter(); !i.Done(); i.Next()) {
410 auto* entry = static_cast<AtomTableEntry*>(i.Get());
411 if (entry->mAtom->IsStatic()) {
412 continue;
415 nsAtom* atom = entry->mAtom;
416 if (atom->IsDynamic() && atom->AsDynamic()->mRefCnt == 0) {
417 i.Remove();
418 nsDynamicAtom::Destroy(atom->AsDynamic());
419 ++removedCount;
421 #ifdef NS_FREE_PERMANENT_DATA
422 else if (aKind == GCKind::Shutdown && PR_GetEnv("XPCOM_MEM_BLOAT_LOG")) {
423 // Only report leaking atoms in leak-checking builds in a run where we
424 // are checking for leaks, during shutdown. If something is anomalous,
425 // then we'll assert later in this function.
426 nsAutoCString name;
427 atom->ToUTF8String(name);
428 if (nonZeroRefcountAtomsCount == 0) {
429 nonZeroRefcountAtoms = name;
430 } else if (nonZeroRefcountAtomsCount < 20) {
431 nonZeroRefcountAtoms += ","_ns + name;
432 } else if (nonZeroRefcountAtomsCount == 20) {
433 nonZeroRefcountAtoms += ",..."_ns;
435 nonZeroRefcountAtomsCount++;
437 #endif
439 if (nonZeroRefcountAtomsCount) {
440 nsPrintfCString msg("%d dynamic atom(s) with non-zero refcount: %s",
441 nonZeroRefcountAtomsCount, nonZeroRefcountAtoms.get());
442 NS_ASSERTION(nonZeroRefcountAtomsCount == 0, msg.get());
445 nsDynamicAtom::gUnusedAtomCount -= removedCount;
448 void nsDynamicAtom::GCAtomTable() {
449 MOZ_ASSERT(gAtomTable);
450 if (NS_IsMainThread()) {
451 gAtomTable->GC(GCKind::RegularOperation);
455 //----------------------------------------------------------------------
457 // Have the static atoms been inserted into the table?
458 static bool gStaticAtomsDone = false;
460 void NS_InitAtomTable() {
461 MOZ_ASSERT(NS_IsMainThread());
462 MOZ_ASSERT(!gAtomTable);
464 // We register static atoms immediately so they're available for use as early
465 // as possible.
466 gAtomTable = new nsAtomTable();
467 gAtomTable->RegisterStaticAtoms(nsGkAtoms::sAtoms, nsGkAtoms::sAtomsLen);
468 gStaticAtomsDone = true;
471 void NS_ShutdownAtomTable() {
472 MOZ_ASSERT(NS_IsMainThread());
473 MOZ_ASSERT(gAtomTable);
475 #ifdef NS_FREE_PERMANENT_DATA
476 // Do a final GC to satisfy leak checking. We skip this step in release
477 // builds.
478 gAtomTable->GC(GCKind::Shutdown);
479 #endif
481 delete gAtomTable;
482 gAtomTable = nullptr;
485 void NS_AddSizeOfAtoms(MallocSizeOf aMallocSizeOf, AtomsSizes& aSizes) {
486 MOZ_ASSERT(NS_IsMainThread());
487 MOZ_ASSERT(gAtomTable);
488 return gAtomTable->AddSizeOfIncludingThis(aMallocSizeOf, aSizes);
491 void nsAtomSubTable::AddSizeOfExcludingThisLocked(MallocSizeOf aMallocSizeOf,
492 AtomsSizes& aSizes) {
493 aSizes.mTable += mTable.ShallowSizeOfExcludingThis(aMallocSizeOf);
494 for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) {
495 auto* entry = static_cast<AtomTableEntry*>(iter.Get());
496 entry->mAtom->AddSizeOfIncludingThis(aMallocSizeOf, aSizes);
500 void nsAtomTable::RegisterStaticAtoms(const nsStaticAtom* aAtoms,
501 size_t aAtomsLen) {
502 MOZ_ASSERT(NS_IsMainThread());
503 MOZ_RELEASE_ASSERT(!gStaticAtomsDone, "Static atom insertion is finished!");
505 for (uint32_t i = 0; i < aAtomsLen; ++i) {
506 const nsStaticAtom* atom = &aAtoms[i];
507 MOZ_ASSERT(IsAsciiNullTerminated(atom->String()));
508 MOZ_ASSERT(NS_strlen(atom->String()) == atom->GetLength());
509 MOZ_ASSERT(atom->IsAsciiLowercase() ==
510 ::IsAsciiLowercase(atom->String(), atom->GetLength()));
512 // This assertion ensures the static atom's precomputed hash value matches
513 // what would be computed by mozilla::HashString(aStr), which is what we use
514 // when atomizing strings. We compute this hash in Atom.py.
515 MOZ_ASSERT(HashString(atom->String()) == atom->hash());
517 AtomTableKey key(atom);
518 nsAtomSubTable& table = SelectSubTable(key);
519 AutoWriteLock lock(table.mLock);
520 AtomTableEntry* he = table.Add(key);
521 if (he->mAtom) {
522 // There are two ways we could get here.
523 // - Register two static atoms with the same string.
524 // - Create a dynamic atom and then register a static atom with the same
525 // string while the dynamic atom is alive.
526 // Both cases can cause subtle bugs, and are disallowed. We're
527 // programming in C++ here, not Smalltalk.
528 nsAutoCString name;
529 he->mAtom->ToUTF8String(name);
530 MOZ_CRASH_UNSAFE_PRINTF("Atom for '%s' already exists", name.get());
532 he->mAtom = const_cast<nsStaticAtom*>(atom);
536 already_AddRefed<nsAtom> NS_Atomize(const char* aUTF8String) {
537 MOZ_ASSERT(gAtomTable);
538 return gAtomTable->Atomize(nsDependentCString(aUTF8String));
541 already_AddRefed<nsAtom> nsAtomTable::Atomize(const nsACString& aUTF8String) {
542 bool err;
543 AtomTableKey key(aUTF8String.Data(), aUTF8String.Length(), &err);
544 if (MOZ_UNLIKELY(err)) {
545 MOZ_ASSERT_UNREACHABLE("Tried to atomize invalid UTF-8.");
546 // The input was invalid UTF-8. Let's replace the errors with U+FFFD
547 // and atomize the result.
548 nsString str;
549 CopyUTF8toUTF16(aUTF8String, str);
550 return Atomize(str);
552 nsAtomSubTable& table = SelectSubTable(key);
554 AutoReadLock lock(table.mLock);
555 if (AtomTableEntry* he = table.Search(key)) {
556 return do_AddRef(he->mAtom);
560 AutoWriteLock lock(table.mLock);
561 AtomTableEntry* he = table.Add(key);
563 if (he->mAtom) {
564 return do_AddRef(he->mAtom);
567 nsString str;
568 CopyUTF8toUTF16(aUTF8String, str);
569 MOZ_ASSERT(nsStringBuffer::FromString(str), "Should create a string buffer");
570 RefPtr<nsAtom> atom = dont_AddRef(nsDynamicAtom::Create(str, key.mHash));
572 he->mAtom = atom;
574 return atom.forget();
577 already_AddRefed<nsAtom> NS_Atomize(const nsACString& aUTF8String) {
578 MOZ_ASSERT(gAtomTable);
579 return gAtomTable->Atomize(aUTF8String);
582 already_AddRefed<nsAtom> NS_Atomize(const char16_t* aUTF16String) {
583 MOZ_ASSERT(gAtomTable);
584 return gAtomTable->Atomize(nsDependentString(aUTF16String));
587 already_AddRefed<nsAtom> nsAtomTable::Atomize(const nsAString& aUTF16String) {
588 AtomTableKey key(aUTF16String.Data(), aUTF16String.Length());
589 nsAtomSubTable& table = SelectSubTable(key);
591 AutoReadLock lock(table.mLock);
592 if (AtomTableEntry* he = table.Search(key)) {
593 return do_AddRef(he->mAtom);
596 AutoWriteLock lock(table.mLock);
597 AtomTableEntry* he = table.Add(key);
599 if (he->mAtom) {
600 RefPtr<nsAtom> atom = he->mAtom;
601 return atom.forget();
604 RefPtr<nsAtom> atom =
605 dont_AddRef(nsDynamicAtom::Create(aUTF16String, key.mHash));
606 he->mAtom = atom;
608 return atom.forget();
611 already_AddRefed<nsAtom> NS_Atomize(const nsAString& aUTF16String) {
612 MOZ_ASSERT(gAtomTable);
613 return gAtomTable->Atomize(aUTF16String);
616 already_AddRefed<nsAtom> nsAtomTable::AtomizeMainThread(
617 const nsAString& aUTF16String) {
618 MOZ_ASSERT(NS_IsMainThread());
619 RefPtr<nsAtom> retVal;
620 AtomTableKey key(aUTF16String.Data(), aUTF16String.Length());
621 auto p = sRecentlyUsedMainThreadAtoms.Lookup(key);
622 if (p) {
623 retVal = p.Data();
624 return retVal.forget();
627 nsAtomSubTable& table = SelectSubTable(key);
629 AutoReadLock lock(table.mLock);
630 if (AtomTableEntry* he = table.Search(key)) {
631 p.Set(he->mAtom);
632 return do_AddRef(he->mAtom);
636 AutoWriteLock lock(table.mLock);
637 AtomTableEntry* he = table.Add(key);
638 if (he->mAtom) {
639 retVal = he->mAtom;
640 } else {
641 RefPtr<nsAtom> newAtom =
642 dont_AddRef(nsDynamicAtom::Create(aUTF16String, key.mHash));
643 he->mAtom = newAtom;
644 retVal = std::move(newAtom);
647 p.Set(retVal);
648 return retVal.forget();
651 already_AddRefed<nsAtom> NS_AtomizeMainThread(const nsAString& aUTF16String) {
652 MOZ_ASSERT(gAtomTable);
653 return gAtomTable->AtomizeMainThread(aUTF16String);
656 nsrefcnt NS_GetNumberOfAtoms(void) {
657 MOZ_ASSERT(gAtomTable);
658 return gAtomTable->RacySlowCount();
661 int32_t NS_GetUnusedAtomCount(void) { return nsDynamicAtom::gUnusedAtomCount; }
663 nsStaticAtom* NS_GetStaticAtom(const nsAString& aUTF16String) {
664 MOZ_ASSERT(gStaticAtomsDone, "Static atom setup not yet done.");
665 MOZ_ASSERT(gAtomTable);
666 return gAtomTable->GetStaticAtom(aUTF16String);
669 nsStaticAtom* nsAtomTable::GetStaticAtom(const nsAString& aUTF16String) {
670 AtomTableKey key(aUTF16String.Data(), aUTF16String.Length());
671 nsAtomSubTable& table = SelectSubTable(key);
672 AutoReadLock lock(table.mLock);
673 AtomTableEntry* he = table.Search(key);
674 return he && he->mAtom->IsStatic() ? static_cast<nsStaticAtom*>(he->mAtom)
675 : nullptr;
678 void ToLowerCaseASCII(RefPtr<nsAtom>& aAtom) {
679 // Assume the common case is that the atom is already ASCII lowercase.
680 if (aAtom->IsAsciiLowercase()) {
681 return;
684 nsAutoString lowercased;
685 ToLowerCaseASCII(nsDependentAtomString(aAtom), lowercased);
686 aAtom = NS_Atomize(lowercased);