gcc_analyzer.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python3
  2. """GCC's -fanalyzer over the engine's own sources (src/WallpaperEngine, no External), one translation unit at a time
  3. from build/compile_commands.json with the object going to /dev/null. A TU takes up to 6 GB, so the default is two at
  4. once; the machine is shared with the user's desktop.
  5. tools/analysis/gcc_analyzer.py <out dir> [-j 2] [--timeout 600] [path substring...]
  6. Writes <out dir>/<file>.txt per source with the analyzer's warnings and <out dir>/summary.txt.
  7. """
  8. import argparse
  9. import concurrent.futures
  10. import json
  11. import resource
  12. import shlex
  13. import subprocess
  14. import time
  15. from pathlib import Path
  16. ROOT = Path(__file__).resolve().parent.parent.parent
  17. def analyze(entry, out, timeout):
  18. words = shlex.split(entry['command'])
  19. command = []
  20. skip = False
  21. for word in words:
  22. if skip:
  23. skip = False
  24. continue
  25. if word == '-o':
  26. skip = True
  27. continue
  28. command.append(word)
  29. command += ['-o', '/dev/null', '-fanalyzer', '-Wno-error', '-Wno-all', '-Wno-extra', '-Wanalyzer-too-complex']
  30. command += ['-Wanalyzer-null-dereference', '-Wanalyzer-use-after-free', '-Wanalyzer-double-free',
  31. '-Wanalyzer-malloc-leak', '-Wanalyzer-file-leak', '-Wanalyzer-possible-null-argument',
  32. '-Wanalyzer-possible-null-dereference', '-Wanalyzer-null-argument', '-Wanalyzer-use-of-uninitialized-value',
  33. '-Wanalyzer-out-of-bounds', '-Wanalyzer-deref-before-check', '-Wanalyzer-fd-leak']
  34. name = str(Path(entry['file']).relative_to(ROOT)).replace('/', '_')
  35. started = time.time()
  36. try:
  37. done = subprocess.run(command, cwd=entry['directory'], capture_output=True, text=True, timeout=timeout,
  38. preexec_fn=lambda: resource.setrlimit(resource.RLIMIT_AS, (10 << 30, 10 << 30)))
  39. text, code = done.stderr, done.returncode
  40. except subprocess.TimeoutExpired:
  41. text, code = '', 'timeout'
  42. (out / f'{name}.txt').write_text(text)
  43. warnings = text.count('[-Wanalyzer-')
  44. return f'{entry["file"].replace(str(ROOT) + "/", "")}: exit={code} warnings={warnings} {time.time() - started:.0f}s'
  45. def main():
  46. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  47. parser.add_argument('out', type=Path)
  48. parser.add_argument('-j', '--jobs', type=int, default=2)
  49. parser.add_argument('--timeout', type=int, default=600)
  50. parser.add_argument('filters', nargs='*')
  51. options = parser.parse_args()
  52. options.out.mkdir(parents=True, exist_ok=True)
  53. entries = [e for e in json.loads((ROOT / 'build' / 'compile_commands.json').read_text())
  54. if '/src/WallpaperEngine/' in e['file'] and e['file'].endswith('.cpp') and '/Testing/' not in e['file']
  55. and (not options.filters or any(f in e['file'] for f in options.filters))]
  56. entries = sorted({e['file']: e for e in entries}.values(), key=lambda e: e['file'])
  57. lines = []
  58. with concurrent.futures.ThreadPoolExecutor(options.jobs) as pool:
  59. for line in pool.map(lambda e: analyze(e, options.out, options.timeout), entries):
  60. print(line, flush=True)
  61. lines.append(line)
  62. (options.out / 'summary.txt').write_text('\n'.join(lines) + '\n')
  63. if __name__ == '__main__':
  64. main()