runtime_analysis.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #!/usr/bin/env python3
  2. """Runtime analysis of the engine on headless renders: sanitizer builds, heaptrack, Valgrind.
  3. Usage:
  4. runtime_analysis.py build asan|tsan [-j jobs]
  5. runtime_analysis.py run plain|asan|tsan|heaptrack|memcheck|massif [-s scenario]... [-t seconds] [-o out dir]
  6. runtime_analysis.py swap plain|asan|tsan|heaptrack [-r rounds] [-o out dir]
  7. runtime_analysis.py fuzz build|seeds|run [target] [-t seconds]
  8. runtime_analysis.py list
  9. build makes build-asan (AddressSanitizer + UndefinedBehaviorSanitizer + LeakSanitizer) or build-tsan
  10. (ThreadSanitizer) next to build/ through the LWE_SANITIZE CMake option. The sanitizer runtimes are looked up in
  11. LWE_SANITIZER_LIBS (a lib64 folder) when the compiler's own package does not ship them.
  12. run renders the scenarios one after the other (never in parallel, a sanitizer build of a scene with V8 and CEF is
  13. heavy) with the same isolation as headless_render.sh: private XDG_RUNTIME_DIR and session bus without service
  14. activation, dead audio and system bus, no desktop variables, no core dumps, headless EGL driver. A watchdog kills the
  15. run when its process group passes --rss-limit or the machine runs below --min-available. Each scenario runs for
  16. --seconds, then gets SIGTERM so the leak checks and heaptrack's final write happen.
  17. swap loads a wallpaper and hotswaps through a list of others through the control file, --rounds times, to look at
  18. what the texture cache, CPass rebuilds and script engines leave behind.
  19. fuzz builds the libFuzzer harnesses of tools/fuzz/ (clang, AddressSanitizer + UndefinedBehaviorSanitizer) in
  20. build-fuzz/: the parser sources are compiled with coverage instrumentation next to each harness, the rest of the
  21. engine is left out (symbols the parsers never reach stay unresolved). seeds fills build-fuzz/corpus/<target> from the
  22. installed workshop items and run starts one target (-t seconds, -j workers) with crashes written to
  23. build-fuzz/crashes/<target>.
  24. Results go to <out dir> (default build/runtime-analysis/<tool>), one folder per scenario with the engine log, the
  25. sanitizer reports (<tool>.<pid>) or heaptrack's summary, and summary.txt with one line per scenario.
  26. Suppressions are in tools/runtime_analysis/.
  27. """
  28. import argparse
  29. import os
  30. import re
  31. import resource
  32. import shutil
  33. import signal
  34. import subprocess
  35. import sys
  36. import tempfile
  37. import threading
  38. import time
  39. from pathlib import Path
  40. ROOT = Path(__file__).resolve().parent.parent
  41. SUPP = ROOT / 'tools' / 'runtime_analysis'
  42. SHIM_SRC = ROOT / 'tools' / 'dbus_noop_shim.c'
  43. NOCORE_SRC = SUPP / 'nocore.c'
  44. WORKSHOP = Path(os.environ.get('LWE_WORKSHOP_DIR', Path.home() / '.local/share/Steam/steamapps/workshop/content/431960'))
  45. ASSETS = Path(os.environ.get('LWE_ASSETS_DIR', Path.home() / '.local/share/Steam/steamapps/common/wallpaper_engine/assets'))
  46. SANITIZER_LIBS = Path(os.environ.get('LWE_SANITIZER_LIBS', Path.home() / '.local/share/sanitizers/root/usr/lib64'))
  47. SCENARIOS = {
  48. 'scene-audio': ('3299228616', []),
  49. 'scene-collage': ('2250930375', []),
  50. 'scene-tiny': ('2828779339', []),
  51. 'puppet': ('3509578940', []),
  52. 'particles': ('1995089753', []),
  53. 'text': ('3577513994', []),
  54. 'model-3d': ('3777414605', []),
  55. 'scripts': ('3737268876', []),
  56. 'video-texture': ('3410266156', []),
  57. 'video': ('1367456719', []),
  58. 'splat': ('3752541815', []),
  59. 'web': ('3496522892', []),
  60. }
  61. SWAP_ITEMS = ['3299228616', '3509578940', '1995089753', '3577513994', '3777414605', '2250930375']
  62. BUILDS = {
  63. 'asan': ('build-asan', 'address;undefined'),
  64. 'tsan': ('build-tsan', 'thread'),
  65. }
  66. SANITIZER_TOOLS = ('asan', 'tsan')
  67. def build_dir(tool):
  68. return ROOT / ('build-tsan' if tool == 'tsan' else 'build-asan' if tool == 'asan' else 'build') / 'output'
  69. def build(tool, jobs):
  70. folder, sanitize = BUILDS[tool]
  71. target = ROOT / folder
  72. link = f'-L{SANITIZER_LIBS} -Wl,-rpath,{SANITIZER_LIBS}' if SANITIZER_LIBS.is_dir() else ''
  73. subprocess.run(['cmake', '-S', str(ROOT), '-B', str(target), '-DCMAKE_BUILD_TYPE=Release',
  74. f'-DLWE_SANITIZE={sanitize}', f'-DCMAKE_EXE_LINKER_FLAGS={link}',
  75. f'-DCMAKE_SHARED_LINKER_FLAGS={link}'], check=True)
  76. subprocess.run(['nice', 'cmake', '--build', str(target), '-j', str(jobs)], check=True)
  77. def available_mb():
  78. for line in Path('/proc/meminfo').read_text().splitlines():
  79. if line.startswith('MemAvailable:'):
  80. return int(line.split()[1]) // 1024
  81. return 1 << 30
  82. def group_rss_mb(pgid):
  83. total = 0
  84. for entry in Path('/proc').iterdir():
  85. if not entry.name.isdigit():
  86. continue
  87. try:
  88. stat = (entry / 'stat').read_text()
  89. if int(stat[stat.rindex(')') + 2:].split()[3]) != pgid:
  90. continue
  91. for line in (entry / 'status').read_text().splitlines():
  92. if line.startswith('VmRSS:'):
  93. total += int(line.split()[1])
  94. except (OSError, ValueError):
  95. continue
  96. return total // 1024
  97. class Watchdog(threading.Thread):
  98. def __init__(self, pgid, rss_limit, min_available, log):
  99. super().__init__(daemon=True)
  100. self.pgid, self.rss_limit, self.min_available, self.log = pgid, rss_limit, min_available, log
  101. self.stop_flag = threading.Event()
  102. self.peak = 0
  103. self.killed = None
  104. self.samples = []
  105. def run(self):
  106. while not self.stop_flag.wait(0.5):
  107. rss = group_rss_mb(self.pgid)
  108. self.peak = max(self.peak, rss)
  109. self.samples.append((time.time(), rss))
  110. free = available_mb()
  111. if rss > self.rss_limit or free < self.min_available:
  112. self.killed = f'rss {rss} MB, {free} MB available'
  113. with open(self.log, 'a') as f:
  114. f.write(f'\nWATCHDOG: killed at {self.killed}\n')
  115. try:
  116. os.killpg(self.pgid, signal.SIGKILL)
  117. except ProcessLookupError:
  118. pass
  119. return
  120. BUS_CONFIG = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
  121. "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
  122. <busconfig>
  123. <type>session</type>
  124. <listen>unix:path=%s</listen>
  125. <auth>EXTERNAL</auth>
  126. <policy context="default">
  127. <allow send_destination="*" eavesdrop="true"/>
  128. <allow eavesdrop="true"/>
  129. <allow own="*"/>
  130. </policy>
  131. </busconfig>
  132. """
  133. def start_bus(runtime):
  134. # no <servicedir>: nothing gets activated, so nothing is left behind to outlive the bus
  135. config = runtime / 'bus.conf'
  136. config.write_text(BUS_CONFIG % (runtime / 'bus'))
  137. proc = subprocess.Popen(['dbus-daemon', '--config-file', str(config), '--nofork'], stdin=subprocess.DEVNULL,
  138. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  139. for _ in range(100):
  140. if (runtime / 'bus').exists():
  141. break
  142. time.sleep(0.05)
  143. return proc
  144. def free_display():
  145. for number in range(90, 200):
  146. if not Path(f'/tmp/.X11-unix/X{number}').exists():
  147. return number
  148. raise RuntimeError('no free X display')
  149. def sanitizer_env(tool, out):
  150. reports = out / tool
  151. if tool == 'asan':
  152. return {
  153. 'ASAN_OPTIONS': f'log_path={reports}:handle_abort=1:verify_asan_link_order=0:detect_leaks=1:detect_stack_use_after_return=1:'
  154. 'allocator_may_return_null=1:strict_string_checks=1:check_initialization_order=1',
  155. 'LSAN_OPTIONS': f'suppressions={SUPP / "lsan.supp"}:print_suppressions=0',
  156. 'UBSAN_OPTIONS': f'log_path={reports}:print_stacktrace=1:suppressions={SUPP / "ubsan.supp"}',
  157. }
  158. if tool == 'tsan':
  159. return {'TSAN_OPTIONS': f'log_path={reports}:handle_abort=1:suppressions={SUPP / "tsan.supp"}:second_deadlock_stack=1:'
  160. 'history_size=4'}
  161. return {}
  162. def wrapper(tool, out):
  163. if tool == 'heaptrack':
  164. return ['heaptrack', '--record-only', '-o', str(out / 'heaptrack')]
  165. if tool == 'memcheck':
  166. return ['valgrind', '--tool=memcheck', '--leak-check=full', '--num-callers=30', '--error-limit=no',
  167. f'--log-file={out / "memcheck.%p"}', f'--suppressions={SUPP / "valgrind.supp"}']
  168. if tool == 'massif':
  169. return ['valgrind', '--tool=massif', f'--massif-out-file={out / "massif.%p"}', '--time-unit=ms']
  170. return []
  171. class Run:
  172. def __init__(self, tool, binary_dir, out, args, web=False, rss_limit=8192, min_available=6144):
  173. self.tool, self.out = tool, out
  174. out.mkdir(parents=True, exist_ok=True)
  175. scratch = Path(tempfile.mkdtemp(prefix='lwe-rt-'))
  176. self.scratch = scratch
  177. self.runtime = scratch / 'run'
  178. self.runtime.mkdir(mode=0o700)
  179. shim = scratch / 'dbus_noop_shim.so'
  180. subprocess.run(['gcc', '-shared', '-fPIC', '-o', str(shim), str(SHIM_SRC), '-ldl'], check=True)
  181. nocore = scratch / 'nocore.so'
  182. subprocess.run(['gcc', '-shared', '-fPIC', '-o', str(nocore), str(NOCORE_SRC)], check=True)
  183. # test processes must not carry the engine's name, we_manager's shutdown pkill -f matches it
  184. link = scratch / 'lwk'
  185. link.symlink_to((binary_dir / 'linux-wallpaperengine').resolve())
  186. self.bus = start_bus(self.runtime)
  187. self.xvfb = None
  188. env = {k: v for k, v in os.environ.items() if k not in (
  189. 'WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'KDE_FULL_SESSION', 'KDE_SESSION_VERSION', 'DESKTOP_SESSION',
  190. 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_DESKTOP', 'DISPLAY', 'PULSE_SERVER', 'PIPEWIRE_REMOTE')}
  191. env.update({
  192. 'XDG_RUNTIME_DIR': str(self.runtime),
  193. 'DBUS_SESSION_BUS_ADDRESS': f'unix:path={self.runtime}/bus',
  194. 'DBUS_SYSTEM_BUS_ADDRESS': 'unix:path=/nonexistent-system-bus',
  195. 'PULSE_SERVER': 'unix:/nonexistent-pulse',
  196. 'PIPEWIRE_REMOTE': '/nonexistent-pipewire',
  197. 'ALSA_CONFIG_PATH': '/dev/null',
  198. 'SDL_AUDIODRIVER': 'dummy',
  199. 'XDG_SESSION_TYPE': 'headless',
  200. 'XDG_CACHE_HOME': str(scratch / 'cache'),
  201. 'LD_LIBRARY_PATH': str(binary_dir) + (f':{SANITIZER_LIBS}' if SANITIZER_LIBS.is_dir() else ''),
  202. # the host's core_pattern pipes to a crash handler that runs whatever RLIMIT_CORE says: a crash exits here instead
  203. 'LD_PRELOAD': f'{shim}:{nocore}' if tool not in SANITIZER_TOOLS else str(shim),
  204. 'LWE_FRAME_STATS': '1',
  205. })
  206. if web:
  207. display = free_display()
  208. self.xvfb = subprocess.Popen(['Xvfb', f':{display}', '-screen', '0', '1920x1080x24', '-nolisten', 'tcp'],
  209. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  210. time.sleep(1)
  211. env.update({
  212. 'DISPLAY': f':{display}', 'LWE_CEF_NO_SANDBOX': '1',
  213. 'LWE_WEB_HOST_PRELOAD': str(binary_dir / 'libcef.so'),
  214. 'LWE_CEF_SWITCHES': '--ozone-platform=headless --use-gl=angle --use-angle=gl-egl '
  215. '--ignore-gpu-blocklist --disable-dev-shm-usage',
  216. })
  217. env.update(sanitizer_env(tool, out))
  218. self.log = out / 'engine.log'
  219. self.control = scratch / 'control'
  220. command = [*wrapper(tool, out), str(link), '--window', '0x0x1280x720', '--silent', '--assets-dir', str(ASSETS),
  221. '--control-file', str(self.control), *args]
  222. self.logfile = open(self.log, 'wb')
  223. self.started = time.time()
  224. self.proc = subprocess.Popen(command, env=env, stdin=subprocess.DEVNULL, stdout=self.logfile,
  225. stderr=subprocess.STDOUT, preexec_fn=self.child_setup)
  226. self.watchdog = Watchdog(self.proc.pid, rss_limit, min_available, self.log)
  227. self.watchdog.start()
  228. @staticmethod
  229. def child_setup():
  230. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  231. os.setsid()
  232. def alive(self):
  233. return self.proc.poll() is None
  234. def engine_pid(self):
  235. # behind a wrapper script the engine is a child of the process this class started
  236. for entry in Path('/proc').iterdir():
  237. if not entry.name.isdigit():
  238. continue
  239. try:
  240. stat = (entry / 'stat').read_text()
  241. if int(stat[stat.rindex(')') + 2:].split()[3]) != self.proc.pid:
  242. continue
  243. if (entry / 'exe').resolve().name == 'linux-wallpaperengine' \
  244. and b'--web-host' not in (entry / 'cmdline').read_bytes():
  245. return int(entry.name)
  246. except (OSError, ValueError):
  247. continue
  248. return self.proc.pid
  249. def hotswap(self, text):
  250. self.control.write_text(text)
  251. os.kill(self.engine_pid() if self.tool == 'heaptrack' else self.proc.pid, signal.SIGUSR1)
  252. def finish(self, grace=120):
  253. if self.alive():
  254. # the wrappers (heaptrack, valgrind) have to pass it on, so the whole group gets it
  255. os.killpg(self.proc.pid, signal.SIGTERM)
  256. try:
  257. self.proc.wait(grace)
  258. except subprocess.TimeoutExpired:
  259. os.killpg(self.proc.pid, signal.SIGKILL)
  260. self.proc.wait()
  261. try:
  262. os.killpg(self.proc.pid, signal.SIGKILL)
  263. except ProcessLookupError:
  264. pass
  265. self.watchdog.stop_flag.set()
  266. self.logfile.close()
  267. self.bus.kill()
  268. self.bus.wait(5)
  269. if self.xvfb:
  270. self.xvfb.kill()
  271. self.xvfb.wait(5)
  272. shutil.rmtree(self.scratch, ignore_errors=True)
  273. return self.proc.returncode
  274. REPORT_MARKERS = {
  275. 'asan': [('AddressSanitizer', 'ERROR: AddressSanitizer'), ('LeakSanitizer', 'ERROR: LeakSanitizer'),
  276. ('UBSan', 'runtime error:')],
  277. 'tsan': [('races', 'WARNING: ThreadSanitizer: data race'), ('other', 'WARNING: ThreadSanitizer'),
  278. ('deadlock', 'lock-order-inversion')],
  279. 'memcheck': [('invalid', 'Invalid '), ('uninit', 'uninitialised'), ('leaks', 'definitely lost')],
  280. }
  281. def rss_growth(samples):
  282. # RSS of the process group over the last 70% of the run (the first 30% is loading), in MB per minute
  283. if len(samples) < 20:
  284. return None
  285. steady = samples[len(samples) * 3 // 10:]
  286. n = len(steady)
  287. mean_t = sum(t for t, _ in steady) / n
  288. mean_r = sum(r for _, r in steady) / n
  289. spread = sum((t - mean_t) ** 2 for t, _ in steady)
  290. return 60 * sum((t - mean_t) * (r - mean_r) for t, r in steady) / spread if spread else 0.0
  291. def summarize(tool, out, run, code):
  292. text = run.log.read_text(errors='replace')
  293. reports = ''
  294. for path in sorted(out.glob(f'{tool}*')) + sorted(out.glob('memcheck.*')):
  295. if path.is_file():
  296. reports += path.read_text(errors='replace')
  297. counts = []
  298. for label, marker in REPORT_MARKERS.get(tool, []):
  299. counts.append(f'{label}={(reports + text).count(marker)}')
  300. stats = len(re.findall(r'FRAME-STATS', text))
  301. growth = rss_growth(run.watchdog.samples)
  302. parts = [f'exit={code}', f'peak={run.watchdog.peak}MB',
  303. f'growth={growth:+.1f}MB/min' if growth is not None else 'growth=n/a', f'stats-windows={stats}', *counts]
  304. if run.watchdog.killed:
  305. parts.append(f'WATCHDOG({run.watchdog.killed})')
  306. if tool == 'heaptrack':
  307. dumps = sorted(out.glob('heaptrack*.zst')) + sorted(out.glob('heaptrack*.gz'))
  308. if dumps:
  309. summary = subprocess.run(['heaptrack_print', '-n', '25', str(dumps[-1])], capture_output=True, text=True)
  310. (out / 'heaptrack_summary.txt').write_text(summary.stdout)
  311. leaks = subprocess.run(['heaptrack_print', '-l', '-n', '25', '-s', '12', str(dumps[-1])],
  312. capture_output=True, text=True)
  313. (out / 'heaptrack_leaks.txt').write_text(leaks.stdout[leaks.stdout.find('MEMORY LEAKS'):])
  314. peak = re.search(r'peak heap memory consumption: (\S+)', summary.stdout)
  315. leaked = re.search(r'total memory leaked: (\S+)', summary.stdout)
  316. parts += [f'heap-peak={peak.group(1) if peak else "?"}', f'leaked={leaked.group(1) if leaked else "?"}']
  317. return ' '.join(parts)
  318. def run_scenario(tool, name, args, seconds, web, out_root, rss_limit, min_available):
  319. binary_dir = build_dir(tool if tool in SANITIZER_TOOLS else 'plain')
  320. out = out_root / name
  321. if out.exists():
  322. shutil.rmtree(out)
  323. run = Run(tool, binary_dir, out, args, web, rss_limit, min_available)
  324. end = time.time() + seconds
  325. while time.time() < end and run.alive():
  326. time.sleep(0.5)
  327. code = run.finish()
  328. return summarize(tool, out, run, code)
  329. def command_run(options):
  330. if options.tool in SANITIZER_TOOLS and not (build_dir(options.tool) / 'linux-wallpaperengine').exists():
  331. sys.exit(f'{build_dir(options.tool).parent} is not built, run: runtime_analysis.py build {options.tool}')
  332. out_root = Path(options.out) if options.out else ROOT / 'build' / 'runtime-analysis' / options.tool
  333. out_root.mkdir(parents=True, exist_ok=True)
  334. names = options.scenario or list(SCENARIOS)
  335. lines = []
  336. for name in names:
  337. item, extra = SCENARIOS[name]
  338. path = WORKSHOP / item
  339. if not path.is_dir():
  340. lines.append(f'{name}: SKIP, {item} not in {WORKSHOP}')
  341. continue
  342. web = name == 'web'
  343. seconds = options.seconds * (3 if options.tool in ('memcheck', 'massif') else 1)
  344. print(f'== {name} ({item}) {options.tool} {seconds}s', flush=True)
  345. line = f'{name}: ' + run_scenario(options.tool, name, [*extra, str(path)], seconds, web, out_root,
  346. options.rss_limit, options.min_available)
  347. print(line, flush=True)
  348. lines.append(line)
  349. (out_root / 'summary.txt').write_text('\n'.join(lines) + '\n')
  350. def command_swap(options):
  351. out_root = Path(options.out) if options.out else ROOT / 'build' / 'runtime-analysis' / options.tool
  352. out = out_root / 'swap'
  353. binary_dir = build_dir(options.tool if options.tool in SANITIZER_TOOLS else 'plain')
  354. items = [WORKSHOP / item for item in SWAP_ITEMS if (WORKSHOP / item).is_dir()]
  355. if len(items) < 2:
  356. sys.exit('need at least two of the swap wallpapers installed')
  357. if out.exists():
  358. shutil.rmtree(out)
  359. run = Run(options.tool, binary_dir, out, [str(items[0])], False, options.rss_limit, options.min_available)
  360. time.sleep(options.wait)
  361. swaps = 0
  362. for round_number in range(options.rounds):
  363. for item in items:
  364. if not run.alive():
  365. break
  366. run.hotswap(f'path={item}\n')
  367. swaps += 1
  368. time.sleep(options.wait)
  369. print(f'round {round_number + 1}: rss {group_rss_mb(run.proc.pid)} MB, alive={run.alive()}', flush=True)
  370. code = run.finish()
  371. failed = run.log.read_text(errors='replace').count('Hotswap failed')
  372. line = f'swap: swaps={swaps} failed-swaps={failed} ' + summarize(options.tool, out, run, code)
  373. print(line)
  374. (out_root / 'summary.txt').write_text(line + '\n')
  375. FUZZ_DIR = ROOT / 'build-fuzz'
  376. FUZZ_TARGETS = ['texture', 'package', 'mdl', 'sog', 'json']
  377. FUZZ_SOURCES = ['Data/*.cpp', 'Data/Builders/*.cpp', 'Data/Model/*.cpp', 'Data/Parsers/*.cpp', 'Data/Utils/*.cpp',
  378. 'Assets/*.cpp', 'FileSystem/*.cpp', 'FileSystem/Adapters/*.cpp', 'Logging/*.cpp', 'Maths.cpp',
  379. 'Render/Objects/Puppet*.cpp', 'Render/Objects/CMesh.cpp', 'Splat/SogLoader.cpp']
  380. FUZZ_LIBS = ['-llz4', '-lavcodec', '-lavutil', '-lavformat', '-lswscale', '-lswresample', '-lpng', '-lfreetype',
  381. '-lharfbuzz', '-lGLEW', '-lGL']
  382. FUZZ_FLAGS = ['-std=gnu++20', '-O1', '-g1', '-fno-omit-frame-pointer', '-fno-sanitize=vptr', '-Wno-narrowing', '-w']
  383. def fuzz_compile_flags():
  384. import json
  385. import shlex
  386. for entry in json.loads((ROOT / 'build' / 'compile_commands.json').read_text()):
  387. if entry['file'].endswith('Parsers/TextureParser.cpp'):
  388. words = shlex.split(entry['command'])
  389. flags, i = [], 1
  390. while i < len(words):
  391. if words[i].startswith(('-I', '-D')):
  392. flags.append(words[i])
  393. elif words[i] == '-isystem':
  394. flags += ['-isystem', words[i + 1]]
  395. i += 1
  396. i += 1
  397. return flags
  398. sys.exit('build/compile_commands.json has no TextureParser.cpp, configure build/ first')
  399. def fuzz_build(jobs):
  400. import concurrent.futures
  401. objects = FUZZ_DIR / 'obj'
  402. objects.mkdir(parents=True, exist_ok=True)
  403. flags = fuzz_compile_flags()
  404. sources = sorted(path for pattern in FUZZ_SOURCES for path in (ROOT / 'src' / 'WallpaperEngine').glob(pattern))
  405. def compile_one(source):
  406. target = objects / (str(source.relative_to(ROOT)).replace('/', '_') + '.o')
  407. if target.exists() and target.stat().st_mtime > source.stat().st_mtime:
  408. return target
  409. subprocess.run(['clang++', *FUZZ_FLAGS, '-fsanitize=fuzzer-no-link,address,undefined', '-fPIC', *flags,
  410. '-c', str(source), '-o', str(target)], check=True)
  411. return target
  412. with concurrent.futures.ThreadPoolExecutor(jobs) as pool:
  413. objs = list(pool.map(compile_one, sources))
  414. globals_file = FUZZ_DIR / 'globals.cpp'
  415. globals_file.write_text('float g_Time;\nfloat g_TimeLast;\n')
  416. for name in FUZZ_TARGETS:
  417. subprocess.run(['clang++', *FUZZ_FLAGS, '-fsanitize=fuzzer,address,undefined', *flags,
  418. str(ROOT / 'tools' / 'fuzz' / f'{name}.cpp'), str(globals_file), *map(str, objs),
  419. '-o', str(FUZZ_DIR / name), '-Wl,--unresolved-symbols=ignore-all', *FUZZ_LIBS], check=True)
  420. print(f'built {FUZZ_DIR / name}')
  421. def fuzz_seeds():
  422. sys.path.insert(0, str(ROOT / 'tools'))
  423. import struct
  424. def sized(f):
  425. return f.read(struct.unpack('<I', f.read(4))[0])
  426. corpus = FUZZ_DIR / 'corpus'
  427. for name in FUZZ_TARGETS:
  428. (corpus / name).mkdir(parents=True, exist_ok=True)
  429. counts = dict.fromkeys(FUZZ_TARGETS, 0)
  430. def add(name, data, label):
  431. if 0 < len(data) <= 1_000_000:
  432. (corpus / name / label).write_bytes(data)
  433. counts[name] += 1
  434. for pkg in sorted(WORKSHOP.glob('*/*.pkg')):
  435. item = pkg.parent.name
  436. with open(pkg, 'rb') as f:
  437. try:
  438. sized(f)
  439. entries = [(sized(f).decode('utf-8', 'replace'), *struct.unpack('<II', f.read(8)))
  440. for _ in range(struct.unpack('<I', f.read(4))[0])]
  441. except (struct.error, ValueError):
  442. continue
  443. base = f.tell()
  444. add('package', pkg.read_bytes()[:base + 64], f'{item}_{pkg.stem}_head')
  445. for entry, offset, length in entries:
  446. kind = {'.tex': 'texture', '.mdl': 'mdl', '.json': 'json'}.get(Path(entry).suffix)
  447. if kind and counts[kind] < (1500 if kind == 'json' else 400) and (kind != 'json' or length < 60_000):
  448. f.seek(base + offset)
  449. add(kind, f.read(length), f'{item}_{entry.replace("/", "_")}')
  450. for project in sorted(WORKSHOP.glob('*/project.json')):
  451. add('json', project.read_bytes(), f'{project.parent.name}_project.json')
  452. for meta in sorted(WORKSHOP.glob('*/imgs/*/meta.json'))[:3]:
  453. image = min(meta.parent.glob('*.webp'), key=lambda path: path.stat().st_size, default=None)
  454. if image is not None:
  455. text = meta.read_bytes()
  456. add('sog', struct.pack('<H', len(text)) + text + image.read_bytes(), f'{meta.parent.parent.parent.name}_{meta.parent.name}')
  457. print(', '.join(f'{name}: {count}' for name, count in counts.items()))
  458. def fuzz_run(options):
  459. binary = FUZZ_DIR / options.target
  460. crashes = FUZZ_DIR / 'crashes' / options.target
  461. crashes.mkdir(parents=True, exist_ok=True)
  462. corpus = FUZZ_DIR / 'corpus' / options.target
  463. work = FUZZ_DIR / 'work' / options.target
  464. work.mkdir(parents=True, exist_ok=True)
  465. env = {**os.environ, 'ASAN_OPTIONS': 'allocator_may_return_null=1:detect_leaks=1:max_allocation_size_mb=2048',
  466. 'UBSAN_OPTIONS': f'print_stacktrace=1:suppressions={SUPP / "ubsan.supp"}'}
  467. subprocess.run([str(binary), str(work), str(corpus), f'-max_total_time={options.seconds}', '-max_len=1000000',
  468. '-rss_limit_mb=3000', '-timeout=20', f'-artifact_prefix={crashes}/', f'-jobs={options.jobs}',
  469. f'-workers={options.jobs}', '-print_final_stats=1'], env=env, cwd=work)
  470. def main():
  471. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  472. sub = parser.add_subparsers(dest='command', required=True)
  473. b = sub.add_parser('build')
  474. b.add_argument('tool', choices=BUILDS)
  475. b.add_argument('-j', '--jobs', type=int, default=8)
  476. for name in ('run', 'swap'):
  477. r = sub.add_parser(name)
  478. r.add_argument('tool', choices=['plain', 'asan', 'tsan', 'heaptrack', 'memcheck', 'massif'])
  479. r.add_argument('-o', '--out')
  480. r.add_argument('--rss-limit', type=int, default=8192, help='MB for the whole process group')
  481. r.add_argument('--min-available', type=int, default=6144, help='MB of MemAvailable below which the run is killed')
  482. if name == 'run':
  483. r.add_argument('-s', '--scenario', action='append', choices=list(SCENARIOS))
  484. r.add_argument('-t', '--seconds', type=int, default=40)
  485. else:
  486. r.add_argument('-r', '--rounds', type=int, default=3)
  487. r.add_argument('-w', '--wait', type=float, default=8, help='seconds to let each wallpaper run')
  488. f = sub.add_parser('fuzz')
  489. f.add_argument('action', choices=['build', 'seeds', 'run'])
  490. f.add_argument('target', nargs='?', choices=FUZZ_TARGETS)
  491. f.add_argument('-t', '--seconds', type=int, default=300)
  492. f.add_argument('-j', '--jobs', type=int, default=4)
  493. sub.add_parser('list')
  494. options = parser.parse_args()
  495. if options.command == 'build':
  496. build(options.tool, options.jobs)
  497. elif options.command == 'run':
  498. command_run(options)
  499. elif options.command == 'swap':
  500. command_swap(options)
  501. elif options.command == 'fuzz':
  502. if options.action == 'build':
  503. fuzz_build(options.jobs)
  504. elif options.action == 'seeds':
  505. fuzz_seeds()
  506. elif options.target is None:
  507. sys.exit('fuzz run needs a target')
  508. else:
  509. fuzz_run(options)
  510. else:
  511. for name, (item, extra) in SCENARIOS.items():
  512. print(f'{name:14s} {item} {" ".join(extra)}')
  513. if __name__ == '__main__':
  514. main()