Bug 1842364 - Null check weak pointers when tracing IC stubs r=jandem
[gecko.git] / testing / gtest / rungtests.py
blob126d4ca560f4da82e5e83e5e705e1076bb85682b
1 #!/usr/bin/env python
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this
5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 import argparse
8 import os
9 import subprocess
10 import sys
11 import threading
12 import time
14 import mozcrash
15 import mozinfo
16 import mozlog
17 from mozrunner.utils import get_stack_fixer_function
19 log = mozlog.unstructured.getLogger("gtest")
22 class GTests(object):
23 # Time (seconds) to wait for test process to complete
24 TEST_PROC_TIMEOUT = 2400
25 # Time (seconds) in which process will be killed if it produces no output.
26 TEST_PROC_NO_OUTPUT_TIMEOUT = 300
28 def run_gtest(
29 self,
30 prog,
31 xre_path,
32 cwd,
33 symbols_path=None,
34 utility_path=None,
36 """
37 Run a single C++ unit test program.
39 Arguments:
40 * prog: The path to the test program to run.
41 * env: The environment to use for running the program.
42 * cwd: The directory to run tests from (support files will be found
43 in this direcotry).
44 * symbols_path: A path to a directory containing Breakpad-formatted
45 symbol files for producing stack traces on crash.
46 * utility_path: A path to a directory containing utility programs.
47 currently used to locate a stack fixer to provide
48 symbols symbols for assertion stacks.
50 Return True if the program exits with a zero status, False otherwise.
51 """
52 self.xre_path = xre_path
53 env = self.build_environment()
54 log.info("Running gtest")
56 if cwd and not os.path.isdir(cwd):
57 os.makedirs(cwd)
59 stack_fixer = None
60 if utility_path:
61 stack_fixer = get_stack_fixer_function(utility_path, symbols_path)
63 proc = None
64 timed_out = False
66 def proc_timeout_handler():
67 output_timer.cancel()
68 log.testFail("gtest | timed out after %d seconds", GTests.TEST_PROC_TIMEOUT)
69 mozcrash.kill_and_get_minidump(proc.pid, cwd, utility_path)
71 def output_timeout_handler():
72 nonlocal output_timer
73 seconds_since_last_output = time.time() - output_time
74 next_possible_output_timeout = (
75 GTests.TEST_PROC_NO_OUTPUT_TIMEOUT - seconds_since_last_output
77 if next_possible_output_timeout <= 0:
78 proc_timer.cancel()
79 log.testFail(
80 "gtest | timed out after %d seconds without output",
81 GTests.TEST_PROC_NO_OUTPUT_TIMEOUT,
83 mozcrash.kill_and_get_minidump(proc.pid, cwd, utility_path)
84 else:
85 output_timer = threading.Timer(
86 next_possible_output_timeout, output_timeout_handler
88 output_timer.start()
90 with subprocess.Popen(
91 [prog, "-unittest", "--gtest_death_test_style=threadsafe"],
92 cwd=cwd,
93 env=env,
94 stdout=subprocess.PIPE,
95 stderr=subprocess.STDOUT,
96 text=True,
97 ) as proc:
99 proc_timer = None
100 proc_timer = threading.Timer(GTests.TEST_PROC_TIMEOUT, proc_timeout_handler)
101 proc_timer.start()
103 output_time = time.time()
104 output_timer = None
105 output_timer = threading.Timer(
106 GTests.TEST_PROC_NO_OUTPUT_TIMEOUT, output_timeout_handler
108 output_timer.start()
110 for line in proc.stdout:
111 output_time = time.time()
112 if stack_fixer:
113 print(stack_fixer(line))
114 else:
115 print(line)
116 proc.wait()
117 proc_timer.cancel()
118 output_timer.cancel()
120 log.info("gtest | process wait complete, returncode=%s" % proc.returncode)
121 if mozcrash.check_for_crashes(cwd, symbols_path, test_name="gtest"):
122 # mozcrash will output the log failure line for us.
123 return False
124 if timed_out:
125 return False
126 result = proc.returncode == 0
127 if not result:
128 log.testFail("gtest | test failed with return code %d", proc.returncode)
129 return result
131 def build_core_environment(self, env={}):
133 Add environment variables likely to be used across all platforms, including remote systems.
135 env["MOZ_XRE_DIR"] = self.xre_path
136 env["MOZ_GMP_PATH"] = os.pathsep.join(
137 os.path.join(self.xre_path, p, "1.0")
138 for p in ("gmp-fake", "gmp-fakeopenh264")
140 env["XPCOM_DEBUG_BREAK"] = "stack-and-abort"
141 env["MOZ_CRASHREPORTER_NO_REPORT"] = "1"
142 env["MOZ_CRASHREPORTER"] = "1"
143 env["MOZ_DISABLE_NONLOCAL_CONNECTIONS"] = "1"
144 env["MOZ_RUN_GTEST"] = "1"
145 # Normally we run with GTest default output, override this to use the TBPL test format.
146 env["MOZ_TBPL_PARSER"] = "1"
148 if not mozinfo.has_sandbox:
149 # Bug 1082193 - This is horrible. Our linux build boxes run CentOS 6,
150 # which is too old to support sandboxing. Disable sandbox for gtests
151 # on machines which don't support sandboxing until they can be
152 # upgraded, or gtests are run on test machines instead.
153 env["MOZ_DISABLE_GMP_SANDBOX"] = "1"
155 return env
157 def build_environment(self):
159 Create and return a dictionary of all the appropriate env variables
160 and values. On a remote system, we overload this to set different
161 values and are missing things like os.environ and PATH.
163 if not os.path.isdir(self.xre_path):
164 raise Exception("xre_path does not exist: %s", self.xre_path)
165 env = dict(os.environ)
166 env = self.build_core_environment(env)
167 env["PERFHERDER_ALERTING_ENABLED"] = "1"
168 pathvar = ""
169 if mozinfo.os == "linux":
170 pathvar = "LD_LIBRARY_PATH"
171 # disable alerts for unstable tests (Bug 1369807)
172 del env["PERFHERDER_ALERTING_ENABLED"]
173 elif mozinfo.os == "mac":
174 pathvar = "DYLD_LIBRARY_PATH"
175 elif mozinfo.os == "win":
176 pathvar = "PATH"
177 if pathvar:
178 if pathvar in env:
179 env[pathvar] = "%s%s%s" % (self.xre_path, os.pathsep, env[pathvar])
180 else:
181 env[pathvar] = self.xre_path
183 symbolizer_path = None
184 if mozinfo.info["asan"]:
185 symbolizer_path = "ASAN_SYMBOLIZER_PATH"
186 elif mozinfo.info["tsan"]:
187 symbolizer_path = "TSAN_SYMBOLIZER_PATH"
189 if symbolizer_path is not None:
190 # Use llvm-symbolizer for ASan/TSan if available/required
191 if symbolizer_path in env and os.path.isfile(env[symbolizer_path]):
192 llvmsym = env[symbolizer_path]
193 else:
194 llvmsym = os.path.join(
195 self.xre_path, "llvm-symbolizer" + mozinfo.info["bin_suffix"]
197 if os.path.isfile(llvmsym):
198 env[symbolizer_path] = llvmsym
199 log.info("Using LLVM symbolizer at %s", llvmsym)
200 else:
201 # This should be |testFail| instead of |info|. See bug 1050891.
202 log.info("Failed to find LLVM symbolizer at %s", llvmsym)
204 # webrender needs gfx.webrender.all=true, gtest doesn't use prefs
205 env["MOZ_WEBRENDER"] = "1"
206 env["MOZ_ACCELERATED"] = "1"
208 return env
211 class gtestOptions(argparse.ArgumentParser):
212 def __init__(self):
213 super(gtestOptions, self).__init__()
215 self.add_argument(
216 "--cwd",
217 dest="cwd",
218 default=os.getcwd(),
219 help="absolute path to directory from which " "to run the binary",
221 self.add_argument(
222 "--xre-path",
223 dest="xre_path",
224 default=None,
225 help="absolute path to directory containing XRE " "(probably xulrunner)",
227 self.add_argument(
228 "--symbols-path",
229 dest="symbols_path",
230 default=None,
231 help="absolute path to directory containing breakpad "
232 "symbols, or the URL of a zip file containing "
233 "symbols",
235 self.add_argument(
236 "--utility-path",
237 dest="utility_path",
238 default=None,
239 help="path to a directory containing utility program binaries",
241 self.add_argument("args", nargs=argparse.REMAINDER)
244 def update_mozinfo():
245 """walk up directories to find mozinfo.json update the info"""
246 path = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
247 dirs = set()
248 while path != os.path.expanduser("~"):
249 if path in dirs:
250 break
251 dirs.add(path)
252 path = os.path.split(path)[0]
253 mozinfo.find_and_update_from_json(*dirs)
256 def main():
257 parser = gtestOptions()
258 options = parser.parse_args()
259 args = options.args
260 if not args:
261 print("Usage: %s <binary>" % sys.argv[0])
262 sys.exit(1)
263 if not options.xre_path:
264 print("Error: --xre-path is required")
265 sys.exit(1)
266 if not options.utility_path:
267 print("Warning: --utility-path is required to process assertion stacks")
269 update_mozinfo()
270 prog = os.path.abspath(args[0])
271 options.xre_path = os.path.abspath(options.xre_path)
272 tester = GTests()
273 try:
274 result = tester.run_gtest(
275 prog,
276 options.xre_path,
277 options.cwd,
278 symbols_path=options.symbols_path,
279 utility_path=options.utility_path,
281 except Exception as e:
282 log.error(str(e))
283 result = False
284 exit_code = 0 if result else 1
285 log.info("rungtests.py exits with code %s" % exit_code)
286 sys.exit(exit_code)
289 if __name__ == "__main__":
290 main()