static_analysis.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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] [--full] 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. --full widens the clang tools: the analyzer also runs the alpha, optin, security and cplusplus checkers (noisier, some
  16. report things that cannot happen), and clang-tidy gets a second run in tidy-full/ with the bugprone, cert, concurrency,
  17. misc, performance and portability groups besides the repo's own list.
  18. Run one tool at a time on a machine others are using, each one starts <jobs> processes.
  19. """
  20. import argparse
  21. import json
  22. import os
  23. import plistlib
  24. import re
  25. import shutil
  26. import subprocess
  27. import sys
  28. from collections import Counter
  29. from pathlib import Path
  30. ROOT = Path(__file__).resolve().parent.parent
  31. SOURCE_SUFFIXES = {'.c', '.cc', '.cpp'}
  32. CLANG_EXTRA_ARG = '-Wno-unknown-warning-option'
  33. def define_count(entry):
  34. command = entry.get('command') or ' '.join(entry['arguments'])
  35. return command.count(' -D')
  36. def own_database(build, out):
  37. entries = json.loads((build / 'compile_commands.json').read_text())
  38. src = ROOT / 'src'
  39. external = src / 'External'
  40. seen = {}
  41. for entry in entries:
  42. path = Path(entry['directory'], entry['file']).resolve()
  43. if path.suffix not in SOURCE_SUFFIXES or src not in path.parents or external in path.parents:
  44. continue
  45. # a file built by two targets keeps the entry of the one with the feature defines (ENABLE_WAYLAND, ...)
  46. if path not in seen or define_count(entry) > define_count(seen[path]):
  47. seen[path] = entry
  48. out.mkdir(parents=True, exist_ok=True)
  49. database = out / 'compile_commands.json'
  50. database.write_text(json.dumps(list(seen.values()), indent=1))
  51. return database, list(seen.values())
  52. def ours(path):
  53. path = Path(path)
  54. src = ROOT / 'src'
  55. return src in path.parents and (src / 'External') not in path.parents
  56. def write_report(out, findings):
  57. unique = sorted(set(findings))
  58. (out / 'report.txt').write_text(''.join(line + '\n' for _, line in unique))
  59. counts = Counter(check for check, _ in unique)
  60. print(f'{len(unique)} unique findings in {out / "report.txt"}')
  61. for check, count in counts.most_common():
  62. print(f'{count:6d} {check}')
  63. def run_pvs(build, out, jobs, full=False):
  64. folder = out / 'pvs'
  65. shutil.rmtree(folder, ignore_errors=True)
  66. database, entries = own_database(build, folder)
  67. log = folder / 'pvs.log'
  68. subprocess.run(['pvs-studio-analyzer', 'analyze', '-f', str(database), '-o', str(log), '-j', str(jobs),
  69. '-e', str(ROOT / 'src/External')], check=True)
  70. levels = 'GA:1,2,3;64:1,2,3;OP:1,2,3'
  71. text = folder / 'raw.txt'
  72. subprocess.run(['plog-converter', '-a', levels, '-t', 'errorfile', '-o', str(text), str(log)],
  73. check=True, stdout=subprocess.DEVNULL)
  74. subprocess.run(['plog-converter', '-a', levels, '-t', 'fullhtml', '-o', str(folder / 'html'), str(log)],
  75. check=True, stdout=subprocess.DEVNULL)
  76. pattern = re.compile(r'^(.+?):(\d+):(\d+): (?:warning|error|note): (V\d+) (.*)$')
  77. findings = []
  78. for line in text.read_text(errors='replace').splitlines():
  79. match = pattern.match(line)
  80. if match and ours(match.group(1)):
  81. path, row, col, code, message = match.groups()
  82. findings.append((code, f'{path}:{row}:{col}: [{code}] {message}'))
  83. print(f'{len(entries)} files analyzed')
  84. write_report(folder, findings)
  85. CSA_FULL_CHECKERS = ['alpha.core', 'alpha.cplusplus', 'alpha.security', 'alpha.unix', 'alpha.deadcode',
  86. 'optin.cplusplus', 'optin.performance', 'optin.portability', 'security', 'cplusplus', 'nullability']
  87. TIDY_FULL_CHECKS = ('-*,bugprone-*,cert-*,clang-analyzer-*,concurrency-*,misc-*,performance-*,portability-*,'
  88. '-misc-non-private-member-variables-in-classes,-misc-include-cleaner')
  89. def run_csa(build, out, jobs, full=False):
  90. folder = out / 'csa'
  91. shutil.rmtree(folder, ignore_errors=True)
  92. database, entries = own_database(build, folder)
  93. shards = []
  94. for index in range(jobs):
  95. part = entries[index::jobs]
  96. if not part:
  97. continue
  98. shard = folder / f'shard{index}'
  99. shard.mkdir()
  100. (shard / 'compile_commands.json').write_text(json.dumps(part))
  101. wrapper = shard / 'clang++'
  102. wrapper.write_text(f'#!/bin/sh\ncase "$1" in -cc1*) exec clang++ "$@" ;; esac\n'
  103. f'exec clang++ {CLANG_EXTRA_ARG} "$@"\n')
  104. wrapper.chmod(0o755)
  105. command = ['analyze-build', '--cdb', str(shard / 'compile_commands.json'),
  106. '--output', str(shard / 'reports'), '--plist', '--use-analyzer', str(wrapper)]
  107. for checker in CSA_FULL_CHECKERS if full else []:
  108. command += ['--enable-checker', checker]
  109. shards.append(subprocess.Popen(command))
  110. for process in shards:
  111. process.wait()
  112. findings = []
  113. failures = 0
  114. for plist in folder.glob('shard*/reports/*/*.plist'):
  115. data = plistlib.loads(plist.read_bytes())
  116. files = data.get('files', [])
  117. for diag in data.get('diagnostics', []):
  118. location = diag['location']
  119. path = files[location['file']]
  120. if ours(path):
  121. check = diag.get('check_name', diag.get('category', 'csa'))
  122. findings.append((check, f"{path}:{location['line']}:{location['col']}: [{check}] "
  123. f"{diag['description']}"))
  124. for failure in folder.glob('shard*/reports/*/failures/*'):
  125. failures += 1
  126. print(f'{len(entries)} files analyzed, {failures} failure reports (files clang could not parse)')
  127. write_report(folder, findings)
  128. def run_tidy(build, out, jobs, full=False):
  129. run_tidy_with(build, out / 'tidy', jobs, None)
  130. if full:
  131. run_tidy_with(build, out / 'tidy-full', jobs, TIDY_FULL_CHECKS)
  132. def run_tidy_with(build, folder, jobs, checks):
  133. shutil.rmtree(folder, ignore_errors=True)
  134. database, entries = own_database(build, folder)
  135. log = folder / 'tidy.log'
  136. header_filter = f'{ROOT}/src/(WallpaperEngine|Steam)/.*|{ROOT}/src/[^/]*'
  137. with open(log, 'w') as handle:
  138. subprocess.run(['run-clang-tidy', '-p', str(folder), '-j', str(jobs), '-quiet',
  139. f'-extra-arg={CLANG_EXTRA_ARG}', f'-header-filter={header_filter}',
  140. f'-config-file={ROOT / ".clang-tidy"}', *([f'-checks={checks}'] if checks else [])],
  141. stdout=handle, stderr=subprocess.STDOUT, check=False)
  142. pattern = re.compile(r'^(.+?):(\d+):(\d+): (warning|error): (.*) \[([\w.,-]+)\]$')
  143. findings = []
  144. for line in log.read_text(errors='replace').splitlines():
  145. match = pattern.match(line)
  146. if match and ours(match.group(1)):
  147. path, row, col, _, message, check = match.groups()
  148. findings.append((check, f'{path}:{row}:{col}: [{check}] {message}'))
  149. print(f'{len(entries)} files analyzed')
  150. write_report(folder, findings)
  151. TOOLS = {'pvs': run_pvs, 'csa': run_csa, 'tidy': run_tidy}
  152. def main():
  153. parser = argparse.ArgumentParser(description=__doc__.split('\n')[0])
  154. parser.add_argument('tool', choices=[*TOOLS, 'all'])
  155. parser.add_argument('-b', '--build', type=Path, default=ROOT / 'build')
  156. parser.add_argument('-o', '--out', type=Path, default=ROOT / 'build' / 'static-analysis')
  157. parser.add_argument('--full', action='store_true', help='wider clang analyzer and clang-tidy checks')
  158. parser.add_argument('-j', '--jobs', type=int, default=8)
  159. args = parser.parse_args()
  160. if not (args.build / 'compile_commands.json').exists():
  161. sys.exit(f'{args.build}/compile_commands.json is missing, configure with -DCMAKE_EXPORT_COMPILE_COMMANDS=ON')
  162. for name in (TOOLS if args.tool == 'all' else [args.tool]):
  163. print(f'== {name} ==', flush=True)
  164. TOOLS[name](args.build.resolve(), args.out.resolve(), args.jobs, args.full)
  165. if __name__ == '__main__':
  166. main()