Skip to content

Commit

Permalink
add initial support for fuzz testing (#287)
Browse files Browse the repository at this point in the history
  • Loading branch information
smackysnacks authored May 27, 2024
1 parent 5a1e6b9 commit f7c8786
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 0 deletions.
4 changes: 4 additions & 0 deletions fuzz/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
target
corpus
artifacts
coverage
24 changes: 24 additions & 0 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "tiled-fuzz"
version = "0.0.0"
publish = false
edition = "2018"

[package.metadata]
cargo-fuzz = true

[dependencies]
libfuzzer-sys = "0.4"

[build-dependencies]
glob = "0.3.1"

[dependencies.tiled]
path = ".."

[[bin]]
name = "tiled"
path = "fuzz_targets/tiled.rs"
test = false
doc = false
bench = false
28 changes: 28 additions & 0 deletions fuzz/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use std::path::PathBuf;

use glob::glob;

macro_rules! p {
($($tokens: tt)*) => {
println!("cargo:warning={}", format!($($tokens)*))
}
}

fn main() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let corpus_dir = path.join("corpus/tiled");
std::fs::create_dir_all(&corpus_dir).expect("failed creating corpus dir");

let tmx_assets_path = path.join("../assets/*.tmx");
for entry in glob(tmx_assets_path.to_str().unwrap()).unwrap() {
match entry {
Ok(src) => {
let dest = corpus_dir.join(src.file_name().unwrap());
std::fs::copy(src, dest).unwrap();
}
Err(e) => {
p!("{:?}", e)
}
}
}
}
32 changes: 32 additions & 0 deletions fuzz/fuzz_targets/tiled.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#![no_main]

use libfuzzer_sys::fuzz_target;

use std::path::Path;

use tiled::{DefaultResourceCache, Loader, ResourceReader};

struct FuzzResourceReader<'a> {
data: &'a [u8],
}

impl<'a> FuzzResourceReader<'a> {
fn new(data: &'a [u8]) -> Self {
FuzzResourceReader { data }
}
}

impl<'a> ResourceReader for FuzzResourceReader<'a> {
type Resource = &'a [u8];
type Error = std::io::Error;

fn read_from(&mut self, _path: &Path) -> Result<Self::Resource, Self::Error> {
Ok(self.data)
}
}

fuzz_target!(|data: &[u8]| {
let mut loader =
Loader::with_cache_and_reader(DefaultResourceCache::new(), FuzzResourceReader::new(data));
let _ = loader.load_tmx_map("fuzz.tmx");
});

0 comments on commit f7c8786

Please sign in to comment.