runtime_analysis.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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|helgrind|drd|callgrind [-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. if tool in ('helgrind', 'drd'):
  206. return ['valgrind', f'--tool={tool}', '--num-callers=30', '--error-limit=no', f'--log-file={out / (tool + ".%p")}',
  207. f'--suppressions={SUPP / "valgrind.supp"}']
  208. if tool == 'callgrind':
  209. return ['valgrind', '--tool=callgrind', f'--callgrind-out-file={out / "callgrind.%p"}', '--dump-instr=no']
  210. return []
  211. class Run:
  212. def __init__(self, tool, binary_dir, out, args, web=False, rss_limit=8192, min_available=6144):
  213. self.tool, self.out = tool, out
  214. out.mkdir(parents=True, exist_ok=True)
  215. scratch = Path(tempfile.mkdtemp(prefix='lwe-rt-'))
  216. self.scratch = scratch
  217. self.runtime = scratch / 'run'
  218. self.runtime.mkdir(mode=0o700)
  219. shim = scratch / 'dbus_noop_shim.so'
  220. subprocess.run(['gcc', '-shared', '-fPIC', '-o', str(shim), str(SHIM_SRC), '-ldl'], check=True)
  221. nocore = scratch / 'nocore.so'
  222. subprocess.run(['gcc', '-shared', '-fPIC', '-o', str(nocore), str(NOCORE_SRC)], check=True)
  223. # test processes must not carry the engine's name, we_manager's shutdown pkill -f matches it
  224. link = scratch / 'lwk'
  225. link.symlink_to((binary_dir / 'linux-wallpaperengine').resolve())
  226. self.bus = start_bus(self.runtime)
  227. self.xvfb = None
  228. env = {k: v for k, v in os.environ.items() if k not in (
  229. 'WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'KDE_FULL_SESSION', 'KDE_SESSION_VERSION', 'DESKTOP_SESSION',
  230. 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_DESKTOP', 'DISPLAY', 'PULSE_SERVER', 'PIPEWIRE_REMOTE')}
  231. env.update({
  232. 'XDG_RUNTIME_DIR': str(self.runtime),
  233. 'DBUS_SESSION_BUS_ADDRESS': f'unix:path={self.runtime}/bus',
  234. 'DBUS_SYSTEM_BUS_ADDRESS': 'unix:path=/nonexistent-system-bus',
  235. 'PULSE_SERVER': 'unix:/nonexistent-pulse',
  236. 'PIPEWIRE_REMOTE': '/nonexistent-pipewire',
  237. 'ALSA_CONFIG_PATH': '/dev/null',
  238. 'SDL_AUDIODRIVER': 'dummy',
  239. 'XDG_SESSION_TYPE': 'headless',
  240. 'XDG_CACHE_HOME': str(scratch / 'cache'),
  241. 'LD_LIBRARY_PATH': str(binary_dir) + (f':{SANITIZER_LIBS}' if SANITIZER_LIBS.is_dir() else ''),
  242. # the host's core_pattern pipes to a crash handler that runs whatever RLIMIT_CORE says: a crash exits here instead
  243. 'LD_PRELOAD': f'{shim}:{nocore}' if tool not in SANITIZER_TOOLS else str(shim),
  244. 'LWE_FRAME_STATS': '1',
  245. })
  246. if web:
  247. display = free_display()
  248. self.xvfb = subprocess.Popen(['Xvfb', f':{display}', '-screen', '0', '1920x1080x24', '-nolisten', 'tcp'],
  249. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  250. time.sleep(1)
  251. env.update({
  252. 'DISPLAY': f':{display}', 'LWE_CEF_NO_SANDBOX': '1',
  253. 'LWE_WEB_HOST_PRELOAD': str(binary_dir / 'libcef.so'),
  254. 'LWE_CEF_SWITCHES': '--ozone-platform=headless --use-gl=angle --use-angle=gl-egl '
  255. '--ignore-gpu-blocklist --disable-dev-shm-usage',
  256. })
  257. env.update(sanitizer_env(tool, out))
  258. self.log = out / 'engine.log'
  259. self.control = scratch / 'control'
  260. command = [*wrapper(tool, out), str(link), '--window', '0x0x1280x720', '--silent', '--assets-dir', str(ASSETS),
  261. '--control-file', str(self.control), *args]
  262. self.logfile = open(self.log, 'wb')
  263. self.started = time.time()
  264. self.proc = subprocess.Popen(command, env=env, stdin=subprocess.DEVNULL, stdout=self.logfile,
  265. stderr=subprocess.STDOUT, preexec_fn=self.child_setup)
  266. self.watchdog = Watchdog(self.proc.pid, rss_limit, min_available, self.log)
  267. self.watchdog.start()
  268. @staticmethod
  269. def child_setup():
  270. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  271. os.setsid()
  272. def alive(self):
  273. return self.proc.poll() is None
  274. def engine_pid(self):
  275. # behind a wrapper script the engine is a child of the process this class started
  276. for entry in Path('/proc').iterdir():
  277. if not entry.name.isdigit():
  278. continue
  279. try:
  280. stat = (entry / 'stat').read_text()
  281. if int(stat[stat.rindex(')') + 2:].split()[3]) != self.proc.pid:
  282. continue
  283. if (entry / 'exe').resolve().name == 'linux-wallpaperengine' \
  284. and b'--web-host' not in (entry / 'cmdline').read_bytes():
  285. return int(entry.name)
  286. except (OSError, ValueError):
  287. continue
  288. return self.proc.pid
  289. def hotswap(self, text):
  290. self.control.write_text(text)
  291. os.kill(self.engine_pid() if self.tool == 'heaptrack' else self.proc.pid, signal.SIGUSR1)
  292. def finish(self, grace=120):
  293. if self.alive():
  294. # the wrappers (heaptrack, valgrind) have to pass it on, so the whole group gets it
  295. os.killpg(self.proc.pid, signal.SIGTERM)
  296. try:
  297. self.proc.wait(grace)
  298. except subprocess.TimeoutExpired:
  299. os.killpg(self.proc.pid, signal.SIGKILL)
  300. self.proc.wait()
  301. try:
  302. os.killpg(self.proc.pid, signal.SIGKILL)
  303. except ProcessLookupError:
  304. pass
  305. self.watchdog.stop_flag.set()
  306. self.logfile.close()
  307. self.bus.kill()
  308. self.bus.wait(5)
  309. if self.xvfb:
  310. self.xvfb.kill()
  311. self.xvfb.wait(5)
  312. shutil.rmtree(self.scratch, ignore_errors=True)
  313. return self.proc.returncode
  314. REPORT_MARKERS = {
  315. 'asan': [('AddressSanitizer', 'ERROR: AddressSanitizer'), ('LeakSanitizer', 'ERROR: LeakSanitizer'),
  316. ('UBSan', 'runtime error:')],
  317. 'tsan': [('races', 'WARNING: ThreadSanitizer: data race'), ('other', 'WARNING: ThreadSanitizer'),
  318. ('deadlock', 'lock-order-inversion')],
  319. 'memcheck': [('invalid', 'Invalid '), ('uninit', 'uninitialised'), ('leaks', 'definitely lost')],
  320. 'helgrind': [('races', 'Possible data race'), ('lock-order', 'lock order'), ('misuse', 'Thread #')],
  321. 'drd': [('races', 'Conflicting'), ('lock-order', 'lock order'), ('misuse', 'Thread #')],
  322. }
  323. def rss_growth(samples):
  324. # RSS of the process group over the last 70% of the run (the first 30% is loading), in MB per minute
  325. if len(samples) < 20:
  326. return None
  327. steady = samples[len(samples) * 3 // 10:]
  328. n = len(steady)
  329. mean_t = sum(t for t, _ in steady) / n
  330. mean_r = sum(r for _, r in steady) / n
  331. spread = sum((t - mean_t) ** 2 for t, _ in steady)
  332. return 60 * sum((t - mean_t) * (r - mean_r) for t, r in steady) / spread if spread else 0.0
  333. def summarize(tool, out, run, code):
  334. text = run.log.read_text(errors='replace')
  335. reports = ''
  336. for path in sorted(out.glob(f'{tool}*')) + sorted(out.glob('memcheck.*')):
  337. if path.is_file():
  338. reports += path.read_text(errors='replace')
  339. counts = []
  340. for label, marker in REPORT_MARKERS.get(tool, []):
  341. counts.append(f'{label}={(reports + text).count(marker)}')
  342. stats = len(re.findall(r'FRAME-STATS', text))
  343. growth = rss_growth(run.watchdog.samples)
  344. parts = [f'exit={code}', f'peak={run.watchdog.peak}MB',
  345. f'growth={growth:+.1f}MB/min' if growth is not None else 'growth=n/a', f'stats-windows={stats}', *counts]
  346. if run.watchdog.killed:
  347. parts.append(f'WATCHDOG({run.watchdog.killed})')
  348. if tool == 'heaptrack':
  349. dumps = sorted(out.glob('heaptrack*.zst')) + sorted(out.glob('heaptrack*.gz'))
  350. if dumps:
  351. summary = subprocess.run(['heaptrack_print', '-n', '25', str(dumps[-1])], capture_output=True, text=True)
  352. (out / 'heaptrack_summary.txt').write_text(summary.stdout)
  353. leaks = subprocess.run(['heaptrack_print', '-l', '-n', '25', '-s', '12', str(dumps[-1])],
  354. capture_output=True, text=True)
  355. (out / 'heaptrack_leaks.txt').write_text(leaks.stdout[leaks.stdout.find('MEMORY LEAKS'):])
  356. peak = re.search(r'peak heap memory consumption: (\S+)', summary.stdout)
  357. leaked = re.search(r'total memory leaked: (\S+)', summary.stdout)
  358. parts += [f'heap-peak={peak.group(1) if peak else "?"}', f'leaked={leaked.group(1) if leaked else "?"}']
  359. return ' '.join(parts)
  360. def run_scenario(tool, name, args, seconds, web, out_root, rss_limit, min_available):
  361. binary_dir = build_dir(tool if tool in SANITIZER_TOOLS else 'plain')
  362. out = out_root / name
  363. if out.exists():
  364. shutil.rmtree(out)
  365. run = Run(tool, binary_dir, out, args, web, rss_limit, min_available)
  366. end = time.time() + seconds
  367. while time.time() < end and run.alive():
  368. time.sleep(0.5)
  369. code = run.finish()
  370. return summarize(tool, out, run, code)
  371. def command_run(options):
  372. if options.tool in SANITIZER_TOOLS and not (build_dir(options.tool) / 'linux-wallpaperengine').exists():
  373. sys.exit(f'{build_dir(options.tool).parent} is not built, run: runtime_analysis.py build {options.tool}')
  374. out_root = Path(options.out) if options.out else ROOT / 'build' / 'runtime-analysis' / options.tool
  375. out_root.mkdir(parents=True, exist_ok=True)
  376. names = options.scenario or list(SCENARIOS)
  377. lines = []
  378. for name in names:
  379. item, extra = SCENARIOS[name]
  380. path = WORKSHOP / item
  381. if not path.is_dir():
  382. lines.append(f'{name}: SKIP, {item} not in {WORKSHOP}')
  383. continue
  384. web = name == 'web'
  385. seconds = options.seconds * (3 if options.tool in ('memcheck', 'massif', 'helgrind', 'drd', 'callgrind') else 1)
  386. print(f'== {name} ({item}) {options.tool} {seconds}s', flush=True)
  387. line = f'{name}: ' + run_scenario(options.tool, name, [*extra, str(path)], seconds, web, out_root,
  388. options.rss_limit, options.min_available)
  389. print(line, flush=True)
  390. lines.append(line)
  391. (out_root / 'summary.txt').write_text('\n'.join(lines) + '\n')
  392. def command_swap(options):
  393. out_root = Path(options.out) if options.out else ROOT / 'build' / 'runtime-analysis' / options.tool
  394. out = out_root / 'swap'
  395. binary_dir = build_dir(options.tool if options.tool in SANITIZER_TOOLS else 'plain')
  396. items = [WORKSHOP / item for item in SWAP_ITEMS if (WORKSHOP / item).is_dir()]
  397. if len(items) < 2:
  398. sys.exit('need at least two of the swap wallpapers installed')
  399. if out.exists():
  400. shutil.rmtree(out)
  401. run = Run(options.tool, binary_dir, out, [str(items[0])], False, options.rss_limit, options.min_available)
  402. time.sleep(options.wait)
  403. swaps = 0
  404. snapshots = []
  405. for round_number in range(options.rounds):
  406. for item in items:
  407. if not run.alive():
  408. break
  409. run.hotswap(f'path={item}\n')
  410. swaps += 1
  411. time.sleep(options.wait)
  412. print(f'round {round_number + 1}: rss {group_rss_mb(run.proc.pid)} MB, alive={run.alive()}', flush=True)
  413. snapshots.append(mapping_rss_kb(run.proc.pid))
  414. print_mapping_growth(snapshots)
  415. code = run.finish()
  416. failed = run.log.read_text(errors='replace').count('Hotswap failed')
  417. line = f'swap: swaps={swaps} failed-swaps={failed} ' + summarize(options.tool, out, run, code)
  418. print(line)
  419. (out_root / 'summary.txt').write_text(line + '\n')
  420. FUZZ_DIR = ROOT / 'build-fuzz'
  421. FUZZ_TARGETS = ['texture', 'package', 'mdl', 'sog', 'json']
  422. FUZZ_SOURCES = ['Data/*.cpp', 'Data/Builders/*.cpp', 'Data/Model/*.cpp', 'Data/Parsers/*.cpp', 'Data/Utils/*.cpp',
  423. 'Assets/*.cpp', 'FileSystem/*.cpp', 'FileSystem/Adapters/*.cpp', 'Logging/*.cpp', 'Maths.cpp',
  424. 'Render/Objects/Puppet*.cpp', 'Render/Objects/CMesh.cpp', 'Splat/SogLoader.cpp']
  425. FUZZ_LIBS = ['-llz4', '-lavcodec', '-lavutil', '-lavformat', '-lswscale', '-lswresample', '-lpng', '-lfreetype',
  426. '-lharfbuzz', '-lGLEW', '-lGL']
  427. FUZZ_FLAGS = ['-std=gnu++20', '-O1', '-g1', '-fno-omit-frame-pointer', '-fno-sanitize=vptr', '-Wno-narrowing', '-w']
  428. # MemorySanitizer needs every library the parsers touch instrumented: libc++ from the LLVM sources
  429. # (-DLLVM_USE_SANITIZER=MemoryWithOrigins, runtimes build) and lz4, zlib and libpng built with -fsanitize=memory; the
  430. # targets are linked without freetype and GL, so a parser path that reaches them is a null call. The system's FFmpeg
  431. # libraries pull in libaribcaption, whose static initializer MSan reports, so sog gets its own FFmpeg built from source
  432. # with -fsanitize=memory and only the WebP and VP8 decoders (swscale for the conversion): configure with
  433. # --disable-everything --enable-decoder=webp,vp8 --enable-parser=webp,vp8 --enable-swscale --disable-asm
  434. # --disable-avformat --disable-shared and the sanitizer in --extra-cflags/--extra-ldflags
  435. MSAN_LIBCXX = Path(os.environ.get('LWE_MSAN_LIBCXX', Path.home() / '.local/share/msan-libcxx/install'))
  436. MSAN_DEPS = Path(os.environ.get('LWE_MSAN_DEPS', Path.home() / '.local/share/msan-deps/install'))
  437. MSAN_FFMPEG = Path(os.environ.get('LWE_MSAN_FFMPEG', Path.home() / '.local/share/msan-ffmpeg/install'))
  438. MSAN_TARGETS = ['texture', 'package', 'mdl', 'json', 'sog']
  439. def fuzz_compile_flags():
  440. import json
  441. import shlex
  442. for entry in json.loads((ROOT / 'build' / 'compile_commands.json').read_text()):
  443. if entry['file'].endswith('Parsers/TextureParser.cpp'):
  444. words = shlex.split(entry['command'])
  445. flags, i = [], 1
  446. while i < len(words):
  447. if words[i].startswith(('-I', '-D')):
  448. flags.append(words[i])
  449. elif words[i] == '-isystem':
  450. flags += ['-isystem', words[i + 1]]
  451. i += 1
  452. i += 1
  453. return flags
  454. sys.exit('build/compile_commands.json has no TextureParser.cpp, configure build/ first')
  455. def fuzz_build(jobs, msan=False):
  456. import concurrent.futures
  457. if msan:
  458. sanitizers = 'memory'
  459. compile_extra = ['-fsanitize-memory-track-origins=2', '-stdlib=libc++', '-nostdinc++',
  460. f'-isystem{MSAN_LIBCXX / "include/c++/v1"}', f'-I{MSAN_DEPS / "include"}', f'-I{MSAN_FFMPEG / "include"}']
  461. libs = [str(MSAN_DEPS / 'lib/liblz4.a'), str(MSAN_DEPS / 'lib64/libpng16.a'), str(MSAN_DEPS / 'lib/libz.a'),
  462. *(str(MSAN_FFMPEG / 'lib' / name) for name in ('libswscale.a', 'libavcodec.a', 'libswresample.a', 'libavutil.a'))]
  463. link_extra = ['-stdlib=libc++', '-nostdlib++', str(MSAN_LIBCXX / 'lib/libc++.a'),
  464. str(MSAN_LIBCXX / 'lib/libc++abi.a'), '-lpthread']
  465. targets = MSAN_TARGETS
  466. else:
  467. sanitizers = 'address,undefined'
  468. compile_extra, link_extra, libs, targets = [], [], FUZZ_LIBS, FUZZ_TARGETS
  469. objects = FUZZ_DIR / 'obj'
  470. objects.mkdir(parents=True, exist_ok=True)
  471. flags = fuzz_compile_flags()
  472. sources = sorted(path for pattern in FUZZ_SOURCES for path in (ROOT / 'src' / 'WallpaperEngine').glob(pattern))
  473. def compile_one(source):
  474. target = objects / (str(source.relative_to(ROOT)).replace('/', '_') + '.o')
  475. if target.exists() and target.stat().st_mtime > source.stat().st_mtime:
  476. return target
  477. subprocess.run(['clang++', *FUZZ_FLAGS, f'-fsanitize=fuzzer-no-link,{sanitizers}', '-fPIC', *compile_extra, *flags,
  478. '-c', str(source), '-o', str(target)], check=True)
  479. return target
  480. with concurrent.futures.ThreadPoolExecutor(jobs) as pool:
  481. objs = list(pool.map(compile_one, sources))
  482. globals_file = FUZZ_DIR / 'globals.cpp'
  483. globals_file.write_text('float g_Time;\nfloat g_TimeLast;\n')
  484. for name in targets:
  485. subprocess.run(['clang++', *FUZZ_FLAGS, f'-fsanitize=fuzzer,{sanitizers}', *compile_extra, *flags,
  486. str(ROOT / 'tools' / 'fuzz' / f'{name}.cpp'), str(globals_file), *map(str, objs),
  487. '-o', str(FUZZ_DIR / name), '-Wl,--unresolved-symbols=ignore-all', *link_extra, *libs], check=True)
  488. print(f'built {FUZZ_DIR / name}')
  489. def fuzz_seeds():
  490. sys.path.insert(0, str(ROOT / 'tools'))
  491. import struct
  492. def sized(f):
  493. return f.read(struct.unpack('<I', f.read(4))[0])
  494. corpus = FUZZ_DIR / 'corpus'
  495. for name in FUZZ_TARGETS:
  496. (corpus / name).mkdir(parents=True, exist_ok=True)
  497. counts = dict.fromkeys(FUZZ_TARGETS, 0)
  498. def add(name, data, label):
  499. if 0 < len(data) <= 1_000_000:
  500. (corpus / name / label).write_bytes(data)
  501. counts[name] += 1
  502. for pkg in sorted(WORKSHOP.glob('*/*.pkg')):
  503. item = pkg.parent.name
  504. with open(pkg, 'rb') as f:
  505. try:
  506. sized(f)
  507. entries = [(sized(f).decode('utf-8', 'replace'), *struct.unpack('<II', f.read(8)))
  508. for _ in range(struct.unpack('<I', f.read(4))[0])]
  509. except (struct.error, ValueError):
  510. continue
  511. base = f.tell()
  512. add('package', pkg.read_bytes()[:base + 64], f'{item}_{pkg.stem}_head')
  513. for entry, offset, length in entries:
  514. kind = {'.tex': 'texture', '.mdl': 'mdl', '.json': 'json'}.get(Path(entry).suffix)
  515. if kind and counts[kind] < (1500 if kind == 'json' else 400) and (kind != 'json' or length < 60_000):
  516. f.seek(base + offset)
  517. add(kind, f.read(length), f'{item}_{entry.replace("/", "_")}')
  518. for project in sorted(WORKSHOP.glob('*/project.json')):
  519. add('json', project.read_bytes(), f'{project.parent.name}_project.json')
  520. for meta in sorted(WORKSHOP.glob('*/imgs/*/meta.json'))[:3]:
  521. image = min(meta.parent.glob('*.webp'), key=lambda path: path.stat().st_size, default=None)
  522. if image is not None:
  523. text = meta.read_bytes()
  524. add('sog', struct.pack('<H', len(text)) + text + image.read_bytes(), f'{meta.parent.parent.parent.name}_{meta.parent.name}')
  525. print(', '.join(f'{name}: {count}' for name, count in counts.items()))
  526. def fuzz_run(options):
  527. binary = FUZZ_DIR / options.target
  528. crashes = FUZZ_DIR / 'crashes' / options.target
  529. crashes.mkdir(parents=True, exist_ok=True)
  530. corpus = ROOT / 'build-fuzz' / 'corpus' / options.target if options.msan else FUZZ_DIR / 'corpus' / options.target
  531. work = FUZZ_DIR / 'work' / options.target
  532. work.mkdir(parents=True, exist_ok=True)
  533. env = {**os.environ, 'ASAN_OPTIONS': 'allocator_may_return_null=1:detect_leaks=1:max_allocation_size_mb=2048',
  534. 'UBSAN_OPTIONS': f'print_stacktrace=1:suppressions={SUPP / "ubsan.supp"}',
  535. 'MSAN_OPTIONS': 'print_stats=0:halt_on_error=1:abort_on_error=0:handle_abort=1'}
  536. subprocess.run([str(binary), str(work), str(corpus), f'-max_total_time={options.seconds}', '-max_len=1000000',
  537. '-rss_limit_mb=3000', '-timeout=20', f'-artifact_prefix={crashes}/', f'-jobs={options.jobs}',
  538. f'-workers={options.jobs}', '-print_final_stats=1'], env=env, cwd=work)
  539. def main():
  540. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  541. sub = parser.add_subparsers(dest='command', required=True)
  542. b = sub.add_parser('build')
  543. b.add_argument('tool', choices=BUILDS)
  544. b.add_argument('-j', '--jobs', type=int, default=8)
  545. for name in ('run', 'swap'):
  546. r = sub.add_parser(name)
  547. r.add_argument('tool', choices=['plain', 'asan', 'tsan', 'heaptrack', 'memcheck', 'massif', 'helgrind', 'drd', 'callgrind'])
  548. r.add_argument('-o', '--out')
  549. r.add_argument('--rss-limit', type=int, default=8192, help='MB for the whole process group')
  550. r.add_argument('--min-available', type=int, default=6144, help='MB of MemAvailable below which the run is killed')
  551. if name == 'run':
  552. r.add_argument('-s', '--scenario', action='append', choices=list(SCENARIOS))
  553. r.add_argument('-t', '--seconds', type=int, default=40)
  554. else:
  555. r.add_argument('-r', '--rounds', type=int, default=3)
  556. r.add_argument('-w', '--wait', type=float, default=8, help='seconds to let each wallpaper run')
  557. f = sub.add_parser('fuzz')
  558. f.add_argument('action', choices=['build', 'seeds', 'run'])
  559. f.add_argument('target', nargs='?', choices=FUZZ_TARGETS)
  560. f.add_argument('--msan', action='store_true', help=f'MemorySanitizer build in build-fuzz-msan ({", ".join(MSAN_TARGETS)}), '
  561. 'corpus from build-fuzz')
  562. f.add_argument('-t', '--seconds', type=int, default=300)
  563. f.add_argument('-j', '--jobs', type=int, default=4)
  564. sub.add_parser('list')
  565. options = parser.parse_args()
  566. if options.command == 'build':
  567. build(options.tool, options.jobs)
  568. elif options.command == 'run':
  569. command_run(options)
  570. elif options.command == 'swap':
  571. command_swap(options)
  572. elif options.command == 'fuzz':
  573. if options.msan:
  574. global FUZZ_DIR
  575. FUZZ_DIR = ROOT / 'build-fuzz-msan'
  576. if options.action == 'build':
  577. fuzz_build(options.jobs, options.msan)
  578. elif options.action == 'seeds':
  579. fuzz_seeds()
  580. elif options.target is None:
  581. sys.exit('fuzz run needs a target')
  582. else:
  583. fuzz_run(options)
  584. else:
  585. for name, (item, extra) in SCENARIOS.items():
  586. print(f'{name:14s} {item} {" ".join(extra)}')
  587. if __name__ == '__main__':
  588. main()