Bug Summary

File:root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h
Warning:line 1356, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name HeapSnapshot.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/devtools/shared/heapsnapshot -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/devtools/shared/heapsnapshot -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -D _GLIBCXX_ASSERTIONS=1 -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D GOOGLE_PROTOBUF_NO_RTTI -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D MOZ_SUPPORT_LEAKCHECKING -D STATIC_EXPORTABLE_JS_API -I /root/firefox-clang/devtools/shared/heapsnapshot -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/devtools/shared/heapsnapshot -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /root/firefox-clang/ipc/chromium/src -I /root/firefox-clang/third_party/abseil-cpp -I /root/firefox-clang/toolkit/components/telemetry -I /root/firefox-clang/xpcom/base -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=pessimizing-move -Wno-error=large-by-value-copy=128 -Wno-error=implicit-int-float-conversion -Wno-error=thread-safety-analysis -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -Wno-character-conversion -std=gnu++20 -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fno-implicit-modules -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-09-01-224014-2642839-1 -x c++ /root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp

/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5#include "HeapSnapshot.h"
6
7#include <google/protobuf/io/coded_stream.h>
8#include <google/protobuf/io/gzip_stream.h>
9#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
10
11#include "js/Array.h" // JS::NewArrayObject
12#include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin, JS::TaggedColumnNumberOneOrigin
13#include "js/Debug.h"
14#include "js/PropertyAndElement.h" // JS_DefineProperty
15#include "js/TypeDecls.h"
16#include "js/UbiNodeBreadthFirst.h"
17#include "js/UbiNodeCensus.h"
18#include "js/UbiNodeDominatorTree.h"
19#include "js/UbiNodeShortestPaths.h"
20#include "mozilla/Attributes.h"
21#include "mozilla/CycleCollectedJSContext.h"
22#include "mozilla/devtools/AutoMemMap.h"
23#include "mozilla/devtools/CoreDump.pb.h"
24#include "mozilla/devtools/DeserializedNode.h"
25#include "mozilla/devtools/DominatorTree.h"
26#include "mozilla/devtools/FileDescriptorOutputStream.h"
27#include "mozilla/devtools/HeapSnapshotTempFileHelperChild.h"
28#include "mozilla/devtools/ZeroCopyNSIOutputStream.h"
29#include "mozilla/dom/ChromeUtils.h"
30#include "mozilla/dom/ContentChild.h"
31#include "mozilla/dom/HeapSnapshotBinding.h"
32#include "mozilla/RangedPtr.h"
33#include "mozilla/glean/DevtoolsSharedHeapsnapshotMetrics.h"
34
35#include "jsapi.h"
36#include "jsfriendapi.h"
37#include "js/GCVector.h"
38#include "js/MapAndSet.h"
39#include "js/Object.h" // JS::GetCompartment
40#include "nsComponentManagerUtils.h" // do_CreateInstance
41#include "nsCycleCollectionParticipant.h"
42#include "nsCRTGlue.h"
43#include "nsIFile.h"
44#include "nsIOutputStream.h"
45#include "nsISupportsImpl.h"
46#include "nsNetUtil.h"
47#include "nsPrintfCString.h"
48#include "prerror.h"
49#include "prio.h"
50#include "prtypes.h"
51#include "SpecialSystemDirectory.h"
52
53namespace mozilla {
54namespace devtools {
55
56using namespace JS;
57using namespace dom;
58
59using ::google::protobuf::io::ArrayInputStream;
60using ::google::protobuf::io::CodedInputStream;
61using ::google::protobuf::io::GzipInputStream;
62using ::google::protobuf::io::ZeroCopyInputStream;
63
64using JS::ubi::AtomOrTwoByteChars;
65using JS::ubi::ShortestPaths;
66
67MallocSizeOf GetCurrentThreadDebuggerMallocSizeOf() {
68 auto ccjscx = CycleCollectedJSContext::Get();
69 MOZ_ASSERT(ccjscx)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ccjscx)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(ccjscx))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("ccjscx", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 69); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ccjscx" ")");
do { MOZ_CrashSequence(__null, 69); __attribute__((nomerge))
::abort(); } while (false); } } while (false)
;
70 auto cx = ccjscx->Context();
71 MOZ_ASSERT(cx)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(cx)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(cx))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("cx", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 71); AnnotateMozCrashReason("MOZ_ASSERT" "(" "cx" ")"); do {
MOZ_CrashSequence(__null, 71); __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
72 auto mallocSizeOf = JS::dbg::GetDebuggerMallocSizeOf(cx);
73 MOZ_ASSERT(mallocSizeOf)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mallocSizeOf)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mallocSizeOf))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("mallocSizeOf", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 73); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mallocSizeOf"
")"); do { MOZ_CrashSequence(__null, 73); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
74 return mallocSizeOf;
75}
76
77/*** Cycle Collection Boilerplate *********************************************/
78
79NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(HeapSnapshot, mParent)static_assert(std::is_base_of_v<nsWrapperCache, HeapSnapshot
>, "Class should inherit nsWrapperCache"); HeapSnapshot::cycleCollection
HeapSnapshot::_cycleCollectorGlobal( nsCycleCollectionParticipant
::FlagMaybeSingleZoneJSHolder); void HeapSnapshot::cycleCollection
::Trace( void* p, const TraceCallbacks& aCallbacks, void*
aClosure) { HeapSnapshot* tmp = DowncastCCParticipant<HeapSnapshot
>(p); TraceWrapper(p, aCallbacks, aClosure); (void)tmp; } void
HeapSnapshot::cycleCollection::TraceWrapper( void* p, const TraceCallbacks
& aCallbacks, void* aClosure) { HeapSnapshot* tmp = DowncastCCParticipant
<HeapSnapshot>(p); tmp->TraceWrapper(aCallbacks, aClosure
); } void HeapSnapshot::cycleCollection::Unlink(void* p) { HeapSnapshot
* tmp = DowncastCCParticipant<HeapSnapshot>(p); ImplCycleCollectionUnlink
(tmp->mParent); tmp->ReleaseWrapper(p); (void)tmp; } nsresult
HeapSnapshot::cycleCollection::TraverseNative( void* p, nsCycleCollectionTraversalCallback
& cb) { HeapSnapshot* tmp = DowncastCCParticipant<HeapSnapshot
>(p); cb.DescribeRefCountedNode(tmp->mRefCnt.get(), "HeapSnapshot"
); ImplCycleCollectionTraverse(cb, tmp->mParent, "mParent"
, 0); (void)tmp; return NS_OK; }
80
81NS_IMPL_CYCLE_COLLECTING_ADDREF(HeapSnapshot)MozExternalRefCountType HeapSnapshot::AddRef(void) { static_assert
(!std::is_destructible_v<HeapSnapshot>, "Reference-counted class "
"HeapSnapshot" " should not have a public destructor. " "Make this class's destructor non-public"
); do { static_assert( mozilla::detail::AssertionConditionType
<decltype(int32_t(mRefCnt) >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) >= 0))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) >= 0"
" (" "illegal refcnt" ")", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 81); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) >= 0"
") (" "illegal refcnt" ")"); do { MOZ_CrashSequence(__null, 81
); __attribute__((nomerge)) ::abort(); } while (false); } } while
(false); _mOwningThread.AssertOwnership("HeapSnapshot" " not thread-safe"
); nsISupports* base = HeapSnapshot::cycleCollection::Upcast(
this); nsrefcnt count = mRefCnt.incr(base); NS_LogAddRef((this
), (count), ("HeapSnapshot"), (uint32_t)(sizeof(*this))); return
count; }
82NS_IMPL_CYCLE_COLLECTING_RELEASE(HeapSnapshot)MozExternalRefCountType HeapSnapshot::Release(void) { do { static_assert
( mozilla::detail::AssertionConditionType<decltype(int32_t
(mRefCnt) > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) > 0))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) > 0"
" (" "dup release" ")", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 82); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) > 0"
") (" "dup release" ")"); do { MOZ_CrashSequence(__null, 82)
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false); _mOwningThread.AssertOwnership("HeapSnapshot" " not thread-safe"
); nsISupports* base = HeapSnapshot::cycleCollection::Upcast(
this); nsrefcnt count = mRefCnt.decr(base); if (count == 0) {
NS_CycleCollectableHasRefCntZero(); } NS_LogRelease((this), (
count), ("HeapSnapshot")); return count; } void HeapSnapshot::
DeleteCycleCollectable(void) { delete (this); }
83
84NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(HeapSnapshot)nsresult HeapSnapshot::QueryInterface(const nsIID& aIID, void
** aInstancePtr) { do { if (!(aInstancePtr)) { NS_DebugBreak(
NS_DEBUG_ASSERTION, "QueryInterface requires a non-NULL destination!"
, "aInstancePtr", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 84); MOZ_PretendNoReturn(); } } while (0); nsISupports* foundInterface
; if (TopThreeWordsEquals( aIID, (nsXPCOMCycleCollectionParticipant
::kIID), (nsCycleCollectionISupports::kIID)) && (LowWordEquals
(aIID, (nsXPCOMCycleCollectionParticipant::kIID)) || LowWordEquals
(aIID, (nsCycleCollectionISupports::kIID)))) { if (LowWordEquals
(aIID, (nsXPCOMCycleCollectionParticipant::kIID))) { *aInstancePtr
= HeapSnapshot::cycleCollection::GetParticipant(); return NS_OK
; } if (LowWordEquals(aIID, (nsCycleCollectionISupports::kIID
))) { *aInstancePtr = HeapSnapshot::cycleCollection::Upcast(this
); return NS_OK; } foundInterface = nullptr; } else
85 NS_WRAPPERCACHE_INTERFACE_MAP_ENTRYif (aIID.Equals((nsWrapperCache::kIID))) { *aInstancePtr = static_cast
<nsWrapperCache*>(this); return NS_OK; } else
86 NS_INTERFACE_MAP_ENTRY(nsISupports)if (aIID.Equals(mozilla::detail::kImplementedIID<std::remove_reference_t
<decltype(*this)>, nsISupports>)) foundInterface = static_cast
<nsISupports*>(this); else
87NS_INTERFACE_MAP_ENDfoundInterface = 0; nsresult status; if (!foundInterface) { do
{ static_assert( mozilla::detail::AssertionConditionType<
decltype(!aIID.Equals((nsISupports::kIID)))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aIID.Equals((nsISupports::kIID
))))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!aIID.Equals((nsISupports::kIID))", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 87); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aIID.Equals((nsISupports::kIID))"
")"); do { MOZ_CrashSequence(__null, 87); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); status = NS_NOINTERFACE
; } else { (foundInterface)->AddRef(); status = NS_OK; } *
aInstancePtr = foundInterface; return status; }
88
89/* virtual */
90JSObject* HeapSnapshot::WrapObject(JSContext* aCx,
91 JS::Handle<JSObject*> aGivenProto) {
92 return HeapSnapshot_Binding::Wrap(aCx, this, aGivenProto);
93}
94
95/*** Reading Heap Snapshots ***************************************************/
96
97/* static */
98already_AddRefed<HeapSnapshot> HeapSnapshot::Create(JSContext* cx,
99 GlobalObject& global,
100 const uint8_t* buffer,
101 uint32_t size,
102 ErrorResult& rv) {
103 RefPtr<HeapSnapshot> snapshot = new HeapSnapshot(cx, global.GetAsSupports());
104 if (!snapshot->init(cx, buffer, size)) {
105 rv.Throw(NS_ERROR_UNEXPECTED);
106 return nullptr;
107 }
108 return snapshot.forget();
109}
110
111template <typename MessageType>
112static bool parseMessage(ZeroCopyInputStream& stream, uint32_t sizeOfMessage,
113 MessageType& message) {
114 // We need to create a new `CodedInputStream` for each message so that the
115 // 64MB limit is applied per-message rather than to the whole stream.
116 CodedInputStream codedStream(&stream);
117
118 // The protobuf message nesting that core dumps exhibit is dominated by
119 // allocation stacks' frames. In the most deeply nested case, each frame has
120 // two messages: a StackFrame message and a StackFrame::Data message. These
121 // frames are on top of a small constant of other messages. There are a
122 // MAX_STACK_DEPTH number of frames, so we multiply this by 3 to make room for
123 // the two messages per frame plus some head room for the constant number of
124 // non-dominating messages.
125 codedStream.SetRecursionLimit(HeapSnapshot::MAX_STACK_DEPTH * 3);
126
127 auto limit = codedStream.PushLimit(sizeOfMessage);
128 if (NS_WARN_IF(!message.ParseFromCodedStream(&codedStream))NS_warn_if_impl(!message.ParseFromCodedStream(&codedStream
), "!message.ParseFromCodedStream(&codedStream)", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 128)
||
129 NS_WARN_IF(!codedStream.ConsumedEntireMessage())NS_warn_if_impl(!codedStream.ConsumedEntireMessage(), "!codedStream.ConsumedEntireMessage()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 129)
||
130 NS_WARN_IF(codedStream.BytesUntilLimit() != 0)NS_warn_if_impl(codedStream.BytesUntilLimit() != 0, "codedStream.BytesUntilLimit() != 0"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 130)
) {
131 return false;
132 }
133
134 codedStream.PopLimit(limit);
135 return true;
136}
137
138template <typename CharT, typename InternedStringSet>
139struct GetOrInternStringMatcher {
140 InternedStringSet& internedStrings;
141
142 explicit GetOrInternStringMatcher(InternedStringSet& strings)
143 : internedStrings(strings) {}
144
145 const CharT* operator()(const std::string* str) {
146 MOZ_ASSERT(str)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(str)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(str))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("str", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 146); AnnotateMozCrashReason("MOZ_ASSERT" "(" "str" ")"); do
{ MOZ_CrashSequence(__null, 146); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
147 size_t length = str->length() / sizeof(CharT);
148 auto tempString = reinterpret_cast<const CharT*>(str->data());
149
150 UniqueFreePtr<CharT[]> owned(NS_xstrndup(tempString, length));
151 if (!internedStrings.append(std::move(owned))) return nullptr;
152
153 return internedStrings.back().get();
154 }
155
156 const CharT* operator()(uint64_t ref) {
157 if (MOZ_LIKELY(ref < internedStrings.length())(__builtin_expect(!!(ref < internedStrings.length()), 1))) {
158 auto& string = internedStrings[ref];
159 MOZ_ASSERT(string)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(string)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(string))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("string", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 159); AnnotateMozCrashReason("MOZ_ASSERT" "(" "string" ")")
; do { MOZ_CrashSequence(__null, 159); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
160 return string.get();
161 }
162
163 return nullptr;
164 }
165};
166
167template <
168 // Either char or char16_t.
169 typename CharT,
170 // A reference to either `internedOneByteStrings` or
171 // `internedTwoByteStrings` if CharT is char or char16_t respectively.
172 typename InternedStringSet>
173const CharT* HeapSnapshot::getOrInternString(
174 InternedStringSet& internedStrings, Maybe<StringOrRef>& maybeStrOrRef) {
175 // Incomplete message: has neither a string nor a reference to an already
176 // interned string.
177 if (MOZ_UNLIKELY(maybeStrOrRef.isNothing())(__builtin_expect(!!(maybeStrOrRef.isNothing()), 0))) return nullptr;
178
179 GetOrInternStringMatcher<CharT, InternedStringSet> m(internedStrings);
180 return maybeStrOrRef->match(m);
181}
182
183// Get a de-duplicated string as a Maybe<StringOrRef> from the given `msg`.
184#define GET_STRING_OR_REF_WITH_PROP_NAMES(msg, strPropertyName, \
185 refPropertyName) \
186 (msg.has_##refPropertyName() ? Some(StringOrRef(msg.refPropertyName())) \
187 : msg.has_##strPropertyName() ? Some(StringOrRef(&msg.strPropertyName())) \
188 : Nothing())
189
190#define GET_STRING_OR_REF(msg, property) \
191 (msg.has_##property##ref() ? Some(StringOrRef(msg.property##ref())) \
192 : msg.has_##property() ? Some(StringOrRef(&msg.property())) \
193 : Nothing())
194
195bool HeapSnapshot::saveNode(const protobuf::Node& node,
196 NodeIdSet& edgeReferents) {
197 // NB: de-duplicated string properties must be read back and interned in the
198 // same order here as they are written and serialized in
199 // `CoreDumpWriter::writeNode` or else indices in references to already
200 // serialized strings will be off.
201
202 if (NS_WARN_IF(!node.has_id())NS_warn_if_impl(!node.has_id(), "!node.has_id()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 202)
) return false;
203 NodeId id = node.id();
204
205 // NodeIds are derived from pointers (at most 48 bits) and we rely on them
206 // fitting into JS numbers (IEEE 754 doubles, can precisely store 53 bit
207 // integers) despite storing them on disk as 64 bit integers.
208 if (NS_WARN_IF(!JS::Value::isNumberRepresentable(id))NS_warn_if_impl(!JS::Value::isNumberRepresentable(id), "!JS::Value::isNumberRepresentable(id)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 208)
) return false;
209
210 // Should only deserialize each node once.
211 if (NS_WARN_IF(nodes.has(id))NS_warn_if_impl(nodes.has(id), "nodes.has(id)", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 211)
) return false;
212
213 if (NS_WARN_IF(!JS::ubi::Uint32IsValidCoarseType(node.coarsetype()))NS_warn_if_impl(!JS::ubi::Uint32IsValidCoarseType(node.coarsetype
()), "!JS::ubi::Uint32IsValidCoarseType(node.coarsetype())", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 213)
)
214 return false;
215 auto coarseType = JS::ubi::Uint32ToCoarseType(node.coarsetype());
216
217 Maybe<StringOrRef> typeNameOrRef =
218 GET_STRING_OR_REF_WITH_PROP_NAMES(node, typename_, typenameref);
219 auto typeName =
220 getOrInternString<char16_t>(internedTwoByteStrings, typeNameOrRef);
221 if (NS_WARN_IF(!typeName)NS_warn_if_impl(!typeName, "!typeName", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 221)
) return false;
222
223 if (NS_WARN_IF(!node.has_size())NS_warn_if_impl(!node.has_size(), "!node.has_size()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 223)
) return false;
224 uint64_t size = node.size();
225
226 auto edgesLength = node.edges_size();
227 DeserializedNode::EdgeVector edges;
228 if (NS_WARN_IF(!edges.reserve(edgesLength))NS_warn_if_impl(!edges.reserve(edgesLength), "!edges.reserve(edgesLength)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 228)
) return false;
229 for (decltype(edgesLength) i = 0; i < edgesLength; i++) {
230 auto& protoEdge = node.edges(i);
231
232 if (NS_WARN_IF(!protoEdge.has_referent())NS_warn_if_impl(!protoEdge.has_referent(), "!protoEdge.has_referent()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 232)
) return false;
233 NodeId referent = protoEdge.referent();
234
235 if (NS_WARN_IF(!edgeReferents.put(referent))NS_warn_if_impl(!edgeReferents.put(referent), "!edgeReferents.put(referent)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 235)
) return false;
236
237 const char16_t* edgeName = nullptr;
238 if (protoEdge.EdgeNameOrRef_case() !=
239 protobuf::Edge::EDGENAMEORREF_NOT_SET) {
240 Maybe<StringOrRef> edgeNameOrRef = GET_STRING_OR_REF(protoEdge, name);
241 edgeName =
242 getOrInternString<char16_t>(internedTwoByteStrings, edgeNameOrRef);
243 if (NS_WARN_IF(!edgeName)NS_warn_if_impl(!edgeName, "!edgeName", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 243)
) return false;
244 }
245
246 edges.infallibleAppend(DeserializedEdge(referent, edgeName));
247 }
248
249 Maybe<StackFrameId> allocationStack;
250 if (node.has_allocationstack()) {
251 StackFrameId id = 0;
252 if (NS_WARN_IF(!saveStackFrame(node.allocationstack(), id))NS_warn_if_impl(!saveStackFrame(node.allocationstack(), id), "!saveStackFrame(node.allocationstack(), id)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 252)
) return false;
253 allocationStack.emplace(id);
254 }
255 MOZ_ASSERT(allocationStack.isSome() == node.has_allocationstack())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(allocationStack.isSome() == node.has_allocationstack
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(allocationStack.isSome() == node.has_allocationstack
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("allocationStack.isSome() == node.has_allocationstack()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 255); AnnotateMozCrashReason("MOZ_ASSERT" "(" "allocationStack.isSome() == node.has_allocationstack()"
")"); do { MOZ_CrashSequence(__null, 255); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
256
257 const char* jsObjectClassName = nullptr;
258 if (node.JSObjectClassNameOrRef_case() !=
259 protobuf::Node::JSOBJECTCLASSNAMEORREF_NOT_SET) {
260 Maybe<StringOrRef> clsNameOrRef =
261 GET_STRING_OR_REF(node, jsobjectclassname);
262 jsObjectClassName =
263 getOrInternString<char>(internedOneByteStrings, clsNameOrRef);
264 if (NS_WARN_IF(!jsObjectClassName)NS_warn_if_impl(!jsObjectClassName, "!jsObjectClassName", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 264)
) return false;
265 }
266
267 const char* scriptFilename = nullptr;
268 if (node.ScriptFilenameOrRef_case() !=
269 protobuf::Node::SCRIPTFILENAMEORREF_NOT_SET) {
270 Maybe<StringOrRef> scriptFilenameOrRef =
271 GET_STRING_OR_REF(node, scriptfilename);
272 scriptFilename =
273 getOrInternString<char>(internedOneByteStrings, scriptFilenameOrRef);
274 if (NS_WARN_IF(!scriptFilename)NS_warn_if_impl(!scriptFilename, "!scriptFilename", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 274)
) return false;
275 }
276
277 const char16_t* descriptiveTypeName = nullptr;
278 if (node.descriptiveTypeNameOrRef_case() !=
279 protobuf::Node::DESCRIPTIVETYPENAMEORREF_NOT_SET) {
280 Maybe<StringOrRef> descriptiveTypeNameOrRef =
281 GET_STRING_OR_REF(node, descriptivetypename);
282 descriptiveTypeName = getOrInternString<char16_t>(internedTwoByteStrings,
283 descriptiveTypeNameOrRef);
284 if (NS_WARN_IF(!descriptiveTypeName)NS_warn_if_impl(!descriptiveTypeName, "!descriptiveTypeName",
"/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 284)
) return false;
285 }
286
287 if (NS_WARN_IF(!nodes.putNew(NS_warn_if_impl(!nodes.putNew( id, DeserializedNode(id, coarseType
, typeName, size, std::move(edges), allocationStack, jsObjectClassName
, scriptFilename, descriptiveTypeName, *this)), "!nodes.putNew( id, DeserializedNode(id, coarseType, typeName, size, std::move(edges), allocationStack, jsObjectClassName, scriptFilename, descriptiveTypeName, *this))"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 290)
288 id, DeserializedNode(id, coarseType, typeName, size, std::move(edges),NS_warn_if_impl(!nodes.putNew( id, DeserializedNode(id, coarseType
, typeName, size, std::move(edges), allocationStack, jsObjectClassName
, scriptFilename, descriptiveTypeName, *this)), "!nodes.putNew( id, DeserializedNode(id, coarseType, typeName, size, std::move(edges), allocationStack, jsObjectClassName, scriptFilename, descriptiveTypeName, *this))"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 290)
289 allocationStack, jsObjectClassName,NS_warn_if_impl(!nodes.putNew( id, DeserializedNode(id, coarseType
, typeName, size, std::move(edges), allocationStack, jsObjectClassName
, scriptFilename, descriptiveTypeName, *this)), "!nodes.putNew( id, DeserializedNode(id, coarseType, typeName, size, std::move(edges), allocationStack, jsObjectClassName, scriptFilename, descriptiveTypeName, *this))"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 290)
290 scriptFilename, descriptiveTypeName, *this)))NS_warn_if_impl(!nodes.putNew( id, DeserializedNode(id, coarseType
, typeName, size, std::move(edges), allocationStack, jsObjectClassName
, scriptFilename, descriptiveTypeName, *this)), "!nodes.putNew( id, DeserializedNode(id, coarseType, typeName, size, std::move(edges), allocationStack, jsObjectClassName, scriptFilename, descriptiveTypeName, *this))"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 290)
) {
291 return false;
292 };
293
294 return true;
295}
296
297bool HeapSnapshot::saveStackFrame(const protobuf::StackFrame& frame,
298 StackFrameId& outFrameId) {
299 // NB: de-duplicated string properties must be read in the same order here as
300 // they are written in `CoreDumpWriter::getProtobufStackFrame` or else indices
301 // in references to already serialized strings will be off.
302
303 if (frame.has_ref()) {
304 // We should only get a reference to the previous frame if we have already
305 // seen the previous frame.
306 if (!frames.has(frame.ref())) return false;
307
308 outFrameId = frame.ref();
309 return true;
310 }
311
312 // Incomplete message.
313 if (!frame.has_data()) return false;
314
315 const auto& data = frame.data();
316
317 if (!data.has_id()) return false;
318 StackFrameId id = data.id();
319
320 // This should be the first and only time we see this frame.
321 if (frames.has(id)) return false;
322
323 if (!data.has_line()) return false;
324 uint32_t line = data.line();
325
326 if (!data.has_column()) return false;
327 JS::TaggedColumnNumberOneOrigin column(
328 JS::LimitedColumnNumberOneOrigin(data.column()));
329
330 if (!data.has_issystem()) return false;
331 bool isSystem = data.issystem();
332
333 if (!data.has_isselfhosted()) return false;
334 bool isSelfHosted = data.isselfhosted();
335
336 Maybe<StringOrRef> sourceOrRef = GET_STRING_OR_REF(data, source);
337 auto source =
338 getOrInternString<char16_t>(internedTwoByteStrings, sourceOrRef);
339 if (!source) return false;
340
341 const char16_t* functionDisplayName = nullptr;
342 if (data.FunctionDisplayNameOrRef_case() !=
343 protobuf::StackFrame_Data::FUNCTIONDISPLAYNAMEORREF_NOT_SET) {
344 Maybe<StringOrRef> nameOrRef = GET_STRING_OR_REF(data, functiondisplayname);
345 functionDisplayName =
346 getOrInternString<char16_t>(internedTwoByteStrings, nameOrRef);
347 if (!functionDisplayName) return false;
348 }
349
350 Maybe<StackFrameId> parent;
351 if (data.has_parent()) {
352 StackFrameId parentId = 0;
353 if (!saveStackFrame(data.parent(), parentId)) return false;
354 parent = Some(parentId);
355 }
356
357 if (!frames.putNew(id,
358 DeserializedStackFrame(id, parent, line, column, source,
359 functionDisplayName, isSystem,
360 isSelfHosted, *this))) {
361 return false;
362 }
363
364 outFrameId = id;
365 return true;
366}
367
368#undef GET_STRING_OR_REF_WITH_PROP_NAMES
369#undef GET_STRING_OR_REF
370
371// Because protobuf messages aren't self-delimiting, we serialize each message
372// preceded by its size in bytes. When deserializing, we read this size and then
373// limit reading from the stream to the given byte size. If we didn't, then the
374// first message would consume the entire stream.
375static bool readSizeOfNextMessage(ZeroCopyInputStream& stream,
376 uint32_t* sizep) {
377 MOZ_ASSERT(sizep)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(sizep)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(sizep))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("sizep", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 377); AnnotateMozCrashReason("MOZ_ASSERT" "(" "sizep" ")");
do { MOZ_CrashSequence(__null, 377); __attribute__((nomerge)
) ::abort(); } while (false); } } while (false)
;
378 CodedInputStream codedStream(&stream);
379 return codedStream.ReadVarint32(sizep) && *sizep > 0;
380}
381
382bool HeapSnapshot::init(JSContext* cx, const uint8_t* buffer, uint32_t size) {
383 ArrayInputStream stream(buffer, size);
384 GzipInputStream gzipStream(&stream);
385 uint32_t sizeOfMessage = 0;
386
387 // First is the metadata.
388
389 protobuf::Metadata metadata;
390 if (NS_WARN_IF(!readSizeOfNextMessage(gzipStream, &sizeOfMessage))NS_warn_if_impl(!readSizeOfNextMessage(gzipStream, &sizeOfMessage
), "!readSizeOfNextMessage(gzipStream, &sizeOfMessage)", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 390)
)
391 return false;
392 if (!parseMessage(gzipStream, sizeOfMessage, metadata)) return false;
393 if (metadata.has_timestamp()) timestamp.emplace(metadata.timestamp());
394
395 // Next is the root node.
396
397 protobuf::Node root;
398 if (NS_WARN_IF(!readSizeOfNextMessage(gzipStream, &sizeOfMessage))NS_warn_if_impl(!readSizeOfNextMessage(gzipStream, &sizeOfMessage
), "!readSizeOfNextMessage(gzipStream, &sizeOfMessage)", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 398)
)
399 return false;
400 if (!parseMessage(gzipStream, sizeOfMessage, root)) return false;
401
402 // Although the id is optional in the protobuf format for future proofing, we
403 // can't currently do anything without it.
404 if (NS_WARN_IF(!root.has_id())NS_warn_if_impl(!root.has_id(), "!root.has_id()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 404)
) return false;
405 rootId = root.id();
406
407 // The set of all node ids we've found edges pointing to.
408 NodeIdSet edgeReferents(cx);
409
410 if (NS_WARN_IF(!saveNode(root, edgeReferents))NS_warn_if_impl(!saveNode(root, edgeReferents), "!saveNode(root, edgeReferents)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 410)
) return false;
411
412 // Finally, the rest of the nodes in the core dump.
413
414 // Test for the end of the stream. The protobuf library gives no way to tell
415 // the difference between an underlying read error and the stream being
416 // done. All we can do is attempt to read the size of the next message and
417 // extrapolate guestimations from the result of that operation.
418 while (readSizeOfNextMessage(gzipStream, &sizeOfMessage)) {
419 protobuf::Node node;
420 if (!parseMessage(gzipStream, sizeOfMessage, node)) return false;
421 if (NS_WARN_IF(!saveNode(node, edgeReferents))NS_warn_if_impl(!saveNode(node, edgeReferents), "!saveNode(node, edgeReferents)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 421)
) return false;
422 }
423
424 // Check the set of node ids referred to by edges we found and ensure that we
425 // have the node corresponding to each id. If we don't have all of them, it is
426 // unsafe to perform analyses of this heap snapshot.
427 for (auto iter = edgeReferents.iter(); !iter.done(); iter.next()) {
428 if (NS_WARN_IF(!nodes.has(iter.get()))NS_warn_if_impl(!nodes.has(iter.get()), "!nodes.has(iter.get())"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 428)
) return false;
429 }
430
431 return true;
432}
433
434/*** Heap Snapshot Analyses ***************************************************/
435
436void HeapSnapshot::TakeCensus(JSContext* cx, JS::Handle<JSObject*> options,
437 JS::MutableHandle<JS::Value> rval,
438 ErrorResult& rv) {
439 JS::ubi::Census census(cx);
440
441 JS::ubi::CountTypePtr rootType;
442 if (NS_WARN_IF(!JS::ubi::ParseCensusOptions(cx, census, options, rootType))NS_warn_if_impl(!JS::ubi::ParseCensusOptions(cx, census, options
, rootType), "!JS::ubi::ParseCensusOptions(cx, census, options, rootType)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 442)
) {
443 rv.Throw(NS_ERROR_UNEXPECTED);
444 return;
445 }
446
447 JS::ubi::RootedCount rootCount(cx, rootType->makeCount());
448 if (NS_WARN_IF(!rootCount)NS_warn_if_impl(!rootCount, "!rootCount", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 448)
) {
449 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
450 return;
451 }
452
453 JS::ubi::CensusHandler handler(census, rootCount,
454 GetCurrentThreadDebuggerMallocSizeOf());
455
456 {
457 JS::AutoCheckCannotGC nogc;
458
459 JS::ubi::CensusTraversal traversal(cx, handler, nogc);
460
461 if (NS_WARN_IF(!traversal.addStart(getRoot()))NS_warn_if_impl(!traversal.addStart(getRoot()), "!traversal.addStart(getRoot())"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 461)
) {
462 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
463 return;
464 }
465
466 if (NS_WARN_IF(!traversal.traverse())NS_warn_if_impl(!traversal.traverse(), "!traversal.traverse()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 466)
) {
467 rv.Throw(NS_ERROR_UNEXPECTED);
468 return;
469 }
470 }
471
472 if (NS_WARN_IF(!handler.report(cx, rval))NS_warn_if_impl(!handler.report(cx, rval), "!handler.report(cx, rval)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 472)
) {
473 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
474 return;
475 }
476}
477
478void HeapSnapshot::DescribeNode(JSContext* cx, JS::Handle<JSObject*> breakdown,
479 uint64_t nodeId,
480 JS::MutableHandle<JS::Value> rval,
481 ErrorResult& rv) {
482 MOZ_ASSERT(breakdown)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(breakdown)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(breakdown))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("breakdown", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 482); AnnotateMozCrashReason("MOZ_ASSERT" "(" "breakdown" ")"
); do { MOZ_CrashSequence(__null, 482); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
483 JS::Rooted<JS::Value> breakdownVal(cx, JS::ObjectValue(*breakdown));
484 JS::Rooted<JS::GCVector<JSLinearString*>> seen(cx, cx);
485 JS::ubi::CountTypePtr rootType =
486 JS::ubi::ParseBreakdown(cx, breakdownVal, &seen);
487 if (NS_WARN_IF(!rootType)NS_warn_if_impl(!rootType, "!rootType", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 487)
) {
488 rv.Throw(NS_ERROR_UNEXPECTED);
489 return;
490 }
491
492 JS::ubi::RootedCount rootCount(cx, rootType->makeCount());
493 if (NS_WARN_IF(!rootCount)NS_warn_if_impl(!rootCount, "!rootCount", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 493)
) {
494 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
495 return;
496 }
497
498 JS::ubi::Node::Id id(nodeId);
499 Maybe<JS::ubi::Node> node = getNodeById(id);
500 if (NS_WARN_IF(node.isNothing())NS_warn_if_impl(node.isNothing(), "node.isNothing()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 500)
) {
501 rv.Throw(NS_ERROR_INVALID_ARG);
502 return;
503 }
504
505 MallocSizeOf mallocSizeOf = GetCurrentThreadDebuggerMallocSizeOf();
506 if (NS_WARN_IF(!rootCount->count(mallocSizeOf, *node))NS_warn_if_impl(!rootCount->count(mallocSizeOf, *node), "!rootCount->count(mallocSizeOf, *node)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 506)
) {
507 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
508 return;
509 }
510
511 if (NS_WARN_IF(!rootCount->report(cx, rval))NS_warn_if_impl(!rootCount->report(cx, rval), "!rootCount->report(cx, rval)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 511)
) {
512 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
513 return;
514 }
515}
516
517already_AddRefed<DominatorTree> HeapSnapshot::ComputeDominatorTree(
518 ErrorResult& rv) {
519 Maybe<JS::ubi::DominatorTree> maybeTree;
520 {
521 auto ccjscx = CycleCollectedJSContext::Get();
522 MOZ_ASSERT(ccjscx)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ccjscx)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(ccjscx))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("ccjscx", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 522); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ccjscx" ")")
; do { MOZ_CrashSequence(__null, 522); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
523 auto cx = ccjscx->Context();
524 MOZ_ASSERT(cx)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(cx)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(cx))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("cx", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 524); AnnotateMozCrashReason("MOZ_ASSERT" "(" "cx" ")"); do
{ MOZ_CrashSequence(__null, 524); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
525 JS::AutoCheckCannotGC nogc(cx);
526 maybeTree = JS::ubi::DominatorTree::Create(cx, nogc, getRoot());
527 }
528
529 if (NS_WARN_IF(maybeTree.isNothing())NS_warn_if_impl(maybeTree.isNothing(), "maybeTree.isNothing()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 529)
) {
530 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
531 return nullptr;
532 }
533
534 return MakeAndAddRef<DominatorTree>(std::move(*maybeTree), this, mParent);
535}
536
537void HeapSnapshot::ComputeShortestPaths(JSContext* cx, uint64_t start,
538 const Sequence<uint64_t>& targets,
539 uint64_t maxNumPaths,
540 JS::MutableHandle<JSObject*> results,
541 ErrorResult& rv) {
542 // First ensure that our inputs are valid.
543
544 if (NS_WARN_IF(maxNumPaths == 0)NS_warn_if_impl(maxNumPaths == 0, "maxNumPaths == 0", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 544)
) {
1
Assuming 'maxNumPaths' is not equal to 0
2
Taking false branch
545 rv.Throw(NS_ERROR_INVALID_ARG);
546 return;
547 }
548
549 Maybe<JS::ubi::Node> startNode = getNodeById(start);
3
Calling 'HeapSnapshot::getNodeById'
550 if (NS_WARN_IF(startNode.isNothing())NS_warn_if_impl(startNode.isNothing(), "startNode.isNothing()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 550)
) {
551 rv.Throw(NS_ERROR_INVALID_ARG);
552 return;
553 }
554
555 if (NS_WARN_IF(targets.Length() == 0)NS_warn_if_impl(targets.Length() == 0, "targets.Length() == 0"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 555)
) {
556 rv.Throw(NS_ERROR_INVALID_ARG);
557 return;
558 }
559
560 // Aggregate the targets into a set and make sure that they exist in the heap
561 // snapshot.
562
563 JS::ubi::NodeSet targetsSet;
564
565 for (const auto& target : targets) {
566 Maybe<JS::ubi::Node> targetNode = getNodeById(target);
567 if (NS_WARN_IF(targetNode.isNothing())NS_warn_if_impl(targetNode.isNothing(), "targetNode.isNothing()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 567)
) {
568 rv.Throw(NS_ERROR_INVALID_ARG);
569 return;
570 }
571
572 if (NS_WARN_IF(!targetsSet.put(*targetNode))NS_warn_if_impl(!targetsSet.put(*targetNode), "!targetsSet.put(*targetNode)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 572)
) {
573 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
574 return;
575 }
576 }
577
578 // Walk the heap graph and find the shortest paths.
579
580 Maybe<ShortestPaths> maybeShortestPaths;
581 {
582 JS::AutoCheckCannotGC nogc(cx);
583 maybeShortestPaths = ShortestPaths::Create(
584 cx, nogc, maxNumPaths, *startNode, std::move(targetsSet));
585 }
586
587 if (NS_WARN_IF(maybeShortestPaths.isNothing())NS_warn_if_impl(maybeShortestPaths.isNothing(), "maybeShortestPaths.isNothing()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 587)
) {
588 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
589 return;
590 }
591
592 auto& shortestPaths = *maybeShortestPaths;
593
594 // Convert the results into a Map object mapping target node IDs to arrays of
595 // paths found.
596
597 JS::Rooted<JSObject*> resultsMap(cx, JS::NewMapObject(cx));
598 if (NS_WARN_IF(!resultsMap)NS_warn_if_impl(!resultsMap, "!resultsMap", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 598)
) {
599 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
600 return;
601 }
602
603 for (auto iter = shortestPaths.targetIter(); !iter.done(); iter.next()) {
604 JS::Rooted<JS::Value> key(cx, JS::NumberValue(iter.get().identifier()));
605 JS::RootedVector<JS::Value> paths(cx);
606
607 bool ok = shortestPaths.forEachPath(iter.get(), [&](JS::ubi::Path& path) {
608 JS::RootedVector<JS::Value> pathValues(cx);
609
610 for (JS::ubi::BackEdge* edge : path) {
611 JS::Rooted<JSObject*> pathPart(cx, JS_NewPlainObject(cx));
612 if (!pathPart) {
613 return false;
614 }
615
616 JS::Rooted<JS::Value> predecessor(
617 cx, NumberValue(edge->predecessor().identifier()));
618 if (!JS_DefineProperty(cx, pathPart, "predecessor", predecessor,
619 JSPROP_ENUMERATE)) {
620 return false;
621 }
622
623 JS::Rooted<JS::Value> edgeNameVal(cx, NullValue());
624 if (edge->name()) {
625 JS::Rooted<JSString*> edgeName(
626 cx, JS_AtomizeUCString(cx, edge->name().get()));
627 if (!edgeName) {
628 return false;
629 }
630 edgeNameVal = StringValue(edgeName);
631 }
632
633 if (!JS_DefineProperty(cx, pathPart, "edge", edgeNameVal,
634 JSPROP_ENUMERATE)) {
635 return false;
636 }
637
638 if (!pathValues.append(ObjectValue(*pathPart))) {
639 return false;
640 }
641 }
642
643 JS::Rooted<JSObject*> pathObj(cx, JS::NewArrayObject(cx, pathValues));
644 return pathObj && paths.append(ObjectValue(*pathObj));
645 });
646
647 if (NS_WARN_IF(!ok)NS_warn_if_impl(!ok, "!ok", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 647)
) {
648 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
649 return;
650 }
651
652 JS::Rooted<JSObject*> pathsArray(cx, JS::NewArrayObject(cx, paths));
653 if (NS_WARN_IF(!pathsArray)NS_warn_if_impl(!pathsArray, "!pathsArray", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 653)
) {
654 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
655 return;
656 }
657
658 JS::Rooted<JS::Value> pathsVal(cx, ObjectValue(*pathsArray));
659 if (NS_WARN_IF(!JS::MapSet(cx, resultsMap, key, pathsVal))NS_warn_if_impl(!JS::MapSet(cx, resultsMap, key, pathsVal), "!JS::MapSet(cx, resultsMap, key, pathsVal)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 659)
) {
660 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
661 return;
662 }
663 }
664
665 results.set(resultsMap);
666}
667
668/*** Saving Heap Snapshots ****************************************************/
669
670// If we are only taking a snapshot of the heap affected by the given set of
671// globals, find the set of compartments the globals are allocated
672// within. Returns false on OOM failure.
673static bool PopulateCompartmentsWithGlobals(
674 CompartmentSet& compartments, JS::HandleVector<JSObject*> globals) {
675 unsigned length = globals.length();
676 for (unsigned i = 0; i < length; i++) {
677 if (!compartments.put(JS::GetCompartment(globals[i]))) return false;
678 }
679
680 return true;
681}
682
683// Add the given set of globals as explicit roots in the given roots
684// list. Returns false on OOM failure.
685static bool AddGlobalsAsRoots(JS::HandleVector<JSObject*> globals,
686 ubi::RootList& roots) {
687 unsigned length = globals.length();
688 for (unsigned i = 0; i < length; i++) {
689 if (!roots.addRoot(ubi::Node(globals[i].get()), u"heap snapshot global")) {
690 return false;
691 }
692 }
693 return true;
694}
695
696// Choose roots and limits for a traversal, given `boundaries`. Set `roots` to
697// the set of nodes within the boundaries that are referred to by nodes
698// outside. If `boundaries` does not include all JS compartments, initialize
699// `compartments` to the set of included compartments; otherwise, leave
700// `compartments` uninitialized. (You can use compartments.initialized() to
701// check.)
702//
703// If `boundaries` is incoherent, or we encounter an error while trying to
704// handle it, or we run out of memory, set `rv` appropriately and return
705// `false`.
706//
707// Return value is a pair of the status and an AutoCheckCannotGC token,
708// forwarded from ubi::RootList::init(), to ensure that the caller does
709// not GC while the RootList is live and initialized.
710static std::pair<bool, AutoCheckCannotGC> EstablishBoundaries(
711 JSContext* cx, ErrorResult& rv, const HeapSnapshotBoundaries& boundaries,
712 ubi::RootList& roots, CompartmentSet& compartments) {
713 MOZ_ASSERT(!roots.initialized())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!roots.initialized())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!roots.initialized()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!roots.initialized()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 713); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!roots.initialized()"
")"); do { MOZ_CrashSequence(__null, 713); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
714 MOZ_ASSERT(compartments.empty())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(compartments.empty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(compartments.empty()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("compartments.empty()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 714); AnnotateMozCrashReason("MOZ_ASSERT" "(" "compartments.empty()"
")"); do { MOZ_CrashSequence(__null, 714); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
715
716 bool foundBoundaryProperty = false;
717
718 if (boundaries.mRuntime.WasPassed()) {
719 foundBoundaryProperty = true;
720
721 if (!boundaries.mRuntime.Value()) {
722 rv.Throw(NS_ERROR_INVALID_ARG);
723 return {false, AutoCheckCannotGC(cx)};
724 }
725
726 auto [ok, nogc] = roots.init();
727 if (!ok) {
728 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
729 return {false, nogc};
730 }
731 }
732
733 if (boundaries.mDebugger.WasPassed()) {
734 if (foundBoundaryProperty) {
735 rv.Throw(NS_ERROR_INVALID_ARG);
736 return {false, AutoCheckCannotGC(cx)};
737 }
738 foundBoundaryProperty = true;
739
740 JSObject* dbgObj = boundaries.mDebugger.Value();
741 if (!dbgObj || !dbg::IsDebugger(*dbgObj)) {
742 rv.Throw(NS_ERROR_INVALID_ARG);
743 return {false, AutoCheckCannotGC(cx)};
744 }
745
746 JS::RootedVector<JSObject*> globals(cx);
747 if (!dbg::GetDebuggeeGlobals(cx, *dbgObj, &globals) ||
748 !PopulateCompartmentsWithGlobals(compartments, globals) ||
749 !roots.init(compartments).first || !AddGlobalsAsRoots(globals, roots)) {
750 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
751 return {false, AutoCheckCannotGC(cx)};
752 }
753 }
754
755 if (boundaries.mGlobals.WasPassed()) {
756 if (foundBoundaryProperty) {
757 rv.Throw(NS_ERROR_INVALID_ARG);
758 return {false, AutoCheckCannotGC(cx)};
759 }
760 foundBoundaryProperty = true;
761
762 uint32_t length = boundaries.mGlobals.Value().Length();
763 if (length == 0) {
764 rv.Throw(NS_ERROR_INVALID_ARG);
765 return {false, AutoCheckCannotGC(cx)};
766 }
767
768 JS::RootedVector<JSObject*> globals(cx);
769 for (uint32_t i = 0; i < length; i++) {
770 JSObject* global = boundaries.mGlobals.Value().ElementAt(i);
771 if (!JS_IsGlobalObject(global)) {
772 rv.Throw(NS_ERROR_INVALID_ARG);
773 return {false, AutoCheckCannotGC(cx)};
774 }
775 if (!globals.append(global)) {
776 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
777 return {false, AutoCheckCannotGC(cx)};
778 }
779 }
780
781 if (!PopulateCompartmentsWithGlobals(compartments, globals) ||
782 !roots.init(compartments).first || !AddGlobalsAsRoots(globals, roots)) {
783 rv.Throw(NS_ERROR_OUT_OF_MEMORY);
784 return {false, AutoCheckCannotGC(cx)};
785 }
786 }
787 AutoCheckCannotGC nogc(cx);
788
789 if (!foundBoundaryProperty) {
790 rv.Throw(NS_ERROR_INVALID_ARG);
791 return {false, nogc};
792 }
793
794 MOZ_ASSERT(roots.initialized())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(roots.initialized())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(roots.initialized()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("roots.initialized()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 794); AnnotateMozCrashReason("MOZ_ASSERT" "(" "roots.initialized()"
")"); do { MOZ_CrashSequence(__null, 794); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
795 return {true, nogc};
796}
797
798// A variant covering all the various two-byte strings that we can get from the
799// ubi::Node API.
800class TwoByteString
801 : public Variant<JSAtom*, const char16_t*, JS::ubi::EdgeName> {
802 using Base = Variant<JSAtom*, const char16_t*, JS::ubi::EdgeName>;
803
804 struct CopyToBufferMatcher {
805 RangedPtr<char16_t> destination;
806 size_t maxLength;
807
808 CopyToBufferMatcher(RangedPtr<char16_t> destination, size_t maxLength)
809 : destination(destination), maxLength(maxLength) {}
810
811 size_t operator()(JS::ubi::EdgeName& ptr) {
812 return ptr ? operator()(ptr.get()) : 0;
813 }
814
815 size_t operator()(JSAtom* atom) {
816 MOZ_ASSERT(atom)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(atom)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(atom))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("atom", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 816); AnnotateMozCrashReason("MOZ_ASSERT" "(" "atom" ")"); do
{ MOZ_CrashSequence(__null, 816); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
817 JS::ubi::AtomOrTwoByteChars s(atom);
818 return s.copyToBuffer(destination, maxLength);
819 }
820
821 size_t operator()(const char16_t* chars) {
822 MOZ_ASSERT(chars)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(chars)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(chars))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("chars", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 822); AnnotateMozCrashReason("MOZ_ASSERT" "(" "chars" ")");
do { MOZ_CrashSequence(__null, 822); __attribute__((nomerge)
) ::abort(); } while (false); } } while (false)
;
823 JS::ubi::AtomOrTwoByteChars s(chars);
824 return s.copyToBuffer(destination, maxLength);
825 }
826 };
827
828 public:
829 // NOTE: The type requirement prevents this constructor to shadow default
830 // copy/move constructor, see
831 // https://clang.llvm.org/extra/clang-tidy/checks/bugprone/forwarding-reference-overload.html
832 template <typename T>
833 requires(std::is_constructible_v<Base, T>)
834 MOZ_IMPLICIT TwoByteString(T&& rhs) : Base(std::forward<T>(rhs)) {}
835
836 template <typename T>
837 TwoByteString& operator=(T&& rhs) {
838 MOZ_ASSERT(this != &rhs, "self-move disallowed")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(this != &rhs)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(this != &rhs))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("this != &rhs"
" (" "self-move disallowed" ")", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 838); AnnotateMozCrashReason("MOZ_ASSERT" "(" "this != &rhs"
") (" "self-move disallowed" ")"); do { MOZ_CrashSequence(__null
, 838); __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
;
839 this->~TwoByteString();
840 new (this) TwoByteString(std::forward<T>(rhs));
841 return *this;
842 }
843
844 TwoByteString(TwoByteString&&) = default;
845 TwoByteString& operator=(TwoByteString&&) = default;
846
847 TwoByteString(const TwoByteString&) = delete;
848 TwoByteString& operator=(const TwoByteString&) = delete;
849
850 // Rewrap the inner value of a JS::ubi::AtomOrTwoByteChars as a TwoByteString.
851 static TwoByteString from(JS::ubi::AtomOrTwoByteChars&& s) {
852 return s.match([](auto* a) { return TwoByteString(a); });
853 }
854
855 // Returns true if the given TwoByteString is non-null, false otherwise.
856 bool isNonNull() const {
857 return match([](auto& t) { return t != nullptr; });
858 }
859
860 // Return the length of the string, 0 if it is null.
861 size_t length() const {
862 return match(
863 [](JSAtom* atom) -> size_t {
864 MOZ_ASSERT(atom)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(atom)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(atom))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("atom", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 864); AnnotateMozCrashReason("MOZ_ASSERT" "(" "atom" ")"); do
{ MOZ_CrashSequence(__null, 864); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
865 JS::ubi::AtomOrTwoByteChars s(atom);
866 return s.length();
867 },
868 [](const char16_t* chars) -> size_t {
869 MOZ_ASSERT(chars)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(chars)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(chars))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("chars", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 869); AnnotateMozCrashReason("MOZ_ASSERT" "(" "chars" ")");
do { MOZ_CrashSequence(__null, 869); __attribute__((nomerge)
) ::abort(); } while (false); } } while (false)
;
870 return NS_strlen(chars);
871 },
872 [](const JS::ubi::EdgeName& ptr) -> size_t {
873 MOZ_ASSERT(ptr)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ptr)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(ptr))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("ptr", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 873); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ")"); do
{ MOZ_CrashSequence(__null, 873); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
874 return NS_strlen(ptr.get());
875 });
876 }
877
878 // Copy the contents of a TwoByteString into the provided buffer. The buffer
879 // is NOT null terminated. The number of characters written is returned.
880 size_t copyToBuffer(RangedPtr<char16_t> destination, size_t maxLength) {
881 CopyToBufferMatcher m(destination, maxLength);
882 return match(m);
883 }
884
885 struct HashPolicy;
886};
887
888// A hashing policy for TwoByteString.
889//
890// Atoms are pointer hashed and use pointer equality, which means that we
891// tolerate some duplication across atoms and the other two types of two-byte
892// strings. In practice, we expect the amount of this duplication to be very low
893// because each type is generally a different semantic thing in addition to
894// having a slightly different representation. For example, the set of edge
895// names and the set stack frames' source names naturally tend not to overlap
896// very much if at all.
897struct TwoByteString::HashPolicy {
898 using Lookup = TwoByteString;
899
900 static js::HashNumber hash(const Lookup& l) {
901 return l.match(
902 [](const JSAtom* atom) {
903 return js::DefaultHasher<const JSAtom*>::hash(atom);
904 },
905 [](const char16_t* chars) {
906 MOZ_ASSERT(chars)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(chars)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(chars))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("chars", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 906); AnnotateMozCrashReason("MOZ_ASSERT" "(" "chars" ")");
do { MOZ_CrashSequence(__null, 906); __attribute__((nomerge)
) ::abort(); } while (false); } } while (false)
;
907 auto length = NS_strlen(chars);
908 return HashString(chars, length);
909 },
910 [](const JS::ubi::EdgeName& ptr) {
911 const char16_t* chars = ptr.get();
912 MOZ_ASSERT(chars)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(chars)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(chars))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("chars", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 912); AnnotateMozCrashReason("MOZ_ASSERT" "(" "chars" ")");
do { MOZ_CrashSequence(__null, 912); __attribute__((nomerge)
) ::abort(); } while (false); } } while (false)
;
913 auto length = NS_strlen(chars);
914 return HashString(chars, length);
915 });
916 }
917
918 struct EqualityMatcher {
919 const TwoByteString& rhs;
920 explicit EqualityMatcher(const TwoByteString& rhs) : rhs(rhs) {}
921
922 bool operator()(const JSAtom* atom) {
923 return rhs.is<JSAtom*>() && rhs.as<JSAtom*>() == atom;
924 }
925
926 bool operator()(const char16_t* chars) {
927 MOZ_ASSERT(chars)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(chars)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(chars))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("chars", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 927); AnnotateMozCrashReason("MOZ_ASSERT" "(" "chars" ")");
do { MOZ_CrashSequence(__null, 927); __attribute__((nomerge)
) ::abort(); } while (false); } } while (false)
;
928
929 const char16_t* rhsChars = nullptr;
930 if (rhs.is<const char16_t*>())
931 rhsChars = rhs.as<const char16_t*>();
932 else if (rhs.is<JS::ubi::EdgeName>())
933 rhsChars = rhs.as<JS::ubi::EdgeName>().get();
934 else
935 return false;
936 MOZ_ASSERT(rhsChars)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(rhsChars)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(rhsChars))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("rhsChars", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 936); AnnotateMozCrashReason("MOZ_ASSERT" "(" "rhsChars" ")"
); do { MOZ_CrashSequence(__null, 936); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
937
938 auto length = NS_strlen(chars);
939 if (NS_strlen(rhsChars) != length) return false;
940
941 return memcmp(chars, rhsChars, length * sizeof(char16_t)) == 0;
942 }
943
944 bool operator()(const JS::ubi::EdgeName& ptr) {
945 MOZ_ASSERT(ptr)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ptr)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(ptr))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("ptr", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 945); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ")"); do
{ MOZ_CrashSequence(__null, 945); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
946 return operator()(ptr.get());
947 }
948 };
949
950 static bool match(const TwoByteString& k, const Lookup& l) {
951 EqualityMatcher eq(l);
952 return k.match(eq);
953 }
954
955 static void rekey(TwoByteString& k, TwoByteString&& newKey) {
956 k = std::move(newKey);
957 }
958};
959
960// Returns whether `edge` should be included in a heap snapshot of
961// `compartments`. The optional `policy` out-param is set to INCLUDE_EDGES
962// if we want to include the referent's edges, or EXCLUDE_EDGES if we don't
963// want to include them.
964static bool ShouldIncludeEdge(JS::CompartmentSet* compartments,
965 const ubi::Node& origin, const ubi::Edge& edge,
966 CoreDumpWriter::EdgePolicy* policy = nullptr) {
967 if (policy) {
968 *policy = CoreDumpWriter::INCLUDE_EDGES;
969 }
970
971 if (!compartments) {
972 // We aren't targeting a particular set of compartments, so serialize all
973 // the things!
974 return true;
975 }
976
977 // We are targeting a particular set of compartments. If this node is in our
978 // target set, serialize it and all of its edges. If this node is _not_ in our
979 // target set, we also serialize under the assumption that it is a shared
980 // resource being used by something in our target compartments since we
981 // reached it by traversing the heap graph. However, we do not serialize its
982 // outgoing edges and we abandon further traversal from this node.
983 //
984 // If the node does not belong to any compartment, we also serialize its
985 // outgoing edges. This case is relevant for Shapes: they don't belong to a
986 // specific compartment and contain edges to parent/kids Shapes we want to
987 // include. Note that these Shapes may contain pointers into our target
988 // compartment (the Shape's getter/setter JSObjects). However, we do not
989 // serialize nodes in other compartments that are reachable from these
990 // non-compartment nodes.
991
992 JS::Compartment* compartment = edge.referent.compartment();
993
994 if (!compartment || compartments->has(compartment)) {
995 return true;
996 }
997
998 if (policy) {
999 *policy = CoreDumpWriter::EXCLUDE_EDGES;
1000 }
1001
1002 return !!origin.compartment();
1003}
1004
1005// A `CoreDumpWriter` that serializes nodes to protobufs and writes them to the
1006// given `ZeroCopyOutputStream`.
1007class MOZ_STACK_CLASS StreamWriter : public CoreDumpWriter {
1008 using FrameSet = js::HashSet<uint64_t>;
1009 using TwoByteStringMap =
1010 js::HashMap<TwoByteString, uint64_t, TwoByteString::HashPolicy>;
1011 using OneByteStringMap = js::HashMap<const char*, uint64_t>;
1012
1013 JSContext* cx;
1014 bool wantNames;
1015 // The set of |JS::ubi::StackFrame::identifier()|s that have already been
1016 // serialized and written to the core dump.
1017 FrameSet framesAlreadySerialized;
1018 // The set of two-byte strings that have already been serialized and written
1019 // to the core dump.
1020 TwoByteStringMap twoByteStringsAlreadySerialized;
1021 // The set of one-byte strings that have already been serialized and written
1022 // to the core dump.
1023 OneByteStringMap oneByteStringsAlreadySerialized;
1024
1025 ::google::protobuf::io::ZeroCopyOutputStream& stream;
1026
1027 JS::CompartmentSet* compartments;
1028
1029 bool writeMessage(const ::google::protobuf::MessageLite& message) {
1030 // We have to create a new CodedOutputStream when writing each message so
1031 // that the 64MB size limit used by Coded{Output,Input}Stream to prevent
1032 // integer overflow is enforced per message rather than on the whole stream.
1033 ::google::protobuf::io::CodedOutputStream codedStream(&stream);
1034 codedStream.WriteVarint32(message.ByteSizeLong());
1035 message.SerializeWithCachedSizes(&codedStream);
1036 return !codedStream.HadError();
1037 }
1038
1039 // Attach the full two-byte string or a reference to a two-byte string that
1040 // has already been serialized to a protobuf message.
1041 template <typename SetStringFunction, typename SetRefFunction>
1042 bool attachTwoByteString(TwoByteString& string, SetStringFunction setString,
1043 SetRefFunction setRef) {
1044 auto ptr = twoByteStringsAlreadySerialized.lookupForAdd(string);
1045 if (ptr) {
1046 setRef(ptr->value());
1047 return true;
1048 }
1049
1050 auto length = string.length();
1051 auto stringData = MakeUnique<std::string>(length * sizeof(char16_t), '\0');
1052 if (!stringData) return false;
1053
1054 auto buf = const_cast<char16_t*>(
1055 reinterpret_cast<const char16_t*>(stringData->data()));
1056 string.copyToBuffer(RangedPtr<char16_t>(buf, length), length);
1057
1058 uint64_t ref = twoByteStringsAlreadySerialized.count();
1059 if (!twoByteStringsAlreadySerialized.add(ptr, std::move(string), ref))
1060 return false;
1061
1062 setString(stringData.release());
1063 return true;
1064 }
1065
1066 // Attach the full one-byte string or a reference to a one-byte string that
1067 // has already been serialized to a protobuf message.
1068 template <typename SetStringFunction, typename SetRefFunction>
1069 bool attachOneByteString(const char* string, SetStringFunction setString,
1070 SetRefFunction setRef) {
1071 auto ptr = oneByteStringsAlreadySerialized.lookupForAdd(string);
1072 if (ptr) {
1073 setRef(ptr->value());
1074 return true;
1075 }
1076
1077 auto length = strlen(string);
1078 auto stringData = MakeUnique<std::string>(string, length);
1079 if (!stringData) return false;
1080
1081 uint64_t ref = oneByteStringsAlreadySerialized.count();
1082 if (!oneByteStringsAlreadySerialized.add(ptr, string, ref)) return false;
1083
1084 setString(stringData.release());
1085 return true;
1086 }
1087
1088 protobuf::StackFrame* getProtobufStackFrame(JS::ubi::StackFrame& frame,
1089 size_t depth = 1) {
1090 // NB: de-duplicated string properties must be written in the same order
1091 // here as they are read in `HeapSnapshot::saveStackFrame` or else indices
1092 // in references to already serialized strings will be off.
1093
1094 MOZ_ASSERT(frame,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(frame)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(frame))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("frame" " (" "null frames should be represented as the lack of a serialized "
"stack frame" ")", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1096); AnnotateMozCrashReason("MOZ_ASSERT" "(" "frame" ") ("
"null frames should be represented as the lack of a serialized "
"stack frame" ")"); do { MOZ_CrashSequence(__null, 1096); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
1095 "null frames should be represented as the lack of a serialized "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(frame)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(frame))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("frame" " (" "null frames should be represented as the lack of a serialized "
"stack frame" ")", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1096); AnnotateMozCrashReason("MOZ_ASSERT" "(" "frame" ") ("
"null frames should be represented as the lack of a serialized "
"stack frame" ")"); do { MOZ_CrashSequence(__null, 1096); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
1096 "stack frame")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(frame)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(frame))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("frame" " (" "null frames should be represented as the lack of a serialized "
"stack frame" ")", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1096); AnnotateMozCrashReason("MOZ_ASSERT" "(" "frame" ") ("
"null frames should be represented as the lack of a serialized "
"stack frame" ")"); do { MOZ_CrashSequence(__null, 1096); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
1097
1098 auto id = frame.identifier();
1099 auto protobufStackFrame = MakeUnique<protobuf::StackFrame>();
1100 if (!protobufStackFrame) return nullptr;
1101
1102 if (framesAlreadySerialized.has(id)) {
1103 protobufStackFrame->set_ref(id);
1104 return protobufStackFrame.release();
1105 }
1106
1107 auto data = MakeUnique<protobuf::StackFrame_Data>();
1108 if (!data) return nullptr;
1109
1110 data->set_id(id);
1111 data->set_line(frame.line());
1112 data->set_column(frame.column().oneOriginValue());
1113 data->set_issystem(frame.isSystem());
1114 data->set_isselfhosted(frame.isSelfHosted(cx));
1115
1116 auto dupeSource = TwoByteString::from(frame.source());
1117 if (!attachTwoByteString(
1118 dupeSource,
1119 [&](std::string* source) { data->set_allocated_source(source); },
1120 [&](uint64_t ref) { data->set_sourceref(ref); })) {
1121 return nullptr;
1122 }
1123
1124 auto dupeName = TwoByteString::from(frame.functionDisplayName());
1125 if (dupeName.isNonNull()) {
1126 if (!attachTwoByteString(
1127 dupeName,
1128 [&](std::string* name) {
1129 data->set_allocated_functiondisplayname(name);
1130 },
1131 [&](uint64_t ref) { data->set_functiondisplaynameref(ref); })) {
1132 return nullptr;
1133 }
1134 }
1135
1136 auto parent = frame.parent();
1137 if (parent && depth < HeapSnapshot::MAX_STACK_DEPTH) {
1138 auto protobufParent = getProtobufStackFrame(parent, depth + 1);
1139 if (!protobufParent) return nullptr;
1140 data->set_allocated_parent(protobufParent);
1141 }
1142
1143 protobufStackFrame->set_allocated_data(data.release());
1144
1145 if (!framesAlreadySerialized.put(id)) return nullptr;
1146
1147 return protobufStackFrame.release();
1148 }
1149
1150 public:
1151 StreamWriter(JSContext* cx,
1152 ::google::protobuf::io::ZeroCopyOutputStream& stream,
1153 bool wantNames, JS::CompartmentSet* compartments)
1154 : cx(cx),
1155 wantNames(wantNames),
1156 framesAlreadySerialized(cx),
1157 twoByteStringsAlreadySerialized(cx),
1158 oneByteStringsAlreadySerialized(cx),
1159 stream(stream),
1160 compartments(compartments) {}
1161
1162 ~StreamWriter() override = default;
1163
1164 bool writeMetadata(uint64_t timestamp) final {
1165 protobuf::Metadata metadata;
1166 metadata.set_timestamp(timestamp);
1167 return writeMessage(metadata);
1168 }
1169
1170 bool writeNode(const JS::ubi::Node& ubiNode, EdgePolicy includeEdges) final {
1171 // NB: de-duplicated string properties must be written in the same order
1172 // here as they are read in `HeapSnapshot::saveNode` or else indices in
1173 // references to already serialized strings will be off.
1174
1175 protobuf::Node protobufNode;
1176 protobufNode.set_id(ubiNode.identifier());
1177
1178 protobufNode.set_coarsetype(
1179 JS::ubi::CoarseTypeToUint32(ubiNode.coarseType()));
1180
1181 auto typeName = TwoByteString(ubiNode.typeName());
1182 if (NS_WARN_IF(!attachTwoByteString(NS_warn_if_impl(!attachTwoByteString( typeName, [&](std::
string* name) { protobufNode.set_allocated_typename_(name); }
, [&](uint64_t ref) { protobufNode.set_typenameref(ref); }
), "!attachTwoByteString( typeName, [&](std::string* name) { protobufNode.set_allocated_typename_(name); }, [&](uint64_t ref) { protobufNode.set_typenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1187)
1183 typeName,NS_warn_if_impl(!attachTwoByteString( typeName, [&](std::
string* name) { protobufNode.set_allocated_typename_(name); }
, [&](uint64_t ref) { protobufNode.set_typenameref(ref); }
), "!attachTwoByteString( typeName, [&](std::string* name) { protobufNode.set_allocated_typename_(name); }, [&](uint64_t ref) { protobufNode.set_typenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1187)
1184 [&](std::string* name) {NS_warn_if_impl(!attachTwoByteString( typeName, [&](std::
string* name) { protobufNode.set_allocated_typename_(name); }
, [&](uint64_t ref) { protobufNode.set_typenameref(ref); }
), "!attachTwoByteString( typeName, [&](std::string* name) { protobufNode.set_allocated_typename_(name); }, [&](uint64_t ref) { protobufNode.set_typenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1187)
1185 protobufNode.set_allocated_typename_(name);NS_warn_if_impl(!attachTwoByteString( typeName, [&](std::
string* name) { protobufNode.set_allocated_typename_(name); }
, [&](uint64_t ref) { protobufNode.set_typenameref(ref); }
), "!attachTwoByteString( typeName, [&](std::string* name) { protobufNode.set_allocated_typename_(name); }, [&](uint64_t ref) { protobufNode.set_typenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1187)
1186 },NS_warn_if_impl(!attachTwoByteString( typeName, [&](std::
string* name) { protobufNode.set_allocated_typename_(name); }
, [&](uint64_t ref) { protobufNode.set_typenameref(ref); }
), "!attachTwoByteString( typeName, [&](std::string* name) { protobufNode.set_allocated_typename_(name); }, [&](uint64_t ref) { protobufNode.set_typenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1187)
1187 [&](uint64_t ref) { protobufNode.set_typenameref(ref); }))NS_warn_if_impl(!attachTwoByteString( typeName, [&](std::
string* name) { protobufNode.set_allocated_typename_(name); }
, [&](uint64_t ref) { protobufNode.set_typenameref(ref); }
), "!attachTwoByteString( typeName, [&](std::string* name) { protobufNode.set_allocated_typename_(name); }, [&](uint64_t ref) { protobufNode.set_typenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1187)
) {
1188 return false;
1189 }
1190
1191 mozilla::MallocSizeOf mallocSizeOf = dbg::GetDebuggerMallocSizeOf(cx);
1192 MOZ_ASSERT(mallocSizeOf)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mallocSizeOf)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mallocSizeOf))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("mallocSizeOf", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1192); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mallocSizeOf"
")"); do { MOZ_CrashSequence(__null, 1192); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1193 protobufNode.set_size(ubiNode.size(mallocSizeOf));
1194
1195 if (includeEdges) {
1196 auto edges = ubiNode.edges(cx, wantNames);
1197 if (NS_WARN_IF(!edges)NS_warn_if_impl(!edges, "!edges", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1197)
) return false;
1198
1199 for (; !edges->empty(); edges->popFront()) {
1200 ubi::Edge& ubiEdge = edges->front();
1201 if (!ShouldIncludeEdge(compartments, ubiNode, ubiEdge)) {
1202 continue;
1203 }
1204
1205 protobuf::Edge* protobufEdge = protobufNode.add_edges();
1206 if (NS_WARN_IF(!protobufEdge)NS_warn_if_impl(!protobufEdge, "!protobufEdge", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1206)
) {
1207 return false;
1208 }
1209
1210 protobufEdge->set_referent(ubiEdge.referent.identifier());
1211
1212 if (wantNames && ubiEdge.name) {
1213 TwoByteString edgeName(std::move(ubiEdge.name));
1214 if (NS_WARN_IF(!attachTwoByteString(NS_warn_if_impl(!attachTwoByteString( edgeName, [&](std::
string* name) { protobufEdge->set_allocated_name(name); },
[&](uint64_t ref) { protobufEdge->set_nameref(ref); }
), "!attachTwoByteString( edgeName, [&](std::string* name) { protobufEdge->set_allocated_name(name); }, [&](uint64_t ref) { protobufEdge->set_nameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1219)
1215 edgeName,NS_warn_if_impl(!attachTwoByteString( edgeName, [&](std::
string* name) { protobufEdge->set_allocated_name(name); },
[&](uint64_t ref) { protobufEdge->set_nameref(ref); }
), "!attachTwoByteString( edgeName, [&](std::string* name) { protobufEdge->set_allocated_name(name); }, [&](uint64_t ref) { protobufEdge->set_nameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1219)
1216 [&](std::string* name) {NS_warn_if_impl(!attachTwoByteString( edgeName, [&](std::
string* name) { protobufEdge->set_allocated_name(name); },
[&](uint64_t ref) { protobufEdge->set_nameref(ref); }
), "!attachTwoByteString( edgeName, [&](std::string* name) { protobufEdge->set_allocated_name(name); }, [&](uint64_t ref) { protobufEdge->set_nameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1219)
1217 protobufEdge->set_allocated_name(name);NS_warn_if_impl(!attachTwoByteString( edgeName, [&](std::
string* name) { protobufEdge->set_allocated_name(name); },
[&](uint64_t ref) { protobufEdge->set_nameref(ref); }
), "!attachTwoByteString( edgeName, [&](std::string* name) { protobufEdge->set_allocated_name(name); }, [&](uint64_t ref) { protobufEdge->set_nameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1219)
1218 },NS_warn_if_impl(!attachTwoByteString( edgeName, [&](std::
string* name) { protobufEdge->set_allocated_name(name); },
[&](uint64_t ref) { protobufEdge->set_nameref(ref); }
), "!attachTwoByteString( edgeName, [&](std::string* name) { protobufEdge->set_allocated_name(name); }, [&](uint64_t ref) { protobufEdge->set_nameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1219)
1219 [&](uint64_t ref) { protobufEdge->set_nameref(ref); }))NS_warn_if_impl(!attachTwoByteString( edgeName, [&](std::
string* name) { protobufEdge->set_allocated_name(name); },
[&](uint64_t ref) { protobufEdge->set_nameref(ref); }
), "!attachTwoByteString( edgeName, [&](std::string* name) { protobufEdge->set_allocated_name(name); }, [&](uint64_t ref) { protobufEdge->set_nameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1219)
) {
1220 return false;
1221 }
1222 }
1223 }
1224 }
1225
1226 if (ubiNode.hasAllocationStack()) {
1227 auto ubiStackFrame = ubiNode.allocationStack();
1228 auto protoStackFrame = getProtobufStackFrame(ubiStackFrame);
1229 if (NS_WARN_IF(!protoStackFrame)NS_warn_if_impl(!protoStackFrame, "!protoStackFrame", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1229)
) return false;
1230 protobufNode.set_allocated_allocationstack(protoStackFrame);
1231 }
1232
1233 if (auto className = ubiNode.jsObjectClassName()) {
1234 if (NS_WARN_IF(!attachOneByteString(NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
1235 className,NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
1236 [&](std::string* name) {NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
1237 protobufNode.set_allocated_jsobjectclassname(name);NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
1238 },NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
1239 [&](uint64_t ref) {NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
1240 protobufNode.set_jsobjectclassnameref(ref);NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
1241 }))NS_warn_if_impl(!attachOneByteString( className, [&](std::
string* name) { protobufNode.set_allocated_jsobjectclassname(
name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref
(ref); }), "!attachOneByteString( className, [&](std::string* name) { protobufNode.set_allocated_jsobjectclassname(name); }, [&](uint64_t ref) { protobufNode.set_jsobjectclassnameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1241)
) {
1242 return false;
1243 }
1244 }
1245
1246 if (auto scriptFilename = ubiNode.scriptFilename()) {
1247 if (NS_WARN_IF(!attachOneByteString(NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
1248 scriptFilename,NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
1249 [&](std::string* name) {NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
1250 protobufNode.set_allocated_scriptfilename(name);NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
1251 },NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
1252 [&](uint64_t ref) {NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
1253 protobufNode.set_scriptfilenameref(ref);NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
1254 }))NS_warn_if_impl(!attachOneByteString( scriptFilename, [&]
(std::string* name) { protobufNode.set_allocated_scriptfilename
(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref
(ref); }), "!attachOneByteString( scriptFilename, [&](std::string* name) { protobufNode.set_allocated_scriptfilename(name); }, [&](uint64_t ref) { protobufNode.set_scriptfilenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1254)
) {
1255 return false;
1256 }
1257 }
1258
1259 if (ubiNode.descriptiveTypeName()) {
1260 auto descriptiveTypeName = TwoByteString(ubiNode.descriptiveTypeName());
1261 if (NS_WARN_IF(!attachTwoByteString(NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
1262 descriptiveTypeName,NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
1263 [&](std::string* name) {NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
1264 protobufNode.set_allocated_descriptivetypename(name);NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
1265 },NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
1266 [&](uint64_t ref) {NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
1267 protobufNode.set_descriptivetypenameref(ref);NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
1268 }))NS_warn_if_impl(!attachTwoByteString( descriptiveTypeName, [&
](std::string* name) { protobufNode.set_allocated_descriptivetypename
(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref
(ref); }), "!attachTwoByteString( descriptiveTypeName, [&](std::string* name) { protobufNode.set_allocated_descriptivetypename(name); }, [&](uint64_t ref) { protobufNode.set_descriptivetypenameref(ref); })"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1268)
) {
1269 return false;
1270 }
1271 }
1272
1273 return writeMessage(protobufNode);
1274 }
1275};
1276
1277// A JS::ubi::BreadthFirst handler that serializes a snapshot of the heap into a
1278// core dump.
1279class MOZ_STACK_CLASS HeapSnapshotHandler {
1280 CoreDumpWriter& writer;
1281 JS::CompartmentSet* compartments;
1282
1283 public:
1284 // For telemetry.
1285 uint32_t nodeCount;
1286 uint32_t edgeCount;
1287
1288 HeapSnapshotHandler(CoreDumpWriter& writer, JS::CompartmentSet* compartments)
1289 : writer(writer),
1290 compartments(compartments),
1291 nodeCount(0),
1292 edgeCount(0) {}
1293
1294 // JS::ubi::BreadthFirst handler interface.
1295
1296 class NodeData {};
1297 typedef JS::ubi::BreadthFirst<HeapSnapshotHandler> Traversal;
1298 bool operator()(Traversal& traversal, JS::ubi::Node origin,
1299 const JS::ubi::Edge& edge, NodeData*, bool first) {
1300 edgeCount++;
1301
1302 // We're only interested in the first time we reach edge.referent, not in
1303 // every edge arriving at that node. "But, don't we want to serialize every
1304 // edge in the heap graph?" you ask. Don't worry! This edge is still
1305 // serialized into the core dump. Serializing a node also serializes each of
1306 // its edges, and if we are traversing a given edge, we must have already
1307 // visited and serialized the origin node and its edges.
1308 if (!first) return true;
1309
1310 CoreDumpWriter::EdgePolicy policy;
1311 if (!ShouldIncludeEdge(compartments, origin, edge, &policy)) {
1312 // Because ShouldIncludeEdge considers the |origin| node as well, we don't
1313 // want to consider this node 'visited' until we write it to the core
1314 // dump.
1315 traversal.doNotMarkReferentAsVisited();
1316 return true;
1317 }
1318
1319 nodeCount++;
1320
1321 if (policy == CoreDumpWriter::EXCLUDE_EDGES) traversal.abandonReferent();
1322
1323 return writer.writeNode(edge.referent, policy);
1324 }
1325};
1326
1327bool WriteHeapGraph(JSContext* cx, const JS::ubi::Node& node,
1328 CoreDumpWriter& writer, bool wantNames,
1329 JS::CompartmentSet* compartments,
1330 JS::AutoCheckCannotGC& noGC, uint32_t& outNodeCount,
1331 uint32_t& outEdgeCount) {
1332 // Serialize the starting node to the core dump.
1333
1334 if (NS_WARN_IF(!writer.writeNode(node, CoreDumpWriter::INCLUDE_EDGES))NS_warn_if_impl(!writer.writeNode(node, CoreDumpWriter::INCLUDE_EDGES
), "!writer.writeNode(node, CoreDumpWriter::INCLUDE_EDGES)", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1334)
) {
1335 return false;
1336 }
1337
1338 // Walk the heap graph starting from the given node and serialize it into the
1339 // core dump.
1340
1341 HeapSnapshotHandler handler(writer, compartments);
1342 HeapSnapshotHandler::Traversal traversal(cx, handler, noGC);
1343 traversal.wantNames = wantNames;
1344
1345 bool ok = traversal.addStartVisited(node) && traversal.traverse();
1346
1347 if (ok) {
1348 outNodeCount = handler.nodeCount;
1349 outEdgeCount = handler.edgeCount;
1350 }
1351
1352 return ok;
1353}
1354
1355static unsigned long msSinceProcessCreation(const TimeStamp& now) {
1356 auto duration = now - TimeStamp::ProcessCreation();
1357 return (unsigned long)duration.ToMilliseconds();
1358}
1359
1360/* static */
1361already_AddRefed<nsIFile> HeapSnapshot::CreateUniqueCoreDumpFile(
1362 ErrorResult& rv, const TimeStamp& now, nsAString& outFilePath,
1363 nsAString& outSnapshotId) {
1364 MOZ_RELEASE_ASSERT(XRE_IsParentProcess())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(XRE_IsParentProcess())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(XRE_IsParentProcess()))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("XRE_IsParentProcess()"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1364); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "XRE_IsParentProcess()"
")"); do { MOZ_CrashSequence(__null, 1364); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1365 nsCOMPtr<nsIFile> file;
1366 rv = GetSpecialSystemDirectory(OS_TemporaryDirectory, getter_AddRefs(file));
1367 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1367)
) return nullptr;
1368
1369 nsAutoString tempPath;
1370 rv = file->GetPath(tempPath);
1371 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1371)
) return nullptr;
1372
1373 auto ms = msSinceProcessCreation(now);
1374 rv = file->AppendNative(nsPrintfCString("%lu.fxsnapshot", ms));
1375 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1375)
) return nullptr;
1376
1377 rv = file->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0666);
1378 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1378)
) return nullptr;
1379
1380 rv = file->GetPath(outFilePath);
1381 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1381)
) return nullptr;
1382
1383 // The snapshot ID must be computed in the process that created the
1384 // temp file, because TmpD may not be the same in all processes.
1385 outSnapshotId.Assign(Substring(
1386 outFilePath, tempPath.Length() + 1,
1387 outFilePath.Length() - tempPath.Length() - sizeof(".fxsnapshot")));
1388
1389 return file.forget();
1390}
1391
1392// Deletion policy for cleaning up PHeapSnapshotTempFileHelperChild pointers.
1393class DeleteHeapSnapshotTempFileHelperChild {
1394 public:
1395 constexpr DeleteHeapSnapshotTempFileHelperChild() = default;
1396
1397 void operator()(PHeapSnapshotTempFileHelperChild* ptr) const {
1398 (void)NS_WARN_IF(!HeapSnapshotTempFileHelperChild::Send__delete__(ptr))NS_warn_if_impl(!HeapSnapshotTempFileHelperChild::Send__delete__
(ptr), "!HeapSnapshotTempFileHelperChild::Send__delete__(ptr)"
, "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1398)
;
1399 }
1400};
1401
1402// A UniquePtr alias to automatically manage PHeapSnapshotTempFileHelperChild
1403// pointers.
1404using UniqueHeapSnapshotTempFileHelperChild =
1405 UniquePtr<PHeapSnapshotTempFileHelperChild,
1406 DeleteHeapSnapshotTempFileHelperChild>;
1407
1408// Get an nsIOutputStream that we can write the heap snapshot to. In non-e10s
1409// and in the e10s parent process, open a file directly and create an output
1410// stream for it. In e10s child processes, we are sandboxed without access to
1411// the filesystem. Use IPDL to request a file descriptor from the parent
1412// process.
1413static already_AddRefed<nsIOutputStream> getCoreDumpOutputStream(
1414 ErrorResult& rv, TimeStamp& start, nsAString& outFilePath,
1415 nsAString& outSnapshotId) {
1416 if (XRE_IsParentProcess()) {
1417 // Create the file and open the output stream directly.
1418
1419 nsCOMPtr<nsIFile> file = HeapSnapshot::CreateUniqueCoreDumpFile(
1420 rv, start, outFilePath, outSnapshotId);
1421 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1421)
) return nullptr;
1422
1423 nsCOMPtr<nsIOutputStream> outputStream;
1424 rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), file,
1425 PR_WRONLY0x02, -1, 0);
1426 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1426)
) return nullptr;
1427
1428 return outputStream.forget();
1429 }
1430 // Request a file descriptor from the parent process over IPDL.
1431
1432 auto cc = ContentChild::GetSingleton();
1433 if (!cc) {
1434 rv.Throw(NS_ERROR_UNEXPECTED);
1435 return nullptr;
1436 }
1437
1438 UniqueHeapSnapshotTempFileHelperChild helper(
1439 cc->SendPHeapSnapshotTempFileHelperConstructor());
1440 if (NS_WARN_IF(!helper)NS_warn_if_impl(!helper, "!helper", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1440)
) {
1441 rv.Throw(NS_ERROR_UNEXPECTED);
1442 return nullptr;
1443 }
1444
1445 OpenHeapSnapshotTempFileResponse response;
1446 if (!helper->SendOpenHeapSnapshotTempFile(&response)) {
1447 rv.Throw(NS_ERROR_UNEXPECTED);
1448 return nullptr;
1449 }
1450 if (response.type() == OpenHeapSnapshotTempFileResponse::Tnsresult) {
1451 rv.Throw(response.get_nsresult());
1452 return nullptr;
1453 }
1454
1455 auto opened = response.get_OpenedFile();
1456 outFilePath = opened.path();
1457 outSnapshotId = opened.snapshotId();
1458 nsCOMPtr<nsIOutputStream> outputStream =
1459 FileDescriptorOutputStream::Create(opened.descriptor());
1460 if (NS_WARN_IF(!outputStream)NS_warn_if_impl(!outputStream, "!outputStream", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1460)
) {
1461 rv.Throw(NS_ERROR_UNEXPECTED);
1462 return nullptr;
1463 }
1464
1465 return outputStream.forget();
1466}
1467
1468} // namespace devtools
1469
1470namespace dom {
1471
1472using namespace JS;
1473using namespace devtools;
1474
1475/* static */
1476void ChromeUtils::SaveHeapSnapshotShared(
1477 GlobalObject& global, const HeapSnapshotBoundaries& boundaries,
1478 nsAString& outFilePath, nsAString& outSnapshotId, ErrorResult& rv) {
1479 auto start = TimeStamp::Now();
1480
1481 bool wantNames = true;
1482 CompartmentSet compartments;
1483 uint32_t nodeCount = 0;
1484 uint32_t edgeCount = 0;
1485
1486 nsCOMPtr<nsIOutputStream> outputStream =
1487 getCoreDumpOutputStream(rv, start, outFilePath, outSnapshotId);
1488 if (NS_WARN_IF(rv.Failed())NS_warn_if_impl(rv.Failed(), "rv.Failed()", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.cpp"
, 1488)
) return;
1489
1490 ZeroCopyNSIOutputStream zeroCopyStream(outputStream);
1491 ::google::protobuf::io::GzipOutputStream gzipStream(&zeroCopyStream);
1492
1493 JSContext* cx = global.Context();
1494
1495 {
1496 ubi::RootList rootList(cx, wantNames);
1497 auto [ok, nogc] =
1498 EstablishBoundaries(cx, rv, boundaries, rootList, compartments);
1499 if (!ok) {
1500 return;
1501 }
1502
1503 StreamWriter writer(cx, gzipStream, wantNames,
1504 !compartments.empty() ? &compartments : nullptr);
1505
1506 ubi::Node roots(&rootList);
1507
1508 // Serialize the initial heap snapshot metadata to the core dump.
1509 if (!writer.writeMetadata(PR_Now()) ||
1510 // Serialize the heap graph to the core dump, starting from our list of
1511 // roots.
1512 !WriteHeapGraph(cx, roots, writer, wantNames,
1513 !compartments.empty() ? &compartments : nullptr, nogc,
1514 nodeCount, edgeCount)) {
1515 rv.Throw(zeroCopyStream.failed() ? zeroCopyStream.result()
1516 : NS_ERROR_UNEXPECTED);
1517 return;
1518 }
1519 }
1520
1521 glean::devtools::save_heap_snapshot.AccumulateRawDuration(TimeStamp::Now() -
1522 start);
1523 glean::devtools::heap_snapshot_node_count.AccumulateSingleSample(nodeCount);
1524 glean::devtools::heap_snapshot_edge_count.AccumulateSingleSample(edgeCount);
1525}
1526
1527/* static */
1528uint64_t ChromeUtils::GetObjectNodeId(GlobalObject& global,
1529 JS::Handle<JSObject*> val) {
1530 JS::Rooted<JSObject*> obj(global.Context(), val);
1531
1532 JS::ubi::Node node(obj);
1533 return node.identifier();
1534}
1535
1536/* static */
1537void ChromeUtils::SaveHeapSnapshot(GlobalObject& global,
1538 const HeapSnapshotBoundaries& boundaries,
1539 nsAString& outFilePath, ErrorResult& rv) {
1540 nsAutoString snapshotId;
1541 SaveHeapSnapshotShared(global, boundaries, outFilePath, snapshotId, rv);
1542}
1543
1544/* static */
1545void ChromeUtils::SaveHeapSnapshotGetId(
1546 GlobalObject& global, const HeapSnapshotBoundaries& boundaries,
1547 nsAString& outSnapshotId, ErrorResult& rv) {
1548 nsAutoString filePath;
1549 SaveHeapSnapshotShared(global, boundaries, filePath, outSnapshotId, rv);
1550}
1551
1552/* static */
1553already_AddRefed<HeapSnapshot> ChromeUtils::ReadHeapSnapshot(
1554 GlobalObject& global, const nsAString& filePath, ErrorResult& rv) {
1555 auto start = TimeStamp::Now();
1556
1557 nsCOMPtr<nsIFile> snapshotFile;
1558 rv = NS_NewLocalFile(filePath, getter_AddRefs(snapshotFile));
1559 if (rv.Failed()) {
1560 return nullptr;
1561 }
1562
1563 AutoMemMap mm;
1564 rv = mm.init(snapshotFile);
1565 if (rv.Failed()) return nullptr;
1566
1567 RefPtr<HeapSnapshot> snapshot = HeapSnapshot::Create(
1568 global.Context(), global, reinterpret_cast<const uint8_t*>(mm.address()),
1569 mm.size(), rv);
1570
1571 if (!rv.Failed())
1572 glean::devtools::read_heap_snapshot.AccumulateRawDuration(TimeStamp::Now() -
1573 start);
1574
1575 return snapshot.forget();
1576}
1577
1578} // namespace dom
1579} // namespace mozilla

/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.h

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5#ifndef mozilla_devtools_HeapSnapshot_
6#define mozilla_devtools_HeapSnapshot_
7
8#include "js/HashTable.h"
9#include "mozilla/devtools/DeserializedNode.h"
10#include "mozilla/dom/BindingDeclarations.h"
11#include "mozilla/dom/Nullable.h"
12#include "mozilla/Maybe.h"
13#include "mozilla/TimeStamp.h"
14#include "mozilla/UniquePtrExtensions.h"
15
16#include "CoreDump.pb.h"
17#include "nsCOMPtr.h"
18#include "nsCRTGlue.h"
19#include "nsCycleCollectionParticipant.h"
20#include "nsISupports.h"
21#include "nsWrapperCache.h"
22#include "nsXPCOM.h"
23
24namespace mozilla {
25class ErrorResult;
26
27namespace devtools {
28
29class DominatorTree;
30
31using UniqueTwoByteString = UniqueFreePtr<char16_t[]>;
32using UniqueOneByteString = UniqueFreePtr<char[]>;
33
34class HeapSnapshot final : public nsISupports, public nsWrapperCache {
35 friend struct DeserializedNode;
36 friend struct DeserializedEdge;
37 friend struct DeserializedStackFrame;
38 friend class JS::ubi::Concrete<JS::ubi::DeserializedNode>;
39
40 explicit HeapSnapshot(JSContext* cx, nsISupports* aParent)
41 : timestamp(Nothing()),
42 rootId(0),
43 nodes(cx),
44 frames(cx),
45 mParent(aParent) {
46 MOZ_ASSERT(aParent)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aParent", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.h"
, 46); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent" ")")
; do { MOZ_CrashSequence(__null, 46); __attribute__((nomerge)
) ::abort(); } while (false); } } while (false)
;
47 };
48
49 // Initialize this HeapSnapshot from the given buffer that contains a
50 // serialized core dump. Do NOT take ownership of the buffer, only borrow it
51 // for the duration of the call. Return false on failure.
52 bool init(JSContext* cx, const uint8_t* buffer, uint32_t size);
53
54 using NodeIdSet = js::HashSet<NodeId>;
55
56 // Save the given `protobuf::Node` message in this `HeapSnapshot` as a
57 // `DeserializedNode`.
58 bool saveNode(const protobuf::Node& node, NodeIdSet& edgeReferents);
59
60 // Save the given `protobuf::StackFrame` message in this `HeapSnapshot` as a
61 // `DeserializedStackFrame`. The saved stack frame's id is returned via the
62 // out parameter.
63 bool saveStackFrame(const protobuf::StackFrame& frame,
64 StackFrameId& outFrameId);
65
66 public:
67 // The maximum number of stack frames that we will serialize into a core
68 // dump. This helps prevent over-recursion in the protobuf library when
69 // deserializing stacks.
70 static const size_t MAX_STACK_DEPTH = 60;
71
72 private:
73 // If present, a timestamp in the same units that `PR_Now` gives.
74 Maybe<uint64_t> timestamp;
75
76 // The id of the root node for this deserialized heap graph.
77 NodeId rootId;
78
79 // The set of nodes in this deserialized heap graph, keyed by id.
80 using NodeSet = js::HashSet<DeserializedNode, DeserializedNode::HashPolicy>;
81 NodeSet nodes;
82
83 // The set of stack frames in this deserialized heap graph, keyed by id.
84 using FrameSet =
85 js::HashSet<DeserializedStackFrame, DeserializedStackFrame::HashPolicy>;
86 FrameSet frames;
87
88 Vector<UniqueTwoByteString> internedTwoByteStrings;
89 Vector<UniqueOneByteString> internedOneByteStrings;
90
91 using StringOrRef = Variant<const std::string*, uint64_t>;
92
93 template <typename CharT, typename InternedStringSet>
94 const CharT* getOrInternString(InternedStringSet& internedStrings,
95 Maybe<StringOrRef>& maybeStrOrRef);
96
97 protected:
98 nsCOMPtr<nsISupports> mParent;
99
100 virtual ~HeapSnapshot() = default;
101
102 public:
103 // Create a `HeapSnapshot` from the given buffer that contains a serialized
104 // core dump. Do NOT take ownership of the buffer, only borrow it for the
105 // duration of the call.
106 static already_AddRefed<HeapSnapshot> Create(JSContext* cx,
107 dom::GlobalObject& global,
108 const uint8_t* buffer,
109 uint32_t size, ErrorResult& rv);
110
111 // Creates the `$TEMP_DIR/XXXXXX-XXX.fxsnapshot` core dump file that heap
112 // snapshots are serialized into.
113 static already_AddRefed<nsIFile> CreateUniqueCoreDumpFile(
114 ErrorResult& rv, const TimeStamp& now, nsAString& outFilePath,
115 nsAString& outSnapshotId);
116
117 NS_DECL_CYCLE_COLLECTING_ISUPPORTSpublic: virtual nsresult QueryInterface(const nsIID& aIID
, void** aInstancePtr) override; virtual MozExternalRefCountType
AddRef(void) override; virtual MozExternalRefCountType Release
(void) override; using HasThreadSafeRefCnt = std::false_type;
protected: nsCycleCollectingAutoRefCnt mRefCnt; nsAutoOwningThread
_mOwningThread; public: virtual void DeleteCycleCollectable(
void); public:
118 NS_DECL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS(HeapSnapshot)class cycleCollection : public nsXPCOMCycleCollectionParticipant
{ public: constexpr explicit cycleCollection(Flags aFlags = 0
) : nsXPCOMCycleCollectionParticipant(aFlags | FlagMaybeSingleZoneJSHolder
) {} private: public: virtual nsresult TraverseNative(void* p
, nsCycleCollectionTraversalCallback& cb) override; virtual
const char* ClassName() override { return "HeapSnapshot"; };
virtual void DeleteCycleCollectable(void* p) override { DowncastCCParticipant
<HeapSnapshot>(p)->DeleteCycleCollectable(); } static
HeapSnapshot* Downcast(nsISupports* s) { return static_cast<
HeapSnapshot*>(static_cast<HeapSnapshot*>(s)); } static
nsISupports* Upcast(HeapSnapshot* p) { return static_cast<
nsISupports*>(static_cast<HeapSnapshot*>(p)); } virtual
void Unlink(void* p) override; virtual void Trace(void* p, const
TraceCallbacks& cb, void* closure) override; virtual void
TraceWrapper(void* aPtr, const TraceCallbacks& aCb, void
* aClosure) final; static constexpr nsXPCOMCycleCollectionParticipant
* GetParticipant() { return &HeapSnapshot::_cycleCollectorGlobal
; } }; clang diagnostic push clang diagnostic ignored "-Wunnecessary-virtual-specifier"
virtual void CheckForRightParticipant() clang diagnostic pop
{ nsXPCOMCycleCollectionParticipant* p; CallQueryInterface(
this, &p); do { static_assert( mozilla::detail::AssertionConditionType
<decltype(p == &_cycleCollectorGlobal)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(p == &_cycleCollectorGlobal
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"p == &_cycleCollectorGlobal" " (" "HeapSnapshot" " should QI to its own CC participant"
")", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.h"
, 118); AnnotateMozCrashReason("MOZ_ASSERT" "(" "p == &_cycleCollectorGlobal"
") (" "HeapSnapshot" " should QI to its own CC participant" ")"
); do { MOZ_CrashSequence(__null, 118); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } static cycleCollection
_cycleCollectorGlobal; clang diagnostic push clang diagnostic
ignored "-Wunnecessary-virtual-specifier" virtual void BaseCycleCollectable
() final{} clang diagnostic pop
119 MOZ_DECLARE_REFCOUNTED_TYPENAME(HeapSnapshot)const char* typeName() const { return "HeapSnapshot"; } size_t
typeSize() const { return sizeof(*this); }
120
121 nsISupports* GetParentObject() const { return mParent; }
122
123 virtual JSObject* WrapObject(JSContext* aCx,
124 JS::Handle<JSObject*> aGivenProto) override;
125
126 const char16_t* borrowUniqueString(const char16_t* duplicateString,
127 size_t length);
128
129 // Get the root node of this heap snapshot's graph.
130 JS::ubi::Node getRoot() {
131 auto p = nodes.lookup(rootId);
132 MOZ_ASSERT(p)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(p)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(p))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("p", "/root/firefox-clang/devtools/shared/heapsnapshot/HeapSnapshot.h"
, 132); AnnotateMozCrashReason("MOZ_ASSERT" "(" "p" ")"); do {
MOZ_CrashSequence(__null, 132); __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
133 const DeserializedNode& node = *p;
134 return JS::ubi::Node(const_cast<DeserializedNode*>(&node));
135 }
136
137 Maybe<JS::ubi::Node> getNodeById(JS::ubi::Node::Id nodeId) {
138 auto p = nodes.lookup(nodeId);
4
Calling 'HashSet::lookup'
13
Returning from 'HashSet::lookup'
139 if (!p) return Nothing();
14
Assuming the condition is false
15
Taking false branch
140 return Some(JS::ubi::Node(const_cast<DeserializedNode*>(&*p)));
16
Calling 'Ptr::operator*'
141 }
142
143 void TakeCensus(JSContext* cx, JS::Handle<JSObject*> options,
144 JS::MutableHandle<JS::Value> rval, ErrorResult& rv);
145
146 void DescribeNode(JSContext* cx, JS::Handle<JSObject*> breakdown,
147 uint64_t nodeId, JS::MutableHandle<JS::Value> rval,
148 ErrorResult& rv);
149
150 already_AddRefed<DominatorTree> ComputeDominatorTree(ErrorResult& rv);
151
152 void ComputeShortestPaths(JSContext* cx, uint64_t start,
153 const dom::Sequence<uint64_t>& targets,
154 uint64_t maxNumPaths,
155 JS::MutableHandle<JSObject*> results,
156 ErrorResult& rv);
157
158 dom::Nullable<uint64_t> GetCreationTime() {
159 static const uint64_t maxTime = uint64_t(1) << 53;
160 if (timestamp.isSome() && timestamp.ref() <= maxTime) {
161 return dom::Nullable<uint64_t>(timestamp.ref());
162 }
163
164 return dom::Nullable<uint64_t>();
165 }
166};
167
168// A `CoreDumpWriter` is given the data we wish to save in a core dump and
169// serializes it to disk, or memory, or a socket, etc.
170class CoreDumpWriter {
171 public:
172 virtual ~CoreDumpWriter() = default;
173
174 // Write the given bits of metadata we would like to associate with this core
175 // dump.
176 virtual bool writeMetadata(uint64_t timestamp) = 0;
177
178 enum EdgePolicy : bool { INCLUDE_EDGES = true, EXCLUDE_EDGES = false };
179
180 // Write the given `JS::ubi::Node` to the core dump. The given `EdgePolicy`
181 // dictates whether its outgoing edges should also be written to the core
182 // dump, or excluded.
183 virtual bool writeNode(const JS::ubi::Node& node,
184 EdgePolicy includeEdges) = 0;
185};
186
187// Serialize the heap graph as seen from `node` with the given `CoreDumpWriter`.
188// If `wantNames` is true, capture edge names. If `zones` is non-null, only
189// capture the sub-graph within the zone set, otherwise capture the whole heap
190// graph. Returns false on failure.
191bool WriteHeapGraph(JSContext* cx, const JS::ubi::Node& node,
192 CoreDumpWriter& writer, bool wantNames,
193 JS::CompartmentSet* compartments,
194 JS::AutoCheckCannotGC& noGC, uint32_t& outNodeCount,
195 uint32_t& outEdgeCount);
196inline bool WriteHeapGraph(JSContext* cx, const JS::ubi::Node& node,
197 CoreDumpWriter& writer, bool wantNames,
198 JS::CompartmentSet* compartments,
199 JS::AutoCheckCannotGC& noGC) {
200 uint32_t ignoreNodeCount;
201 uint32_t ignoreEdgeCount;
202 return WriteHeapGraph(cx, node, writer, wantNames, compartments, noGC,
203 ignoreNodeCount, ignoreEdgeCount);
204}
205
206// Get the mozilla::MallocSizeOf for the current thread's JSRuntime.
207MallocSizeOf GetCurrentThreadDebuggerMallocSizeOf();
208
209} // namespace devtools
210} // namespace mozilla
211
212#endif // mozilla_devtools_HeapSnapshot_

/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//---------------------------------------------------------------------------
6// Overview
7//---------------------------------------------------------------------------
8//
9// This file defines HashMap<Key, Value> and HashSet<T>, hash tables that are
10// fast and have a nice API.
11//
12// Both hash tables have two optional template parameters.
13//
14// - HashPolicy. This defines the operations for hashing and matching keys. The
15// default HashPolicy is appropriate when both of the following two
16// conditions are true.
17//
18// - The key type stored in the table (|Key| for |HashMap<Key, Value>|, |T|
19// for |HashSet<T>|) is an integer, pointer, UniquePtr, float, or double.
20//
21// - The type used for lookups (|Lookup|) is the same as the key type. This
22// is usually the case, but not always.
23//
24// There is also a |CStringHasher| policy for |char*| keys. If your keys
25// don't match any of the above cases, you must provide your own hash policy;
26// see the "Hash Policy" section below.
27//
28// - AllocPolicy. This defines how allocations are done by the table.
29//
30// - |MallocAllocPolicy| is the default and is usually appropriate; note that
31// operations (such as insertions) that might cause allocations are
32// fallible and must be checked for OOM. These checks are enforced by the
33// use of [[nodiscard]].
34//
35// - |InfallibleAllocPolicy| is another possibility; it allows the
36// abovementioned OOM checks to be done with MOZ_ALWAYS_TRUE().
37//
38// Note that entry storage allocation is lazy, and not done until the first
39// lookupForAdd(), put(), or putNew() is performed.
40//
41// See AllocPolicy.h for more details.
42//
43// Documentation on how to use HashMap and HashSet, including examples, is
44// present within those classes. Search for "class HashMap" and "class
45// HashSet".
46//
47// Both HashMap and HashSet are implemented on top of a third class, HashTable.
48// You only need to look at HashTable if you want to understand the
49// implementation.
50//
51// How does mozilla::HashTable (this file) compare with PLDHashTable (and its
52// subclasses, such as nsTHashtable)?
53//
54// - mozilla::HashTable is a lot faster, largely because it uses templates
55// throughout *and* inlines everything. PLDHashTable inlines operations much
56// less aggressively, and also uses "virtual ops" for operations like hashing
57// and matching entries that require function calls.
58//
59// - Correspondingly, mozilla::HashTable use is likely to increase executable
60// size much more than PLDHashTable.
61//
62// - mozilla::HashTable has a nicer API, with a proper HashSet vs. HashMap
63// distinction.
64//
65// - mozilla::HashTable requires more explicit OOM checking. As mentioned
66// above, the use of |InfallibleAllocPolicy| can simplify things.
67//
68// - mozilla::HashTable has a default capacity on creation of 32 and a minimum
69// capacity of 4. PLDHashTable has a default capacity on creation of 8 and a
70// minimum capacity of 8.
71
72#ifndef mozilla_HashTable_h
73#define mozilla_HashTable_h
74
75#include <bit>
76#include <type_traits>
77#include <utility>
78
79#include "mozilla/AllocPolicy.h"
80#include "mozilla/Assertions.h"
81#include "mozilla/Attributes.h"
82#include "mozilla/Casting.h"
83#include "mozilla/HashFunctions.h"
84#include "mozilla/MathAlgorithms.h"
85#include "mozilla/Maybe.h"
86#include "mozilla/MemoryChecking.h"
87#include "mozilla/MemoryReporting.h"
88#include "mozilla/Opaque.h"
89#include "mozilla/OperatorNewExtensions.h"
90#include "mozilla/ReentrancyGuard.h"
91#include "mozilla/UniquePtr.h"
92#include "mozilla/WrappingOperations.h"
93
94namespace mozilla {
95
96template <class, class = void>
97struct DefaultHasher;
98
99template <class, class>
100class HashMapEntry;
101
102namespace detail {
103
104template <typename T>
105class HashTableEntry;
106
107template <class T, class HashPolicy, class AllocPolicy>
108class HashTable;
109
110} // namespace detail
111
112// The "generation" of a hash table is an opaque value indicating the state of
113// modification of the hash table through its lifetime. If the generation of
114// a hash table compares equal at times T1 and T2, then lookups in the hash
115// table, pointers to (or into) hash table entries, etc. at time T1 are valid
116// at time T2. If the generation compares unequal, these computations are all
117// invalid and must be performed again to be used.
118//
119// Generations are meaningfully comparable only with respect to a single hash
120// table. It's always nonsensical to compare the generation of distinct hash
121// tables H1 and H2.
122using Generation = Opaque<uint64_t>;
123
124//---------------------------------------------------------------------------
125// HashMap
126//---------------------------------------------------------------------------
127
128// HashMap is a fast hash-based map from keys to values.
129//
130// Template parameter requirements:
131// - Key/Value: movable, destructible, assignable.
132// - HashPolicy: see the "Hash Policy" section below.
133// - AllocPolicy: see AllocPolicy.h.
134//
135// Note:
136// - HashMap is not reentrant: Key/Value/HashPolicy/AllocPolicy members
137// called by HashMap must not call back into the same HashMap object.
138//
139template <class Key, class Value, class HashPolicy = DefaultHasher<Key>,
140 class AllocPolicy = MallocAllocPolicy>
141class MOZ_STANDALONE_DEBUG[[clang::standalone_debug]] HashMap {
142 // -- Implementation details -----------------------------------------------
143
144 // HashMap is not copyable or assignable.
145 HashMap(const HashMap& hm) = delete;
146 HashMap& operator=(const HashMap& hm) = delete;
147
148 using TableEntry = HashMapEntry<Key, Value>;
149
150 struct MapHashPolicy : HashPolicy {
151 using Base = HashPolicy;
152 using KeyType = Key;
153
154 static const Key& getKey(TableEntry& aEntry) { return aEntry.key(); }
155
156 template <typename KeyInput>
157 static void setKey(TableEntry& aEntry, KeyInput&& aKey) {
158 HashPolicy::rekey(aEntry.mutableKey(), std::forward<KeyInput>(aKey));
159 }
160 };
161
162 using Impl = detail::HashTable<TableEntry, MapHashPolicy, AllocPolicy>;
163 Impl mImpl;
164
165 public:
166 using Lookup = typename HashPolicy::Lookup;
167 using Entry = TableEntry;
168
169 // -- Initialization -------------------------------------------------------
170
171 constexpr explicit HashMap(AllocPolicy aAllocPolicy = AllocPolicy(),
172 uint32_t aLen = Impl::sDefaultLen)
173 : mImpl(std::move(aAllocPolicy), aLen) {}
174
175 explicit HashMap(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}
176
177 // HashMap is movable.
178 HashMap(HashMap&& aRhs) = default;
179 HashMap& operator=(HashMap&& aRhs) = default;
180
181 // Swap the contents of this hash map with another.
182 void swap(HashMap& aOther) { mImpl.swap(aOther.mImpl); }
183
184 // -- Status and sizing ----------------------------------------------------
185
186 // The map's current generation.
187 Generation generation() const { return mImpl.generation(); }
188
189 // Is the map empty?
190 bool empty() const { return mImpl.empty(); }
191
192 // Number of keys/values in the map.
193 uint32_t count() const { return mImpl.count(); }
194
195 // Number of key/value slots in the map. Note: resize will happen well before
196 // count() == capacity().
197 uint32_t capacity() const { return mImpl.capacity(); }
198
199 // The size of the map's entry storage, in bytes. If the keys/values contain
200 // pointers to other heap blocks, you must iterate over the map and measure
201 // them separately; hence the "shallow" prefix.
202 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
203 return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
204 }
205 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
206 return aMallocSizeOf(this) +
207 mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
208 }
209
210 // Attempt to minimize the capacity(). If the table is empty, this will free
211 // the empty storage and upon regrowth it will be given the minimum capacity.
212 void compact() { mImpl.compact(); }
213
214 // Attempt to reserve enough space to fit at least |aLen| elements. This is
215 // total capacity, including elements already present. Does nothing if the
216 // map already has sufficient capacity.
217 [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }
218
219 // -- Lookups --------------------------------------------------------------
220
221 // Does the map contain a key/value matching |aLookup|?
222 bool has(const Lookup& aLookup) const {
223 return mImpl.lookup(aLookup).found();
224 }
225
226 // Return a Ptr indicating whether a key/value matching |aLookup| is
227 // present in the map. E.g.:
228 //
229 // using HM = HashMap<int,char>;
230 // HM h;
231 // if (HM::Ptr p = h.lookup(3)) {
232 // assert(p->key() == 3);
233 // char val = p->value();
234 // }
235 //
236 using Ptr = typename Impl::Ptr;
237 MOZ_ALWAYS_INLINEinline Ptr lookup(const Lookup& aLookup) const {
238 return mImpl.lookup(aLookup);
239 }
240
241 // Like lookup(), but does not assert if two threads call it at the same
242 // time. Only use this method when none of the threads will modify the map.
243 MOZ_ALWAYS_INLINEinline Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
244 return mImpl.readonlyThreadsafeLookup(aLookup);
245 }
246
247 // -- Insertions -----------------------------------------------------------
248
249 // Overwrite existing value with |aValue|, or add it if not present. Returns
250 // false on OOM.
251 template <typename KeyInput, typename ValueInput>
252 [[nodiscard]] bool put(KeyInput&& aKey, ValueInput&& aValue) {
253 return put(aKey, std::forward<KeyInput>(aKey),
254 std::forward<ValueInput>(aValue));
255 }
256
257 template <typename KeyInput, typename ValueInput>
258 [[nodiscard]] bool put(const Lookup& aLookup, KeyInput&& aKey,
259 ValueInput&& aValue) {
260 AddPtr p = lookupForAdd(aLookup);
261 if (p) {
262 p->value() = std::forward<ValueInput>(aValue);
263 return true;
264 }
265 return add(p, std::forward<KeyInput>(aKey),
266 std::forward<ValueInput>(aValue));
267 }
268
269 // Like put(), but slightly faster. Must only be used when the given key is
270 // not already present. (In debug builds, assertions check this.)
271 template <typename KeyInput, typename ValueInput>
272 [[nodiscard]] bool putNew(KeyInput&& aKey, ValueInput&& aValue) {
273 return mImpl.putNew(aKey, std::forward<KeyInput>(aKey),
274 std::forward<ValueInput>(aValue));
275 }
276
277 template <typename KeyInput, typename ValueInput>
278 [[nodiscard]] bool putNew(const Lookup& aLookup, KeyInput&& aKey,
279 ValueInput&& aValue) {
280 return mImpl.putNew(aLookup, std::forward<KeyInput>(aKey),
281 std::forward<ValueInput>(aValue));
282 }
283
284 // Like putNew(), but should be only used when the table is known to be big
285 // enough for the insertion, and hashing cannot fail. Typically this is used
286 // to populate an empty map with known-unique keys after reserving space with
287 // reserve(), e.g.
288 //
289 // using HM = HashMap<int,char>;
290 // HM h;
291 // if (!h.reserve(3)) {
292 // MOZ_CRASH("OOM");
293 // }
294 // h.putNewInfallible(1, 'a'); // unique key
295 // h.putNewInfallible(2, 'b'); // unique key
296 // h.putNewInfallible(3, 'c'); // unique key
297 //
298 template <typename KeyInput, typename ValueInput>
299 void putNewInfallible(KeyInput&& aKey, ValueInput&& aValue) {
300 mImpl.putNewInfallible(aKey, std::forward<KeyInput>(aKey),
301 std::forward<ValueInput>(aValue));
302 }
303
304 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
305 // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using
306 // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new key/value. E.g.:
307 //
308 // using HM = HashMap<int,char>;
309 // HM h;
310 // HM::AddPtr p = h.lookupForAdd(3);
311 // if (!p) {
312 // if (!h.add(p, 3, 'a')) {
313 // return false;
314 // }
315 // }
316 // assert(p->key() == 3);
317 // char val = p->value();
318 //
319 // N.B. The caller must ensure that no mutating hash table operations occur
320 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
321 // key a second time, the caller may use the more efficient relookupOrAdd()
322 // method. This method reuses part of the hashing computation to more
323 // efficiently insert the key if it has not been added. For example, a
324 // mutation-handling version of the previous example:
325 //
326 // HM::AddPtr p = h.lookupForAdd(3);
327 // if (!p) {
328 // call_that_may_mutate_h();
329 // if (!h.relookupOrAdd(p, 3, 'a')) {
330 // return false;
331 // }
332 // }
333 // assert(p->key() == 3);
334 // char val = p->value();
335 //
336 using AddPtr = typename Impl::AddPtr;
337 MOZ_ALWAYS_INLINEinline AddPtr lookupForAdd(const Lookup& aLookup) {
338 return mImpl.lookupForAdd(aLookup);
339 }
340
341 // Add a key/value. Returns false on OOM.
342 template <typename KeyInput, typename ValueInput>
343 [[nodiscard]] bool add(AddPtr& aPtr, KeyInput&& aKey, ValueInput&& aValue) {
344 return mImpl.add(aPtr, std::forward<KeyInput>(aKey),
345 std::forward<ValueInput>(aValue));
346 }
347
348 // See the comment above lookupForAdd() for details.
349 template <typename KeyInput, typename ValueInput>
350 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, KeyInput&& aKey,
351 ValueInput&& aValue) {
352 return mImpl.relookupOrAdd(aPtr, aKey, std::forward<KeyInput>(aKey),
353 std::forward<ValueInput>(aValue));
354 }
355
356 // -- Removal --------------------------------------------------------------
357
358 // Lookup and remove the key/value matching |aLookup|, if present.
359 void remove(const Lookup& aLookup) {
360 if (Ptr p = lookup(aLookup)) {
361 remove(p);
362 }
363 }
364
365 // Remove a previously found key/value (assuming aPtr.found()). The map must
366 // not have been mutated in the interim.
367 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
368
369 // Remove all keys/values without changing the capacity.
370 void clear() { mImpl.clear(); }
371
372 // Like clear() followed by compact().
373 void clearAndCompact() { mImpl.clearAndCompact(); }
374
375 // -- Rekeying -------------------------------------------------------------
376
377 // Infallibly rekey one entry, if necessary. Requires Key to be rekeyable (via
378 // to HashPolicy::rekey) from Lookup.
379 void rekeyIfMoved(const Lookup& aOldKey, const Lookup& aNewKeyInput) {
380 if (aOldKey != aNewKeyInput) {
381 rekeyAs(aOldKey, aNewKeyInput, aNewKeyInput);
382 }
383 }
384
385 // Infallibly rekey one entry if present, and return whether that happened.
386 template <typename KeyInput>
387 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
388 KeyInput&& aNewKey) {
389 if (Ptr p = lookup(aOldLookup)) {
390 mImpl.rekeyAndMaybeRehash(p, aNewLookup, std::forward<KeyInput>(aNewKey));
391 return true;
392 }
393 return false;
394 }
395
396 // -- Iteration ------------------------------------------------------------
397
398 // |iter()| returns an Iterator:
399 //
400 // HashMap<int, char> h;
401 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
402 // char c = iter.get().value();
403 // }
404 //
405 using Iterator = typename Impl::Iterator;
406 Iterator iter() const { return mImpl.iter(); }
407
408 // |modIter()| returns a ModIterator:
409 //
410 // HashMap<int, char> h;
411 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
412 // if (iter.get().value() == 'l') {
413 // iter.remove();
414 // }
415 // }
416 //
417 // Table resize may occur in ModIterator's destructor.
418 using ModIterator = typename Impl::ModIterator;
419 ModIterator modIter() { return mImpl.modIter(); }
420
421 // -- Alloc policy ---------------------------------------------------------
422
423 // Get the alloc policy.
424 const AllocPolicy& allocPolicy() const { return mImpl.allocPolicy(); }
425 AllocPolicy& allocPolicy() { return mImpl.allocPolicy(); }
426
427 // For internal use by allocation policies that provide garbage collected
428 // memory.
429 //
430 // Trace any allocations owned by this object that were made with AllocPolicy.
431 // Call the supplied closure |aTraceFunc| for each of them, passing a double
432 // pointer to the memory held (e.g. a void** pointer).
433 template <typename F>
434 void traceOwnedAllocs(F&& aTraceFunc) {
435 mImpl.traceOwnedAllocs(std::forward<F>(aTraceFunc));
436 }
437
438 // -- Layout information for JIT access ------------------------------------
439
440 static size_t offsetOfHashShift() {
441 return offsetof(HashMap, mImpl)__builtin_offsetof(HashMap, mImpl) + Impl::offsetOfHashShift();
442 }
443 static size_t offsetOfTable() {
444 return offsetof(HashMap, mImpl)__builtin_offsetof(HashMap, mImpl) + Impl::offsetOfTable();
445 }
446 static size_t offsetOfEntryCount() {
447 return offsetof(HashMap, mImpl)__builtin_offsetof(HashMap, mImpl) + Impl::offsetOfEntryCount();
448 }
449};
450
451//---------------------------------------------------------------------------
452// HashSet
453//---------------------------------------------------------------------------
454
455// HashSet is a fast hash-based set of values.
456//
457// Template parameter requirements:
458// - T: movable, destructible, assignable.
459// - HashPolicy: see the "Hash Policy" section below.
460// - AllocPolicy: see AllocPolicy.h
461//
462// Note:
463// - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by
464// HashSet must not call back into the same HashSet object.
465//
466template <class T, class HashPolicy = DefaultHasher<T>,
467 class AllocPolicy = MallocAllocPolicy>
468class HashSet {
469 // -- Implementation details -----------------------------------------------
470
471 // HashSet is not copyable or assignable.
472 HashSet(const HashSet& hs) = delete;
473 HashSet& operator=(const HashSet& hs) = delete;
474
475 struct SetHashPolicy : HashPolicy {
476 using Base = HashPolicy;
477 using KeyType = T;
478
479 static const KeyType& getKey(const T& aT) { return aT; }
480
481 template <typename KeyInput>
482 static void setKey(T& aT, KeyInput&& aKey) {
483 HashPolicy::rekey(aT, std::forward<KeyInput>(aKey));
484 }
485 };
486
487 using Impl = detail::HashTable<const T, SetHashPolicy, AllocPolicy>;
488 Impl mImpl;
489
490 public:
491 using Lookup = typename HashPolicy::Lookup;
492 using Entry = T;
493
494 // -- Initialization -------------------------------------------------------
495
496 explicit HashSet(AllocPolicy aAllocPolicy = AllocPolicy(),
497 uint32_t aLen = Impl::sDefaultLen)
498 : mImpl(std::move(aAllocPolicy), aLen) {}
499
500 explicit HashSet(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}
501
502 // HashSet is movable.
503 HashSet(HashSet&& aRhs) = default;
504 HashSet& operator=(HashSet&& aRhs) = default;
505
506 // Swap the contents of this hash set with another.
507 void swap(HashSet& aOther) { mImpl.swap(aOther.mImpl); }
508
509 // -- Status and sizing ----------------------------------------------------
510
511 // The set's current generation.
512 Generation generation() const { return mImpl.generation(); }
513
514 // Is the set empty?
515 bool empty() const { return mImpl.empty(); }
516
517 // Number of elements in the set.
518 uint32_t count() const { return mImpl.count(); }
519
520 // Number of element slots in the set. Note: resize will happen well before
521 // count() == capacity().
522 uint32_t capacity() const { return mImpl.capacity(); }
523
524 // The size of the set's entry storage, in bytes. If the elements contain
525 // pointers to other heap blocks, you must iterate over the set and measure
526 // them separately; hence the "shallow" prefix.
527 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
528 return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
529 }
530 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
531 return aMallocSizeOf(this) +
532 mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
533 }
534
535 // Attempt to minimize the capacity(). If the table is empty, this will free
536 // the empty storage and upon regrowth it will be given the minimum capacity.
537 void compact() { mImpl.compact(); }
538
539 // Attempt to reserve enough space to fit at least |aLen| elements. This is
540 // total capacity, including elements already present. Does nothing if the
541 // map already has sufficient capacity.
542 [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }
543
544 // -- Lookups --------------------------------------------------------------
545
546 // Does the set contain an element matching |aLookup|?
547 bool has(const Lookup& aLookup) const {
548 return mImpl.lookup(aLookup).found();
549 }
550
551 // Return a Ptr indicating whether an element matching |aLookup| is present
552 // in the set. E.g.:
553 //
554 // using HS = HashSet<int>;
555 // HS h;
556 // if (HS::Ptr p = h.lookup(3)) {
557 // assert(*p == 3); // p acts like a pointer to int
558 // }
559 //
560 using Ptr = typename Impl::Ptr;
561 MOZ_ALWAYS_INLINEinline Ptr lookup(const Lookup& aLookup) const {
562 return mImpl.lookup(aLookup);
5
Calling 'HashTable::lookup'
12
Returning from 'HashTable::lookup'
563 }
564
565 // Like lookup(), but does not assert if two threads call it at the same
566 // time. Only use this method when none of the threads will modify the set.
567 MOZ_ALWAYS_INLINEinline Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
568 return mImpl.readonlyThreadsafeLookup(aLookup);
569 }
570
571 // -- Insertions -----------------------------------------------------------
572
573 // Add |aU| if it is not present already. Returns false on OOM.
574 template <typename U>
575 [[nodiscard]] bool put(U&& aU) {
576 AddPtr p = lookupForAdd(aU);
577 return p ? true : add(p, std::forward<U>(aU));
578 }
579
580 // Like put(), but slightly faster. Must only be used when the given element
581 // is not already present. (In debug builds, assertions check this.)
582 template <typename U>
583 [[nodiscard]] bool putNew(U&& aU) {
584 return mImpl.putNew(aU, std::forward<U>(aU));
585 }
586
587 // Like the other putNew(), but for when |Lookup| is different to |T|.
588 template <typename U>
589 [[nodiscard]] bool putNew(const Lookup& aLookup, U&& aU) {
590 return mImpl.putNew(aLookup, std::forward<U>(aU));
591 }
592
593 // Like putNew(), but should be only used when the table is known to be big
594 // enough for the insertion, and hashing cannot fail. Typically this is used
595 // to populate an empty set with known-unique elements after reserving space
596 // with reserve(), e.g.
597 //
598 // using HS = HashMap<int>;
599 // HS h;
600 // if (!h.reserve(3)) {
601 // MOZ_CRASH("OOM");
602 // }
603 // h.putNewInfallible(1); // unique element
604 // h.putNewInfallible(2); // unique element
605 // h.putNewInfallible(3); // unique element
606 //
607 template <typename U>
608 void putNewInfallible(const Lookup& aLookup, U&& aU) {
609 mImpl.putNewInfallible(aLookup, std::forward<U>(aU));
610 }
611
612 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
613 // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using
614 // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.:
615 //
616 // using HS = HashSet<int>;
617 // HS h;
618 // HS::AddPtr p = h.lookupForAdd(3);
619 // if (!p) {
620 // if (!h.add(p, 3)) {
621 // return false;
622 // }
623 // }
624 // assert(*p == 3); // p acts like a pointer to int
625 //
626 // N.B. The caller must ensure that no mutating hash table operations occur
627 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
628 // key a second time, the caller may use the more efficient relookupOrAdd()
629 // method. This method reuses part of the hashing computation to more
630 // efficiently insert the key if it has not been added. For example, a
631 // mutation-handling version of the previous example:
632 //
633 // HS::AddPtr p = h.lookupForAdd(3);
634 // if (!p) {
635 // call_that_may_mutate_h();
636 // if (!h.relookupOrAdd(p, 3, 3)) {
637 // return false;
638 // }
639 // }
640 // assert(*p == 3);
641 //
642 // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the
643 // entry |t|, where the caller ensures match(l,t).
644 using AddPtr = typename Impl::AddPtr;
645 MOZ_ALWAYS_INLINEinline AddPtr lookupForAdd(const Lookup& aLookup) {
646 return mImpl.lookupForAdd(aLookup);
647 }
648
649 // Add an element. Returns false on OOM.
650 template <typename U>
651 [[nodiscard]] bool add(AddPtr& aPtr, U&& aU) {
652 return mImpl.add(aPtr, std::forward<U>(aU));
653 }
654
655 // See the comment above lookupForAdd() for details.
656 template <typename U>
657 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
658 U&& aU) {
659 return mImpl.relookupOrAdd(aPtr, aLookup, std::forward<U>(aU));
660 }
661
662 // -- Removal --------------------------------------------------------------
663
664 // Lookup and remove the element matching |aLookup|, if present.
665 void remove(const Lookup& aLookup) {
666 if (Ptr p = lookup(aLookup)) {
667 remove(p);
668 }
669 }
670
671 // Remove a previously found element (assuming aPtr.found()). The set must
672 // not have been mutated in the interim.
673 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
674
675 // Remove all keys/values without changing the capacity.
676 void clear() { mImpl.clear(); }
677
678 // Like clear() followed by compact().
679 void clearAndCompact() { mImpl.clearAndCompact(); }
680
681 // -- Rekeying -------------------------------------------------------------
682
683 // Infallibly rekey one entry, if necessary. Requires Key be rekeyable (via
684 // to HashPolicy::rekey) from Lookup.
685 void rekeyIfMoved(const Lookup& aOldValue, const Lookup& aNewValue) {
686 if (aOldValue != aNewValue) {
687 rekeyAs(aOldValue, aNewValue, aNewValue);
688 }
689 }
690
691 // Infallibly rekey one entry if present, and return whether that happened.
692 template <typename U>
693 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
694 U&& aNewValue) {
695 if (Ptr p = lookup(aOldLookup)) {
696 mImpl.rekeyAndMaybeRehash(p, aNewLookup, std::forward<U>(aNewValue));
697 return true;
698 }
699 return false;
700 }
701
702 // Infallibly replace the current key at |aPtr| with an equivalent key.
703 // Specifically, both HashPolicy::hash and HashPolicy::match must return
704 // identical results for the new and old key when applied against all
705 // possible matching values.
706 template <typename U>
707 void replaceKey(Ptr aPtr, const Lookup& aLookup, U&& aNewValue) {
708 MOZ_ASSERT(aPtr.found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPtr.found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aPtr.found()))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aPtr.found()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 708); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.found()"
")"); do { MOZ_CrashSequence(__null, 708); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
709 MOZ_ASSERT(HashPolicy::match(*aPtr, aLookup))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HashPolicy::match(*aPtr, aLookup))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(HashPolicy::match(*aPtr, aLookup
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("HashPolicy::match(*aPtr, aLookup)", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 709); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HashPolicy::match(*aPtr, aLookup)"
")"); do { MOZ_CrashSequence(__null, 709); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
710 MOZ_ASSERT(*aPtr != aNewValue)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(*aPtr != aNewValue)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(*aPtr != aNewValue))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("*aPtr != aNewValue"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 710); AnnotateMozCrashReason("MOZ_ASSERT" "(" "*aPtr != aNewValue"
")"); do { MOZ_CrashSequence(__null, 710); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
711 const_cast<T&>(*aPtr) = std::forward<U>(aNewValue);
712 MOZ_ASSERT(*lookup(aLookup) == aNewValue)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(*lookup(aLookup) == aNewValue)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(*lookup(aLookup) == aNewValue
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"*lookup(aLookup) == aNewValue", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 712); AnnotateMozCrashReason("MOZ_ASSERT" "(" "*lookup(aLookup) == aNewValue"
")"); do { MOZ_CrashSequence(__null, 712); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
713 }
714 void replaceKey(Ptr aPtr, const T& aNewValue) {
715 replaceKey(aPtr, aNewValue, aNewValue);
716 }
717
718 // -- Iteration ------------------------------------------------------------
719
720 // |iter()| returns an Iterator:
721 //
722 // HashSet<int> h;
723 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
724 // int i = iter.get();
725 // }
726 //
727 using Iterator = typename Impl::Iterator;
728 Iterator iter() const { return mImpl.iter(); }
729
730 // |modIter()| returns a ModIterator:
731 //
732 // HashSet<int> h;
733 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
734 // if (iter.get() == 42) {
735 // iter.remove();
736 // }
737 // }
738 //
739 // Table resize may occur in ModIterator's destructor.
740 using ModIterator = typename Impl::ModIterator;
741 ModIterator modIter() { return mImpl.modIter(); }
742
743 // -- Alloc policy ---------------------------------------------------------
744
745 // Get the alloc policy.
746 const AllocPolicy& allocPolicy() const { return mImpl.allocPolicy(); }
747 AllocPolicy& allocPolicy() { return mImpl.allocPolicy(); }
748
749 // For internal use by allocation policies that provide garbage collected
750 // memory.
751 //
752 // Trace any allocations owned by this object that were made with AllocPolicy.
753 // Call the supplied closure |aTraceFunc| for each of them, passing a double
754 // pointer to the memory held (e.g. a void** pointer).
755 template <typename F>
756 void traceOwnedAllocs(F&& aTraceFunc) {
757 mImpl.traceOwnedAllocs(std::forward<F>(aTraceFunc));
758 }
759};
760
761//---------------------------------------------------------------------------
762// Hash Policy
763//---------------------------------------------------------------------------
764
765// A hash policy |HP| for a hash table with key-type |Key| must provide:
766//
767// - a type |HP::Lookup| to use to lookup table entries;
768//
769// - a static member function |HP::hash| that hashes lookup values:
770//
771// static mozilla::HashNumber hash(const Lookup&);
772//
773// - a static member function |HP::match| that tests equality of key and
774// lookup values:
775//
776// static bool match(const Key& aKey, const Lookup& aLookup);
777//
778// |aKey| and |aLookup| can have different hash numbers, only when a
779// collision happens with |prepareHash| operation, which is less frequent.
780// Thus, |HP::match| shouldn't assume the hash equality in the comparison,
781// even if the hash numbers are almost always same between them.
782//
783// Normally, Lookup = Key. In general, though, different values and types of
784// values can be used to lookup and store. If a Lookup value |l| is not equal
785// to the added Key value |k|, the user must ensure that |HP::match(k,l)| is
786// true. E.g.:
787//
788// mozilla::HashSet<Key, HP>::AddPtr p = h.lookup(l);
789// if (!p) {
790// assert(HP::match(k, l)); // must hold
791// h.add(p, k);
792// }
793
794// A pointer hashing policy that uses HashGeneric() to create good hashes for
795// pointers. Note that we don't shift out the lowest k bits because we don't
796// want to assume anything about the alignment of the pointers.
797template <typename Key>
798struct PointerHasher {
799 static_assert(std::is_pointer_v<Key>);
800
801 using Lookup = Key;
802
803 static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }
804
805 static bool match(const Key& aKey, const Lookup& aLookup) {
806 return aKey == aLookup;
807 }
808
809 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
810};
811
812// The default hash policy, which only works with integers.
813template <class Key, typename>
814struct DefaultHasher {
815 using Lookup = Key;
816
817 static HashNumber hash(const Lookup& aLookup) {
818 // Just convert the integer to a HashNumber and use that as is. (This
819 // discards the high 32-bits of 64-bit integers!) ScrambleHashCode() is
820 // subsequently called on the value to improve the distribution.
821 return aLookup;
822 }
823
824 static bool match(const Key& aKey, const Lookup& aLookup) {
825 // Use builtin or overloaded operator==.
826 return aKey == aLookup;
827 }
828
829 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
830};
831
832// A DefaultHasher specialization for enums.
833template <class T>
834struct DefaultHasher<T, std::enable_if_t<std::is_enum_v<T>>> {
835 using Key = T;
836 using Lookup = Key;
837
838 static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }
839
840 static bool match(const Key& aKey, const Lookup& aLookup) {
841 // Use builtin or overloaded operator==.
842 return aKey == static_cast<Key>(aLookup);
843 }
844
845 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
846};
847
848// A DefaultHasher specialization for pointers.
849template <class T>
850struct DefaultHasher<T*> : PointerHasher<T*> {};
851
852// A DefaultHasher specialization for mozilla::UniquePtr.
853template <class T, class D>
854struct DefaultHasher<UniquePtr<T, D>> {
855 using Key = UniquePtr<T, D>;
856 using Lookup = Key;
857 using PtrHasher = PointerHasher<T*>;
858
859 static HashNumber hash(const Lookup& aLookup) {
860 return PtrHasher::hash(aLookup.get());
861 }
862
863 static bool match(const Key& aKey, const Lookup& aLookup) {
864 return PtrHasher::match(aKey.get(), aLookup.get());
865 }
866
867 static void rekey(Key& aKey, Key&& aNewKey) { aKey = std::move(aNewKey); }
868};
869
870// A DefaultHasher specialization for doubles.
871template <>
872struct DefaultHasher<double> {
873 using Key = double;
874 using Lookup = Key;
875
876 static HashNumber hash(const Lookup& aLookup) {
877 // Just xor the high bits with the low bits, and then treat the bits of the
878 // result as a uint32_t.
879 static_assert(sizeof(HashNumber) == 4,
880 "subsequent code assumes a four-byte hash");
881 uint64_t u = BitwiseCast<uint64_t>(aLookup);
882 return HashNumber(u ^ (u >> 32));
883 }
884
885 static bool match(const Key& aKey, const Lookup& aLookup) {
886 return BitwiseCast<uint64_t>(aKey) == BitwiseCast<uint64_t>(aLookup);
887 }
888};
889
890// A DefaultHasher specialization for floats.
891template <>
892struct DefaultHasher<float> {
893 using Key = float;
894 using Lookup = Key;
895
896 static HashNumber hash(const Lookup& aLookup) {
897 // Just use the value as if its bits form an integer. ScrambleHashCode() is
898 // subsequently called on the value to improve the distribution.
899 static_assert(sizeof(HashNumber) == 4,
900 "subsequent code assumes a four-byte hash");
901 return HashNumber(BitwiseCast<uint32_t>(aLookup));
902 }
903
904 static bool match(const Key& aKey, const Lookup& aLookup) {
905 return BitwiseCast<uint32_t>(aKey) == BitwiseCast<uint32_t>(aLookup);
906 }
907};
908
909// A hash policy for C strings.
910struct CStringHasher {
911 using Key = const char*;
912 using Lookup = const char*;
913
914 static HashNumber hash(const Lookup& aLookup) {
915 return HashString(aLookup, strlen(aLookup));
916 }
917
918 static bool match(const Key& aKey, const Lookup& aLookup) {
919 return strcmp(aKey, aLookup) == 0;
920 }
921};
922
923//---------------------------------------------------------------------------
924// Fallible Hashing Interface
925//---------------------------------------------------------------------------
926
927// Most of the time generating a hash code is infallible, but sometimes it is
928// necessary to generate hash codes on demand in a way that can fail. Specialize
929// this class for your own hash policy to provide fallible hashing.
930//
931// This is used by MovableCellHasher to handle the fact that generating a unique
932// ID for cell pointer may fail due to OOM.
933//
934// The default implementations of these methods delegate to the usual HashPolicy
935// implementation and always succeed.
936template <typename HashPolicy>
937struct FallibleHashMethods {
938 // Return true if a hashcode is already available for its argument, and
939 // sets |aHashOut|. Once this succeeds for a specific argument it
940 // must continue to do so.
941 //
942 // Return false if a hashcode is not already available. This implies that any
943 // lookup must fail, as the hash code would have to have been successfully
944 // created on insertion.
945 template <typename Lookup>
946 static bool maybeGetHash(Lookup&& aLookup, HashNumber* aHashOut) {
947 *aHashOut = HashPolicy::hash(aLookup);
948 return true;
949 }
950
951 // Fallible method to ensure a hashcode exists for its argument and create one
952 // if not. Sets |aHashOut| to the hashcode and retuns true on success. Returns
953 // false on error, e.g. out of memory.
954 template <typename Lookup>
955 static bool ensureHash(Lookup&& aLookup, HashNumber* aHashOut) {
956 *aHashOut = HashPolicy::hash(aLookup);
957 return true;
958 }
959};
960
961template <typename HashPolicy, typename Lookup>
962bool MaybeGetHash(Lookup&& aLookup, HashNumber* aHashOut) {
963 return FallibleHashMethods<typename HashPolicy::Base>::maybeGetHash(
964 std::forward<Lookup>(aLookup), aHashOut);
965}
966
967template <typename HashPolicy, typename Lookup>
968bool EnsureHash(Lookup&& aLookup, HashNumber* aHashOut) {
969 return FallibleHashMethods<typename HashPolicy::Base>::ensureHash(
970 std::forward<Lookup>(aLookup), aHashOut);
971}
972
973//---------------------------------------------------------------------------
974// Implementation Details (HashMapEntry, HashTableEntry, HashTable)
975//---------------------------------------------------------------------------
976
977// Both HashMap and HashSet are implemented by a single HashTable that is even
978// more heavily parameterized than the other two. This leaves HashTable gnarly
979// and extremely coupled to HashMap and HashSet; thus code should not use
980// HashTable directly.
981
982template <class Key, class Value>
983class HashMapEntry {
984 Key key_;
985 Value value_;
986
987 template <class, class, class>
988 friend class detail::HashTable;
989 template <class>
990 friend class detail::HashTableEntry;
991 template <class, class, class, class>
992 friend class HashMap;
993
994 public:
995 template <typename KeyInput, typename ValueInput>
996 HashMapEntry(KeyInput&& aKey, ValueInput&& aValue)
997 : key_(std::forward<KeyInput>(aKey)),
998 value_(std::forward<ValueInput>(aValue)) {}
999
1000 HashMapEntry(HashMapEntry&& aRhs) = default;
1001 HashMapEntry& operator=(HashMapEntry&& aRhs) = default;
1002
1003 using KeyType = Key;
1004 using ValueType = Value;
1005
1006 const Key& key() const { return key_; }
1007
1008 // Use this method with caution! If the key is changed such that its hash
1009 // value also changes, the map will be left in an invalid state.
1010 Key& mutableKey() { return key_; }
1011
1012 const Value& value() const { return value_; }
1013 Value& value() { return value_; }
1014
1015 static size_t offsetOfKey() { return offsetof(HashMapEntry, key_)__builtin_offsetof(HashMapEntry, key_); }
1016 static size_t offsetOfValue() { return offsetof(HashMapEntry, value_)__builtin_offsetof(HashMapEntry, value_); }
1017
1018 private:
1019 HashMapEntry(const HashMapEntry&) = delete;
1020 void operator=(const HashMapEntry&) = delete;
1021};
1022
1023namespace detail {
1024
1025static const HashNumber kHashTableFreeKey = 0;
1026static const HashNumber kHashTableRemovedKey = 1;
1027static const HashNumber kHashTableCollisionBit = 1;
1028
1029template <class T, class HashPolicy, class AllocPolicy>
1030class HashTable;
1031
1032template <typename T>
1033class EntrySlot;
1034
1035template <typename T>
1036class HashTableEntry {
1037 private:
1038 using NonConstT = std::remove_const_t<T>;
1039
1040 // Instead of having a hash table entry store that looks like this:
1041 //
1042 // +--------+--------+--------+--------+
1043 // | entry0 | entry1 | .... | entryN |
1044 // +--------+--------+--------+--------+
1045 //
1046 // where the entries contained their cached hash code, we're going to lay out
1047 // the entry store thusly:
1048 //
1049 // +-------+-------+-------+-------+--------+--------+--------+--------+
1050 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
1051 // +-------+-------+-------+-------+--------+--------+--------+--------+
1052 //
1053 // with all the cached hashes prior to the actual entries themselves.
1054 //
1055 // We do this because implementing the first strategy requires us to make
1056 // HashTableEntry look roughly like:
1057 //
1058 // template <typename T>
1059 // class HashTableEntry {
1060 // HashNumber mKeyHash;
1061 // T mValue;
1062 // };
1063 //
1064 // The problem with this setup is that, depending on the layout of `T`, there
1065 // may be platform ABI-mandated padding between `mKeyHash` and the first
1066 // member of `T`. This ABI-mandated padding is wasted space, and can be
1067 // surprisingly common, e.g. when `T` is a single pointer on 64-bit platforms.
1068 // In such cases, we're throwing away a quarter of our entry store on padding,
1069 // which is undesirable.
1070 //
1071 // The second layout above, namely:
1072 //
1073 // +-------+-------+-------+-------+--------+--------+--------+--------+
1074 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
1075 // +-------+-------+-------+-------+--------+--------+--------+--------+
1076 //
1077 // means there is no wasted space between the hashes themselves, and no wasted
1078 // space between the entries themselves. However, we would also like there to
1079 // be no gap between the last hash and the first entry. The memory allocator
1080 // guarantees the alignment of the start of the hashes. The use of a
1081 // power-of-two capacity of at least 4 guarantees that the alignment of the
1082 // *end* of the hash array is no less than the alignment of the start.
1083 // Finally, the static_asserts here guarantee that the entries themselves
1084 // don't need to be any more aligned than the alignment of the entry store
1085 // itself.
1086 //
1087 // This assertion is safe for 32-bit builds because on both Windows and Linux
1088 // (including Android), the minimum alignment for allocations larger than 8
1089 // bytes is 8 bytes, and the actual data for entries in our entry store is
1090 // guaranteed to have that alignment as well, thanks to the power-of-two
1091 // number of cached hash values stored prior to the entry data.
1092
1093 // The allocation policy must allocate a table with at least this much
1094 // alignment.
1095 static constexpr size_t kMinimumAlignment = 8;
1096
1097 static_assert(alignof(HashNumber) <= kMinimumAlignment,
1098 "[N*2 hashes, N*2 T values] allocation's alignment must be "
1099 "enough to align each hash");
1100 static_assert(alignof(NonConstT) <= 2 * sizeof(HashNumber),
1101 "subsequent N*2 T values must not require more than an even "
1102 "number of HashNumbers provides");
1103
1104 static const HashNumber sFreeKey = kHashTableFreeKey;
1105 static const HashNumber sRemovedKey = kHashTableRemovedKey;
1106 static const HashNumber sCollisionBit = kHashTableCollisionBit;
1107
1108 alignas(NonConstT) unsigned char mValueData[sizeof(NonConstT)];
1109
1110 private:
1111 template <class, class, class>
1112 friend class HashTable;
1113 template <typename>
1114 friend class EntrySlot;
1115
1116 // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
1117 // -Werror compile error) to reinterpret_cast<> |mValueData| to |T*|, even
1118 // through |void*|. Placing the latter cast in these separate functions
1119 // breaks the chain such that affected GCC versions no longer warn/error.
1120 void* rawValuePtr() { return mValueData; }
1121
1122 static bool isLiveHash(HashNumber hash) { return hash > sRemovedKey; }
1123
1124 HashTableEntry(const HashTableEntry&) = delete;
1125 void operator=(const HashTableEntry&) = delete;
1126
1127 NonConstT* valuePtr() { return reinterpret_cast<NonConstT*>(rawValuePtr()); }
1128
1129 void destroyStoredT() {
1130 NonConstT* ptr = valuePtr();
1131 ptr->~T();
1132 MOZ_MAKE_MEM_UNDEFINED(ptr, sizeof(*ptr))do { } while (0);
1133 }
1134
1135 public:
1136 HashTableEntry() = default;
1137
1138 ~HashTableEntry() { MOZ_MAKE_MEM_UNDEFINED(this, sizeof(*this))do { } while (0); }
1139
1140 void destroy() { destroyStoredT(); }
1141
1142 void swap(HashTableEntry* aOther, bool aOtherIsLive) {
1143 // This allows types to use Argument-Dependent-Lookup, and thus use a custom
1144 // std::swap, which is needed by types like JS::Heap and such.
1145 using std::swap;
1146
1147 if (this == aOther) {
1148 return;
1149 }
1150 if (aOtherIsLive) {
1151 swap(*valuePtr(), *aOther->valuePtr());
1152 } else {
1153 new (KnownNotNull, aOther->valuePtr()) NonConstT(std::move(*valuePtr()));
1154 destroy();
1155 }
1156 }
1157
1158 T& get() { return *valuePtr(); }
1159
1160 NonConstT& getMutable() { return *valuePtr(); }
1161};
1162
1163// A slot represents a cached hash value and its associated entry stored
1164// in the hash table. These two things are not stored in contiguous memory.
1165template <class T>
1166class EntrySlot {
1167 using NonConstT = std::remove_const_t<T>;
1168
1169 using Entry = HashTableEntry<T>;
1170
1171 Entry* mEntry;
1172 HashNumber* mKeyHash;
1173
1174 template <class, class, class>
1175 friend class HashTable;
1176
1177 EntrySlot(Entry* aEntry, HashNumber* aKeyHash)
1178 : mEntry(aEntry), mKeyHash(aKeyHash) {}
1179
1180 public:
1181 static bool isLiveHash(HashNumber hash) { return hash > Entry::sRemovedKey; }
1182
1183 EntrySlot(const EntrySlot&) = default;
1184 EntrySlot(EntrySlot&& aOther) = default;
1185
1186 EntrySlot& operator=(const EntrySlot&) = default;
1187 EntrySlot& operator=(EntrySlot&&) = default;
1188
1189 bool operator==(const EntrySlot& aRhs) const { return mEntry == aRhs.mEntry; }
1190
1191 bool operator<(const EntrySlot& aRhs) const { return mEntry < aRhs.mEntry; }
1192
1193 EntrySlot& operator++() {
1194 ++mEntry;
1195 ++mKeyHash;
1196 return *this;
1197 }
1198
1199 void destroy() { mEntry->destroy(); }
1200
1201 void swap(EntrySlot& aOther) {
1202 mEntry->swap(aOther.mEntry, aOther.isLive());
1203 std::swap(*mKeyHash, *aOther.mKeyHash);
1204 }
1205
1206 T& get() const { return mEntry->get(); }
1207
1208 NonConstT& getMutable() { return mEntry->getMutable(); }
1209
1210 bool isFree() const { return *mKeyHash == Entry::sFreeKey; }
1211
1212 void clearLive() {
1213 MOZ_ASSERT(isLive())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isLive())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isLive()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isLive()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1213); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isLive()" ")"
); do { MOZ_CrashSequence(__null, 1213); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1214 *mKeyHash = Entry::sFreeKey;
1215 mEntry->destroyStoredT();
1216 }
1217
1218 void clear() {
1219 if (isLive()) {
1220 mEntry->destroyStoredT();
1221 }
1222 MOZ_MAKE_MEM_UNDEFINED(mEntry, sizeof(*mEntry))do { } while (0);
1223 *mKeyHash = Entry::sFreeKey;
1224 }
1225
1226 bool isRemoved() const { return *mKeyHash == Entry::sRemovedKey; }
1227
1228 void removeLive() {
1229 MOZ_ASSERT(isLive())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isLive())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isLive()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isLive()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1229); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isLive()" ")"
); do { MOZ_CrashSequence(__null, 1229); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1230 *mKeyHash = Entry::sRemovedKey;
1231 mEntry->destroyStoredT();
1232 }
1233
1234 bool isLive() const { return isLiveHash(*mKeyHash); }
1235
1236 void setCollision() {
1237 MOZ_ASSERT(isLive())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isLive())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isLive()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isLive()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1237); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isLive()" ")"
); do { MOZ_CrashSequence(__null, 1237); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1238 *mKeyHash |= Entry::sCollisionBit;
1239 }
1240 void unsetCollision() { *mKeyHash &= ~Entry::sCollisionBit; }
1241 bool hasCollision() const { return *mKeyHash & Entry::sCollisionBit; }
1242 bool matchHash(HashNumber hn) {
1243 return (*mKeyHash & ~Entry::sCollisionBit) == hn;
1244 }
1245 HashNumber getKeyHash() const { return *mKeyHash & ~Entry::sCollisionBit; }
1246
1247 template <typename... Args>
1248 void setLive(HashNumber aHashNumber, Args&&... aArgs) {
1249 MOZ_ASSERT(!isLive())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!isLive())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!isLive()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!isLive()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1249); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!isLive()" ")"
); do { MOZ_CrashSequence(__null, 1249); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1250 *mKeyHash = aHashNumber;
1251 new (KnownNotNull, mEntry->valuePtr()) T(std::forward<Args>(aArgs)...);
1252 MOZ_ASSERT(isLive())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isLive())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isLive()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isLive()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1252); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isLive()" ")"
); do { MOZ_CrashSequence(__null, 1252); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1253 }
1254
1255 Entry* toEntry() const { return mEntry; }
1256};
1257
1258template <class T, class HashPolicy, class AllocPolicy>
1259class MOZ_STANDALONE_DEBUG[[clang::standalone_debug]] HashTable : private AllocPolicy {
1260 friend class mozilla::ReentrancyGuard;
1261
1262 using NonConstT = std::remove_const_t<T>;
1263 using Key = typename HashPolicy::KeyType;
1264 using Lookup = typename HashPolicy::Lookup;
1265
1266 public:
1267 using Entry = HashTableEntry<T>;
1268 using Slot = EntrySlot<T>;
1269
1270 template <typename F>
1271 static void forEachSlot(char* aTable, uint32_t aCapacity, F&& f) {
1272 auto hashes = reinterpret_cast<HashNumber*>(aTable);
1273 auto entries = reinterpret_cast<Entry*>(&hashes[aCapacity]);
1274 Slot slot(entries, hashes);
1275 for (size_t i = 0; i < size_t(aCapacity); ++i) {
1276 f(slot);
1277 ++slot;
1278 }
1279 }
1280
1281 // A nullable pointer to a hash table element. A Ptr |p| can be tested
1282 // either explicitly |if (p.found()) p->...| or using boolean conversion
1283 // |if (p) p->...|. Ptr objects must not be used after any mutating hash
1284 // table operations unless |generation()| is tested.
1285 class Ptr {
1286 friend class HashTable;
1287
1288 Slot mSlot;
1289#ifdef DEBUG1
1290 const HashTable* mTable;
1291 Generation mGeneration;
1292#endif
1293
1294 protected:
1295 Ptr(Slot aSlot, const HashTable& aTable)
1296 : mSlot(aSlot)
1297#ifdef DEBUG1
1298 ,
1299 mTable(&aTable),
1300 mGeneration(aTable.generation())
1301#endif
1302 {
1303 }
1304
1305 // This constructor is used only by AddPtr() within lookupForAdd().
1306 explicit Ptr(const HashTable& aTable)
1307 : mSlot(nullptr, nullptr)
1308#ifdef DEBUG1
1309 ,
1310 mTable(&aTable),
1311 mGeneration(aTable.generation())
1312#endif
1313 {
1314 }
1315
1316 bool isValid() const { return !!mSlot.toEntry(); }
1317
1318 public:
1319 Ptr()
1320 : mSlot(nullptr, nullptr)
1321#ifdef DEBUG1
1322 ,
1323 mTable(nullptr),
9
Null pointer value stored to 'p.mTable'
1324 mGeneration(0)
1325#endif
1326 {
1327 }
1328
1329 bool found() const {
1330 if (!isValid()) {
1331 return false;
1332 }
1333#ifdef DEBUG1
1334 MOZ_ASSERT(mGeneration == mTable->generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mGeneration == mTable->generation())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mGeneration == mTable->generation()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mGeneration == mTable->generation()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1334); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mGeneration == mTable->generation()"
")"); do { MOZ_CrashSequence(__null, 1334); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1335#endif
1336 return mSlot.isLive();
1337 }
1338
1339 explicit operator bool() const { return found(); }
1340
1341 bool operator==(const Ptr& aRhs) const {
1342 MOZ_ASSERT(found() && aRhs.found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(found() && aRhs.found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(found() && aRhs.found
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("found() && aRhs.found()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1342); AnnotateMozCrashReason("MOZ_ASSERT" "(" "found() && aRhs.found()"
")"); do { MOZ_CrashSequence(__null, 1342); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1343 return mSlot == aRhs.mSlot;
1344 }
1345
1346 bool operator!=(const Ptr& aRhs) const {
1347#ifdef DEBUG1
1348 MOZ_ASSERT(mGeneration == mTable->generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mGeneration == mTable->generation())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mGeneration == mTable->generation()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mGeneration == mTable->generation()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1348); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mGeneration == mTable->generation()"
")"); do { MOZ_CrashSequence(__null, 1348); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1349#endif
1350 return !(*this == aRhs);
1351 }
1352
1353 T& operator*() const {
1354#ifdef DEBUG1
1355 MOZ_ASSERT(found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(found()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("found()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1355); AnnotateMozCrashReason("MOZ_ASSERT" "(" "found()" ")"
); do { MOZ_CrashSequence(__null, 1355); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
17
Assuming the condition is false
18
Taking false branch
19
Loop condition is false. Exiting loop
1356 MOZ_ASSERT(mGeneration == mTable->generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mGeneration == mTable->generation())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mGeneration == mTable->generation()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mGeneration == mTable->generation()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1356); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mGeneration == mTable->generation()"
")"); do { MOZ_CrashSequence(__null, 1356); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
20
Called C++ object pointer is null
1357#endif
1358 return mSlot.get();
1359 }
1360
1361 T* operator->() const {
1362#ifdef DEBUG1
1363 MOZ_ASSERT(found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(found()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("found()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1363); AnnotateMozCrashReason("MOZ_ASSERT" "(" "found()" ")"
); do { MOZ_CrashSequence(__null, 1363); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1364 MOZ_ASSERT(mGeneration == mTable->generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mGeneration == mTable->generation())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mGeneration == mTable->generation()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mGeneration == mTable->generation()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1364); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mGeneration == mTable->generation()"
")"); do { MOZ_CrashSequence(__null, 1364); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1365#endif
1366 return &mSlot.get();
1367 }
1368 };
1369
1370 // A Ptr that can be used to add a key after a failed lookup.
1371 class AddPtr : public Ptr {
1372 friend class HashTable;
1373
1374 HashNumber mKeyHash;
1375#ifdef DEBUG1
1376 uint64_t mMutationCount;
1377#endif
1378
1379 AddPtr(Slot aSlot, const HashTable& aTable, HashNumber aHashNumber)
1380 : Ptr(aSlot, aTable),
1381 mKeyHash(aHashNumber)
1382#ifdef DEBUG1
1383 ,
1384 mMutationCount(aTable.mMutationCount)
1385#endif
1386 {
1387 }
1388
1389 // This constructor is used when lookupForAdd() is performed on a table
1390 // lacking entry storage; it leaves mSlot null but initializes everything
1391 // else.
1392 AddPtr(const HashTable& aTable, HashNumber aHashNumber)
1393 : Ptr(aTable),
1394 mKeyHash(aHashNumber)
1395#ifdef DEBUG1
1396 ,
1397 mMutationCount(aTable.mMutationCount)
1398#endif
1399 {
1400 MOZ_ASSERT(isLive())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isLive())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isLive()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isLive()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1400); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isLive()" ")"
); do { MOZ_CrashSequence(__null, 1400); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1401 }
1402
1403 bool isLive() const { return isLiveHash(mKeyHash); }
1404
1405 public:
1406 AddPtr() : mKeyHash(0) {}
1407 };
1408
1409 // A hash table iterator that (mostly) doesn't allow table modifications.
1410 // As with Ptr/AddPtr, Iterator objects must not be used after any mutating
1411 // hash table operation unless the |generation()| is tested.
1412 class Iterator {
1413 void moveToNextLiveEntry() {
1414 while (++mCur < mEnd && !mCur.isLive()) {
1415 continue;
1416 }
1417 }
1418
1419 protected:
1420 friend class HashTable;
1421
1422 explicit Iterator(const HashTable& aTable)
1423 : mCur(aTable.slotForIndex(0)),
1424 mEnd(aTable.slotForIndex(aTable.capacity()))
1425#ifdef DEBUG1
1426 ,
1427 mTable(aTable),
1428 mMutationCount(aTable.mMutationCount),
1429 mGeneration(aTable.generation()),
1430 mValidEntry(true)
1431#endif
1432 {
1433 if (!done() && !mCur.isLive()) {
1434 moveToNextLiveEntry();
1435 }
1436 }
1437
1438 Slot mCur;
1439 Slot mEnd;
1440#ifdef DEBUG1
1441 const HashTable& mTable;
1442 uint64_t mMutationCount;
1443 Generation mGeneration;
1444 bool mValidEntry;
1445#endif
1446
1447 public:
1448 bool done() const {
1449 MOZ_ASSERT(mGeneration == mTable.generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mGeneration == mTable.generation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mGeneration == mTable.generation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mGeneration == mTable.generation()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1449); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mGeneration == mTable.generation()"
")"); do { MOZ_CrashSequence(__null, 1449); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1450 MOZ_ASSERT(mMutationCount == mTable.mMutationCount)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mMutationCount == mTable.mMutationCount)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mMutationCount == mTable.mMutationCount))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mMutationCount == mTable.mMutationCount"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1450); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mMutationCount == mTable.mMutationCount"
")"); do { MOZ_CrashSequence(__null, 1450); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1451 return mCur == mEnd;
1452 }
1453
1454 T& get() const {
1455 MOZ_ASSERT(!done())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!done())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!done()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!done()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1455); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!done()" ")"
); do { MOZ_CrashSequence(__null, 1455); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1456 MOZ_ASSERT(mValidEntry)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mValidEntry)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mValidEntry))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("mValidEntry", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1456); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mValidEntry"
")"); do { MOZ_CrashSequence(__null, 1456); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1457 MOZ_ASSERT(mGeneration == mTable.generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mGeneration == mTable.generation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mGeneration == mTable.generation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mGeneration == mTable.generation()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1457); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mGeneration == mTable.generation()"
")"); do { MOZ_CrashSequence(__null, 1457); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1458 MOZ_ASSERT(mMutationCount == mTable.mMutationCount)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mMutationCount == mTable.mMutationCount)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mMutationCount == mTable.mMutationCount))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mMutationCount == mTable.mMutationCount"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1458); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mMutationCount == mTable.mMutationCount"
")"); do { MOZ_CrashSequence(__null, 1458); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1459 return mCur.get();
1460 }
1461
1462 void next() {
1463 MOZ_ASSERT(!done())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!done())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!done()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!done()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1463); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!done()" ")"
); do { MOZ_CrashSequence(__null, 1463); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1464 MOZ_ASSERT(mGeneration == mTable.generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mGeneration == mTable.generation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mGeneration == mTable.generation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mGeneration == mTable.generation()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1464); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mGeneration == mTable.generation()"
")"); do { MOZ_CrashSequence(__null, 1464); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1465 MOZ_ASSERT(mMutationCount == mTable.mMutationCount)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mMutationCount == mTable.mMutationCount)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mMutationCount == mTable.mMutationCount))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mMutationCount == mTable.mMutationCount"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1465); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mMutationCount == mTable.mMutationCount"
")"); do { MOZ_CrashSequence(__null, 1465); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1466 moveToNextLiveEntry();
1467#ifdef DEBUG1
1468 mValidEntry = true;
1469#endif
1470 }
1471 };
1472
1473 // A hash table iterator that permits modification, removal and rekeying.
1474 // Since rehashing when elements were removed during iteration would be
1475 // bad, it is postponed until the ModIterator is destructed. Since the
1476 // ModIterator's destructor touches the hash table, the user must ensure
1477 // that the hash table is still alive when the destructor runs.
1478 class ModIterator : public Iterator {
1479 friend class HashTable;
1480
1481 HashTable& mTable;
1482 bool mRekeyed;
1483 bool mRemoved;
1484
1485 // ModIterator is movable but not copyable.
1486 ModIterator(const ModIterator&) = delete;
1487 void operator=(const ModIterator&) = delete;
1488
1489 protected:
1490 explicit ModIterator(HashTable& aTable)
1491 : Iterator(aTable), mTable(aTable), mRekeyed(false), mRemoved(false) {}
1492
1493 public:
1494 MOZ_IMPLICIT ModIterator(ModIterator&& aOther)
1495 : Iterator(aOther),
1496 mTable(aOther.mTable),
1497 mRekeyed(aOther.mRekeyed),
1498 mRemoved(aOther.mRemoved) {
1499 aOther.mRekeyed = false;
1500 aOther.mRemoved = false;
1501 }
1502
1503 // Removes the current element from the table, leaving |get()| invalid until
1504 // the next call to |next()|.
1505 //
1506 // See the comments on ~ModIterator about table resizing after removing
1507 // entries.
1508 void remove() {
1509 mTable.remove(this->mCur);
1510 mRemoved = true;
1511#ifdef DEBUG1
1512 this->mValidEntry = false;
1513 this->mMutationCount = mTable.mMutationCount;
1514#endif
1515 }
1516
1517 NonConstT& getMutable() {
1518 MOZ_ASSERT(!this->done())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!this->done())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!this->done()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!this->done()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1518); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!this->done()"
")"); do { MOZ_CrashSequence(__null, 1518); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1519 MOZ_ASSERT(this->mValidEntry)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(this->mValidEntry)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(this->mValidEntry))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("this->mValidEntry"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1519); AnnotateMozCrashReason("MOZ_ASSERT" "(" "this->mValidEntry"
")"); do { MOZ_CrashSequence(__null, 1519); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1520 MOZ_ASSERT(this->mGeneration == this->Iterator::mTable.generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(this->mGeneration == this->Iterator::mTable.generation
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(this->mGeneration == this->Iterator::mTable.generation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("this->mGeneration == this->Iterator::mTable.generation()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1520); AnnotateMozCrashReason("MOZ_ASSERT" "(" "this->mGeneration == this->Iterator::mTable.generation()"
")"); do { MOZ_CrashSequence(__null, 1520); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1521 MOZ_ASSERT(this->mMutationCount == this->Iterator::mTable.mMutationCount)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(this->mMutationCount == this->Iterator::mTable
.mMutationCount)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(this->mMutationCount == this
->Iterator::mTable.mMutationCount))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("this->mMutationCount == this->Iterator::mTable.mMutationCount"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1521); AnnotateMozCrashReason("MOZ_ASSERT" "(" "this->mMutationCount == this->Iterator::mTable.mMutationCount"
")"); do { MOZ_CrashSequence(__null, 1521); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1522 return this->mCur.getMutable();
1523 }
1524
1525 // Removes the current element and re-inserts it into the table with
1526 // a new key at the new Lookup position. |get()| is invalid after
1527 // this operation until the next call to |next()|.
1528 template <typename KeyInput>
1529 void rekey(const Lookup& l, KeyInput&& k) {
1530 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
())))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
()))))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
" (" "Don't pass a reference into the table here" ")", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1533); AnnotateMozCrashReason("MOZ_ASSERT" "(" "static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
") (" "Don't pass a reference into the table here" ")"); do {
MOZ_CrashSequence(__null, 1533); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
1531 static_cast<const void*>(&k) !=do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
())))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
()))))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
" (" "Don't pass a reference into the table here" ")", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1533); AnnotateMozCrashReason("MOZ_ASSERT" "(" "static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
") (" "Don't pass a reference into the table here" ")"); do {
MOZ_CrashSequence(__null, 1533); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
1532 static_cast<const void*>(&HashPolicy::getKey(this->mCur.get())),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
())))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
()))))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
" (" "Don't pass a reference into the table here" ")", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1533); AnnotateMozCrashReason("MOZ_ASSERT" "(" "static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
") (" "Don't pass a reference into the table here" ")"); do {
MOZ_CrashSequence(__null, 1533); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
1533 "Don't pass a reference into the table here")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
())))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(static_cast<const void*>(&k) != static_cast
<const void*>(&HashPolicy::getKey(this->mCur.get
()))))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
" (" "Don't pass a reference into the table here" ")", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1533); AnnotateMozCrashReason("MOZ_ASSERT" "(" "static_cast<const void*>(&k) != static_cast<const void*>(&HashPolicy::getKey(this->mCur.get()))"
") (" "Don't pass a reference into the table here" ")"); do {
MOZ_CrashSequence(__null, 1533); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
1534 Ptr p(this->mCur, mTable);
1535 mTable.rekeyWithoutRehash(p, l, std::forward<KeyInput>(k));
1536 mRekeyed = true;
1537#ifdef DEBUG1
1538 this->mValidEntry = false;
1539 this->mMutationCount = mTable.mMutationCount;
1540#endif
1541 }
1542
1543 void rekey(const Lookup& l) { rekey(l, l); }
1544
1545 // This can rehash the table or resize it if entries were removed.
1546 //
1547 // This does not go as far as freeing the table if it is now empty, as that
1548 // can lead to repeatedly allocating and freeing the table when a small
1549 // number of entries are repeatedly added and removed. If callers require
1550 // memory to be minimised after removing entries they should call compact().
1551 ~ModIterator() {
1552 if (mRekeyed) {
1553 mTable.incrementGeneration();
1554 mTable.infallibleRehashIfOverloaded();
1555 }
1556
1557 if (mRemoved) {
1558 mTable.shrinkToBestCapacity();
1559 }
1560 }
1561 };
1562
1563 // HashTable is movable
1564 HashTable(HashTable&& aRhs) : AllocPolicy(std::move(aRhs)) { moveFrom(aRhs); }
1565 HashTable& operator=(HashTable&& aRhs) {
1566 MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(this != &aRhs)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(this != &aRhs))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("this != &aRhs"
" (" "self-move assignment is prohibited" ")", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1566); AnnotateMozCrashReason("MOZ_ASSERT" "(" "this != &aRhs"
") (" "self-move assignment is prohibited" ")"); do { MOZ_CrashSequence
(__null, 1566); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1567 if (mTable) {
1568 destroyTable(*this, mTable, capacity());
1569 }
1570 AllocPolicy::operator=(std::move(aRhs));
1571 moveFrom(aRhs);
1572 return *this;
1573 }
1574
1575 void swap(HashTable& aOther) {
1576 ReentrancyGuard g1(*this);
1577 ReentrancyGuard g2(aOther);
1578
1579 std::swap(mGenAndHashShift, aOther.mGenAndHashShift);
1580 std::swap(mTable, aOther.mTable);
1581 std::swap(mEntryCount, aOther.mEntryCount);
1582 std::swap(mRemovedCount, aOther.mRemovedCount);
1583#ifdef DEBUG1
1584 std::swap(mMutationCount, aOther.mMutationCount);
1585 std::swap(mEntered, aOther.mEntered);
1586#endif
1587 }
1588
1589 AllocPolicy& allocPolicy() { return *this; }
1590 const AllocPolicy& allocPolicy() const { return *this; }
1591
1592 template <typename F>
1593 void traceOwnedAllocs(F&& aTraceFunc) {
1594 if (mTable) {
1595 aTraceFunc(&mTable);
1596 }
1597 }
1598
1599 private:
1600 void moveFrom(HashTable& aRhs) {
1601 mGenAndHashShift = aRhs.mGenAndHashShift;
1602 mTable = aRhs.mTable;
1603 mEntryCount = aRhs.mEntryCount;
1604 mRemovedCount = aRhs.mRemovedCount;
1605#ifdef DEBUG1
1606 mMutationCount = aRhs.mMutationCount;
1607 mEntered = aRhs.mEntered;
1608#endif
1609 aRhs.mTable = nullptr;
1610 aRhs.clearAndCompact();
1611 }
1612
1613 // HashTable is not copyable or assignable
1614 HashTable(const HashTable&) = delete;
1615 void operator=(const HashTable&) = delete;
1616
1617 static const uint32_t CAP_BITS = 30;
1618
1619 public:
1620 uint64_t mGenAndHashShift; // entry storage generation number (56 bits)
1621 // and multiplicative hash shift (8 bits)
1622 char* mTable; // entry storage
1623 uint32_t mEntryCount; // number of entries in mTable
1624 uint32_t mRemovedCount; // removed entry sentinels in mTable
1625
1626#ifdef DEBUG1
1627 uint64_t mMutationCount;
1628 mutable bool mEntered;
1629#endif
1630
1631 // The default initial capacity is 32 (enough to hold 16 elements), but it
1632 // can be as low as 4.
1633 static const uint32_t sDefaultLen = 16;
1634 static const uint32_t sMinCapacity = 4;
1635 // See the comments in HashTableEntry about this value.
1636 static_assert(sMinCapacity >= 4, "too-small sMinCapacity breaks assumptions");
1637 static const uint32_t sMaxInit = 1u << (CAP_BITS - 1);
1638 static const uint32_t sMaxCapacity = 1u << CAP_BITS;
1639
1640 // Hash-table alpha is conceptually a fraction, but to avoid floating-point
1641 // math we implement it as a ratio of integers.
1642 static const uint8_t sAlphaDenominator = 4;
1643 static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4
1644 static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4
1645
1646 static const HashNumber sFreeKey = Entry::sFreeKey;
1647 static const HashNumber sRemovedKey = Entry::sRemovedKey;
1648 static const HashNumber sCollisionBit = Entry::sCollisionBit;
1649
1650 static const uint64_t sHashShiftBits = 8;
1651 static const uint64_t sHashShiftMask = (1 << sHashShiftBits) - 1;
1652 static const uint64_t sGenerationShift = sHashShiftBits;
1653
1654 MOZ_ALWAYS_INLINEinline uint8_t hashShift() const {
1655 return uint8_t(mGenAndHashShift & sHashShiftMask);
1656 }
1657 MOZ_ALWAYS_INLINEinline uint64_t gen() const {
1658 return mGenAndHashShift >> sGenerationShift;
1659 }
1660
1661 private:
1662 void setGenAndHashShift(uint64_t aGeneration, uint8_t aHashShift) {
1663 mGenAndHashShift = aGeneration << sGenerationShift | aHashShift;
1664 }
1665
1666 public:
1667 void incrementGeneration() { setGenAndHashShift(gen() + 1, hashShift()); }
1668 void setHashShift(uint32_t aHashShift) {
1669 MOZ_ASSERT((aHashShift & sHashShiftMask) == aHashShift)do { static_assert( mozilla::detail::AssertionConditionType<
decltype((aHashShift & sHashShiftMask) == aHashShift)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!((aHashShift & sHashShiftMask) == aHashShift))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("(aHashShift & sHashShiftMask) == aHashShift"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1669); AnnotateMozCrashReason("MOZ_ASSERT" "(" "(aHashShift & sHashShiftMask) == aHashShift"
")"); do { MOZ_CrashSequence(__null, 1669); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1670 mGenAndHashShift = (mGenAndHashShift & ~sHashShiftMask) | aHashShift;
1671 }
1672
1673 constexpr static uint32_t bestCapacity(uint32_t aLen) {
1674 static_assert(
1675 (sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit,
1676 "multiplication in numerator below could overflow");
1677 static_assert(
1678 sMaxInit * sAlphaDenominator <= UINT32_MAX(4294967295U) - sMaxAlphaNumerator,
1679 "numerator calculation below could potentially overflow");
1680
1681 // Callers should ensure this is true.
1682 MOZ_ASSERT(aLen <= sMaxInit)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aLen <= sMaxInit)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aLen <= sMaxInit))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("aLen <= sMaxInit"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1682); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aLen <= sMaxInit"
")"); do { MOZ_CrashSequence(__null, 1682); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1683
1684 // Compute the smallest capacity allowing |aLen| elements to be
1685 // inserted without rehashing: ceil(aLen / max-alpha). (Ceiling
1686 // integral division: <http://stackoverflow.com/a/2745086>.)
1687 uint32_t capacity = (aLen * sAlphaDenominator + sMaxAlphaNumerator - 1) /
1688 sMaxAlphaNumerator;
1689 capacity = (capacity < sMinCapacity) ? sMinCapacity : RoundUpPow2(capacity);
1690
1691 MOZ_ASSERT(capacity >= aLen)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(capacity >= aLen)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(capacity >= aLen))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("capacity >= aLen"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1691); AnnotateMozCrashReason("MOZ_ASSERT" "(" "capacity >= aLen"
")"); do { MOZ_CrashSequence(__null, 1691); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1692 MOZ_ASSERT(capacity <= sMaxCapacity)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(capacity <= sMaxCapacity)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(capacity <= sMaxCapacity)
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("capacity <= sMaxCapacity"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1692); AnnotateMozCrashReason("MOZ_ASSERT" "(" "capacity <= sMaxCapacity"
")"); do { MOZ_CrashSequence(__null, 1692); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1693
1694 return capacity;
1695 }
1696
1697 constexpr static uint32_t hashShiftForLength(uint32_t aLen) {
1698 // Reject all lengths whose initial computed capacity would exceed
1699 // sMaxCapacity. Round that maximum aLen down to the nearest power of two
1700 // for speedier code.
1701 if (MOZ_UNLIKELY(aLen > sMaxInit)(__builtin_expect(!!(aLen > sMaxInit), 0))) {
1702 MOZ_CRASH("initial length is too large")do { do { } while (false); MOZ_ReportCrash("" "initial length is too large"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1702); AnnotateMozCrashReason("MOZ_CRASH(" "initial length is too large"
")"); do { MOZ_CrashSequence(__null, 1702); __attribute__((nomerge
)) ::abort(); } while (false); } while (false)
;
1703 }
1704
1705 return kHashNumberBits - mozilla::CeilingLog2(bestCapacity(aLen));
1706 }
1707
1708 static bool isLiveHash(HashNumber aHash) { return Entry::isLiveHash(aHash); }
1709
1710 static HashNumber prepareHash(HashNumber aInputHash) {
1711 HashNumber keyHash = ScrambleHashCode(aInputHash);
1712
1713 // Avoid reserved hash codes.
1714 if (!isLiveHash(keyHash)) {
1715 keyHash -= (sRemovedKey + 1);
1716 }
1717 return keyHash & ~sCollisionBit;
1718 }
1719
1720 enum FailureBehavior { DontReportFailure = false, ReportFailure = true };
1721
1722 // Fake a struct that we're going to alloc. See the comments in
1723 // HashTableEntry about how the table is laid out, and why it's safe.
1724 struct FakeSlot {
1725 unsigned char c[sizeof(HashNumber) + sizeof(typename Entry::NonConstT)];
1726 };
1727
1728 static char* createTable(AllocPolicy& aAllocPolicy, uint32_t aCapacity,
1729 FailureBehavior aReportFailure = ReportFailure) {
1730 FakeSlot* fake =
1731 aReportFailure
1732 ? aAllocPolicy.template pod_malloc<FakeSlot>(aCapacity)
1733 : aAllocPolicy.template maybe_pod_malloc<FakeSlot>(aCapacity);
1734
1735 MOZ_ASSERT((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment
) == 0)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment
) == 0))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("(reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) == 0"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1736); AnnotateMozCrashReason("MOZ_ASSERT" "(" "(reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) == 0"
")"); do { MOZ_CrashSequence(__null, 1736); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1736 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment
) == 0)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment
) == 0))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("(reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) == 0"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1736); AnnotateMozCrashReason("MOZ_ASSERT" "(" "(reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) == 0"
")"); do { MOZ_CrashSequence(__null, 1736); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1737
1738 char* table = reinterpret_cast<char*>(fake);
1739 if (table) {
1740 forEachSlot(table, aCapacity, [&](Slot& slot) {
1741 *slot.mKeyHash = sFreeKey;
1742 new (KnownNotNull, slot.toEntry()) Entry();
1743 });
1744 }
1745 return table;
1746 }
1747
1748 static void destroyTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1749 uint32_t aCapacity) {
1750 forEachSlot(aOldTable, aCapacity, [&](const Slot& slot) {
1751 if (slot.isLive()) {
1752 slot.toEntry()->destroyStoredT();
1753 }
1754 });
1755 freeTable(aAllocPolicy, aOldTable, aCapacity);
1756 }
1757
1758 static void freeTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1759 uint32_t aCapacity) {
1760 FakeSlot* fake = reinterpret_cast<FakeSlot*>(aOldTable);
1761 aAllocPolicy.free_(fake, aCapacity);
1762 }
1763
1764 public:
1765 constexpr HashTable(AllocPolicy aAllocPolicy, uint32_t aLen)
1766 : AllocPolicy(std::move(aAllocPolicy)),
1767 mGenAndHashShift(hashShiftForLength(aLen)),
1768 mTable(nullptr),
1769 mEntryCount(0),
1770 mRemovedCount(0)
1771#ifdef DEBUG1
1772 ,
1773 mMutationCount(0),
1774 mEntered(false)
1775#endif
1776 {
1777 }
1778
1779 explicit HashTable(AllocPolicy aAllocPolicy)
1780 : HashTable(aAllocPolicy, sDefaultLen) {}
1781
1782 ~HashTable() {
1783 if (mTable) {
1784 destroyTable(*this, mTable, capacity());
1785 }
1786 }
1787
1788 private:
1789 HashNumber hash1(HashNumber aHash0) const { return aHash0 >> hashShift(); }
1790
1791 struct DoubleHash {
1792 HashNumber mHash2;
1793 HashNumber mSizeMask;
1794 };
1795
1796 DoubleHash hash2(HashNumber aCurKeyHash) const {
1797 uint32_t sizeLog2 = kHashNumberBits - hashShift();
1798 DoubleHash dh = {((aCurKeyHash << sizeLog2) >> hashShift()) | 1,
1799 (HashNumber(1) << sizeLog2) - 1};
1800 return dh;
1801 }
1802
1803 static HashNumber applyDoubleHash(HashNumber aHash1,
1804 const DoubleHash& aDoubleHash) {
1805 return WrappingSubtract(aHash1, aDoubleHash.mHash2) & aDoubleHash.mSizeMask;
1806 }
1807
1808 static MOZ_ALWAYS_INLINEinline bool match(T& aEntry, const Lookup& aLookup) {
1809 return HashPolicy::match(HashPolicy::getKey(aEntry), aLookup);
1810 }
1811
1812 enum LookupReason { ForNonAdd, ForAdd };
1813
1814 Slot slotForIndex(HashNumber aIndex) const {
1815 auto hashes = reinterpret_cast<HashNumber*>(mTable);
1816 auto entries = reinterpret_cast<Entry*>(&hashes[capacity()]);
1817 return Slot(&entries[aIndex], &hashes[aIndex]);
1818 }
1819
1820 // Warning: in order for readonlyThreadsafeLookup() to be safe this
1821 // function must not modify the table in any way when Reason==ForNonAdd.
1822 template <LookupReason Reason>
1823 MOZ_ALWAYS_INLINEinline Slot lookup(const Lookup& aLookup,
1824 HashNumber aKeyHash) const {
1825 MOZ_ASSERT(isLiveHash(aKeyHash))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isLiveHash(aKeyHash))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isLiveHash(aKeyHash)))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("isLiveHash(aKeyHash)"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1825); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isLiveHash(aKeyHash)"
")"); do { MOZ_CrashSequence(__null, 1825); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1826 MOZ_ASSERT(!(aKeyHash & sCollisionBit))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!(aKeyHash & sCollisionBit))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!(aKeyHash & sCollisionBit
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!(aKeyHash & sCollisionBit)", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1826); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!(aKeyHash & sCollisionBit)"
")"); do { MOZ_CrashSequence(__null, 1826); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1827 MOZ_ASSERT(mTable)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mTable)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(mTable))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mTable", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1827); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mTable" ")"
); do { MOZ_CrashSequence(__null, 1827); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1828
1829 // Compute the primary hash address.
1830 HashNumber h1 = hash1(aKeyHash);
1831 Slot slot = slotForIndex(h1);
1832
1833 // Miss: return space for a new entry.
1834 if (slot.isFree()) {
1835 return slot;
1836 }
1837
1838 // Hit: return entry.
1839 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1840 return slot;
1841 }
1842
1843 // Collision: double hash.
1844 DoubleHash dh = hash2(aKeyHash);
1845
1846 // Save the first removed entry pointer so we can recycle later.
1847 Maybe<Slot> firstRemoved;
1848
1849 while (true) {
1850 if (Reason == ForAdd && !firstRemoved) {
1851 if (MOZ_UNLIKELY(slot.isRemoved())(__builtin_expect(!!(slot.isRemoved()), 0))) {
1852 firstRemoved.emplace(slot);
1853 } else {
1854 slot.setCollision();
1855 }
1856 }
1857
1858 h1 = applyDoubleHash(h1, dh);
1859
1860 slot = slotForIndex(h1);
1861 if (slot.isFree()) {
1862 return firstRemoved.refOr(slot);
1863 }
1864
1865 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1866 return slot;
1867 }
1868 }
1869 }
1870
1871 // This is a copy of lookup() hardcoded to the assumptions:
1872 // 1. the lookup is for an add;
1873 // 2. the key, whose |keyHash| has been passed, is not in the table.
1874 Slot findNonLiveSlot(HashNumber aKeyHash) {
1875 MOZ_ASSERT(!(aKeyHash & sCollisionBit))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!(aKeyHash & sCollisionBit))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!(aKeyHash & sCollisionBit
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!(aKeyHash & sCollisionBit)", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1875); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!(aKeyHash & sCollisionBit)"
")"); do { MOZ_CrashSequence(__null, 1875); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1876 MOZ_ASSERT(mTable)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mTable)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(mTable))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mTable", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1876); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mTable" ")"
); do { MOZ_CrashSequence(__null, 1876); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1877
1878 // We assume 'aKeyHash' has already been distributed.
1879
1880 // Compute the primary hash address.
1881 HashNumber h1 = hash1(aKeyHash);
1882 Slot slot = slotForIndex(h1);
1883
1884 // Miss: return space for a new entry.
1885 if (!slot.isLive()) {
1886 return slot;
1887 }
1888
1889 // Collision: double hash.
1890 DoubleHash dh = hash2(aKeyHash);
1891
1892 while (true) {
1893 slot.setCollision();
1894
1895 h1 = applyDoubleHash(h1, dh);
1896
1897 slot = slotForIndex(h1);
1898 if (!slot.isLive()) {
1899 return slot;
1900 }
1901 }
1902 }
1903
1904 enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed };
1905
1906 RebuildStatus changeTableSize(
1907 uint32_t newCapacity, FailureBehavior aReportFailure = ReportFailure) {
1908 MOZ_ASSERT(std::has_single_bit(newCapacity))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(std::has_single_bit(newCapacity))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(std::has_single_bit(newCapacity
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("std::has_single_bit(newCapacity)", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1908); AnnotateMozCrashReason("MOZ_ASSERT" "(" "std::has_single_bit(newCapacity)"
")"); do { MOZ_CrashSequence(__null, 1908); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1909 MOZ_ASSERT(!!mTable == !!capacity())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!!mTable == !!capacity())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!!mTable == !!capacity()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("!!mTable == !!capacity()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1909); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!!mTable == !!capacity()"
")"); do { MOZ_CrashSequence(__null, 1909); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1910
1911 // Look, but don't touch, until we succeed in getting new entry store.
1912 char* oldTable = mTable;
1913 uint32_t oldCapacity = capacity();
1914 uint32_t newLog2 = mozilla::CeilingLog2(newCapacity);
1915
1916 if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)(__builtin_expect(!!(newCapacity > sMaxCapacity), 0))) {
1917 if (aReportFailure) {
1918 this->reportAllocOverflow();
1919 }
1920 return RehashFailed;
1921 }
1922
1923 char* newTable = createTable(*this, newCapacity, aReportFailure);
1924 if (!newTable) {
1925 return RehashFailed;
1926 }
1927
1928 // We can't fail from here on, so update table parameters.
1929 mRemovedCount = 0;
1930 incrementGeneration();
1931 setHashShift(kHashNumberBits - newLog2);
1932 mTable = newTable;
1933
1934 // Copy only live entries, leaving removed ones behind.
1935 forEachSlot(oldTable, oldCapacity, [&](Slot& slot) {
1936 if (slot.isLive()) {
1937 HashNumber hn = slot.getKeyHash();
1938 findNonLiveSlot(hn).setLive(
1939 hn, std::move(const_cast<typename Entry::NonConstT&>(slot.get())));
1940 }
1941
1942 slot.clear();
1943 });
1944
1945 // All entries have been destroyed, no need to destroyTable.
1946 freeTable(*this, oldTable, oldCapacity);
1947 return Rehashed;
1948 }
1949
1950 RebuildStatus rehashIfOverloaded(
1951 FailureBehavior aReportFailure = ReportFailure) {
1952 static_assert(sMaxCapacity <= UINT32_MAX(4294967295U) / sMaxAlphaNumerator,
1953 "multiplication below could overflow");
1954
1955 // Note: if capacity() is zero, this will always succeed, which is
1956 // what we want.
1957 bool overloaded = mEntryCount + mRemovedCount >=
1958 capacity() * sMaxAlphaNumerator / sAlphaDenominator;
1959
1960 if (!overloaded) {
1961 return NotOverloaded;
1962 }
1963
1964 // Succeed if a quarter or more of all entries are removed. Note that this
1965 // always succeeds if capacity() == 0 (i.e. entry storage has not been
1966 // allocated), which is what we want, because it means changeTableSize()
1967 // will allocate the requested capacity rather than doubling it.
1968 bool manyRemoved = mRemovedCount >= (capacity() >> 2);
1969 uint32_t newCapacity = manyRemoved ? rawCapacity() : rawCapacity() * 2;
1970 return changeTableSize(newCapacity, aReportFailure);
1971 }
1972
1973 void infallibleRehashIfOverloaded() {
1974 if (rehashIfOverloaded(DontReportFailure) == RehashFailed) {
1975 rehashTableInPlace();
1976 }
1977 }
1978
1979 void remove(Slot& aSlot) {
1980 MOZ_ASSERT(mTable)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mTable)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(mTable))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mTable", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 1980); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mTable" ")"
); do { MOZ_CrashSequence(__null, 1980); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1981
1982 if (aSlot.hasCollision()) {
1983 aSlot.removeLive();
1984 mRemovedCount++;
1985 } else {
1986 aSlot.clearLive();
1987 }
1988 mEntryCount--;
1989#ifdef DEBUG1
1990 mMutationCount++;
1991#endif
1992 }
1993
1994 void shrinkIfUnderloaded() {
1995 static_assert(sMaxCapacity <= UINT32_MAX(4294967295U) / sMinAlphaNumerator,
1996 "multiplication below could overflow");
1997 bool underloaded =
1998 capacity() > sMinCapacity &&
1999 mEntryCount <= capacity() * sMinAlphaNumerator / sAlphaDenominator;
2000
2001 if (underloaded) {
2002 (void)changeTableSize(capacity() / 2, DontReportFailure);
2003 }
2004 }
2005
2006 // This is identical to changeTableSize(currentSize), but without requiring
2007 // a second table. We do this by recycling the collision bits to tell us if
2008 // the element is already inserted or still waiting to be inserted. Since
2009 // already-inserted elements win any conflicts, we get the same table as we
2010 // would have gotten through random insertion order.
2011 void rehashTableInPlace() {
2012 mRemovedCount = 0;
2013 incrementGeneration();
2014 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.unsetCollision(); });
2015 for (uint32_t i = 0; i < capacity();) {
2016 Slot src = slotForIndex(i);
2017
2018 if (!src.isLive() || src.hasCollision()) {
2019 ++i;
2020 continue;
2021 }
2022
2023 HashNumber keyHash = src.getKeyHash();
2024 HashNumber h1 = hash1(keyHash);
2025 DoubleHash dh = hash2(keyHash);
2026 Slot tgt = slotForIndex(h1);
2027 while (true) {
2028 if (!tgt.hasCollision()) {
2029 src.swap(tgt);
2030 tgt.setCollision();
2031 break;
2032 }
2033
2034 h1 = applyDoubleHash(h1, dh);
2035 tgt = slotForIndex(h1);
2036 }
2037 }
2038
2039 // TODO: this algorithm leaves collision bits on *all* elements, even if
2040 // they are on no collision path. We have the option of setting the
2041 // collision bits correctly on a subsequent pass or skipping the rehash
2042 // unless we are totally filled with tombstones: benchmark to find out
2043 // which approach is best.
2044 }
2045
2046 // Prefer to use putNewInfallible; this function does not check
2047 // invariants.
2048 template <typename... Args>
2049 void putNewInfallibleInternal(HashNumber aKeyHash, Args&&... aArgs) {
2050 MOZ_ASSERT(mTable)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mTable)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(mTable))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mTable", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2050); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mTable" ")"
); do { MOZ_CrashSequence(__null, 2050); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2051
2052 Slot slot = findNonLiveSlot(aKeyHash);
2053
2054 if (slot.isRemoved()) {
2055 mRemovedCount--;
2056 aKeyHash |= sCollisionBit;
2057 }
2058
2059 slot.setLive(aKeyHash, std::forward<Args>(aArgs)...);
2060 mEntryCount++;
2061#ifdef DEBUG1
2062 mMutationCount++;
2063#endif
2064 }
2065
2066 public:
2067 void clear() {
2068 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.clear(); });
2069 mRemovedCount = 0;
2070 mEntryCount = 0;
2071#ifdef DEBUG1
2072 mMutationCount++;
2073#endif
2074 }
2075
2076 // Minimise the memory used. If there are no entries the table is freed,
2077 // otherwise the table is resized to the smallest capacity that doesn't
2078 // overload the table and that is at least sMinCapacity entries.
2079 //
2080 // Since we shrink the table after every remove, you only need to call this if
2081 // you want to free the table when it's empty.
2082 void compact() {
2083 if (empty()) {
2084 // Free the entry storage.
2085 freeTable(*this, mTable, capacity());
2086 incrementGeneration();
2087 setHashShift(
2088 hashShiftForLength(0)); // gives minimum capacity on regrowth
2089 mTable = nullptr;
2090 mRemovedCount = 0;
2091 return;
2092 }
2093
2094 shrinkToBestCapacity();
2095 }
2096
2097 void shrinkToBestCapacity() {
2098 uint32_t bestCapacity = this->bestCapacity(mEntryCount);
2099 if (bestCapacity < capacity()) {
2100 (void)changeTableSize(bestCapacity, DontReportFailure);
2101 }
2102 }
2103
2104 void clearAndCompact() {
2105 clear();
2106 compact();
2107 }
2108
2109 [[nodiscard]] bool reserve(uint32_t aLen) {
2110 if (aLen == 0) {
2111 return true;
2112 }
2113
2114 if (MOZ_UNLIKELY(aLen > sMaxInit)(__builtin_expect(!!(aLen > sMaxInit), 0))) {
2115 this->reportAllocOverflow();
2116 return false;
2117 }
2118
2119 uint32_t bestCapacity = this->bestCapacity(aLen);
2120 if (bestCapacity <= capacity()) {
2121 return true; // Capacity is already sufficient.
2122 }
2123
2124 RebuildStatus status = changeTableSize(bestCapacity, ReportFailure);
2125 MOZ_ASSERT(status != NotOverloaded)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(status != NotOverloaded)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(status != NotOverloaded))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("status != NotOverloaded"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2125); AnnotateMozCrashReason("MOZ_ASSERT" "(" "status != NotOverloaded"
")"); do { MOZ_CrashSequence(__null, 2125); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2126 return status != RehashFailed;
2127 }
2128
2129 Iterator iter() const { return Iterator(*this); }
2130
2131 ModIterator modIter() { return ModIterator(*this); }
2132
2133 bool empty() const { return mEntryCount == 0; }
2134
2135 uint32_t count() const { return mEntryCount; }
2136
2137 uint32_t rawCapacity() const { return 1u << (kHashNumberBits - hashShift()); }
2138
2139 uint32_t capacity() const { return mTable ? rawCapacity() : 0; }
2140
2141 Generation generation() const { return Generation(gen()); }
2142
2143 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
2144 return aMallocSizeOf(mTable);
2145 }
2146
2147 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
2148 return aMallocSizeOf(this) + shallowSizeOfExcludingThis(aMallocSizeOf);
2149 }
2150
2151 MOZ_ALWAYS_INLINEinline Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
2152 if (empty()) {
7
Taking true branch
2153 return Ptr();
8
Calling default constructor for 'Ptr'
10
Returning from default constructor for 'Ptr'
2154 }
2155
2156 HashNumber inputHash;
2157 if (!MaybeGetHash<HashPolicy>(aLookup, &inputHash)) {
2158 return Ptr();
2159 }
2160
2161 HashNumber keyHash = prepareHash(inputHash);
2162 return Ptr(lookup<ForNonAdd>(aLookup, keyHash), *this);
2163 }
2164
2165 MOZ_ALWAYS_INLINEinline Ptr lookup(const Lookup& aLookup) const {
2166 ReentrancyGuard g(*this);
2167 return readonlyThreadsafeLookup(aLookup);
6
Calling 'HashTable::readonlyThreadsafeLookup'
11
Returning from 'HashTable::readonlyThreadsafeLookup'
2168 }
2169
2170 MOZ_ALWAYS_INLINEinline AddPtr lookupForAdd(const Lookup& aLookup) {
2171 ReentrancyGuard g(*this);
2172
2173 HashNumber inputHash;
2174 if (!EnsureHash<HashPolicy>(aLookup, &inputHash)) {
2175 return AddPtr();
2176 }
2177
2178 HashNumber keyHash = prepareHash(inputHash);
2179
2180 if (!mTable) {
2181 return AddPtr(*this, keyHash);
2182 }
2183
2184 // Directly call the constructor in the return statement to avoid
2185 // excess copying when building with Visual Studio 2017.
2186 // See bug 1385181.
2187 return AddPtr(lookup<ForAdd>(aLookup, keyHash), *this, keyHash);
2188 }
2189
2190 template <typename... Args>
2191 [[nodiscard]] bool add(AddPtr& aPtr, Args&&... aArgs) {
2192 ReentrancyGuard g(*this);
2193 MOZ_ASSERT_IF(aPtr.isValid(), mTable)do { if (aPtr.isValid()) { do { static_assert( mozilla::detail
::AssertionConditionType<decltype(mTable)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mTable))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mTable", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2193); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mTable" ")"
); do { MOZ_CrashSequence(__null, 2193); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
2194 MOZ_ASSERT_IF(aPtr.isValid(), aPtr.mTable == this)do { if (aPtr.isValid()) { do { static_assert( mozilla::detail
::AssertionConditionType<decltype(aPtr.mTable == this)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aPtr.mTable == this))), 0))) { do { } while (false);
MOZ_ReportAssertionFailure("aPtr.mTable == this", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2194); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.mTable == this"
")"); do { MOZ_CrashSequence(__null, 2194); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
2195 MOZ_ASSERT(!aPtr.found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aPtr.found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aPtr.found()))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("!aPtr.found()",
"/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2195); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aPtr.found()"
")"); do { MOZ_CrashSequence(__null, 2195); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2196 MOZ_ASSERT(!(aPtr.mKeyHash & sCollisionBit))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!(aPtr.mKeyHash & sCollisionBit))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!(aPtr.mKeyHash & sCollisionBit
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!(aPtr.mKeyHash & sCollisionBit)", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2196); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!(aPtr.mKeyHash & sCollisionBit)"
")"); do { MOZ_CrashSequence(__null, 2196); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2197
2198 // Check for error from ensureHash() here.
2199 if (!aPtr.isLive()) {
2200 return false;
2201 }
2202
2203 MOZ_ASSERT(aPtr.mGeneration == generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPtr.mGeneration == generation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aPtr.mGeneration == generation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aPtr.mGeneration == generation()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2203); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.mGeneration == generation()"
")"); do { MOZ_CrashSequence(__null, 2203); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2204#ifdef DEBUG1
2205 MOZ_ASSERT(aPtr.mMutationCount == mMutationCount)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPtr.mMutationCount == mMutationCount)>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(aPtr.mMutationCount == mMutationCount))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aPtr.mMutationCount == mMutationCount"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2205); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.mMutationCount == mMutationCount"
")"); do { MOZ_CrashSequence(__null, 2205); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2206#endif
2207
2208 if (!aPtr.isValid()) {
2209 MOZ_ASSERT(!mTable && mEntryCount == 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mTable && mEntryCount == 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!mTable && mEntryCount
== 0))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!mTable && mEntryCount == 0", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2209); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mTable && mEntryCount == 0"
")"); do { MOZ_CrashSequence(__null, 2209); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2210 uint32_t newCapacity = rawCapacity();
2211 RebuildStatus status = changeTableSize(newCapacity, ReportFailure);
2212 MOZ_ASSERT(status != NotOverloaded)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(status != NotOverloaded)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(status != NotOverloaded))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("status != NotOverloaded"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2212); AnnotateMozCrashReason("MOZ_ASSERT" "(" "status != NotOverloaded"
")"); do { MOZ_CrashSequence(__null, 2212); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2213 if (status == RehashFailed) {
2214 return false;
2215 }
2216 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2217
2218 } else if (aPtr.mSlot.isRemoved()) {
2219 // Changing an entry from removed to live does not affect whether we are
2220 // overloaded and can be handled separately.
2221 if (!this->checkSimulatedOOM()) {
2222 return false;
2223 }
2224 mRemovedCount--;
2225 aPtr.mKeyHash |= sCollisionBit;
2226
2227 } else {
2228 // Preserve the validity of |aPtr.mSlot|.
2229 RebuildStatus status = rehashIfOverloaded();
2230 if (status == RehashFailed) {
2231 return false;
2232 }
2233 if (status == NotOverloaded && !this->checkSimulatedOOM()) {
2234 return false;
2235 }
2236 if (status == Rehashed) {
2237 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2238 }
2239 }
2240
2241 aPtr.mSlot.setLive(aPtr.mKeyHash, std::forward<Args>(aArgs)...);
2242 mEntryCount++;
2243#ifdef DEBUG1
2244 mMutationCount++;
2245 aPtr.mGeneration = generation();
2246 aPtr.mMutationCount = mMutationCount;
2247#endif
2248 return true;
2249 }
2250
2251 // Note: |aLookup| may reference pieces of arguments in |aArgs|, so this
2252 // function must take care not to use |aLookup| after moving |aArgs|.
2253 template <typename... Args>
2254 void putNewInfallible(const Lookup& aLookup, Args&&... aArgs) {
2255 MOZ_ASSERT(!lookup(aLookup).found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!lookup(aLookup).found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!lookup(aLookup).found()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("!lookup(aLookup).found()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2255); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!lookup(aLookup).found()"
")"); do { MOZ_CrashSequence(__null, 2255); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2256 ReentrancyGuard g(*this);
2257 HashNumber keyHash = prepareHash(HashPolicy::hash(aLookup));
2258 putNewInfallibleInternal(keyHash, std::forward<Args>(aArgs)...);
2259 }
2260
2261 // Note: |aLookup| may alias arguments in |aArgs|, so this function must take
2262 // care not to use |aLookup| after moving |aArgs|.
2263 template <typename... Args>
2264 [[nodiscard]] bool putNew(const Lookup& aLookup, Args&&... aArgs) {
2265 MOZ_ASSERT(!lookup(aLookup).found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!lookup(aLookup).found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!lookup(aLookup).found()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("!lookup(aLookup).found()"
, "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2265); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!lookup(aLookup).found()"
")"); do { MOZ_CrashSequence(__null, 2265); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2266 ReentrancyGuard g(*this);
2267 if (!this->checkSimulatedOOM()) {
2268 return false;
2269 }
2270 HashNumber inputHash;
2271 if (!EnsureHash<HashPolicy>(aLookup, &inputHash)) {
2272 return false;
2273 }
2274 HashNumber keyHash = prepareHash(inputHash);
2275 if (rehashIfOverloaded() == RehashFailed) {
2276 return false;
2277 }
2278 putNewInfallibleInternal(keyHash, std::forward<Args>(aArgs)...);
2279 return true;
2280 }
2281
2282 // Note: |aLookup| may be a reference pieces of arguments in |aArgs|, so this
2283 // function must take care not to use |aLookup| after moving |aArgs|.
2284 template <typename... Args>
2285 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
2286 Args&&... aArgs) {
2287 // Check for error from ensureHash() here.
2288 if (!aPtr.isLive()) {
2289 return false;
2290 }
2291#ifdef DEBUG1
2292 aPtr.mGeneration = generation();
2293 aPtr.mMutationCount = mMutationCount;
2294#endif
2295 if (mTable) {
2296 ReentrancyGuard g(*this);
2297 // Check that aLookup has not been destroyed.
2298 MOZ_ASSERT(prepareHash(HashPolicy::hash(aLookup)) == aPtr.mKeyHash)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(prepareHash(HashPolicy::hash(aLookup)) == aPtr.mKeyHash
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(prepareHash(HashPolicy::hash(aLookup)) == aPtr.mKeyHash
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"prepareHash(HashPolicy::hash(aLookup)) == aPtr.mKeyHash", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2298); AnnotateMozCrashReason("MOZ_ASSERT" "(" "prepareHash(HashPolicy::hash(aLookup)) == aPtr.mKeyHash"
")"); do { MOZ_CrashSequence(__null, 2298); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2299 aPtr.mSlot = lookup<ForAdd>(aLookup, aPtr.mKeyHash);
2300 if (aPtr.found()) {
2301 return true;
2302 }
2303 } else {
2304 // Clear aPtr so it's invalid; add() will allocate storage and redo the
2305 // lookup.
2306 aPtr.mSlot = Slot(nullptr, nullptr);
2307 }
2308 return add(aPtr, std::forward<Args>(aArgs)...);
2309 }
2310
2311 void remove(Ptr aPtr) {
2312 MOZ_ASSERT(mTable)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mTable)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(mTable))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mTable", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2312); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mTable" ")"
); do { MOZ_CrashSequence(__null, 2312); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2313 ReentrancyGuard g(*this);
2314 MOZ_ASSERT(aPtr.found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPtr.found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aPtr.found()))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aPtr.found()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2314); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.found()"
")"); do { MOZ_CrashSequence(__null, 2314); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2315 MOZ_ASSERT(aPtr.mGeneration == generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPtr.mGeneration == generation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aPtr.mGeneration == generation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aPtr.mGeneration == generation()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2315); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.mGeneration == generation()"
")"); do { MOZ_CrashSequence(__null, 2315); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2316 remove(aPtr.mSlot);
2317 shrinkIfUnderloaded();
2318 }
2319
2320 template <typename KeyInput>
2321 void rekeyWithoutRehash(Ptr aPtr, const Lookup& aLookup, KeyInput&& aKey) {
2322 MOZ_ASSERT(mTable)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mTable)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(mTable))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mTable", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2322); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mTable" ")"
); do { MOZ_CrashSequence(__null, 2322); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2323 ReentrancyGuard g(*this);
2324 MOZ_ASSERT(aPtr.found())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPtr.found())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aPtr.found()))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aPtr.found()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2324); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.found()"
")"); do { MOZ_CrashSequence(__null, 2324); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2325 MOZ_ASSERT(aPtr.mGeneration == generation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPtr.mGeneration == generation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aPtr.mGeneration == generation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aPtr.mGeneration == generation()", "/root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/mozilla/HashTable.h"
, 2325); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPtr.mGeneration == generation()"
")"); do { MOZ_CrashSequence(__null, 2325); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2326 typename HashTableEntry<T>::NonConstT t(std::move(*aPtr));
2327 HashPolicy::setKey(t, std::forward<KeyInput>(aKey));
2328 remove(aPtr.mSlot);
2329 HashNumber keyHash = prepareHash(HashPolicy::hash(aLookup));
2330 putNewInfallibleInternal(keyHash, std::move(t));
2331 }
2332
2333 template <typename KeyInput>
2334 void rekeyAndMaybeRehash(Ptr aPtr, const Lookup& aLookup, KeyInput&& aKey) {
2335 rekeyWithoutRehash(aPtr, aLookup, std::forward<KeyInput>(aKey));
2336 infallibleRehashIfOverloaded();
2337 }
2338
2339 static size_t offsetOfHashShift() {
2340 static_assert(sHashShiftBits == 8,
2341 "callers assume hash shift is stored in a byte");
2342 // The hash shift is stored in the least significant bits of
2343 // mGenAndHashShift. On little-endian platforms, this is the
2344 // same offset as mGenAndHashShift itself. On big-endian platforms,
2345 // we have to add an additional offset to point to the last byte.
2346 // (Or we would if we had JIT support for any big-endian platforms.)
2347 if constexpr (std::endian::native == std::endian::big) {
2348 return offsetof(HashTable, mGenAndHashShift)__builtin_offsetof(HashTable, mGenAndHashShift) + sizeof(mGenAndHashShift) -
2349 sizeof(uint8_t);
2350 } else {
2351 return offsetof(HashTable, mGenAndHashShift)__builtin_offsetof(HashTable, mGenAndHashShift);
2352 }
2353 }
2354 static size_t offsetOfTable() { return offsetof(HashTable, mTable)__builtin_offsetof(HashTable, mTable); }
2355 static size_t offsetOfEntryCount() {
2356 return offsetof(HashTable, mEntryCount)__builtin_offsetof(HashTable, mEntryCount);
2357 }
2358};
2359
2360} // namespace detail
2361} // namespace mozilla
2362
2363#endif /* mozilla_HashTable_h */