Debian Codegraph @

js/src/devtools/rootAnalysis/annotations.js

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 /* -*- indent-tabs-mode: nil; js-indent-level: 4 -*- */
6
7 "use strict";
8
9 // Ignore calls made through these function pointers
10 var ignoreIndirectCalls = {
11 "mallocSizeOf" : true,
12 "aMallocSizeOf" : true,
13 "__conv" : true,
14 "__convf" : true,
15 "callback_newtable": true,
16 "gLogAddRefFunc": true,
17 "gLogReleaseFunc": true,
18 };
19
20 // Types that when constructed with no arguments, are "safe" values (they do
21 // not contain GC pointers, or values with nontrivial destructors.)
22 var typesWithSafeConstructors = new Set([
23 "mozilla::Maybe",
24 "mozilla::dom::Nullable",
25 "mozilla::dom::Optional",
26 "mozilla::UniquePtr",
27 "js::UniquePtr"
28 ]);
29
30 var resetterMethods = {
31 'mozilla::Maybe': new Set(["reset"]),
32 'mozilla::UniquePtr': new Set(["reset"]),
33 'js::UniquePtr': new Set(["reset"]),
34 'mozilla::dom::Nullable': new Set(["SetNull"]),
35 'mozilla::dom::TypedArray_base': new Set(["Reset"]),
36 'RefPtr': new Set(["forget"]),
37 'nsCOMPtr': new Set(["forget"]),
38 'JS::AutoAssertNoGC': new Set(["reset"]),
39 };
40
41 function isRefcountedDtor(name) {
42 return name.includes("::~RefPtr(") || name.includes("::~nsCOMPtr(");
43 }
44
45 function indirectCallCannotGC(fullCaller, fullVariable)
46 {
47 var caller = readable(fullCaller);
48
49 // This is usually a simple variable name, but sometimes a full name gets
50 // passed through. And sometimes that name is truncated. Examples:
51 // _ZL13gAbortHandler$mozalloc_oom.cpp:void (* gAbortHandler)(size_t)
52 // _ZL14pMutexUnlockFn$umutex.cpp:void (* pMutexUnlockFn)(const void*
53 var name = readable(fullVariable);
54
55 if (name in ignoreIndirectCalls)
56 return true;
57
58 if (name == "mapper" && caller == "ptio.c:pt_MapError")
59 return true;
60
61 if (name == "params" && caller == "PR_ExplodeTime")
62 return true;
63
64 // hook called during script finalization which cannot GC.
65 if (/CallDestroyScriptHook/.test(caller))
66 return true;
67
68 // Call through a 'callback' function pointer, in a place where we're going
69 // to be throwing a JS exception.
70 if (name == "callback" && caller.includes("js::ErrorToException"))
71 return true;
72
73 // The math cache only gets called with non-GC math functions.
74 if (name == "f" && caller.includes("js::MathCache::lookup"))
75 return true;
76
77 // It would probably be better to somehow rewrite PR_CallOnce(foo) into a
78 // call of foo, but for now just assume that nobody is crazy enough to use
79 // PR_CallOnce with a function that can GC.
80 if (name == "func" && caller == "PR_CallOnce")
81 return true;
82
83 return false;
84 }
85
86 // Ignore calls through functions pointers with these types
87 var ignoreClasses = {
88 "JSStringFinalizer" : true,
89 "SprintfState" : true,
90 "SprintfStateStr" : true,
91 "JSLocaleCallbacks" : true,
92 "JSC::ExecutableAllocator" : true,
93 "PRIOMethods": true,
94 "_MD_IOVector" : true,
95 "malloc_table_t": true, // replace_malloc
96 "malloc_hook_table_t": true, // replace_malloc
97 "mozilla::MallocSizeOf": true,
98 "MozMallocSizeOf": true,
99 };
100
101 // Ignore calls through TYPE.FIELD, where TYPE is the class or struct name containing
102 // a function pointer field named FIELD.
103 var ignoreCallees = {
104 "js::Class.trace" : true,
105 "js::Class.finalize" : true,
106 "JSClassOps.trace" : true,
107 "JSClassOps.finalize" : true,
108 "JSRuntime.destroyPrincipals" : true,
109 "icu_50::UObject.__deleting_dtor" : true, // destructors in ICU code can't cause GC
110 "mozilla::CycleCollectedJSRuntime.DescribeCustomObjects" : true, // During tracing, cannot GC.
111 "mozilla::CycleCollectedJSRuntime.NoteCustomGCThingXPCOMChildren" : true, // During tracing, cannot GC.
112 "PLDHashTableOps.hashKey" : true,
113 "PLDHashTableOps.clearEntry" : true,
114 "z_stream_s.zfree" : true,
115 "z_stream_s.zalloc" : true,
116 "GrGLInterface.fCallback" : true,
117 "std::strstreambuf._M_alloc_fun" : true,
118 "std::strstreambuf._M_free_fun" : true,
119 "struct js::gc::Callback<void (*)(JSContext*, void*)>.op" : true,
120 "mozilla::ThreadSharedFloatArrayBufferList::Storage.mFree" : true,
121 "mozilla::SizeOfState.mMallocSizeOf": true,
122 "mozilla::gfx::SourceSurfaceRawData.mDeallocator": true,
123 };
124
125 function fieldCallCannotGC(csu, fullfield)
126 {
127 if (csu in ignoreClasses)
128 return true;
129 if (fullfield in ignoreCallees)
130 return true;
131
132 // Example: fmt::v11::detail::buffer<char16_t>.grow_
133 if (/^fmt\b.*::buffer/.test(fullfield))
134 return true;
135 // Example: fmt::v11::detail::custom_value<fmt::v11::context>.format
136 // Example: fmt::v11::detail::custom_value<fmt::v11::generic_context<fmt::v11::basic_appender<wchar_t>, wchar_t> >.format
137 if (/^fmt\b.*::custom_value<.*>/.test(fullfield))
138 return true;
139
140 return false;
141 }
142
143 function ignoreEdgeUse(edge, variable, body)
144 {
145 // Horrible special case for ignoring a false positive in xptcstubs: there
146 // is a local variable 'paramBuffer' holding an array of nsXPTCMiniVariant
147 // on the stack, which appears to be live across a GC call because its
148 // constructor is called when the array is initialized, even though the
149 // constructor is a no-op. So we'll do a very narrow exclusion for the use
150 // that incorrectly started the live range, which was basically "__temp_1 =
151 // paramBuffer".
152 //
153 // By scoping it so narrowly, we can detect most hazards that would be
154 // caused by modifications in the PrepareAndDispatch code. It just barely
155 // avoids having a hazard already.
156 if (('Name' in variable) && (variable.Name[0] == 'paramBuffer')) {
157 if (body.BlockId.Kind == 'Function' && body.BlockId.Variable.Name[0] == 'PrepareAndDispatch')
158 if (edge.Kind == 'Assign' && edge.Type.Kind == 'Pointer')
159 if (edge.Exp[0].Kind == 'Var' && edge.Exp[1].Kind == 'Var')
160 if (edge.Exp[1].Variable.Kind == 'Local' && edge.Exp[1].Variable.Name[0] == 'paramBuffer')
161 return true;
162 }
163
164 // Functions which should not be treated as using variable.
165 if (edge.Kind == "Call") {
166 var callee = edge.Exp[0];
167 if (callee.Kind == "Var") {
168 var name = callee.Variable.Name[0];
169 if (/~DebugOnly/.test(name))
170 return true;
171 if (/~ScopedThreadSafeStringInspector/.test(name))
172 return true;
173 }
174 }
175
176 return false;
177 }
178
179 function ignoreEdgeAddressTaken(edge)
180 {
181 // Functions which may take indirect pointers to unrooted GC things,
182 // but will copy them into rooted locations before calling anything
183 // that can GC. These parameters should usually be replaced with
184 // handles or mutable handles.
185 if (edge.Kind == "Call") {
186 var callee = edge.Exp[0];
187 if (callee.Kind == "Var") {
188 var name = callee.Variable.Name[0];
189 if (/js::Invoke\(/.test(name))
190 return true;
191 }
192 }
193
194 return false;
195 }
196
197 // Ignore calls of these functions (so ignore any stack containing these)
198 var ignoreFunctions = {
199 "ptio.c:pt_MapError" : true,
200 "je_malloc_printf" : true,
201 "malloc_usable_size" : true,
202 "vprintf_stderr" : true,
203 "PR_ExplodeTime" : true,
204 "PR_ErrorInstallTable" : true,
205 "PR_SetThreadPrivate" : true,
206 "uint8 NS_IsMainThread()" : true,
207
208 // Has an indirect call under it by the name "__f", which seemed too
209 // generic to ignore by itself.
210 "void* std::_Locale_impl::~_Locale_impl(int32)" : true,
211
212 // Bug 1056410 - devirtualization prevents the standard nsISupports::Release heuristic from working
213 "uint32 nsXPConnect::Release()" : true,
214 "uint32 nsAtom::Release()" : true,
215
216 // Allocation API
217 "malloc": true,
218 "calloc": true,
219 "realloc": true,
220 "free": true,
221
222 // FIXME!
223 "NS_LogInit": true,
224 "NS_LogTerm": true,
225 "NS_LogAddRef": true,
226 "NS_LogRelease": true,
227 "NS_LogCtor": true,
228 "NS_LogDtor": true,
229 "NS_LogCOMPtrAddRef": true,
230 "NS_LogCOMPtrRelease": true,
231
232 // FIXME!
233 "NS_DebugBreak": true,
234
235 // Similar to heap snapshot mock classes, and GTests below. This posts a
236 // synchronous runnable when a GTest fails, and we are pretty sure that the
237 // particular runnable it posts can't even GC, but the analysis isn't
238 // currently smart enough to determine that. In either case, this is (a)
239 // only in GTests, and (b) only when the Gtest has already failed. We have
240 // static and dynamic checks for no GC in the non-test code, and in the test
241 // code we fall back to only the dynamic checks.
242 "void test::RingbufferDumper::OnTestPartResult(testing::TestPartResult*)" : true,
243
244 "float64 JS_GetCurrentEmbedderTime()" : true,
245
246 // This calls any JSObjectMovedOp for the tenured object via an indirect call.
247 "JSObject* js::TenuringTracer::moveToTenuredSlow(JSObject*)" : true,
248
249 "void js::Nursery::freeMallocedBuffers()" : true,
250
251 "void js::AutoEnterOOMUnsafeRegion::crash(uint64, int8*)" : true,
252 "void js::AutoEnterOOMUnsafeRegion::crash_impl(uint64, int8*)" : true,
253
254 "void mozilla::dom::WorkerPrivate::AssertIsOnWorkerThread() const" : true,
255
256 // It would be cool to somehow annotate that nsTHashtable<T> will use
257 // nsTHashtable<T>::s_MatchEntry for its matchEntry function pointer, but
258 // there is no mechanism for that. So we will just annotate a particularly
259 // troublesome logging-related usage.
260 "EntryType* nsTHashtable<EntryType>::PutEntry(nsTHashtable<EntryType>::KeyType, const fallible_t&) [with EntryType = nsBaseHashtableET<nsCharPtrHashKey, nsAutoPtr<mozilla::LogModule> >; nsTHashtable<EntryType>::KeyType = const char*; nsTHashtable<EntryType>::fallible_t = mozilla::fallible_t]" : true,
261 "EntryType* nsTHashtable<EntryType>::GetEntry(nsTHashtable<EntryType>::KeyType) const [with EntryType = nsBaseHashtableET<nsCharPtrHashKey, nsAutoPtr<mozilla::LogModule> >; nsTHashtable<EntryType>::KeyType = const char*]" : true,
262 "EntryType* nsTHashtable<EntryType>::PutEntry(nsTHashtable<EntryType>::KeyType) [with EntryType = nsBaseHashtableET<nsPtrHashKey<const mozilla::BlockingResourceBase>, nsAutoPtr<mozilla::DeadlockDetector<mozilla::BlockingResourceBase>::OrderingEntry> >; nsTHashtable<EntryType>::KeyType = const mozilla::BlockingResourceBase*]" : true,
263 "EntryType* nsTHashtable<EntryType>::GetEntry(nsTHashtable<EntryType>::KeyType) const [with EntryType = nsBaseHashtableET<nsPtrHashKey<const mozilla::BlockingResourceBase>, nsAutoPtr<mozilla::DeadlockDetector<mozilla::BlockingResourceBase>::OrderingEntry> >; nsTHashtable<EntryType>::KeyType = const mozilla::BlockingResourceBase*]" : true,
264
265 // VTune internals that lazy-load a shared library and make IndirectCalls.
266 "iJIT_IsProfilingActive" : true,
267 "iJIT_NotifyEvent": true,
268
269 // The big hammers.
270 "PR_GetCurrentThread" : true,
271 "calloc" : true,
272
273 // This will happen early enough in initialization to not matter.
274 "_PR_UnixInit" : true,
275
276 "uint8 nsContentUtils::IsExpandedPrincipal(nsIPrincipal*)" : true,
277
278 "void mozilla::AutoProfilerLabel::~AutoProfilerLabel(int32)" : true,
279
280 // Stores a function pointer in an AutoProfilerLabelData struct and calls it.
281 // And it's in mozglue, which doesn't have access to the attributes yet.
282 "void mozilla::ProfilerLabelEnd(std::tuple<void*, unsigned int>*)" : true,
283
284 // This gets into PLDHashTable function pointer territory, and should get
285 // set up early enough to not do anything when it matters anyway.
286 "mozilla::LogModule* mozilla::LogModule::Get(int8*)": true,
287
288 // This annotation is correct, but the reasoning is still being hashed out
289 // in bug 1582326 comment 8 and on.
290 "nsCycleCollector.cpp:nsISupports* CanonicalizeXPCOMParticipant(nsISupports*)": true,
291
292 // PLDHashTable again
293 "void mozilla::DeadlockDetector<T>::Add(const T*) [with T = mozilla::BlockingResourceBase]": true,
294
295 // OOM handling during logging
296 "void mozilla::detail::log_print(mozilla::LogModule*, int32, int8*)": true,
297
298 // This would need to know that the nsCOMPtr refcount will not go to zero.
299 "uint8 XPCJSRuntime::DescribeCustomObjects(JSObject*, JSClass*, int8[72]*)[72]) const": true,
300
301 // As the comment says "Refcount isn't zero, so Suspect won't delete anything."
302 "uint64 nsCycleCollectingAutoRefCnt::incr(void*, nsCycleCollectionParticipant*) [with void (* suspect)(void*, nsCycleCollectionParticipant*, nsCycleCollectingAutoRefCnt*, bool*) = NS_CycleCollectorSuspect3; uintptr_t = long unsigned int]": true,
303
304 // Calls MergeSort
305 "uint8 v8::internal::RegExpDisjunction::SortConsecutiveAtoms(v8::internal::RegExpCompiler*)": true,
306
307 // nsIEventTarget.IsOnCurrentThreadInfallible does not get resolved, and
308 // this is called on non-JS threads so cannot use AutoSuppressGCAnalysis.
309 "uint8 nsAutoOwningEventTarget::IsCurrentThread() const": true,
310
311 // ~JSStreamConsumer calls 2 ~RefCnt/~nsCOMPtr destructors for its fields,
312 // but the body of the destructor is written so that all Releases
313 // are proxied, and the members will all be empty at destruction time.
314 "void mozilla::dom::JSStreamConsumer::~JSStreamConsumer() [[base_dtor]]": true,
315 };
316
317 function extraGCFunctions(readableNames) {
318 return ["ffi_call"].filter(f => f in readableNames);
319 }
320
321 function isProtobuf(name)
322 {
323 return name.match(/\bgoogle::protobuf\b/) ||
324 name.match(/\bmozilla::devtools::protobuf\b/);
325 }
326
327 function isHeapSnapshotMockClass(name)
328 {
329 return name.match(/\bMockWriter\b/) ||
330 name.match(/\bMockDeserializedNode\b/);
331 }
332
333 function isGTest(name)
334 {
335 return name.match(/\btesting::/);
336 }
337
338 function isICU(name)
339 {
340 return name.match(/\bicu_\d+::/) ||
341 name.match(/u(prv_malloc|prv_realloc|prv_free|case_toFullLower)_\d+/)
342 }
343
344 function ignoreGCFunction(mangled, readableNames)
345 {
346 // Field calls will not be in readableNames
347 if (!(mangled in readableNames))
348 return false;
349
350 const fun = readableNames[mangled][0];
351
352 if (fun in ignoreFunctions)
353 return true;
354
355 // The protobuf library, and [de]serialization code generated by the
356 // protobuf compiler, uses a _ton_ of function pointers but they are all
357 // internal. The same is true for ICU. Easiest to just ignore that mess
358 // here.
359 if (isProtobuf(fun) || isICU(fun))
360 return true;
361
362 // Ignore anything that goes through heap snapshot GTests or mocked classes
363 // used in heap snapshot GTests. GTest and GMock expose a lot of virtual
364 // methods and function pointers that could potentially GC after an
365 // assertion has already failed (depending on user-provided code), but don't
366 // exhibit that behavior currently. For non-test code, we have dynamic and
367 // static checks that ensure we don't GC. However, for test code we opt out
368 // of static checks here, because of the above stated GMock/GTest issues,
369 // and rely on only the dynamic checks provided by AutoAssertCannotGC.
370 if (isHeapSnapshotMockClass(fun) || isGTest(fun))
371 return true;
372
373 // Templatized function
374 if (fun.includes("void nsCOMPtr<T>::Assert_NoQueryNeeded()"))
375 return true;
376
377 // Bug 1577915 - Sixgill is ignoring a template param that makes its CFG
378 // impossible.
379 if (fun.includes("UnwrapObjectInternal") && fun.includes("mayBeWrapper = false"))
380 return true;
381
382 // These call through an 'op' function pointer.
383 if (fun.includes("js::WeakMap<Key, Value, HashPolicy>::getDelegate("))
384 return true;
385
386 // TODO: modify refillFreeList<NoGC> to not need data flow analysis to
387 // understand it cannot GC. As of gcc 6, the same problem occurs with
388 // tryNewTenuredThing, tryNewNurseryObject, and others.
389 if (/refillFreeList|tryNew/.test(fun) && /= js::NoGC/.test(fun))
390 return true;
391
392 return false;
393 }
394
395 function stripUCSAndNamespace(name)
396 {
397 name = name.replace(/(struct|class|union|const) /g, "");
398 name = name.replace(/(js::ctypes::|js::|JS::|mozilla::dom::|mozilla::)/g, "");
399 return name;
400 }
401
402 function extraRootedGCThings()
403 {
404 return [ 'JSAddonId' ];
405 }
406
407 function extraRootedPointers()
408 {
409 return [
410 ];
411 }
412
413 function isRootedGCPointerTypeName(name)
414 {
415 name = stripUCSAndNamespace(name);
416
417 if (name.startsWith('MaybeRooted<'))
418 return /\(js::AllowGC\)1u>::RootType/.test(name);
419
420 return false;
421 }
422
423 function isUnsafeStorage(typeName)
424 {
425 typeName = stripUCSAndNamespace(typeName);
426 return typeName.startsWith('UniquePtr<');
427 }
428
429 // If edgeType is a constructor type, return whatever bits it implies for its
430 // scope (or zero if not matching).
431 function isLimitConstructor(typeInfo, edgeType, varName)
432 {
433 // Check whether this could be a constructor
434 if (edgeType.Kind != 'Function')
435 return 0;
436 if (!('TypeFunctionCSU' in edgeType))
437 return 0;
438 if (edgeType.Type.Kind != 'Void')
439 return 0;
440
441 // Check whether the type is a known suppression type.
442 var type = edgeType.TypeFunctionCSU.Type.Name;
443 let attrs = 0;
444 if (type in typeInfo.GCSuppressors)
445 attrs = attrs | ATTR_GC_SUPPRESSED;
446
447 // And now make sure this is the constructor, not some other method on a
448 // suppression type. varName[0] contains the qualified name.
449 var [ mangled, unmangled ] = splitFunction(varName[0]);
450 if (mangled.search(/C\d[EI]/) == -1)
451 return 0; // Mangled names of constructors have C<num>E or C<num>I
452 var m = unmangled.match(/([~\w]+)(?:<.*>)?\(/);
453 if (!m)
454 return 0;
455 var type_stem = type.replace(/\w+::/g, '').replace(/\<.*\>/g, '');
456 if (m[1] != type_stem)
457 return 0;
458
459 return attrs;
460 }
461
462 // XPIDL-generated methods may invoke JS code, depending on the IDL
463 // attributes. This is not visible in the static callgraph since it
464 // goes through generated asm code. We can use the JS_HAZ_CAN_RUN_SCRIPT
465 // annotation to tell whether this is possible, which is set programmatically
466 // by the code generator when needed (bug 1347999):
467 // https://searchfox.org/mozilla-central/rev/81c52abeec336685330af5956c37b4bcf8926476/xpcom/idl-parser/xpidl/header.py#213-219
468 //
469 // Note that WebIDL callbacks can also invoke JS code, but our code generator
470 // produces regular C++ code and so does not need any annotations. (There will
471 // be a call to JS::Call() or similar.)
472 function virtualCanRunJS(csu, field)
473 {
474 const tags = typeInfo.OtherFieldTags;
475 const iface = tags[csu]
476 if (!iface) {
477 return false;
478 }
479 const virtual_method_tags = iface[field];
480 return virtual_method_tags && virtual_method_tags.includes("Can run script");
481 }
482
483 function listNonGCPointers() {
484 return [
485 // Safe only because jsids are currently only made from pinned strings.
486 'NPIdentifier',
487 ];
488 }
489
490 function isJSNative(mangled)
491 {
492 // _Z...E = function
493 // 9JSContext = JSContext*
494 // j = uint32
495 // PN2JS5Value = JS::Value*
496 // P = pointer
497 // N2JS = JS::
498 // 5Value = Value
499 return mangled.endsWith("P9JSContextjPN2JS5ValueE") && mangled.startsWith("_Z");
500 }