runtime_analysis.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. def mapping_rss_kb(pgid):
  98. """resident kB of a process group per kind of mapping: the heap, anonymous memory, each file or device"""
  99. totals = {}
  100. for entry in Path('/proc').iterdir():
  101. if not entry.name.isdigit():
  102. continue
  103. try:
  104. stat = (entry / 'stat').read_text()
  105. if int(stat[stat.rindex(')') + 2:].split()[3]) != pgid:
  106. continue
  107. lines = (entry / 'smaps').read_text().splitlines()
  108. except (OSError, ValueError):
  109. continue
  110. name = '[anon]'
  111. for line in lines:
  112. words = line.split(None, 5)
  113. if len(words) >= 2 and '-' in words[0] and not words[0].endswith(':'):
  114. name = words[5] if len(words) == 6 else '[anon]'
  115. if name.startswith('/memfd:') or name.startswith('/dev/shm'):
  116. name = name.split(' (')[0]
  117. elif line.startswith('Rss:'):
  118. totals[name] = totals.get(name, 0) + int(line.split()[1])
  119. return totals
  120. def print_mapping_growth(rounds, rows=8):
  121. """which mappings grew between the first and the last round of a swap run"""
  122. # a round after the engine died has no mappings to compare
  123. seen = [(number, snapshot) for number, snapshot in enumerate(rounds, 1) if snapshot]
  124. if len(seen) < 2:
  125. return
  126. (first_round, first), (last_round, last) = seen[1] if len(seen) > 2 else seen[0], seen[-1]
  127. growth = sorted(((last.get(name, 0) - first.get(name, 0), name) for name in set(first) | set(last)), reverse=True)
  128. print(f'mapping growth, round {first_round} -> {last_round} (MB):')
  129. for delta, name in growth[:rows]:
  130. if delta > 1024:
  131. print(f' {delta / 1024:+8.1f} {name}')
  132. class Watchdog(threading.Thread):
  133. def __init__(self, pgid, rss_limit, min_available, log):
  134. super().__init__(daemon=True)
  135. self.pgid, self.rss_limit, self.min_available, self.log = pgid, rss_limit, min_available, log
  136. self.stop_flag = threading.Event()
  137. self.peak = 0
  138. self.killed = None
  139. self.samples = []
  140. def run(self):
  141. while not self.stop_flag.wait(0.5):
  142. rss = group_rss_mb(self.pgid)
  143. self.peak = max(self.peak, rss)
  144. self.samples.append((time.time(), rss))
  145. free = available_mb()
  146. if rss > self.rss_limit or free < self.min_available:
  147. self.killed = f'rss {rss} MB, {free} MB available'
  148. with open(self.log, 'a') as f:
  149. f.write(f'\nWATCHDOG: killed at {self.killed}\n')
  150. try:
  151. os.killpg(self.pgid, signal.SIGKILL)
  152. except ProcessLookupError:
  153. pass
  154. return
  155. BUS_CONFIG = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
  156. "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
  157. <busconfig>
  158. <type>session</type>
  159. <listen>unix:path=%s</listen>
  160. <auth>EXTERNAL</auth>
  161. <policy context="default">
  162. <allow send_destination="*" eavesdrop="true"/>
  163. <allow eavesdrop="true"/>
  164. <allow own="*"/>
  165. </policy>
  166. </busconfig>
  167. """
  168. def start_bus(runtime):
  169. # no <servicedir>: nothing gets activated, so nothing is left behind to outlive the bus
  170. config = runtime / 'bus.conf'
  171. config.write_text(BUS_CONFIG % (runtime / 'bus'))
  172. proc = subprocess.Popen(['dbus-daemon', '--config-file', str(config), '--nofork'], stdin=subprocess.DEVNULL,
  173. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  174. for _ in range(100):
  175. if (runtime / 'bus').exists():
  176. break
  177. time.sleep(0.05)
  178. return proc
  179. def free_display():
  180. for number in range(90, 200):
  181. if not Path(f'/tmp/.X11-unix/X{number}').exists():
  182. return number
  183. raise RuntimeError('no free X display')
  184. def sanitizer_env(tool, out):
  185. reports = out / tool
  186. if tool == 'asan':
  187. return {
  188. 'ASAN_OPTIONS': f'log_path={reports}:handle_abort=1:verify_asan_link_order=0:detect_leaks=1:detect_stack_use_after_return=1:'
  189. 'allocator_may_return_null=1:strict_string_checks=1:check_initialization_order=1',
  190. 'LSAN_OPTIONS': f'suppressions={SUPP / "lsan.supp"}:print_suppressions=0',
  191. 'UBSAN_OPTIONS': f'log_path={reports}:print_stacktrace=1:suppressions={SUPP / "ubsan.supp"}',
  192. }
  193. if tool == 'tsan':
  194. return {'TSAN_OPTIONS': f'log_path={reports}:handle_abort=1:suppressions={SUPP / "tsan.supp"}:second_deadlock_stack=1:'
  195. 'history_size=4'}
  196. return {}
  197. def wrapper(tool, out):
  198. if tool == 'heaptrack':
  199. return ['heaptrack', '--record-only', '-o', str(out / 'heaptrack')]
  200. if tool == 'memcheck':
  201. return ['valgrind', '--tool=memcheck', '--leak-check=full', '--num-callers=30', '--error-limit=no',
  202. f'--log-file={out / "memcheck.%p"}', f'--suppressions={SUPP / "valgrind.supp"}']
  203. if tool == 'massif':
  204. return ['valgrind', '--tool=massif', f'--massif-out-file={out / "massif.%p"}', '--time-unit=ms']
  205. return []
  206. class Run:
  207. def __init__(self, tool, binary_dir, out, args, web=False, rss_limit=8192, min_available=6144):
  208. self.tool, self.out = tool, out
  209. out.mkdir(parents=True, exist_ok=True)
  210. scratch = Path(tempfile.mkdtemp(prefix='lwe-rt-'))
  211. self.scratch = scratch
  212. self.runtime = scratch / 'run'
  213. self.runtime.mkdir(mode=0o700)
  214. shim = scratch / 'dbus_noop_shim.so'
  215. subprocess.run(['gcc', '-shared', '-fPIC', '-o', str(shim), str(SHIM_SRC), '-ldl'], check=True)
  216. nocore = scratch / 'nocore.so'
  217. subprocess.run(['gcc', '-shared', '-fPIC', '-o', str(nocore), str(NOCORE_SRC)], check=True)
  218. # test processes must not carry the engine's name, we_manager's shutdown pkill -f matches it
  219. link = scratch / 'lwk'
  220. link.symlink_to((binary_dir / 'linux-wallpaperengine').resolve())
  221. self.bus = start_bus(self.runtime)
  222. self.xvfb = None
  223. env = {k: v for k, v in os.environ.items() if k not in (
  224. 'WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'KDE_FULL_SESSION', 'KDE_SESSION_VERSION', 'DESKTOP_SESSION',
  225. 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_DESKTOP', 'DISPLAY', 'PULSE_SERVER', 'PIPEWIRE_REMOTE')}
  226. env.update({
  227. 'XDG_RUNTIME_DIR': str(self.runtime),
  228. 'DBUS_SESSION_BUS_ADDRESS': f'unix:path={self.runtime}/bus',
  229. 'DBUS_SYSTEM_BUS_ADDRESS': 'unix:path=/nonexistent-system-bus',
  230. 'PULSE_SERVER': 'unix:/nonexistent-pulse',
  231. 'PIPEWIRE_REMOTE': '/nonexistent-pipewire',
  232. 'ALSA_CONFIG_PATH': '/dev/null',
  233. 'SDL_AUDIODRIVER': 'dummy',
  234. 'XDG_SESSION_TYPE': 'headless',
  235. 'XDG_CACHE_HOME': str(scratch / 'cache'),
  236. 'LD_LIBRARY_PATH': str(binary_dir) + (f':{SANITIZER_LIBS}' if SANITIZER_LIBS.is_dir() else ''),
  237. # the host's core_pattern pipes to a crash handler that runs whatever RLIMIT_CORE says: a crash exits here instead
  238. 'LD_PRELOAD': f'{shim}:{nocore}' if tool not in SANITIZER_TOOLS else str(shim),
  239. 'LWE_FRAME_STATS': '1',
  240. })
  241. if web:
  242. display = free_display()
  243. self.xvfb = subprocess.Popen(['Xvfb', f':{display}', '-screen', '0', '1920x1080x24', '-nolisten', 'tcp'],
  244. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  245. time.sleep(1)
  246. env.update({
  247. 'DISPLAY': f':{display}', 'LWE_CEF_NO_SANDBOX': '1',
  248. 'LWE_WEB_HOST_PRELOAD': str(binary_dir / 'libcef.so'),
  249. 'LWE_CEF_SWITCHES': '--ozone-platform=headless --use-gl=angle --use-angle=gl-egl '
  250. '--ignore-gpu-blocklist --disable-dev-shm-usage',
  251. })
  252. env.update(sanitizer_env(tool, out))
  253. self.log = out / 'engine.log'
  254. self.control = scratch / 'control'
  255. command = [*wrapper(tool, out), str(link), '--window', '0x0x1280x720', '--silent', '--assets-dir', str(ASSETS),
  256. '--control-file', str(self.control), *args]
  257. self.logfile = open(self.log, 'wb')
  258. self.started = time.time()
  259. self.proc = subprocess.Popen(command, env=env, stdin=subprocess.DEVNULL, stdout=self.logfile,
  260. stderr=subprocess.STDOUT, preexec_fn=self.child_setup)
  261. self.watchdog = Watchdog(self.proc.pid, rss_limit, min_available, self.log)
  262. self.watchdog.start()
  263. @staticmethod
  264. def child_setup():
  265. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  266. os.setsid()
  267. def alive(self):
  268. return self.proc.poll() is None
  269. def engine_pid(self):
  270. # behind a wrapper script the engine is a child of the process this class started
  271. for entry in Path('/proc').iterdir():
  272. if not entry.name.isdigit():
  273. continue
  274. try:
  275. stat = (entry / 'stat').read_text()
  276. if int(stat[stat.rindex(')') + 2:].split()[3]) != self.proc.pid:
  277. continue
  278. if (entry / 'exe').resolve().name == 'linux-wallpaperengine' \
  279. and b'--web-host' not in (entry / 'cmdline').read_bytes():
  280. return int(entry.name)
  281. except (OSError, ValueError):
  282. continue
  283. return self.proc.pid
  284. def hotswap(self, text):
  285. self.control.write_text(text)
  286. os.kill(self.engine_pid() if self.tool == 'heaptrack' else self.proc.pid, signal.SIGUSR1)
  287. def finish(self, grace=120):
  288. if self.alive():
  289. # the wrappers (heaptrack, valgrind) have to pass it on, so the whole group gets it
  290. os.killpg(self.proc.pid, signal.SIGTERM)
  291. try:
  292. self.proc.wait(grace)
  293. except subprocess.TimeoutExpired:
  294. os.killpg(self.proc.pid, signal.SIGKILL)
  295. self.proc.wait()
  296. try:
  297. os.killpg(self.proc.pid, signal.SIGKILL)
  298. except ProcessLookupError:
  299. pass
  300. self.watchdog.stop_flag.set()
  301. self.logfile.close()
  302. self.bus.kill()
  303. self.bus.wait(5)
  304. if self.xvfb:
  305. self.xvfb.kill()
  306. self.xvfb.wait(5)
  307. shutil.rmtree(self.scratch, ignore_errors=True)
  308. return self.proc.returncode
  309. REPORT_MARKERS = {
  310. 'asan': [('AddressSanitizer', 'ERROR: AddressSanitizer'), ('LeakSanitizer', 'ERROR: LeakSanitizer'),
  311. ('UBSan', 'runtime error:')],
  312. 'tsan': [('races', 'WARNING: ThreadSanitizer: data race'), ('other', 'WARNING: ThreadSanitizer'),
  313. ('deadlock', 'lock-order-inversion')],
  314. 'memcheck': [('invalid', 'Invalid '), ('uninit', 'uninitialised'), ('leaks', 'definitely lost')],
  315. }
  316. def rss_growth(samples):
  317. # RSS of the process group over the last 70% of the run (the first 30% is loading), in MB per minute
  318. if len(samples) < 20:
  319. return None
  320. steady = samples[len(samples) * 3 // 10:]
  321. n = len(steady)
  322. mean_t = sum(t for t, _ in steady) / n
  323. mean_r = sum(r for _, r in steady) / n
  324. spread = sum((t - mean_t) ** 2 for t, _ in steady)
  325. return 60 * sum((t - mean_t) * (r - mean_r) for t, r in steady) / spread if spread else 0.0
  326. def summarize(tool, out, run, code):
  327. text = run.log.read_text(errors='replace')
  328. reports = ''
  329. for path in sorted(out.glob(f'{tool}*')) + sorted(out.glob('memcheck.*')):
  330. if path.is_file():
  331. reports += path.read_text(errors='replace')
  332. counts = []
  333. for label, marker in REPORT_MARKERS.get(tool, []):
  334. counts.append(f'{label}={(reports + text).count(marker)}')
  335. stats = len(re.findall(r'FRAME-STATS', text))
  336. growth = rss_growth(run.watchdog.samples)
  337. parts = [f'exit={code}', f'peak={run.watchdog.peak}MB',
  338. f'growth={growth:+.1f}MB/min' if growth is not None else 'growth=n/a', f'stats-windows={stats}', *counts]
  339. if run.watchdog.killed:
  340. parts.append(f'WATCHDOG({run.watchdog.killed})')
  341. if tool == 'heaptrack':
  342. dumps = sorted(out.glob('heaptrack*.zst')) + sorted(out.glob('heaptrack*.gz'))
  343. if dumps:
  344. summary = subprocess.run(['heaptrack_print', '-n', '25', str(dumps[-1])], capture_output=True, text=True)
  345. (out / 'heaptrack_summary.txt').write_text(summary.stdout)
  346. leaks = subprocess.run(['heaptrack_print', '-l', '-n', '25', '-s', '12', str(dumps[-1])],
  347. capture_output=True, text=True)
  348. (out / 'heaptrack_leaks.txt').write_text(leaks.stdout[leaks.stdout.find('MEMORY LEAKS'):])
  349. peak = re.search(r'peak heap memory consumption: (\S+)', summary.stdout)
  350. leaked = re.search(r'total memory leaked: (\S+)', summary.stdout)
  351. parts += [f'heap-peak={peak.group(1) if peak else "?"}', f'leaked={leaked.group(1) if leaked else "?"}']
  352. return ' '.join(parts)
  353. def run_scenario(tool, name, args, seconds, web, out_root, rss_limit, min_available):
  354. binary_dir = build_dir(tool if tool in SANITIZER_TOOLS else 'plain')
  355. out = out_root / name
  356. if out.exists():
  357. shutil.rmtree(out)
  358. run = Run(tool, binary_dir, out, args, web, rss_limit, min_available)
  359. end = time.time() + seconds
  360. while time.time() < end and run.alive():
  361. time.sleep(0.5)
  362. code = run.finish()
  363. return summarize(tool, out, run, code)
  364. def command_run(options):
  365. if options.tool in SANITIZER_TOOLS and not (build_dir(options.tool) / 'linux-wallpaperengine').exists():
  366. sys.exit(f'{build_dir(options.tool).parent} is not built, run: runtime_analysis.py build {options.tool}')
  367. out_root = Path(options.out) if options.out else ROOT / 'build' / 'runtime-analysis' / options.tool
  368. out_root.mkdir(parents=True, exist_ok=True)
  369. names = options.scenario or list(SCENARIOS)
  370. lines = []
  371. for name in names:
  372. item, extra = SCENARIOS[name]
  373. path = WORKSHOP / item
  374. if not path.is_dir():
  375. lines.append(f'{name}: SKIP, {item} not in {WORKSHOP}')
  376. continue
  377. web = name == 'web'
  378. seconds = options.seconds * (3 if options.tool in ('memcheck', 'massif') else 1)
  379. print(f'== {name} ({item}) {options.tool} {seconds}s', flush=True)
  380. line = f'{name}: ' + run_scenario(options.tool, name, [*extra, str(path)], seconds, web, out_root,
  381. options.rss_limit, options.min_available)
  382. print(line, flush=True)
  383. lines.append(line)
  384. (out_root / 'summary.txt').write_text('\n'.join(lines) + '\n')
  385. def command_swap(options):
  386. out_root = Path(options.out) if options.out else ROOT / 'build' / 'runtime-analysis' / options.tool
  387. out = out_root / 'swap'
  388. binary_dir = build_dir(options.tool if options.tool in SANITIZER_TOOLS else 'plain')
  389. items = [WORKSHOP / item for item in SWAP_ITEMS if (WORKSHOP / item).is_dir()]
  390. if len(items) < 2:
  391. sys.exit('need at least two of the swap wallpapers installed')
  392. if out.exists():
  393. shutil.rmtree(out)
  394. run = Run(options.tool, binary_dir, out, [str(items[0])], False, options.rss_limit, options.min_available)
  395. time.sleep(options.wait)
  396. swaps = 0
  397. snapshots = []
  398. for round_number in range(options.rounds):
  399. for item in items:
  400. if not run.alive():
  401. break
  402. run.hotswap(f'path={item}\n')
  403. swaps += 1
  404. time.sleep(options.wait)
  405. print(f'round {round_number + 1}: rss {group_rss_mb(run.proc.pid)} MB, alive={run.alive()}', flush=True)
  406. snapshots.append(mapping_rss_kb(run.proc.pid))
  407. print_mapping_growth(snapshots)
  408. code = run.finish()
  409. failed = run.log.read_text(errors='replace').count('Hotswap failed')
  410. line = f'swap: swaps={swaps} failed-swaps={failed} ' + summarize(options.tool, out, run, code)
  411. print(line)
  412. (out_root / 'summary.txt').write_text(line + '\n')
  413. FUZZ_DIR = ROOT / 'build-fuzz'
  414. FUZZ_TARGETS = ['texture', 'package', 'mdl', 'sog', 'json']
  415. FUZZ_SOURCES = ['Data/*.cpp', 'Data/Builders/*.cpp', 'Data/Model/*.cpp', 'Data/Parsers/*.cpp', 'Data/Utils/*.cpp',
  416. 'Assets/*.cpp', 'FileSystem/*.cpp', 'FileSystem/Adapters/*.cpp', 'Logging/*.cpp', 'Maths.cpp',
  417. 'Render/Objects/Puppet*.cpp', 'Render/Objects/CMesh.cpp', 'Splat/SogLoader.cpp']
  418. FUZZ_LIBS = ['-llz4', '-lavcodec', '-lavutil', '-lavformat', '-lswscale', '-lswresample', '-lpng', '-lfreetype',
  419. '-lharfbuzz', '-lGLEW', '-lGL']
  420. FUZZ_FLAGS = ['-std=gnu++20', '-O1', '-g1', '-fno-omit-frame-pointer', '-fno-sanitize=vptr', '-Wno-narrowing', '-w']
  421. def fuzz_compile_flags():
  422. import json
  423. import shlex
  424. for entry in json.loads((ROOT / 'build' / 'compile_commands.json').read_text()):
  425. if entry['file'].endswith('Parsers/TextureParser.cpp'):
  426. words = shlex.split(entry['command'])
  427. flags, i = [], 1
  428. while i < len(words):
  429. if words[i].startswith(('-I', '-D')):
  430. flags.append(words[i])
  431. elif words[i] == '-isystem':
  432. flags += ['-isystem', words[i + 1]]
  433. i += 1
  434. i += 1
  435. return flags
  436. sys.exit('build/compile_commands.json has no TextureParser.cpp, configure build/ first')
  437. def fuzz_build(jobs):
  438. import concurrent.futures
  439. objects = FUZZ_DIR / 'obj'
  440. objects.mkdir(parents=True, exist_ok=True)
  441. flags = fuzz_compile_flags()
  442. sources = sorted(path for pattern in FUZZ_SOURCES for path in (ROOT / 'src' / 'WallpaperEngine').glob(pattern))
  443. def compile_one(source):
  444. target = objects / (str(source.relative_to(ROOT)).replace('/', '_') + '.o')
  445. if target.exists() and target.stat().st_mtime > source.stat().st_mtime:
  446. return target
  447. subprocess.run(['clang++', *FUZZ_FLAGS, '-fsanitize=fuzzer-no-link,address,undefined', '-fPIC', *flags,
  448. '-c', str(source), '-o', str(target)], check=True)
  449. return target
  450. with concurrent.futures.ThreadPoolExecutor(jobs) as pool:
  451. objs = list(pool.map(compile_one, sources))
  452. globals_file = FUZZ_DIR / 'globals.cpp'
  453. globals_file.write_text('float g_Time;\nfloat g_TimeLast;\n')
  454. for name in FUZZ_TARGETS:
  455. subprocess.run(['clang++', *FUZZ_FLAGS, '-fsanitize=fuzzer,address,undefined', *flags,
  456. str(ROOT / 'tools' / 'fuzz' / f'{name}.cpp'), str(globals_file), *map(str, objs),
  457. '-o', str(FUZZ_DIR / name), '-Wl,--unresolved-symbols=ignore-all', *FUZZ_LIBS], check=True)
  458. print(f'built {FUZZ_DIR / name}')
  459. def fuzz_seeds():
  460. sys.path.insert(0, str(ROOT / 'tools'))
  461. import struct
  462. def sized(f):
  463. return f.read(struct.unpack('<I', f.read(4))[0])
  464. corpus = FUZZ_DIR / 'corpus'
  465. for name in FUZZ_TARGETS:
  466. (corpus / name).mkdir(parents=True, exist_ok=True)
  467. counts = dict.fromkeys(FUZZ_TARGETS, 0)
  468. def add(name, data, label):
  469. if 0 < len(data) <= 1_000_000:
  470. (corpus / name / label).write_bytes(data)
  471. counts[name] += 1
  472. for pkg in sorted(WORKSHOP.glob('*/*.pkg')):
  473. item = pkg.parent.name
  474. with open(pkg, 'rb') as f:
  475. try:
  476. sized(f)
  477. entries = [(sized(f).decode('utf-8', 'replace'), *struct.unpack('<II', f.read(8)))
  478. for _ in range(struct.unpack('<I', f.read(4))[0])]
  479. except (struct.error, ValueError):
  480. continue
  481. base = f.tell()
  482. add('package', pkg.read_bytes()[:base + 64], f'{item}_{pkg.stem}_head')
  483. for entry, offset, length in entries:
  484. kind = {'.tex': 'texture', '.mdl': 'mdl', '.json': 'json'}.get(Path(entry).suffix)
  485. if kind and counts[kind] < (1500 if kind == 'json' else 400) and (kind != 'json' or length < 60_000):
  486. f.seek(base + offset)
  487. add(kind, f.read(length), f'{item}_{entry.replace("/", "_")}')
  488. for project in sorted(WORKSHOP.glob('*/project.json')):
  489. add('json', project.read_bytes(), f'{project.parent.name}_project.json')
  490. for meta in sorted(WORKSHOP.glob('*/imgs/*/meta.json'))[:3]:
  491. image = min(meta.parent.glob('*.webp'), key=lambda path: path.stat().st_size, default=None)
  492. if image is not None:
  493. text = meta.read_bytes()
  494. add('sog', struct.pack('<H', len(text)) + text + image.read_bytes(), f'{meta.parent.parent.parent.name}_{meta.parent.name}')
  495. print(', '.join(f'{name}: {count}' for name, count in counts.items()))
  496. def fuzz_run(options):
  497. binary = FUZZ_DIR / options.target
  498. crashes = FUZZ_DIR / 'crashes' / options.target
  499. crashes.mkdir(parents=True, exist_ok=True)
  500. corpus = FUZZ_DIR / 'corpus' / options.target
  501. work = FUZZ_DIR / 'work' / options.target
  502. work.mkdir(parents=True, exist_ok=True)
  503. env = {**os.environ, 'ASAN_OPTIONS': 'allocator_may_return_null=1:detect_leaks=1:max_allocation_size_mb=2048',
  504. 'UBSAN_OPTIONS': f'print_stacktrace=1:suppressions={SUPP / "ubsan.supp"}'}
  505. subprocess.run([str(binary), str(work), str(corpus), f'-max_total_time={options.seconds}', '-max_len=1000000',
  506. '-rss_limit_mb=3000', '-timeout=20', f'-artifact_prefix={crashes}/', f'-jobs={options.jobs}',
  507. f'-workers={options.jobs}', '-print_final_stats=1'], env=env, cwd=work)
  508. def main():
  509. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  510. sub = parser.add_subparsers(dest='command', required=True)
  511. b = sub.add_parser('build')
  512. b.add_argument('tool', choices=BUILDS)
  513. b.add_argument('-j', '--jobs', type=int, default=8)
  514. for name in ('run', 'swap'):
  515. r = sub.add_parser(name)
  516. r.add_argument('tool', choices=['plain', 'asan', 'tsan', 'heaptrack', 'memcheck', 'massif'])
  517. r.add_argument('-o', '--out')
  518. r.add_argument('--rss-limit', type=int, default=8192, help='MB for the whole process group')
  519. r.add_argument('--min-available', type=int, default=6144, help='MB of MemAvailable below which the run is killed')
  520. if name == 'run':
  521. r.add_argument('-s', '--scenario', action='append', choices=list(SCENARIOS))
  522. r.add_argument('-t', '--seconds', type=int, default=40)
  523. else:
  524. r.add_argument('-r', '--rounds', type=int, default=3)
  525. r.add_argument('-w', '--wait', type=float, default=8, help='seconds to let each wallpaper run')
  526. f = sub.add_parser('fuzz')
  527. f.add_argument('action', choices=['build', 'seeds', 'run'])
  528. f.add_argument('target', nargs='?', choices=FUZZ_TARGETS)
  529. f.add_argument('-t', '--seconds', type=int, default=300)
  530. f.add_argument('-j', '--jobs', type=int, default=4)
  531. sub.add_parser('list')
  532. options = parser.parse_args()
  533. if options.command == 'build':
  534. build(options.tool, options.jobs)
  535. elif options.command == 'run':
  536. command_run(options)
  537. elif options.command == 'swap':
  538. command_swap(options)
  539. elif options.command == 'fuzz':
  540. if options.action == 'build':
  541. fuzz_build(options.jobs)
  542. elif options.action == 'seeds':
  543. fuzz_seeds()
  544. elif options.target is None:
  545. sys.exit('fuzz run needs a target')
  546. else:
  547. fuzz_run(options)
  548. else:
  549. for name, (item, extra) in SCENARIOS.items():
  550. print(f'{name:14s} {item} {" ".join(extra)}')
  551. if __name__ == '__main__':
  552. main()