PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/deps/v8/tools/clusterfuzz/v8_foozzie.py

https://github.com/isaacs/node
Python | 508 lines | 484 code | 13 blank | 11 comment | 0 complexity | 19deb8002d2156440702b7a45ac19b1c MD5 | raw file
  1. #!/usr/bin/env python
  2. # Copyright 2016 the V8 project 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. """
  6. V8 correctness fuzzer launcher script.
  7. """
  8. # for py2/py3 compatibility
  9. from __future__ import print_function
  10. import argparse
  11. import hashlib
  12. import itertools
  13. import json
  14. import os
  15. import random
  16. import re
  17. import sys
  18. import traceback
  19. from collections import namedtuple
  20. from v8_commands import Command, FailException, PassException
  21. import v8_suppressions
  22. PYTHON3 = sys.version_info >= (3, 0)
  23. CONFIGS = dict(
  24. default=[],
  25. ignition=[
  26. '--turbo-filter=~',
  27. '--noopt',
  28. '--liftoff',
  29. '--no-wasm-tier-up',
  30. ],
  31. ignition_asm=[
  32. '--turbo-filter=~',
  33. '--noopt',
  34. '--validate-asm',
  35. '--stress-validate-asm',
  36. ],
  37. ignition_eager=[
  38. '--turbo-filter=~',
  39. '--noopt',
  40. '--no-lazy',
  41. '--no-lazy-inner-functions',
  42. ],
  43. ignition_no_ic=[
  44. '--turbo-filter=~',
  45. '--noopt',
  46. '--liftoff',
  47. '--no-wasm-tier-up',
  48. '--no-use-ic',
  49. '--no-lazy-feedback-allocation',
  50. ],
  51. ignition_turbo=[],
  52. ignition_turbo_no_ic=[
  53. '--no-use-ic',
  54. ],
  55. ignition_turbo_opt=[
  56. '--always-opt',
  57. '--no-liftoff',
  58. ],
  59. ignition_turbo_opt_eager=[
  60. '--always-opt',
  61. '--no-lazy',
  62. '--no-lazy-inner-functions',
  63. ],
  64. jitless=[
  65. '--jitless',
  66. ],
  67. slow_path=[
  68. '--force-slow-path',
  69. ],
  70. slow_path_opt=[
  71. '--always-opt',
  72. '--force-slow-path',
  73. ],
  74. trusted=[
  75. '--no-untrusted-code-mitigations',
  76. ],
  77. trusted_opt=[
  78. '--always-opt',
  79. '--no-untrusted-code-mitigations',
  80. ],
  81. )
  82. BASELINE_CONFIG = 'ignition'
  83. DEFAULT_CONFIG = 'ignition_turbo'
  84. DEFAULT_D8 = 'd8'
  85. # Return codes.
  86. RETURN_PASS = 0
  87. RETURN_FAIL = 2
  88. BASE_PATH = os.path.dirname(os.path.abspath(__file__))
  89. SANITY_CHECKS = os.path.join(BASE_PATH, 'v8_sanity_checks.js')
  90. # Timeout for one d8 run.
  91. SANITY_CHECK_TIMEOUT_SEC = 1
  92. TEST_TIMEOUT_SEC = 3
  93. SUPPORTED_ARCHS = ['ia32', 'x64', 'arm', 'arm64']
  94. # Output for suppressed failure case.
  95. FAILURE_HEADER_TEMPLATE = """#
  96. # V8 correctness failure
  97. # V8 correctness configs: %(configs)s
  98. # V8 correctness sources: %(source_key)s
  99. # V8 correctness suppression: %(suppression)s
  100. """
  101. # Extended output for failure case. The 'CHECK' is for the minimizer.
  102. FAILURE_TEMPLATE = FAILURE_HEADER_TEMPLATE + """#
  103. # CHECK
  104. #
  105. # Compared %(first_config_label)s with %(second_config_label)s
  106. #
  107. # Flags of %(first_config_label)s:
  108. %(first_config_flags)s
  109. # Flags of %(second_config_label)s:
  110. %(second_config_flags)s
  111. #
  112. # Difference:
  113. %(difference)s%(source_file_text)s
  114. #
  115. ### Start of configuration %(first_config_label)s:
  116. %(first_config_output)s
  117. ### End of configuration %(first_config_label)s
  118. #
  119. ### Start of configuration %(second_config_label)s:
  120. %(second_config_output)s
  121. ### End of configuration %(second_config_label)s
  122. """
  123. SOURCE_FILE_TEMPLATE = """
  124. #
  125. # Source file:
  126. %s"""
  127. FUZZ_TEST_RE = re.compile(r'.*fuzz(-\d+\.js)')
  128. SOURCE_RE = re.compile(r'print\("v8-foozzie source: (.*)"\);')
  129. # The number of hex digits used from the hash of the original source file path.
  130. # Keep the number small to avoid duplicate explosion.
  131. ORIGINAL_SOURCE_HASH_LENGTH = 3
  132. # Placeholder string if no original source file could be determined.
  133. ORIGINAL_SOURCE_DEFAULT = 'none'
  134. # Placeholder string for failures from crash tests. If a failure is found with
  135. # this signature, the matching sources should be moved to the mapping below.
  136. ORIGINAL_SOURCE_CRASHTESTS = 'placeholder for CrashTests'
  137. # Mapping from relative original source path (e.g. CrashTests/path/to/file.js)
  138. # to a string key. Map to the same key for duplicate issues. The key should
  139. # have more than 3 characters to not collide with other existing hashes.
  140. # If a symptom from a particular original source file is known to map to a
  141. # known failure, it can be added to this mapping. This should be done for all
  142. # failures from CrashTests, as those by default map to the placeholder above.
  143. KNOWN_FAILURES = {
  144. # Foo.caller with asm.js: https://crbug.com/1042556
  145. 'CrashTests/4782147262545920/494.js': '.caller',
  146. 'CrashTests/5637524389167104/01457.js': '.caller',
  147. 'CrashTests/5703451898085376/02176.js': '.caller',
  148. 'CrashTests/4846282433495040/04342.js': '.caller',
  149. 'CrashTests/5712410200899584/04483.js': '.caller',
  150. 'v8/test/mjsunit/regress/regress-105.js': '.caller',
  151. # Flaky issue that almost never repros.
  152. 'CrashTests/5694376231632896/1033966.js': 'flaky',
  153. }
  154. def infer_arch(d8):
  155. """Infer the V8 architecture from the build configuration next to the
  156. executable.
  157. """
  158. with open(os.path.join(os.path.dirname(d8), 'v8_build_config.json')) as f:
  159. arch = json.load(f)['v8_current_cpu']
  160. arch = 'ia32' if arch == 'x86' else arch
  161. assert arch in SUPPORTED_ARCHS
  162. return arch
  163. class ExecutionArgumentsConfig(object):
  164. def __init__(self, label):
  165. self.label = label
  166. def add_arguments(self, parser, default_config):
  167. def add_argument(flag_template, help_template, **kwargs):
  168. parser.add_argument(
  169. flag_template % self.label,
  170. help=help_template % self.label,
  171. **kwargs)
  172. add_argument(
  173. '--%s-config',
  174. '%s configuration',
  175. default=default_config)
  176. add_argument(
  177. '--%s-config-extra-flags',
  178. 'additional flags passed to the %s run',
  179. action='append',
  180. default=[])
  181. add_argument(
  182. '--%s-d8',
  183. 'optional path to %s d8 executable, '
  184. 'default: bundled in the directory of this script',
  185. default=DEFAULT_D8)
  186. def make_options(self, options, default_config=None):
  187. def get(name):
  188. return getattr(options, '%s_%s' % (self.label, name))
  189. config = default_config or get('config')
  190. assert config in CONFIGS
  191. d8 = get('d8')
  192. if not os.path.isabs(d8):
  193. d8 = os.path.join(BASE_PATH, d8)
  194. assert os.path.exists(d8)
  195. flags = CONFIGS[config] + get('config_extra_flags')
  196. RunOptions = namedtuple('RunOptions', ['arch', 'config', 'd8', 'flags'])
  197. return RunOptions(infer_arch(d8), config, d8, flags)
  198. class ExecutionConfig(object):
  199. def __init__(self, options, label):
  200. self.options = options
  201. self.label = label
  202. self.arch = getattr(options, label).arch
  203. self.config = getattr(options, label).config
  204. d8 = getattr(options, label).d8
  205. flags = getattr(options, label).flags
  206. self.command = Command(options, label, d8, flags)
  207. @property
  208. def flags(self):
  209. return self.command.flags
  210. def parse_args():
  211. first_config_arguments = ExecutionArgumentsConfig('first')
  212. second_config_arguments = ExecutionArgumentsConfig('second')
  213. parser = argparse.ArgumentParser()
  214. parser.add_argument(
  215. '--random-seed', type=int, required=True,
  216. help='random seed passed to both runs')
  217. parser.add_argument(
  218. '--skip-sanity-checks', default=False, action='store_true',
  219. help='skip sanity checks for testing purposes')
  220. parser.add_argument(
  221. '--skip-suppressions', default=False, action='store_true',
  222. help='skip suppressions to reproduce known issues')
  223. # Add arguments for each run configuration.
  224. first_config_arguments.add_arguments(parser, BASELINE_CONFIG)
  225. second_config_arguments.add_arguments(parser, DEFAULT_CONFIG)
  226. parser.add_argument('testcase', help='path to test case')
  227. options = parser.parse_args()
  228. # Ensure we have a test case.
  229. assert (os.path.exists(options.testcase) and
  230. os.path.isfile(options.testcase)), (
  231. 'Test case %s doesn\'t exist' % options.testcase)
  232. options.first = first_config_arguments.make_options(options)
  233. options.second = second_config_arguments.make_options(options)
  234. options.default = second_config_arguments.make_options(
  235. options, DEFAULT_CONFIG)
  236. # Ensure we make a valid comparison.
  237. if (options.first.d8 == options.second.d8 and
  238. options.first.config == options.second.config):
  239. parser.error('Need either executable or config difference.')
  240. return options
  241. def get_meta_data(content):
  242. """Extracts original-source-file paths from test case content."""
  243. sources = []
  244. for line in content.splitlines():
  245. match = SOURCE_RE.match(line)
  246. if match:
  247. sources.append(match.group(1))
  248. return {'sources': sources}
  249. def content_bailout(content, ignore_fun):
  250. """Print failure state and return if ignore_fun matches content."""
  251. bug = (ignore_fun(content) or '').strip()
  252. if bug:
  253. raise FailException(FAILURE_HEADER_TEMPLATE % dict(
  254. configs='', source_key='', suppression=bug))
  255. def fail_bailout(output, ignore_by_output_fun):
  256. """Print failure state and return if ignore_by_output_fun matches output."""
  257. bug = (ignore_by_output_fun(output.stdout) or '').strip()
  258. if bug:
  259. raise FailException(FAILURE_HEADER_TEMPLATE % dict(
  260. configs='', source_key='', suppression=bug))
  261. def format_difference(
  262. source_key, first_config, second_config,
  263. first_config_output, second_config_output, difference, source=None):
  264. # The first three entries will be parsed by clusterfuzz. Format changes
  265. # will require changes on the clusterfuzz side.
  266. first_config_label = '%s,%s' % (first_config.arch, first_config.config)
  267. second_config_label = '%s,%s' % (second_config.arch, second_config.config)
  268. source_file_text = SOURCE_FILE_TEMPLATE % source if source else ''
  269. if PYTHON3:
  270. first_stdout = first_config_output.stdout
  271. second_stdout = second_config_output.stdout
  272. else:
  273. first_stdout = first_config_output.stdout.decode('utf-8', 'replace')
  274. second_stdout = second_config_output.stdout.decode('utf-8', 'replace')
  275. difference = difference.decode('utf-8', 'replace')
  276. text = (FAILURE_TEMPLATE % dict(
  277. configs='%s:%s' % (first_config_label, second_config_label),
  278. source_file_text=source_file_text,
  279. source_key=source_key,
  280. suppression='', # We can't tie bugs to differences.
  281. first_config_label=first_config_label,
  282. second_config_label=second_config_label,
  283. first_config_flags=' '.join(first_config.flags),
  284. second_config_flags=' '.join(second_config.flags),
  285. first_config_output=first_stdout,
  286. second_config_output=second_stdout,
  287. source=source,
  288. difference=difference,
  289. ))
  290. if PYTHON3:
  291. return text
  292. else:
  293. return text.encode('utf-8', 'replace')
  294. def cluster_failures(source, known_failures=None):
  295. """Returns a string key for clustering duplicate failures.
  296. Args:
  297. source: The original source path where the failure happened.
  298. known_failures: Mapping from original source path to failure key.
  299. """
  300. known_failures = known_failures or KNOWN_FAILURES
  301. # No source known. Typical for manually uploaded issues. This
  302. # requires also manual issue creation.
  303. if not source:
  304. return ORIGINAL_SOURCE_DEFAULT
  305. # Source is known to produce a particular failure.
  306. if source in known_failures:
  307. return known_failures[source]
  308. # Subsume all other sources from CrashTests under one key. Otherwise
  309. # failures lead to new crash tests which in turn lead to new failures.
  310. if source.startswith('CrashTests'):
  311. return ORIGINAL_SOURCE_CRASHTESTS
  312. # We map all remaining failures to a short hash of the original source.
  313. long_key = hashlib.sha1(source.encode('utf-8')).hexdigest()
  314. return long_key[:ORIGINAL_SOURCE_HASH_LENGTH]
  315. def run_comparisons(suppress, execution_configs, test_case, timeout,
  316. verbose=True, ignore_crashes=True, source_key=None):
  317. """Runs different configurations and bails out on output difference.
  318. Args:
  319. suppress: The helper object for textual suppressions.
  320. execution_configs: Two or more configurations to run. The first one will be
  321. used as baseline to compare all others to.
  322. test_case: The test case to run.
  323. timeout: Timeout in seconds for one run.
  324. verbose: Prints the executed commands.
  325. ignore_crashes: Typically we ignore crashes during fuzzing as they are
  326. frequent. However, when running sanity checks we should not crash
  327. and immediately flag crashes as a failure.
  328. source_key: A fixed source key. If not given, it will be inferred from the
  329. output.
  330. """
  331. run_test_case = lambda config: config.command.run(
  332. test_case, timeout=timeout, verbose=verbose)
  333. # Run the baseline configuration.
  334. baseline_config = execution_configs[0]
  335. baseline_output = run_test_case(baseline_config)
  336. has_crashed = baseline_output.HasCrashed()
  337. # Iterate over the remaining configurations, run and compare.
  338. for comparison_config in execution_configs[1:]:
  339. comparison_output = run_test_case(comparison_config)
  340. has_crashed = has_crashed or comparison_output.HasCrashed()
  341. difference, source = suppress.diff(baseline_output, comparison_output)
  342. if difference:
  343. # Only bail out due to suppressed output if there was a difference. If a
  344. # suppression doesn't show up anymore in the statistics, we might want to
  345. # remove it.
  346. fail_bailout(baseline_output, suppress.ignore_by_output)
  347. fail_bailout(comparison_output, suppress.ignore_by_output)
  348. source_key = source_key or cluster_failures(source)
  349. raise FailException(format_difference(
  350. source_key, baseline_config, comparison_config,
  351. baseline_output, comparison_output, difference, source))
  352. if has_crashed:
  353. if ignore_crashes:
  354. # Show if a crash has happened in one of the runs and no difference was
  355. # detected. This is only for the statistics during experiments.
  356. raise PassException('# V8 correctness - C-R-A-S-H')
  357. else:
  358. # Subsume unexpected crashes (e.g. during sanity checks) with one failure
  359. # state.
  360. raise FailException(FAILURE_HEADER_TEMPLATE % dict(
  361. configs='', source_key='', suppression='unexpected crash'))
  362. def main():
  363. options = parse_args()
  364. suppress = v8_suppressions.get_suppression(options.skip_suppressions)
  365. # Static bailout based on test case content or metadata.
  366. kwargs = {}
  367. if PYTHON3:
  368. kwargs['encoding'] = 'utf-8'
  369. with open(options.testcase, 'r', **kwargs) as f:
  370. content = f.read()
  371. content_bailout(get_meta_data(content), suppress.ignore_by_metadata)
  372. content_bailout(content, suppress.ignore_by_content)
  373. # Prepare the baseline, default and a secondary configuration to compare to.
  374. # The baseline (turbofan) takes precedence as many of the secondary configs
  375. # are based on the turbofan config with additional parameters.
  376. execution_configs = [
  377. ExecutionConfig(options, 'first'),
  378. ExecutionConfig(options, 'default'),
  379. ExecutionConfig(options, 'second'),
  380. ]
  381. # First, run some fixed smoke tests in all configs to ensure nothing
  382. # is fundamentally wrong, in order to prevent bug flooding.
  383. if not options.skip_sanity_checks:
  384. run_comparisons(
  385. suppress, execution_configs,
  386. test_case=SANITY_CHECKS,
  387. timeout=SANITY_CHECK_TIMEOUT_SEC,
  388. verbose=False,
  389. # Don't accept crashes during sanity checks. A crash would hint at
  390. # a flag that might be incompatible or a broken test file.
  391. ignore_crashes=False,
  392. # Special source key for sanity checks so that clusterfuzz dedupes all
  393. # cases on this in case it's hit.
  394. source_key = 'sanity check failed',
  395. )
  396. # Second, run all configs against the fuzz test case.
  397. run_comparisons(
  398. suppress, execution_configs,
  399. test_case=options.testcase,
  400. timeout=TEST_TIMEOUT_SEC,
  401. )
  402. # TODO(machenbach): Figure out if we could also return a bug in case
  403. # there's no difference, but one of the line suppressions has matched -
  404. # and without the match there would be a difference.
  405. print('# V8 correctness - pass')
  406. return RETURN_PASS
  407. if __name__ == "__main__":
  408. try:
  409. result = main()
  410. except FailException as e:
  411. print(e.message)
  412. result = RETURN_FAIL
  413. except PassException as e:
  414. print(e.message)
  415. result = RETURN_PASS
  416. except SystemExit:
  417. # Make sure clusterfuzz reports internal errors and wrong usage.
  418. # Use one label for all internal and usage errors.
  419. print(FAILURE_HEADER_TEMPLATE % dict(
  420. configs='', source_key='', suppression='wrong_usage'))
  421. result = RETURN_FAIL
  422. except MemoryError:
  423. # Running out of memory happens occasionally but is not actionable.
  424. print('# V8 correctness - pass')
  425. result = RETURN_PASS
  426. except Exception as e:
  427. print(FAILURE_HEADER_TEMPLATE % dict(
  428. configs='', source_key='', suppression='internal_error'))
  429. print('# Internal error: %s' % e)
  430. traceback.print_exc(file=sys.stdout)
  431. result = RETURN_FAIL
  432. sys.exit(result)