PageRenderTime 70ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/media/webrtc/trunk/tools/valgrind/suppressions.py

https://bitbucket.org/thinker/mozilla-central
Python | 916 lines | 786 code | 27 blank | 103 comment | 19 complexity | b099b0897d50c393ccf56735bdaa11e5 MD5 | raw file
Possible License(s): JSON, 0BSD, LGPL-3.0, BSD-2-Clause, MIT, MPL-2.0-no-copyleft-exception, BSD-3-Clause, GPL-2.0, AGPL-1.0, MPL-2.0, Apache-2.0, LGPL-2.1
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. # suppressions.py
  6. """Post-process Valgrind suppression matcher.
  7. Suppressions are defined as follows:
  8. # optional one-line comments anywhere in the suppressions file.
  9. {
  10. <Short description of the error>
  11. Toolname:Errortype
  12. fun:function_name
  13. obj:object_filename
  14. fun:wildcarded_fun*_name
  15. # an ellipsis wildcards zero or more functions in a stack.
  16. ...
  17. fun:some_other_function_name
  18. }
  19. If ran from the command line, suppressions.py does a self-test
  20. of the Suppression class.
  21. """
  22. import os
  23. import re
  24. import sys
  25. ELLIPSIS = '...'
  26. def GlobToRegex(glob_pattern):
  27. """Translate glob wildcards (*?) into regex syntax. Escape the rest."""
  28. regex = ''
  29. for char in glob_pattern:
  30. if char == '*':
  31. regex += '.*'
  32. elif char == '?':
  33. regex += '.'
  34. else:
  35. regex += re.escape(char)
  36. return ''.join(regex)
  37. def StripAndSkipCommentsIterator(lines):
  38. """Generator of (line_no, line) pairs that strips comments and whitespace."""
  39. for (line_no, line) in enumerate(lines):
  40. line = line.strip() # Drop \n
  41. if line.startswith('#'):
  42. continue # Comments
  43. # Skip comment lines, but not empty lines, they indicate the end of a
  44. # suppression. Add one to the line number as well, since most editors use
  45. # 1-based numberings, and enumerate is 0-based.
  46. yield (line_no + 1, line)
  47. class Suppression(object):
  48. """This class represents a single stack trace suppression.
  49. Attributes:
  50. description: A string representing the error description.
  51. type: A string representing the error type, e.g. Memcheck:Leak.
  52. stack: The lines comprising the stack trace for the suppression.
  53. regex: The actual regex used to match against scraped reports.
  54. """
  55. def __init__(self, description, type, stack, defined_at, regex):
  56. """Inits Suppression.
  57. description, type, stack, regex: same as class attributes
  58. defined_at: file:line identifying where the suppression was defined
  59. """
  60. self.description = description
  61. self.type = type
  62. self.stack = stack
  63. self.defined_at = defined_at
  64. self.regex = re.compile(regex, re.MULTILINE)
  65. def Match(self, suppression_from_report):
  66. """Returns bool indicating whether this suppression matches
  67. the suppression generated from Valgrind error report.
  68. We match our suppressions against generated suppressions
  69. (not against reports) since they have the same format
  70. while the reports are taken from XML, contain filenames,
  71. they are demangled, and are generally more difficult to
  72. parse.
  73. Args:
  74. suppression_from_report: list of strings (function names).
  75. Returns:
  76. True if the suppression is not empty and matches the report.
  77. """
  78. if not self.stack:
  79. return False
  80. lines = [f.strip() for f in suppression_from_report]
  81. return self.regex.match('\n'.join(lines) + '\n') is not None
  82. def FilenameToTool(filename):
  83. """Return the name of the tool that a file is related to, or None.
  84. Example mappings:
  85. tools/heapcheck/suppressions.txt -> heapcheck
  86. tools/valgrind/tsan/suppressions.txt -> tsan
  87. tools/valgrind/drmemory/suppressions.txt -> drmemory
  88. tools/valgrind/drmemory/suppressions_full.txt -> drmemory
  89. tools/valgrind/memcheck/suppressions.txt -> memcheck
  90. tools/valgrind/memcheck/suppressions_mac.txt -> memcheck
  91. """
  92. filename = os.path.abspath(filename)
  93. parts = filename.split(os.sep)
  94. tool = parts[-2]
  95. if tool in ('heapcheck', 'drmemory', 'memcheck', 'tsan'):
  96. return tool
  97. return None
  98. def ReadSuppressionsFromFile(filename):
  99. """Read suppressions from the given file and return them as a list"""
  100. tool_to_parser = {
  101. "drmemory": ReadDrMemorySuppressions,
  102. "memcheck": ReadValgrindStyleSuppressions,
  103. "tsan": ReadValgrindStyleSuppressions,
  104. "heapcheck": ReadValgrindStyleSuppressions,
  105. }
  106. tool = FilenameToTool(filename)
  107. assert tool in tool_to_parser, (
  108. "unknown tool %s for filename %s" % (tool, filename))
  109. parse_func = tool_to_parser[tool]
  110. input_file = file(filename, 'r')
  111. try:
  112. return parse_func(input_file, filename)
  113. except SuppressionError:
  114. input_file.close()
  115. raise
  116. class ValgrindStyleSuppression(Suppression):
  117. """A suppression using the Valgrind syntax.
  118. Most tools, even ones that are not Valgrind-based, use this syntax, ie
  119. Heapcheck, TSan, etc.
  120. Attributes:
  121. Same as Suppression.
  122. """
  123. def __init__(self, description, type, stack, defined_at):
  124. """Creates a suppression using the Memcheck, TSan, and Heapcheck syntax."""
  125. regex = '{\n.*\n%s\n' % type
  126. for line in stack:
  127. if line == ELLIPSIS:
  128. regex += '(.*\n)*'
  129. else:
  130. regex += GlobToRegex(line)
  131. regex += '\n'
  132. regex += '(.*\n)*'
  133. regex += '}'
  134. # In the recent version of valgrind-variant we've switched
  135. # from memcheck's default Addr[1248]/Value[1248]/Cond suppression types
  136. # to simply Unaddressable/Uninitialized.
  137. # The suppression generator no longer gives us "old" types thus
  138. # for the "new-type" suppressions:
  139. # * Memcheck:Unaddressable should also match Addr* reports,
  140. # * Memcheck:Uninitialized should also match Cond and Value reports,
  141. #
  142. # We also want to support legacy suppressions (e.g. copied from
  143. # upstream bugs etc), so:
  144. # * Memcheck:Addr[1248] suppressions should match Unaddressable reports,
  145. # * Memcheck:Cond and Memcheck:Value[1248] should match Uninitialized.
  146. # Please note the latest two rules only apply to the
  147. # tools/valgrind/waterfall.sh suppression matcher and the real
  148. # valgrind-variant Memcheck will not suppress
  149. # e.g. Addr1 printed as Unaddressable with Addr4 suppression.
  150. # Be careful to check the access size while copying legacy suppressions!
  151. for sz in [1, 2, 4, 8]:
  152. regex = regex.replace("\nMemcheck:Addr%d\n" % sz,
  153. "\nMemcheck:(Addr%d|Unaddressable)\n" % sz)
  154. regex = regex.replace("\nMemcheck:Value%d\n" % sz,
  155. "\nMemcheck:(Value%d|Uninitialized)\n" % sz)
  156. regex = regex.replace("\nMemcheck:Cond\n",
  157. "\nMemcheck:(Cond|Uninitialized)\n")
  158. regex = regex.replace("\nMemcheck:Unaddressable\n",
  159. "\nMemcheck:(Addr.|Unaddressable)\n")
  160. regex = regex.replace("\nMemcheck:Uninitialized\n",
  161. "\nMemcheck:(Cond|Value.|Uninitialized)\n")
  162. return super(ValgrindStyleSuppression, self).__init__(
  163. description, type, stack, defined_at, regex)
  164. def __str__(self):
  165. """Stringify."""
  166. lines = [self.description, self.type] + self.stack
  167. return "{\n %s\n}\n" % "\n ".join(lines)
  168. class SuppressionError(Exception):
  169. def __init__(self, message, happened_at):
  170. self._message = message
  171. self._happened_at = happened_at
  172. def __str__(self):
  173. return 'Error reading suppressions at %s!\n%s' % (
  174. self._happened_at, self._message)
  175. def ReadValgrindStyleSuppressions(lines, supp_descriptor):
  176. """Given a list of lines, returns a list of suppressions.
  177. Args:
  178. lines: a list of lines containing suppressions.
  179. supp_descriptor: should typically be a filename.
  180. Used only when printing errors.
  181. """
  182. result = []
  183. cur_descr = ''
  184. cur_type = ''
  185. cur_stack = []
  186. in_suppression = False
  187. nline = 0
  188. for line in lines:
  189. nline += 1
  190. line = line.strip()
  191. if line.startswith('#'):
  192. continue
  193. if not in_suppression:
  194. if not line:
  195. # empty lines between suppressions
  196. pass
  197. elif line.startswith('{'):
  198. in_suppression = True
  199. pass
  200. else:
  201. raise SuppressionError('Expected: "{"',
  202. "%s:%d" % (supp_descriptor, nline))
  203. elif line.startswith('}'):
  204. result.append(
  205. ValgrindStyleSuppression(cur_descr, cur_type, cur_stack,
  206. "%s:%d" % (supp_descriptor, nline)))
  207. cur_descr = ''
  208. cur_type = ''
  209. cur_stack = []
  210. in_suppression = False
  211. elif not cur_descr:
  212. cur_descr = line
  213. continue
  214. elif not cur_type:
  215. if (not line.startswith("Memcheck:") and
  216. not line.startswith("ThreadSanitizer:") and
  217. (line != "Heapcheck:Leak")):
  218. raise SuppressionError(
  219. 'Expected "Memcheck:TYPE", "ThreadSanitizer:TYPE" '
  220. 'or "Heapcheck:Leak", got "%s"' % line,
  221. "%s:%d" % (supp_descriptor, nline))
  222. supp_type = line.split(':')[1]
  223. if not supp_type in ["Addr1", "Addr2", "Addr4", "Addr8",
  224. "Cond", "Free", "Jump", "Leak", "Overlap", "Param",
  225. "Value1", "Value2", "Value4", "Value8",
  226. "Race", "UnlockNonLocked", "InvalidLock",
  227. "Unaddressable", "Uninitialized"]:
  228. raise SuppressionError('Unknown suppression type "%s"' % supp_type,
  229. "%s:%d" % (supp_descriptor, nline))
  230. cur_type = line
  231. continue
  232. elif re.match("^fun:.*|^obj:.*|^\.\.\.$", line):
  233. cur_stack.append(line.strip())
  234. elif len(cur_stack) == 0 and cur_type == "Memcheck:Param":
  235. cur_stack.append(line.strip())
  236. else:
  237. raise SuppressionError(
  238. '"fun:function_name" or "obj:object_file" or "..." expected',
  239. "%s:%d" % (supp_descriptor, nline))
  240. return result
  241. def PresubmitCheckSuppressions(supps):
  242. """Check a list of suppressions and return a list of SuppressionErrors.
  243. Mostly useful for separating the checking logic from the Presubmit API for
  244. testing.
  245. """
  246. known_supp_names = {} # Key: name, Value: suppression.
  247. errors = []
  248. for s in supps:
  249. if re.search("<.*suppression.name.here>", s.description):
  250. # Suppression name line is
  251. # <insert_a_suppression_name_here> for Memcheck,
  252. # <Put your suppression name here> for TSan,
  253. # name=<insert_a_suppression_name_here> for DrMemory
  254. errors.append(
  255. SuppressionError(
  256. "You've forgotten to put a suppression name like bug_XXX",
  257. s.defined_at))
  258. continue
  259. if s.description in known_supp_names:
  260. errors.append(
  261. SuppressionError(
  262. 'Suppression named "%s" is defined more than once, '
  263. 'see %s' % (s.description,
  264. known_supp_names[s.description].defined_at),
  265. s.defined_at))
  266. else:
  267. known_supp_names[s.description] = s
  268. return errors
  269. def PresubmitCheck(input_api, output_api):
  270. """A helper function useful in PRESUBMIT.py
  271. Returns a list of errors or [].
  272. """
  273. sup_regex = re.compile('suppressions.*\.txt$')
  274. filenames = [f.AbsoluteLocalPath() for f in input_api.AffectedFiles()
  275. if sup_regex.search(f.LocalPath())]
  276. errors = []
  277. # TODO(timurrrr): warn on putting suppressions into a wrong file,
  278. # e.g. TSan suppression in a memcheck file.
  279. for f in filenames:
  280. try:
  281. supps = ReadSuppressionsFromFile(f)
  282. errors.extend(PresubmitCheckSuppressions(supps))
  283. except SuppressionError as e:
  284. errors.append(e)
  285. return [output_api.PresubmitError(str(e)) for e in errors]
  286. class DrMemorySuppression(Suppression):
  287. """A suppression using the DrMemory syntax.
  288. Attributes:
  289. instr: The instruction to match.
  290. Rest inherited from Suppression.
  291. """
  292. def __init__(self, name, report_type, instr, stack, defined_at):
  293. """Constructor."""
  294. self.instr = instr
  295. # Construct the regex.
  296. regex = '{\n'
  297. if report_type == 'LEAK':
  298. regex += '(POSSIBLE )?LEAK'
  299. else:
  300. regex += report_type
  301. regex += '\nname=.*\n'
  302. # TODO(rnk): Implement http://crbug.com/107416#c5 .
  303. # drmemory_analyze.py doesn't generate suppressions with an instruction in
  304. # them, so these suppressions will always fail to match. We should override
  305. # Match to fetch the instruction from the report and try to match against
  306. # that.
  307. if instr:
  308. regex += 'instruction=%s\n' % GlobToRegex(instr)
  309. for line in stack:
  310. if line == ELLIPSIS:
  311. regex += '(.*\n)*'
  312. else:
  313. regex += GlobToRegex(line)
  314. regex += '\n'
  315. regex += '(.*\n)*' # Match anything left in the stack.
  316. regex += '}'
  317. return super(DrMemorySuppression, self).__init__(name, report_type, stack,
  318. defined_at, regex)
  319. def __str__(self):
  320. """Stringify."""
  321. text = self.type + "\n"
  322. if self.description:
  323. text += "name=%s\n" % self.description
  324. if self.instr:
  325. text += "instruction=%s\n" % self.instr
  326. text += "\n".join(self.stack)
  327. text += "\n"
  328. return text
  329. # Possible DrMemory error report types. Keep consistent with suppress_name
  330. # array in drmemory/drmemory/report.c.
  331. DRMEMORY_ERROR_TYPES = [
  332. 'UNADDRESSABLE ACCESS',
  333. 'UNINITIALIZED READ',
  334. 'INVALID HEAP ARGUMENT',
  335. 'LEAK',
  336. 'POSSIBLE LEAK',
  337. 'WARNING',
  338. ]
  339. # Regexes to match valid drmemory frames.
  340. DRMEMORY_FRAME_PATTERNS = [
  341. re.compile(r"^.*\!.*$"),
  342. re.compile(r"^\<.*\+0x.*\>$"),
  343. re.compile(r"^\<not in a module\>$"),
  344. re.compile(r"^system call .*$"),
  345. re.compile(r"^\*$"),
  346. re.compile(r"^\.\.\.$"),
  347. ]
  348. def ReadDrMemorySuppressions(lines, supp_descriptor):
  349. """Given a list of lines, returns a list of DrMemory suppressions.
  350. Args:
  351. lines: a list of lines containing suppressions.
  352. supp_descriptor: should typically be a filename.
  353. Used only when parsing errors happen.
  354. """
  355. lines = StripAndSkipCommentsIterator(lines)
  356. suppressions = []
  357. for (line_no, line) in lines:
  358. if not line:
  359. continue
  360. if line not in DRMEMORY_ERROR_TYPES:
  361. raise SuppressionError('Expected a DrMemory error type, '
  362. 'found %r instead\n Valid error types: %s' %
  363. (line, ' '.join(DRMEMORY_ERROR_TYPES)),
  364. "%s:%d" % (supp_descriptor, line_no))
  365. # Suppression starts here.
  366. report_type = line
  367. name = ''
  368. instr = None
  369. stack = []
  370. defined_at = "%s:%d" % (supp_descriptor, line_no)
  371. found_stack = False
  372. for (line_no, line) in lines:
  373. if not found_stack and line.startswith('name='):
  374. name = line.replace('name=', '')
  375. elif not found_stack and line.startswith('instruction='):
  376. instr = line.replace('instruction=', '')
  377. else:
  378. # Unrecognized prefix indicates start of stack trace.
  379. found_stack = True
  380. if not line:
  381. # Blank line means end of suppression.
  382. break
  383. if not any([regex.match(line) for regex in DRMEMORY_FRAME_PATTERNS]):
  384. raise SuppressionError(
  385. ('Unexpected stack frame pattern at line %d\n' +
  386. 'Frames should be one of the following:\n' +
  387. ' module!function\n' +
  388. ' <module+0xhexoffset>\n' +
  389. ' <not in a module>\n' +
  390. ' system call Name\n' +
  391. ' *\n' +
  392. ' ...\n') % line_no, defined_at)
  393. stack.append(line)
  394. if len(stack) == 0: # In case we hit EOF or blank without any stack frames.
  395. raise SuppressionError('Suppression "%s" has no stack frames, ends at %d'
  396. % (name, line_no), defined_at)
  397. if stack[-1] == ELLIPSIS:
  398. raise SuppressionError('Suppression "%s" ends in an ellipsis on line %d' %
  399. (name, line_no), defined_at)
  400. suppressions.append(
  401. DrMemorySuppression(name, report_type, instr, stack, defined_at))
  402. return suppressions
  403. def ParseSuppressionOfType(lines, supp_descriptor, def_line_no, report_type):
  404. """Parse the suppression starting on this line.
  405. Suppressions start with a type, have an optional name and instruction, and a
  406. stack trace that ends in a blank line.
  407. """
  408. def TestStack(stack, positive, negative, suppression_parser=None):
  409. """A helper function for SelfTest() that checks a single stack.
  410. Args:
  411. stack: the stack to match the suppressions.
  412. positive: the list of suppressions that must match the given stack.
  413. negative: the list of suppressions that should not match.
  414. suppression_parser: optional arg for the suppression parser, default is
  415. ReadValgrindStyleSuppressions.
  416. """
  417. if not suppression_parser:
  418. suppression_parser = ReadValgrindStyleSuppressions
  419. for supp in positive:
  420. parsed = suppression_parser(supp.split("\n"), "positive_suppression")
  421. assert parsed[0].Match(stack.split("\n")), (
  422. "Suppression:\n%s\ndidn't match stack:\n%s" % (supp, stack))
  423. for supp in negative:
  424. parsed = suppression_parser(supp.split("\n"), "negative_suppression")
  425. assert not parsed[0].Match(stack.split("\n")), (
  426. "Suppression:\n%s\ndid match stack:\n%s" % (supp, stack))
  427. def TestFailPresubmit(supp_text, error_text, suppression_parser=None):
  428. """A helper function for SelfTest() that verifies a presubmit check fires.
  429. Args:
  430. supp_text: suppression text to parse.
  431. error_text: text of the presubmit error we expect to find.
  432. suppression_parser: optional arg for the suppression parser, default is
  433. ReadValgrindStyleSuppressions.
  434. """
  435. if not suppression_parser:
  436. suppression_parser = ReadValgrindStyleSuppressions
  437. try:
  438. supps = suppression_parser(supp_text.split("\n"), "<presubmit suppression>")
  439. except SuppressionError, e:
  440. # If parsing raised an exception, match the error text here.
  441. assert error_text in str(e), (
  442. "presubmit text %r not in SuppressionError:\n%r" %
  443. (error_text, str(e)))
  444. else:
  445. # Otherwise, run the presubmit checks over the supps. We expect a single
  446. # error that has text matching error_text.
  447. errors = PresubmitCheckSuppressions(supps)
  448. assert len(errors) == 1, (
  449. "expected exactly one presubmit error, got:\n%s" % errors)
  450. assert error_text in str(errors[0]), (
  451. "presubmit text %r not in SuppressionError:\n%r" %
  452. (error_text, str(errors[0])))
  453. def SelfTest():
  454. """Tests the Suppression.Match() capabilities."""
  455. test_memcheck_stack_1 = """{
  456. test
  457. Memcheck:Leak
  458. fun:absolutly
  459. fun:brilliant
  460. obj:condition
  461. fun:detection
  462. fun:expression
  463. }"""
  464. test_memcheck_stack_2 = """{
  465. test
  466. Memcheck:Uninitialized
  467. fun:absolutly
  468. fun:brilliant
  469. obj:condition
  470. fun:detection
  471. fun:expression
  472. }"""
  473. test_memcheck_stack_3 = """{
  474. test
  475. Memcheck:Unaddressable
  476. fun:absolutly
  477. fun:brilliant
  478. obj:condition
  479. fun:detection
  480. fun:expression
  481. }"""
  482. test_memcheck_stack_4 = """{
  483. test
  484. Memcheck:Addr4
  485. fun:absolutly
  486. fun:brilliant
  487. obj:condition
  488. fun:detection
  489. fun:expression
  490. }"""
  491. test_heapcheck_stack = """{
  492. test
  493. Heapcheck:Leak
  494. fun:absolutly
  495. fun:brilliant
  496. obj:condition
  497. fun:detection
  498. fun:expression
  499. }"""
  500. test_tsan_stack = """{
  501. test
  502. ThreadSanitizer:Race
  503. fun:absolutly
  504. fun:brilliant
  505. obj:condition
  506. fun:detection
  507. fun:expression
  508. }"""
  509. positive_memcheck_suppressions_1 = [
  510. "{\nzzz\nMemcheck:Leak\nfun:absolutly\n}",
  511. "{\nzzz\nMemcheck:Leak\nfun:ab*ly\n}",
  512. "{\nzzz\nMemcheck:Leak\nfun:absolutly\nfun:brilliant\n}",
  513. "{\nzzz\nMemcheck:Leak\n...\nfun:brilliant\n}",
  514. "{\nzzz\nMemcheck:Leak\n...\nfun:detection\n}",
  515. "{\nzzz\nMemcheck:Leak\nfun:absolutly\n...\nfun:detection\n}",
  516. "{\nzzz\nMemcheck:Leak\nfun:ab*ly\n...\nfun:detection\n}",
  517. "{\nzzz\nMemcheck:Leak\n...\nobj:condition\n}",
  518. "{\nzzz\nMemcheck:Leak\n...\nobj:condition\nfun:detection\n}",
  519. "{\nzzz\nMemcheck:Leak\n...\nfun:brilliant\nobj:condition\n}",
  520. ]
  521. positive_memcheck_suppressions_2 = [
  522. "{\nzzz\nMemcheck:Uninitialized\nfun:absolutly\n}",
  523. "{\nzzz\nMemcheck:Uninitialized\nfun:ab*ly\n}",
  524. "{\nzzz\nMemcheck:Uninitialized\nfun:absolutly\nfun:brilliant\n}",
  525. # Legacy suppression types
  526. "{\nzzz\nMemcheck:Value1\n...\nfun:brilliant\n}",
  527. "{\nzzz\nMemcheck:Cond\n...\nfun:detection\n}",
  528. "{\nzzz\nMemcheck:Value8\nfun:absolutly\nfun:brilliant\n}",
  529. ]
  530. positive_memcheck_suppressions_3 = [
  531. "{\nzzz\nMemcheck:Unaddressable\nfun:absolutly\n}",
  532. "{\nzzz\nMemcheck:Unaddressable\nfun:absolutly\nfun:brilliant\n}",
  533. "{\nzzz\nMemcheck:Unaddressable\nfun:absolutly\nfun:brilliant\n}",
  534. # Legacy suppression types
  535. "{\nzzz\nMemcheck:Addr1\n...\nfun:brilliant\n}",
  536. "{\nzzz\nMemcheck:Addr8\n...\nfun:detection\n}",
  537. ]
  538. positive_memcheck_suppressions_4 = [
  539. "{\nzzz\nMemcheck:Addr4\nfun:absolutly\n}",
  540. "{\nzzz\nMemcheck:Unaddressable\nfun:absolutly\n}",
  541. "{\nzzz\nMemcheck:Addr4\nfun:absolutly\nfun:brilliant\n}",
  542. "{\nzzz\nMemcheck:Unaddressable\n...\nfun:brilliant\n}",
  543. "{\nzzz\nMemcheck:Addr4\n...\nfun:detection\n}",
  544. ]
  545. positive_heapcheck_suppressions = [
  546. "{\nzzz\nHeapcheck:Leak\n...\nobj:condition\n}",
  547. "{\nzzz\nHeapcheck:Leak\nfun:absolutly\n}",
  548. ]
  549. positive_tsan_suppressions = [
  550. "{\nzzz\nThreadSanitizer:Race\n...\nobj:condition\n}",
  551. "{\nzzz\nThreadSanitizer:Race\nfun:absolutly\n}",
  552. ]
  553. negative_memcheck_suppressions_1 = [
  554. "{\nzzz\nMemcheck:Leak\nfun:abnormal\n}",
  555. "{\nzzz\nMemcheck:Leak\nfun:ab*liant\n}",
  556. "{\nzzz\nMemcheck:Leak\nfun:brilliant\n}",
  557. "{\nzzz\nMemcheck:Leak\nobj:condition\n}",
  558. "{\nzzz\nMemcheck:Addr8\nfun:brilliant\n}",
  559. ]
  560. negative_memcheck_suppressions_2 = [
  561. "{\nzzz\nMemcheck:Cond\nfun:abnormal\n}",
  562. "{\nzzz\nMemcheck:Value2\nfun:abnormal\n}",
  563. "{\nzzz\nMemcheck:Uninitialized\nfun:ab*liant\n}",
  564. "{\nzzz\nMemcheck:Value4\nfun:brilliant\n}",
  565. "{\nzzz\nMemcheck:Leak\nobj:condition\n}",
  566. "{\nzzz\nMemcheck:Addr8\nfun:brilliant\n}",
  567. "{\nzzz\nMemcheck:Unaddressable\nfun:brilliant\n}",
  568. ]
  569. negative_memcheck_suppressions_3 = [
  570. "{\nzzz\nMemcheck:Addr1\nfun:abnormal\n}",
  571. "{\nzzz\nMemcheck:Uninitialized\nfun:absolutly\n}",
  572. "{\nzzz\nMemcheck:Addr2\nfun:ab*liant\n}",
  573. "{\nzzz\nMemcheck:Value4\nfun:brilliant\n}",
  574. "{\nzzz\nMemcheck:Leak\nobj:condition\n}",
  575. "{\nzzz\nMemcheck:Addr8\nfun:brilliant\n}",
  576. ]
  577. negative_memcheck_suppressions_4 = [
  578. "{\nzzz\nMemcheck:Addr1\nfun:abnormal\n}",
  579. "{\nzzz\nMemcheck:Addr4\nfun:abnormal\n}",
  580. "{\nzzz\nMemcheck:Unaddressable\nfun:abnormal\n}",
  581. "{\nzzz\nMemcheck:Addr1\nfun:absolutly\n}",
  582. "{\nzzz\nMemcheck:Addr2\nfun:ab*liant\n}",
  583. "{\nzzz\nMemcheck:Value4\nfun:brilliant\n}",
  584. "{\nzzz\nMemcheck:Leak\nobj:condition\n}",
  585. "{\nzzz\nMemcheck:Addr8\nfun:brilliant\n}",
  586. ]
  587. negative_heapcheck_suppressions = [
  588. "{\nzzz\nMemcheck:Leak\nfun:absolutly\n}",
  589. "{\nzzz\nHeapcheck:Leak\nfun:brilliant\n}",
  590. ]
  591. negative_tsan_suppressions = [
  592. "{\nzzz\nThreadSanitizer:Leak\nfun:absolutly\n}",
  593. "{\nzzz\nThreadSanitizer:Race\nfun:brilliant\n}",
  594. ]
  595. TestStack(test_memcheck_stack_1,
  596. positive_memcheck_suppressions_1,
  597. negative_memcheck_suppressions_1)
  598. TestStack(test_memcheck_stack_2,
  599. positive_memcheck_suppressions_2,
  600. negative_memcheck_suppressions_2)
  601. TestStack(test_memcheck_stack_3,
  602. positive_memcheck_suppressions_3,
  603. negative_memcheck_suppressions_3)
  604. TestStack(test_memcheck_stack_4,
  605. positive_memcheck_suppressions_4,
  606. negative_memcheck_suppressions_4)
  607. TestStack(test_heapcheck_stack, positive_heapcheck_suppressions,
  608. negative_heapcheck_suppressions)
  609. TestStack(test_tsan_stack, positive_tsan_suppressions,
  610. negative_tsan_suppressions)
  611. # TODO(timurrrr): add TestFailPresubmit tests.
  612. ### DrMemory self tests.
  613. # http://crbug.com/96010 suppression.
  614. stack_96010 = """{
  615. UNADDRESSABLE ACCESS
  616. name=<insert_a_suppression_name_here>
  617. *!TestingProfile::FinishInit
  618. *!TestingProfile::TestingProfile
  619. *!BrowserAboutHandlerTest_WillHandleBrowserAboutURL_Test::TestBody
  620. *!testing::Test::Run
  621. }"""
  622. suppress_96010 = [
  623. "UNADDRESSABLE ACCESS\nname=zzz\n...\n*!testing::Test::Run\n",
  624. ("UNADDRESSABLE ACCESS\nname=zzz\n...\n" +
  625. "*!BrowserAboutHandlerTest_WillHandleBrowserAboutURL_Test::TestBody\n"),
  626. "UNADDRESSABLE ACCESS\nname=zzz\n...\n*!BrowserAboutHandlerTest*\n",
  627. "UNADDRESSABLE ACCESS\nname=zzz\n*!TestingProfile::FinishInit\n",
  628. # No name should be needed
  629. "UNADDRESSABLE ACCESS\n*!TestingProfile::FinishInit\n",
  630. # Whole trace
  631. ("UNADDRESSABLE ACCESS\n" +
  632. "*!TestingProfile::FinishInit\n" +
  633. "*!TestingProfile::TestingProfile\n" +
  634. "*!BrowserAboutHandlerTest_WillHandleBrowserAboutURL_Test::TestBody\n" +
  635. "*!testing::Test::Run\n"),
  636. ]
  637. negative_96010 = [
  638. # Wrong type
  639. "UNINITIALIZED READ\nname=zzz\n*!TestingProfile::FinishInit\n",
  640. # No ellipsis
  641. "UNADDRESSABLE ACCESS\nname=zzz\n*!BrowserAboutHandlerTest*\n",
  642. ]
  643. TestStack(stack_96010, suppress_96010, negative_96010,
  644. suppression_parser=ReadDrMemorySuppressions)
  645. # Invalid heap arg
  646. stack_invalid = """{
  647. INVALID HEAP ARGUMENT
  648. name=asdf
  649. *!foo
  650. }"""
  651. suppress_invalid = [
  652. "INVALID HEAP ARGUMENT\n*!foo\n",
  653. ]
  654. negative_invalid = [
  655. "UNADDRESSABLE ACCESS\n*!foo\n",
  656. ]
  657. TestStack(stack_invalid, suppress_invalid, negative_invalid,
  658. suppression_parser=ReadDrMemorySuppressions)
  659. # Suppress only ntdll
  660. stack_in_ntdll = """{
  661. UNADDRESSABLE ACCESS
  662. name=<insert_a_suppression_name_here>
  663. ntdll.dll!RtlTryEnterCriticalSection
  664. }"""
  665. stack_not_ntdll = """{
  666. UNADDRESSABLE ACCESS
  667. name=<insert_a_suppression_name_here>
  668. notntdll.dll!RtlTryEnterCriticalSection
  669. }"""
  670. suppress_in_ntdll = [
  671. "UNADDRESSABLE ACCESS\nntdll.dll!RtlTryEnterCriticalSection\n",
  672. ]
  673. suppress_in_any = [
  674. "UNADDRESSABLE ACCESS\n*!RtlTryEnterCriticalSection\n",
  675. ]
  676. TestStack(stack_in_ntdll, suppress_in_ntdll + suppress_in_any, [],
  677. suppression_parser=ReadDrMemorySuppressions)
  678. # Make sure we don't wildcard away the "not" part and match ntdll.dll by
  679. # accident.
  680. TestStack(stack_not_ntdll, suppress_in_any, suppress_in_ntdll,
  681. suppression_parser=ReadDrMemorySuppressions)
  682. # Suppress a POSSIBLE LEAK with LEAK.
  683. stack_foo_possible = """{
  684. POSSIBLE LEAK
  685. name=foo possible
  686. *!foo
  687. }"""
  688. suppress_foo_possible = [ "POSSIBLE LEAK\n*!foo\n" ]
  689. suppress_foo_leak = [ "LEAK\n*!foo\n" ]
  690. TestStack(stack_foo_possible, suppress_foo_possible + suppress_foo_leak, [],
  691. suppression_parser=ReadDrMemorySuppressions)
  692. # Don't suppress LEAK with POSSIBLE LEAK.
  693. stack_foo_leak = """{
  694. LEAK
  695. name=foo leak
  696. *!foo
  697. }"""
  698. TestStack(stack_foo_leak, suppress_foo_leak, suppress_foo_possible,
  699. suppression_parser=ReadDrMemorySuppressions)
  700. # Test that the presubmit checks work.
  701. forgot_to_name = """
  702. UNADDRESSABLE ACCESS
  703. name=<insert_a_suppression_name_here>
  704. ntdll.dll!RtlTryEnterCriticalSection
  705. """
  706. TestFailPresubmit(forgot_to_name, 'forgotten to put a suppression',
  707. suppression_parser=ReadDrMemorySuppressions)
  708. named_twice = """
  709. UNADDRESSABLE ACCESS
  710. name=http://crbug.com/1234
  711. *!foo
  712. UNADDRESSABLE ACCESS
  713. name=http://crbug.com/1234
  714. *!bar
  715. """
  716. TestFailPresubmit(named_twice, 'defined more than once',
  717. suppression_parser=ReadDrMemorySuppressions)
  718. forgot_stack = """
  719. UNADDRESSABLE ACCESS
  720. name=http://crbug.com/1234
  721. """
  722. TestFailPresubmit(forgot_stack, 'has no stack frames',
  723. suppression_parser=ReadDrMemorySuppressions)
  724. ends_in_ellipsis = """
  725. UNADDRESSABLE ACCESS
  726. name=http://crbug.com/1234
  727. ntdll.dll!RtlTryEnterCriticalSection
  728. ...
  729. """
  730. TestFailPresubmit(ends_in_ellipsis, 'ends in an ellipsis',
  731. suppression_parser=ReadDrMemorySuppressions)
  732. bad_stack_frame = """
  733. UNADDRESSABLE ACCESS
  734. name=http://crbug.com/1234
  735. fun:memcheck_style_frame
  736. """
  737. TestFailPresubmit(bad_stack_frame, 'Unexpected stack frame pattern',
  738. suppression_parser=ReadDrMemorySuppressions)
  739. # Test FilenameToTool.
  740. filenames_to_tools = {
  741. "tools/heapcheck/suppressions.txt": "heapcheck",
  742. "tools/valgrind/tsan/suppressions.txt": "tsan",
  743. "tools/valgrind/drmemory/suppressions.txt": "drmemory",
  744. "tools/valgrind/drmemory/suppressions_full.txt": "drmemory",
  745. "tools/valgrind/memcheck/suppressions.txt": "memcheck",
  746. "tools/valgrind/memcheck/suppressions_mac.txt": "memcheck",
  747. "asdf/tools/valgrind/memcheck/suppressions_mac.txt": "memcheck",
  748. "foo/bar/baz/tools/valgrind/memcheck/suppressions_mac.txt": "memcheck",
  749. "foo/bar/baz/tools/valgrind/suppressions.txt": None,
  750. "tools/valgrind/suppressions.txt": None,
  751. }
  752. for (filename, expected_tool) in filenames_to_tools.items():
  753. filename.replace('/', os.sep) # Make the path look native.
  754. tool = FilenameToTool(filename)
  755. assert tool == expected_tool, (
  756. "failed to get expected tool for filename %r, expected %s, got %s" %
  757. (filename, expected_tool, tool))
  758. # Test ValgrindStyleSuppression.__str__.
  759. supp = ValgrindStyleSuppression("http://crbug.com/1234", "Memcheck:Leak",
  760. ["...", "fun:foo"], "supp.txt:1")
  761. # Intentional 3-space indent. =/
  762. supp_str = ("{\n"
  763. " http://crbug.com/1234\n"
  764. " Memcheck:Leak\n"
  765. " ...\n"
  766. " fun:foo\n"
  767. "}\n")
  768. assert str(supp) == supp_str, (
  769. "str(supp) != supp_str:\nleft: %s\nright: %s" % (str(supp), supp_str))
  770. # Test DrMemorySuppression.__str__.
  771. supp = DrMemorySuppression(
  772. "http://crbug.com/1234", "LEAK", None, ["...", "*!foo"], "supp.txt:1")
  773. supp_str = ("LEAK\n"
  774. "name=http://crbug.com/1234\n"
  775. "...\n"
  776. "*!foo\n")
  777. assert str(supp) == supp_str, (
  778. "str(supp) != supp_str:\nleft: %s\nright: %s" % (str(supp), supp_str))
  779. supp = DrMemorySuppression(
  780. "http://crbug.com/1234", "UNINITIALIZED READ", "test 0x08(%eax) $0x01",
  781. ["ntdll.dll!*", "*!foo"], "supp.txt:1")
  782. supp_str = ("UNINITIALIZED READ\n"
  783. "name=http://crbug.com/1234\n"
  784. "instruction=test 0x08(%eax) $0x01\n"
  785. "ntdll.dll!*\n"
  786. "*!foo\n")
  787. assert str(supp) == supp_str, (
  788. "str(supp) != supp_str:\nleft: %s\nright: %s" % (str(supp), supp_str))
  789. if __name__ == '__main__':
  790. SelfTest()
  791. print 'PASS'