Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/merge_watchdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,42 @@

from collections.abc import Sequence
import os
from typing import Any
from typing import NamedTuple

try:
import psutil
except ImportError:
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

_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 FuzzerDriver.cpp.
Expand Down Expand Up @@ -152,3 +175,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
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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()
Loading