thread_safety.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. """Runs clang's -Wthread-safety over the engine sources and prints only those diagnostics (and real errors).
  3. tools/analysis/thread_safety.py [-b build-clang] [-j 8] [file substring ...]
  4. Needs a clang build directory with compile_commands.json (cmake -DCMAKE_CXX_COMPILER=clang++
  5. -DCMAKE_EXPORT_COMPILE_COMMANDS=ON). The locks are the ones of Debugging/ThreadSafety.h, std::mutex has no attributes.
  6. """
  7. import argparse
  8. import concurrent.futures as cf
  9. import json
  10. import re
  11. import shlex
  12. import subprocess
  13. import sys
  14. from pathlib import Path
  15. ROOT = Path(__file__).resolve().parents[2]
  16. KEEP = re.compile(r'(warning: .*\[-Wthread-safety[^\]]*\]|error:)')
  17. def check(entry):
  18. args = shlex.split(entry['command'])
  19. args[0] = 'clang++'
  20. if '-o' in args:
  21. i = args.index('-o')
  22. del args[i:i + 2]
  23. args = [a for a in args if a not in ('-c', '-ftime-trace') and not (a.startswith ('-W') and not a.startswith ('-Wno-'))]
  24. args += ['-fsyntax-only', '-Wthread-safety', '-Wthread-safety-beta']
  25. result = subprocess.run(args, cwd=entry['directory'], capture_output=True, text=True)
  26. lines = [line for line in result.stderr.splitlines() if KEEP.search(line)]
  27. return [(entry['file'], line) for line in lines]
  28. def main():
  29. parser = argparse.ArgumentParser()
  30. parser.add_argument('-b', '--build', default='build-clang')
  31. parser.add_argument('-j', '--jobs', type=int, default=8)
  32. parser.add_argument('filters', nargs='*')
  33. options = parser.parse_args()
  34. entries = json.load(open(ROOT / options.build / 'compile_commands.json'))
  35. entries = [e for e in entries if '/src/WallpaperEngine/' in e['file'] or e['file'].endswith('/src/main.cpp')]
  36. if options.filters:
  37. entries = [e for e in entries if any(f in e['file'] for f in options.filters)]
  38. seen = set()
  39. with cf.ThreadPoolExecutor(options.jobs) as pool:
  40. for found in pool.map(check, entries):
  41. for _, line in found:
  42. line = line.replace(str(ROOT) + '/src/WallpaperEngine/', '')
  43. if line not in seen:
  44. seen.add(line)
  45. print(line)
  46. print(f'{len(seen)} diagnostics', file=sys.stderr)
  47. return 1 if seen else 0
  48. if __name__ == '__main__':
  49. sys.exit(main())