### Custom Directories for Fuzzing Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Examples of initializing a project or running fuzzing with a custom fuzz directory using `--fuzz-dir`. ```bash cargo fuzz init --fuzz-dir fuzzy cargo fuzz run my_target --fuzz-dir fuzzy ``` -------------------------------- ### Run Fuzzing with Default Settings Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Execute a fuzz target with default configurations. This is the most basic way to start fuzzing. ```bash cargo fuzz run my_target ``` -------------------------------- ### Beginner Learning Path for Cargo-Fuzz Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/INDEX.md A simplified learning path for new users who want to quickly get started with using cargo-fuzz. It focuses on essential commands for project initialization and running fuzzers. ```text README.md ↓ api-reference/init.md ↓ api-reference/add.md ↓ api-reference/run.md ↓ (Run fuzzer) ``` -------------------------------- ### Fuzzing with Sanitizers Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Examples of running fuzzing with different sanitizers: address, thread, or none. ```bash cargo fuzz run my_target --sanitizer address # Default cargo fuzz run my_target --sanitizer thread # ThreadSanitizer cargo fuzz run my_target --sanitizer none # No sanitizer ``` -------------------------------- ### Install rustfmt Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/CONTRIBUTING.md Install the rustfmt component for the current stable Rust channel if it is not already installed. ```sh rustup component add rustfmt ``` -------------------------------- ### Install LLVM Tools for Coverage Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md Install the necessary LLVM tools for your Rust version if you encounter 'Failed to run command' errors during coverage analysis. This is a prerequisite for coverage features. ```bash # Install LLVM tools for your Rust version rustup component add llvm-tools-preview ``` -------------------------------- ### Initialize with Default Settings Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/init.md Creates a new fuzzing project with the default fuzz target named 'fuzz_target_1'. No additional setup is required. ```bash cargo fuzz init ``` -------------------------------- ### Cargo Fuzz Command Examples Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Demonstrates common ways to interact with cargo-fuzz from the command line for type-checking, building, running, and debugging. ```bash # Type-check only (faster) cargo fuzz check my_target ``` ```bash # Build specific target cargo fuzz build my_target ``` ```bash # Run with verbose output cargo fuzz run my_target -v ``` ```bash # Run with debugging RUST_BACKTRACE=1 cargo fuzz run my_target ``` -------------------------------- ### Rustflags Assembly Example Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md Demonstrates how rustflags are constructed to include sanitizer and coverage options for fine-grained compilation control. ```rust let mut rustflags = String::new(); rustflags.push_str(" -Cpasses=sancov-module"); rustflags.push_str(" -Cllvm-args=-sanitizer-coverage-level=4"); // ... 20+ conditional flags based on BuildOptions cmd.env("RUSTFLAGS", rustflags); ``` -------------------------------- ### Main Function Flow Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md Illustrates the execution flow starting from the main function, through argument parsing with clap, to dispatching commands via the RunCommand trait. ```text main() ↓ Command::parse() [clap] ↓ command.run_command() [trait dispatch] ↓ Specific command implementation ``` -------------------------------- ### Parallel Fuzzing Example Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Shows how to run multiple fuzzers in parallel to speed up bug discovery. The corpus is automatically merged. ```bash # Run 4 independent fuzzers in parallel cargo fuzz run my_target -j 4 # Each will find different inputs, corpus is merged automatically ``` -------------------------------- ### Successful Minimization Output Example Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/tmin.md This shows the typical output when the `tmin` command successfully minimizes a test case. It includes the path to the minimized artifact and reproduction instructions. ```text ──────────────────────────────────────────────────────────────────────────────── Minimized artifact: fuzz/artifacts/my_target/minimized-crash Output of `std::fmt::Debug`: [Debug representation of minimized input] Reproduce with: cargo fuzz run my_target fuzz/artifacts/my_target/minimized-crash ──────────────────────────────────────────────────────────────────────────────── ``` -------------------------------- ### RunCommand Trait Implementation for Init Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md Example implementation of the `RunCommand` trait for the `Init` struct, demonstrating how to delegate command execution to a specific project method. ```rust impl RunCommand for Init { fn run_command(&mut self) -> Result<()> { FuzzProject::init(self, self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; Ok(()) } } ``` -------------------------------- ### Error Context Stack Example Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md Illustrates how error context information is presented, showing a chain of causes leading to the main error. ```text Error: Fuzz target exited with Exited(1) Caused by: 0: Some useful context 1: More specific information 2: System error details ``` -------------------------------- ### Install cargo-fuzz Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/README.md Install the cargo-fuzz subcommand using cargo. Ensure you have a nightly Rust compiler and a C++11 compliant compiler. ```sh $ cargo install cargo-fuzz ``` -------------------------------- ### Run Fuzzing Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Starts fuzzing a target. Can specify custom corpora or pass libFuzzer options using `--`. ```bash cargo fuzz run my_target # Start fuzzing (default corpus) cargo fuzz run my_target corpus1 corpus2 # Custom corpora cargo fuzz run my_target -- -max_len=100 # libFuzzer options ``` -------------------------------- ### LibFuzzer Merge Command Example Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/cmin.md Illustrates the libFuzzer command used internally for corpus minimization, specifying the output directory and input corpus. ```bash libfuzzer -merge=1 ``` -------------------------------- ### Crash Output Example Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Illustrates the output format when a fuzz target crashes, including the failing input, debug output, and commands for reproduction and minimization. ```text ──────────────────────────────────────────────────────────────────────────────── Failing input: fuzz/artifacts/my_target/crash-abc123 Output of `std::fmt::Debug`: [Debug representation of input] Reproduce with: cargo fuzz run my_target fuzz/artifacts/my_target/crash-abc123 Minimize test case with: cargo fuzz tmin my_target fuzz/artifacts/my_target/crash-abc123 ──────────────────────────────────────────────────────────────────────────────── ``` -------------------------------- ### Fuzz Project Structure Example Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Illustrates the typical directory layout for a cargo-fuzz project, including source files, fuzz targets, and runtime-generated directories for corpus, artifacts, and coverage. ```directory my_crate/ ├── Cargo.toml ├── src/ └── fuzz/ # Fuzz project directory ├── Cargo.toml ├── .gitignore ├── fuzz_targets/ # Fuzz target implementations │ ├── fuzz_target_1.rs │ └── other_target.rs ├── corpus/ # Input corpora (created at runtime) │ ├── fuzz_target_1/ │ └── other_target/ ├── artifacts/ # Crash reproductions (created at runtime) │ ├── fuzz_target_1/ │ └── other_target/ └── coverage/ # Coverage data (created at runtime) ├── fuzz_target_1/ └── other_target/ ``` -------------------------------- ### Intermediate Learning Path for Cargo-Fuzz Configuration Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/INDEX.md A learning path for users who want to understand and configure cargo-fuzz. It guides through understanding build options and related types. ```text README.md ↓ configuration.md ↓ api-reference/build.md ↓ types.md#BuildOptions ↓ (Understand all options) ``` -------------------------------- ### LibFuzzer Arguments Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Example of passing libFuzzer specific arguments to a fuzz target using the `--` separator. ```bash cargo fuzz run my_target -- -max_len=100 -runs=1000 ``` -------------------------------- ### Debug print an input with custom features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/fmt.md This example shows how to debug print an input file while enabling custom features for the build. Specify the target, input path, and the desired features using the --features flag. ```bash cargo fuzz fmt my_target path/to/input.bin --features debug ``` -------------------------------- ### List All Fuzz Targets Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/list.md Use this command to display all fuzz targets configured in the current cargo fuzz project. No additional setup is required. ```bash cargo fuzz list ``` -------------------------------- ### Run Fuzzing with Custom Corpus Directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Provide a custom directory containing initial test cases for the fuzzer. This helps guide the fuzzing process. ```bash cargo fuzz run my_target fuzz/corpus/my_target ``` -------------------------------- ### Use Keyword Dictionary with LibFuzzer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Provide a keyword dictionary file to guide libFuzzer's input generation using the `-dict` option. This can significantly improve fuzzing efficiency for structured inputs. ```bash cargo fuzz run my_target -- -dict=keywords.txt ``` -------------------------------- ### Build for a Specific Target Triple Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Specify the target triple for compilation using the `--target` option. For example, `x86_64-unknown-linux-gnu`. ```bash cargo fuzz build --target=x86_64-unknown-linux-gnu ``` -------------------------------- ### Basic Cargo Fuzz Workflow Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Demonstrates the fundamental steps for setting up and running a fuzzing project. ```bash # 1. Initialize project cargo fuzz init # 2. Add more targets as needed cargo fuzz add my_parser cargo fuzz add url_handler # 3. List targets cargo fuzz list # 4. Run fuzzer cargo fuzz run my_parser # 5. When crash found, minimize it cargo fuzz tmin my_parser fuzz/artifacts/my_parser/crash-abc # 6. Generate coverage cargo fuzz coverage my_parser ``` -------------------------------- ### Initialize with Custom Fuzz Directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/init.md Specifies a custom path for the fuzzing project directory instead of the default 'fuzz/'. Ensure the path is valid and accessible. ```bash cargo fuzz init --fuzz-dir custom_fuzz_path ``` -------------------------------- ### Initialize Fuzz Project Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Initializes a new fuzz project. Use the `--target` flag to specify a custom target name. ```bash cargo fuzz init # Create fuzz project with first target cargo fuzz init --target my_fuzz # Custom target name ``` -------------------------------- ### Initialize with LibAFL Engine Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/init.md Initializes the fuzzing project to use the LibAFL fuzzing engine. This requires LibAFL to be correctly configured. ```bash cargo fuzz init --fuzz-engine libafl ``` -------------------------------- ### Minimize with specific sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/tmin.md Control which sanitizer is used during the build and minimization process. For example, use the 'leak' sanitizer. ```bash cargo fuzz tmin my_target crash.bin -s leak ``` -------------------------------- ### Cmin Failure Output Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/cmin.md Example of the output format when the corpus minimization process fails, indicating the exit status. ```bash Failed to minimize corpus: ``` -------------------------------- ### Build with Specific Features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md How to build a fuzz target with specific cargo features enabled. ```bash cargo fuzz build my_target --features my_feature ``` -------------------------------- ### Creating and executing FuzzProject Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md This code demonstrates the creation of a single `FuzzProject` instance and its subsequent execution. This approach ensures consistent state, a single source of truth for project paths, and easy cleanup. ```rust let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.exec_fuzz(self)?; ``` -------------------------------- ### Initializing Cargo-Fuzz in a Cargo Project Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md Shows the correct command and directory structure for initializing cargo-fuzz within a Rust project. ```bash cd /path/to/my_crate cargo fuzz init ``` -------------------------------- ### Build with All Features Enabled Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Builds the fuzz target with all available Cargo features enabled. Use the `--all-features` flag. ```bash cargo fuzz build my_target --all-features ``` -------------------------------- ### LibFuzzer Options Configuration Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Demonstrates how to pass specific options to the LibFuzzer engine, such as input length limits, execution time limits, timeouts, dictionaries, and run counts. ```bash # Limit input length cargo fuzz run my_target -- -max_len=256 # Limit execution time cargo fuzz run my_target -- -max_total_time=3600 # Set timeout per run cargo fuzz run my_target -- -timeout=10 # Use dictionary cargo fuzz run my_target -- -dict=keywords.txt # Combine multiple options cargo fuzz run my_target -- -max_len=512 -timeout=5 -runs=100000 ``` -------------------------------- ### Build Options Struct Composition Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md Demonstrates how common build options are composed using structs in Rust for consistent argument parsing across different commands. ```rust pub struct Build { pub build: BuildOptions, // Build options pub fuzz_dir_wrapper: FuzzDirWrapper, pub target: Option, // Custom field } ``` -------------------------------- ### Build with Address Sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Use the `-s` or `--sanitizer` flag to specify the desired sanitizer. The default is 'address'. ```bash cargo fuzz build -s address ``` -------------------------------- ### Reset Corpus and Rerun Target Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md If your fuzz target crashes immediately, it might be due to corrupted corpus data. Clean the corpus directory and rerun the target to start with fresh seeds. ```bash # Clean corpus and run with fresh seeds rm -rf fuzz/corpus/my_target cargo fuzz run my_target ``` -------------------------------- ### Build with Careful Mode Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Enable careful mode using `-c` or `--careful` for extra UB and initialization checks. This flag implies `--build-std`. ```bash cargo fuzz build -c ``` -------------------------------- ### Getting corpus path for a target Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md The `corpus_for` method takes a target name as a string slice to return the path to its input corpus. This string-based identification simplifies command-line parsing and directory naming. ```rust pub fn corpus_for(&self, target: &str) -> Result ``` -------------------------------- ### Build with Custom Fuzz Directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Specify a custom path to the fuzz project directory using the `--fuzz-dir` option. The default is `fuzz/`. ```bash cargo fuzz build --fuzz-dir=./my-fuzz-project ``` -------------------------------- ### Initialize Project Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Initializes a new cargo fuzz project. Use the --target flag to specify a name and --fuzz-engine to select the fuzzing engine (libfuzzer or libafl). ```bash cargo fuzz init [--target NAME] [--fuzz-engine libfuzzer|libafl] ``` -------------------------------- ### Build with Specific Cargo Features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Use the `--features` flag to enable specific Cargo features for the build. Features are provided as a comma-separated list. ```bash cargo fuzz build --features="my-feature,another-feature" ``` -------------------------------- ### Build All Fuzz Targets Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Use this command to build all fuzz targets defined in your project. This is the default behavior when no specific target is named. ```bash cargo fuzz build ``` -------------------------------- ### Run struct with composed BuildOptions Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md The `Run` struct demonstrates the composition pattern by embedding other structs like `BuildOptions` and `FuzzDirWrapper`. This allows for modularity and reusability of components. ```rust pub struct Run { pub build: BuildOptions, // Composed pub target: String, pub corpus: Vec, pub fuzz_dir_wrapper: FuzzDirWrapper, // Composed pub jobs: u16, pub args: Vec, } ``` -------------------------------- ### Build with Memory Sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md To use the memory sanitizer, you must also enable `--build-std`. This flag is required for the Memory sanitizer. ```bash cargo fuzz build -s memory --build-std ``` -------------------------------- ### Run All Tests Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/CONTRIBUTING.md Execute all tests for the cargo-fuzz project using the standard Cargo command. ```sh cargo test ``` -------------------------------- ### Initialize in a Separate Fuzzing Workspace Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/init.md Sets up the fuzzing project to be independent of the main project's workspace. This can be useful for managing dependencies separately. ```bash cargo fuzz init --fuzzing-workspace=true ``` -------------------------------- ### Build with a Custom Target Directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Specify a custom directory for build artifacts using the `--target-dir` option. ```bash cargo fuzz build --target-dir=./build-artifacts ``` -------------------------------- ### Build with No Default Cargo Features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Use `--no-default-features` to build without enabling the default Cargo features. ```bash cargo fuzz build --no-default-features ``` -------------------------------- ### Build with Custom Codegen Units Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Builds the fuzz target with a specified number of codegen units, which can significantly speed up build times. Use the `--codegen-units` flag followed by the desired number. ```bash cargo fuzz build my_target --codegen-units 16 ``` -------------------------------- ### Build for Windows DLLs without Main Include Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Use `--no-include-main-msvc` to prevent the inclusion of `/include:main` MSVC linker argument, useful for Windows DLLs. ```bash cargo fuzz build --no-include-main-msvc ``` -------------------------------- ### Initialize with Custom Target Name Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/init.md Initializes a fuzzing project and specifies a custom name for the first fuzz target. This is useful for organizing multiple fuzz targets. ```bash cargo fuzz init --target my_fuzz_target ``` -------------------------------- ### Show Line Coverage Report Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/coverage.md Generates an HTML report showing line-by-line code coverage. This requires the merged `.profdata` file and the instrumented build artifacts. ```bash llvm-cov show -format=html -o coverage_report target/{triple}/coverage/my_target \ -instr-profile=fuzz/coverage/my_target/coverage.profdata ``` -------------------------------- ### Build with Supported Sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md Use this command to build your fuzz target with the Address Sanitizer, which is widely supported. Ensure your Rust version and platform are compatible. ```bash # Use Address Sanitizer (most widely supported) cargo fuzz build my_target --sanitizer address ``` -------------------------------- ### Run Fuzzing with Multiple Corpus Directories Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Incorporate test cases from several custom directories to broaden the input space for fuzzing. ```bash cargo fuzz run my_target corpus1 corpus2 corpus3 ``` -------------------------------- ### Library Error Handling with Rust Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md Demonstrates how to handle potential errors when initializing a FuzzProject programmatically using Rust's Result type. ```rust match FuzzProject::new(fuzz_dir) { Ok(project) => { /* use project */ }, Err(e) => eprintln!("Fatal error: {:?}", e), } ``` -------------------------------- ### Constructing Cargo commands Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md The `cargo()` method constructs complete Cargo commands by sequentially adding necessary arguments such as manifest path, target triple, feature flags, rustflags, and environment variables. ```rust let mut cmd = self.cargo_cmd(manifest_path, target_triple)?; cmd.arg("--features").arg(&features); cmd.env("RUSTFLAGS", rustflags); ``` -------------------------------- ### Manifest Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/types.md Contains metadata about the parent crate, such as its name and Rust edition. ```APIDOC ## Struct Manifest ### Description Metadata about the parent crate. ### Fields - `crate_name` (String) - Name of the parent crate. - `edition` (Option) - Rust edition (e.g., "2021"). ### Public Methods - `parse() -> Result`: Parse metadata from current Cargo workspace. ``` -------------------------------- ### Cargo-Fuzz Project Directory Structure Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/INDEX.md Illustrates the expected file and directory layout for a cargo-fuzz project. This helps in understanding where different types of documentation and source files are located. ```tree /workspace/home/output/ ├── INDEX.md ← You are here ├── README.md ← Start here ├── types.md ← Type reference ├── configuration.md ← Config reference ├── errors.md ← Error reference ├── module-structure.md ← Architecture reference └── api-reference/ ├── README.md ← Commands overview ├── init.md ├── add.md ├── build.md ├── check.md ├── fmt.md ├── list.md ├── run.md ├── tmin.md ├── cmin.md └── coverage.md ``` -------------------------------- ### Display all cargo-fuzz commands Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/README.md View all available command-line options for cargo-fuzz. This is useful for discovering all functionalities and their specific arguments. ```sh $ cargo fuzz --help ``` -------------------------------- ### Generate Coverage with Custom LLVM Tools Path Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/coverage.md Generates code coverage using a custom path to the LLVM binary directory. Use this if your LLVM tools are not in the default system path. ```bash cargo fuzz coverage my_target --llvm-path /path/to/llvm/bin ``` -------------------------------- ### List Fuzz Targets in Custom Directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/list.md Specify a custom path to your fuzz project directory when listing targets. This is useful if your fuzz project is not located in the default location. ```bash cargo fuzz list --fuzz-dir custom_fuzz_path ``` -------------------------------- ### Search for Error Handling in Source Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md Use grep to search for error handling mechanisms like `bail` and `anyhow` within the `src/` directory of the cargo-fuzz project. This helps in locating specific error reporting logic. ```bash cd /workspace/home/cargo-fuzz grep -r "bail\|anyhow" src/ | grep -E ".*""" | head -20 ``` -------------------------------- ### Generating fuzz/Cargo.toml using a macro Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md Shows how the `toml_template!` macro is used to generate the content for the fuzz/Cargo.toml file, including project metadata. ```rust let mut cargo = fs::File::create(&cargo_toml)?; cargo.write_fmt(toml_template!( manifest.crate_name, manifest.edition, init.fuzz_engine, init.fuzzing_workspace ))?; ``` -------------------------------- ### Build Without Address Sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Builds the fuzz target with sanitizers explicitly disabled. Use the `--sanitizer none` flag. ```bash cargo fuzz build my_target --sanitizer none ``` -------------------------------- ### Custom Corpora Usage Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Illustrates how to specify multiple corpus directories or use existing artifact directories as input for fuzzing. ```bash # Use multiple corpus directories cargo fuzz run my_target corpus1/ corpus2/ # Use all inputs from artifacts directory cargo fuzz run my_target fuzz/artifacts/my_target/ ``` -------------------------------- ### Build with All Cargo Features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md The `--all-features` flag enables all available Cargo features. Note that this flag conflicts with `--no-default-features` and `--features`. ```bash cargo fuzz build --all-features ``` -------------------------------- ### Build with Verbose Output Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Enable verbose output from the cargo build process using the `-v` or `--verbose` flag. ```bash cargo fuzz build -v ``` -------------------------------- ### Build with Address Sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Builds a fuzz target with the Address Sanitizer enabled. This is the default sanitizer and provides memory error detection. ```bash cargo fuzz build my_target -s address ``` -------------------------------- ### Format Code with rustfmt Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/CONTRIBUTING.md Format the project's code according to the established style guidelines using the stable Rust channel's rustfmt. ```sh cargo +stable fmt ``` -------------------------------- ### Debug print an input from the artifacts directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/fmt.md Use this command to debug print a specific input file located in the artifacts directory. Ensure the target name and the path to the input file are correctly provided. ```bash cargo fuzz fmt my_target fuzz/artifacts/my_target/crash-1234567 ``` -------------------------------- ### Command Dispatch Implementation Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Illustrates how the `RunCommand` trait is implemented for the main `Command` enum to dispatch calls to specific command implementations. ```rust impl RunCommand for Command { fn run_command(&mut self) -> Result<()> { match self { Command::Init(x) => x.run_command(), Command::Add(x) => x.run_command(), // ... all commands } } } ``` -------------------------------- ### Advanced Learning Path for Cargo-Fuzz Internals Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/INDEX.md A detailed learning path for advanced users who want to understand the internal architecture and implementation of cargo-fuzz. It covers module structure, types, APIs, and error handling. ```text module-structure.md ↓ types.md ↓ api-reference/ ↓ errors.md ↓ (Full understanding) ``` -------------------------------- ### Minimize a failing input with default settings Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/tmin.md This is the most basic usage of the `tmin` command. It requires the target name and the path to the failing test case. ```bash cargo fuzz tmin my_target fuzz/artifacts/my_target/crash-abc123 ``` -------------------------------- ### Build with Release Mode and Debug Assertions Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md The default build mode is release with debug assertions enabled. This can be explicitly set using `-O` and `-a` flags. ```bash cargo fuzz build -O -a ``` -------------------------------- ### Parallel Coverage Processing with Rayon Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md Illustrates the use of Rayon for parallel processing of input files during coverage generation, utilizing a thread pool. ```rust let pool = rayon::ThreadPoolBuilder::new() .num_threads(effective_workers) .build()?; pool.install(|| { all_input_files .par_chunks(batch_size) .enumerate() .try_for_each(|(batch_idx, file_batch)| { ... }) }) ``` -------------------------------- ### Fuzzing with Build Modes Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Builds fuzz targets using development (D) or release (O) modes. Development is faster to compile but slower to run. ```bash cargo fuzz build my_target -D # Development (fast compile, slow run) cargo fuzz build my_target -O # Release (slow compile, fast run) ``` -------------------------------- ### Manage Fuzz Targets Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Commands to add new fuzz targets or list existing ones. ```bash cargo fuzz add parse_json # Create new target cargo fuzz list # List all targets ``` -------------------------------- ### Build with Custom Codegen Units Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Control the number of codegen units with the `--codegen-units` option. The default varies between release and dev modes. ```bash cargo fuzz build --codegen-units=4 ``` -------------------------------- ### Fuzzing with Features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Runs fuzzing with specified features enabled, either all features or a comma-separated list. ```bash cargo fuzz run my_target --all-features cargo fuzz run my_target --features "feature1,feature2" ``` -------------------------------- ### Build a Specific Fuzz Target Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Use this command to build a single, named fuzz target. Replace `my_target` with the actual name of your fuzz target. ```bash cargo fuzz build my_target ``` -------------------------------- ### Show Coverage Summary Report Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/coverage.md Generates a summary report of code coverage. This provides an overview of coverage metrics without detailed line-by-line information. ```bash llvm-cov report target/{triple}/coverage/my_target \ -instr-profile=fuzz/coverage/my_target/coverage.profdata ``` -------------------------------- ### Build Fuzz Targets Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Builds fuzz targets. Use `build` for all targets or specify a target name. `check` performs type-checking only. ```bash cargo fuzz build # Build all targets cargo fuzz build my_target # Build specific target cargo fuzz check my_target # Type-check only ``` -------------------------------- ### Build and Check Fuzz Targets Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Builds fuzz targets with instrumentation or performs a type check without building. Accepts optional TARGET and OPTIONS. ```bash cargo fuzz build [TARGET] [OPTIONS] ``` ```bash cargo fuzz check [TARGET] [OPTIONS] ``` -------------------------------- ### Minimize with fewer attempts (faster) Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/tmin.md Use a smaller number of minimization runs for a quicker, though potentially less thorough, minimization. ```bash cargo fuzz tmin my_target crash.bin -r 100 ``` -------------------------------- ### RustVersion Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/types.md Represents Rust compiler version information and supports comparison. ```APIDOC ## Struct RustVersion ### Description Rust compiler version information with comparison support. ### Fields - `major` (u32) - Major version (e.g., 1 in rustc 1.78.0). - `minor` (u32) - Minor version (e.g., 78 in rustc 1.78.0). - `nightly` (bool) - True if nightly build or RUSTC_BOOTSTRAP is set. ### Trait Implementations - `Ord`, `PartialOrd` — Compares by major then minor version. - `FromStr` — Parses from `rustc --version` output. - `Display` — (not implemented, use Debug). ### Public Methods - `discover() -> Result`: Detect current Rust compiler version. - `has_sanitizers_on_stable(&self) -> bool`: Check if sanitizers are stabilized on this version. ``` -------------------------------- ### BuildOptions Struct Definition Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/types.md Defines the complete set of configuration options for compiling fuzz targets. This struct is used to pass build-time settings to the fuzzing process. ```rust #[derive(Clone, Debug, Eq, PartialEq, Parser)] pub struct BuildOptions { // Optimization and build mode pub dev: bool, pub release: bool, pub debug_assertions: bool, pub verbose: bool, // Feature flags pub no_default_features: bool, pub all_features: bool, pub features: Option, // Sanitizer pub sanitizer: Sanitizer, // Standard library and build config pub build_std: bool, pub careful_mode: bool, pub triple: String, pub codegen_units: Option, pub strip_dead_code: Option>, // Advanced flags pub target_dir: Option, pub unstable_flags: Vec, pub coverage: bool, // Instrumentation pub no_cfg_fuzzing: bool, pub no_trace_compares: bool, pub trace_div: bool, pub trace_gep: bool, pub disable_branch_folding: Option>, pub no_include_main_msvc: bool, } ``` -------------------------------- ### Run Fuzzing with Parallel Jobs Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Utilize multiple CPU cores to speed up fuzzing by running concurrent jobs. Specify the number of jobs using the `-j` flag. ```bash cargo fuzz run my_target -j 4 ``` -------------------------------- ### Build Without Sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/errors.md Build your fuzz target without any sanitizer if compatibility issues arise or if sanitization is not required. This is a fallback option. ```bash # Or use no sanitizer cargo fuzz build my_target --sanitizer none ``` -------------------------------- ### Build without Default Features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/configuration.md Command to build a fuzz target without enabling its default cargo features. ```bash cargo fuzz check my_target --no-default-features ``` -------------------------------- ### cargo fuzz add Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/add.md Creates a new fuzz target within an existing `cargo fuzz` project. This command sets up the corpus, artifact directories, and a template file for the new target, and updates the `fuzz/Cargo.toml` manifest. ```APIDOC ## cargo fuzz add ### Description Creates a new fuzz target within an existing `cargo fuzz` project. This command sets up the corpus, artifact directories, and a template file for the new target, and updates the `fuzz/Cargo.toml` manifest. ### Method Not applicable (CLI command) ### Parameters #### Path Parameters None #### Query Parameters None #### Command Line Arguments - **target** (`String`) - Required - Name of the new fuzz target. - **--fuzz-dir** (`Option`) - Optional - Custom path to the fuzz project directory. ### Request Example ```bash cargo fuzz add parse_json cargo fuzz add my_target --fuzz-dir custom_fuzz_path ``` ### Response #### Success Response Returns `Ok(())` on success. #### Response Example None (CLI command) ### Error Handling Returns an error if: - The fuzz project does not exist or is not a valid cargo-fuzz manifest. - The target name already exists. - Unable to create corpus or artifact directories. - Unable to write target template file. ``` -------------------------------- ### Minimize from Custom Fuzz Directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/cmin.md Specify a custom path to the fuzz project directory when performing corpus minimization. ```bash cargo fuzz cmin my_target fuzz/corpus/my_target --fuzz-dir custom_fuzz_path ``` -------------------------------- ### Generate Coverage with Custom Fuzz Directory Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/coverage.md Generates code coverage using a custom path for the fuzz project directory. This is useful for non-standard project layouts. ```bash cargo fuzz coverage my_target --fuzz-dir custom_fuzz_path ``` -------------------------------- ### Build in Development Mode Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Builds the fuzz target in development mode, which disables optimizations for faster compilation times but results in slower execution. Use the `-D` flag. ```bash cargo fuzz build my_target -D ``` -------------------------------- ### Pass LibFuzzer Options Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/coverage.md Passes additional arguments directly to the libFuzzer executable. This allows fine-tuning libFuzzer's behavior during coverage generation. ```bash cargo fuzz coverage my_target -- -max_len=256 ``` -------------------------------- ### Pass libFuzzer options Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/tmin.md Include additional arguments that will be passed directly to the libFuzzer binary. Use `--` to separate `cargo fuzz` arguments from libFuzzer arguments. ```bash cargo fuzz tmin my_target crash.bin -- -timeout=10 ``` -------------------------------- ### Minimize with more attempts (more thorough) Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/tmin.md Increase the number of minimization runs to potentially achieve a more reduced test case, at the cost of longer execution time. ```bash cargo fuzz tmin my_target crash.bin -r 1000 ``` -------------------------------- ### Fuzz Project Cargo.toml Marker Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Shows the essential `[package.metadata]` section in the `fuzz/Cargo.toml` file that identifies a directory as a fuzz project. ```toml [package.metadata] cargo-fuzz = true ``` -------------------------------- ### Check All Fuzz Targets Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/check.md Checks all fuzz targets in the project. This is the default behavior when no specific target is provided. ```bash cargo fuzz check ``` -------------------------------- ### Build with Thread Sanitizer Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/build.md Builds a fuzz target with the Thread Sanitizer enabled. This sanitizer helps detect data races and other threading issues. ```bash cargo fuzz build my_target -s thread ``` -------------------------------- ### Building Rustflags string with conditional additions Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md This snippet shows how a `rustflags` string is built by appending various flags, including conditional additions based on environment variables like `RUSTFLAGS`. It's crucial for setting up sanitizers and coverage options. ```rust let mut rustflags = String::new(); rustflags.push_str(" -Cpasses=sancov-module"); // ... 20+ conditional additions if let Ok(other_flags) = env::var("RUSTFLAGS") { rustflags.push(' '); rustflags.push_str(&other_flags); } cmd.env("RUSTFLAGS", rustflags); ``` -------------------------------- ### Minimize with LibFuzzer Arguments Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/cmin.md Pass additional arguments directly to the libFuzzer executable during the minimization process, like setting the maximum input length. ```bash cargo fuzz cmin my_target -- -max_len=512 ``` -------------------------------- ### Pass LibFuzzer Options Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Pass additional arguments directly to the underlying libFuzzer engine. These arguments must follow the `--` separator. ```bash cargo fuzz run my_target -- -max_len=100 -runs=1000000 ``` -------------------------------- ### cargo fuzz list Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/list.md Lists all existing fuzz targets in the current 'cargo fuzz' project. It can also accept a custom path to the fuzz project directory. ```APIDOC ## cargo fuzz list ### Description Lists all existing fuzz targets in the current 'cargo fuzz' project. It can also accept a custom path to the fuzz project directory. ### Method Not applicable (CLI command) ### Endpoint Not applicable (CLI command) ### Parameters #### Query Parameters - **--fuzz-dir** (Option) - Optional - Custom path to the fuzz project directory ### Request Example ```bash # List all fuzz targets carpenter fuzz list # List all fuzz targets in a custom fuzz directory carpenter fuzz list --fuzz-dir custom_fuzz_path ``` ### Response #### Success Response (200) - **Output**: Alphabetically sorted list of target names printed to stdout. #### Response Example ``` my_fuzz_target parse_json url_parser ``` ### Error Handling - The fuzz project is not found. - Unable to read the fuzz project manifest. ``` -------------------------------- ### BuildOptions Struct Definition Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Defines the BuildOptions struct for comprehensive build configuration, including modes, features, sanitizers, and build settings. ```rust pub struct BuildOptions { // Mode pub dev: bool, pub release: bool, pub debug_assertions: bool, // Features pub features: Option, pub all_features: bool, pub no_default_features: bool, // Sanitizers pub sanitizer: Sanitizer, pub no_trace_compares: bool, pub trace_div: bool, pub trace_gep: bool, // Build config pub target_dir: Option, pub triple: String, pub codegen_units: Option, pub build_std: bool, pub careful_mode: bool, // Advanced pub coverage: bool, pub no_cfg_fuzzing: bool, pub verbose: bool, pub no_include_main_msvc: bool, pub unstable_flags: Vec, // ... } ``` -------------------------------- ### Minimize Test Cases and Corpus Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/README.md Commands for minimizing crash inputs or entire corpora. `fmt` shows debug output for an input. ```bash cargo fuzz fmt my_target crash.bin # Show Debug output cargo fuzz tmin my_target crash.bin # Minimize test case cargo fuzz cmin my_target # Minimize corpus ``` -------------------------------- ### Minimize with Sanitizer Option Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/cmin.md Run corpus minimization while specifying a particular sanitizer, such as 'thread'. ```bash cargo fuzz cmin my_target --sanitizer thread ``` -------------------------------- ### Check Target with Custom Features Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/check.md Checks a specific fuzz target and enables custom Cargo features. Use `--features` followed by the feature name(s). ```bash cargo fuzz check my_target --features my_feature ``` -------------------------------- ### Add Fuzz Targets Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/README.md Adds a new fuzz target to an existing project. Use 'cargo fuzz list' to see all targets. ```bash cargo fuzz add ``` ```bash cargo fuzz list ``` -------------------------------- ### Determining Sanitizer Flag based on Rust Version Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/module-structure.md Illustrates how to dynamically select the correct sanitizer flag ('-Csanitizer' or '-Zsanitizer') based on the detected Rust version's capabilities on stable. ```rust let rust_version = RustVersion::discover()?; let sanitizer_flag = match rust_version.has_sanitizers_on_stable() { true => "-Csanitizer", false => "-Zsanitizer", }; ``` -------------------------------- ### Parallel Fuzzing with LibFuzzer Arguments Source: https://github.com/rust-fuzz/cargo-fuzz/blob/main/_autodocs/api-reference/run.md Combine parallel job execution with specific libFuzzer arguments to optimize both speed and input generation strategy. ```bash cargo fuzz run my_target -j 8 -- -max_len=512 -runs=100000 ```