valgrind_test.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. #!/usr/bin/env python
  2. # Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style license
  5. # that can be found in the LICENSE file in the root of the source
  6. # tree. An additional intellectual property rights grant can be found
  7. # in the file PATENTS. All contributing project authors may
  8. # be found in the AUTHORS file in the root of the source tree.
  9. """Runs an exe through Valgrind and puts the intermediate files in a
  10. directory.
  11. """
  12. import datetime
  13. import glob
  14. import logging
  15. import optparse
  16. import os
  17. import re
  18. import shutil
  19. import stat
  20. import subprocess
  21. import sys
  22. import tempfile
  23. import common
  24. import memcheck_analyze
  25. class BaseTool(object):
  26. """Abstract class for running dynamic error detection tools.
  27. Always subclass this and implement ToolCommand with framework- and
  28. tool-specific stuff.
  29. """
  30. def __init__(self):
  31. temp_parent_dir = None
  32. self.log_parent_dir = ""
  33. if common.IsWindows():
  34. # gpu process on Windows Vista+ runs at Low Integrity and can only
  35. # write to certain directories (http://crbug.com/119131)
  36. #
  37. # TODO(bruening): if scripts die in middle and don't clean up temp
  38. # dir, we'll accumulate files in profile dir. should remove
  39. # really old files automatically.
  40. profile = os.getenv("USERPROFILE")
  41. if profile:
  42. self.log_parent_dir = profile + "\\AppData\\LocalLow\\"
  43. if os.path.exists(self.log_parent_dir):
  44. self.log_parent_dir = common.NormalizeWindowsPath(self.log_parent_dir)
  45. temp_parent_dir = self.log_parent_dir
  46. # Generated every time (even when overridden)
  47. self.temp_dir = tempfile.mkdtemp(prefix="vg_logs_", dir=temp_parent_dir)
  48. self.log_dir = self.temp_dir # overridable by --keep_logs
  49. self.option_parser_hooks = []
  50. # TODO(glider): we may not need some of the env vars on some of the
  51. # platforms.
  52. self._env = {
  53. "G_SLICE" : "always-malloc",
  54. "NSS_DISABLE_UNLOAD" : "1",
  55. "NSS_DISABLE_ARENA_FREE_LIST" : "1",
  56. "GTEST_DEATH_TEST_USE_FORK": "1",
  57. }
  58. def ToolName(self):
  59. raise NotImplementedError, "This method should be implemented " \
  60. "in the tool-specific subclass"
  61. def Analyze(self, check_sanity=False):
  62. raise NotImplementedError, "This method should be implemented " \
  63. "in the tool-specific subclass"
  64. def RegisterOptionParserHook(self, hook):
  65. # Frameworks and tools can add their own flags to the parser.
  66. self.option_parser_hooks.append(hook)
  67. def CreateOptionParser(self):
  68. # Defines Chromium-specific flags.
  69. self._parser = optparse.OptionParser("usage: %prog [options] <program to "
  70. "test>")
  71. self._parser.disable_interspersed_args()
  72. self._parser.add_option("-t", "--timeout",
  73. dest="timeout", metavar="TIMEOUT", default=10000,
  74. help="timeout in seconds for the run (default 10000)")
  75. self._parser.add_option("", "--build-dir",
  76. help="the location of the compiler output")
  77. self._parser.add_option("", "--source-dir",
  78. help="path to top of source tree for this build"
  79. "(used to normalize source paths in baseline)")
  80. self._parser.add_option("", "--gtest_filter", default="",
  81. help="which test case to run")
  82. self._parser.add_option("", "--gtest_repeat",
  83. help="how many times to run each test")
  84. self._parser.add_option("", "--gtest_print_time", action="store_true",
  85. default=False,
  86. help="show how long each test takes")
  87. self._parser.add_option("", "--ignore_exit_code", action="store_true",
  88. default=False,
  89. help="ignore exit code of the test "
  90. "(e.g. test failures)")
  91. self._parser.add_option("", "--keep_logs", action="store_true",
  92. default=False,
  93. help="store memory tool logs in the <tool>.logs "
  94. "directory instead of /tmp.\nThis can be "
  95. "useful for tool developers/maintainers.\n"
  96. "Please note that the <tool>.logs directory "
  97. "will be clobbered on tool startup.")
  98. # To add framework- or tool-specific flags, please add a hook using
  99. # RegisterOptionParserHook in the corresponding subclass.
  100. # See ValgrindTool for an example.
  101. for hook in self.option_parser_hooks:
  102. hook(self, self._parser)
  103. def ParseArgv(self, args):
  104. self.CreateOptionParser()
  105. # self._tool_flags will store those tool flags which we don't parse
  106. # manually in this script.
  107. self._tool_flags = []
  108. known_args = []
  109. """ We assume that the first argument not starting with "-" is a program
  110. name and all the following flags should be passed to the program.
  111. TODO(timurrrr): customize optparse instead
  112. """
  113. while len(args) > 0 and args[0][:1] == "-":
  114. arg = args[0]
  115. if (arg == "--"):
  116. break
  117. if self._parser.has_option(arg.split("=")[0]):
  118. known_args += [arg]
  119. else:
  120. self._tool_flags += [arg]
  121. args = args[1:]
  122. if len(args) > 0:
  123. known_args += args
  124. self._options, self._args = self._parser.parse_args(known_args)
  125. self._timeout = int(self._options.timeout)
  126. self._source_dir = self._options.source_dir
  127. if self._options.keep_logs:
  128. # log_parent_dir has trailing slash if non-empty
  129. self.log_dir = self.log_parent_dir + "%s.logs" % self.ToolName()
  130. if os.path.exists(self.log_dir):
  131. shutil.rmtree(self.log_dir)
  132. os.mkdir(self.log_dir)
  133. logging.info("Logs are in " + self.log_dir)
  134. self._ignore_exit_code = self._options.ignore_exit_code
  135. if self._options.gtest_filter != "":
  136. self._args.append("--gtest_filter=%s" % self._options.gtest_filter)
  137. if self._options.gtest_repeat:
  138. self._args.append("--gtest_repeat=%s" % self._options.gtest_repeat)
  139. if self._options.gtest_print_time:
  140. self._args.append("--gtest_print_time")
  141. return True
  142. def Setup(self, args):
  143. return self.ParseArgv(args)
  144. def ToolCommand(self):
  145. raise NotImplementedError, "This method should be implemented " \
  146. "in the tool-specific subclass"
  147. def Cleanup(self):
  148. # You may override it in the tool-specific subclass
  149. pass
  150. def Execute(self):
  151. """ Execute the app to be tested after successful instrumentation.
  152. Full execution command-line provided by subclassers via proc."""
  153. logging.info("starting execution...")
  154. proc = self.ToolCommand()
  155. for var in self._env:
  156. common.PutEnvAndLog(var, self._env[var])
  157. return common.RunSubprocess(proc, self._timeout)
  158. def RunTestsAndAnalyze(self, check_sanity):
  159. exec_retcode = self.Execute()
  160. analyze_retcode = self.Analyze(check_sanity)
  161. if analyze_retcode:
  162. logging.error("Analyze failed.")
  163. logging.info("Search the log for '[ERROR]' to see the error reports.")
  164. return analyze_retcode
  165. if exec_retcode:
  166. if self._ignore_exit_code:
  167. logging.info("Test execution failed, but the exit code is ignored.")
  168. else:
  169. logging.error("Test execution failed.")
  170. return exec_retcode
  171. else:
  172. logging.info("Test execution completed successfully.")
  173. if not analyze_retcode:
  174. logging.info("Analysis completed successfully.")
  175. return 0
  176. def Main(self, args, check_sanity, min_runtime_in_seconds):
  177. """Call this to run through the whole process: Setup, Execute, Analyze"""
  178. start_time = datetime.datetime.now()
  179. retcode = -1
  180. if self.Setup(args):
  181. retcode = self.RunTestsAndAnalyze(check_sanity)
  182. shutil.rmtree(self.temp_dir, ignore_errors=True)
  183. self.Cleanup()
  184. else:
  185. logging.error("Setup failed")
  186. end_time = datetime.datetime.now()
  187. runtime_in_seconds = (end_time - start_time).seconds
  188. hours = runtime_in_seconds / 3600
  189. seconds = runtime_in_seconds % 3600
  190. minutes = seconds / 60
  191. seconds = seconds % 60
  192. logging.info("elapsed time: %02d:%02d:%02d" % (hours, minutes, seconds))
  193. if (min_runtime_in_seconds > 0 and
  194. runtime_in_seconds < min_runtime_in_seconds):
  195. logging.error("Layout tests finished too quickly. "
  196. "It should have taken at least %d seconds. "
  197. "Something went wrong?" % min_runtime_in_seconds)
  198. retcode = -1
  199. return retcode
  200. def Run(self, args, module, min_runtime_in_seconds=0):
  201. MODULES_TO_SANITY_CHECK = ["base"]
  202. check_sanity = module in MODULES_TO_SANITY_CHECK
  203. return self.Main(args, check_sanity, min_runtime_in_seconds)
  204. class ValgrindTool(BaseTool):
  205. """Abstract class for running Valgrind tools.
  206. Always subclass this and implement ToolSpecificFlags() and
  207. ExtendOptionParser() for tool-specific stuff.
  208. """
  209. def __init__(self):
  210. super(ValgrindTool, self).__init__()
  211. self.RegisterOptionParserHook(ValgrindTool.ExtendOptionParser)
  212. def UseXML(self):
  213. # Override if tool prefers nonxml output
  214. return True
  215. def ExtendOptionParser(self, parser):
  216. parser.add_option("", "--suppressions", default=[],
  217. action="append",
  218. help="path to a valgrind suppression file")
  219. parser.add_option("", "--indirect", action="store_true",
  220. default=False,
  221. help="set BROWSER_WRAPPER rather than "
  222. "running valgrind directly")
  223. parser.add_option("", "--indirect_webkit_layout", action="store_true",
  224. default=False,
  225. help="set --wrapper rather than running Dr. Memory "
  226. "directly.")
  227. parser.add_option("", "--trace_children", action="store_true",
  228. default=False,
  229. help="also trace child processes")
  230. parser.add_option("", "--num-callers",
  231. dest="num_callers", default=30,
  232. help="number of callers to show in stack traces")
  233. parser.add_option("", "--generate_dsym", action="store_true",
  234. default=False,
  235. help="Generate .dSYM file on Mac if needed. Slow!")
  236. def Setup(self, args):
  237. if not BaseTool.Setup(self, args):
  238. return False
  239. return True
  240. def ToolCommand(self):
  241. """Get the valgrind command to run."""
  242. # Note that self._args begins with the exe to be run.
  243. tool_name = self.ToolName()
  244. # Construct the valgrind command.
  245. if 'CHROME_VALGRIND' in os.environ:
  246. path = os.path.join(os.environ['CHROME_VALGRIND'], "bin", "valgrind")
  247. else:
  248. path = "valgrind"
  249. proc = [path, "--tool=%s" % tool_name]
  250. proc += ["--num-callers=%i" % int(self._options.num_callers)]
  251. if self._options.trace_children:
  252. proc += ["--trace-children=yes"]
  253. proc += ["--trace-children-skip='*dbus-daemon*'"]
  254. proc += ["--trace-children-skip='*dbus-launch*'"]
  255. proc += ["--trace-children-skip='*perl*'"]
  256. proc += ["--trace-children-skip='*python*'"]
  257. # This is really Python, but for some reason Valgrind follows it.
  258. proc += ["--trace-children-skip='*lsb_release*'"]
  259. proc += self.ToolSpecificFlags()
  260. proc += self._tool_flags
  261. suppression_count = 0
  262. for suppression_file in self._options.suppressions:
  263. if os.path.exists(suppression_file):
  264. suppression_count += 1
  265. proc += ["--suppressions=%s" % suppression_file]
  266. if not suppression_count:
  267. logging.warning("WARNING: NOT USING SUPPRESSIONS!")
  268. logfilename = self.log_dir + ("/%s." % tool_name) + "%p"
  269. if self.UseXML():
  270. proc += ["--xml=yes", "--xml-file=" + logfilename]
  271. else:
  272. proc += ["--log-file=" + logfilename]
  273. # The Valgrind command is constructed.
  274. # Handle --indirect_webkit_layout separately.
  275. if self._options.indirect_webkit_layout:
  276. # Need to create the wrapper before modifying |proc|.
  277. wrapper = self.CreateBrowserWrapper(proc, webkit=True)
  278. proc = self._args
  279. proc.append("--wrapper")
  280. proc.append(wrapper)
  281. return proc
  282. if self._options.indirect:
  283. wrapper = self.CreateBrowserWrapper(proc)
  284. os.environ["BROWSER_WRAPPER"] = wrapper
  285. logging.info('export BROWSER_WRAPPER=' + wrapper)
  286. proc = []
  287. proc += self._args
  288. return proc
  289. def ToolSpecificFlags(self):
  290. raise NotImplementedError, "This method should be implemented " \
  291. "in the tool-specific subclass"
  292. def CreateBrowserWrapper(self, proc, webkit=False):
  293. """The program being run invokes Python or something else that can't stand
  294. to be valgrinded, and also invokes the Chrome browser. In this case, use a
  295. magic wrapper to only valgrind the Chrome browser. Build the wrapper here.
  296. Returns the path to the wrapper. It's up to the caller to use the wrapper
  297. appropriately.
  298. """
  299. command = " ".join(proc)
  300. # Add the PID of the browser wrapper to the logfile names so we can
  301. # separate log files for different UI tests at the analyze stage.
  302. command = command.replace("%p", "$$.%p")
  303. (fd, indirect_fname) = tempfile.mkstemp(dir=self.log_dir,
  304. prefix="browser_wrapper.",
  305. text=True)
  306. f = os.fdopen(fd, "w")
  307. f.write('#!/bin/bash\n'
  308. 'echo "Started Valgrind wrapper for this test, PID=$$" >&2\n')
  309. f.write('DIR=`dirname $0`\n'
  310. 'TESTNAME_FILE=$DIR/testcase.$$.name\n\n')
  311. if webkit:
  312. # Webkit layout_tests pass the URL as the first line of stdin.
  313. f.write('tee $TESTNAME_FILE | %s "$@"\n' % command)
  314. else:
  315. # Try to get the test case name by looking at the program arguments.
  316. # i.e. Chromium ui_tests used --test-name arg.
  317. # TODO(timurrrr): This doesn't handle "--test-name Test.Name"
  318. # TODO(timurrrr): ui_tests are dead. Where do we use the non-webkit
  319. # wrapper now? browser_tests? What do they do?
  320. f.write('for arg in $@\ndo\n'
  321. ' if [[ "$arg" =~ --test-name=(.*) ]]\n then\n'
  322. ' echo ${BASH_REMATCH[1]} >$TESTNAME_FILE\n'
  323. ' fi\n'
  324. 'done\n\n'
  325. '%s "$@"\n' % command)
  326. f.close()
  327. os.chmod(indirect_fname, stat.S_IRUSR|stat.S_IXUSR)
  328. return indirect_fname
  329. def CreateAnalyzer(self):
  330. raise NotImplementedError, "This method should be implemented " \
  331. "in the tool-specific subclass"
  332. def GetAnalyzeResults(self, check_sanity=False):
  333. # Glob all the files in the log directory
  334. filenames = glob.glob(self.log_dir + "/" + self.ToolName() + ".*")
  335. # If we have browser wrapper, the logfiles are named as
  336. # "toolname.wrapper_PID.valgrind_PID".
  337. # Let's extract the list of wrapper_PIDs and name it ppids
  338. ppids = set([int(f.split(".")[-2]) \
  339. for f in filenames if re.search("\.[0-9]+\.[0-9]+$", f)])
  340. analyzer = self.CreateAnalyzer()
  341. if len(ppids) == 0:
  342. # Fast path - no browser wrapper was set.
  343. return analyzer.Report(filenames, None, check_sanity)
  344. ret = 0
  345. for ppid in ppids:
  346. testcase_name = None
  347. try:
  348. f = open(self.log_dir + ("/testcase.%d.name" % ppid))
  349. testcase_name = f.read().strip()
  350. f.close()
  351. wk_layout_prefix="third_party/WebKit/LayoutTests/"
  352. wk_prefix_at = testcase_name.rfind(wk_layout_prefix)
  353. if wk_prefix_at != -1:
  354. testcase_name = testcase_name[wk_prefix_at + len(wk_layout_prefix):]
  355. except IOError:
  356. pass
  357. print "====================================================="
  358. print " Below is the report for valgrind wrapper PID=%d." % ppid
  359. if testcase_name:
  360. print " It was used while running the `%s` test." % testcase_name
  361. else:
  362. print " You can find the corresponding test"
  363. print " by searching the above log for 'PID=%d'" % ppid
  364. sys.stdout.flush()
  365. ppid_filenames = [f for f in filenames \
  366. if re.search("\.%d\.[0-9]+$" % ppid, f)]
  367. # check_sanity won't work with browser wrappers
  368. assert check_sanity == False
  369. ret |= analyzer.Report(ppid_filenames, testcase_name)
  370. print "====================================================="
  371. sys.stdout.flush()
  372. if ret != 0:
  373. print ""
  374. print "The Valgrind reports are grouped by test names."
  375. print "Each test has its PID printed in the log when the test was run"
  376. print "and at the beginning of its Valgrind report."
  377. print "Hint: you can search for the reports by Ctrl+F -> `=#`"
  378. sys.stdout.flush()
  379. return ret
  380. # TODO(timurrrr): Split into a separate file.
  381. class Memcheck(ValgrindTool):
  382. """Memcheck
  383. Dynamic memory error detector for Linux & Mac
  384. http://valgrind.org/info/tools.html#memcheck
  385. """
  386. def __init__(self):
  387. super(Memcheck, self).__init__()
  388. self.RegisterOptionParserHook(Memcheck.ExtendOptionParser)
  389. def ToolName(self):
  390. return "memcheck"
  391. def ExtendOptionParser(self, parser):
  392. parser.add_option("--leak-check", "--leak_check", type="string",
  393. default="yes", # --leak-check=yes is equivalent of =full
  394. help="perform leak checking at the end of the run")
  395. parser.add_option("", "--show_all_leaks", action="store_true",
  396. default=False,
  397. help="also show less blatant leaks")
  398. parser.add_option("", "--track_origins", action="store_true",
  399. default=False,
  400. help="Show whence uninitialized bytes came. 30% slower.")
  401. def ToolSpecificFlags(self):
  402. ret = ["--gen-suppressions=all", "--demangle=no"]
  403. ret += ["--leak-check=%s" % self._options.leak_check]
  404. if self._options.show_all_leaks:
  405. ret += ["--show-reachable=yes"]
  406. else:
  407. ret += ["--show-possibly-lost=no"]
  408. if self._options.track_origins:
  409. ret += ["--track-origins=yes"]
  410. # TODO(glider): this is a temporary workaround for http://crbug.com/51716
  411. # Let's see whether it helps.
  412. if common.IsMac():
  413. ret += ["--smc-check=all"]
  414. return ret
  415. def CreateAnalyzer(self):
  416. use_gdb = common.IsMac()
  417. return memcheck_analyze.MemcheckAnalyzer(self._source_dir,
  418. self._options.show_all_leaks,
  419. use_gdb=use_gdb)
  420. def Analyze(self, check_sanity=False):
  421. ret = self.GetAnalyzeResults(check_sanity)
  422. if ret != 0:
  423. logging.info("Please see http://dev.chromium.org/developers/how-tos/"
  424. "using-valgrind for the info on Memcheck/Valgrind")
  425. return ret
  426. class ToolFactory:
  427. def Create(self, tool_name):
  428. if tool_name == "memcheck":
  429. return Memcheck()
  430. try:
  431. platform_name = common.PlatformNames()[0]
  432. except common.NotImplementedError:
  433. platform_name = sys.platform + "(Unknown)"
  434. raise RuntimeError, "Unknown tool (tool=%s, platform=%s)" % (tool_name,
  435. platform_name)
  436. def CreateTool(tool):
  437. return ToolFactory().Create(tool)