From 8580da4fcf4aa85e1741f9977a1c1601a93a7440 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Wed, 18 Nov 2026 18:25:07 +0000 Subject: [PATCH 1/3] fix(builtins): byte-exact tee, split, cut and xxd -r A differential probe on a Latin-1 + invalid-byte file found byte tools decoding through text: tee rewrote output and file to U+FFFD, split wrote damaged pieces (and -l dropped \r), cut -b was an alias of -c, xxd -r returned lossy UTF-8. All now work on bytes. sort -o FILE FILE refuses a non-UTF-8 FILE instead of destroying it, like sed -i. Refs #2935 --- crates/bashkit/src/builtins/cuttr.rs | 132 ++++++++++++------ crates/bashkit/src/builtins/hextools.rs | 6 +- crates/bashkit/src/builtins/pipeline.rs | 10 +- crates/bashkit/src/builtins/sortuniq.rs | 30 ++++ crates/bashkit/src/builtins/split.rs | 30 ++-- .../tests/integration/byte_stream_tests.rs | 56 ++++++++ knowledge/log.md | 1 + knowledge/operations/limitations.md | 2 +- 8 files changed, 198 insertions(+), 69 deletions(-) diff --git a/crates/bashkit/src/builtins/cuttr.rs b/crates/bashkit/src/builtins/cuttr.rs index 83988246b..a6137d3d6 100644 --- a/crates/bashkit/src/builtins/cuttr.rs +++ b/crates/bashkit/src/builtins/cuttr.rs @@ -2,7 +2,7 @@ use async_trait::async_trait; -use super::{Builtin, BuiltinHelper, Context, read_text_file}; +use super::{Builtin, BuiltinHelper, Context, read_stream_file}; use crate::error::Result; use crate::fs::vfs_join; use crate::interpreter::ExecResult; @@ -33,7 +33,46 @@ impl BuiltinHelper for Cut { #[derive(PartialEq)] enum CutMode { Fields, + /// `-c`: UTF-8 characters; an invalid byte counts as one character. Chars, + /// `-b`: bytes. + Bytes, +} + +/// Selection units of a line: one per UTF-8 char, one per invalid byte. +/// Input stays bytes end to end, so `cut` never rewrites a Latin-1 or +/// binary line to U+FFFD (L-STREAM-001 does not apply to cut). +fn char_units(line: &[u8]) -> Vec<&[u8]> { + let mut units = Vec::new(); + for chunk in line.utf8_chunks() { + let valid = chunk.valid(); + let mut start = 0; + for ch in valid.chars() { + let end = start + ch.len_utf8(); + units.push(&valid.as_bytes()[start..end]); + start = end; + } + units.extend(chunk.invalid().chunks(1)); + } + units +} + +/// Split `line` on every occurrence of `delim` (non-empty). +fn split_bytes<'a>(line: &'a [u8], delim: &[u8]) -> Vec<&'a [u8]> { + let mut parts = Vec::new(); + let mut start = 0; + let mut i = 0; + while i + delim.len() <= line.len() { + if &line[i..i + delim.len()] == delim { + parts.push(&line[start..i]); + i += delim.len(); + start = i; + } else { + i += 1; + } + } + parts.push(&line[start..]); + parts } #[async_trait] @@ -84,7 +123,11 @@ impl Builtin for Cut { spec = val; mode = CutMode::Fields; } - 'b' | 'c' => { + 'b' => { + spec = val; + mode = CutMode::Bytes; + } + 'c' => { spec = val; mode = CutMode::Chars; } @@ -104,40 +147,44 @@ impl Builtin for Cut { let positions = parse_position_spec(&spec); let out_delim = output_delimiter.unwrap_or_else(|| delimiter.to_string()); - let process_line = |line: &str| -> Option { + let mut delim_buf = [0u8; 4]; + let delim: &[u8] = delimiter.encode_utf8(&mut delim_buf).as_bytes(); + let out_delim = out_delim.into_bytes(); + + let select = |units: Vec<&[u8]>| -> Vec { + let resolved = resolve_positions(&positions, units.len()); + if complement { + units + .iter() + .enumerate() + .filter(|(i, _)| resolved.binary_search(&(i + 1)).is_err()) + .flat_map(|(_, u)| u.iter().copied()) + .collect() + } else { + resolved + .iter() + .filter_map(|&p| units.get(p - 1)) + .flat_map(|u| u.iter().copied()) + .collect() + } + }; + + let process_line = |line: &[u8]| -> Option> { match mode { - CutMode::Chars => { - let chars: Vec = line.chars().collect(); - let total = chars.len(); - let resolved = resolve_positions(&positions, total); - let selected: Vec = if complement { - chars - .iter() - .enumerate() - .filter(|(i, _)| !resolved.contains(&(i + 1))) - .map(|(_, c)| *c) - .collect() - } else { - resolved - .iter() - .filter_map(|&p| chars.get(p - 1).copied()) - .collect() - }; - Some(selected.into_iter().collect()) - } + CutMode::Bytes => Some(select(line.chunks(1).collect())), + CutMode::Chars => Some(select(char_units(line))), CutMode::Fields => { + let parts = split_bytes(line, delim); // Lines without a delimiter print whole unless -s. - if !line.contains(delimiter) { - return (!only_delimited).then(|| line.to_string()); + if parts.len() == 1 { + return (!only_delimited).then(|| line.to_vec()); } - let parts: Vec<&str> = line.split(delimiter).collect(); - let total = parts.len(); - let resolved = resolve_positions(&positions, total); - let selected: Vec<&str> = if complement { + let resolved = resolve_positions(&positions, parts.len()); + let selected: Vec<&[u8]> = if complement { parts .iter() .enumerate() - .filter(|(i, _)| !resolved.contains(&(i + 1))) + .filter(|(i, _)| resolved.binary_search(&(i + 1)).is_err()) .map(|(_, s)| *s) .collect() } else { @@ -146,36 +193,35 @@ impl Builtin for Cut { .filter_map(|&f| parts.get(f - 1).copied()) .collect() }; - Some(selected.join(&out_delim)) + Some(selected.join(out_delim.as_slice())) } } }; - let mut output = String::new(); - let line_sep = if zero_terminated { '\0' } else { '\n' }; - let out_sep = if zero_terminated { "\0" } else { "\n" }; + let mut output: Vec = Vec::new(); + let line_sep = if zero_terminated { b'\0' } else { b'\n' }; - let process_input = |text: &str, output: &mut String| { - let body = text.strip_suffix(line_sep).unwrap_or(text); + let process_input = |text: &[u8], output: &mut Vec| { if text.is_empty() { return; } - for line in body.split(line_sep) { + let body = text.strip_suffix(&[line_sep]).unwrap_or(text); + for line in body.split(|&b| b == line_sep) { if let Some(result) = process_line(line) { - output.push_str(&result); - output.push_str(out_sep); + output.extend_from_slice(&result); + output.push(line_sep); } } }; if files.is_empty() || files.iter().all(|f| f.as_str() == "-") { - if let Some(stdin) = ctx.stdin { + if let Some(stdin) = ctx.stdin_bytes() { process_input(stdin, &mut output); } } else { for file in &files { if file.as_str() == "-" { - if let Some(stdin) = ctx.stdin { + if let Some(stdin) = ctx.stdin_bytes() { process_input(stdin, &mut output); } continue; @@ -187,15 +233,15 @@ impl Builtin for Cut { vfs_join(ctx.cwd, file) }; - let text = match read_text_file(&*ctx.fs, &path, "cut").await { + let data = match read_stream_file(&*ctx.fs, &path, "cut").await { Ok(t) => t, Err(e) => return Ok(*e), }; - process_input(&text, &mut output); + process_input(data.as_bytes(), &mut output); } } - Ok(ExecResult::ok(output)) + Ok(ExecResult::ok_bytes(output)) } } diff --git a/crates/bashkit/src/builtins/hextools.rs b/crates/bashkit/src/builtins/hextools.rs index 11ae229ba..fee69c24f 100644 --- a/crates/bashkit/src/builtins/hextools.rs +++ b/crates/bashkit/src/builtins/hextools.rs @@ -738,10 +738,8 @@ impl Builtin for Xxd { }; if opts.reverse { - let bytes = xxd_reverse(&data, opts.plain); - // Output raw bytes as lossy UTF-8 - let output = String::from_utf8_lossy(&bytes).to_string(); - Ok(ExecResult::ok(output)) + // Raw bytes: `xxd -r` exists to rebuild binary data. + Ok(ExecResult::ok_bytes(xxd_reverse(&data, opts.plain))) } else { let output = xxd_dump(&data, &opts); Ok(ExecResult::ok(output)) diff --git a/crates/bashkit/src/builtins/pipeline.rs b/crates/bashkit/src/builtins/pipeline.rs index b75edaac5..695d5752f 100644 --- a/crates/bashkit/src/builtins/pipeline.rs +++ b/crates/bashkit/src/builtins/pipeline.rs @@ -780,7 +780,9 @@ impl Builtin for Tee { .map(|vs| vs.map(|v| v.to_string_lossy().into_owned()).collect()) .unwrap_or_default(); - let input = ctx.stdin.map(|stdin| &**stdin).unwrap_or(""); + // Bytes, not text: tee is a passthrough and must not rewrite invalid + // UTF-8 (a Latin-1 CSV, a binary blob) to U+FFFD. + let input = ctx.stdin_bytes().unwrap_or_default(); for file in &files { // tee(1): "If a FILE is -, it refers to a file named - ." @@ -788,13 +790,13 @@ impl Builtin for Tee { let path = resolve_path(ctx.cwd, file); if append { - ctx.fs.append_file(&path, input.as_bytes()).await?; + ctx.fs.append_file(&path, input).await?; } else { - ctx.fs.write_file(&path, input.as_bytes()).await?; + ctx.fs.write_file(&path, input).await?; } } - Ok(ExecResult::ok(input.to_string())) + Ok(ExecResult::ok_bytes(input.to_vec())) } } diff --git a/crates/bashkit/src/builtins/sortuniq.rs b/crates/bashkit/src/builtins/sortuniq.rs index c1d03fc1c..71740d0d7 100644 --- a/crates/bashkit/src/builtins/sortuniq.rs +++ b/crates/bashkit/src/builtins/sortuniq.rs @@ -981,6 +981,36 @@ impl Builtin for Sort { files.push("-".to_string()); } let line_sep = if zero_terminated { '\0' } else { '\n' }; + + // `sort -o FILE FILE` rewrites its own input. Text builtins decode + // invalid UTF-8 with U+FFFD (L-STREAM-001), so a Latin-1 or binary + // FILE would be silently destroyed; refuse instead, like `sed -i` + // (L-SED-003). Writing to a different file stays lossy-but-safe. + if let Some(ref outfile) = output_file { + let out_path = if outfile.starts_with('/') { + std::path::PathBuf::from(outfile) + } else { + vfs_join(ctx.cwd, outfile) + }; + for file in files.iter().filter(|f| f.as_str() != "-") { + let path = if file.starts_with('/') { + std::path::PathBuf::from(file) + } else { + vfs_join(ctx.cwd, file) + }; + if path != out_path { + continue; + } + if let Ok(bytes) = ctx.fs.read_file(&path).await + && std::str::from_utf8(&bytes).is_err() + { + return Ok(sort_err(format!( + "sort: cannot rewrite {file}: not a valid UTF-8 text file\n" + ))); + } + } + } + let mut streams: Vec> = Vec::new(); for file in &files { let text = if file == "-" { diff --git a/crates/bashkit/src/builtins/split.rs b/crates/bashkit/src/builtins/split.rs index fb4096ec1..fd06020e8 100644 --- a/crates/bashkit/src/builtins/split.rs +++ b/crates/bashkit/src/builtins/split.rs @@ -2,7 +2,7 @@ use async_trait::async_trait; -use super::{Builtin, Context, read_text_file, resolve_path}; +use super::{Builtin, Context, read_stream_file, resolve_path}; use crate::error::Result; use crate::interpreter::ExecResult; @@ -80,12 +80,14 @@ impl Builtin for Split { let file = positional.first().copied().unwrap_or("-"); let prefix = positional.get(1).copied().unwrap_or("x"); - let input = if file == "-" { - ctx.stdin.map(ToString::to_string).unwrap_or_default() + // Bytes end to end: pieces must concatenate back to the exact input, + // whatever its encoding or line endings. + let input: Vec = if file == "-" { + ctx.stdin_bytes().unwrap_or_default().to_vec() } else { let path = resolve_path(ctx.cwd, file); - match read_text_file(ctx.fs.as_ref(), &path, "split").await { - Ok(text) => text, + match read_stream_file(ctx.fs.as_ref(), &path, "split").await { + Ok(data) => data.into_bytes(), Err(_) => { return Ok(ExecResult::err( format!( @@ -109,7 +111,7 @@ impl Builtin for Split { )); } let chunk_size = input.len().div_ceil(n); - let bytes = input.as_bytes(); + let bytes = input.as_slice(); let mut pos = 0; while pos < bytes.len() { let end = (pos + chunk_size).min(bytes.len()); @@ -121,7 +123,7 @@ impl Builtin for Split { } } else if let Some(size) = bytes_per_file { // Split by byte size - let bytes = input.as_bytes(); + let bytes = input.as_slice(); let mut pos = 0; while pos < bytes.len() { let end = (pos + size).min(bytes.len()); @@ -134,21 +136,15 @@ impl Builtin for Split { } else { // Split by lines let n = lines_per_file.unwrap_or(1000); - let lines: Vec<&str> = input.lines().collect(); + // Each line keeps its own terminator (`\r\n` stays intact). + let lines: Vec<&[u8]> = input.split_inclusive(|&b| b == b'\n').collect(); let mut pos = 0; while pos < lines.len() { let end = (pos + n).min(lines.len()); let suffix = make_suffix(file_index, numeric_suffix); let out_path = resolve_path(ctx.cwd, &format!("{}{}", prefix, suffix)); - let chunk = lines[pos..end].join("\n"); - let chunk_with_newline = if end < lines.len() || input.ends_with('\n') { - format!("{}\n", chunk) - } else { - chunk - }; - ctx.fs - .write_file(&out_path, chunk_with_newline.as_bytes()) - .await?; + let chunk = lines[pos..end].concat(); + ctx.fs.write_file(&out_path, &chunk).await?; file_index += 1; pos = end; } diff --git a/crates/bashkit/tests/integration/byte_stream_tests.rs b/crates/bashkit/tests/integration/byte_stream_tests.rs index 6d93e8fab..2b99269f8 100644 --- a/crates/bashkit/tests/integration/byte_stream_tests.rs +++ b/crates/bashkit/tests/integration/byte_stream_tests.rs @@ -241,3 +241,59 @@ async fn iconv_code_pages_match_real_iconv() { ); } } + +#[tokio::test] +async fn byte_tools_match_real_bash_on_non_utf8_input() { + // tee, split and cut pass bytes through; text tools would print U+FFFD. + let setup = "cd \"$(mktemp -d)\" && printf 'K\\366ln,\\377\\376\\000z\\nb,K\\303\\266ln\\200\\r\\n' > in.bin && "; + for case in [ + "tee o.bin < in.bin && cat o.bin", + "split -b 4 in.bin p_ && cat p_*", + "split -l 1 in.bin q_ && cat q_ab", + "cut -b1-3 in.bin", + "cut -b2- --complement in.bin", + "cut -c1-3 in.bin", + "cut -d, -f2 in.bin", + ] { + let script = format!("{setup}{case}"); + let expected = Command::new("bash").args(["-c", &script]).output().unwrap(); + assert!(expected.status.success(), "{case}"); + let mut bash = Bash::new(); + let actual = bash.exec(&script).await.unwrap(); + assert_eq!(actual.stdout.as_bytes(), expected.stdout, "{case}"); + assert_eq!(actual.exit_code, 0, "{case}"); + } +} + +#[tokio::test] +async fn xxd_reverse_rebuilds_exact_bytes() { + let mut bash = Bash::new(); + let result = bash + .exec("printf 'K\\366\\377\\000\\n' | xxd | xxd -r | od -An -tx1; printf '4bf6ff' | xxd -r -p | od -An -tx1") + .await + .unwrap(); + assert_eq!( + result.stdout.text().unwrap(), + " 4b f6 ff 00 0a\n 4b f6 ff\n" + ); +} + +#[tokio::test] +async fn sort_refuses_to_rewrite_non_utf8_file_in_place() { + let mut bash = Bash::new(); + let result = bash + .exec("printf 'b\\n\\366\\na\\n' > /f; sort -o /f /f; echo rc=$?; od -An -tx1 /f; sort -o /g /f; echo rc=$?") + .await + .unwrap(); + assert_eq!( + result.stdout.text().unwrap(), + "rc=2\n 62 0a f6 0a 61 0a\nrc=0\n" + ); + assert!( + result + .stderr + .text() + .unwrap() + .contains("not a valid UTF-8 text file") + ); +} diff --git a/knowledge/log.md b/knowledge/log.md index 63a5fe118..4dd20bb6e 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,7 @@ ## 2026-11-18 +* **Byte-exact `tee`, `split`, `cut`, `xxd -r`; `sort -o` in place refuses non-UTF-8**: a 60-command differential probe (bashkit vs bash on a Latin-1 + invalid-byte file, follow-up to issue #2935) found byte-oriented builtins decoding through text: `tee` rewrote both its output and the file to U+FFFD, `split -b`/`-l` wrote damaged pieces (and `-l` dropped `\r` from CRLF lines), `cut -b` was an alias of `-c`, and `xxd -r` returned lossy UTF-8. All four now work on bytes; `cut -b` selects bytes, `cut -c` counts a UTF-8 char or an invalid byte as one unit. `sort -o FILE FILE` would silently destroy a non-UTF-8 FILE, so it now refuses with exit 2, matching `sed -i` (L-SED-003). Pinned by differential tests in `byte_stream_tests`. See [Limitations](operations/limitations.md) L-STREAM-001. * **iconv code pages** (issue #2935): new default feature `iconv_charsets` adds `encoding_rs` (already in the lockfile through markkit) for windows-125x, iso-8859-x, koi8, macintosh and the CJK sets. Built-in names win, and any WHATWG windows-1252 label not spelled 1252 resolves to real Latin-1/ASCII, because WHATWG maps `latin1`/`ascii` to windows-1252. Decoding feeds encoding_rs one byte at a time so errors keep exact byte positions; encoding uses the no-replacement API, so unmappable characters are errors or `-c` drops, never `&#NNN;`. Listed by `bashkit-cli`/`bashkit-capi`, absent from `bashkit-wasm` like `tzdata`. See [Dependency Policy](operations/dependencies.md), L-ICONV-001. * **iconv writes real bytes; `-o`, `-c`, `//IGNORE`** (issue #2935): `iconv` built its output as a `String`, so `-t latin1` wrote UTF-8 again (double-encoded `Köln` could not be repaired) and `-t utf-16` went through a lossy decode. Conversion now runs char by char from input bytes to output bytes, with GNU positions in errors and the converted prefix on stdout when it stops. `UTF-16LE`/`UTF-16BE` write no BOM (`utf-16le` was an alias of the BOM form). `-o FILE` writes only after a full conversion, so `-o in.csv in.csv` with a wrong `-f` leaves the file intact. `-c`/`//IGNORE` drop bad input and unconvertible characters and exit 1. Output growth is charged to the execution budget. See [Limitations](operations/limitations.md) L-ICONV-001. * **Windows `/dev/stderr` redirects hit the VFS (#2933), and four more host-separator joins**: `dev_fd_alias` re-normalized the already-clean redirect target with `PathBuf::push`, which joins with `\` on Windows, so `/dev\stderr` missed the string match and `echo x > /dev/stderr` wrote a VFS file. It now uses the shared `normalize_path`. A clippy trial run with the join methods banned found the rest of the class: `PosixFs::mkdir -p` parent checks (backend saw `/a\b`), `cd x/..`, `readlink -f`/`realpath` prefix probes, and `OverlayFs` upper-dir counting, all now `vfs_join`. Second sweep after #2425, so the fix is a guard, not a sweep: `crates/bashkit/clippy.toml` bans `Path::join`/`PathBuf::push`/`set_file_name`/`with_file_name` with scoped allows for host-path code; `testing::CheckedFs` records paths a filesystem receives; the Windows CI job now runs the device-path and separator integration tests. Fuzzing could not have found it: Linux's separator is `/`. See [Virtual Filesystem](foundations/vfs.md). diff --git a/knowledge/operations/limitations.md b/knowledge/operations/limitations.md index be37c86c3..76ad9a1b1 100644 --- a/knowledge/operations/limitations.md +++ b/knowledge/operations/limitations.md @@ -68,7 +68,7 @@ execution model. Evidence is a threat-model ID, a test, or `stance` | L-WASM-002 | Browser build: `executeSync()` cannot run async custom builtins (fails with a clear message); use `execute()` | Single-threaded event loop can't settle a JS `Promise` without yielding | `crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs` | | L-WASM-003 | Browser build: background jobs (`cmd &`) run synchronously and `awk` file redirects drive the VFS inline; no work runs on a separate thread | `wasm32-unknown-unknown` is single-threaded, `std::thread::spawn`/`tokio::spawn` are unavailable; safe because the in-memory VFS never suspends | `crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs` | | L-CAPI-001 | C ABI v1 excludes custom builtins, streaming, transport hooks, snapshots, scripted tools, and external filesystem providers | Runtime host functions, cancellation and host mounts are supported; the remaining surfaces need explicit ownership and callback contracts | [C API](../runtimes/c-api.md), stance | -| L-STREAM-001 | Shell words, variables, command substitution, script source, text-oriented builtins, and JSON tool responses cannot represent arbitrary bytes. Command substitution removes NUL; other text boundaries decode invalid UTF-8 with replacement. Use `StreamData`, binding byte fields, redirects, or byte-oriented builtins for exact data | Bash variables and the parser are text domains; JSON strings are Unicode | `byte_stream_tests`, [Architecture](../foundations/architecture.md) | +| L-STREAM-001 | Shell words, variables, command substitution, script source, text-oriented builtins, and JSON tool responses cannot represent arbitrary bytes. Command substitution removes NUL; other text boundaries decode invalid UTF-8 with replacement. Use `StreamData`, binding byte fields, redirects, or byte-oriented builtins for exact data. Byte-exact builtins: `cat`, `head`/`tail`, `tee`, `split`, `cut` (`-b`, and `-c`/`-f` keep invalid bytes as-is), `tr` under `LC_ALL=C`, `base64`, `xxd -r`, `dd`, `gzip`, `iconv`, archives. `sort -o FILE FILE` refuses a non-UTF-8 FILE rather than rewrite it, like `sed -i` (L-SED-003) | Bash variables and the parser are text domains; JSON strings are Unicode | `byte_stream_tests`, [Architecture](../foundations/architecture.md) | ### Design Rationale From 822537bf3cdebf782b915b79df877118e8d9d403 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Wed, 18 Nov 2026 20:16:45 +0000 Subject: [PATCH 2/3] fix(sort): normalize paths in -o in-place UTF-8 guard ./f, d/../f and /cwd/f aliases of the input bypassed the refusal. --- crates/bashkit/src/builtins/sortuniq.rs | 15 ++++----------- .../tests/integration/byte_stream_tests.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/bashkit/src/builtins/sortuniq.rs b/crates/bashkit/src/builtins/sortuniq.rs index 71740d0d7..c81bbae50 100644 --- a/crates/bashkit/src/builtins/sortuniq.rs +++ b/crates/bashkit/src/builtins/sortuniq.rs @@ -11,7 +11,7 @@ use std::cmp::Ordering; use async_trait::async_trait; -use super::{Builtin, Context, read_text_file}; +use super::{Builtin, Context, read_text_file, resolve_path}; use crate::error::Result; use crate::fs::vfs_join; use crate::interpreter::ExecResult; @@ -987,17 +987,10 @@ impl Builtin for Sort { // FILE would be silently destroyed; refuse instead, like `sed -i` // (L-SED-003). Writing to a different file stays lossy-but-safe. if let Some(ref outfile) = output_file { - let out_path = if outfile.starts_with('/') { - std::path::PathBuf::from(outfile) - } else { - vfs_join(ctx.cwd, outfile) - }; + // Normalize both sides so `./f`, `d/../f` and `/cwd/f` all match. + let out_path = resolve_path(ctx.cwd, outfile); for file in files.iter().filter(|f| f.as_str() != "-") { - let path = if file.starts_with('/') { - std::path::PathBuf::from(file) - } else { - vfs_join(ctx.cwd, file) - }; + let path = resolve_path(ctx.cwd, file); if path != out_path { continue; } diff --git a/crates/bashkit/tests/integration/byte_stream_tests.rs b/crates/bashkit/tests/integration/byte_stream_tests.rs index 2b99269f8..d27792875 100644 --- a/crates/bashkit/tests/integration/byte_stream_tests.rs +++ b/crates/bashkit/tests/integration/byte_stream_tests.rs @@ -297,3 +297,16 @@ async fn sort_refuses_to_rewrite_non_utf8_file_in_place() { .contains("not a valid UTF-8 text file") ); } + +#[tokio::test] +async fn sort_in_place_guard_sees_through_path_aliases() { + let mut bash = Bash::new(); + let result = bash + .exec("mkdir -p /d/s && cd /d && printf 'b\\n\\366\\n' > f; for o in ./f s/../f /d/f; do sort -o \"$o\" f; echo rc=$?; done; od -An -tx1 f") + .await + .unwrap(); + assert_eq!( + result.stdout.text().unwrap(), + "rc=2\nrc=2\nrc=2\n 62 0a f6 0a\n" + ); +} From 57c8790ac75ba5143186ed479014085d2571630d Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Wed, 18 Nov 2026 20:25:46 +0000 Subject: [PATCH 3/3] fix(sort): follow symlinks in -o in-place UTF-8 guard ln -s f link; sort -o link f bypassed the lexical comparison. --- crates/bashkit/src/builtins/sortuniq.rs | 16 +++++++++++++--- .../tests/integration/byte_stream_tests.rs | 4 ++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/bashkit/src/builtins/sortuniq.rs b/crates/bashkit/src/builtins/sortuniq.rs index c81bbae50..03096cdf5 100644 --- a/crates/bashkit/src/builtins/sortuniq.rs +++ b/crates/bashkit/src/builtins/sortuniq.rs @@ -987,10 +987,20 @@ impl Builtin for Sort { // FILE would be silently destroyed; refuse instead, like `sed -i` // (L-SED-003). Writing to a different file stays lossy-but-safe. if let Some(ref outfile) = output_file { - // Normalize both sides so `./f`, `d/../f` and `/cwd/f` all match. - let out_path = resolve_path(ctx.cwd, outfile); + // Canonicalize both sides (normalize + follow symlinks) so `./f`, + // `d/../f`, `/cwd/f` and `ln -s f link` all match, like GNU's + // stat-based same-file check. Unresolvable paths fall back to the + // lexical form (a missing -o target cannot alias an input). + let fs = ctx.fs.as_ref(); + let lexical_out = resolve_path(ctx.cwd, outfile); + let out_path = crate::fs::canonicalize(fs, &lexical_out) + .await + .unwrap_or(lexical_out); for file in files.iter().filter(|f| f.as_str() != "-") { - let path = resolve_path(ctx.cwd, file); + let lexical = resolve_path(ctx.cwd, file); + let path = crate::fs::canonicalize(fs, &lexical) + .await + .unwrap_or(lexical); if path != out_path { continue; } diff --git a/crates/bashkit/tests/integration/byte_stream_tests.rs b/crates/bashkit/tests/integration/byte_stream_tests.rs index d27792875..929eb689f 100644 --- a/crates/bashkit/tests/integration/byte_stream_tests.rs +++ b/crates/bashkit/tests/integration/byte_stream_tests.rs @@ -302,11 +302,11 @@ async fn sort_refuses_to_rewrite_non_utf8_file_in_place() { async fn sort_in_place_guard_sees_through_path_aliases() { let mut bash = Bash::new(); let result = bash - .exec("mkdir -p /d/s && cd /d && printf 'b\\n\\366\\n' > f; for o in ./f s/../f /d/f; do sort -o \"$o\" f; echo rc=$?; done; od -An -tx1 f") + .exec("mkdir -p /d/s && cd /d && printf 'b\\n\\366\\n' > f; ln -s f link; for o in ./f s/../f /d/f link; do sort -o \"$o\" f; echo rc=$?; done; sort -o f link; echo rc=$?; od -An -tx1 f") .await .unwrap(); assert_eq!( result.stdout.text().unwrap(), - "rc=2\nrc=2\nrc=2\n 62 0a f6 0a\n" + "rc=2\nrc=2\nrc=2\nrc=2\nrc=2\n 62 0a f6 0a\n" ); }