Skip to content
Merged
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
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ jobs:
cmake-args: -DCMAKE_CXX_STANDARD=20
- runs-on: ubuntu-latest
python-version: '3.15'
cmake-args: -DCMAKE_CXX_STANDARD=20
cmake-args: -DCMAKE_CXX_STANDARD=20 -DPYBIND11_BUILD_FUZZERS=ON
fuzz-replay: true
- runs-on: macos-latest
python-version: '3.14'
cmake-args: -DCMAKE_CXX_STANDARD=14
Expand All @@ -78,6 +79,7 @@ jobs:
runs-on: ${{ matrix.runs-on }}
python-version: ${{ matrix.python-version }}
cmake-args: ${{ matrix.cmake-args }}
fuzz-replay: ${{ matrix.fuzz-replay || false }}

# Build the test suite against the precompiled pybind11 static library; a
# definition missing from the -inl.h split shows up here as a link error.
Expand Down
36 changes: 36 additions & 0 deletions .github/workflows/cifuzz.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: CIFuzz

on:
workflow_dispatch:

permissions: {}

jobs:
Fuzzing:
# CIFuzz builds through the OSS-Fuzz project, not this repository's CMake
# cache. The job is allowed to fail until oss-fuzz's pybind11 build.sh
# compiles tests/fuzz/pybind_fuzzer.cpp with LIB_FUZZING_ENGINE set
# (google/oss-fuzz#16274). Corpus replay in CI provides the required check.
continue-on-error: true
runs-on: ubuntu-latest
permissions:
security-events: write
steps:
- name: Build Fuzzers
id: build
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
with:
oss-fuzz-project-name: pybind11
language: c++
- name: Run Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: pybind11
language: c++
fuzz-seconds: 300
- name: Upload Crash
uses: actions/upload-artifact@v4
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
path: ./out/artifacts
8 changes: 8 additions & 0 deletions .github/workflows/reusable-standard.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ on:
runs-on:
required: true
type: string
fuzz-replay:
required: false
type: boolean
default: false

env:
PYTHONDEVMODE: 1
Expand Down Expand Up @@ -107,5 +111,9 @@ jobs:
timeout-minutes: 3
run: cmake --build build --target cpptest

- name: Fuzz corpus replay
if: inputs.fuzz-replay
run: cmake --build build --target fuzz_replay

- name: Visibility test
run: cmake --build build --target test_cross_module_rtti
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,10 @@ if(NOT DEFINED CMAKE_CROSSCOMPILING_EMULATOR)
set(_pybind11_use_crosscompiling_default ON)
endif()
endif()

option(PYBIND11_USE_CROSSCOMPILING "Respect CMAKE_CROSSCOMPILING"
${_pybind11_use_crosscompiling_default})
option(PYBIND11_BUILD_FUZZERS "Build the OSS-Fuzz harnesses" OFF)

cmake_dependent_option(
USE_PYTHON_INCLUDE_DIR
Expand Down
4 changes: 4 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -753,4 +753,8 @@ if(NOT PYBIND11_CUDA_TESTS)

# Test visibility of common symbols across shared libraries
add_subdirectory(test_cross_module_rtti)

# Optional OSS-Fuzz harness. The subdirectory is a no-op unless
# PYBIND11_BUILD_FUZZERS is ON.
add_subdirectory(fuzz)
endif()
73 changes: 73 additions & 0 deletions tests/fuzz/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
if(NOT PYBIND11_BUILD_FUZZERS)
return()
endif()

possibly_uninitialized(PYTHON_MODULE_EXTENSION Python_INTERPRETER_ID)

if("${PYTHON_MODULE_EXTENSION}" MATCHES "pypy"
OR "${Python_INTERPRETER_ID}" STREQUAL "PyPy"
OR "${PYTHON_MODULE_EXTENSION}" MATCHES "graalpy")
message(STATUS "Skipping fuzz harness on PyPy or GraalPy")
return()
endif()

if(TARGET Python::Module AND NOT TARGET Python::Python)
message(STATUS "Skipping fuzz harness since no embed libs found")
return()
endif()

if(NOT PYBIND11_FUZZER_INCLUDE_DIR)
find_program(_pybind11_fuzz_clang NAMES clang)
if(_pybind11_fuzz_clang)
execute_process(
COMMAND "${_pybind11_fuzz_clang}" -print-resource-dir
OUTPUT_VARIABLE _pybind11_fuzz_resource_dir
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
endif()
find_path(
PYBIND11_FUZZER_INCLUDE_DIR fuzzer/FuzzedDataProvider.h
HINTS "${_pybind11_fuzz_resource_dir}/include"
DOC "Directory containing fuzzer/FuzzedDataProvider.h")
if(NOT EXISTS "${PYBIND11_FUZZER_INCLUDE_DIR}/fuzzer/FuzzedDataProvider.h")
message(
FATAL_ERROR
"FuzzedDataProvider.h not found. Install Clang's development headers or set "
"PYBIND11_FUZZER_INCLUDE_DIR to the directory containing fuzzer/FuzzedDataProvider.h")
endif()

# Copy only this portable header: Clang's full resource include directory also
# contains compiler-specific standard headers that cannot be used with GCC.
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)
# 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)
pybind11_enable_warnings(${target})
target_include_directories(${target} SYSTEM PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/include")
endforeach()
target_link_libraries(pybind_fuzzer PRIVATE pybind11::embed)
if(_pybind11_fuzz_engine)
target_link_libraries(pybind_fuzzer PRIVATE ${_pybind11_fuzz_engine})
endif()

file(GLOB _pybind11_fuzz_corpus CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/corpus/*")
add_custom_target(
fuzz_replay
COMMAND "$<TARGET_FILE:test_fuzz_input>" "${CMAKE_CURRENT_SOURCE_DIR}/corpus/exec_success"
COMMAND "$<TARGET_FILE:pybind_fuzzer>" ${_pybind11_fuzz_corpus}
DEPENDS pybind_fuzzer test_fuzz_input
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
USES_TERMINAL
COMMENT "Replaying the checked-in fuzz corpus")
75 changes: 75 additions & 0 deletions tests/fuzz/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Embedding fuzzer

`pybind_fuzzer` is the existing OSS-Fuzz harness, moved here so it can be
reviewed and updated with the code it exercises. It does not define pybind11
bindings. Each input is split into strings and used to:

- start the embedded interpreter once, then run `py::exec`
- import `os` and look up an attribute
- construct `decimal.Decimal` and call a method on it
- construct a `py::str`

`py::error_already_set` is caught. That is expected for invalid Python, a
missing attribute, or a bad `Decimal` argument. A failure worth reporting is a
crash, sanitizer error, or hang in pybind11's embedding layer or in CPython
reached through that layer.

## Build and replay

The target is off unless requested. Replay needs a C++ compiler, CPython's
embedding library, and LLVM's `fuzzer/FuzzedDataProvider.h`; it does not need
libFuzzer:

```bash
cmake -S . -B build -DPYBIND11_BUILD_FUZZERS=ON
cmake --build build --target pybind_fuzzer
cmake --build build --target fuzz_replay
```

CMake finds the header through `clang -print-resource-dir`. If Clang is not
on `PATH`, set `-DPYBIND11_FUZZER_INCLUDE_DIR=/path/to/include`, where that
directory contains `fuzzer/FuzzedDataProvider.h`. GCC can use this header too.

`fuzz_replay` first checks the decoded fields of the `exec_success` seed,
then runs `LLVMFuzzerTestOneInput` on every file in `tests/fuzz/corpus`.
To reproduce one OSS-Fuzz artifact with the standalone binary:

```bash
./build/tests/fuzz/pybind_fuzzer /path/to/crash
```

OSS-Fuzz sets `LIB_FUZZING_ENGINE` and links that instead of `fuzz_replay.cpp`.
Both builds use the same callback and input decoder. When reproducing a
sanitizer finding, enable the same sanitizer in the replay build. The
libFuzzer binary can also replay one artifact with `-runs=1 <file>`.

## Input format

The decoder reads five strings, in order: Python code, an `os` attribute
name, a `Decimal` argument, a `Decimal` method name, and text for `py::str`.
It calls `FuzzedDataProvider::ConsumeRandomLengthString` once for each field.
A backslash followed by any non-backslash byte ends a field; two consecutive
backslashes encode a literal backslash. The last field can end at EOF.
For example, the `exec_success` seed contains these bytes:

```text
x = 1\!getcwd\!1\!as_tuple\!ok\!
```

This upstream harness uses five fields. The older OSS-Fuzz copy consumed an
additional, independent string for the unused tuple argument, so artifacts
from that version need the matching older harness for reproduction.

## Reducing a crash

1. Rebuild with `-DPYBIND11_BUILD_FUZZERS=ON` and rerun the artifact.
2. Reduce the decoded strings while preserving their separators, rerunning
the input after each change. Empty fields still need separators when a
later field is involved.
3. Turn the surviving call into a normal `tests/test_*.py` regression. If the
crash is only reachable through embedding, add it beside
`tests/test_with_catch` instead.

Arbitrary `py::exec` is intentionally broad and retains the operations of the
existing OSS-Fuzz target. A later harness can drive explicit `class_`, `def`,
and caster operations as a separate target.
Empty file added tests/fuzz/corpus/empty
Empty file.
1 change: 1 addition & 0 deletions tests/fuzz/corpus/exec_runtime_error
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1/0\!\!\!\!runtime\!
1 change: 1 addition & 0 deletions tests/fuzz/corpus/exec_success
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
x = 1\!getcwd\!1\!as_tuple\!ok\!
1 change: 1 addition & 0 deletions tests/fuzz/corpus/exec_syntax_error
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
def (\!not_an_os_attr\!not-a-decimal\!no_such_method\!\!
1 change: 1 addition & 0 deletions tests/fuzz/corpus/str_only
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
\!\!\!\!hello\!
32 changes: 32 additions & 0 deletions tests/fuzz/fuzz_input.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) 2026 The pybind Community.

#pragma once

#include <cstddef>
#include <cstdint>
#include <string>

#include <fuzzer/FuzzedDataProvider.h>

namespace pybind11_fuzz {

struct input {
std::string code;
std::string attr_name;
std::string decimal_text;
std::string decimal_attr;
std::string text;
};

inline input decode_input(const std::uint8_t *data, std::size_t size) {
FuzzedDataProvider fdp(data, size);
input result;
result.code = fdp.ConsumeRandomLengthString();
result.attr_name = fdp.ConsumeRandomLengthString();
result.decimal_text = fdp.ConsumeRandomLengthString();
result.decimal_attr = fdp.ConsumeRandomLengthString();
result.text = fdp.ConsumeRandomLengthString();
return result;
}

} // namespace pybind11_fuzz
57 changes: 57 additions & 0 deletions tests/fuzz/fuzz_replay.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Local and CI driver for LLVMFuzzerTestOneInput. OSS-Fuzz supplies its own
// main() through LIB_FUZZING_ENGINE, so this file is not linked there.

#include <cstdint>
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);

namespace {

std::vector<uint8_t> read_file(const std::string &path) {
std::ifstream input(path, std::ios::binary);
if (!input) {
throw std::runtime_error("failed to open fuzz input: " + path);
}
input.seekg(0, std::ios::end);
const auto nbytes = input.tellg();
if (nbytes < 0) {
throw std::runtime_error("failed to size fuzz input: " + path);
}
input.seekg(0, std::ios::beg);
std::vector<uint8_t> bytes(static_cast<size_t>(nbytes));
if (nbytes > 0) {
input.read(reinterpret_cast<char *>(bytes.data()), nbytes);
}
if (!input) {
throw std::runtime_error("failed to read fuzz input: " + path);
}
return bytes;
}

} // namespace

int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "usage: " << argv[0] << " <input>...\n";
return 2;
}
try {
for (int i = 1; i < argc; ++i) {
const std::vector<uint8_t> bytes = read_file(argv[i]);
const int rc = LLVMFuzzerTestOneInput(bytes.data(), bytes.size());
if (rc != 0) {
std::cerr << "fuzz callback failed on " << argv[i] << "\n";
return rc;
}
}
} catch (const std::exception &ex) {
std::cerr << ex.what() << "\n";
return 1;
}
return 0;
}
Loading
Loading