Skip to content
Open
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
26 changes: 22 additions & 4 deletions centipede/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -979,8 +979,6 @@ cc_library(
name = "engine_worker",
srcs = [
"engine_worker.cc",
"runner_utils.cc",
"runner_utils.h",
],
hdrs = ["engine_worker_abi.h"],
deps = [
Expand All @@ -989,6 +987,7 @@ cc_library(
":feature",
":runner_request",
":runner_result",
":runner_utils",
":shared_memory_blob_sequence",
"@abseil-cpp//absl/base:nullability",
"@com_google_fuzztest//common:defs",
Expand Down Expand Up @@ -1215,8 +1214,6 @@ cc_library(
"reverse_pc_table.h",
"runner_dl_info.cc",
"runner_dl_info.h",
"runner_utils.cc",
"runner_utils.h",
"sancov_callbacks.cc",
"sancov_interceptors.cc",
"sancov_object_array.cc",
Expand All @@ -1238,6 +1235,7 @@ cc_library(
":foreach_nonzero",
":int_utils",
":runner_cmp_trace",
":runner_utils",
"@abseil-cpp//absl/base:core_headers",
"@abseil-cpp//absl/base:nullability",
"@abseil-cpp//absl/numeric:bits",
Expand Down Expand Up @@ -2000,3 +1998,23 @@ sh_test(
":test_util_sh",
],
)

cc_library(
name = "runner_utils",
srcs = ["runner_utils.cc"],
hdrs = ["runner_utils.h"],
copts = DISABLE_SANCOV_COPTS,
deps = [
"@abseil-cpp//absl/base:nullability",
],
)

cc_static_library(
name = "centipede_engine_static",
deps = [
":engine_controller_with_subprocess",
":engine_worker",
":sancov_runtime",
":weak_sancov_stubs",
],
)
3 changes: 3 additions & 0 deletions rust/.rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
use_field_init_shorthand = true
use_try_shorthand = true
edition = "2021"
44 changes: 44 additions & 0 deletions rust/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
load("//third_party/bazel_rules/rules_rust/rust:defs.bzl", "rust_library", "rust_test")

licenses(["notice"])

exports_files(["BUILD"])

rust_library(
name = "fuzztest",
srcs = glob([
"src/**/*.rs",
]),
edition = "2024",
proc_macro_deps = [
"@com_google_fuzztest//rust/fuzztest_macro:fuzztest_macro",
],
rustc_flags = ["-Zallow-features=cfg_sanitize"],
visibility = ["__subpackages__"],
deps = [
"//third_party/rust/anyhow/v1:anyhow",
"//third_party/rust/clap/v4:clap",
"//third_party/rust/humantime/v2:humantime",
"//third_party/rust/inventory/v0_3:inventory",
"//third_party/rust/num_traits/v0_2:num_traits",
"//third_party/rust/postcard/v1:postcard",
"//third_party/rust/rand/v0_10:rand",
"//third_party/rust/serde/v1:serde",
"//third_party/rust/spin/v0_10:spin",
"//third_party/rust/tempfile/v3:tempfile",
"@com_google_fuzztest//rust/coverage",
"@com_google_fuzztest//rust/engine",
],
)

rust_test(
name = "fuzztest_test",
# Avoid interference when setting/resetting environment variables in tests.
args = ["--test-threads=1"],
crate = ":fuzztest",
edition = "2024",
rustc_flags = ["-Zallow-features=cfg_sanitize"],
deps = [
"//third_party/gtest_rust/googletest",
],
)
42 changes: 42 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[package]
name = "fuzztest"
version = "0.1.0"
edition = "2024"

[[test]]
name = "trybuild"
path = "tests/trybuild.rs"

[dependencies]
anyhow = "1.0.100"
fuzztest-macro = { path = "fuzztest_macro" }
inventory = "0.3.20"
num-traits = "0.2"
postcard = { version = "1.0.0", features = ["use-std"] }
rand = { version = "0.10.1", features = ["std_rng"] }
serde = { version = "1.0", features = ["derive"] }
coverage = { path = "coverage" }
engine = { path = "engine", package = "engine-ffi" }
spin = "0.10.0"
tempfile = "3.27.0"
clap = { version = "4.6.1", features = ["derive", "env"] }
humantime = "2.4.0"

[dev-dependencies]
googletest = "0.14.3"

[dev-dependencies.trybuild]
version = "1.0.103"
features = ["diff"]

[profile.fuzztest]
inherits = 'release'
panic = 'abort'
opt-level = "s"
debug = true
split-debuginfo = "packed"

[workspace]
members = [
"cargo_fuzztest",
]
62 changes: 62 additions & 0 deletions rust/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# FuzzTest Rust

A framework for fuzzing Rust projects using Google FuzzTest.

## Prerequisites

1. Clone the repository.
2. Build the C++ Centipede static library engine using Bazel (from the
repository root):

```bash
cd /path/to/fuzztest
bazel build //centipede:centipede_engine_static
```
3. Copy the libcentipede_engine_static.a library to another location:

```bash
mkdir -p $HOME/.local/lib
cp /path/to/fuzztest/bazel-bin/centipede/libcentipede_engine_static.a \
$HOME/.local/lib/
```

## Setup a Project

1. Create a new Rust project:

```bash
cargo new my_fuzz_project --bin
```

2. Add `fuzztest` as a dependency in your `Cargo.toml`:

```toml
[dependencies]
fuzztest = { path = "/path/to/fuzztest/rust" }
googletest = "0.14.3"
```

## Write a Fuzz Test

In `src/main.rs`:

```rust
#[cfg(test)]
mod tests {
use fuzztest::domains::arbitrary::Arbitrary;
use fuzztest::fuzztest;

#[fuzztest(a = Arbitrary::<i32>::default(), b = Arbitrary::<i32>::default())]
fn test_addition(a: i32, b: i32) {
let _ = a.wrapping_add(b);
}
}
```

## Build and Run Fuzz Tests

To run the fuzz tests, you must specify:

```bash
RUSTFLAGS="-L $HOME/.local/lib" cargo test __fuzztest_mod__::test_addition
```
8 changes: 8 additions & 0 deletions rust/cargo_fuzztest/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "cargo-fuzztest"
version = "0.1.0"
edition = "2021"

[dependencies]
clap = { version = "4.5", features = ["derive"] }
anyhow = "1.0.100"
105 changes: 105 additions & 0 deletions rust/cargo_fuzztest/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use anyhow::Context;

fn get_host_target_triple() -> anyhow::Result<String> {
let cargo_bin = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
let output = std::process::Command::new(&cargo_bin)
.arg("-vV")
.output()
.context("while attempting to run `cargo -vV` to determine host target triple")?;

if !output.status.success() {
anyhow::bail!("cargo -vV exited with status: {:?}", output.status);
}

let stdout_str = String::from_utf8(output.stdout)
.context("while attempting to parse stdout of cargo -vV as UTF-8")?;
parse_host_triple(&stdout_str)
}

/// Parses the output of `cargo -vV` to extract the host target triple.
///
/// Cargo's verbose version output contains lines of key-value metadata, including
/// a `host: <triple>` line representing the host build architecture.
fn parse_host_triple(stdout: &str) -> anyhow::Result<String> {
for line in stdout.lines() {
if let Some(triple) = line.strip_prefix("host: ") {
return Ok(triple.trim().to_string());
}
}
anyhow::bail!("Failed to find 'host: ' line in cargo -vV output")
}

fn main() -> anyhow::Result<()> {
let host_triple = get_host_target_triple()?;

let cargo_bin = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
let mut cmd = std::process::Command::new(&cargo_bin);

// run all fuzztests
cmd.arg("test");
cmd.arg("__fuzztest_mod__");

cmd.arg("--").arg("--test-threads=1");

// We set the target-specific rustflags (`CARGO_TARGET_<TRIPLE>_RUSTFLAGS`) instead of a global
// `RUSTFLAGS` environment variable.
//
// If a global `RUSTFLAGS` is set, Cargo applies sanitizer coverage flags to both target code
// and host tools (such as build scripts and proc-macros). This causes host tool compilation
// to fail during linking because host tools are not linked against the fuzzer runtime
// (which implements the sanitizer coverage callbacks).
//
// Using a target-specific key combined with Cargo's explicit `--target` flag ensures
// that host tool helper crates are compiled normally, while only our target fuzz tests
// receive fuzzer instrumentation.
let target_env_key =
format!("CARGO_TARGET_{}_RUSTFLAGS", host_triple.to_uppercase().replace("-", "_"));
let rustflags_value = "-Cpasses=sancov-module \
-Cllvm-args=-sanitizer-coverage-level=4 \
-Cllvm-args=-sanitizer-coverage-pc-table \
-Cllvm-args=-sanitizer-coverage-inline-8bit-counters \
-Cllvm-args=-sanitizer-coverage-trace-compares";
cmd.env(&target_env_key, rustflags_value);

let exit_code = {
let status = cmd.status().context("run cargo test command")?;
status.code().unwrap_or(1)
};
std::process::exit(exit_code);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_parse_host_triple_valid() {
let stdout = "rustc 1.75.0 (82e5872f3 2023-12-21)\n\
binary: rustc\n\
commit-hash: 82e5872f3d693c9d7d4c2c56a8fb7f59d47c4058\n\
commit-date: 2023-12-21\n\
host: x86_64-unknown-linux-gnu\n\
release: 1.75.0\n\
LLVM version: 17.0.6\n";
let result = parse_host_triple(stdout).expect("valid stdout parsing should succeed");
assert_eq!(result, "x86_64-unknown-linux-gnu");
}

#[test]
fn test_parse_host_triple_missing_host() {
let stdout = "rustc 1.75.0 (82e5872f3 2023-12-21)\n\
binary: rustc\n";
let result = parse_host_triple(stdout);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("Failed to find 'host: ' line"));
}

#[test]
fn test_get_host_target_triple_success() {
let result = get_host_target_triple();
assert!(result.is_ok(), "Expected to succeed on host system, got: {:?}", result);
let triple = result.expect("get_host_target_triple should succeed on host system");
assert!(!triple.is_empty());
assert!(triple.contains('-'));
}
}
34 changes: 34 additions & 0 deletions rust/coverage/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
load("//third_party/bazel_rules/rules_rust/rust:defs.bzl", "rust_library", "rust_test")

licenses(["notice"])

rust_library(
name = "coverage",
srcs = [
"src/coverage.rs",
"src/lib.rs",
],
cc_deps = [
"@com_google_fuzztest//centipede:sancov_runtime",
],
visibility = ["@com_google_fuzztest//rust:__subpackages__"],
)

rust_test(
name = "coverage_test",
# Avoid interference on coverage collection between threads.
args = ["--test-threads=1"],
crate = ":coverage",
env = {
"CENTIPEDE_RUNNER_FLAGS": ":use_cmp_features:",
},
# TODO: b/437896409 - Replace with global config once it's available.
rustc_flags = [
"-Cpasses=sancov-module",
"-Cllvm-args=-sanitizer-coverage-level=1",
"-Cllvm-args=-sanitizer-coverage-trace-compares",
],
deps = [
"//third_party/gtest_rust/googletest",
],
)
6 changes: 6 additions & 0 deletions rust/coverage/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "coverage"
version = "0.1.0"
edition = "2021"

[dependencies]
Loading
Loading