//! RUSTC_WRAPPER shim that restores absolute paths in SBF DWARF output. //! //! ## Problem //! //! The Solana toolchain's cargo passes `-Zremap-cwd-prefix=` (empty //! replacement) to rustc for every SBF crate. This strips `DW_AT_comp_dir` //! from the DWARF, making all source paths relative. When multiple crates //! share filenames like `src/lib.rs`, the debugger can't tell them apart //! and may show source from the wrong crate. //! //! ## Solution //! //! `anchor debugger` sets `RUSTC_WRAPPER` to the `anchor` binary itself. //! Cargo then invokes `anchor ` for every rustc //! call. This module detects that invocation pattern (the env var //! `__ANCHOR_RUSTC_WRAPPER=1` disambiguates from normal CLI usage) and //! replaces `-Zremap-cwd-prefix=` with `-Zremap-cwd-prefix=$CWD`, //! preserving absolute paths in the debug info. //! //! The sentinel env var is necessary because `RUSTC_WRAPPER` mode passes //! a path as `argv[1]` (the real rustc binary), which clap would reject as //! an unknown subcommand. The check in `main.rs` runs before clap //! parsing so the process never hits the normal CLI dispatch. //! //! ## Performance //! //! The wrapper adds ~1ms of fork+exec overhead per rustc invocation. //! This is negligible compared to actual compilation time. use { std::{fs, io::Write, process}, tempfile::NamedTempFile, }; /// Env var set by `anchor debugger` before calling `cargo build-sbf`. /// When present, the process knows it was invoked as a RUSTC_WRAPPER /// and should rewrite args instead of running the normal CLI. pub const WRAPPER_SENTINEL: &str = "__ANCHOR_RUSTC_WRAPPER"; pub fn rewrite_args(args: &[String], cwd: &str) -> (Vec, Vec) { let mut rewritten = Vec::new(); let mut temp_files = Vec::new(); for arg in args { if let Some(path) = arg.strip_prefix('@') { if let Ok(content) = fs::read_to_string(path) { let mut new_content = String::new(); let mut modified = false; // Filter out empty lines to prevent rustc from failing on "" arguments for line in content.lines().filter(|l| !l.trim().is_empty()) { if line == "-Zremap-cwd-prefix=" { new_content.push_str(&format!("-Zremap-cwd-prefix={cwd}\n")); modified = true; } else { new_content.push_str(line); new_content.push('\n'); } } if modified { if let Ok(mut temp_file) = NamedTempFile::new() { if temp_file.write_all(new_content.as_bytes()).is_ok() { rewritten.push(format!("@{}", temp_file.path().display())); // Keep the handle alive so the file isn't deleted prematurely temp_files.push(temp_file); continue; } } } else { rewritten.push(arg.clone()); continue; } } } if arg == "-Zremap-cwd-prefix=" { rewritten.push(format!("-Zremap-cwd-prefix={cwd}")); } else { rewritten.push(arg.clone()); } } (rewritten, temp_files) } /// If we're running as a RUSTC_WRAPPER (sentinel env var is set), /// rewrite the rustc args (including expanding `@argfiles` generated by newer Cargo versions) /// and exec the real compiler. Never returns. /// /// If we're NOT in wrapper mode, returns `false` so the caller can /// proceed with normal CLI parsing. pub fn maybe_exec_as_wrapper() -> bool { if std::env::var_os(WRAPPER_SENTINEL).is_none() { return false; } let args: Vec = std::env::args().collect(); // RUSTC_WRAPPER invocation: argv[0]=anchor, argv[1]=rustc, argv[2..]=args if args.len() < 2 { eprintln!("anchor rustc-wrapper: expected "); process::exit(1); } let rustc = &args[1]; let cwd = std::env::current_dir() .map(|p| p.display().to_string()) .unwrap_or_default(); let (rewritten, _temp_files) = rewrite_args(&args[2..], &cwd); let result = process::Command::new(rustc).args(&rewritten).status(); drop(_temp_files); match result { Ok(status) => process::exit(status.code().unwrap_or(1)), Err(e) => { eprintln!("anchor rustc-wrapper: failed to exec {rustc}: {e}"); process::exit(1); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_argfile_rewrite() { let tmp = tempfile::tempdir().unwrap(); let argfile = tmp.path().join("args"); fs::write(&argfile, "--crate-name\nfoo\n\n-Zremap-cwd-prefix=\n").unwrap(); let args = vec![format!("@{}", argfile.display())]; let (rewritten, _temp_files) = rewrite_args(&args, "/workspace"); assert_eq!(rewritten.len(), 1); assert!(rewritten[0].starts_with('@')); let new_content = fs::read_to_string(&rewritten[0][1..]).unwrap(); assert_eq!( new_content, "--crate-name\nfoo\n-Zremap-cwd-prefix=/workspace\n" ); } }