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
204 changes: 204 additions & 0 deletions src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/merge_watchdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@
can skip the stalled input and continue with the next attempt.
"""

from collections.abc import Callable
from collections.abc import Sequence
import os
import threading
import time
from typing import Any
from typing import NamedTuple

Expand All @@ -38,12 +41,20 @@
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.metrics import logs

DEFAULT_POLL_INTERVAL_SEC = 2.0
# 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
# Stop intervening after this many consecutive kills with no MCF byte growth.
# A cold-start binary or large control-file load can exceed the 60s floor once
# before the OS page cache warms, so stopping at 1 would give up too early.
# Allowing 3 gives two retries (~3 min max overhead at the 60s floor) while
# bounding a permanently stuck initializer so MERGE-OUTER does not loop forever.
MAX_CONSECUTIVE_NO_PROGRESS_KILLS = 3

_KILL_WAIT_TIMEOUT_SEC = 1.0
_STOP_JOIN_TIMEOUT_SEC = 5.0
_WINDOWS_SHELL_NAMES = frozenset({'cmd.exe', 'cmd'})


Expand Down Expand Up @@ -304,3 +315,196 @@ def _kill_process_tree(proc: Any) -> bool:
pass

return killed


class WindowsMergeWatchdog:
"""Context manager that reaps stalled Windows libFuzzer -merge_inner children.

While entered, a daemon thread polls the outer MERGE-OUTER process tree every
DEFAULT_POLL_INTERVAL_SEC seconds. For each active -merge_inner child, it
tracks live byte growth of the merge control file (MCF). If the file stops
growing for compute_stall_timeout(unit_timeout) seconds, the watchdog kills
only that -merge_inner process tree so MERGE-OUTER can advance past the
stalled input. A 3-kill circuit breaker stops the watchdog if repeated kills
never produce new MCF bytes.
"""

def __init__(
self,
root_pid: int,
unit_timeout: int,
fallback_control_file: str | None = None,
cwd: str | None = None,
clock: Callable[[], float] = time.monotonic,
) -> None:
"""Initializes the merge watchdog for a single outer libFuzzer merge run.

Args:
root_pid: PID of the outer libFuzzer MERGE-OUTER process.
unit_timeout: Positive per-unit libFuzzer -timeout value in seconds.
fallback_control_file: Outer -merge_control_file path to use if the inner
child command line omits the flag, or None.
cwd: Working directory of the merge process used to resolve relative
control-file paths, or None.
clock: Monotonic clock callable returning seconds (injectable for tests).
"""
self._root_pid = root_pid
self._fallback_control_file = fallback_control_file or None
self._cwd = cwd or None
self._stall_timeout = compute_stall_timeout(unit_timeout)
self._clock = clock
self._stop_event = threading.Event()
self._thread: threading.Thread | None = None
self._root_proc: Any = None
self._tracked_identity: tuple[int, float] | None = None
self._last_cf_size: int | None = None
self._last_progress_time = 0.0
self._last_killed_cf_size: int | None = None
self._consecutive_no_progress_kills = 0

def __enter__(self) -> 'WindowsMergeWatchdog':
"""Starts the background watchdog thread if psutil and root_pid are live.

Returns:
This WindowsMergeWatchdog instance.
"""
if psutil is None:
return self
try:
self._root_proc = psutil.Process(self._root_pid)
except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
self._root_proc = None
return self

self._thread = threading.Thread(
target=self._run, name='windows-merge-watchdog', daemon=True)
self._thread.start()
return self

def __exit__(self, unused_exc_type: Any, unused_exc_val: Any,
unused_exc_tb: Any) -> None:
"""Signals the background thread to stop and waits briefly for exit."""
self._stop_event.set()
if self._thread is not None:
self._thread.join(timeout=_STOP_JOIN_TIMEOUT_SEC)
self._thread = None

def _is_root_alive(self) -> bool:
"""Returns True if the outer MERGE-OUTER process is still running."""
assert psutil is not None
if self._root_proc is None:
return False
try:
return bool(self._root_proc.is_running())
except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
return False

def _reset_tracked_inner(self) -> None:
"""Clears tracking state for the currently observed -merge_inner process."""
self._tracked_identity = None
self._last_cf_size = None
self._last_progress_time = 0.0

def _run(self) -> None:
"""Polls until stopped, the root exits, or _poll_once returns False."""
while not self._stop_event.wait(DEFAULT_POLL_INTERVAL_SEC):
try:
if not self._poll_once():
break
except Exception: # pylint: disable=broad-except
logs.error('Unexpected error in Windows libFuzzer merge watchdog.')
break

def _poll_once(self) -> bool:
"""Runs a single poll cycle against the outer merge process tree.

Inspects the active -merge_inner descendant, checks live MCF byte growth,
reaps the inner tree if stalled past _stall_timeout, and updates the
consecutive no-progress kill circuit breaker. Missing or temporarily
unreadable control files are treated as fail-safe (never killed).

Returns:
True to continue polling, or False to stop the watchdog thread (when
stopped, the outer process exited, or the circuit breaker tripped).
"""
assert psutil is not None
if self._stop_event.is_set() or self._root_proc is None:
return False

try:
inner = _find_merge_inner_process(self._root_proc)
except psutil.NoSuchProcess:
return False

if inner is None:
self._reset_tracked_inner()
return True

identity = (inner.pid, inner.create_time)
cf_path = inner.control_file or self._fallback_control_file
if cf_path and self._cwd and not os.path.isabs(cf_path):
cf_path = os.path.join(self._cwd, cf_path)
now = self._clock()

if identity != self._tracked_identity:
self._tracked_identity = identity
self._last_cf_size = None
if not cf_path:
logs.warning(
f'Windows merge watchdog could not find merge control file for '
f'merge_inner pid {inner.pid}.')

if not cf_path:
return True

cf_size = _get_live_file_size(cf_path)
if cf_size is None:
return True

if self._last_cf_size is None:
self._last_cf_size = cf_size
self._last_progress_time = now
return True

if cf_size > self._last_cf_size:
self._last_cf_size = cf_size
self._last_progress_time = now
self._last_killed_cf_size = None
self._consecutive_no_progress_kills = 0
return True

stalled_for = now - self._last_progress_time
if stalled_for < self._stall_timeout:
return True

if self._stop_event.is_set() or not self._is_root_alive():
return False

if not _kill_process_tree(inner.proc):
self._reset_tracked_inner()
return True

if (self._last_killed_cf_size is not None and
cf_size <= self._last_killed_cf_size):
self._consecutive_no_progress_kills += 1
else:
self._last_killed_cf_size = cf_size
self._consecutive_no_progress_kills = 1

self._last_progress_time = now
logs.warning(
f'Reaped stalled Windows libFuzzer merge_inner pid {inner.pid} after '
f'{stalled_for:.1f}s without merge control file growth '
f'(threshold={self._stall_timeout:.1f}s, cf={cf_path}, '
f'size={cf_size}, no_progress_kills='
f'{self._consecutive_no_progress_kills}).')

if (self._consecutive_no_progress_kills >=
MAX_CONSECUTIVE_NO_PROGRESS_KILLS):
logs.warning(
f'Stopping Windows merge watchdog after '
f'{self._consecutive_no_progress_kills} consecutive kills without '
f'control file progress at {cf_size} bytes.')
return False

return True
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,16 @@
# limitations under the License.
"""Tests for Windows libFuzzer merge watchdog."""

import os
import shutil
import tempfile
import unittest
from unittest import mock

import psutil

from clusterfuzz._internal.bot.fuzzers.libFuzzer import merge_watchdog
from clusterfuzz._internal.tests.test_libs import helpers as test_helpers


def _make_fake_proc(
Expand Down Expand Up @@ -45,6 +51,13 @@ class MergeWatchdogTest(unittest.TestCase):

# pylint: disable=protected-access

def setUp(self) -> None:
test_helpers.patch_environ(self)
self.temp_dir = tempfile.mkdtemp()

def tearDown(self) -> None:
shutil.rmtree(self.temp_dir, ignore_errors=True)

def test_parse_libfuzzer_flags_and_stall_timeout(self) -> None:
"""Flag parsing matches FuzzerDriver.cpp and stall timeout applies floor."""
flags = merge_watchdog._parse_libfuzzer_flags([
Expand Down Expand Up @@ -106,6 +119,136 @@ def test_find_merge_inner_process_selection(self) -> None:
self.assertEqual((match.pid, match.create_time), (300, 10.0))
self.assertEqual(match.control_file, 'C:\\mcf.txt')

def test_progress_resets_stall_timer_and_reaps_on_stall(self) -> None:
"""Live EOF growth resets timer; stall kills children bottom-up then proc."""
cf_path = os.path.join(self.temp_dir, 'mcf.txt')
events: list[str] = []
grandchild = _make_fake_proc(401, ['helper.exe'], ppid=300)
grandchild.kill.side_effect = lambda: events.append('kill:401')
# Pass a relative -merge_control_file to verify resolution against cwd.
inner = _make_fake_proc(
300, ['fuzzer.exe', '-merge_inner=1', '-merge_control_file=mcf.txt'],
children=[grandchild])
inner.kill.side_effect = lambda: events.append('kill:300')
inner.wait.side_effect = lambda timeout=None: events.append('wait:300')
root = _make_fake_proc(100, ['outer.exe', '-merge=1'], children=[inner])

now = [0.0]
watchdog = merge_watchdog.WindowsMergeWatchdog(
100, unit_timeout=5, cwd=self.temp_dir, clock=lambda: now[0])
watchdog._root_proc = root

with open(cf_path, 'wb') as writer:
writer.write(b'STARTED 0 4\n')
writer.flush()
self.assertTrue(watchdog._poll_once())

# Control file growth at t=40 resets 60s timer so t=99 does not kill.
now[0] = 40.0
writer.write(b'FT 0 1 2\n')
writer.flush()
self.assertTrue(watchdog._poll_once())

now[0] = 99.0
self.assertTrue(watchdog._poll_once())
self.assertEqual(events, [])

# Stall for 60s since t=40 -> reaps grandchild first, then inner + wait.
now[0] = 100.0
self.assertTrue(watchdog._poll_once())
self.assertEqual(events, ['kill:401', 'kill:300', 'wait:300'])

# Pre-kill guard: does not kill if root died right before kill.
events.clear()
root.is_running.return_value = False
now[0] = 160.0
self.assertFalse(watchdog._poll_once())
self.assertEqual(events, [])

def test_missing_or_unreadable_control_file_is_fail_safe(self) -> None:
"""Missing/unreadable MCF never kills; transient None preserves timer."""
cf_path = os.path.join(self.temp_dir, 'mcf.txt')
inner = _make_fake_proc(
300, ['fuzzer.exe', '-merge_inner=1', f'-merge_control_file={cf_path}'])
root = _make_fake_proc(100, ['outer.exe', '-merge=1'], children=[inner])
now = [0.0]
watchdog = merge_watchdog.WindowsMergeWatchdog(
100, unit_timeout=5, clock=lambda: now[0])
watchdog._root_proc = root

# File does not exist yet: never kills even past 60s stall timeout.
self.assertTrue(watchdog._poll_once())
now[0] = 100.0
self.assertTrue(watchdog._poll_once())
inner.kill.assert_not_called()

# Once readable at t=110, 60s baseline starts at t=110.
with open(cf_path, 'wb') as writer:
writer.write(b'STARTED 0 4\n')
now[0] = 110.0
self.assertTrue(watchdog._poll_once())

# Transient read failure at t=140 neither kills nor resets the t=110 timer.
with mock.patch.object(
merge_watchdog, '_get_live_file_size', return_value=None):
now[0] = 140.0
self.assertTrue(watchdog._poll_once())

now[0] = 169.0
self.assertTrue(watchdog._poll_once())
inner.kill.assert_not_called()

# Readable again at t=170 (60s since t=110) -> reaps.
now[0] = 170.0
self.assertTrue(watchdog._poll_once())
inner.kill.assert_called_once()

def test_circuit_breaker_counts_exact_no_progress_kills_and_resets(
self) -> None:
"""Breaker stops after 3 unchanged kills, ignores NoSuchProcess, resets."""
cf_path = os.path.join(self.temp_dir, 'mcf.txt')
with open(cf_path, 'wb') as writer:
writer.write(b'STARTED 0 4\n')

now = [0.0]
watchdog = merge_watchdog.WindowsMergeWatchdog(
100, unit_timeout=5, clock=lambda: now[0])
root = _make_fake_proc(100, ['outer.exe', '-merge=1'])
watchdog._root_proc = root

def _run_attempt(pid: int,
create_time: float,
kill_error: Exception | None = None) -> bool:
inner = _make_fake_proc(
pid,
['fuzzer.exe', '-merge_inner=1', f'-merge_control_file={cf_path}'],
create_time=create_time)
if kill_error is not None:
inner.kill.side_effect = kill_error
root.children.return_value = [inner]
self.assertTrue(watchdog._poll_once())
now[0] += 60.0
return watchdog._poll_once()

# Natural exit race (NoSuchProcess) does not count toward circuit breaker.
self.assertTrue(
_run_attempt(300, 1.0, kill_error=psutil.NoSuchProcess(300)))
self.assertEqual(watchdog._consecutive_no_progress_kills, 0)

# Kill 1 at size S0, then growth to S1 resets breaker on Kill 2.
self.assertTrue(_run_attempt(301, 2.0))
self.assertEqual(watchdog._consecutive_no_progress_kills, 1)
with open(cf_path, 'ab') as writer:
writer.write(b'STARTED 1 4\n')
self.assertTrue(_run_attempt(302, 3.0))
self.assertEqual(watchdog._consecutive_no_progress_kills, 1)

# Two more kills at the same size S1 trip the breaker on exact kill #3.
self.assertTrue(_run_attempt(303, 4.0))
self.assertEqual(watchdog._consecutive_no_progress_kills, 2)
self.assertFalse(_run_attempt(304, 5.0))
self.assertEqual(watchdog._consecutive_no_progress_kills, 3)


if __name__ == '__main__':
unittest.main()
Loading