blob: a52a2e18faa50f78cbeea2337b4b1780bcfcc6c7 [file]
#!/usr/bin/env python3
# Copyright 2026 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs one fuzzing session of a Chromium fuzz target and records it.
Note: The target must already be built in --build-dir. The runner never runs GN
or ninja.
Example:
python3 tools/fuzzing/fuzz_target_runner.py \\
--engine=libfuzzer --build-dir=out/libfuzzer-asan \\
--target=zlib_inflate_fuzzer --duration=15m \\
--output-dir=/tmp/pb/zlib/libfuzzer/1
Output directory:
logs/engine.log The engine's combined stdout and stderr.
corpus/ Inputs the engine kept.
crashes/ Inputs that crashed the target.
work/ home/ The engine's cwd and $HOME.
Exit codes:
0 The session ran, whether or not the engine found a crash.
1 A runner bug (an uncaught Python exception).
2 Bad flags, build dir or output dir.
3 The target isn't built in the build dir.
4 The engine didn't start.
130 Interrupted by Ctrl-C or SIGTERM.
"""
from __future__ import annotations
import argparse
import dataclasses
import enum
import os
import pathlib
import re
import subprocess
import sys
import engines
# The dynamic loader exits with this when it can't load the binary, e.g. a
# shared library or symbol is missing because the build is stale.
_LOADER_ERROR_EXIT_CODE = 127
class ExitCode(enum.IntEnum):
"""Process exit codes."""
OK = 0
# 1 is unused: Python exits with 1 on an uncaught exception, meaning a
# runner bug.
BAD_SPEC = 2 # Also what argparse exits with on bad flags
MISSING_BINARY = 3
ENGINE_DID_NOT_START = 4
INTERRUPTED = 130
class SetupError(Exception):
"""The session could not start. Carries the exit code."""
def __init__(self, message: str, exit_code: ExitCode = ExitCode.BAD_SPEC):
super().__init__(message)
self.exit_code = exit_code
@dataclasses.dataclass(frozen=True)
class Layout:
"""The paths within the output directory."""
root: pathlib.Path
# The writable corpus: it starts empty and the engine saves the inputs it
# keeps here.
@property
def corpus(self) -> pathlib.Path:
return self.root / 'corpus'
@property
def crashes(self) -> pathlib.Path:
return self.root / 'crashes'
# Engine cwd, keeping relative outputs inside the output dir.
@property
def work(self) -> pathlib.Path:
return self.root / 'work'
# The engine's $HOME, so a host's state doesn't affect fuzzers.
@property
def home(self) -> pathlib.Path:
return self.root / 'home'
@property
def logs(self) -> pathlib.Path:
return self.root / 'logs'
# The engine's combined stdout and stderr.
@property
def engine_log(self) -> pathlib.Path:
return self.logs / 'engine.log'
def subdirs(self) -> list[pathlib.Path]:
return [self.corpus, self.crashes, self.work, self.home, self.logs]
def parse_duration(value: str) -> int:
"""Parses '900', '900s', '15m', '1h' or '1h30m' into seconds."""
value = value.strip().lower()
if value.isdecimal():
duration = int(value)
else:
parts = re.findall(r'(\d+)([hms])', value)
if not parts or ''.join(num + unit for num, unit in parts) != value:
raise argparse.ArgumentTypeError(f'bad duration: {value!r}')
units = {'h': 3600, 'm': 60, 's': 1}
duration = sum(int(num) * units[unit] for num, unit in parts)
if duration <= 0:
raise argparse.ArgumentTypeError(f'duration must be positive: {value!r}')
return duration
def parse_seed(value: str) -> int:
"""Parses a seed. 0 is rejected because the engines take it to mean a random
seed. Negative is rejected since the value wraps to a different fixed seed."""
value = value.strip()
if not value.isdecimal() or int(value) == 0:
raise argparse.ArgumentTypeError(
f'seed must be a positive integer: {value!r}'
)
return int(value)
def parse_nonempty(value: str) -> str:
value = value.strip()
if not value:
raise argparse.ArgumentTypeError('must not be empty')
return value
def parse_path(value: str) -> pathlib.Path:
"""Makes the path absolute, because the engine runs with its cwd inside the
output dir."""
return pathlib.Path(os.path.abspath(parse_nonempty(value)))
def session_from_argv(argv: list[str] | None) -> Session:
"""Parses command line arguments into a Session."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
allow_abbrev=False,
)
parser.add_argument('--engine', required=True, choices=engines.ENGINES)
parser.add_argument(
'--build-dir',
required=True,
type=parse_path,
help='GN out dir where the target is built.',
)
parser.add_argument(
'--target', required=True, type=parse_nonempty, help='Fuzz target name.'
)
parser.add_argument(
'--duration',
required=True,
type=parse_duration,
help='How long the engine is told to fuzz, e.g. 900, 15m, 1h.',
)
parser.add_argument(
'--output-dir',
required=True,
type=parse_path,
help='Must be missing or empty.',
)
parser.add_argument(
'--seed',
type=parse_seed,
help='Positive engine RNG seed. If unset, the engine picks a random one.',
)
# TODO(crbug.com/581948942): Add flags for the engine limits in EngineOptions.
args = parser.parse_args(argv)
return Session(
adapter=engines.get_adapter(args.engine),
target=engines.Target(build_dir=args.build_dir, name=args.target),
engine_options=engines.EngineOptions(
duration_s=args.duration, seed=args.seed
),
layout=Layout(args.output_dir),
)
@dataclasses.dataclass(frozen=True)
class Session:
"""Runs one fuzz target under one engine and records it in the output dir."""
adapter: engines.EngineAdapter
target: engines.Target
engine_options: engines.EngineOptions
layout: Layout
# TODO(crbug.com/581948942): Add a hard-deadline timeout, and stop the engine
# when the runner is interrupted.
def run(self) -> ExitCode:
"""Runs the session."""
# TODO(crbug.com/581948942): Record the session in trial.json (inputs) and
# summary.json (results).
# Check the build before creating anything, so that a missing target leaves
# no output dir behind.
binary = self.target.binary
if not binary.is_file():
raise SetupError(
f'fuzz target is not built: {binary}', ExitCode.MISSING_BINARY
)
# Create the output dir.
root = self.layout.root
try:
if not root.exists():
root.mkdir(parents=True)
elif not root.is_dir():
raise SetupError(f'output dir is not a directory: {root}')
elif any(root.iterdir()):
raise SetupError(f'output dir is not empty: {root}')
for subdir in self.layout.subdirs():
subdir.mkdir()
except OSError as e:
raise SetupError(f'cannot create the output dir: {e}') from e
# Run the engine until it stops by itself.
command = self.adapter.command(
self.target,
self.engine_options,
corpus_dir=self.layout.corpus,
crashes_dir=self.layout.crashes,
)
# TODO(crbug.com/581948942): Pin the sanitizer options.
env = dict(os.environ, HOME=str(self.layout.home))
# TODO(crbug.com/581948942): Add an option to also print the engine's
# output to stdout.
log_path = self.layout.engine_log
with open(log_path, 'wb') as log:
try:
engine = subprocess.run(
command,
cwd=self.layout.work,
env=env,
stdin=subprocess.DEVNULL,
stdout=log,
stderr=subprocess.STDOUT,
check=False,
)
except OSError as e:
raise SetupError(
f'failed to start the engine: {e}', ExitCode.ENGINE_DID_NOT_START
) from e
if engine.returncode == _LOADER_ERROR_EXIT_CODE:
raise SetupError(
f'the engine could not be loaded, see {log_path}',
ExitCode.ENGINE_DID_NOT_START,
)
# Any other engine exit code is a result, not a runner failure: libFuzzer
# exits with a non-zero code when it finds a crash.
return ExitCode.OK
def main(argv: list[str] | None = None) -> ExitCode:
try:
return session_from_argv(argv).run()
except SetupError as e:
print(f'error: {e}', file=sys.stderr)
return e.exit_code
if __name__ == '__main__':
sys.exit(main())