Bug 1682766 [wpt PR 26921] - Fix nullptr dereference accessing PolicyContainer in...
[gecko.git] / config / check_vanilla_allocations.py
blob10578d8b6568750f017724d9ecea5373b2b9ee89
1 # vim: set ts=8 sts=4 et sw=4 tw=79:
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/.
6 # ----------------------------------------------------------------------------
7 # All heap allocations in SpiderMonkey must go through js_malloc, js_calloc,
8 # js_realloc, and js_free. This is so that any embedder who uses a custom
9 # allocator (by defining JS_USE_CUSTOM_ALLOCATOR) will see all heap allocation
10 # go through that custom allocator.
12 # Therefore, the presence of any calls to "vanilla" allocation/free functions
13 # from within SpiderMonkey itself (e.g. malloc(), free()) is a bug. Calls from
14 # within mozglue and non-SpiderMonkey locations are fine; there is a list of
15 # exceptions that can be added to as the need arises.
17 # This script checks for the presence of such disallowed vanilla
18 # allocation/free function in SpiderMonkey when it's built as a library. It
19 # relies on |nm| from the GNU binutils, and so only works on Linux, but one
20 # platform is good enough to catch almost all violations.
22 # This checking is only 100% reliable in a JS_USE_CUSTOM_ALLOCATOR build in
23 # which the default definitions of js_malloc et al (in Utility.h) -- which call
24 # malloc et al -- are replaced with empty definitions. This is because the
25 # presence and possible inlining of the default js_malloc et al can cause
26 # malloc/calloc/realloc/free calls show up in unpredictable places.
28 # Unfortunately, that configuration cannot be tested on Mozilla's standard
29 # testing infrastructure. Instead, by default this script only tests that none
30 # of the other vanilla allocation/free functions (operator new, memalign, etc)
31 # are present. If given the --aggressive flag, it will also check for
32 # malloc/calloc/realloc/free.
34 # Note: We don't check for |operator delete| and |operator delete[]|. These
35 # can be present somehow due to virtual destructors, but this is not too
36 # because vanilla delete/delete[] calls don't make sense without corresponding
37 # vanilla new/new[] calls, and any explicit calls will be caught by Valgrind's
38 # mismatched alloc/free checking.
39 # ----------------------------------------------------------------------------
41 from __future__ import absolute_import, print_function, unicode_literals
43 import argparse
44 import re
45 import subprocess
46 import sys
47 import buildconfig
49 # The obvious way to implement this script is to search for occurrences of
50 # malloc et al, succeed if none are found, and fail is some are found.
51 # However, "none are found" does not necessarily mean "none are present" --
52 # this script could be buggy. (Or the output format of |nm| might change in
53 # the future.)
55 # So util/Utility.cpp deliberately contains a (never-called) function that
56 # contains a single use of all the vanilla allocation/free functions. And this
57 # script fails if it (a) finds uses of those functions in files other than
58 # util/Utility.cpp, *or* (b) fails to find them in util/Utility.cpp.
60 # Tracks overall success of the test.
61 has_failed = False
64 def fail(msg):
65 print("TEST-UNEXPECTED-FAIL | check_vanilla_allocations.py |", msg)
66 global has_failed
67 has_failed = True
70 def main():
71 parser = argparse.ArgumentParser()
72 parser.add_argument(
73 "--aggressive",
74 action="store_true",
75 help="also check for malloc, calloc, realloc and free",
77 parser.add_argument("file", type=str, help="name of the file to check")
78 args = parser.parse_args()
80 # Run |nm|. Options:
81 # -u: show only undefined symbols
82 # -C: demangle symbol names
83 # -A: show an object filename for each undefined symbol
84 nm = buildconfig.substs.get("NM") or "nm"
85 cmd = [nm, "-u", "-C", "-A", args.file]
86 lines = subprocess.check_output(
87 cmd, universal_newlines=True, stderr=subprocess.PIPE
88 ).split("\n")
90 # alloc_fns contains all the vanilla allocation/free functions that we look
91 # for. Regexp chars are escaped appropriately.
93 alloc_fns = [
94 # Matches |operator new(unsigned T)|, where |T| is |int| or |long|.
95 r"operator new\(unsigned",
96 # Matches |operator new[](unsigned T)|, where |T| is |int| or |long|.
97 r"operator new\[\]\(unsigned",
98 r"memalign",
99 # These three aren't available on all Linux configurations.
100 # r'posix_memalign',
101 # r'aligned_alloc',
102 # r'valloc',
105 if args.aggressive:
106 alloc_fns += [r"malloc", r"calloc", r"realloc", r"free", r"strdup"]
108 # This is like alloc_fns, but regexp chars are not escaped.
109 alloc_fns_unescaped = [fn.replace("\\", "") for fn in alloc_fns]
111 # This regexp matches the relevant lines in the output of |nm|, which look
112 # like the following.
114 # js/src/libjs_static.a:Utility.o: U malloc
116 alloc_fns_re = r"([^:/ ]+):\s+U (" + r"|".join(alloc_fns) + r")"
118 # This tracks which allocation/free functions have been seen in
119 # util/Utility.cpp.
120 util_Utility_cpp = set([])
122 # Would it be helpful to emit detailed line number information after a failure?
123 emit_line_info = False
125 for line in lines:
126 m = re.search(alloc_fns_re, line)
127 if m is None:
128 continue
130 filename = m.group(1)
132 # The stdc++compat library has an implicit call to operator new in
133 # thread::_M_start_thread.
134 if "stdc++compat" in filename:
135 continue
137 # The memory allocator code contains calls to memalign. These are ok, so
138 # we whitelist them.
139 if "_memory_" in filename:
140 continue
142 # Ignore the fuzzing code imported from m-c
143 if "Fuzzer" in filename:
144 continue
146 # Ignore the profiling pseudo-stack, since it needs to run even when
147 # SpiderMonkey's allocator isn't initialized.
148 if "ProfilingStack" in filename:
149 continue
151 # Ignore implicit call to operator new in std::condition_variable_any.
153 # From intl/icu/source/common/umutex.h:
154 # On Linux, the default constructor of std::condition_variable_any
155 # produces an in-line reference to global operator new(), [...].
156 if filename == "umutex.o":
157 continue
159 # Ignore allocations from decimal conversion functions inside mozglue.
160 if filename == "Decimal.o":
161 continue
163 fn = m.group(2)
164 if filename == "Utility.o":
165 util_Utility_cpp.add(fn)
166 else:
167 # An allocation is present in a non-special file. Fail!
168 fail("'" + fn + "' present in " + filename)
169 # Try to give more precise information about the offending code.
170 emit_line_info = True
172 # Check that all functions we expect are used in util/Utility.cpp. (This
173 # will fail if the function-detection code breaks at any point.)
174 for fn in alloc_fns_unescaped:
175 if fn not in util_Utility_cpp:
176 fail("'" + fn + "' isn't used as expected in util/Utility.cpp")
177 else:
178 util_Utility_cpp.remove(fn)
180 # This should never happen, but check just in case.
181 if util_Utility_cpp:
182 fail(
183 "unexpected allocation fns used in util/Utility.cpp: "
184 + ", ".join(util_Utility_cpp)
187 # If we found any improper references to allocation functions, try to use
188 # DWARF debug info to get more accurate line number information about the
189 # bad calls. This is a lot slower than 'nm -A', and it is not always
190 # precise when building with --enable-optimized.
191 if emit_line_info:
192 print("check_vanilla_allocations.py: Source lines with allocation calls:")
193 print(
194 "check_vanilla_allocations.py: Accurate in unoptimized builds; "
195 "util/Utility.cpp expected."
198 # Run |nm|. Options:
199 # -u: show only undefined symbols
200 # -C: demangle symbol names
201 # -l: show line number information for each undefined symbol
202 cmd = ["nm", "-u", "-C", "-l", args.file]
203 lines = subprocess.check_output(
204 cmd, universal_newlines=True, stderr=subprocess.PIPE
205 ).split("\n")
207 # This regexp matches the relevant lines in the output of |nm -l|,
208 # which look like the following.
210 # U malloc util/Utility.cpp:117
212 alloc_lines_re = r"U ((" + r"|".join(alloc_fns) + r").*)\s+(\S+:\d+)$"
214 for line in lines:
215 m = re.search(alloc_lines_re, line)
216 if m:
217 print(
218 "check_vanilla_allocations.py:", m.group(1), "called at", m.group(3)
221 if has_failed:
222 sys.exit(1)
224 print("TEST-PASS | check_vanilla_allocations.py | ok")
225 sys.exit(0)
228 if __name__ == "__main__":
229 main()