static_analysis.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. #!/usr/bin/env python3
  2. """Static analysis over our own sources (src/, not src/External) with PVS-Studio, the Clang Static Analyzer and clang-tidy.
  3. Usage:
  4. static_analysis.py [-b build dir] [-o out dir] [-j jobs] pvs|csa|tidy|all
  5. Needs a build made with CMAKE_EXPORT_COMPILE_COMMANDS=ON (default build dir: build). The compile database comes from
  6. GCC, so the clang tools get -Wno-unknown-warning-option for the GCC-only warning flags in it. Every tool works on a
  7. copy of the database that only holds our own translation units, one entry per file.
  8. Results go to <out dir> (default build/static-analysis, git ignored), one folder per tool, each with a report.txt of
  9. unique findings in `file:line:col: [check] message` form that only lists files under src/ outside src/External, and a
  10. count per check printed at the end:
  11. pvs/ PVS-Studio (needs a license in ~/.config/PVS-Studio), pvs.log is the raw log, report.txt levels 1-3 of
  12. GA, 64 and OP, html/ the browsable version
  13. csa/ analyze-build in <jobs> shards, plist files per shard, failures/ for files clang could not parse
  14. tidy/ run-clang-tidy with the repo's .clang-tidy, tidy.log is its raw output
  15. Run one tool at a time on a machine others are using, each one starts <jobs> processes.
  16. """
  17. import argparse
  18. import json
  19. import os
  20. import plistlib
  21. import re
  22. import shutil
  23. import subprocess
  24. import sys
  25. from collections import Counter
  26. from pathlib import Path
  27. ROOT = Path(__file__).resolve().parent.parent
  28. SOURCE_SUFFIXES = {'.c', '.cc', '.cpp'}
  29. CLANG_EXTRA_ARG = '-Wno-unknown-warning-option'
  30. def define_count(entry):
  31. command = entry.get('command') or ' '.join(entry['arguments'])
  32. return command.count(' -D')
  33. def own_database(build, out):
  34. entries = json.loads((build / 'compile_commands.json').read_text())
  35. src = ROOT / 'src'
  36. external = src / 'External'
  37. seen = {}
  38. for entry in entries:
  39. path = Path(entry['directory'], entry['file']).resolve()
  40. if path.suffix not in SOURCE_SUFFIXES or src not in path.parents or external in path.parents:
  41. continue
  42. # a file built by two targets keeps the entry of the one with the feature defines (ENABLE_WAYLAND, ...)
  43. if path not in seen or define_count(entry) > define_count(seen[path]):
  44. seen[path] = entry
  45. out.mkdir(parents=True, exist_ok=True)
  46. database = out / 'compile_commands.json'
  47. database.write_text(json.dumps(list(seen.values()), indent=1))
  48. return database, list(seen.values())
  49. def ours(path):
  50. path = Path(path)
  51. src = ROOT / 'src'
  52. return src in path.parents and (src / 'External') not in path.parents
  53. def write_report(out, findings):
  54. unique = sorted(set(findings))
  55. (out / 'report.txt').write_text(''.join(line + '\n' for _, line in unique))
  56. counts = Counter(check for check, _ in unique)
  57. print(f'{len(unique)} unique findings in {out / "report.txt"}')
  58. for check, count in counts.most_common():
  59. print(f'{count:6d} {check}')
  60. def run_pvs(build, out, jobs):
  61. folder = out / 'pvs'
  62. shutil.rmtree(folder, ignore_errors=True)
  63. database, entries = own_database(build, folder)
  64. log = folder / 'pvs.log'
  65. subprocess.run(['pvs-studio-analyzer', 'analyze', '-f', str(database), '-o', str(log), '-j', str(jobs),
  66. '-e', str(ROOT / 'src/External')], check=True)
  67. levels = 'GA:1,2,3;64:1,2,3;OP:1,2,3'
  68. text = folder / 'raw.txt'
  69. subprocess.run(['plog-converter', '-a', levels, '-t', 'errorfile', '-o', str(text), str(log)],
  70. check=True, stdout=subprocess.DEVNULL)
  71. subprocess.run(['plog-converter', '-a', levels, '-t', 'fullhtml', '-o', str(folder / 'html'), str(log)],
  72. check=True, stdout=subprocess.DEVNULL)
  73. pattern = re.compile(r'^(.+?):(\d+):(\d+): (?:warning|error|note): (V\d+) (.*)$')
  74. findings = []
  75. for line in text.read_text(errors='replace').splitlines():
  76. match = pattern.match(line)
  77. if match and ours(match.group(1)):
  78. path, row, col, code, message = match.groups()
  79. findings.append((code, f'{path}:{row}:{col}: [{code}] {message}'))
  80. print(f'{len(entries)} files analyzed')
  81. write_report(folder, findings)
  82. def run_csa(build, out, jobs):
  83. folder = out / 'csa'
  84. shutil.rmtree(folder, ignore_errors=True)
  85. database, entries = own_database(build, folder)
  86. shards = []
  87. for index in range(jobs):
  88. part = entries[index::jobs]
  89. if not part:
  90. continue
  91. shard = folder / f'shard{index}'
  92. shard.mkdir()
  93. (shard / 'compile_commands.json').write_text(json.dumps(part))
  94. wrapper = shard / 'clang++'
  95. wrapper.write_text(f'#!/bin/sh\ncase "$1" in -cc1*) exec clang++ "$@" ;; esac\n'
  96. f'exec clang++ {CLANG_EXTRA_ARG} "$@"\n')
  97. wrapper.chmod(0o755)
  98. shards.append(subprocess.Popen(['analyze-build', '--cdb', str(shard / 'compile_commands.json'),
  99. '--output', str(shard / 'reports'), '--plist',
  100. '--use-analyzer', str(wrapper)]))
  101. for process in shards:
  102. process.wait()
  103. findings = []
  104. failures = 0
  105. for plist in folder.glob('shard*/reports/*/*.plist'):
  106. data = plistlib.loads(plist.read_bytes())
  107. files = data.get('files', [])
  108. for diag in data.get('diagnostics', []):
  109. location = diag['location']
  110. path = files[location['file']]
  111. if ours(path):
  112. check = diag.get('check_name', diag.get('category', 'csa'))
  113. findings.append((check, f"{path}:{location['line']}:{location['col']}: [{check}] "
  114. f"{diag['description']}"))
  115. for failure in folder.glob('shard*/reports/*/failures/*'):
  116. failures += 1
  117. print(f'{len(entries)} files analyzed, {failures} failure reports (files clang could not parse)')
  118. write_report(folder, findings)
  119. def run_tidy(build, out, jobs):
  120. folder = out / 'tidy'
  121. shutil.rmtree(folder, ignore_errors=True)
  122. database, entries = own_database(build, folder)
  123. log = folder / 'tidy.log'
  124. header_filter = f'{ROOT}/src/(WallpaperEngine|Steam)/.*|{ROOT}/src/[^/]*'
  125. with open(log, 'w') as handle:
  126. subprocess.run(['run-clang-tidy', '-p', str(folder), '-j', str(jobs), '-quiet',
  127. f'-extra-arg={CLANG_EXTRA_ARG}', f'-header-filter={header_filter}',
  128. f'-config-file={ROOT / ".clang-tidy"}'],
  129. stdout=handle, stderr=subprocess.STDOUT, check=False)
  130. pattern = re.compile(r'^(.+?):(\d+):(\d+): (warning|error): (.*) \[([\w.,-]+)\]$')
  131. findings = []
  132. for line in log.read_text(errors='replace').splitlines():
  133. match = pattern.match(line)
  134. if match and ours(match.group(1)):
  135. path, row, col, _, message, check = match.groups()
  136. findings.append((check, f'{path}:{row}:{col}: [{check}] {message}'))
  137. print(f'{len(entries)} files analyzed')
  138. write_report(folder, findings)
  139. TOOLS = {'pvs': run_pvs, 'csa': run_csa, 'tidy': run_tidy}
  140. def main():
  141. parser = argparse.ArgumentParser(description=__doc__.split('\n')[0])
  142. parser.add_argument('tool', choices=[*TOOLS, 'all'])
  143. parser.add_argument('-b', '--build', type=Path, default=ROOT / 'build')
  144. parser.add_argument('-o', '--out', type=Path, default=ROOT / 'build' / 'static-analysis')
  145. parser.add_argument('-j', '--jobs', type=int, default=8)
  146. args = parser.parse_args()
  147. if not (args.build / 'compile_commands.json').exists():
  148. sys.exit(f'{args.build}/compile_commands.json is missing, configure with -DCMAKE_EXPORT_COMPILE_COMMANDS=ON')
  149. for name in (TOOLS if args.tool == 'all' else [args.tool]):
  150. print(f'== {name} ==', flush=True)
  151. TOOLS[name](args.build.resolve(), args.out.resolve(), args.jobs)
  152. if __name__ == '__main__':
  153. main()