diff --git a/tests/fuzz/CMakeLists.txt b/tests/fuzz/CMakeLists.txt index 44fbf4d159..0a3dbba56a 100644 --- a/tests/fuzz/CMakeLists.txt +++ b/tests/fuzz/CMakeLists.txt @@ -41,26 +41,33 @@ endif() configure_file("${PYBIND11_FUZZER_INCLUDE_DIR}/fuzzer/FuzzedDataProvider.h" "${CMAKE_CURRENT_BINARY_DIR}/include/fuzzer/FuzzedDataProvider.h" COPYONLY) -set(_pybind11_fuzz_sources pybind_fuzzer.cpp) +# One fuzz target per *_fuzzer.cpp in this directory. +set(_pybind11_fuzz_targets pybind_fuzzer cast_fuzzer) # OSS-Fuzz exports LIB_FUZZING_ENGINE to the object that provides main(). # Locally, link a small file-replay driver instead. if(DEFINED ENV{LIB_FUZZING_ENGINE} AND NOT "$ENV{LIB_FUZZING_ENGINE}" STREQUAL "") set(_pybind11_fuzz_engine "$ENV{LIB_FUZZING_ENGINE}") else() - list(APPEND _pybind11_fuzz_sources fuzz_replay.cpp) set(_pybind11_fuzz_engine "") endif() -add_executable(pybind_fuzzer ${_pybind11_fuzz_sources}) -add_executable(test_fuzz_input test_fuzz_input.cpp) -foreach(target pybind_fuzzer test_fuzz_input) +foreach(target ${_pybind11_fuzz_targets}) + set(_pybind11_fuzz_sources ${target}.cpp) + if(NOT _pybind11_fuzz_engine) + list(APPEND _pybind11_fuzz_sources fuzz_replay.cpp) + endif() + add_executable(${target} ${_pybind11_fuzz_sources}) pybind11_enable_warnings(${target}) target_include_directories(${target} SYSTEM PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/include") + target_link_libraries(${target} PRIVATE pybind11::embed) + if(_pybind11_fuzz_engine) + target_link_libraries(${target} PRIVATE ${_pybind11_fuzz_engine}) + endif() endforeach() -target_link_libraries(pybind_fuzzer PRIVATE pybind11::embed) -if(_pybind11_fuzz_engine) - target_link_libraries(pybind_fuzzer PRIVATE ${_pybind11_fuzz_engine}) -endif() + +add_executable(test_fuzz_input test_fuzz_input.cpp) +pybind11_enable_warnings(test_fuzz_input) +target_include_directories(test_fuzz_input SYSTEM PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/include") file(GLOB _pybind11_fuzz_corpus CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/corpus/*") add_custom_target( diff --git a/tests/fuzz/cast_fuzzer.cpp b/tests/fuzz/cast_fuzzer.cpp new file mode 100644 index 0000000000..f998d70c61 --- /dev/null +++ b/tests/fuzz/cast_fuzzer.cpp @@ -0,0 +1,379 @@ +// Fuzz harness: pybind11 value type casters (cast_fuzzer.cpp) +// +// Threat model: pybind11's type casters are the library's trust boundary -- +// every bound function receiving attacker-controlled data (dict payloads, +// JSON-ish structures, numeric/text fields) funnels through cast.h and the +// stl/chrono/complex/functional caster modules. This harness models that: +// the fuzzed bytes choose which caster runs, the Python value fed into it +// (including deliberate type confusions, e.g. casting a str where a +// container is expected), and the C++ value to round-trip. +// +// Coverage targets (dark in the 2026-11-25 local baseline, 10.41% lines): +// cast.h (376 dark), plus caster modules entirely absent from the fuzz +// build before this harness: stl.h (764 lines), chrono.h (415), +// complex.h (141), functional.h (140). +// +// Design notes (learnings from the rejected classes_fuzzer run): +// * One-time setup (interpreter + statics + warm-up of every op) happens in +// LLVMFuzzerInitialize so each traced callback execution allocates and +// frees a balanced set (libFuzzer's in-run leak detection must never see +// persistent interpreter startup state). +// * Bounded: <= 24 ops/iteration, strings <= 32 bytes, ints within +// [-1000, 1000000]. Per-op try/catch keeps expected cast failures as +// control flow; sanitizers remain the bug oracle. +// +// Input layout (stable, so crashes reproduce): +// * Op opcodes and small selectors are consumed from the END of the buffer +// (one byte each, first op = last byte). +// * 32-bit range ints are consumed from the END (3 bytes each). +// * Strings are consumed from the FRONT (ConsumeRandomLengthString(32)). + +#include "pybind11/pybind11.h" +#include "pybind11/cast.h" +#include "pybind11/chrono.h" +#include "pybind11/complex.h" +#include "pybind11/embed.h" +#include "pybind11/functional.h" +#include "pybind11/stl.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace py = pybind11; + +namespace pybind11_fuzz { + +enum Op : uint8_t { + kIntCasts = 0, + kFloatCasts, + kStringCasts, + kBytesCasts, + kVectorCasts, + kMapCasts, + kSetPairTuple, + kOptionalVariant, + kChronoDuration, + kComplexCast, + kFunctionalCall, + kWrongTypeProbes, + kNoneCasts, + kMaxOp // sentinel +}; + +inline uint8_t next_op(FuzzedDataProvider &fdp) { + return fdp.ConsumeIntegralInRange(0, static_cast(kMaxOp - 1)); +} + +inline int next_int(FuzzedDataProvider &fdp) { + return fdp.ConsumeIntegralInRange(-1000, 1000000); +} + +inline std::string next_str(FuzzedDataProvider &fdp) { return fdp.ConsumeRandomLengthString(32); } + +// Static handles live inside CastEnv, declared AFTER the scoped_interpreter +// member, so destruction (reverse member order) releases every py::object +// BEFORE the interpreter finalizes (file-scope static py::object globals +// would be destroyed after the guard and crash at exit). +struct CastEnv; +static void warm_up(CastEnv &env); + +struct CastEnv { + py::scoped_interpreter guard; + py::object abs_fn; // builtins.abs, for the functional caster + py::object timedelta; // datetime.timedelta, for the chrono caster + + CastEnv() + : guard{}, abs_fn(py::module_::import("builtins").attr("abs")), + timedelta(py::module_::import("datetime").attr("timedelta")) { + warm_up(*this); + } + + static CastEnv &get() { + static CastEnv env; + return env; + } +}; + +inline py::object scalar_object(FuzzedDataProvider &fdp) { + uint8_t kind = fdp.ConsumeIntegralInRange(0, 3); + switch (kind) { + case 0: + return py::int_(next_int(fdp)); + case 1: + return py::float_(static_cast(next_int(fdp)) / 8.0); + case 2: + return py::str(next_str(fdp)); + default: + return py::bool_(next_int(fdp) % 2 == 0); + } +} + +} // namespace pybind11_fuzz + +// Warm-up: exercise every caster once with fixed values so first-time +// allocations (interned type names, caster caches) happen outside traced +// executions. Strict on purpose: a throw here is a fixture bug we must see. +namespace pybind11_fuzz { + +static void warm_up(CastEnv &env) { + py::object i = py::int_(42); + (void) i.cast(); + (void) i.cast(); + py::object f = py::float_(1.5); + (void) f.cast(); + py::object s = py::str("warm"); + (void) s.cast(); + py::object b = py::bytes("wb"); + (void) b.cast(); + py::list l; + l.append(1); + l.append(2); + auto lv = l.cast>(); + py::object lb = py::cast(lv); + (void) lb.cast>(); + py::dict d; + d[py::str("k")] = 1; + auto dm = d.cast>(); + (void) py::cast(dm).cast>(); + py::object st = py::cast(std::set{3, 4}); + (void) st.cast>(); + auto pr = py::make_tuple(1, py::str("p")).cast>(); + (void) py::cast(pr).cast>(); + auto tp = py::make_tuple(1, py::float_(2.5), py::str("t")) + .cast>(); + (void) py::cast(tp); + py::object none = py::none(); + (void) none.cast>(); + (void) i.cast>(); + (void) i.cast>(); + (void) s.cast>(); + // chrono.h casts durations from Python timedeltas (not ints). + py::object td = env.timedelta(0, 0, 42000); // 42 ms + auto dur = td.cast(); + (void) py::cast(dur).cast(); + try { + (void) i.cast(); // int source: cast_error path + } catch (const py::error_already_set &) { + } catch (const py::builtin_exception &) { + } + py::object c = py::cast(std::complex(1.0, 2.0)); + auto cc = c.cast>(); + (void) py::cast(cc).cast>(); + try { + auto fn = env.abs_fn.cast>(); + (void) fn(py::float_(-2.5)); + } catch (const py::error_already_set &) { + } + try { + (void) s.cast>(); // deliberate type confusion: cast_error path + } catch (const py::error_already_set &) { + } catch (const py::builtin_exception &) { + } + (void) (none.cast>() == std::nullopt); +} + +} // namespace pybind11_fuzz + +extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { + pybind11_fuzz::CastEnv::get(); + return 0; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + using namespace pybind11_fuzz; + + FuzzedDataProvider fdp(data, size); + + try { + int ops = 0; + while (fdp.remaining_bytes() > 0 && ops < 24) { + ++ops; + const uint8_t op = next_op(fdp); + try { + switch (op) { + case kIntCasts: { + py::object v = py::int_(next_int(fdp)); + try { + (void) v.cast(); + } catch (const py::error_already_set &) { + } + long long wide = v.cast(); + py::object back = py::cast(wide); + if (back.cast() != wide) { + continue; // documented round-trip identity violated + } + (void) v.cast(); + break; + } + case kFloatCasts: { + double d = static_cast(next_int(fdp)) / 8.0; + py::object f = py::float_(d); + double rt = f.cast(); + if (rt != d) { + continue; + } + (void) f.cast(); + break; + } + case kStringCasts: { + std::string s = next_str(fdp); + py::object o = py::str(s); + std::string rt = o.cast(); + if (rt != s) { + continue; + } + (void) o.cast(); + break; + } + case kBytesCasts: { + std::string s = next_str(fdp); + py::object o = py::bytes(s); + std::string rt = o.cast(); + if (rt != s) { + continue; + } + break; + } + case kVectorCasts: { + int n = next_int(fdp) % 6; + if (n < 0) { + n = -n; + } + py::list l; + bool poison = (fdp.ConsumeIntegralInRange(0, 7) == 0); + for (int k = 0; k < n; ++k) { + l.append(poison && k == n / 2 ? py::object(py::str("x")) + : py::object(py::int_(next_int(fdp)))); + } + auto v = l.cast>(); + py::object back = py::cast(v); + auto v2 = back.cast>(); + if (v2.size() != v.size()) { + continue; + } + break; + } + case kMapCasts: { + int n = next_int(fdp) % 5; + if (n < 0) { + n = -n; + } + py::dict d; + for (int k = 0; k < n; ++k) { + d[py::str(next_str(fdp))] = next_int(fdp); + } + auto m = d.cast>(); + py::object back = py::cast(m); + auto m2 = back.cast>(); + if (m2 != m) { + continue; + } + break; + } + case kSetPairTuple: { + py::list l; + l.append(next_int(fdp)); + l.append(next_int(fdp)); + auto st = l.cast>(); + (void) py::cast(st).cast>(); + auto pr = py::make_tuple(next_int(fdp), py::str(next_str(fdp))) + .cast>(); + (void) py::cast(pr); + auto tp = py::make_tuple( + next_int(fdp), py::float_(1.25), py::str(next_str(fdp))) + .cast>(); + (void) py::cast(tp); + break; + } + case kChronoDuration: { + long long micros = next_int(fdp) * 1000; + py::object td = CastEnv::get().timedelta(0, 0, micros); + auto dur = td.cast(); + py::object back = py::cast(dur); + long long rt = back.cast().count(); + if (rt != micros / 1000) { + continue; + } + try { + (void) py::int_(micros).cast(); + } catch (const py::error_already_set &) { + } catch (const py::builtin_exception &) { + } + break; + } + case kComplexCast: { + double re = static_cast(next_int(fdp)) / 16.0; + double im = static_cast(next_int(fdp)) / 16.0; + auto c + = py::cast(std::complex(re, im)).cast>(); + py::object back = py::cast(c); + auto c2 = back.cast>(); + if (c2.real() != c.real() || c2.imag() != c.imag()) { + continue; + } + break; + } + case kFunctionalCall: { + auto fn = pybind11_fuzz::CastEnv::get() + .abs_fn.cast>(); + double arg = static_cast(next_int(fdp)) / 8.0; + (void) fn(py::float_(arg)); + break; + } + case kWrongTypeProbes: { + uint8_t probe = fdp.ConsumeIntegralInRange(0, 3); + py::object s = py::str(next_str(fdp)); + try { + if (probe == 0) { + (void) s.cast>(); + } else if (probe == 1) { + (void) s.cast>(); + } else if (probe == 2) { + (void) s.cast(); + } else { + (void) s.cast>(); + } + } catch (const py::error_already_set &) { + } + break; + } + case kNoneCasts: { + auto opt = py::none().cast>(); + if (opt.has_value()) { + continue; + } + try { + (void) py::none().cast(); + } catch (const py::error_already_set &) { + } + break; + } + default: + break; + } + } catch (const py::error_already_set &) { + // Expected control flow: failed/narrowed casts raise Python errors. + } catch (const py::builtin_exception &) { + // Expected control flow: caster rejections (cast_error etc.). + } catch (const std::exception &) { + // Keep the gate clean from documented C++ exception paths; + // memory-safety violations crash before this handler. + } + } + } catch (const py::error_already_set &) { + } catch (const py::builtin_exception &) { + } catch (const std::exception &) { + } + return 0; +} diff --git a/tests/fuzz/corpus_cast_fuzzer/01_int b/tests/fuzz/corpus_cast_fuzzer/01_int new file mode 100644 index 0000000000..ce1fa01b91 Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/01_int differ diff --git a/tests/fuzz/corpus_cast_fuzzer/02_float b/tests/fuzz/corpus_cast_fuzzer/02_float new file mode 100644 index 0000000000..1c339f6f4d Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/02_float differ diff --git a/tests/fuzz/corpus_cast_fuzzer/03_str b/tests/fuzz/corpus_cast_fuzzer/03_str new file mode 100644 index 0000000000..981bc3b29c --- /dev/null +++ b/tests/fuzz/corpus_cast_fuzzer/03_str @@ -0,0 +1 @@ +hello\! \ No newline at end of file diff --git a/tests/fuzz/corpus_cast_fuzzer/04_bytes b/tests/fuzz/corpus_cast_fuzzer/04_bytes new file mode 100644 index 0000000000..6636340fe9 --- /dev/null +++ b/tests/fuzz/corpus_cast_fuzzer/04_bytes @@ -0,0 +1 @@ +abc\! \ No newline at end of file diff --git a/tests/fuzz/corpus_cast_fuzzer/05_vec b/tests/fuzz/corpus_cast_fuzzer/05_vec new file mode 100644 index 0000000000..add15a0fc2 Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/05_vec differ diff --git a/tests/fuzz/corpus_cast_fuzzer/06_map b/tests/fuzz/corpus_cast_fuzzer/06_map new file mode 100644 index 0000000000..b93b8f2bbd Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/06_map differ diff --git a/tests/fuzz/corpus_cast_fuzzer/07_setpair b/tests/fuzz/corpus_cast_fuzzer/07_setpair new file mode 100644 index 0000000000..c9f0355e19 Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/07_setpair differ diff --git a/tests/fuzz/corpus_cast_fuzzer/08_optvar b/tests/fuzz/corpus_cast_fuzzer/08_optvar new file mode 100644 index 0000000000..24ec91c62b Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/08_optvar differ diff --git a/tests/fuzz/corpus_cast_fuzzer/09_chrono b/tests/fuzz/corpus_cast_fuzzer/09_chrono new file mode 100644 index 0000000000..2298e4d537 Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/09_chrono differ diff --git a/tests/fuzz/corpus_cast_fuzzer/10_complex b/tests/fuzz/corpus_cast_fuzzer/10_complex new file mode 100644 index 0000000000..dfde96ea48 Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/10_complex differ diff --git a/tests/fuzz/corpus_cast_fuzzer/11_func b/tests/fuzz/corpus_cast_fuzzer/11_func new file mode 100644 index 0000000000..bf3f4885ad Binary files /dev/null and b/tests/fuzz/corpus_cast_fuzzer/11_func differ diff --git a/tests/fuzz/corpus_cast_fuzzer/12_wrong b/tests/fuzz/corpus_cast_fuzzer/12_wrong new file mode 100644 index 0000000000..4d4e9dcab4 --- /dev/null +++ b/tests/fuzz/corpus_cast_fuzzer/12_wrong @@ -0,0 +1 @@ +nope\! \ No newline at end of file diff --git a/tests/fuzz/corpus_cast_fuzzer/13_none b/tests/fuzz/corpus_cast_fuzzer/13_none new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/tests/fuzz/corpus_cast_fuzzer/13_none @@ -0,0 +1 @@ +