diff --git a/src/exec.rs b/src/exec.rs index a2fd83e..867d445 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -1592,7 +1592,12 @@ impl Shell { let mut pumps = Vec::new(); // Here-doc input lent to the child as a file (see `MemReader::lend_file`). let mut lent = Vec::new(); + // `>>` handles given to the program; they stay shared while it runs (io::shared_append). + let mut appends = Vec::new(); for fd in 0..3 { + if let Some(Handle::Append(a)) = self.fds.get(fd) { + appends.push(a.clone()); + } if msys_child && names_std_fd(&argv[1..], fd) { if let Some(Handle::Mem(m)) = self.fds.get(fd) { if let Ok(Some(f)) = m.lock().unwrap().lend_file() { @@ -1656,6 +1661,9 @@ impl Shell { return Ok(code); } }; + if !appends.is_empty() { + crate::io::append_started(&appends, child.id()); + } if self.spawn_only { self.spawned = Some(child); return Ok(0); @@ -1719,6 +1727,7 @@ impl Shell { for (fd, old) in saved.0.into_iter().rev() { self.fds.set(fd, old); } + crate::io::prune_append_files(); } fn set_fd_saved(&mut self, fd: i32, h: Option, saved: &mut Saved, persist: bool) { @@ -1773,7 +1782,7 @@ impl Shell { let f = oo.open(&wp)?; if append && write && crate::sys::is_disk(std::os::windows::io::AsRawHandle::as_raw_handle(&f) as _) { (&f).seek(std::io::SeekFrom::End(0))?; - return Ok(Handle::Append(Arc::new(f))); + return Ok(Handle::Append(crate::io::shared_append(f))); } Ok(Handle::File(Arc::new(f))) } diff --git a/src/io.rs b/src/io.rs index f55307a..81c191f 100644 --- a/src/io.rs +++ b/src/io.rs @@ -5,7 +5,7 @@ use crate::sys; use std::fs::File; use std::io::{self, BufRead, PipeReader, PipeWriter, Read, Seek, SeekFrom, Write}; use std::mem::ManuallyDrop; -use std::os::windows::io::{AsHandle, FromRawHandle}; +use std::os::windows::io::{AsHandle, AsRawHandle, FromRawHandle}; use std::process::Stdio; use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; @@ -237,9 +237,18 @@ impl Handle { Handle::Stderr => write_std(true, data), Handle::File(f) => (&**f).write_all(data), Handle::Append(f) => { - let mut f = &**f; - f.seek(SeekFrom::End(0))?; - f.write_all(data) + // Each write is one append at the current end (sys::write_at_end), which also + // leaves the shared position there. Seeking to the end and then writing could + // land at a stale end when another writer appended in between, and overwrite it. + let mut rest = data; + while !rest.is_empty() { + let n = sys::write_at_end(f.as_raw_handle() as sys::HANDLE, rest)?; + if n == 0 { + return Err(io::ErrorKind::WriteZero.into()); + } + rest = &rest[n..]; + } + Ok(()) } Handle::PipeW(p) => (&**p).write_all(data), Handle::Buf(b) => { @@ -409,7 +418,17 @@ impl Handle { } Handle::File(f) => (Stdio::from(f.try_clone()?), None), Handle::Append(f) => { - let _ = (&**f).seek(SeekFrom::End(0)); + // Writes through this handle leave its position at the end (see `write_all`), so it + // needs moving only when another handle to the file has appended since. Seeking + // every time could move it back over output that a program still writing through + // it adds meanwhile. The length is read first: writers on this handle only move + // the position forward, so they can't make it look behind. + let mut g = &**f; + if let (Ok(len), Ok(pos)) = (f.metadata().map(|m| m.len()), g.stream_position()) { + if pos < len { + let _ = g.seek(SeekFrom::End(0)); + } + } (Stdio::from(f.try_clone()?), None) } Handle::PipeR(p) => (Stdio::from(p.try_clone()?), None), @@ -517,3 +536,55 @@ impl Fds { fd } } + +/// A file open for `>>`, shared by every redirection to it in this process (see +/// `shared_append`). +struct AppendFile { + file: Arc, + /// Programs it was handed to, by process id. It stays shared while they run, even after + /// the redirection that started them is gone (`cmd >> log &`). + children: Vec, +} + +static APPEND_FILES: Mutex> = Mutex::new(Vec::new()); + +/// The handle for a file just opened with `>>`. If another `>>` redirection in this process, +/// or a program started with one, still has the same file open, this shares that handle, and +/// so its file object and position, instead of adding a second one. Programs appending to the +/// file through separate redirections at the same time (`cmd >> log &` in a loop) then write +/// one after another, as with Cygwin's O_APPEND, rather than at the same offset and over each +/// other. +pub fn shared_append(f: File) -> Arc { + let mut open = APPEND_FILES.lock().unwrap(); + prune_append(&mut open); + let h = f.as_raw_handle() as sys::HANDLE; + if let Some(a) = open.iter().find(|a| sys::same_file(a.file.as_raw_handle() as sys::HANDLE, h)) { + return a.file.clone(); + } + let file = Arc::new(f); + open.push(AppendFile { file: file.clone(), children: Vec::new() }); + file +} + +/// Record that the program `pid` was started with these `>>` handles. +pub fn append_started(files: &[Arc], pid: u32) { + let mut open = APPEND_FILES.lock().unwrap(); + for a in open.iter_mut().filter(|a| files.iter().any(|f| Arc::ptr_eq(f, &a.file))) { + a.children.push(pid); + } +} + +/// Forget the `>>` files that no redirection holds and no program started with them still +/// writes to, closing them. Called when redirections are undone. +pub fn prune_append_files() { + if let Ok(mut open) = APPEND_FILES.try_lock() { + prune_append(&mut open); + } +} + +fn prune_append(open: &mut Vec) { + open.retain_mut(|a| { + a.children.retain(|&pid| sys::pid_alive(pid)); + Arc::strong_count(&a.file) > 1 || !a.children.is_empty() + }); +} diff --git a/src/sys.rs b/src/sys.rs index 9531279..e8a4d81 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -116,6 +116,45 @@ struct IO_STATUS_BLOCK { #[link(name = "ntdll")] extern "system" { fn NtQueryInformationFile(h: HANDLE, iosb: *mut IO_STATUS_BLOCK, info: *mut core::ffi::c_void, len: u32, class: u32) -> i32; + #[allow(clippy::too_many_arguments)] + fn NtWriteFile( + h: HANDLE, + event: HANDLE, + apc: *mut core::ffi::c_void, + apc_context: *mut core::ffi::c_void, + iosb: *mut IO_STATUS_BLOCK, + buf: *const core::ffi::c_void, + len: u32, + offset: *const i64, + key: *const u32, + ) -> i32; + fn RtlNtStatusToDosError(status: i32) -> u32; +} + +/// Write to the end of the file, wherever the handle's position is, as one append +/// (FILE_WRITE_TO_END_OF_FILE), so that writers sharing the file can't land on the same +/// offset. The position is left just past the data, at the end. Returns the bytes written. +pub fn write_at_end(h: HANDLE, data: &[u8]) -> std::io::Result { + let mut iosb = IO_STATUS_BLOCK { status: 0, information: 0 }; + let end: i64 = -1; // FILE_WRITE_TO_END_OF_FILE in the low part, -1 in the high part + let len = data.len().min(u32::MAX as usize) as u32; + let st = unsafe { + NtWriteFile( + h, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut iosb, + data.as_ptr() as *const _, + len, + &end, + std::ptr::null(), + ) + }; + if st < 0 { + return Err(std::io::Error::from_raw_os_error(unsafe { RtlNtStatusToDosError(st) } as i32)); + } + Ok(iosb.information) } const FILE_READ_DATA: DWORD = 0x0001; @@ -146,7 +185,7 @@ fn granted_access(h: HANDLE) -> Option { } /// Same file (volume and file index), not necessarily the same handle or file object. -fn same_file(a: HANDLE, b: HANDLE) -> bool { +pub fn same_file(a: HANDLE, b: HANDLE) -> bool { let mut x = BY_HANDLE_FILE_INFORMATION::default(); let mut y = BY_HANDLE_FILE_INFORMATION::default(); unsafe { diff --git a/tests/scripts/066_msys_append_concurrent.code b/tests/scripts/066_msys_append_concurrent.code new file mode 100644 index 0000000..c227083 --- /dev/null +++ b/tests/scripts/066_msys_append_concurrent.code @@ -0,0 +1 @@ +0 \ No newline at end of file diff --git a/tests/scripts/066_msys_append_concurrent.out b/tests/scripts/066_msys_append_concurrent.out new file mode 100644 index 0000000..5084df7 --- /dev/null +++ b/tests/scripts/066_msys_append_concurrent.out @@ -0,0 +1,4 @@ +separate redirections: 30 lines, 30 distinct +one redirection: 30 lines, 30 distinct +builtins and MSYS programs: 40 lines, 40 distinct +new diff --git a/tests/scripts/066_msys_append_concurrent.sh b/tests/scripts/066_msys_append_concurrent.sh new file mode 100644 index 0000000..3263b9e --- /dev/null +++ b/tests/scripts/066_msys_append_concurrent.sh @@ -0,0 +1,24 @@ +# MSYS programs appending to one file at the same time keep all of their output, through one +# redirection and through separate ones, as with Git Bash's O_APPEND. +t=$(mktemp -d) +cd "$t" || exit 1 + +for i in $(seq 1 30); do /usr/bin/echo "job $i" >> m & done +wait +echo "separate redirections: $(wc -l < m) lines, $(sort -u m | wc -l) distinct" + +for i in $(seq 1 30); do { /usr/bin/echo "shared $i"; } & done >> n +wait +echo "one redirection: $(wc -l < n) lines, $(sort -u n | wc -l) distinct" + +for i in $(seq 1 20); do { echo "builtin $i"; /usr/bin/echo "msys $i"; } >> k & done +wait +echo "builtins and MSYS programs: $(wc -l < k) lines, $(sort -u k | wc -l) distinct" + +# Nothing keeps the file open afterwards: it can be removed and created again. +/usr/bin/echo old >> o +rm o +echo new > o +cat o + +cd / && rm -rf "$t"