Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h
Warning:line 273, column 9
Branch condition evaluates to a garbage value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -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=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/devtools/shared/heapsnapshot -fcoverage-compilation-dir=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/devtools/shared/heapsnapshot -resource-dir /usr/lib/llvm-19/lib/clang/19 -include /var/lib/jenkins/workspace/firefox-scan-build/config/gcc_hidden.h -include /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -I /var/lib/jenkins/workspace/firefox-scan-build/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 /var/lib/jenkins/workspace/firefox-scan-build/devtools/shared/heapsnapshot -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/devtools/shared/heapsnapshot -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /var/lib/jenkins/workspace/firefox-scan-build/ipc/chromium/src -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/x86_64-linux-gnu/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/backward -internal-isystem /usr/lib/llvm-19/lib/clang/19/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -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-deprecated-this-capture -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 -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 -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2024-09-22-115206-3586786-1 -x c++ /var/lib/jenkins/workspace/firefox-scan-build/devtools/shared/heapsnapshot/HeapSnapshot.cpp

/var/lib/jenkins/workspace/firefox-scan-build/devtools/shared/heapsnapshot/HeapSnapshot.cpp

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

/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h

1/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3/* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7/* A class for optional values and in-place lazy construction. */
8
9#ifndef mozilla_Maybe_h
10#define mozilla_Maybe_h
11
12#include <functional>
13#include <new> // for placement new
14#include <ostream>
15#include <type_traits>
16#include <utility>
17
18#include "mozilla/Alignment.h"
19#include "mozilla/Assertions.h"
20#include "mozilla/Attributes.h"
21#include "mozilla/MaybeStorageBase.h"
22#include "mozilla/MemoryChecking.h"
23#include "mozilla/OperatorNewExtensions.h"
24#include "mozilla/Poison.h"
25#include "mozilla/ThreadSafety.h"
26
27class nsCycleCollectionTraversalCallback;
28
29template <typename T>
30inline void CycleCollectionNoteChild(
31 nsCycleCollectionTraversalCallback& aCallback, T* aChild, const char* aName,
32 uint32_t aFlags);
33
34namespace mozilla {
35
36struct Nothing {};
37
38inline constexpr bool operator==(const Nothing&, const Nothing&) {
39 return true;
40}
41
42template <class T>
43class Maybe;
44
45namespace detail {
46
47// You would think that poisoning Maybe instances could just be a call
48// to mozWritePoison. Unfortunately, using a simple call to
49// mozWritePoison generates poor code on MSVC for small structures. The
50// generated code contains (always not-taken) branches and does a bunch
51// of setup for `rep stos{l,q}`, even though we know at compile time
52// exactly how many words we're poisoning. Instead, we're going to
53// force MSVC to generate the code we want via recursive templates.
54
55// Write the given poisonValue into p at offset*sizeof(uintptr_t).
56template <size_t offset>
57inline void WritePoisonAtOffset(void* p, const uintptr_t poisonValue) {
58 memcpy(static_cast<char*>(p) + offset * sizeof(poisonValue), &poisonValue,
59 sizeof(poisonValue));
60}
61
62template <size_t Offset, size_t NOffsets>
63struct InlinePoisoner {
64 static void poison(void* p, const uintptr_t poisonValue) {
65 WritePoisonAtOffset<Offset>(p, poisonValue);
66 InlinePoisoner<Offset + 1, NOffsets>::poison(p, poisonValue);
67 }
68};
69
70template <size_t N>
71struct InlinePoisoner<N, N> {
72 static void poison(void*, const uintptr_t) {
73 // All done!
74 }
75};
76
77// We can't generate inline code for large structures, though, because we'll
78// blow out recursive template instantiation limits, and the code would be
79// bloated to boot. So provide a fallback to the out-of-line poisoner.
80template <size_t ObjectSize>
81struct OutOfLinePoisoner {
82 static MOZ_NEVER_INLINE__attribute__((noinline)) void poison(void* p, const uintptr_t) {
83 mozWritePoison(p, ObjectSize);
84 }
85};
86
87template <typename T>
88inline void PoisonObject(T* p) {
89 const uintptr_t POISON = mozPoisonValue();
90 std::conditional_t<(sizeof(T) <= 8 * sizeof(POISON)),
91 InlinePoisoner<0, sizeof(T) / sizeof(POISON)>,
92 OutOfLinePoisoner<sizeof(T)>>::poison(p, POISON);
93}
94
95template <typename T>
96struct MaybePoisoner {
97 static const size_t N = sizeof(T);
98
99 static void poison(void* aPtr) {
100#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED1
101 if (N >= sizeof(uintptr_t)) {
102 PoisonObject(static_cast<std::remove_cv_t<T>*>(aPtr));
103 }
104#endif
105 MOZ_MAKE_MEM_UNDEFINED(aPtr, N)do { } while (0);
106 }
107};
108
109template <typename T,
110 bool TriviallyDestructibleAndCopyable =
111 IsTriviallyDestructibleAndCopyable<T>,
112 bool Copyable = std::is_copy_constructible_v<T>,
113 bool Movable = std::is_move_constructible_v<T>>
114class Maybe_CopyMove_Enabler;
115
116#define MOZ_MAYBE_COPY_OPS() \
117 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler& aOther) { \
118 if (downcast(aOther).isSome()) { \
119 downcast(*this).emplace(*downcast(aOther)); \
120 } \
121 } \
122 \
123 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler& aOther) { \
124 return downcast(*this).template operator= <T>(downcast(aOther)); \
125 }
126
127#define MOZ_MAYBE_MOVE_OPS() \
128 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) { \
129 if (downcast(aOther).isSome()) { \
130 downcast(*this).emplace(std::move(*downcast(aOther))); \
131 downcast(aOther).reset(); \
132 } \
133 } \
134 \
135 constexpr Maybe_CopyMove_Enabler& operator=( \
136 Maybe_CopyMove_Enabler&& aOther) { \
137 downcast(*this).template operator= <T>(std::move(downcast(aOther))); \
138 \
139 return *this; \
140 }
141
142#define MOZ_MAYBE_DOWNCAST() \
143 static constexpr Maybe<T>& downcast(Maybe_CopyMove_Enabler& aObj) { \
144 return static_cast<Maybe<T>&>(aObj); \
145 } \
146 static constexpr const Maybe<T>& downcast( \
147 const Maybe_CopyMove_Enabler& aObj) { \
148 return static_cast<const Maybe<T>&>(aObj); \
149 }
150
151template <typename T>
152class Maybe_CopyMove_Enabler<T, true, true, true> {
153 public:
154 Maybe_CopyMove_Enabler() = default;
155
156 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = default;
157 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = default;
158 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) {
159 downcast(aOther).reset();
160 }
161 constexpr Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&& aOther) {
162 downcast(aOther).reset();
163 return *this;
164 }
165
166 private:
167 MOZ_MAYBE_DOWNCAST()
168};
169
170template <typename T>
171class Maybe_CopyMove_Enabler<T, true, false, true> {
172 public:
173 Maybe_CopyMove_Enabler() = default;
174
175 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
176 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
177 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) {
178 downcast(aOther).reset();
179 }
180 constexpr Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&& aOther) {
181 downcast(aOther).reset();
182 return *this;
183 }
184
185 private:
186 MOZ_MAYBE_DOWNCAST()
187};
188
189template <typename T>
190class Maybe_CopyMove_Enabler<T, false, true, true> {
191 public:
192 Maybe_CopyMove_Enabler() = default;
193
194 MOZ_MAYBE_COPY_OPS()
195 MOZ_MAYBE_MOVE_OPS()
196
197 private:
198 MOZ_MAYBE_DOWNCAST()
199};
200
201template <typename T>
202class Maybe_CopyMove_Enabler<T, false, false, true> {
203 public:
204 Maybe_CopyMove_Enabler() = default;
205
206 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
207 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
208 MOZ_MAYBE_MOVE_OPS()
20
Calling 'Maybe_CopyMove_Enabler::downcast'
21
Returning from 'Maybe_CopyMove_Enabler::downcast'
209
210 private:
211 MOZ_MAYBE_DOWNCAST()
212};
213
214template <typename T>
215class Maybe_CopyMove_Enabler<T, false, true, false> {
216 public:
217 Maybe_CopyMove_Enabler() = default;
218
219 MOZ_MAYBE_COPY_OPS()
220 Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&&) = delete;
221 Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&&) = delete;
222
223 private:
224 MOZ_MAYBE_DOWNCAST()
225};
226
227template <typename T, bool TriviallyDestructibleAndCopyable>
228class Maybe_CopyMove_Enabler<T, TriviallyDestructibleAndCopyable, false,
229 false> {
230 public:
231 Maybe_CopyMove_Enabler() = default;
232
233 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
234 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
235 Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&&) = delete;
236 Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&&) = delete;
237};
238
239#undef MOZ_MAYBE_COPY_OPS
240#undef MOZ_MAYBE_MOVE_OPS
241#undef MOZ_MAYBE_DOWNCAST
242
243template <typename T, bool TriviallyDestructibleAndCopyable =
244 IsTriviallyDestructibleAndCopyable<T>>
245struct MaybeStorage;
246
247template <typename T>
248struct MaybeStorage<T, false> : MaybeStorageBase<T> {
249 protected:
250 char mIsSome = false; // not bool -- guarantees minimal space consumption
251
252 MaybeStorage() = default;
3
Calling defaulted default constructor for 'MaybeStorageBase<JS::ubi::DominatorTree, false>'
8
Returning from default constructor for 'MaybeStorageBase<JS::ubi::DominatorTree, false>'
9
Returning without writing to 'this->mStorage.val.retainedSizes.mIsSome'
253 explicit MaybeStorage(const T& aVal)
254 : MaybeStorageBase<T>{aVal}, mIsSome{true} {}
255 explicit MaybeStorage(T&& aVal)
256 : MaybeStorageBase<T>{std::move(aVal)}, mIsSome{true} {}
257
258 template <typename... Args>
259 explicit MaybeStorage(std::in_place_t, Args&&... aArgs)
260 : MaybeStorageBase<T>{std::in_place, std::forward<Args>(aArgs)...},
261 mIsSome{true} {}
262
263 public:
264 // Copy and move operations are no-ops, since copying is moving is implemented
265 // by Maybe_CopyMove_Enabler.
266
267 MaybeStorage(const MaybeStorage&) : MaybeStorageBase<T>{} {}
268 MaybeStorage& operator=(const MaybeStorage&) { return *this; }
269 MaybeStorage(MaybeStorage&&) : MaybeStorageBase<T>{} {}
270 MaybeStorage& operator=(MaybeStorage&&) { return *this; }
271
272 ~MaybeStorage() {
273 if (mIsSome
26.1
Field 'mIsSome' is 0
26.1
Field 'mIsSome' is 0
26.1
Field 'mIsSome' is 0
26.1
Field 'mIsSome' is 0
) {
27
Taking false branch
33
Branch condition evaluates to a garbage value
274 this->addr()->T::~T();
275 }
276 }
28
Calling implicit destructor for 'MaybeStorageBase<JS::ubi::DominatorTree, false>'
29
Calling '~Union'
277};
278
279template <typename T>
280struct MaybeStorage<T, true> : MaybeStorageBase<T> {
281 protected:
282 char mIsSome = false; // not bool -- guarantees minimal space consumption
283
284 constexpr MaybeStorage() = default;
285 constexpr explicit MaybeStorage(const T& aVal)
286 : MaybeStorageBase<T>{aVal}, mIsSome{true} {}
287 constexpr explicit MaybeStorage(T&& aVal)
288 : MaybeStorageBase<T>{std::move(aVal)}, mIsSome{true} {}
289
290 template <typename... Args>
291 constexpr explicit MaybeStorage(std::in_place_t, Args&&... aArgs)
292 : MaybeStorageBase<T>{std::in_place, std::forward<Args>(aArgs)...},
293 mIsSome{true} {}
294};
295
296template <typename T>
297struct IsMaybeImpl : std::false_type {};
298
299template <typename T>
300struct IsMaybeImpl<Maybe<T>> : std::true_type {};
301
302template <typename T>
303using IsMaybe = IsMaybeImpl<std::decay_t<T>>;
304
305} // namespace detail
306
307template <typename T, typename U = typename std::remove_cv<
308 typename std::remove_reference<T>::type>::type>
309constexpr Maybe<U> Some(T&& aValue);
310
311/*
312 * Maybe is a container class which contains either zero or one elements. It
313 * serves two roles. It can represent values which are *semantically* optional,
314 * augmenting a type with an explicit 'Nothing' value. In this role, it provides
315 * methods that make it easy to work with values that may be missing, along with
316 * equality and comparison operators so that Maybe values can be stored in
317 * containers. Maybe values can be constructed conveniently in expressions using
318 * type inference, as follows:
319 *
320 * void doSomething(Maybe<Foo> aFoo) {
321 * if (aFoo) // Make sure that aFoo contains a value...
322 * aFoo->takeAction(); // and then use |aFoo->| to access it.
323 * } // |*aFoo| also works!
324 *
325 * doSomething(Nothing()); // Passes a Maybe<Foo> containing no value.
326 * doSomething(Some(Foo(100))); // Passes a Maybe<Foo> containing |Foo(100)|.
327 *
328 * You'll note that it's important to check whether a Maybe contains a value
329 * before using it, using conversion to bool, |isSome()|, or |isNothing()|. You
330 * can avoid these checks, and sometimes write more readable code, using
331 * |valueOr()|, |ptrOr()|, and |refOr()|, which allow you to retrieve the value
332 * in the Maybe and provide a default for the 'Nothing' case. You can also use
333 * |apply()| to call a function only if the Maybe holds a value, and |map()| to
334 * transform the value in the Maybe, returning another Maybe with a possibly
335 * different type.
336 *
337 * Maybe's other role is to support lazily constructing objects without using
338 * dynamic storage. A Maybe directly contains storage for a value, but it's
339 * empty by default. |emplace()|, as mentioned above, can be used to construct a
340 * value in Maybe's storage. The value a Maybe contains can be destroyed by
341 * calling |reset()|; this will happen automatically if a Maybe is destroyed
342 * while holding a value.
343 *
344 * It's a common idiom in C++ to use a pointer as a 'Maybe' type, with a null
345 * value meaning 'Nothing' and any other value meaning 'Some'. You can convert
346 * from such a pointer to a Maybe value using 'ToMaybe()'.
347 *
348 * Maybe is inspired by similar types in the standard library of many other
349 * languages (e.g. Haskell's Maybe and Rust's Option). In the C++ world it's
350 * very similar to std::optional, which was proposed for C++14 and originated in
351 * Boost. The most important differences between Maybe and std::optional are:
352 *
353 * - std::optional<T> may be compared with T. We deliberately forbid that.
354 * - std::optional has |valueOr()|, equivalent to Maybe's |valueOr()|, but
355 * lacks corresponding methods for |refOr()| and |ptrOr()|.
356 * - std::optional lacks |map()| and |apply()|, making it less suitable for
357 * functional-style code.
358 * - std::optional lacks many convenience functions that Maybe has. Most
359 * unfortunately, it lacks equivalents of the type-inferred constructor
360 * functions |Some()| and |Nothing()|.
361 */
362template <class T>
363class MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS Maybe
364 : private detail::MaybeStorage<T>,
365 public detail::Maybe_CopyMove_Enabler<T> {
366 template <typename, bool, bool, bool>
367 friend class detail::Maybe_CopyMove_Enabler;
368
369 template <typename U, typename V>
370 friend constexpr Maybe<V> Some(U&& aValue);
371
372 struct SomeGuard {};
373
374 template <typename U>
375 constexpr Maybe(U&& aValue, SomeGuard)
376 : detail::MaybeStorage<T>{std::forward<U>(aValue)} {}
377
378 using detail::MaybeStorage<T>::mIsSome;
379 using detail::MaybeStorage<T>::mStorage;
380
381 void poisonData() { detail::MaybePoisoner<T>::poison(&mStorage.val); }
382
383 public:
384 using ValueType = T;
385
386 MOZ_ALLOW_TEMPORARY constexpr Maybe() = default;
2
Calling defaulted default constructor for 'MaybeStorage<JS::ubi::DominatorTree, false>'
10
Returning from default constructor for 'MaybeStorage<JS::ubi::DominatorTree, false>'
11
Returning without writing to 'this->mStorage.val.retainedSizes.mIsSome'
387
388 MOZ_ALLOW_TEMPORARY MOZ_IMPLICIT constexpr Maybe(Nothing) : Maybe{} {}
389
390 template <typename... Args>
391 constexpr explicit Maybe(std::in_place_t, Args&&... aArgs)
392 : detail::MaybeStorage<T>{std::in_place, std::forward<Args>(aArgs)...} {}
393
394 /**
395 * Maybe<T> can be copy-constructed from a Maybe<U> if T is constructible from
396 * a const U&.
397 */
398 template <typename U,
399 std::enable_if_t<std::is_constructible_v<T, const U&>, bool> = true>
400 MOZ_IMPLICIT Maybe(const Maybe<U>& aOther) {
401 if (aOther.isSome()) {
402 emplace(*aOther);
403 }
404 }
405
406 template <typename U, std::enable_if_t<!std::is_constructible_v<T, const U&>,
407 bool> = true>
408 explicit Maybe(const Maybe<U>& aOther) = delete;
409
410 /**
411 * Maybe<T> can be move-constructed from a Maybe<U> if T is constructible from
412 * a U&&.
413 */
414 template <typename U,
415 std::enable_if_t<std::is_constructible_v<T, U&&>, bool> = true>
416 MOZ_IMPLICIT Maybe(Maybe<U>&& aOther) {
417 if (aOther.isSome()) {
418 emplace(std::move(*aOther));
419 aOther.reset();
420 }
421 }
422 template <typename U,
423 std::enable_if_t<!std::is_constructible_v<T, U&&>, bool> = true>
424 explicit Maybe(Maybe<U>&& aOther) = delete;
425
426 template <typename U,
427 std::enable_if_t<std::is_constructible_v<T, const U&>, bool> = true>
428 Maybe& operator=(const Maybe<U>& aOther) {
429 if (aOther.isSome()) {
430 if (mIsSome) {
431 ref() = aOther.ref();
432 } else {
433 emplace(*aOther);
434 }
435 } else {
436 reset();
437 }
438 return *this;
439 }
440
441 template <typename U, std::enable_if_t<!std::is_constructible_v<T, const U&>,
442 bool> = true>
443 Maybe& operator=(const Maybe<U>& aOther) = delete;
444
445 template <typename U,
446 std::enable_if_t<std::is_constructible_v<T, U&&>, bool> = true>
447 Maybe& operator=(Maybe<U>&& aOther) {
448 if (aOther.isSome()) {
449 if (mIsSome) {
450 ref() = std::move(aOther.ref());
451 } else {
452 emplace(std::move(*aOther));
453 }
454 aOther.reset();
455 } else {
456 reset();
457 }
458
459 return *this;
460 }
461
462 template <typename U,
463 std::enable_if_t<!std::is_constructible_v<T, U&&>, bool> = true>
464 Maybe& operator=(Maybe<U>&& aOther) = delete;
465
466 constexpr Maybe& operator=(Nothing) {
467 reset();
468 return *this;
469 }
470
471 /* Methods that check whether this Maybe contains a value */
472 constexpr explicit operator bool() const { return isSome(); }
473 constexpr bool isSome() const { return mIsSome; }
474 constexpr bool isNothing() const { return !mIsSome; }
475
476 /* Returns the contents of this Maybe<T> by value. Unsafe unless |isSome()|.
477 */
478 constexpr T value() const&;
479 constexpr T value() &&;
480 constexpr T value() const&&;
481
482 /**
483 * Move the contents of this Maybe<T> out of internal storage and return it
484 * without calling the destructor. The internal storage is also reset to
485 * avoid multiple calls. Unsafe unless |isSome()|.
486 */
487 constexpr T extract() {
488 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 488); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 488; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
489 T v = std::move(mStorage.val);
490 reset();
491 return v;
492 }
493
494 /**
495 * Returns the value (possibly |Nothing()|) by moving it out of this Maybe<T>
496 * and leaving |Nothing()| in its place.
497 */
498 Maybe<T> take() { return std::exchange(*this, Nothing()); }
499
500 /*
501 * Returns the contents of this Maybe<T> by value. If |isNothing()|, returns
502 * the default value provided.
503 *
504 * Note: If the value passed to aDefault is not the result of a trivial
505 * expression, but expensive to evaluate, e.g. |valueOr(ExpensiveFunction())|,
506 * use |valueOrFrom| instead, e.g.
507 * |valueOrFrom([arg] { return ExpensiveFunction(arg); })|. This ensures
508 * that the expensive expression is only evaluated when its result will
509 * actually be used.
510 */
511 template <typename V>
512 constexpr T valueOr(V&& aDefault) const {
513 if (isSome()) {
514 return ref();
515 }
516 return std::forward<V>(aDefault);
517 }
518
519 /*
520 * Returns the contents of this Maybe<T> by value. If |isNothing()|, returns
521 * the value returned from the function or functor provided.
522 */
523 template <typename F>
524 constexpr T valueOrFrom(F&& aFunc) const {
525 if (isSome()) {
526 return ref();
527 }
528 return aFunc();
529 }
530
531 /* Returns the contents of this Maybe<T> by pointer. Unsafe unless |isSome()|.
532 */
533 T* ptr();
534 constexpr const T* ptr() const;
535
536 /*
537 * Returns the contents of this Maybe<T> by pointer. If |isNothing()|,
538 * returns the default value provided.
539 */
540 T* ptrOr(T* aDefault) {
541 if (isSome()) {
542 return ptr();
543 }
544 return aDefault;
545 }
546
547 constexpr const T* ptrOr(const T* aDefault) const {
548 if (isSome()) {
549 return ptr();
550 }
551 return aDefault;
552 }
553
554 /*
555 * Returns the contents of this Maybe<T> by pointer. If |isNothing()|,
556 * returns the value returned from the function or functor provided.
557 */
558 template <typename F>
559 T* ptrOrFrom(F&& aFunc) {
560 if (isSome()) {
561 return ptr();
562 }
563 return aFunc();
564 }
565
566 template <typename F>
567 const T* ptrOrFrom(F&& aFunc) const {
568 if (isSome()) {
569 return ptr();
570 }
571 return aFunc();
572 }
573
574 constexpr T* operator->();
575 constexpr const T* operator->() const;
576
577 /* Returns the contents of this Maybe<T> by ref. Unsafe unless |isSome()|. */
578 constexpr T& ref() &;
579 constexpr const T& ref() const&;
580 constexpr T&& ref() &&;
581 constexpr const T&& ref() const&&;
582
583 /*
584 * Returns the contents of this Maybe<T> by ref. If |isNothing()|, returns
585 * the default value provided.
586 */
587 constexpr T& refOr(T& aDefault) {
588 if (isSome()) {
589 return ref();
590 }
591 return aDefault;
592 }
593
594 constexpr const T& refOr(const T& aDefault) const {
595 if (isSome()) {
596 return ref();
597 }
598 return aDefault;
599 }
600
601 /*
602 * Returns the contents of this Maybe<T> by ref. If |isNothing()|, returns the
603 * value returned from the function or functor provided.
604 */
605 template <typename F>
606 constexpr T& refOrFrom(F&& aFunc) {
607 if (isSome()) {
608 return ref();
609 }
610 return aFunc();
611 }
612
613 template <typename F>
614 constexpr const T& refOrFrom(F&& aFunc) const {
615 if (isSome()) {
616 return ref();
617 }
618 return aFunc();
619 }
620
621 constexpr T& operator*() &;
622 constexpr const T& operator*() const&;
623 constexpr T&& operator*() &&;
624 constexpr const T&& operator*() const&&;
625
626 /* If |isSome()|, runs the provided function or functor on the contents of
627 * this Maybe. */
628 template <typename Func>
629 constexpr Maybe& apply(Func&& aFunc) & {
630 if (isSome()) {
631 std::forward<Func>(aFunc)(ref());
632 }
633 return *this;
634 }
635
636 template <typename Func>
637 constexpr const Maybe& apply(Func&& aFunc) const& {
638 if (isSome()) {
639 std::forward<Func>(aFunc)(ref());
640 }
641 return *this;
642 }
643
644 template <typename Func>
645 constexpr Maybe& apply(Func&& aFunc) && {
646 if (isSome()) {
647 std::forward<Func>(aFunc)(extract());
648 }
649 return *this;
650 }
651
652 template <typename Func>
653 constexpr Maybe& apply(Func&& aFunc) const&& {
654 if (isSome()) {
655 std::forward<Func>(aFunc)(extract());
656 }
657 return *this;
658 }
659
660 /*
661 * If |isSome()|, runs the provided function and returns the result wrapped
662 * in a Maybe. If |isNothing()|, returns an empty Maybe value with the same
663 * value type as what the provided function would have returned.
664 */
665 template <typename Func>
666 constexpr auto map(Func&& aFunc) & {
667 if (isSome()) {
668 return Some(std::forward<Func>(aFunc)(ref()));
669 }
670 return Maybe<decltype(std::forward<Func>(aFunc)(ref()))>{};
671 }
672
673 template <typename Func>
674 constexpr auto map(Func&& aFunc) const& {
675 if (isSome()) {
676 return Some(std::forward<Func>(aFunc)(ref()));
677 }
678 return Maybe<decltype(std::forward<Func>(aFunc)(ref()))>{};
679 }
680
681 template <typename Func>
682 constexpr auto map(Func&& aFunc) && {
683 if (isSome()) {
684 return Some(std::forward<Func>(aFunc)(extract()));
685 }
686 return Maybe<decltype(std::forward<Func>(aFunc)(extract()))>{};
687 }
688
689 template <typename Func>
690 constexpr auto map(Func&& aFunc) const&& {
691 if (isSome()) {
692 return Some(std::forward<Func>(aFunc)(extract()));
693 }
694 return Maybe<decltype(std::forward<Func>(aFunc)(extract()))>{};
695 }
696
697 /*
698 * If |isSome()|, runs the provided function or functor on the contents of
699 * this Maybe and returns the result. Note that the provided function or
700 * functor must return a Maybe<U> of any type U.
701 * If |isNothing()|, returns an empty Maybe value with the same type as what
702 * the provided function would have returned.
703 */
704 template <typename Func>
705 constexpr auto andThen(Func&& aFunc) & {
706 static_assert(std::is_invocable_v<Func, T&>);
707 using U = std::invoke_result_t<Func, T&>;
708 static_assert(detail::IsMaybe<U>::value);
709 if (isSome()) {
710 return std::invoke(std::forward<Func>(aFunc), ref());
711 }
712 return std::remove_cv_t<std::remove_reference_t<U>>{};
713 }
714
715 template <typename Func>
716 constexpr auto andThen(Func&& aFunc) const& {
717 static_assert(std::is_invocable_v<Func, const T&>);
718 using U = std::invoke_result_t<Func, const T&>;
719 static_assert(detail::IsMaybe<U>::value);
720 if (isSome()) {
721 return std::invoke(std::forward<Func>(aFunc), ref());
722 }
723 return std::remove_cv_t<std::remove_reference_t<U>>{};
724 }
725
726 template <typename Func>
727 constexpr auto andThen(Func&& aFunc) && {
728 static_assert(std::is_invocable_v<Func, T&&>);
729 using U = std::invoke_result_t<Func, T&&>;
730 static_assert(detail::IsMaybe<U>::value);
731 if (isSome()) {
732 return std::invoke(std::forward<Func>(aFunc), extract());
733 }
734 return std::remove_cv_t<std::remove_reference_t<U>>{};
735 }
736
737 template <typename Func>
738 constexpr auto andThen(Func&& aFunc) const&& {
739 static_assert(std::is_invocable_v<Func, const T&&>);
740 using U = std::invoke_result_t<Func, const T&&>;
741 static_assert(detail::IsMaybe<U>::value);
742 if (isSome()) {
743 return std::invoke(std::forward<Func>(aFunc), extract());
744 }
745 return std::remove_cv_t<std::remove_reference_t<U>>{};
746 }
747
748 /*
749 * If |isNothing()|, runs the provided function or functor and returns its
750 * result. If |isSome()|, returns the contained value wrapped in a Maybe.
751 */
752 template <typename Func>
753 constexpr Maybe orElse(Func&& aFunc) & {
754 static_assert(std::is_invocable_v<Func>);
755 using U = std::invoke_result_t<Func>;
756 static_assert(
757 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
758 if (isSome()) {
759 return *this;
760 }
761 return std::invoke(std::forward<Func>(aFunc));
762 }
763
764 template <typename Func>
765 constexpr Maybe orElse(Func&& aFunc) const& {
766 static_assert(std::is_invocable_v<Func>);
767 using U = std::invoke_result_t<Func>;
768 static_assert(
769 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
770 if (isSome()) {
771 return *this;
772 }
773 return std::invoke(std::forward<Func>(aFunc));
774 }
775
776 template <typename Func>
777 constexpr Maybe orElse(Func&& aFunc) && {
778 static_assert(std::is_invocable_v<Func>);
779 using U = std::invoke_result_t<Func>;
780 static_assert(
781 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
782 if (isSome()) {
783 return std::move(*this);
784 }
785 return std::invoke(std::forward<Func>(aFunc));
786 }
787
788 template <typename Func>
789 constexpr Maybe orElse(Func&& aFunc) const&& {
790 static_assert(std::is_invocable_v<Func>);
791 using U = std::invoke_result_t<Func>;
792 static_assert(
793 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
794 if (isSome()) {
795 return std::move(*this);
796 }
797 return std::invoke(std::forward<Func>(aFunc));
798 }
799
800 /* If |isSome()|, empties this Maybe and destroys its contents. */
801 constexpr void reset() {
802 if (isSome()) {
803 if constexpr (!std::is_trivially_destructible_v<T>) {
804 /*
805 * Static analyzer gets confused if we have Maybe<MutexAutoLock>,
806 * so we suppress thread-safety warnings here
807 */
808 MOZ_PUSH_IGNORE_THREAD_SAFETYGCC diagnostic push GCC diagnostic ignored "-Wthread-safety"
809 ref().T::~T();
810 MOZ_POP_THREAD_SAFETYGCC diagnostic pop
811 poisonData();
812 }
813 mIsSome = false;
814 }
815 }
816
817 /*
818 * Constructs a T value in-place in this empty Maybe<T>'s storage. The
819 * arguments to |emplace()| are the parameters to T's constructor.
820 */
821 template <typename... Args>
822 constexpr void emplace(Args&&... aArgs);
823
824 template <typename U>
825 constexpr std::enable_if_t<std::is_same_v<T, U> &&
826 std::is_copy_constructible_v<U> &&
827 !std::is_move_constructible_v<U>>
828 emplace(U&& aArgs) {
829 emplace(aArgs);
830 }
831
832 friend std::ostream& operator<<(std::ostream& aStream,
833 const Maybe<T>& aMaybe) {
834 if (aMaybe) {
835 aStream << aMaybe.ref();
836 } else {
837 aStream << "<Nothing>";
838 }
839 return aStream;
840 }
841};
842
843template <typename T>
844class Maybe<T&> {
845 public:
846 constexpr Maybe() = default;
847 constexpr MOZ_IMPLICIT Maybe(Nothing) {}
848
849 void emplace(T& aRef) { mValue = &aRef; }
850
851 /* Methods that check whether this Maybe contains a value */
852 constexpr explicit operator bool() const { return isSome(); }
853 constexpr bool isSome() const { return mValue; }
854 constexpr bool isNothing() const { return !mValue; }
855
856 T& ref() const {
857 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 857); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 857; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
858 return *mValue;
859 }
860
861 T* operator->() const { return &ref(); }
862 T& operator*() const { return ref(); }
863
864 // Deliberately not defining value and ptr accessors, as these may be
865 // confusing on a reference-typed Maybe.
866
867 // XXX Should we define refOr?
868
869 void reset() { mValue = nullptr; }
870
871 template <typename Func>
872 const Maybe& apply(Func&& aFunc) const {
873 if (isSome()) {
874 std::forward<Func>(aFunc)(ref());
875 }
876 return *this;
877 }
878
879 template <typename Func>
880 auto map(Func&& aFunc) const {
881 Maybe<decltype(std::forward<Func>(aFunc)(ref()))> val;
882 if (isSome()) {
883 val.emplace(std::forward<Func>(aFunc)(ref()));
884 }
885 return val;
886 }
887
888 template <typename Func>
889 constexpr auto andThen(Func&& aFunc) const {
890 static_assert(std::is_invocable_v<Func, T&>);
891 using U = std::invoke_result_t<Func, T&>;
892 static_assert(detail::IsMaybe<U>::value);
893 if (isSome()) {
894 return std::invoke(std::forward<Func>(aFunc), ref());
895 }
896 return std::remove_cv_t<std::remove_reference_t<U>>{};
897 }
898
899 template <typename Func>
900 constexpr Maybe orElse(Func&& aFunc) const {
901 static_assert(std::is_invocable_v<Func>);
902 using U = std::invoke_result_t<Func>;
903 static_assert(
904 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
905 if (isSome()) {
906 return *this;
907 }
908 return std::invoke(std::forward<Func>(aFunc));
909 }
910
911 bool refEquals(const Maybe<T&>& aOther) const {
912 return mValue == aOther.mValue;
913 }
914
915 bool refEquals(const T& aOther) const { return mValue == &aOther; }
916
917 private:
918 T* mValue = nullptr;
919};
920
921template <typename T>
922constexpr T Maybe<T>::value() const& {
923 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 923); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 923; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
924 return ref();
925}
926
927template <typename T>
928constexpr T Maybe<T>::value() && {
929 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 929); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 929; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
930 return std::move(ref());
931}
932
933template <typename T>
934constexpr T Maybe<T>::value() const&& {
935 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 935); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 935; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
936 return std::move(ref());
937}
938
939template <typename T>
940T* Maybe<T>::ptr() {
941 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 941); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 941; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
942 return &ref();
943}
944
945template <typename T>
946constexpr const T* Maybe<T>::ptr() const {
947 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 947); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 947; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
948 return &ref();
949}
950
951template <typename T>
952constexpr T* Maybe<T>::operator->() {
953 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 953); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 953; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
954 return ptr();
955}
956
957template <typename T>
958constexpr const T* Maybe<T>::operator->() const {
959 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 959); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 959; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
960 return ptr();
961}
962
963template <typename T>
964constexpr T& Maybe<T>::ref() & {
965 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 965); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 965; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
966 return mStorage.val;
967}
968
969template <typename T>
970constexpr const T& Maybe<T>::ref() const& {
971 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 971); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 971; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
972 return mStorage.val;
973}
974
975template <typename T>
976constexpr T&& Maybe<T>::ref() && {
977 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 977); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 977; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
978 return std::move(mStorage.val);
979}
980
981template <typename T>
982constexpr const T&& Maybe<T>::ref() const&& {
983 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 983); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 983; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
984 return std::move(mStorage.val);
985}
986
987template <typename T>
988constexpr T& Maybe<T>::operator*() & {
989 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 989); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 989; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
990 return ref();
991}
992
993template <typename T>
994constexpr const T& Maybe<T>::operator*() const& {
995 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 995); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 995; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
996 return ref();
997}
998
999template <typename T>
1000constexpr T&& Maybe<T>::operator*() && {
1001 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 1001); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 1001; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1002 return std::move(ref());
1003}
1004
1005template <typename T>
1006constexpr const T&& Maybe<T>::operator*() const&& {
1007 MOZ_RELEASE_ASSERT(isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 1007); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "isSome()"
")"); do { *((volatile int*)__null) = 1007; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1008 return std::move(ref());
1009}
1010
1011template <typename T>
1012template <typename... Args>
1013constexpr void Maybe<T>::emplace(Args&&... aArgs) {
1014 MOZ_RELEASE_ASSERT(!isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!isSome()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!isSome()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/Maybe.h"
, 1014); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "!isSome()"
")"); do { *((volatile int*)__null) = 1014; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1015 ::new (KnownNotNull, &mStorage.val) T(std::forward<Args>(aArgs)...);
1016 mIsSome = true;
1017}
1018
1019/*
1020 * Some() creates a Maybe<T> value containing the provided T value. If T has a
1021 * move constructor, it's used to make this as efficient as possible.
1022 *
1023 * Some() selects the type of Maybe it returns by removing any const, volatile,
1024 * or reference qualifiers from the type of the value you pass to it. This gives
1025 * it more intuitive behavior when used in expressions, but it also means that
1026 * if you need to construct a Maybe value that holds a const, volatile, or
1027 * reference value, you need to use emplace() instead.
1028 */
1029template <typename T, typename U>
1030constexpr Maybe<U> Some(T&& aValue) {
1031 return {std::forward<T>(aValue), typename Maybe<U>::SomeGuard{}};
1032}
1033
1034template <typename T>
1035constexpr Maybe<T&> SomeRef(T& aValue) {
1036 Maybe<T&> value;
1037 value.emplace(aValue);
1038 return value;
1039}
1040
1041template <typename T>
1042constexpr Maybe<T&> ToMaybeRef(T* const aPtr) {
1043 return aPtr ? SomeRef(*aPtr) : Nothing{};
1044}
1045
1046template <typename T>
1047Maybe<std::remove_cv_t<std::remove_reference_t<T>>> ToMaybe(T* aPtr) {
1048 if (aPtr) {
1049 return Some(*aPtr);
1050 }
1051 return Nothing();
1052}
1053
1054/*
1055 * Two Maybe<T> values are equal if
1056 * - both are Nothing, or
1057 * - both are Some, and the values they contain are equal.
1058 */
1059template <typename T>
1060constexpr bool operator==(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1061 static_assert(!std::is_reference_v<T>,
1062 "operator== is not defined for Maybe<T&>, compare values or "
1063 "addresses explicitly instead");
1064 if (aLHS.isNothing() != aRHS.isNothing()) {
1065 return false;
1066 }
1067 return aLHS.isNothing() || *aLHS == *aRHS;
1068}
1069
1070template <typename T>
1071constexpr bool operator!=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1072 return !(aLHS == aRHS);
1073}
1074
1075/*
1076 * We support comparison to Nothing to allow reasonable expressions like:
1077 * if (maybeValue == Nothing()) { ... }
1078 */
1079template <typename T>
1080constexpr bool operator==(const Maybe<T>& aLHS, const Nothing& aRHS) {
1081 return aLHS.isNothing();
1082}
1083
1084template <typename T>
1085constexpr bool operator!=(const Maybe<T>& aLHS, const Nothing& aRHS) {
1086 return !(aLHS == aRHS);
1087}
1088
1089template <typename T>
1090constexpr bool operator==(const Nothing& aLHS, const Maybe<T>& aRHS) {
1091 return aRHS.isNothing();
1092}
1093
1094template <typename T>
1095constexpr bool operator!=(const Nothing& aLHS, const Maybe<T>& aRHS) {
1096 return !(aLHS == aRHS);
1097}
1098
1099/*
1100 * Maybe<T> values are ordered in the same way T values are ordered, except that
1101 * Nothing comes before anything else.
1102 */
1103template <typename T>
1104constexpr bool operator<(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1105 if (aLHS.isNothing()) {
1106 return aRHS.isSome();
1107 }
1108 if (aRHS.isNothing()) {
1109 return false;
1110 }
1111 return *aLHS < *aRHS;
1112}
1113
1114template <typename T>
1115constexpr bool operator>(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1116 return !(aLHS < aRHS || aLHS == aRHS);
1117}
1118
1119template <typename T>
1120constexpr bool operator<=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1121 return aLHS < aRHS || aLHS == aRHS;
1122}
1123
1124template <typename T>
1125constexpr bool operator>=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1126 return !(aLHS < aRHS);
1127}
1128
1129template <typename T>
1130inline void ImplCycleCollectionTraverse(
1131 nsCycleCollectionTraversalCallback& aCallback, mozilla::Maybe<T>& aField,
1132 const char* aName, uint32_t aFlags = 0) {
1133 if (aField) {
1134 ImplCycleCollectionTraverse(aCallback, aField.ref(), aName, aFlags);
1135 }
1136}
1137
1138template <typename T>
1139inline void ImplCycleCollectionUnlink(mozilla::Maybe<T>& aField) {
1140 if (aField) {
1141 ImplCycleCollectionUnlink(aField.ref());
1142 }
1143}
1144
1145} // namespace mozilla
1146
1147#endif /* mozilla_Maybe_h */

/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/mozilla/MaybeStorageBase.h

1/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3/* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7/* Internal storage class used e.g. by Maybe and Result. This file doesn't
8 * contain any public declarations. */
9
10#ifndef mfbt_MaybeStorageBase_h
11#define mfbt_MaybeStorageBase_h
12
13#include <type_traits>
14#include <utility>
15
16namespace mozilla::detail {
17
18template <typename T>
19constexpr bool IsTriviallyDestructibleAndCopyable =
20 std::is_trivially_destructible_v<T> &&
21 (std::is_trivially_copy_constructible_v<T> ||
22 !std::is_copy_constructible_v<T>);
23
24template <typename T, bool TriviallyDestructibleAndCopyable =
25 IsTriviallyDestructibleAndCopyable<T>>
26struct MaybeStorageBase;
27
28template <typename T>
29struct MaybeStorageBase<T, false> {
30 protected:
31 using NonConstT = std::remove_const_t<T>;
32
33 union Union {
34 Union() {}
5
Returning without writing to 'this->val.retainedSizes.mIsSome'
35 explicit Union(const T& aVal) : val{aVal} {}
36 template <typename U,
37 typename = std::enable_if_t<std::is_move_constructible_v<U>>>
38 explicit Union(U&& aVal) : val{std::forward<U>(aVal)} {}
39 template <typename... Args>
40 explicit Union(std::in_place_t, Args&&... aArgs)
41 : val{std::forward<Args>(aArgs)...} {}
42
43 ~Union() {}
30
Calling implicit destructor for 'DominatorTree'
31
Calling implicit destructor for 'Maybe<mozilla::Vector<unsigned long, 0, js::SystemAllocPolicy>>'
32
Calling '~MaybeStorage'
44
45 NonConstT val;
46 } mStorage;
47
48 public:
49 MaybeStorageBase() = default;
4
Calling default constructor for 'Union'
6
Returning from default constructor for 'Union'
7
Returning without writing to 'this->mStorage.val.retainedSizes.mIsSome'
50 explicit MaybeStorageBase(const T& aVal) : mStorage{aVal} {}
51 explicit MaybeStorageBase(T&& aVal) : mStorage{std::move(aVal)} {}
52 template <typename... Args>
53 explicit MaybeStorageBase(std::in_place_t, Args&&... aArgs)
54 : mStorage{std::in_place, std::forward<Args>(aArgs)...} {}
55
56 const T* addr() const { return &mStorage.val; }
57 T* addr() { return &mStorage.val; }
58};
59
60template <typename T>
61struct MaybeStorageBase<T, true> {
62 protected:
63 using NonConstT = std::remove_const_t<T>;
64
65 union Union {
66 constexpr Union() : dummy() {}
67 constexpr explicit Union(const T& aVal) : val{aVal} {}
68 constexpr explicit Union(T&& aVal) : val{std::move(aVal)} {}
69 template <typename... Args>
70 constexpr explicit Union(std::in_place_t, Args&&... aArgs)
71 : val{std::forward<Args>(aArgs)...} {}
72
73 NonConstT val;
74 char dummy;
75 } mStorage;
76
77 public:
78 constexpr MaybeStorageBase() = default;
79 constexpr explicit MaybeStorageBase(const T& aVal) : mStorage{aVal} {}
80 constexpr explicit MaybeStorageBase(T&& aVal) : mStorage{std::move(aVal)} {}
81
82 template <typename... Args>
83 constexpr explicit MaybeStorageBase(std::in_place_t, Args&&... aArgs)
84 : mStorage{std::in_place, std::forward<Args>(aArgs)...} {}
85
86 constexpr const T* addr() const { return &mStorage.val; }
87 constexpr T* addr() { return &mStorage.val; }
88};
89
90} // namespace mozilla::detail
91
92#endif

/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h

1/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7#ifndef js_UbiNodeDominatorTree_h
8#define js_UbiNodeDominatorTree_h
9
10#include "mozilla/Attributes.h"
11#include "mozilla/DebugOnly.h"
12#include "mozilla/Maybe.h"
13#include "mozilla/UniquePtr.h"
14
15#include <utility>
16
17#include "js/AllocPolicy.h"
18#include "js/UbiNode.h"
19#include "js/UbiNodePostOrder.h"
20#include "js/Utility.h"
21#include "js/Vector.h"
22
23namespace JS {
24namespace ubi {
25
26/**
27 * In a directed graph with a root node `R`, a node `A` is said to "dominate" a
28 * node `B` iff every path from `R` to `B` contains `A`. A node `A` is said to
29 * be the "immediate dominator" of a node `B` iff it dominates `B`, is not `B`
30 * itself, and does not dominate any other nodes which also dominate `B` in
31 * turn.
32 *
33 * If we take every node from a graph `G` and create a new graph `T` with edges
34 * to each node from its immediate dominator, then `T` is a tree (each node has
35 * only one immediate dominator, or none if it is the root). This tree is called
36 * a "dominator tree".
37 *
38 * This class represents a dominator tree constructed from a `JS::ubi::Node`
39 * heap graph. The domination relationship and dominator trees are useful tools
40 * for analyzing heap graphs because they tell you:
41 *
42 * - Exactly what could be reclaimed by the GC if some node `A` became
43 * unreachable: those nodes which are dominated by `A`,
44 *
45 * - The "retained size" of a node in the heap graph, in contrast to its
46 * "shallow size". The "shallow size" is the space taken by a node itself,
47 * not counting anything it references. The "retained size" of a node is its
48 * shallow size plus the size of all the things that would be collected if
49 * the original node wasn't (directly or indirectly) referencing them. In
50 * other words, the retained size is the shallow size of a node plus the
51 * shallow sizes of every other node it dominates. For example, the root
52 * node in a binary tree might have a small shallow size that does not take
53 * up much space itself, but it dominates the rest of the binary tree and
54 * its retained size is therefore significant (assuming no external
55 * references into the tree).
56 *
57 * The simple, engineered algorithm presented in "A Simple, Fast Dominance
58 * Algorithm" by Cooper el al[0] is used to find dominators and construct the
59 * dominator tree. This algorithm runs in O(n^2) time, but is faster in practice
60 * than alternative algorithms with better theoretical running times, such as
61 * Lengauer-Tarjan which runs in O(e * log(n)). The big caveat to that statement
62 * is that Cooper et al found it is faster in practice *on control flow graphs*
63 * and I'm not convinced that this property also holds on *heap* graphs. That
64 * said, the implementation of this algorithm is *much* simpler than
65 * Lengauer-Tarjan and has been found to be fast enough at least for the time
66 * being.
67 *
68 * [0]: http://www.cs.rice.edu/~keith/EMBED/dom.pdf
69 */
70class JS_PUBLIC_API DominatorTree {
71 private:
72 // Types.
73
74 using PredecessorSets = js::HashMap<Node, NodeSetPtr, js::DefaultHasher<Node>,
75 js::SystemAllocPolicy>;
76 using NodeToIndexMap = js::HashMap<Node, uint32_t, js::DefaultHasher<Node>,
77 js::SystemAllocPolicy>;
78 class DominatedSets;
79
80 public:
81 class DominatedSetRange;
82
83 /**
84 * A pointer to an immediately dominated node.
85 *
86 * Don't use this type directly; it is no safer than regular pointers. This
87 * is only for use indirectly with range-based for loops and
88 * `DominatedSetRange`.
89 *
90 * @see JS::ubi::DominatorTree::getDominatedSet
91 */
92 class DominatedNodePtr {
93 friend class DominatedSetRange;
94
95 const JS::ubi::Vector<Node>& postOrder;
96 const uint32_t* ptr;
97
98 DominatedNodePtr(const JS::ubi::Vector<Node>& postOrder,
99 const uint32_t* ptr)
100 : postOrder(postOrder), ptr(ptr) {}
101
102 public:
103 bool operator!=(const DominatedNodePtr& rhs) const {
104 return ptr != rhs.ptr;
105 }
106 void operator++() { ptr++; }
107 const Node& operator*() const { return postOrder[*ptr]; }
108 };
109
110 /**
111 * A range of immediately dominated `JS::ubi::Node`s for use with
112 * range-based for loops.
113 *
114 * @see JS::ubi::DominatorTree::getDominatedSet
115 */
116 class DominatedSetRange {
117 friend class DominatedSets;
118
119 const JS::ubi::Vector<Node>& postOrder;
120 const uint32_t* beginPtr;
121 const uint32_t* endPtr;
122
123 DominatedSetRange(JS::ubi::Vector<Node>& postOrder, const uint32_t* begin,
124 const uint32_t* end)
125 : postOrder(postOrder), beginPtr(begin), endPtr(end) {
126 MOZ_ASSERT(begin <= end)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(begin <= end)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(begin <= end))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("begin <= end"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 126); AnnotateMozCrashReason("MOZ_ASSERT" "(" "begin <= end"
")"); do { *((volatile int*)__null) = 126; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
127 }
128
129 public:
130 DominatedNodePtr begin() const {
131 MOZ_ASSERT(beginPtr <= endPtr)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(beginPtr <= endPtr)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(beginPtr <= endPtr))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("beginPtr <= endPtr"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 131); AnnotateMozCrashReason("MOZ_ASSERT" "(" "beginPtr <= endPtr"
")"); do { *((volatile int*)__null) = 131; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
132 return DominatedNodePtr(postOrder, beginPtr);
133 }
134
135 DominatedNodePtr end() const { return DominatedNodePtr(postOrder, endPtr); }
136
137 size_t length() const {
138 MOZ_ASSERT(beginPtr <= endPtr)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(beginPtr <= endPtr)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(beginPtr <= endPtr))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("beginPtr <= endPtr"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 138); AnnotateMozCrashReason("MOZ_ASSERT" "(" "beginPtr <= endPtr"
")"); do { *((volatile int*)__null) = 138; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
139 return endPtr - beginPtr;
140 }
141
142 /**
143 * Safely skip ahead `n` dominators in the range, in O(1) time.
144 *
145 * Example usage:
146 *
147 * mozilla::Maybe<DominatedSetRange> range =
148 * myDominatorTree.getDominatedSet(myNode);
149 * if (range.isNothing()) {
150 * // Handle unknown nodes however you see fit...
151 * return false;
152 * }
153 *
154 * // Don't care about the first ten, for whatever reason.
155 * range->skip(10);
156 * for (const JS::ubi::Node& dominatedNode : *range) {
157 * // ...
158 * }
159 */
160 void skip(size_t n) {
161 beginPtr += n;
162 if (beginPtr > endPtr) {
163 beginPtr = endPtr;
164 }
165 }
166 };
167
168 private:
169 /**
170 * The set of all dominated sets in a dominator tree.
171 *
172 * Internally stores the sets in a contiguous array, with a side table of
173 * indices into that contiguous array to denote the start index of each
174 * individual set.
175 */
176 class DominatedSets {
177 JS::ubi::Vector<uint32_t> dominated;
178 JS::ubi::Vector<uint32_t> indices;
179
180 DominatedSets(JS::ubi::Vector<uint32_t>&& dominated,
181 JS::ubi::Vector<uint32_t>&& indices)
182 : dominated(std::move(dominated)), indices(std::move(indices)) {}
183
184 public:
185 // DominatedSets is not copy-able.
186 DominatedSets(const DominatedSets& rhs) = delete;
187 DominatedSets& operator=(const DominatedSets& rhs) = delete;
188
189 // DominatedSets is move-able.
190 DominatedSets(DominatedSets&& rhs)
191 : dominated(std::move(rhs.dominated)), indices(std::move(rhs.indices)) {
192 MOZ_ASSERT(this != &rhs, "self-move not allowed")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 not allowed" ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 192); AnnotateMozCrashReason("MOZ_ASSERT" "(" "this != &rhs"
") (" "self-move not allowed" ")"); do { *((volatile int*)__null
) = 192; __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
193 }
194 DominatedSets& operator=(DominatedSets&& rhs) {
195 this->~DominatedSets();
196 new (this) DominatedSets(std::move(rhs));
197 return *this;
198 }
199
200 /**
201 * Create the DominatedSets given the mapping of a node index to its
202 * immediate dominator. Returns `Some` on success, `Nothing` on OOM
203 * failure.
204 */
205 static mozilla::Maybe<DominatedSets> Create(
206 const JS::ubi::Vector<uint32_t>& doms) {
207 auto length = doms.length();
208 MOZ_ASSERT(length < UINT32_MAX)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(length < (4294967295U))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(length < (4294967295U))))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("length < (4294967295U)"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 208); AnnotateMozCrashReason("MOZ_ASSERT" "(" "length < (4294967295U)"
")"); do { *((volatile int*)__null) = 208; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
209
210 // Create a vector `dominated` holding a flattened set of buckets of
211 // immediately dominated children nodes, with a lookup table
212 // `indices` mapping from each node to the beginning of its bucket.
213 //
214 // This has three phases:
215 //
216 // 1. Iterate over the full set of nodes and count up the size of
217 // each bucket. These bucket sizes are temporarily stored in the
218 // `indices` vector.
219 //
220 // 2. Convert the `indices` vector to store the cumulative sum of
221 // the sizes of all buckets before each index, resulting in a
222 // mapping from node index to one past the end of that node's
223 // bucket.
224 //
225 // 3. Iterate over the full set of nodes again, filling in bucket
226 // entries from the end of the bucket's range to its
227 // beginning. This decrements each index as a bucket entry is
228 // filled in. After having filled in all of a bucket's entries,
229 // the index points to the start of the bucket.
230
231 JS::ubi::Vector<uint32_t> dominated;
232 JS::ubi::Vector<uint32_t> indices;
233 if (!dominated.growBy(length) || !indices.growBy(length)) {
234 return mozilla::Nothing();
235 }
236
237 // 1
238 memset(indices.begin(), 0, length * sizeof(uint32_t));
239 for (uint32_t i = 0; i < length; i++) {
240 indices[doms[i]]++;
241 }
242
243 // 2
244 uint32_t sumOfSizes = 0;
245 for (uint32_t i = 0; i < length; i++) {
246 sumOfSizes += indices[i];
247 MOZ_ASSERT(sumOfSizes <= length)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(sumOfSizes <= length)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(sumOfSizes <= length))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("sumOfSizes <= length"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 247); AnnotateMozCrashReason("MOZ_ASSERT" "(" "sumOfSizes <= length"
")"); do { *((volatile int*)__null) = 247; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
248 indices[i] = sumOfSizes;
249 }
250
251 // 3
252 for (uint32_t i = 0; i < length; i++) {
253 auto idxOfDom = doms[i];
254 indices[idxOfDom]--;
255 dominated[indices[idxOfDom]] = i;
256 }
257
258#ifdef DEBUG1
259 // Assert that our buckets are non-overlapping and don't run off the
260 // end of the vector.
261 uint32_t lastIndex = 0;
262 for (uint32_t i = 0; i < length; i++) {
263 MOZ_ASSERT(indices[i] >= lastIndex)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(indices[i] >= lastIndex)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(indices[i] >= lastIndex))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("indices[i] >= lastIndex"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 263); AnnotateMozCrashReason("MOZ_ASSERT" "(" "indices[i] >= lastIndex"
")"); do { *((volatile int*)__null) = 263; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
264 MOZ_ASSERT(indices[i] < length)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(indices[i] < length)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(indices[i] < length))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("indices[i] < length"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 264); AnnotateMozCrashReason("MOZ_ASSERT" "(" "indices[i] < length"
")"); do { *((volatile int*)__null) = 264; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
265 lastIndex = indices[i];
266 }
267#endif
268
269 return mozilla::Some(
270 DominatedSets(std::move(dominated), std::move(indices)));
271 }
272
273 /**
274 * Get the set of nodes immediately dominated by the node at
275 * `postOrder[nodeIndex]`.
276 */
277 DominatedSetRange dominatedSet(JS::ubi::Vector<Node>& postOrder,
278 uint32_t nodeIndex) const {
279 MOZ_ASSERT(postOrder.length() == indices.length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder.length() == indices.length())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(postOrder.length() == indices.length()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("postOrder.length() == indices.length()"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 279); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() == indices.length()"
")"); do { *((volatile int*)__null) = 279; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
280 MOZ_ASSERT(nodeIndex < indices.length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(nodeIndex < indices.length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(nodeIndex < indices.length
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("nodeIndex < indices.length()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 280); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nodeIndex < indices.length()"
")"); do { *((volatile int*)__null) = 280; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
281 auto end = nodeIndex == indices.length() - 1
282 ? dominated.end()
283 : &dominated[indices[nodeIndex + 1]];
284 return DominatedSetRange(postOrder, &dominated[indices[nodeIndex]], end);
285 }
286 };
287
288 private:
289 // Data members.
290 JS::ubi::Vector<Node> postOrder;
291 NodeToIndexMap nodeToPostOrderIndex;
292 JS::ubi::Vector<uint32_t> doms;
293 DominatedSets dominatedSets;
294 mozilla::Maybe<JS::ubi::Vector<JS::ubi::Node::Size>> retainedSizes;
295
296 private:
297 // We use `UNDEFINED` as a sentinel value in the `doms` vector to signal
298 // that we haven't found any dominators for the node at the corresponding
299 // index in `postOrder` yet.
300 static const uint32_t UNDEFINED = UINT32_MAX(4294967295U);
301
302 DominatorTree(JS::ubi::Vector<Node>&& postOrder,
303 NodeToIndexMap&& nodeToPostOrderIndex,
304 JS::ubi::Vector<uint32_t>&& doms, DominatedSets&& dominatedSets)
305 : postOrder(std::move(postOrder)),
306 nodeToPostOrderIndex(std::move(nodeToPostOrderIndex)),
307 doms(std::move(doms)),
308 dominatedSets(std::move(dominatedSets)),
309 retainedSizes(mozilla::Nothing()) {}
310
311 static uint32_t intersect(JS::ubi::Vector<uint32_t>& doms, uint32_t finger1,
312 uint32_t finger2) {
313 while (finger1 != finger2) {
314 if (finger1 < finger2) {
315 finger1 = doms[finger1];
316 } else if (finger2 < finger1) {
317 finger2 = doms[finger2];
318 }
319 }
320 return finger1;
321 }
322
323 // Do the post order traversal of the heap graph and populate our
324 // predecessor sets.
325 [[nodiscard]] static bool doTraversal(JSContext* cx, AutoCheckCannotGC& noGC,
326 const Node& root,
327 JS::ubi::Vector<Node>& postOrder,
328 PredecessorSets& predecessorSets) {
329 uint32_t nodeCount = 0;
330 auto onNode = [&](const Node& node) {
331 nodeCount++;
332 if (MOZ_UNLIKELY(nodeCount == UINT32_MAX)(__builtin_expect(!!(nodeCount == (4294967295U)), 0))) {
333 return false;
334 }
335 return postOrder.append(node);
336 };
337
338 auto onEdge = [&](const Node& origin, const Edge& edge) {
339 auto p = predecessorSets.lookupForAdd(edge.referent);
340 if (!p) {
341 mozilla::UniquePtr<NodeSet, DeletePolicy<NodeSet>> set(
342 js_new<NodeSet>());
343 if (!set || !predecessorSets.add(p, edge.referent, std::move(set))) {
344 return false;
345 }
346 }
347 MOZ_ASSERT(p && p->value())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(p && p->value())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(p && p->value()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("p && p->value()"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 347); AnnotateMozCrashReason("MOZ_ASSERT" "(" "p && p->value()"
")"); do { *((volatile int*)__null) = 347; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
348 return p->value()->put(origin);
349 };
350
351 PostOrder traversal(cx, noGC);
352 return traversal.addStart(root) && traversal.traverse(onNode, onEdge);
353 }
354
355 // Populates the given `map` with an entry for each node to its index in
356 // `postOrder`.
357 [[nodiscard]] static bool mapNodesToTheirIndices(
358 JS::ubi::Vector<Node>& postOrder, NodeToIndexMap& map) {
359 MOZ_ASSERT(map.empty())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(map.empty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(map.empty()))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("map.empty()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 359); AnnotateMozCrashReason("MOZ_ASSERT" "(" "map.empty()"
")"); do { *((volatile int*)__null) = 359; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
360 MOZ_ASSERT(postOrder.length() < UINT32_MAX)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder.length() < (4294967295U))>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(postOrder.length() < (4294967295U)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("postOrder.length() < (4294967295U)"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 360); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() < (4294967295U)"
")"); do { *((volatile int*)__null) = 360; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
361 uint32_t length = postOrder.length();
362 if (!map.reserve(length)) {
363 return false;
364 }
365 for (uint32_t i = 0; i < length; i++) {
366 map.putNewInfallible(postOrder[i], i);
367 }
368 return true;
369 }
370
371 // Convert the Node -> NodeSet predecessorSets to a index -> Vector<index>
372 // form.
373 [[nodiscard]] static bool convertPredecessorSetsToVectors(
374 const Node& root, JS::ubi::Vector<Node>& postOrder,
375 PredecessorSets& predecessorSets, NodeToIndexMap& nodeToPostOrderIndex,
376 JS::ubi::Vector<JS::ubi::Vector<uint32_t>>& predecessorVectors) {
377 MOZ_ASSERT(postOrder.length() < UINT32_MAX)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder.length() < (4294967295U))>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(postOrder.length() < (4294967295U)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("postOrder.length() < (4294967295U)"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 377); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() < (4294967295U)"
")"); do { *((volatile int*)__null) = 377; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
378 uint32_t length = postOrder.length();
379
380 MOZ_ASSERT(predecessorVectors.length() == 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(predecessorVectors.length() == 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(predecessorVectors.length() ==
0))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("predecessorVectors.length() == 0", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 380); AnnotateMozCrashReason("MOZ_ASSERT" "(" "predecessorVectors.length() == 0"
")"); do { *((volatile int*)__null) = 380; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
381 if (!predecessorVectors.growBy(length)) {
382 return false;
383 }
384
385 for (uint32_t i = 0; i < length - 1; i++) {
386 auto& node = postOrder[i];
387 MOZ_ASSERT(node != root,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(node != root)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(node != root))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("node != root" " ("
"Only the last node should be root, since this was a post " "order traversal."
")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 389); AnnotateMozCrashReason("MOZ_ASSERT" "(" "node != root"
") (" "Only the last node should be root, since this was a post "
"order traversal." ")"); do { *((volatile int*)__null) = 389
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
388 "Only the last node should be root, since this was a post "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(node != root)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(node != root))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("node != root" " ("
"Only the last node should be root, since this was a post " "order traversal."
")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 389); AnnotateMozCrashReason("MOZ_ASSERT" "(" "node != root"
") (" "Only the last node should be root, since this was a post "
"order traversal." ")"); do { *((volatile int*)__null) = 389
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
389 "order traversal.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(node != root)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(node != root))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("node != root" " ("
"Only the last node should be root, since this was a post " "order traversal."
")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 389); AnnotateMozCrashReason("MOZ_ASSERT" "(" "node != root"
") (" "Only the last node should be root, since this was a post "
"order traversal." ")"); do { *((volatile int*)__null) = 389
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
;
390
391 auto ptr = predecessorSets.lookup(node);
392 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" " (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 395); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ") (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")"); do
{ *((volatile int*)__null) = 395; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
393 "Because this isn't the root, it had better have "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ptr)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(ptr))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("ptr" " (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 395); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ") (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")"); do
{ *((volatile int*)__null) = 395; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
394 "predecessors, or else how "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ptr)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(ptr))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("ptr" " (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 395); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ") (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")"); do
{ *((volatile int*)__null) = 395; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
395 "did we even find it.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ptr)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(ptr))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("ptr" " (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 395); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ") (" "Because this isn't the root, it had better have "
"predecessors, or else how " "did we even find it." ")"); do
{ *((volatile int*)__null) = 395; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
396
397 auto& predecessors = ptr->value();
398 if (!predecessorVectors[i].reserve(predecessors->count())) {
399 return false;
400 }
401 for (auto range = predecessors->all(); !range.empty(); range.popFront()) {
402 auto ptr = nodeToPostOrderIndex.lookup(range.front());
403 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", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 403); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ")"); do
{ *((volatile int*)__null) = 403; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
404 predecessorVectors[i].infallibleAppend(ptr->value());
405 }
406 }
407 predecessorSets.clearAndCompact();
408 return true;
409 }
410
411 // Initialize `doms` such that the immediate dominator of the `root` is the
412 // `root` itself and all others are `UNDEFINED`.
413 [[nodiscard]] static bool initializeDominators(
414 JS::ubi::Vector<uint32_t>& doms, uint32_t length) {
415 MOZ_ASSERT(doms.length() == 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(doms.length() == 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(doms.length() == 0))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("doms.length() == 0"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 415); AnnotateMozCrashReason("MOZ_ASSERT" "(" "doms.length() == 0"
")"); do { *((volatile int*)__null) = 415; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
416 if (!doms.growByUninitialized(length)) {
417 return false;
418 }
419 doms[length - 1] = length - 1;
420 for (uint32_t i = 0; i < length - 1; i++) {
421 doms[i] = UNDEFINED;
422 }
423 return true;
424 }
425
426 void assertSanity() const {
427 MOZ_ASSERT(postOrder.length() == doms.length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder.length() == doms.length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(postOrder.length() == doms.length
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("postOrder.length() == doms.length()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 427); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() == doms.length()"
")"); do { *((volatile int*)__null) = 427; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
428 MOZ_ASSERT(postOrder.length() == nodeToPostOrderIndex.count())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder.length() == nodeToPostOrderIndex.count())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(postOrder.length() == nodeToPostOrderIndex.count()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("postOrder.length() == nodeToPostOrderIndex.count()"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 428); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() == nodeToPostOrderIndex.count()"
")"); do { *((volatile int*)__null) = 428; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
429 MOZ_ASSERT_IF(retainedSizes.isSome(),do { if (retainedSizes.isSome()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(postOrder.length
() == retainedSizes->length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(postOrder.length() == retainedSizes
->length()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("postOrder.length() == retainedSizes->length()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 430); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() == retainedSizes->length()"
")"); do { *((volatile int*)__null) = 430; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
430 postOrder.length() == retainedSizes->length())do { if (retainedSizes.isSome()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(postOrder.length
() == retainedSizes->length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(postOrder.length() == retainedSizes
->length()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("postOrder.length() == retainedSizes->length()", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 430); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() == retainedSizes->length()"
")"); do { *((volatile int*)__null) = 430; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
431 }
432
433 [[nodiscard]] bool computeRetainedSizes(mozilla::MallocSizeOf mallocSizeOf) {
434 MOZ_ASSERT(retainedSizes.isNothing())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(retainedSizes.isNothing())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(retainedSizes.isNothing())))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("retainedSizes.isNothing()"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 434); AnnotateMozCrashReason("MOZ_ASSERT" "(" "retainedSizes.isNothing()"
")"); do { *((volatile int*)__null) = 434; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
435 auto length = postOrder.length();
436
437 retainedSizes.emplace();
438 if (!retainedSizes->growBy(length)) {
439 retainedSizes = mozilla::Nothing();
440 return false;
441 }
442
443 // Iterate in forward order so that we know all of a node's children in
444 // the dominator tree have already had their retained size
445 // computed. Then we can simply say that the retained size of a node is
446 // its shallow size (JS::ubi::Node::size) plus the retained sizes of its
447 // immediate children in the tree.
448
449 for (uint32_t i = 0; i < length; i++) {
450 auto size = postOrder[i].size(mallocSizeOf);
451
452 for (const auto& dominated : dominatedSets.dominatedSet(postOrder, i)) {
453 // The root node dominates itself, but shouldn't contribute to
454 // its own retained size.
455 if (dominated == postOrder[length - 1]) {
456 MOZ_ASSERT(i == length - 1)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(i == length - 1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(i == length - 1))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("i == length - 1"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 456); AnnotateMozCrashReason("MOZ_ASSERT" "(" "i == length - 1"
")"); do { *((volatile int*)__null) = 456; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
457 continue;
458 }
459
460 auto ptr = nodeToPostOrderIndex.lookup(dominated);
461 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", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 461); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ptr" ")"); do
{ *((volatile int*)__null) = 461; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
462 auto idxOfDominated = ptr->value();
463 MOZ_ASSERT(idxOfDominated < i)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(idxOfDominated < i)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(idxOfDominated < i))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("idxOfDominated < i"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 463); AnnotateMozCrashReason("MOZ_ASSERT" "(" "idxOfDominated < i"
")"); do { *((volatile int*)__null) = 463; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
464 size += retainedSizes.ref()[idxOfDominated];
465 }
466
467 retainedSizes.ref()[i] = size;
468 }
469
470 return true;
471 }
472
473 public:
474 // DominatorTree is not copy-able.
475 DominatorTree(const DominatorTree&) = delete;
476 DominatorTree& operator=(const DominatorTree&) = delete;
477
478 // DominatorTree is move-able.
479 DominatorTree(DominatorTree&& rhs)
480 : postOrder(std::move(rhs.postOrder)),
481 nodeToPostOrderIndex(std::move(rhs.nodeToPostOrderIndex)),
482 doms(std::move(rhs.doms)),
483 dominatedSets(std::move(rhs.dominatedSets)),
484 retainedSizes(std::move(rhs.retainedSizes)) {
485 MOZ_ASSERT(this != &rhs, "self-move is not allowed")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 is not allowed" ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 485); AnnotateMozCrashReason("MOZ_ASSERT" "(" "this != &rhs"
") (" "self-move is not allowed" ")"); do { *((volatile int*
)__null) = 485; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
486 }
487 DominatorTree& operator=(DominatorTree&& rhs) {
488 this->~DominatorTree();
489 new (this) DominatorTree(std::move(rhs));
490 return *this;
491 }
492
493 /**
494 * Construct a `DominatorTree` of the heap graph visible from `root`. The
495 * `root` is also used as the root of the resulting dominator tree.
496 *
497 * The resulting `DominatorTree` instance must not outlive the
498 * `JS::ubi::Node` graph it was constructed from.
499 *
500 * - For `JS::ubi::Node` graphs backed by the live heap graph, this means
501 * that the `DominatorTree`'s lifetime _must_ be contained within the
502 * scope of the provided `AutoCheckCannotGC` reference because a GC will
503 * invalidate the nodes.
504 *
505 * - For `JS::ubi::Node` graphs backed by some other offline structure
506 * provided by the embedder, the resulting `DominatorTree`'s lifetime is
507 * bounded by that offline structure's lifetime.
508 *
509 * In practice, this means that within SpiderMonkey we must treat
510 * `DominatorTree` as if it were backed by the live heap graph and trust
511 * that embedders with knowledge of the graph's implementation will do the
512 * Right Thing.
513 *
514 * Returns `mozilla::Nothing()` on OOM failure. It is the caller's
515 * responsibility to handle and report the OOM.
516 */
517 static mozilla::Maybe<DominatorTree> Create(JSContext* cx,
518 AutoCheckCannotGC& noGC,
519 const Node& root) {
520 JS::ubi::Vector<Node> postOrder;
521 PredecessorSets predecessorSets;
522 if (!doTraversal(cx, noGC, root, postOrder, predecessorSets)) {
523 return mozilla::Nothing();
524 }
525
526 MOZ_ASSERT(postOrder.length() < UINT32_MAX)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder.length() < (4294967295U))>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(postOrder.length() < (4294967295U)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("postOrder.length() < (4294967295U)"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 526); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder.length() < (4294967295U)"
")"); do { *((volatile int*)__null) = 526; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
527 uint32_t length = postOrder.length();
528 MOZ_ASSERT(postOrder[length - 1] == root)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder[length - 1] == root)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(postOrder[length - 1] == root
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"postOrder[length - 1] == root", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 528); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder[length - 1] == root"
")"); do { *((volatile int*)__null) = 528; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
529
530 // From here on out we wish to avoid hash table lookups, and we use
531 // indices into `postOrder` instead of actual nodes wherever
532 // possible. This greatly improves the performance of this
533 // implementation, but we have to pay a little bit of upfront cost to
534 // convert our data structures to play along first.
535
536 NodeToIndexMap nodeToPostOrderIndex(postOrder.length());
537 if (!mapNodesToTheirIndices(postOrder, nodeToPostOrderIndex)) {
538 return mozilla::Nothing();
539 }
540
541 JS::ubi::Vector<JS::ubi::Vector<uint32_t>> predecessorVectors;
542 if (!convertPredecessorSetsToVectors(root, postOrder, predecessorSets,
543 nodeToPostOrderIndex,
544 predecessorVectors))
545 return mozilla::Nothing();
546
547 JS::ubi::Vector<uint32_t> doms;
548 if (!initializeDominators(doms, length)) {
549 return mozilla::Nothing();
550 }
551
552 bool changed = true;
553 while (changed) {
554 changed = false;
555
556 // Iterate over the non-root nodes in reverse post order.
557 for (uint32_t indexPlusOne = length - 1; indexPlusOne > 0;
558 indexPlusOne--) {
559 MOZ_ASSERT(postOrder[indexPlusOne - 1] != root)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(postOrder[indexPlusOne - 1] != root)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(postOrder[indexPlusOne - 1] !=
root))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("postOrder[indexPlusOne - 1] != root", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 559); AnnotateMozCrashReason("MOZ_ASSERT" "(" "postOrder[indexPlusOne - 1] != root"
")"); do { *((volatile int*)__null) = 559; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
560
561 // Take the intersection of every predecessor's dominator set;
562 // that is the current best guess at the immediate dominator for
563 // this node.
564
565 uint32_t newIDomIdx = UNDEFINED;
566
567 auto& predecessors = predecessorVectors[indexPlusOne - 1];
568 auto range = predecessors.all();
569 for (; !range.empty(); range.popFront()) {
570 auto idx = range.front();
571 if (doms[idx] != UNDEFINED) {
572 newIDomIdx = idx;
573 break;
574 }
575 }
576
577 MOZ_ASSERT(newIDomIdx != UNDEFINED,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(newIDomIdx != UNDEFINED)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(newIDomIdx != UNDEFINED))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("newIDomIdx != UNDEFINED"
" (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 582); AnnotateMozCrashReason("MOZ_ASSERT" "(" "newIDomIdx != UNDEFINED"
") (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")"); do { *((volatile int
*)__null) = 582; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
578 "Because the root is initialized to dominate itself and is "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(newIDomIdx != UNDEFINED)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(newIDomIdx != UNDEFINED))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("newIDomIdx != UNDEFINED"
" (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 582); AnnotateMozCrashReason("MOZ_ASSERT" "(" "newIDomIdx != UNDEFINED"
") (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")"); do { *((volatile int
*)__null) = 582; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
579 "the first "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(newIDomIdx != UNDEFINED)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(newIDomIdx != UNDEFINED))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("newIDomIdx != UNDEFINED"
" (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 582); AnnotateMozCrashReason("MOZ_ASSERT" "(" "newIDomIdx != UNDEFINED"
") (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")"); do { *((volatile int
*)__null) = 582; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
580 "node in every path, there must exist a predecessor to this "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(newIDomIdx != UNDEFINED)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(newIDomIdx != UNDEFINED))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("newIDomIdx != UNDEFINED"
" (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 582); AnnotateMozCrashReason("MOZ_ASSERT" "(" "newIDomIdx != UNDEFINED"
") (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")"); do { *((volatile int
*)__null) = 582; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
581 "node that "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(newIDomIdx != UNDEFINED)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(newIDomIdx != UNDEFINED))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("newIDomIdx != UNDEFINED"
" (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 582); AnnotateMozCrashReason("MOZ_ASSERT" "(" "newIDomIdx != UNDEFINED"
") (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")"); do { *((volatile int
*)__null) = 582; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
582 "also has a dominator.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(newIDomIdx != UNDEFINED)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(newIDomIdx != UNDEFINED))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("newIDomIdx != UNDEFINED"
" (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")", "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 582); AnnotateMozCrashReason("MOZ_ASSERT" "(" "newIDomIdx != UNDEFINED"
") (" "Because the root is initialized to dominate itself and is "
"the first " "node in every path, there must exist a predecessor to this "
"node that " "also has a dominator." ")"); do { *((volatile int
*)__null) = 582; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
583
584 for (; !range.empty(); range.popFront()) {
585 auto idx = range.front();
586 if (doms[idx] != UNDEFINED) {
587 newIDomIdx = intersect(doms, newIDomIdx, idx);
588 }
589 }
590
591 // If the immediate dominator changed, we will have to do
592 // another pass of the outer while loop to continue the forward
593 // dataflow.
594 if (newIDomIdx != doms[indexPlusOne - 1]) {
595 doms[indexPlusOne - 1] = newIDomIdx;
596 changed = true;
597 }
598 }
599 }
600
601 auto maybeDominatedSets = DominatedSets::Create(doms);
602 if (maybeDominatedSets.isNothing()) {
603 return mozilla::Nothing();
604 }
605
606 return mozilla::Some(
607 DominatorTree(std::move(postOrder), std::move(nodeToPostOrderIndex),
608 std::move(doms), std::move(*maybeDominatedSets)));
609 }
610
611 /**
612 * Get the root node for this dominator tree.
613 */
614 const Node& root() const { return postOrder[postOrder.length() - 1]; }
615
616 /**
617 * Return the immediate dominator of the given `node`. If `node` was not
618 * reachable from the `root` that this dominator tree was constructed from,
619 * then return the null `JS::ubi::Node`.
620 */
621 Node getImmediateDominator(const Node& node) const {
622 assertSanity();
623 auto ptr = nodeToPostOrderIndex.lookup(node);
624 if (!ptr) {
625 return Node();
626 }
627
628 auto idx = ptr->value();
629 MOZ_ASSERT(idx < postOrder.length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(idx < postOrder.length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(idx < postOrder.length())
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("idx < postOrder.length()"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 629); AnnotateMozCrashReason("MOZ_ASSERT" "(" "idx < postOrder.length()"
")"); do { *((volatile int*)__null) = 629; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
630 return postOrder[doms[idx]];
631 }
632
633 /**
634 * Get the set of nodes immediately dominated by the given `node`. If `node`
635 * is not a member of this dominator tree, return `Nothing`.
636 *
637 * Example usage:
638 *
639 * mozilla::Maybe<DominatedSetRange> range =
640 * myDominatorTree.getDominatedSet(myNode);
641 * if (range.isNothing()) {
642 * // Handle unknown node however you see fit...
643 * return false;
644 * }
645 *
646 * for (const JS::ubi::Node& dominatedNode : *range) {
647 * // Do something with each immediately dominated node...
648 * }
649 */
650 mozilla::Maybe<DominatedSetRange> getDominatedSet(const Node& node) {
651 assertSanity();
652 auto ptr = nodeToPostOrderIndex.lookup(node);
653 if (!ptr) {
654 return mozilla::Nothing();
655 }
656
657 auto idx = ptr->value();
658 MOZ_ASSERT(idx < postOrder.length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(idx < postOrder.length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(idx < postOrder.length())
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("idx < postOrder.length()"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 658); AnnotateMozCrashReason("MOZ_ASSERT" "(" "idx < postOrder.length()"
")"); do { *((volatile int*)__null) = 658; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
659 return mozilla::Some(dominatedSets.dominatedSet(postOrder, idx));
660 }
661
662 /**
663 * Get the retained size of the given `node`. The size is placed in
664 * `outSize`, or 0 if `node` is not a member of the dominator tree. Returns
665 * false on OOM failure, leaving `outSize` unchanged.
666 */
667 [[nodiscard]] bool getRetainedSize(const Node& node,
668 mozilla::MallocSizeOf mallocSizeOf,
669 Node::Size& outSize) {
670 assertSanity();
671 auto ptr = nodeToPostOrderIndex.lookup(node);
672 if (!ptr) {
673 outSize = 0;
674 return true;
675 }
676
677 if (retainedSizes.isNothing() && !computeRetainedSizes(mallocSizeOf)) {
678 return false;
679 }
680
681 auto idx = ptr->value();
682 MOZ_ASSERT(idx < postOrder.length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(idx < postOrder.length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(idx < postOrder.length())
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("idx < postOrder.length()"
, "/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/js/UbiNodeDominatorTree.h"
, 682); AnnotateMozCrashReason("MOZ_ASSERT" "(" "idx < postOrder.length()"
")"); do { *((volatile int*)__null) = 682; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
683 outSize = retainedSizes.ref()[idx];
684 return true;
685 }
686};
687
688} // namespace ubi
689} // namespace JS
690
691#endif // js_UbiNodeDominatorTree_h