Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<Handle>, saved: &mut Saved, persist: bool) {
Expand Down Expand Up @@ -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)))
}
Expand Down
81 changes: 76 additions & 5 deletions src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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<File>,
/// 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<u32>,
}

static APPEND_FILES: Mutex<Vec<AppendFile>> = 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<File> {
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<File>], 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<AppendFile>) {
open.retain_mut(|a| {
a.children.retain(|&pid| sys::pid_alive(pid));
Arc::strong_count(&a.file) > 1 || !a.children.is_empty()
});
}
41 changes: 40 additions & 1 deletion src/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize> {
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;
Expand Down Expand Up @@ -146,7 +185,7 @@ fn granted_access(h: HANDLE) -> Option<DWORD> {
}

/// 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 {
Expand Down
1 change: 1 addition & 0 deletions tests/scripts/066_msys_append_concurrent.code
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0
4 changes: 4 additions & 0 deletions tests/scripts/066_msys_append_concurrent.out
Original file line number Diff line number Diff line change
@@ -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
24 changes: 24 additions & 0 deletions tests/scripts/066_msys_append_concurrent.sh
Original file line number Diff line number Diff line change
@@ -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"
Loading