From 8127e048461fad751cbf2ef0df506ecdbd223129 Mon Sep 17 00:00:00 2001 From: Leah Lundqvist Date: Sat, 7 Nov 2026 12:47:59 +0100 Subject: [PATCH] Resolve /tmp the way the MSYS runtime does When a launcher passed TMP/TEMP in MSYS form (TMP=/tmp), gash and the MSYS programs it ran could use different folders for /tmp, so a folder made with mkdir in /tmp was missing for cd (issue #27). gash read TEMP before TMP and used the raw value, falling back to \tmp when it wasn't a folder, while the MSYS runtime mounts what GetTempPathW returns: TMP, then TEMP, made a full path, so /tmp on the current drive, whether or not it exists. gash now calls GetTempPathW itself (not std::env::temp_dir, which is GetTempPath2W and ignores TMP/TEMP under SYSTEM) and creates the folder when it is missing, since an MSYS process the launcher started may already have mounted it. Only if that fails does it use %LOCALAPPDATA%\Temp, then \tmp. Native programs now get that folder as a full Windows path rather than /tmp, and heredoc temp files go there too instead of to the folder the process's own TMP names. The msys_tmp tests now cover TMP before TEMP, an MSYS-form TMP, a missing folder with an MSYS process already running, and a folder that can't be created, and each test gets its own scratch folder so they can run in parallel. Co-Authored-By: Claude Opus 5.5 --- README.md | 12 ++- src/io.rs | 3 +- src/path.rs | 45 +++++++-- src/shell.rs | 2 +- src/sys.rs | 20 ++++ tests/msys_tmp.rs | 250 ++++++++++++++++++++++++++++++++++++++-------- 6 files changed, 279 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index 8867e22..11826f1 100644 --- a/README.md +++ b/README.md @@ -66,10 +66,18 @@ by real Git Bash) passes 100%. Supported: ### Windows/MSYS integration -- Paths: `/c/foo` ↔ `C:\foo`, `/tmp` → `%TEMP%`, `/usr/bin`, `/bin`, `/ucrt64` → Git's - install dir, `/dev/null`, `/dev/stdin|stdout|stderr|fd/N`, `/dev/tty`. Windows paths +- Paths: `/c/foo` ↔ `C:\foo`, `/tmp` → `%TMP%` (see below), `/usr/bin`, `/bin`, `/ucrt64` → + Git's install dir, `/dev/null`, `/dev/stdin|stdout|stderr|fd/N`, `/dev/tty`. Windows paths (`C:\x`, `C:/x`) work everywhere too. `$PWD` and `pwd` show the MSYS form, `pwd -W` the Windows one (`C:/...`). +- `/tmp` is the folder the MSYS runtime mounts there, which Windows' GetTempPathW gives at + startup: `TMP`, else `TEMP`, else your profile folder (`%USERPROFILE%`), else the Windows + folder. A value in MSYS form such as `TMP=/tmp` therefore means `\tmp` on the current drive, + as it does for Git Bash. gash creates that folder if it doesn't exist, and only if it can't + uses `%LOCALAPPDATA%\Temp` instead. Programs gash starts get `TMP` and `TEMP` set to the same + folder. MSYS programs still see another `/tmp` if an MSYS process from the same Git install + was already running with different `TMP`/`TEMP` values: they share one mount table, and the + first process to start sets `/tmp` for all of them. - PATH is kept in MSYS form inside the shell and converted when launching programs. - Arguments to native programs get MSYS2-style path conversion (`/c/x` → `C:/x`), honoring `MSYS_NO_PATHCONV` and `MSYS2_ARG_CONV_EXCL` when they are exported or given as diff --git a/src/io.rs b/src/io.rs index 0ba2efd..42c13ad 100644 --- a/src/io.rs +++ b/src/io.rs @@ -128,7 +128,8 @@ fn temp_file() -> io::Result { const FILE_ATTRIBUTE_TEMPORARY: u32 = 0x100; const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x0400_0000; static SEQ: AtomicU32 = AtomicU32::new(0); - let dir = std::env::temp_dir(); + // The folder behind /tmp, which is created or replaced when the one TMP names doesn't exist. + let dir = &crate::path::mounts().temp; let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.subsec_nanos()) diff --git a/src/path.rs b/src/path.rs index f5017b0..8d7af71 100644 --- a/src/path.rs +++ b/src/path.rs @@ -1,6 +1,6 @@ //! POSIX <-> Windows path translation, emulating the MSYS2/Git-for-Windows mount table: //! /c/foo -> C:\foo -//! /tmp -> %TEMP% +//! /tmp -> %TMP%, else %TEMP% (see `pick_temp`) //! /bin, /lib -> \usr\bin, \usr\lib //! /usr/... -> \usr\... //! /dev/null -> NUL @@ -76,13 +76,44 @@ pub fn find_msys_root() -> PathBuf { PathBuf::from(r"C:\Program Files\Git") } +/// The folder behind `/tmp`: the one the MSYS runtime mounts there. +/// +/// MSYS builds its `/tmp` mount (`usertemp` in /etc/fstab) from GetTempPathW, which takes TMP, +/// then TEMP, then USERPROFILE, then the Windows folder, and makes the value a full path. So a +/// launcher that passes `TMP=/tmp` gets `C:\tmp` (on the current drive) in every MSYS process it +/// starts, and gash must use the same folder to agree with them about what is in `/tmp` (issue +/// #27). +/// +/// MSYS mounts that folder whether or not it exists, and an MSYS program that started earlier with +/// the same environment may already be using it as `/tmp`, so a missing folder is created rather +/// than replaced. Only when that fails does gash take Windows' default per-user temp folder, and +/// `\tmp` as a last resort: it is read-only for most users of a Git installed under Program +/// Files. MSYS programs gash starts get TMP/TEMP set to the folder chosen here, so they agree with +/// gash unless another MSYS process already running set up `/tmp` differently. +fn pick_temp(root: &Path) -> PathBuf { + let mut temp = crate::sys::temp_path().unwrap_or_default().into_os_string().into_string().unwrap_or_default(); + while temp.len() > 3 && temp.ends_with(['\\', '/']) { + temp.pop(); + } + let temp = PathBuf::from(temp); + if temp.is_absolute() && (temp.is_dir() || std::fs::create_dir_all(&temp).is_ok()) { + return temp; + } + let local = std::env::var_os("LOCALAPPDATA") + .map(PathBuf::from) + .or_else(|| std::env::var_os("USERPROFILE").map(|p| Path::new(&p).join("AppData").join("Local"))); + if let Some(local) = local { + let p = local.join("Temp"); + if p.is_absolute() && p.is_dir() { + return p; + } + } + root.join("tmp") +} + pub fn init() { let root = find_msys_root(); - let temp = std::env::var("TEMP") - .or_else(|_| std::env::var("TMP")) - .map(PathBuf::from) - .unwrap_or_else(|_| root.join("tmp")); - let temp = if temp.is_dir() { temp } else { root.join("tmp") }; + let temp = pick_temp(&root); let root_lc = norm_lc(&root); let temp_lc = norm_lc(&temp); let msys_bins = vec![norm_lc(&root.join("usr").join("bin")), norm_lc(&root.join("bin"))]; @@ -92,7 +123,7 @@ pub fn init() { pub fn mounts() -> &'static Mounts { MOUNTS.get_or_init(|| { let root = find_msys_root(); - let temp = std::env::temp_dir(); + let temp = pick_temp(&root); Mounts { root_lc: norm_lc(&root), temp_lc: norm_lc(&temp), diff --git a/src/shell.rs b/src/shell.rs index 7dcf6d4..7d428f2 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -1090,7 +1090,7 @@ impl Shell { /// which reads TMP/TEMP, and `TMP=/tmp` makes that `C:\tmp`. All running MSYS processes of /// an installation share one mount table, so the first to start decides `/tmp` for the rest. /// MSYS turns TMP/TEMP back into POSIX form at startup, so the program still sees `/tmp`. - /// A child gash also reads TEMP to find the folder behind `/tmp`. + /// A child gash also reads TMP/TEMP to find the folder behind `/tmp`. pub fn child_env(&mut self, extra: &[(String, String)], native: bool) -> Vec<(String, String)> { let mut out: Vec<(String, String)> = Vec::new(); let mut seen: HashSet = HashSet::new(); diff --git a/src/sys.rs b/src/sys.rs index f133f02..74f04ff 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -73,6 +73,7 @@ extern "system" { pub fn GetConsoleWindow() -> HANDLE; pub fn SetConsoleTitleW(title: *const u16) -> BOOL; pub fn GetLastError() -> DWORD; + fn GetTempPathW(len: DWORD, buf: *mut u16) -> DWORD; pub fn ReOpenFile(h: HANDLE, access: DWORD, share: DWORD, flags: DWORD) -> HANDLE; pub fn SetStdHandle(n: DWORD, h: HANDLE) -> BOOL; pub fn SetFilePointerEx(h: HANDLE, dist: i64, new_pos: *mut i64, method: DWORD) -> BOOL; @@ -438,6 +439,25 @@ pub fn user_name() -> String { "user".into() } +/// The temporary folder as GetTempPathW gives it (TMP, then TEMP, then USERPROFILE, then the +/// Windows folder, as a full path ending in `\`). This is what the MSYS runtime mounts at `/tmp`. +/// Unlike `std::env::temp_dir`, which calls GetTempPath2W, it honors TMP/TEMP when running as +/// SYSTEM too. +pub fn temp_path() -> Option { + use std::os::windows::ffi::OsStringExt; + let mut buf = vec![0u16; 261]; + loop { + let n = unsafe { GetTempPathW(buf.len() as DWORD, buf.as_mut_ptr()) } as usize; + if n == 0 { + return None; + } + if n < buf.len() { + return Some(std::ffi::OsString::from_wide(&buf[..n]).into()); + } + buf.resize(n, 0); + } +} + pub fn host_name() -> String { std::env::var("COMPUTERNAME").unwrap_or_else(|_| "localhost".into()) } diff --git a/tests/msys_tmp.rs b/tests/msys_tmp.rs index 39af3cc..4ebb443 100644 --- a/tests/msys_tmp.rs +++ b/tests/msys_tmp.rs @@ -1,18 +1,21 @@ //! MSYS programs that gash starts must resolve `/tmp` to the same folder gash does. //! -//! The MSYS runtime builds its `/tmp` mount (`usertemp` in /etc/fstab) from the Windows -//! TMP/TEMP of the first MSYS process of an installation, and keeps the mount table in +//! The MSYS runtime builds its `/tmp` mount (`usertemp` in /etc/fstab) from GetTempPathW, so from +//! the Windows TMP/TEMP of the first MSYS process of an installation, and keeps the mount table in //! per-user shared memory for every MSYS process that starts while one is still running. //! Against Git's own `/usr/bin` the outcome therefore depends on whether, say, a Git Bash -//! window is open. This test copies the runtime and a few tools into a private root, which -//! MSYS treats as a separate installation, so the program gash starts is always the one -//! that sets up the mount table. +//! window is open. These tests copy the runtime and a few tools into a private root, which +//! MSYS treats as a separate installation, so they decide which MSYS process, if any, is +//! running when gash starts. //! //! Skipped when Git for Windows is not installed. +use std::ffi::OsString; use std::fs; +use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicU32, Ordering}; const RUNTIME: &[&str] = &[ "msys-2.0.dll", @@ -30,8 +33,14 @@ const SCRIPT: &str = r#" echo made-by-gash > /tmp/from-gash /usr/bin/cat /tmp/from-gash /usr/bin/cat <(echo procsub) +/usr/bin/cat /dev/stdin < Option { @@ -58,47 +67,204 @@ impl Drop for Scratch { } } +/// The variables that decide where `/tmp` is, for both gash and the MSYS runtime. +struct TempEnv { + tmp: OsString, + temp: OsString, + local_app_data: PathBuf, +} + +/// The private MSYS root and folders for one test, removed when it ends. +struct Setup { + scratch: Scratch, + root: PathBuf, +} + +impl Setup { + fn new(git_bin: &Path) -> Setup { + // Tests run in parallel in one process, so the name needs more than the process id. + static SEQ: AtomicU32 = AtomicU32::new(0); + let name = format!("gash-msys-tmp-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)); + let scratch = Scratch(std::env::temp_dir().join(name)); + let _ = fs::remove_dir_all(&scratch.0); + let root = scratch.0.join("root"); + let bin = root.join("usr").join("bin"); + fs::create_dir_all(&bin).unwrap(); + fs::create_dir_all(root.join("etc")).unwrap(); + for f in RUNTIME { + fs::copy(git_bin.join(f), bin.join(f)).unwrap_or_else(|e| panic!("copy {f}: {e}")); + } + fs::write(root.join("etc").join("fstab"), FSTAB).unwrap(); + Setup { scratch, root } + } + + fn dir(&self, name: &str) -> PathBuf { + let d = self.scratch.0.join(name); + fs::create_dir_all(&d).unwrap(); + d + } + + fn env(&self, cmd: &mut Command, e: &TempEnv) { + cmd.current_dir(&self.scratch.0) + .env("TMP", &e.tmp) + .env("TEMP", &e.temp) + .env("LOCALAPPDATA", &e.local_app_data); + } + + /// Runs `f` while an MSYS program of the private root is running, started with `e`, so that + /// it, not anything gash starts, sets up the root's mount table. + fn with_msys_running(&self, e: &TempEnv, f: impl FnOnce()) { + let mut cmd = Command::new(self.root.join("usr").join("bin").join("cat.exe")); + self.env(&mut cmd, e); + let mut cat = cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().expect("start cat"); + let mut stdin = cat.stdin.take().unwrap(); + let mut stdout = BufReader::new(cat.stdout.take().unwrap()); + stdin.write_all(b"ready\n").unwrap(); + let mut line = String::new(); + stdout.read_line(&mut line).unwrap(); + assert_eq!(line.trim(), "ready", "the MSYS program didn't start"); + f(); + drop(stdin); + let _ = cat.wait(); + } + + /// Runs SCRIPT with `e` and checks that gash, the MSYS programs it starts and a native + /// program all use `expected` for `/tmp`. + fn check(&self, e: &TempEnv, expected: &Path) { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_gash")); + self.env(&mut cmd, e); + let out = cmd + .arg("-c") + .arg(SCRIPT) + .env("GASH_ROOT", &self.root) + .env("GASH_COREUTILS", "0") + .env_remove("MSYS_NO_PATHCONV") + .env_remove("MSYS2_ARG_CONV_EXCL") + .stdin(Stdio::null()) + .output() + .expect("run gash"); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + let context = format!( + "TMP={:?} TEMP={:?}\nexit: {:?}\nstdout:\n{stdout}\nstderr:\n{stderr}", + e.tmp, + e.temp, + out.status.code() + ); + + let lines: Vec<&str> = stdout.lines().collect(); + assert_eq!(lines.len(), 8, "{context}"); + assert_eq!(lines[..4], ["made-by-gash", "procsub", "heredoc", "cd-ok"], "{context}"); + // A native program can't read `/x` as gash means it, so it must get a full Windows path. + for (line, who) in [(lines[6], "native TMP"), (lines[7], "native TEMP")] { + let b = line.trim().as_bytes(); + let full = (b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'\\') || line.starts_with(r"\\"); + assert!(full, "{who} is not a full Windows path: {line}\n{context}"); + } + let expected = fs::canonicalize(expected).unwrap(); + for (line, who) in [(lines[4], "MSYS"), (lines[5], "gash"), (lines[6], "native TMP"), (lines[7], "native TEMP")] { + let got = fs::canonicalize(line.trim()).unwrap_or_else(|e| panic!("{who}: {e}: {line}\n{context}")); + assert_eq!(got, expected, "{who} /tmp is not the expected folder\n{context}"); + } + assert_eq!(out.status.code(), Some(0), "{context}"); + } +} + +/// `C:\a\b` as `/a/b`: the MSYS form a launcher can pass, which Windows reads on the current drive. +/// None when the scratch folder isn't on a drive letter (a UNC temp folder). +fn drive_relative(p: &Path) -> Option { + let s = p.to_str()?; + let b = s.as_bytes(); + if b.len() < 3 || !b[0].is_ascii_alphabetic() || b[1] != b':' || b[2] != b'\\' { + eprintln!("skipping: scratch folder is not on a drive: {s}"); + return None; + } + Some(s[2..].replace('\\', "/").into()) +} + #[test] fn msys_children_share_gash_tmp() { let Some(git_bin) = git_usr_bin() else { eprintln!("skipping: Git for Windows' MSYS runtime not found"); return; }; - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.subsec_nanos()) - .unwrap_or(0); - let scratch = Scratch(std::env::temp_dir().join(format!("gash-msys-tmp-{}-{nanos}", std::process::id()))); - let root = scratch.0.join("root"); - let temp = scratch.0.join("temp"); - let bin = root.join("usr").join("bin"); - fs::create_dir_all(&bin).unwrap(); - fs::create_dir_all(root.join("etc")).unwrap(); - fs::create_dir_all(&temp).unwrap(); - for f in RUNTIME { - fs::copy(git_bin.join(f), bin.join(f)).unwrap_or_else(|e| panic!("copy {f}: {e}")); - } - fs::write(root.join("etc").join("fstab"), FSTAB).unwrap(); - - let out = Command::new(env!("CARGO_BIN_EXE_gash")) - .arg("-c") - .arg(SCRIPT) - .current_dir(&scratch.0) - .env("GASH_ROOT", &root) - .env("TEMP", &temp) - .env("TMP", &temp) - .env("GASH_COREUTILS", "0") - .stdin(Stdio::null()) - .output() - .expect("run gash"); - let stdout = String::from_utf8_lossy(&out.stdout); - let stderr = String::from_utf8_lossy(&out.stderr); - let context = format!("exit: {:?}\nstdout:\n{stdout}\nstderr:\n{stderr}", out.status.code()); - - let lines: Vec<&str> = stdout.lines().collect(); - assert_eq!(lines.len(), 4, "{context}"); - assert_eq!(lines[..3], ["made-by-gash", "procsub", "cd-ok"], "{context}"); - let msys_tmp = fs::canonicalize(lines[3].trim()).unwrap_or_else(|e| panic!("{e}: {}\n{context}", lines[3])); - assert_eq!(msys_tmp, fs::canonicalize(&temp).unwrap(), "MSYS /tmp differs from gash's\n{context}"); - assert_eq!(out.status.code(), Some(0), "{context}"); + let s = Setup::new(&git_bin); + let temp = s.dir("temp"); + let local = s.dir("local"); + s.dir("local/Temp"); + let e = TempEnv { tmp: temp.clone().into(), temp: temp.clone().into(), local_app_data: local }; + s.check(&e, &temp); +} + +/// As in GetTempPathW, TMP comes before TEMP. +#[test] +fn tmp_comes_before_temp() { + let Some(git_bin) = git_usr_bin() else { + eprintln!("skipping: Git for Windows' MSYS runtime not found"); + return; + }; + let s = Setup::new(&git_bin); + let tmp = s.dir("tmp-var"); + let temp = s.dir("temp-var"); + let local = s.dir("local"); + s.dir("local/Temp"); + let e = TempEnv { tmp: tmp.clone().into(), temp: temp.into(), local_app_data: local }; + s.check(&e, &tmp); +} + +/// A launcher can pass TMP and TEMP in MSYS form (`/tmp`). The MSYS runtime reads that as a +/// folder on the current drive, so every MSYS process the launcher starts uses that folder for +/// `/tmp`, and gash must too (issue #27). +#[test] +fn msys_form_tmp_is_read_like_the_msys_runtime_does() { + let Some(git_bin) = git_usr_bin() else { + eprintln!("skipping: Git for Windows' MSYS runtime not found"); + return; + }; + let s = Setup::new(&git_bin); + let msys_form = s.dir("msys-form"); + let local = s.dir("local"); + s.dir("local/Temp"); + let Some(rel) = drive_relative(&msys_form) else { return }; + let e = TempEnv { tmp: rel.clone(), temp: rel, local_app_data: local }; + s.check(&e, &msys_form); +} + +/// MSYS mounts the folder TMP names at `/tmp` even when it doesn't exist, so gash creates it rather +/// than use another one. Otherwise, with an MSYS program the launcher started still running, `mkdir +/// /tmp/x` in MSYS and `cd /tmp/x` in gash would use different folders (issue #27). +#[test] +fn missing_tmp_folder_is_created() { + let Some(git_bin) = git_usr_bin() else { + eprintln!("skipping: Git for Windows' MSYS runtime not found"); + return; + }; + let s = Setup::new(&git_bin); + let missing = s.scratch.0.join("missing"); + let local = s.dir("local"); + s.dir("local/Temp"); + let Some(rel) = drive_relative(&missing) else { return }; + let e = TempEnv { tmp: rel.clone(), temp: rel, local_app_data: local }; + s.with_msys_running(&e, || { + assert!(!missing.exists(), "the MSYS program created the folder"); + s.check(&e, &missing); + }); +} + +/// When the folder TMP names can't be created, gash uses Windows' default per-user temp folder, and +/// heredocs, which gash keeps in temporary files, still work. +#[test] +fn unusable_tmp_folder_falls_back_to_local_app_data() { + let Some(git_bin) = git_usr_bin() else { + eprintln!("skipping: Git for Windows' MSYS runtime not found"); + return; + }; + let s = Setup::new(&git_bin); + let file = s.scratch.0.join("a-file"); + fs::write(&file, "").unwrap(); + let local = s.dir("local"); + let local_temp = s.dir("local/Temp"); + let under_file: OsString = file.join("tmp").into(); + let e = TempEnv { tmp: under_file.clone(), temp: under_file, local_app_data: local }; + s.check(&e, &local_temp); }