// This file is part of SymCC.
//
// SymCC is free software: you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// SymCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// SymCC. If not, see .
use anyhow::{bail, ensure, Context, Result};
use regex::Regex;
use std::cmp;
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File};
use std::io::{self, Read};
use std::os::unix::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str;
use std::time::{Duration, Instant};
const TIMEOUT: u32 = 90;
/// Replace the first '@@' in the given command line with the input file.
fn insert_input_file, P: AsRef>(
command: &[S],
input_file: P,
) -> Vec {
let mut fixed_command: Vec = command.iter().map(|s| s.into()).collect();
if let Some(at_signs) = fixed_command.iter_mut().find(|s| *s == "@@") {
*at_signs = input_file.as_ref().as_os_str().to_os_string();
}
fixed_command
}
/// A coverage map as used by AFL.
pub struct AflMap {
data: Option>,
}
impl AflMap {
/// Create an empty map.
pub fn new() -> AflMap {
AflMap { data: None }
}
/// Load a map from disk.
pub fn load(path: impl AsRef) -> Result {
let data = fs::read(&path).with_context(|| {
format!(
"Failed to read the AFL bitmap that \
afl-showmap should have generated at {}",
path.as_ref().display()
)
})?;
Ok(AflMap { data: Some(data) })
}
/// Merge two coverage maps in place.
fn merge_vec(data: &mut Vec, new_data: Vec) -> Result {
let mut interesting = false;
ensure!(
data.len() == new_data.len(),
"Coverage maps must have the same size ({} and {})",
data.len(),
new_data.len(),
);
for (known, new) in data.iter_mut().zip(new_data.iter()) {
if *known != (*known | new) {
*known |= new;
interesting = true;
}
}
Ok(interesting)
}
/// Merge with another coverage map in place.
///
/// Return true if the map has changed, i.e., if the other map yielded new
/// coverage.
pub fn merge(&mut self, other: AflMap) -> Result {
match (&mut self.data, other.data) {
(Some(data), Some(new_data)) => AflMap::merge_vec(data, new_data),
(Some(_), None) => Ok(false),
(None, Some(new_data)) => {
self.data = Some(new_data);
Ok(true)
}
(None, None) => Ok(false),
}
}
}
/// Score of a test case.
///
/// We use the lexical comparison implemented by the derived implementation of
/// Ord in order to compare according to various criteria.
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct TestcaseScore {
/// First criterion: new coverage
new_coverage: bool,
/// Second criterion: being derived from seed inputs
derived_from_seed: bool,
/// Third criterion: size (smaller is better)
file_size: i128,
/// Fourth criterion: name (containing the ID)
base_name: OsString,
}
impl TestcaseScore {
/// Score a test case.
///
/// If anything goes wrong, return the minimum score.
fn new(t: impl AsRef) -> Self {
let size = match fs::metadata(&t) {
Err(e) => {
// Has the file disappeared?
log::warn!(
"Warning: failed to score test case {}: {}",
t.as_ref().display(),
e
);
return TestcaseScore::minimum();
}
Ok(meta) => meta.len(),
};
let name: OsString = match t.as_ref().file_name() {
None => return TestcaseScore::minimum(),
Some(n) => n.to_os_string(),
};
let name_string = name.to_string_lossy();
TestcaseScore {
new_coverage: name_string.ends_with("+cov"),
derived_from_seed: name_string.contains("orig:"),
file_size: -i128::from(size),
base_name: name,
}
}
/// Return the smallest possible score.
fn minimum() -> TestcaseScore {
TestcaseScore {
new_coverage: false,
derived_from_seed: false,
file_size: std::i128::MIN,
base_name: OsString::from(""),
}
}
}
/// A directory that we can write test cases to.
pub struct TestcaseDir {
/// The path to the (existing) directory.
pub path: PathBuf,
/// The next free ID in this directory.
current_id: u64,
}
impl TestcaseDir {
/// Create a new test-case directory in the specified location.
///
/// The parent directory must exist.
pub fn new(path: impl AsRef) -> Result {
let dir = TestcaseDir {
path: path.as_ref().into(),
current_id: 0,
};
fs::create_dir(&dir.path)
.with_context(|| format!("Failed to create directory {}", dir.path.display()))?;
Ok(dir)
}
}
/// Copy a test case to a directory, using the parent test case's name to derive
/// the new name.
pub fn copy_testcase(
testcase: impl AsRef,
target_dir: &mut TestcaseDir,
parent: impl AsRef,
) -> Result<()> {
let orig_name = parent
.as_ref()
.file_name()
.expect("The input file does not have a name")
.to_string_lossy();
ensure!(
orig_name.starts_with("id:"),
"The name of test case {} does not start with an ID",
parent.as_ref().display()
);
if let Some(orig_id) = orig_name.get(3..9) {
let new_name = format!("id:{:06},src:{}", target_dir.current_id, &orig_id);
let target = target_dir.path.join(new_name);
log::debug!("Creating test case {}", target.display());
fs::copy(testcase.as_ref(), target).with_context(|| {
format!(
"Failed to copy the test case {} to {}",
testcase.as_ref().display(),
target_dir.path.display()
)
})?;
target_dir.current_id += 1;
} else {
bail!(
"Test case {} does not contain a proper ID",
parent.as_ref().display()
);
}
Ok(())
}
/// Information on the run-time environment.
///
/// This should not change during execution.
#[derive(Debug)]
pub struct AflConfig {
/// The location of the afl-showmap program.
show_map: PathBuf,
/// The command that AFL uses to invoke the target program.
target_command: Vec,
/// Do we need to pass data to standard input?
use_standard_input: bool,
/// Are we using AFL's QEMU mode?
use_qemu_mode: bool,
/// The fuzzer instance's queue of test cases.
queue: PathBuf,
}
/// Possible results of afl-showmap.
pub enum AflShowmapResult {
/// The map was created successfully.
Success(Box),
/// The target timed out or failed to execute.
Hang,
/// The target crashed.
Crash,
}
impl AflConfig {
/// Read the AFL configuration from a fuzzer instance's output directory.
pub fn load(fuzzer_output: impl AsRef) -> Result {
let afl_stats_file_path = fuzzer_output.as_ref().join("fuzzer_stats");
let mut afl_stats_file = File::open(&afl_stats_file_path).with_context(|| {
format!(
"Failed to open the fuzzer's stats at {}",
afl_stats_file_path.display()
)
})?;
let mut afl_stats = String::new();
afl_stats_file
.read_to_string(&mut afl_stats)
.with_context(|| {
format!(
"Failed to read the fuzzer's stats at {}",
afl_stats_file_path.display()
)
})?;
let afl_command: Vec<_> = afl_stats
.lines()
.find(|&l| l.starts_with("command_line"))
.expect("The fuzzer stats don't contain the command line")
.splitn(2, ':')
.nth(1)
.expect("The fuzzer stats follow an unknown format")
.trim()
.split_whitespace()
.collect();
let afl_target_command: Vec<_> = afl_command
.iter()
.skip_while(|s| **s != "--")
.map(OsString::from)
.collect();
let afl_binary_dir = Path::new(
afl_command
.get(0)
.expect("The AFL command is unexpectedly short"),
)
.parent()
.unwrap();
Ok(AflConfig {
show_map: afl_binary_dir.join("afl-showmap"),
use_standard_input: !afl_target_command.contains(&"@@".into()),
use_qemu_mode: afl_command.contains(&"-Q".into()),
target_command: afl_target_command,
queue: fuzzer_output.as_ref().join("queue"),
})
}
/// Return the most promising unseen test case of this fuzzer.
pub fn best_new_testcase(&self, seen: &HashSet) -> Result