From f2223ad63bc9f60ed06e1791987c3623629dcda4 Mon Sep 17 00:00:00 2001 From: Edgar Aguilar Date: Mon, 30 Nov 2026 19:30:38 +0000 Subject: [PATCH] Add Windows libFuzzer -merge_inner process discovery and tree kill helpers --- .../bot/fuzzers/libFuzzer/merge_watchdog.py | 154 ++++++++++++++++++ .../fuzzers/libFuzzer/merge_watchdog_test.py | 58 +++++++ 2 files changed, 212 insertions(+) diff --git a/src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/merge_watchdog.py b/src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/merge_watchdog.py index a7c2fd99b1..b5d2852bdb 100644 --- a/src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/merge_watchdog.py +++ b/src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/merge_watchdog.py @@ -27,6 +27,8 @@ from collections.abc import Sequence import os +from typing import Any +from typing import NamedTuple try: import psutil @@ -34,12 +36,35 @@ psutil = None from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants +from clusterfuzz._internal.metrics import logs # Post-alarm headroom for DumpCurrentUnit, PrintStackTrace, and clean exit. STALL_GRACE_PERIOD_SEC = 30.0 # Floor for small -timeout values (e.g. 5s) so DLL load and MCF parsing finish. MIN_STALL_TIMEOUT_SEC = 60.0 +# Brief wait after kill() so the terminated -merge_inner exits before the next +# poll without blocking the watchdog thread on slow Windows handle teardown. +_KILL_WAIT_TIMEOUT_SEC = 1.0 +_WINDOWS_SHELL_NAMES = frozenset({'cmd.exe', 'cmd'}) + + +class _MergeInnerProcess(NamedTuple): + """Snapshot of an active libFuzzer -merge_inner descendant process. + + Attributes: + proc: Inspected psutil.Process handle preserving create_time PID-reuse + protection when calling kill(). + pid: Process ID of the matched -merge_inner process. + create_time: Process creation timestamp used as part of process identity. + control_file: Value of -merge_control_file from the process command line, + or None if absent. + """ + proc: Any + pid: int + create_time: float + control_file: str | None + def _parse_libfuzzer_flags(args: Sequence[str]) -> dict[str, str]: """Parses single-dash -flag=value arguments matching libFuzzer's parser. @@ -157,3 +182,132 @@ def _get_live_file_size(path: str) -> int | None: return handle.seek(0, os.SEEK_END) except OSError: return None + + +def _has_matched_ancestor(pid: int, pid_to_ppid: dict[int, int], + matched_pids: set[int]) -> bool: + """Checks whether any ancestor of a process is also a matched -merge_inner. + + Walks the parent chain recorded in pid_to_ppid while guarding against cycles + caused by transient OS PID reuse during process enumeration. + + Args: + pid: Process ID whose ancestor chain should be inspected. + pid_to_ppid: Mapping of child PID to parent PID from the current scan. + matched_pids: Set of PIDs matching a positive -merge_inner flag. + + Returns: + True if an ancestor of pid appears in matched_pids, False otherwise. + """ + seen = {pid} + parent_pid = pid_to_ppid.get(pid) + while parent_pid is not None and parent_pid not in seen: + if parent_pid in matched_pids: + return True + seen.add(parent_pid) + parent_pid = pid_to_ppid.get(parent_pid) + return False + + +def _find_merge_inner_process(root_proc: Any) -> _MergeInnerProcess | None: + """Finds the active top-most -merge_inner descendant of root_proc. + + Skips Windows cmd.exe shell intermediaries (which carry the full command line + via system()) and selects the highest matched ancestor so wrapper-launched + fuzzers are terminated as a unit rather than leaving the wrapper alive. When + multiple top-most matches exist, tie-breaks by oldest (create_time, pid). + + Args: + root_proc: psutil.Process for the outer libFuzzer MERGE-OUTER process. + + Returns: + The selected _MergeInnerProcess, or None if no active -merge_inner child + is running or descendants cannot be enumerated. + + Raises: + psutil.NoSuchProcess: If root_proc has already exited. + """ + assert psutil is not None + try: + children = root_proc.children(recursive=True) + except (psutil.AccessDenied, OSError): + return None + + pid_to_ppid: dict[int, int] = {} + matches: list[_MergeInnerProcess] = [] + for proc in children: + try: + pid_to_ppid[proc.pid] = proc.ppid() + if proc.name().lower() in _WINDOWS_SHELL_NAMES: + continue + cmdline = proc.cmdline() + if not cmdline: + continue + flags = _parse_libfuzzer_flags(cmdline[1:]) + # FuzzerMerge.cpp passes -merge_inner=1 for standard merge and + # -merge_inner=2 for set-cover merge; 0 disables inner mode. + if _parse_positive_int(flags.get(constants.MERGE_INNER_FLAGNAME)) is None: + continue + cf_path = flags.get(constants.MERGE_CONTROL_FILE_FLAGNAME) or None + matches.append( + _MergeInnerProcess(proc, proc.pid, proc.create_time(), cf_path)) + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess, + OSError): + continue + + if not matches: + return None + + matched_pids = {match.pid for match in matches} + top_matches = [ + match for match in matches + if not _has_matched_ancestor(match.pid, pid_to_ppid, matched_pids) + ] + return min(top_matches or matches, key=lambda m: (m.create_time, m.pid)) + + +def _kill_process_tree(proc: Any) -> bool: + """Terminates proc and all of its descendants bottom-up. + + Kills descendants in reverse discovery order before killing proc itself, + reusing the already-inspected psutil.Process handles so psutil enforces + create_time PID-reuse protection on every kill() call. + + Args: + proc: Inspected psutil.Process handle for the stalled -merge_inner process. + + Returns: + True if at least one live process in the tree was killed, False if proc had + already exited before termination began. + """ + assert psutil is not None + try: + children = proc.children(recursive=True) + except psutil.NoSuchProcess: + return False + except (psutil.AccessDenied, OSError) as err: + logs.warning( + f'Failed to enumerate children of merge_inner {proc.pid}: {err}') + children = [] + + killed = False + proc_killed = False + for target in (*reversed(children), proc): + try: + target.kill() + killed = True + if target is proc: + proc_killed = True + except psutil.NoSuchProcess: + continue + except (psutil.AccessDenied, OSError) as err: + logs.warning(f'Failed to kill merge_inner process {target.pid}: {err}') + + if proc_killed: + try: + proc.wait(timeout=_KILL_WAIT_TIMEOUT_SEC) + except (psutil.NoSuchProcess, psutil.TimeoutExpired, psutil.AccessDenied, + OSError): + pass + + return killed diff --git a/src/clusterfuzz/_internal/tests/core/bot/fuzzers/libFuzzer/merge_watchdog_test.py b/src/clusterfuzz/_internal/tests/core/bot/fuzzers/libFuzzer/merge_watchdog_test.py index 5b3dded2ad..f2b50d6bb6 100644 --- a/src/clusterfuzz/_internal/tests/core/bot/fuzzers/libFuzzer/merge_watchdog_test.py +++ b/src/clusterfuzz/_internal/tests/core/bot/fuzzers/libFuzzer/merge_watchdog_test.py @@ -14,10 +14,32 @@ """Tests for Windows libFuzzer merge watchdog.""" import unittest +from unittest import mock from clusterfuzz._internal.bot.fuzzers.libFuzzer import merge_watchdog +def _make_fake_proc( + pid: int, + cmdline: list[str], + name: str = 'fuzzer.exe', + ppid: int = 100, + create_time: float = 1000.0, + children: list[mock.MagicMock] | None = None, + is_running: bool = True, +) -> mock.MagicMock: + """Builds a fake psutil.Process for deterministic watchdog unit tests.""" + proc = mock.MagicMock() + proc.pid = pid + proc.ppid.return_value = ppid + proc.name.return_value = name + proc.cmdline.return_value = cmdline + proc.create_time.return_value = create_time + proc.children.return_value = list(children or []) + proc.is_running.return_value = is_running + return proc + + class MergeWatchdogTest(unittest.TestCase): """Tests for merge_watchdog helpers and WindowsMergeWatchdog.""" @@ -48,6 +70,42 @@ def test_parse_libfuzzer_flags_and_stall_timeout(self) -> None: for invalid in (None, 'abc', '0', '-5'): self.assertIsNone(merge_watchdog._parse_positive_int(invalid)) + def test_find_merge_inner_process_selection(self) -> None: + """Skips cmd.exe, picks top-most matched wrapper, and tie-breaks oldest.""" + cmd_proc = _make_fake_proc( + 200, ['cmd.exe', '/c', 'fuzzer.exe', '-merge_inner=1'], + name='cmd.exe', + ppid=100) + wrapper = _make_fake_proc( + 300, + ['wrapper.exe', '-merge_inner=1', '-merge_control_file=C:\\mcf.txt'], + name='wrapper.exe', + ppid=200, + create_time=10.0) + helper = _make_fake_proc(301, ['helper.exe'], name='helper.exe', ppid=300) + # Earlier create_time than wrapper so ancestor filtering is required. + real_inner = _make_fake_proc( + 302, + ['fuzzer.exe', '-merge_inner=1', '-merge_control_file=C:\\other.txt'], + ppid=301, + create_time=9.0) + zero_inner = _make_fake_proc( + 303, ['fuzzer.exe', '-merge_inner=0'], ppid=100, create_time=1.0) + sibling = _make_fake_proc( + 304, ['fuzzer.exe', '-merge_inner=2', '-merge_control_file=C:\\s.txt'], + ppid=200, + create_time=12.0) + + root = _make_fake_proc( + 100, ['outer.exe', '-merge=1'], + children=[cmd_proc, sibling, real_inner, helper, wrapper, zero_inner]) + match = merge_watchdog._find_merge_inner_process(root) + self.assertIsNotNone(match) + assert match is not None + self.assertIs(match.proc, wrapper) + self.assertEqual((match.pid, match.create_time), (300, 10.0)) + self.assertEqual(match.control_file, 'C:\\mcf.txt') + if __name__ == '__main__': unittest.main()