mapsample 0.1.0

In-process Windows x64 stack sampler with a rolling stall recorder, P/E-core placement readings, and an MSVC /MAP symbolizer
Documentation
//! `mapsample symbolize <samples.folded> <binary.map> [--module NAME] [--top N]`

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use mapsample::symbolize::DEFAULT_TOP;

const USAGE: &str = "\
usage: mapsample symbolize <samples.folded> <binary.map> [--module NAME] [--top N]

Names the module-relative frames (`app.exe+0x1a2b`) of a folded stack file from the MSVC
linker map (/MAP) of the same build. Writes <stem>.named.folded and <stem>.flat.txt beside
the folded file and prints the head of the flat report.

  --module NAME  the module the map describes (default: the map's file stem + .exe)
  --top N        rows per list in the flat report (default: 60)
  -h, --help     print this help
  -V, --version  print the version";

#[derive(Debug, PartialEq, Eq)]
enum Command {
    Help,
    Version,
    Symbolize {
        folded: PathBuf,
        map: PathBuf,
        module: String,
        top: usize,
    },
}

fn parse_args(args: &[String]) -> Result<Command, String> {
    let mut args = args.iter();
    match args.next().map(String::as_str) {
        None => return Err("no command given".to_owned()),
        Some("-h" | "--help" | "help") => return Ok(Command::Help),
        Some("-V" | "--version") => return Ok(Command::Version),
        Some("symbolize") => {}
        Some(other) => return Err(format!("unknown command {other:?}")),
    }
    let mut paths = Vec::new();
    let mut module = None;
    let mut top = DEFAULT_TOP;
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-h" | "--help" => return Ok(Command::Help),
            "--module" => {
                let name = args.next().ok_or("--module needs a name")?;
                if name.trim().is_empty() {
                    return Err("--module needs a name".to_owned());
                }
                module = Some(name.clone());
            }
            "--top" => {
                top = args
                    .next()
                    .and_then(|n| n.parse().ok())
                    .ok_or("--top needs a whole number")?;
            }
            "--" => paths.extend(args.by_ref().map(PathBuf::from)),
            other if other.starts_with("--") => return Err(format!("unknown option {other}")),
            path => paths.push(PathBuf::from(path)),
        }
    }
    let [folded, map] = <[PathBuf; 2]>::try_from(paths)
        .map_err(|paths| format!("expected 2 paths, got {}", paths.len()))?;
    let module = module.unwrap_or_else(|| default_module(&map));
    Ok(Command::Symbolize {
        folded,
        map,
        module,
        top,
    })
}

/// `app.map` describes `app.exe`.
fn default_module(map: &Path) -> String {
    let stem = map
        .file_stem()
        .map_or_else(|| "app".into(), |stem| stem.to_string_lossy().into_owned());
    format!("{stem}.exe")
}

/// `dir/samples.folded` with `named.folded` is `dir/samples.named.folded`.
fn sibling(folded: &Path, suffix: &str) -> PathBuf {
    let stem = folded.file_stem().map_or_else(
        || "samples".into(),
        |stem| stem.to_string_lossy().into_owned(),
    );
    folded.with_file_name(format!("{stem}.{suffix}"))
}

fn symbolize(folded_path: &Path, map_path: &Path, module: &str, top: usize) -> Result<(), String> {
    let map_bytes = std::fs::read(map_path)
        .map_err(|error| format!("cannot read {}: {error}", map_path.display()))?;
    let map = mapsample::parse_map(&String::from_utf8_lossy(&map_bytes))
        .map_err(|error| format!("{}: {error}", map_path.display()))?;
    let folded = std::fs::read_to_string(folded_path)
        .map_err(|error| format!("cannot read {}: {error}", folded_path.display()))?;
    let result = mapsample::symbolize(&folded, &map, module, top);
    let named_path = sibling(folded_path, "named.folded");
    let flat_path = sibling(folded_path, "flat.txt");
    for (path, text) in [(&named_path, &result.folded), (&flat_path, &result.flat)] {
        std::fs::write(path, text)
            .map_err(|error| format!("cannot write {}: {error}", path.display()))?;
    }
    println!(
        "{} map symbols; {} of {} sampled frames in {module} named; {} lines skipped",
        map.len(),
        result.named,
        result.in_module,
        result.skipped_lines
    );
    println!("wrote {} and {}", named_path.display(), flat_path.display());
    let head: Vec<&str> = result.flat.lines().take(top.min(40) * 2 + 8).collect();
    println!("{}", head.join("\n"));
    Ok(())
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match parse_args(&args) {
        Ok(Command::Help) => {
            println!("{USAGE}");
            ExitCode::SUCCESS
        }
        Ok(Command::Version) => {
            println!("mapsample {}", env!("CARGO_PKG_VERSION"));
            ExitCode::SUCCESS
        }
        Ok(Command::Symbolize {
            folded,
            map,
            module,
            top,
        }) => match symbolize(&folded, &map, &module, top) {
            Ok(()) => ExitCode::SUCCESS,
            Err(error) => {
                eprintln!("mapsample: {error}");
                ExitCode::FAILURE
            }
        },
        Err(error) => {
            eprintln!("mapsample: {error}\n\n{USAGE}");
            ExitCode::from(2)
        }
    }
}

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

    fn args(text: &str) -> Vec<String> {
        text.split_whitespace().map(String::from).collect()
    }

    #[test]
    fn symbolize_defaults() {
        assert_eq!(
            parse_args(&args("symbolize run/samples.folded build/app.map")),
            Ok(Command::Symbolize {
                folded: PathBuf::from("run/samples.folded"),
                map: PathBuf::from("build/app.map"),
                module: "app.exe".into(),
                top: DEFAULT_TOP,
            })
        );
    }

    #[test]
    fn symbolize_options_anywhere() {
        assert_eq!(
            parse_args(&args(
                "symbolize --top 5 a.folded --module plugin.dll b.map"
            )),
            Ok(Command::Symbolize {
                folded: PathBuf::from("a.folded"),
                map: PathBuf::from("b.map"),
                module: "plugin.dll".into(),
                top: 5,
            })
        );
        assert!(matches!(
            parse_args(&args("symbolize a b --top 0")),
            Ok(Command::Symbolize { top: 0, .. })
        ));
        assert!(matches!(
            parse_args(&args("symbolize -- --odd.folded b.map")),
            Ok(Command::Symbolize { folded, .. }) if folded == Path::new("--odd.folded")
        ));
    }

    #[test]
    fn help_and_version() {
        assert_eq!(parse_args(&args("--help")), Ok(Command::Help));
        assert_eq!(parse_args(&args("-h")), Ok(Command::Help));
        assert_eq!(parse_args(&args("help")), Ok(Command::Help));
        assert_eq!(parse_args(&args("symbolize --help")), Ok(Command::Help));
        assert_eq!(parse_args(&args("-V")), Ok(Command::Version));
        assert_eq!(parse_args(&args("--version")), Ok(Command::Version));
    }

    #[test]
    fn errors() {
        for bad in [
            "",
            "frobnicate",
            "symbolize",
            "symbolize a.folded",
            "symbolize a b c",
            "symbolize a b --top",
            "symbolize a b --top -1",
            "symbolize a b --top many",
            "symbolize a b --module",
            "symbolize a b --verbose",
        ] {
            assert!(parse_args(&args(bad)).is_err(), "{bad:?}");
        }
        assert_eq!(
            parse_args(&args("symbolize a b c")),
            Err("expected 2 paths, got 3".to_owned())
        );
    }

    #[test]
    fn default_module_and_siblings() {
        assert_eq!(default_module(Path::new("out/server.map")), "server.exe");
        assert_eq!(default_module(Path::new("")), "app.exe");
        assert_eq!(
            sibling(Path::new("run/samples.folded"), "named.folded"),
            Path::new("run/samples.named.folded")
        );
        assert_eq!(
            sibling(Path::new("stall-1.folded"), "flat.txt"),
            Path::new("stall-1.flat.txt")
        );
    }

    #[test]
    fn end_to_end_on_files() {
        let dir = std::env::temp_dir().join(format!("mapsample-cli-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let map = dir.join("app.map");
        let folded = dir.join("samples.folded");
        std::fs::write(
            &map,
            " Preferred load address is 0000000140000000\n 0001:00000000 00001000H .text CODE\n 0001:00000000 _ZN3app4main17h0123456789abcdefE 0000000140001000 f app.obj\n",
        )
        .unwrap();
        std::fs::write(&folded, "main;app.exe+0x1010 7\n").unwrap();
        symbolize(&folded, &map, "app.exe", 10).unwrap();
        let named = std::fs::read_to_string(dir.join("samples.named.folded")).unwrap();
        assert_eq!(named, "main;app::main 7\n");
        assert!(dir.join("samples.flat.txt").is_file());
        assert!(symbolize(&dir.join("missing.folded"), &map, "app.exe", 10).is_err());
        assert!(symbolize(&folded, &dir.join("missing.map"), "app.exe", 10).is_err());
        let _ = std::fs::remove_dir_all(&dir);
    }
}