Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

24.9 KB
Raw Blame
// ©AngelaMos | 2026
// replay.rs

use std::path::{Path, PathBuf};
use std::time::Duration;

use lisdex_core::process::{self, CommandSpec};
use serde::Deserialize;

use crate::instrument::Instrumentation;

pub const COMPILE_COMMANDS: &str = "compile_commands.json";
pub const REPLAY_TIMEOUT_SECS: u64 = 600;

const LAUNCHERS: [&str; 4] = ["ccache", "distcc", "sccache", "icecc"];
const FRONTEND_ONLY_ARGS: [&str; 2] = ["-cc1", "-cc1as"];
const CXX_EXTENSIONS: [&str; 6] = ["cpp", "cxx", "cc", "c++", "C", "CPP"];
const OUTPUT_FLAG: &str = "-o";
const LIBTOOL_STAMP_EXTENSION: &str = "lo";
const LIBTOOL_OBJECT_DIR: &str = ".libs";

// A file the library links INTO, as opposed to a program the build runs. `libtiff.so.6.0.2`
// is why every dot-separated part is checked rather than only the last one.
const LIBRARY_EXTENSIONS: [&str; 7] = ["o", "obj", "a", "so", "lo", "la", "dylib"];

#[derive(Debug, thiserror::Error)]
pub enum ReplayError {
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("{path} is not a valid compilation database: {source}")]
    Malformed {
        path: PathBuf,
        source: serde_json::Error,
    },
    #[error("process error: {0}")]
    Process(#[from] process::ProcessError),
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct CompileCommand {
    pub directory: String,
    pub file: String,
    #[serde(default)]
    pub command: Option<String>,
    #[serde(default)]
    pub arguments: Option<Vec<String>>,
    #[serde(default)]
    pub output: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ReplayReport {
    pub attempted: usize,
    pub skipped: usize,
    pub restamped: usize,
    pub failures: Vec<String>,
}

impl ReplayReport {
    #[must_use]
    pub fn succeeded(&self) -> bool {
        self.attempted > 0 && self.failures.is_empty()
    }
}

// The shell's default IFS, which is these three and nothing else. `char::is_whitespace` is
// Unicode-aware, so it split a token on U+00A0 that /bin/sh keeps whole.
const FIELD_SEPARATORS: [char; 3] = [' ', '\t', '\n'];

// Inside double quotes a backslash is only special before one of these, or a newline.
// Everywhere else it stands for itself, which is why `-DP="C:\dir\file"` must survive intact
// instead of replaying as `-DP=C:dirfile`.
const ESCAPABLE_IN_DOUBLE_QUOTES: [char; 4] = ['$', '`', '"', '\\'];

// Differential-tested against /bin/sh over a corpus of compile-command shapes. The oracle is
// only valid where parsing is pure word-splitting and quote removal, so the corpus carries no
// expansion, glob or operator: this splits words, it is deliberately NOT a shell.
//
// None means the command cannot be split at all because a quote is never closed. The shell
// calls that a syntax error and exits 2, and a caller that guessed instead would replay a
// command other than the one that was captured.
#[must_use]
pub fn tokenize(command: &str) -> Option<Vec<String>> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut started = false;
    let mut single = false;
    let mut double = false;
    let mut chars = command.chars().peekable();

    while let Some(character) = chars.next() {
        match character {
            '\\' if single => current.push('\\'),
            '\\' if double => match chars.peek() {
                Some('\n') => {
                    chars.next();
                }
                Some(next) if ESCAPABLE_IN_DOUBLE_QUOTES.contains(next) => {
                    current.push(*next);
                    chars.next();
                }
                _ => current.push('\\'),
            },
            '\\' => match chars.next() {
                Some('\n') | None => {}
                Some(escaped) => {
                    current.push(escaped);
                    started = true;
                }
            },
            '\'' if !double => {
                single = !single;
                started = true;
            }
            '"' if !single => {
                double = !double;
                started = true;
            }
            character if FIELD_SEPARATORS.contains(&character) && !single && !double => {
                if started {
                    tokens.push(std::mem::take(&mut current));
                    started = false;
                }
            }
            character => {
                current.push(character);
                started = true;
            }
        }
    }
    if single || double {
        return None;
    }
    if started {
        tokens.push(current);
    }
    Some(tokens)
}

#[must_use]
pub fn argv(entry: &CompileCommand) -> Option<Vec<String>> {
    match (&entry.arguments, &entry.command) {
        (Some(arguments), _) if !arguments.is_empty() => Some(arguments.clone()),
        (_, Some(command)) => tokenize(command),
        _ => Some(Vec::new()),
    }
}

fn strip_launchers(argv: Vec<String>) -> Vec<String> {
    let mut argv = argv;
    while let Some(first) = argv.first() {
        let name = Path::new(first)
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_default();
        if LAUNCHERS.contains(&name.as_str()) {
            argv.remove(0);
        } else {
            break;
        }
    }
    argv
}

#[must_use]
pub fn is_cxx(file: &str) -> bool {
    Path::new(file)
        .extension()
        .is_some_and(|ext| CXX_EXTENSIONS.iter().any(|known| *known == ext))
}

#[must_use]
pub fn output_of(entry: &CompileCommand, argv: &[String]) -> Option<PathBuf> {
    let named = entry.output.clone().or_else(|| {
        argv.iter()
            .position(|arg| arg == OUTPUT_FLAG)
            .and_then(|at| argv.get(at + 1))
            .cloned()
    })?;
    let path = PathBuf::from(named);
    Some(if path.is_absolute() {
        path
    } else {
        Path::new(&entry.directory).join(path)
    })
}

#[must_use]
pub fn names_a_library(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| {
            name.split('.')
                .skip(1)
                .any(|part| LIBRARY_EXTENSIONS.contains(&part))
        })
}

// The uninstrumented prepass built this path into a program, and the build itself RUNS it:
// sqlite3's `mksqlite3h.tcl` execs `$PWD/mksourceid` to stamp a source id into sqlite3.h.
// Replaying that command with LTO instrumentation replaced the ELF with LLVM bitcode, which
// nothing can exec, so the relink died on a codegen step 500 seconds into the build. A host
// tool is evidence of itself: the prepass left an executable ELF whose name is not a library.
#[must_use]
pub fn is_a_host_tool(path: &Path) -> bool {
    !names_a_library(path)
        && lisdex_core::process::is_executable(path)
        && crate::artifact::is_elf(path)
}

#[must_use]
pub fn rewrite(entry: &CompileCommand, instrumentation: &Instrumentation) -> Option<CommandSpec> {
    let argv = strip_launchers(argv(entry)?);
    if argv
        .iter()
        .any(|arg| FRONTEND_ONLY_ARGS.contains(&arg.as_str()))
    {
        return None;
    }
    if output_of(entry, &argv).is_some_and(|output| is_a_host_tool(&output)) {
        return None;
    }
    let (_, rest) = argv.split_first()?;
    let compiler = if is_cxx(&entry.file) {
        &instrumentation.toolchain.cxx
    } else {
        &instrumentation.toolchain.cc
    };
    Some(
        CommandSpec::new(compiler)
            .args(rest.to_vec())
            .args(instrumentation.cflags.clone())
            .cwd(&entry.directory)
            .envs(instrumentation.envs()),
    )
}

// Replay overwrites the object in place, and under libtool the archive does NOT depend on
// that object: it depends on the `.lo` stamp beside it. Measured on sqlite3, where replay
// wrote an instrumented sqlite3.o at 03:44 while .libs/libsqlite3.a still held the
// uninstrumented ELF from 03:43, and the relink re-archived nothing because the stamp had
// not moved - so the library reported zero sanitizer symbols and the tier was rejected.
// Refreshing the stamp makes the relink re-run `llvm-ar` over what replay actually produced.
#[must_use]
pub fn libtool_stamp_of(output: &Path) -> Option<PathBuf> {
    let stem = output.file_stem()?;
    let beside = output.with_extension(LIBTOOL_STAMP_EXTENSION);
    if beside.is_file() {
        return Some(beside);
    }
    // A PIC object lives in `.libs/`, one level below the stamp libtool keeps for it.
    let parent = output.parent()?;
    if parent.file_name()? != LIBTOOL_OBJECT_DIR {
        return None;
    }
    let above = parent
        .parent()?
        .join(stem)
        .with_extension(LIBTOOL_STAMP_EXTENSION);
    above.is_file().then_some(above)
}

// Rewriting the bytes is what moves the modification time; there is no portable touch in
// std, and a libtool stamp is a couple of hundred bytes of text.
fn refresh(stamp: &Path) -> std::io::Result<()> {
    let contents = std::fs::read(stamp)?;
    std::fs::write(stamp, contents)
}

pub fn load(path: &Path) -> Result<Vec<CompileCommand>, ReplayError> {
    let text = std::fs::read_to_string(path).map_err(|source| ReplayError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    serde_json::from_str(&text).map_err(|source| ReplayError::Malformed {
        path: path.to_path_buf(),
        source,
    })
}

pub fn replay(
    entries: &[CompileCommand],
    instrumentation: &Instrumentation,
) -> Result<ReplayReport, ReplayError> {
    let timeout = Duration::from_secs(REPLAY_TIMEOUT_SECS);
    let mut report = ReplayReport::default();
    for entry in entries {
        // Skipped and unsplittable are not the same thing, and collapsing them hides the
        // second: one is a command lisdex chose not to replay, the other is one it could not
        // read. A database it cannot read means an incomplete replay, and an incomplete
        // replay produces a library that is only partly instrumented.
        let Some(words) = argv(entry) else {
            report.failures.push(format!(
                "{}: the recorded command cannot be split into words because a quote is never \
                 closed, so replaying it would compile something other than what was captured",
                entry.file
            ));
            continue;
        };
        let Some(spec) = rewrite(entry, instrumentation) else {
            report.skipped += 1;
            continue;
        };
        report.attempted += 1;
        let execution = process::run(&spec, timeout)?;
        if execution.success {
            if let Some(stamp) = output_of(entry, &words)
                .as_deref()
                .and_then(libtool_stamp_of)
                && refresh(&stamp).is_ok()
            {
                report.restamped += 1;
            }
        } else {
            report
                .failures
                .push(format!("{}: {}", entry.file, execution.tail(20)));
        }
    }
    Ok(report)
}

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

    fn entry(command: &str, file: &str) -> CompileCommand {
        CompileCommand {
            directory: "/build".to_owned(),
            file: file.to_owned(),
            command: Some(command.to_owned()),
            arguments: None,
            output: None,
        }
    }

    fn split(command: &str) -> Vec<String> {
        tokenize(command).unwrap()
    }

    #[test]
    fn tokenizer_splits_on_whitespace() {
        assert_eq!(split("cc -c png.c"), vec!["cc", "-c", "png.c"]);
    }

    #[test]
    fn tokenizer_keeps_quoted_arguments_whole() {
        assert_eq!(
            split(r#"cc -DNAME="lib png" -c png.c"#),
            vec!["cc", "-DNAME=lib png", "-c", "png.c"]
        );
    }

    #[test]
    fn tokenizer_honours_single_quotes_and_backslashes() {
        assert_eq!(
            split(r#"cc -DPATH='/a b/c' -DQ=\"x\" png.c"#),
            vec!["cc", "-DPATH=/a b/c", "-DQ=\"x\"", "png.c"]
        );
    }

    #[test]
    fn tokenizer_preserves_empty_quoted_arguments() {
        assert_eq!(
            split(r#"cc -DEMPTY="" png.c"#),
            vec!["cc", "-DEMPTY=", "png.c"]
        );
    }

    #[test]
    fn a_windows_path_in_double_quotes_keeps_its_backslashes() {
        assert_eq!(
            split(r#"cc -DP="C:\dir\file""#),
            vec!["cc", r"-DP=C:\dir\file"],
            "the shell only treats a backslash as an escape inside double quotes when it \
             precedes one of $ ` \" or a backslash, so this replayed as -DP=C:dirfile"
        );
    }

    #[test]
    fn the_four_characters_a_backslash_does_escape_in_double_quotes_are_escaped() {
        assert_eq!(split(r#"cc "a\"b""#), vec!["cc", r#"a"b"#]);
        assert_eq!(split(r#"cc "a\\b""#), vec!["cc", r"a\b"]);
        assert_eq!(split(r#"cc "a\$b""#), vec!["cc", "a$b"]);
        assert_eq!(split("cc \"a\\`b\""), vec!["cc", "a`b"]);
    }

    #[test]
    fn a_backslash_inside_single_quotes_is_never_an_escape() {
        assert_eq!(
            split(r"cc -DP='C:\dir\file'"),
            vec!["cc", r"-DP=C:\dir\file"]
        );
    }

    #[test]
    fn only_the_shells_own_field_separators_split_a_word() {
        assert_eq!(
            split("cc -DA=one\u{00a0}two"),
            vec!["cc", "-DA=one\u{00a0}two"],
            "IFS is space, tab and newline; char::is_whitespace is Unicode-aware and split \
             this token in half"
        );
        assert_eq!(split("cc\t-c\nfoo.c"), vec!["cc", "-c", "foo.c"]);
    }

    #[test]
    fn a_command_whose_quote_is_never_closed_is_refused_rather_than_guessed() {
        assert_eq!(tokenize("cc -o 'unterminated"), None);
        assert_eq!(tokenize(r#"cc -o "unterminated"#), None);
        assert!(
            tokenize("cc -o 'closed' fine").is_some(),
            "a balanced command still splits"
        );
    }

    #[test]
    fn a_command_that_cannot_be_split_is_a_failure_and_not_a_skip() {
        let report = replay(
            &[entry("cc -c 'unterminated.c", "unterminated.c")],
            &Instrumentation::instrumented(),
        )
        .unwrap();
        assert_eq!(report.attempted, 0);
        assert_eq!(
            report.skipped, 0,
            "counting this as skipped would say lisdex chose not to replay it, when it could \
             not read it"
        );
        assert_eq!(report.failures.len(), 1);
        assert!(report.failures[0].contains("quote is never closed"));
    }

    #[test]
    fn arguments_are_preferred_over_command() {
        let mut item = entry("cc -c wrong.c", "png.c");
        item.arguments = Some(vec!["cc".to_owned(), "-c".to_owned(), "png.c".to_owned()]);
        assert_eq!(argv(&item).unwrap(), vec!["cc", "-c", "png.c"]);
    }

    #[test]
    fn the_compiler_is_replaced_but_every_other_argument_survives() {
        let spec = rewrite(
            &entry(
                "/usr/bin/gcc -O2 -DHAVE_CONFIG_H -c png.c -o png.o",
                "png.c",
            ),
            &Instrumentation::instrumented(),
        )
        .unwrap();
        assert_eq!(spec.program, "afl-clang-lto");
        assert!(spec.args.contains(&"-DHAVE_CONFIG_H".to_owned()));
        assert!(spec.args.contains(&"-o".to_owned()));
        assert!(spec.args.contains(&"png.o".to_owned()));
    }

    #[test]
    fn cxx_sources_get_the_cxx_compiler() {
        let spec = rewrite(
            &entry("g++ -c poppler.cc -o poppler.o", "poppler.cc"),
            &Instrumentation::instrumented(),
        )
        .unwrap();
        assert_eq!(spec.program, "afl-clang-lto++");
    }

    #[test]
    fn c_sources_get_the_c_compiler() {
        assert!(!is_cxx("png.c"));
        assert!(is_cxx("poppler.cpp"));
        assert!(is_cxx("Object.cc"));
    }

    #[test]
    fn compiler_launchers_are_stripped() {
        let spec = rewrite(
            &entry("/usr/bin/ccache /usr/bin/cc -c png.c", "png.c"),
            &Instrumentation::instrumented(),
        )
        .unwrap();
        assert_eq!(spec.program, "afl-clang-lto");
        assert!(!spec.args.iter().any(|arg| arg.contains("ccache")));
        assert!(!spec.args.iter().any(|arg| arg.ends_with("/cc")));
    }

    #[test]
    fn instrumentation_flags_are_appended_after_the_original_arguments() {
        let spec = rewrite(
            &entry("cc -O0 -c png.c", "png.c"),
            &Instrumentation::instrumented(),
        )
        .unwrap();
        let original = spec.args.iter().position(|arg| arg == "-O0").unwrap();
        let ours = spec.args.iter().position(|arg| arg == "-O2").unwrap();
        assert!(ours > original);
    }

    #[test]
    fn the_original_working_directory_is_preserved() {
        let spec = rewrite(
            &entry("cc -c png.c", "png.c"),
            &Instrumentation::instrumented(),
        )
        .unwrap();
        assert_eq!(spec.cwd, Some(PathBuf::from("/build")));
    }

    #[test]
    fn sanitizer_environment_reaches_every_replayed_command() {
        let spec = rewrite(
            &entry("cc -c png.c", "png.c"),
            &Instrumentation::instrumented(),
        )
        .unwrap();
        assert!(spec.has_env(crate::instrument::ENV_AFL_USE_ASAN));
    }

    #[test]
    fn intercepted_frontend_invocations_are_skipped_not_replayed() {
        let item = entry(
            "/usr/lib/llvm-20/bin/clang -cc1 -triple x86_64 -emit-obj -o x.o x.c",
            "x.c",
        );
        assert!(
            rewrite(&item, &Instrumentation::instrumented()).is_none(),
            "a driver cannot replay clang's internal -cc1 invocation"
        );
    }

    #[test]
    fn an_empty_command_is_skipped_rather_than_run() {
        let item = CompileCommand {
            directory: "/build".to_owned(),
            file: "png.c".to_owned(),
            command: Some(String::new()),
            arguments: None,
            output: None,
        };
        assert!(rewrite(&item, &Instrumentation::instrumented()).is_none());
    }

    #[test]
    fn a_real_compilation_database_round_trips() {
        let path = lisdex_core::scratch::path("ccdb-roundtrip").with_extension("json");
        std::fs::write(
            &path,
            r#"[{"directory":"/build","command":"cc -c /src/png.c -o png.o","file":"/src/png.c"},
                {"directory":"/build","arguments":["cc","-c","/src/pngread.c"],"file":"/src/pngread.c","output":"pngread.o"}]"#,
        )
        .unwrap();
        let entries = load(&path).unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[1].output.as_deref(), Some("pngread.o"));
        assert_eq!(argv(&entries[1]).unwrap()[0], "cc");
    }

    #[test]
    fn a_malformed_database_is_reported_not_ignored() {
        let path = lisdex_core::scratch::path("ccdb-malformed").with_extension("json");
        std::fs::write(&path, "{ not json").unwrap();
        assert!(matches!(load(&path), Err(ReplayError::Malformed { .. })));
    }

    #[test]
    fn a_report_with_no_attempts_is_not_a_success() {
        assert!(!ReplayReport::default().succeeded());
        let report = ReplayReport {
            attempted: 3,
            skipped: 0,
            restamped: 0,
            failures: Vec::new(),
        };
        assert!(report.succeeded());
    }

    fn host_tool_fixture(label: &str, name: &str, executable: bool, elf: bool) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let dir = lisdex_core::scratch::path(&format!("replay-{label}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join(name);
        let body: &[u8] = if elf {
            b"\x7fELF\x02\x01\x01"
        } else {
            b"BC\xc0\xde"
        };
        std::fs::write(&path, body).unwrap();
        let mode = if executable { 0o755 } else { 0o644 };
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
        path
    }

    fn command_writing(output: &Path) -> CompileCommand {
        CompileCommand {
            directory: output.parent().unwrap().display().to_string(),
            file: "tool/mksourceid.c".to_owned(),
            command: Some(format!("cc -O2 -o {} mksourceid.c", output.display())),
            arguments: None,
            output: None,
        }
    }

    #[test]
    fn a_program_the_build_runs_is_left_as_the_prepass_built_it() {
        let tool = host_tool_fixture("hosttool", "mksourceid", true, true);
        assert!(is_a_host_tool(&tool));
        assert!(
            rewrite(&command_writing(&tool), &Instrumentation::default()).is_none(),
            "sqlite3 execs $PWD/mksourceid from mksqlite3h.tcl, and replaying it as LTO \
             bitcode killed the relink 500 seconds into the build"
        );
    }

    #[test]
    fn a_shared_library_is_still_instrumented_even_though_it_is_executable() {
        for (index, name) in ["libtiff.so.6.0.2", "libz.so", "libarchive.a", "parse.o"]
            .into_iter()
            .enumerate()
        {
            let artifact = host_tool_fixture(&format!("libartifact{index}"), name, true, true);
            assert!(
                !is_a_host_tool(&artifact),
                "{name} is what the fuzzer needs instrumented, and shared objects carry the \
                 executable bit too"
            );
            assert!(rewrite(&command_writing(&artifact), &Instrumentation::default()).is_some());
        }
    }

    #[test]
    fn a_path_the_prepass_never_built_is_replayed_normally() {
        let dir = lisdex_core::scratch::path("replay-absent");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let absent = dir.join("mksourceid");
        assert!(!is_a_host_tool(&absent));
        assert!(rewrite(&command_writing(&absent), &Instrumentation::default()).is_some());
    }

    #[test]
    fn a_non_elf_file_of_the_same_name_is_not_mistaken_for_a_program() {
        let bitcode = host_tool_fixture("bitcodetool", "mksourceid", true, false);
        assert!(
            !is_a_host_tool(&bitcode),
            "an executable bit on LLVM bitcode is not a runnable program, and treating it as \
             one would skip the very command that has to be replayed to repair it"
        );
    }

    #[test]
    fn the_stamp_an_archive_depends_on_is_found_beside_the_object() {
        let dir = lisdex_core::scratch::path("replay-stamp");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let object = dir.join("sqlite3.o");
        let stamp = dir.join("sqlite3.lo");
        std::fs::write(&object, b"BC\xc0\xde").unwrap();
        std::fs::write(&stamp, b"# libtool object\npic_object=None\n").unwrap();
        assert_eq!(libtool_stamp_of(&object).as_deref(), Some(stamp.as_path()));
    }

    #[test]
    fn a_pic_object_finds_the_stamp_one_directory_above_it() {
        let dir = lisdex_core::scratch::path("replay-picstamp");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join(LIBTOOL_OBJECT_DIR)).unwrap();
        let object = dir.join(LIBTOOL_OBJECT_DIR).join("sqlite3.o");
        let stamp = dir.join("sqlite3.lo");
        std::fs::write(&object, b"BC\xc0\xde").unwrap();
        std::fs::write(&stamp, b"# libtool object\n").unwrap();
        assert_eq!(
            libtool_stamp_of(&object).as_deref(),
            Some(stamp.as_path()),
            "libtool keeps the stamp beside the build directory, not beside the PIC object"
        );
    }

    #[test]
    fn a_build_with_no_libtool_has_no_stamp_to_refresh() {
        let dir = lisdex_core::scratch::path("replay-nostamp");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let object = dir.join("png.o");
        std::fs::write(&object, b"BC\xc0\xde").unwrap();
        assert!(
            libtool_stamp_of(&object).is_none(),
            "cmake and plain make targets have no .lo, and inventing one would create a file \
             their makefiles never asked for"
        );
    }

    #[test]
    fn refreshing_a_stamp_moves_it_ahead_of_the_object_replay_rewrote() {
        let dir = lisdex_core::scratch::path("replay-refresh");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let stamp = dir.join("sqlite3.lo");
        let body = b"# libtool object\nnon_pic_object='sqlite3.o'\n";
        std::fs::write(&stamp, body).unwrap();
        let before = std::fs::metadata(&stamp).unwrap().modified().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1100));
        refresh(&stamp).unwrap();
        let after = std::fs::metadata(&stamp).unwrap().modified().unwrap();
        assert!(after > before, "make compares stamps by modification time");
        assert_eq!(
            std::fs::read(&stamp).unwrap(),
            body,
            "the stamp names the object libtool archives, so rewriting it must not alter it"
        );
    }

    #[test]
    fn the_output_is_read_from_the_database_field_before_the_argv() {
        let tool = host_tool_fixture("outputfield", "lemon", true, true);
        let mut entry = command_writing(&tool);
        entry.command = Some("cc -O2 -o something-else.o lemon.c".to_owned());
        entry.output = Some(tool.display().to_string());
        assert!(rewrite(&entry, &Instrumentation::default()).is_none());
    }
}