From e70d6f4334b31e2e7272db609a74dabe061c5563 Mon Sep 17 00:00:00 2001 From: Eduardo Rodrigues <16357187+eduardomourar@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:03:41 +0000 Subject: [PATCH] sort: add wasi support for merge operations --- .github/workflows/wasi.yml | 4 +- src/uu/sort/src/check.rs | 19 +- src/uu/sort/src/chunks.rs | 27 +++ src/uu/sort/src/merge.rs | 390 +++++++++++++++++++++++++++------ src/uu/sort/src/sort.rs | 6 +- tests/by-util/test_sort.rs | 69 +++--- tests/uutests_procs/src/lib.rs | 6 +- 7 files changed, 410 insertions(+), 111 deletions(-) diff --git a/.github/workflows/wasi.yml b/.github/workflows/wasi.yml index bbafa7178d9..1875d17da75 100644 --- a/.github/workflows/wasi.yml +++ b/.github/workflows/wasi.yml @@ -78,7 +78,7 @@ jobs: # caret diagnostics; the host test crate does have them, hence the # not(wasi_runner) in the cfg guarding every `mod diagnostics`. # TODO: add integration tests for these tools as WASI support is extended: - # csplit rm sort + # csplit rm # nproc is not part of the default feature set, so it needs to be # requested explicitly for the host test crate to compile its tests. UUTESTS_BINARY_PATH="$(pwd)/target/${{ matrix.job.target }}/debug/coreutils.wasm" \ @@ -93,7 +93,7 @@ jobs: test_paste:: test_pathchk:: test_pr:: test_printenv:: test_printf:: test_ptx:: \ test_pwd:: test_readlink:: test_realpath:: test_rmdir:: test_seq:: test_sha1sum:: test_sha224sum:: test_sha256sum:: \ test_sha384sum:: test_sha512sum:: test_shred:: test_shuf:: test_sleep:: \ - test_sort::sort_multiple test_sort::test_check test_split:: test_sum:: test_tail:: test_tee:: \ + test_sort:: test_split:: test_sum:: test_tail:: test_tee:: \ test_test:: test_touch:: test_tr:: test_true:: test_truncate:: test_tsort:: test_uname:: \ test_uniq:: test_unexpand:: test_unlink:: test_vdir:: test_wc:: test_yes:: diff --git a/src/uu/sort/src/check.rs b/src/uu/sort/src/check.rs index 867df884186..036da33367c 100644 --- a/src/uu/sort/src/check.rs +++ b/src/uu/sort/src/check.rs @@ -163,22 +163,23 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { let mut file = open(path)?; let mut carry_over = vec![]; - let (sender, receiver) = std::sync::mpsc::sync_channel(1); let mut prev_chunk: Option = None; let mut line_idx = 0; + // Reuse the previous chunk's buffer for the next read instead of allocating a + // fresh one each time, once it is no longer needed for the disorder comparison. + let mut recycled_chunk = None; loop { - let recycled = RecycledChunk::new(buffer_size(settings)); - let should_continue = chunks::read( - &sender, - recycled, - None, + let chunk_buffer = recycled_chunk + .take() + .unwrap_or_else(|| RecycledChunk::new(buffer_size(settings))); + let (chunk, should_continue) = chunks::read_once( + chunk_buffer, &mut carry_over, &mut file, - &mut std::iter::empty(), settings.line_ending.into(), settings, )?; - while let Ok(chunk) = receiver.try_recv() { + if let Some(chunk) = chunk { check_chunk( path, settings, @@ -187,7 +188,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { &chunk, &mut line_idx, )?; - prev_chunk = Some(chunk); + recycled_chunk = prev_chunk.replace(chunk).map(Chunk::recycle); } if !should_continue { break; diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index e71b4f12114..316e5971388 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -259,6 +259,33 @@ pub fn read( Ok(should_continue) } +/// Read a single chunk synchronously, without a background reader thread. +/// +/// WASI has no threads, so callers that would otherwise hand `recycled_chunk` to a reader +/// thread call this instead to read the next chunk directly on the current thread. `read` +/// sends at most one chunk per call, so a throwaway channel is enough to receive it. +#[cfg(target_os = "wasi")] +pub fn read_once( + recycled_chunk: RecycledChunk, + carry_over: &mut Vec, + file: &mut T, + separator: u8, + settings: &GlobalSettings, +) -> UResult<(Option, bool)> { + let (sender, receiver) = std::sync::mpsc::sync_channel(1); + let should_continue = read( + &sender, + recycled_chunk, + None, + carry_over, + file, + &mut std::iter::empty(), + separator, + settings, + )?; + Ok((receiver.try_recv().ok(), should_continue)) +} + /// Split `read` into `Line`s, and add them to `lines`. fn parse_lines<'a>( read: &'a [u8], diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index 79fab4b86e2..324be81c15b 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -18,10 +18,13 @@ use std::{ ffi::{OsStr, OsString}, fs::File, io::{self, BufWriter, Read, Write}, - iter, path::Path, process::{Child, ChildStdin, ChildStdout, Command, Stdio}, rc::Rc, +}; +#[cfg(not(target_os = "wasi"))] +use std::{ + iter, sync::mpsc::{Receiver, Sender, SyncSender, TryRecvError, channel, sync_channel}, thread::{self, JoinHandle}, }; @@ -179,6 +182,7 @@ pub fn merge_with_file_limit< /// /// It is the responsibility of the caller to ensure that `files` yields only /// as many files as we are allowed to open concurrently. +#[cfg(not(target_os = "wasi"))] fn merge_without_limit>>( files: F, settings: &GlobalSettings, @@ -247,6 +251,7 @@ fn merge_without_limit>>( }) } /// The struct on the reader thread representing an input file +#[cfg(not(target_os = "wasi"))] struct ReaderFile { file: M, sender: SyncSender, @@ -254,6 +259,7 @@ struct ReaderFile { } /// The function running on the reader thread. +#[cfg(not(target_os = "wasi"))] fn reader( recycled_receiver: &Receiver<(usize, RecycledChunk)>, files: &mut [Option>], @@ -287,10 +293,15 @@ fn reader( } Ok(()) } -/// The struct on the main thread representing an input file +/// The struct representing an input file. +/// +/// WASI has no threads, so chunks are read synchronously, right when needed, +/// instead of by a background reader thread; there is no `receiver` to read +/// the next chunk from. pub struct MergeableFile<'a> { current_chunk: Rc, line_idx: usize, + #[cfg(not(target_os = "wasi"))] receiver: Receiver, file_number: usize, settings: &'a GlobalSettings, @@ -337,10 +348,116 @@ impl Ord for MergeableFile<'_> { struct PreviousLine { chunk: Rc, line_idx: usize, + // Used to recycle the chunk back to the right file once nothing references it + // anymore: to the reader thread's channel on non-WASI, directly onto the file's + // `ReaderFile` on WASI (there is no reader thread to send it to). file_number: usize, } +/// What went wrong writing the next line in [`write_next_line`]. +enum WriteNextError { + /// Writing the line to the output failed. + Write(io::Error), + /// Reading the next chunk for a file whose current one ran out failed. + Chunk(Box), +} + +/// Drive `write_next` to exhaustion, the shared part of both [`FileMerger::write_all_to`] impls. +fn drain_write_next( + mut write_next: impl FnMut() -> Result, + ctx: impl FnOnce() -> String, +) -> UResult<()> { + loop { + match write_next() { + Ok(true) => (), + Ok(false) => return Ok(()), + Err(WriteNextError::Write(error)) => return Err(error).map_err_context(ctx), + // A chunk read failure already has its own context; wrapping it as a write + // failure here would be misleading. + Err(WriteNextError::Chunk(error)) => return Err(error), + } + } +} + +/// How a [`FileMerger`] gets a file's next chunk once its current one runs out, and recycles +/// a chunk once nothing references it anymore. +/// +/// The threaded merger fetches chunks from its reader thread and recycles them back to it +/// over a channel; WASI, which has no threads, reads the next chunk directly and recycles +/// onto the file itself. [`write_next_line`] is the rest of merging, shared between them. +trait ChunkSource { + fn advance(&mut self, file: &mut MergeableFile<'_>) -> UResult>; + fn recycle(&mut self, file_number: usize, chunk: Chunk); +} + +/// Write one line from the file at the front of `heap` to `writer`, and advance that file, +/// using `source` to fetch its next chunk once the current one runs out. +fn write_next_line( + heap: &mut BinaryHeap>, + prev: &mut Option, + writer: &mut impl Write, + settings: &GlobalSettings, + source: &mut impl ChunkSource, +) -> Result { + let Some(mut file) = heap.peek_mut() else { + return Ok(false); + }; + + let old_prev = prev.replace(PreviousLine { + chunk: file.current_chunk.clone(), + line_idx: file.line_idx, + file_number: file.file_number, + }); + + file.current_chunk + .with_dependent(|_, contents| { + let current_line = &contents.lines[file.line_idx]; + if settings.unique + && let Some(prev) = &old_prev + { + let cmp = merge_compare( + &prev.chunk.lines()[prev.line_idx], + current_line, + settings, + prev.chunk.line_data(), + file.current_chunk.line_data(), + ); + if cmp == Ordering::Equal { + return Ok(()); + } + } + current_line.write(writer, settings) + }) + .map_err(WriteNextError::Write)?; + + let was_last_line_for_file = file.current_chunk.lines().len() == file.line_idx + 1; + + if was_last_line_for_file { + let next_chunk = source.advance(&mut file).map_err(WriteNextError::Chunk)?; + if let Some(next_chunk) = next_chunk { + file.current_chunk = Rc::new(next_chunk); + file.line_idx = 0; + } else { + std::collections::binary_heap::PeekMut::pop(file); + } + } else { + // This will cause the comparison to use a different line and the heap to readjust. + file.line_idx += 1; + } + + if let Some(prev) = old_prev + && let Ok(prev_chunk) = Rc::try_unwrap(prev.chunk) + { + // If nothing is referencing the previous chunk anymore, this means that the previous + // line was the last line of the chunk. We can recycle the chunk. + source.recycle(prev.file_number, prev_chunk); + } + + Ok(true) +} + /// Merges files together. This is **not** an iterator because of lifetime problems. +#[cfg(not(target_os = "wasi"))] struct FileMerger<'a> { heap: BinaryHeap>, request_sender: Sender<(usize, RecycledChunk)>, @@ -348,6 +465,7 @@ struct FileMerger<'a> { reader_join_handle: JoinHandle>, } +#[cfg(not(target_os = "wasi"))] impl FileMerger<'_> { /// Write the merged contents to the output file. fn write_all(self, settings: &GlobalSettings, output: Output) -> UResult<()> { @@ -364,18 +482,10 @@ impl FileMerger<'_> { out: &mut impl Write, ctx: impl FnOnce() -> String, ) -> UResult<()> { - let write_result = loop { - match self.write_next(out, settings) { - Ok(true) => (), - Ok(false) => break Ok(()), - Err(error) => { - // Don't return yet: we still have to shut the reader thread down in an - // orderly fashion below. Returning here would drop our receivers while - // the reader is still sending, and `chunks::read` unwraps that send. - break Err(error); - } - } - }; + // Don't return as soon as `drain_write_next` does: we still have to shut the + // reader thread down in an orderly fashion below. Returning here would drop our + // receivers while the reader is still sending, and `chunks::read` unwraps that send. + let write_result = drain_write_next(|| self.write_next(out, settings), ctx); let Self { heap, @@ -400,66 +510,222 @@ impl FileMerger<'_> { let reader_result = reader_join_handle.join().unwrap(); // A write failure is what the user needs to hear about; the reader hitting an error // on the way down is secondary. - write_result.map_err_context(ctx).and(reader_result) + write_result.and(reader_result) } fn write_next( &mut self, writer: &mut impl Write, settings: &GlobalSettings, - ) -> io::Result { - if let Some(file) = self.heap.peek() { - let prev = self.prev.replace(PreviousLine { - chunk: file.current_chunk.clone(), - line_idx: file.line_idx, - file_number: file.file_number, + ) -> Result { + let Self { + heap, + request_sender, + prev, + .. + } = self; + let mut source = ThreadedChunkSource { request_sender }; + write_next_line(heap, prev, writer, settings, &mut source) + } +} + +/// Fetches chunks from the reader thread and recycles them back to it over a channel. +#[cfg(not(target_os = "wasi"))] +struct ThreadedChunkSource<'a> { + request_sender: &'a Sender<(usize, RecycledChunk)>, +} + +#[cfg(not(target_os = "wasi"))] +impl ChunkSource for ThreadedChunkSource<'_> { + fn advance(&mut self, file: &mut MergeableFile<'_>) -> UResult> { + Ok(file.receiver.recv().ok()) + } + + fn recycle(&mut self, file_number: usize, chunk: Chunk) { + self.request_sender + .send((file_number, chunk.recycle())) + .ok(); + } +} + +/// Merge files without limiting how many files are concurrently open. +/// +/// WASI has no threads, so chunks are read synchronously, right when the +/// merger needs them, instead of by a background reader thread. +/// +/// It is the responsibility of the caller to ensure that `files` yields only +/// as many files as we are allowed to open concurrently. +#[cfg(target_os = "wasi")] +fn merge_without_limit>>( + files: F, + settings: &GlobalSettings, +) -> UResult> { + let separator = settings.line_ending.into(); + let mut reader_files = Vec::with_capacity(files.size_hint().0); + for file in files { + reader_files.push(Some(ReaderFile { + file: file?, + carry_over: vec![], + finished: false, + recycled: None, + })); + } + + // The merge comparator (`merge_compare`) compares whole-line locale keys lazily + // with the ICU collator, so chunks don't need precomputed per-line sort keys. + // Disabling `fast_locale_collation` here turns `Line::create` into a no-op for + // that (whole-line, default) mode when reading, same as the threaded merger. + let mut read_settings = settings.clone(); + read_settings.precomputed.fast_locale_collation = false; + + let mut mergeable_files = vec![]; + for (file_number, reader_file) in reader_files.iter_mut().enumerate() { + let chunk = read_next_chunk(reader_file.as_mut().unwrap(), &read_settings, separator)?; + if let Some(chunk) = chunk { + mergeable_files.push(MergeableFile { + current_chunk: Rc::new(chunk), + file_number, + line_idx: 0, + settings, }); + } else { + let ReaderFile { file, .. } = reader_file.take().unwrap(); + file.finished_reading()?; + } + } - file.current_chunk.with_dependent(|_, contents| { - let current_line = &contents.lines[file.line_idx]; - if settings.unique - && let Some(prev) = &prev - { - let cmp = merge_compare( - &prev.chunk.lines()[prev.line_idx], - current_line, - settings, - prev.chunk.line_data(), - file.current_chunk.line_data(), - ); - if cmp == Ordering::Equal { - return Ok(()); - } - } - current_line.write(writer, settings) - })?; + Ok(FileMerger { + heap: BinaryHeap::from(mergeable_files), + reader_files, + prev: None, + separator, + read_settings, + }) +} - let was_last_line_for_file = file.current_chunk.lines().len() == file.line_idx + 1; +/// The struct representing an input file, read synchronously on demand. +#[cfg(target_os = "wasi")] +struct ReaderFile { + file: M, + carry_over: Vec, + /// Set once there is nothing left to read; stops a stale `carry_over` tail from being + /// misparsed as a spurious extra chunk. + finished: bool, + /// A finished chunk's buffer, recycled here instead of to a reader thread, for reuse + /// on this file's next read. + recycled: Option, +} + +/// Reads the next chunk of `reader_file`, or `None` at end of file. +#[cfg(target_os = "wasi")] +fn read_next_chunk( + reader_file: &mut ReaderFile, + settings: &GlobalSettings, + separator: u8, +) -> UResult> { + if reader_file.finished { + return Ok(None); + } + let recycled_chunk = reader_file + .recycled + .take() + .unwrap_or_else(|| RecycledChunk::new(8 * 1024)); + let (chunk, should_continue) = chunks::read_once( + recycled_chunk, + &mut reader_file.carry_over, + reader_file.file.as_read(), + separator, + settings, + )?; + reader_file.finished = !should_continue; + Ok(chunk) +} - if was_last_line_for_file { - if let Ok(next_chunk) = file.receiver.recv() { - let mut file = self.heap.peek_mut().unwrap(); - file.current_chunk = Rc::new(next_chunk); - file.line_idx = 0; - } else { - self.heap.pop(); - } - } else { - // This will cause the comparison to use a different line and the heap to readjust. - self.heap.peek_mut().unwrap().line_idx += 1; - } +/// Merges files together. This is **not** an iterator because of lifetime problems. +/// +/// WASI has no threads, so there is no reader thread to request chunks from; +/// `reader_files` holds each input directly, read from on demand. +#[cfg(target_os = "wasi")] +struct FileMerger<'a, M: MergeInput> { + heap: BinaryHeap>, + reader_files: Vec>>, + prev: Option, + separator: u8, + /// A clone of the real settings with `fast_locale_collation` forced off, used only for + /// reading chunks. See the comment in `merge_without_limit`. + read_settings: GlobalSettings, +} - if let Some(prev) = prev - && let Ok(prev_chunk) = Rc::try_unwrap(prev.chunk) - { - // If nothing is referencing the previous chunk anymore, this means that the previous line - // was the last line of the chunk. We can recycle the chunk. - self.request_sender - .send((prev.file_number, prev_chunk.recycle())) - .ok(); - } +#[cfg(target_os = "wasi")] +impl FileMerger<'_, M> { + /// Write the merged contents to the output file. + fn write_all(self, settings: &GlobalSettings, output: Output) -> UResult<()> { + let ctx = output.write_failed_context(); + let mut out = output.into_write()?; + self.write_all_to(settings, &mut out, &ctx)?; + out.flush().map_err_context(ctx) + } + + /// Write the merged contents to `out`, reporting write errors with `ctx`. + fn write_all_to( + mut self, + settings: &GlobalSettings, + out: &mut impl Write, + ctx: impl FnOnce() -> String, + ) -> UResult<()> { + drain_write_next(|| self.write_next(out, settings), ctx) + } + + fn write_next( + &mut self, + writer: &mut impl Write, + settings: &GlobalSettings, + ) -> Result { + let Self { + heap, + reader_files, + prev, + separator, + read_settings, + } = self; + let mut source = WasiChunkSource { + reader_files, + settings: read_settings, + separator: *separator, + }; + write_next_line(heap, prev, writer, settings, &mut source) + } +} + +/// Reads chunks synchronously, right when needed, and recycles them onto the file itself: +/// there is no reader thread to fetch from or send a recycled chunk back to. +#[cfg(target_os = "wasi")] +struct WasiChunkSource<'a, M: MergeInput> { + reader_files: &'a mut Vec>>, + settings: &'a GlobalSettings, + separator: u8, +} + +#[cfg(target_os = "wasi")] +impl ChunkSource for WasiChunkSource<'_, M> { + fn advance(&mut self, file: &mut MergeableFile<'_>) -> UResult> { + let file_number = file.file_number; + let reader_file = self.reader_files[file_number].as_mut().unwrap(); + let next_chunk = read_next_chunk(reader_file, self.settings, self.separator)?; + if next_chunk.is_none() { + let ReaderFile { file, .. } = self.reader_files[file_number].take().unwrap(); + file.finished_reading()?; + } + Ok(next_chunk) + } + + fn recycle(&mut self, file_number: usize, chunk: Chunk) { + if let Some(reader_file) = self.reader_files[file_number].as_mut() { + // If nothing is referencing the previous chunk anymore, this means that the + // previous line was the last line of the chunk. We can recycle the chunk for + // this file's next read. + reader_file.recycled = Some(chunk.recycle()); } - Ok(!self.heap.is_empty()) } } diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index cec38b32a24..c9477160ffb 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -1521,7 +1521,11 @@ pub(crate) fn fd_soft_limit() -> Option { #[cfg(not(unix))] pub(crate) fn fd_soft_limit() -> Option { - None + // WASI has no `getrlimit`. 256 is the traditional POSIX soft `RLIMIT_NOFILE` + // default most systems used before raising it; assume it instead of treating + // `--batch-size`/merge as unbounded, since wasmtime's fd table tends to be small. + const WASI_FD_LIMIT_GUESS: usize = 256; + cfg!(target_os = "wasi").then_some(WASI_FD_LIMIT_GUESS) } /// The largest `--batch-size` argument that can be honoured with the current file diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index 7f63dcec076..a866e4f3bf4 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -42,10 +42,11 @@ fn test_helper(file_name: &str, possible_args: &[&str]) { #[test] fn test_buffer_sizes() { - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", not(wasi_runner)))] let buffer_sizes = ["0", "50K", "50k", "1M", "100M", "0%", "10%"]; - // TODO Percentage sizes are not yet supported beyond Linux. - #[cfg(not(target_os = "linux"))] + // TODO Percentage sizes are not yet supported beyond Linux, and the WASI + // guest cannot query total physical memory either. + #[cfg(not(all(target_os = "linux", not(wasi_runner))))] let buffer_sizes = ["0", "50K", "50k", "1M", "100M"]; for buffer_size in &buffer_sizes { new_ucmd!() @@ -73,8 +74,8 @@ fn test_buffer_sizes() { } } +#[uutests::wasi_ignore(AutomaticBufferSizeDiffers)] #[test] -#[cfg(not(target_os = "wasi"))] fn test_buffer_size_limits_both_chunks() { let line = format!("{}\n", "b".repeat(1022)); let input = line.repeat(1200); @@ -136,7 +137,7 @@ fn test_invalid_buffer_size() { .stderr_only("sort: invalid suffix in --buffer-size argument '100f'\n"); // TODO Percentage sizes are not yet supported beyond Linux. - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", not(wasi_runner)))] new_ucmd!() .arg("-S") .arg("0x123%") @@ -146,7 +147,7 @@ fn test_invalid_buffer_size() { // A percentage can fit in a u128 while its product with the total // physical memory does not; the parser must report it as too large // rather than panicking or silently wrapping. - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", not(wasi_runner)))] new_ucmd!() .arg("-S") .arg("340282366920938463463374607431768211455%") @@ -591,8 +592,8 @@ fn test_random_source_reads_only_the_salt_length() { assert_eq!(from_16, from_longer); } -#[test] #[uutests::wasi_ignore(NoFifo)] +#[test] #[cfg(unix)] fn test_random_source_pipe_only_needs_16_bytes() { use std::io::Write; @@ -908,7 +909,6 @@ fn month_sort_input_expected(months: &[String]) -> (String, String) { #[test] #[cfg(unix)] -#[uutests::wasi_ignore(NoLocaleData)] fn test_month_sort_french_locale() { let locale = "fr_FR.UTF-8"; if !is_locale_available(locale) { @@ -952,7 +952,6 @@ fn test_month_sort_french_locale() { #[test] #[cfg(unix)] -#[uutests::wasi_ignore(NoLocaleData)] fn test_month_sort_hungarian_locale() { let locale = "hu_HU.UTF-8"; if !is_locale_available(locale) { @@ -996,7 +995,6 @@ fn test_month_sort_hungarian_locale() { /// E.g. "av ril" should NOT match "avril" — GNU treats it as unknown. #[test] #[cfg(unix)] -#[uutests::wasi_ignore(NoLocaleData)] fn test_month_sort_french_embedded_blanks() { let locale = "fr_FR.UTF-8"; if !is_locale_available(locale) { @@ -1061,7 +1059,6 @@ fn test_month_sort_french_embedded_blanks() { #[test] #[cfg(unix)] -#[uutests::wasi_ignore(NoLocaleData)] fn test_month_sort_japanese_locale() { let locale = "ja_JP.UTF-8"; if !is_locale_available(locale) { @@ -1447,7 +1444,6 @@ fn test_unterminated_file_not_fused_across_chunk_boundary() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_interleaved() { new_ucmd!() .arg("-m") @@ -1459,7 +1455,6 @@ fn test_merge_interleaved() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_preserves_long_lines() { use std::fmt::Write; @@ -1519,7 +1514,6 @@ fn test_ext_sort_preserves_long_lines() { // receivers while the reader was still sending, and `chunks::read` unwraps that send. #[test] #[cfg(target_os = "linux")] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_write_error_does_not_panic() { use std::fs::File; @@ -1620,7 +1614,6 @@ fn test_merge_flush_error_is_reported() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_unique() { new_ucmd!() .arg("-m") @@ -1636,7 +1629,6 @@ fn test_merge_unique() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_stable() { new_ucmd!() .arg("-m") @@ -1649,7 +1641,6 @@ fn test_merge_stable() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_reversed() { new_ucmd!() .arg("-m") @@ -1929,9 +1920,9 @@ fn test_compress() { .stdout_only_fixture("ext_sort.expected"); } +#[uutests::wasi_ignore(HostPathsNotVisible)] #[test] #[cfg(any(target_os = "linux", target_os = "android"))] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_compress_merge() { new_ucmd!() .args(&[ @@ -1953,9 +1944,9 @@ fn test_compress_merge() { .stdout_only_fixture("merge_ints_interleaved.expected"); } +#[uutests::wasi_ignore(CompressProgramBypassed)] #[test] #[cfg(not(target_os = "android"))] -#[uutests::wasi_ignore(CompressProgramBypassed)] fn test_compress_fail() { let result = new_ucmd!() .args(&[ @@ -2025,8 +2016,8 @@ fn test_batch_size_too_large() { .stderr_contains("maximum --batch-size argument with current rlimit is"); } +#[uutests::wasi_ignore(HostPathsNotVisible)] #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_batch_size() { new_ucmd!() .arg("--batch-size=2") @@ -2042,11 +2033,11 @@ fn test_merge_batch_size() { .stdout_only_fixture("merge_ints_interleaved.expected"); } +#[uutests::wasi_ignore(NoRlimitSetrlimitSupport)] #[test] // TODO(#7542): Re-enable on Android once we figure out why setting limit is broken. // #[cfg(any(target_os = "linux", target_os = "android"))] #[cfg(target_os = "linux")] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_batch_size_with_limit() { // Currently need... // 3 descriptors for stdin, stdout, stderr @@ -2068,6 +2059,7 @@ fn test_merge_batch_size_with_limit() { .stdout_only_fixture("merge_ints_interleaved.expected"); } +#[uutests::wasi_ignore(NoRlimitSetrlimitSupport)] #[test] // TODO(#7542): Re-enable on Android once we figure out why setting limit is broken. #[cfg(target_os = "linux")] @@ -2100,6 +2092,7 @@ fn test_batch_size_at_fd_limit_is_accepted() { .stdout_only("alpha\ndelta\n"); } +#[uutests::wasi_ignore(NoRlimitSetrlimitSupport)] #[test] #[cfg(target_os = "linux")] fn test_merge_more_files_than_fd_limit() { @@ -2149,6 +2142,7 @@ fn test_more_files_than_fd_limit() { .stdout_only(expected); } +#[uutests::wasi_ignore(NoRlimitSetrlimitSupport)] #[test] #[cfg(target_os = "linux")] fn test_temporary_files_with_few_file_descriptors() { @@ -2199,6 +2193,7 @@ fn test_sigpipe_panic() { child.wait().unwrap().no_stderr(); } +#[uutests::wasi_ignore(NoFifo)] #[test] #[cfg(unix)] fn test_fifo_without_trailing_newline() { @@ -2284,9 +2279,9 @@ fn test_verifies_files_after_keys() { .stderr_contains("invalid field specification '0'"); } +#[uutests::wasi_ignore(HostPathsNotVisible)] #[test] #[cfg(unix)] -#[uutests::wasi_ignore(HostPathsNotVisible)] fn test_verifies_input_files() { new_ucmd!() .args(&["/dev/random", "nonexistent_file"]) @@ -2294,6 +2289,7 @@ fn test_verifies_input_files() { .stderr_is("sort: cannot read: nonexistent_file: No such file or directory\n"); } +#[uutests::wasi_ignore(NoFifo)] #[test] #[cfg(unix)] fn test_verifies_input_files_without_opening_them() { @@ -2375,6 +2371,7 @@ fn test_same_separator_twice_ok(#[case] args: &[&str]) { .stdout_only("b:1\na:2\n"); } +#[uutests::wasi_ignore(AbsoluteHostTmpdirOutsideGuestRoot)] #[test] fn test_output_is_input() { let input = "a\nb\nc\n"; @@ -2388,6 +2385,7 @@ fn test_output_is_input() { assert_eq!(at.read("file"), input); } +#[uutests::wasi_ignore(AbsoluteHostTmpdirOutsideGuestRoot)] #[rstest] #[case::newline('\n', &[])] #[case::newline_unique('\n', &["-u"])] @@ -2415,6 +2413,7 @@ fn test_merge_output_is_hard_link_to_input(#[case] separator: char, #[case] args assert_eq!(at.read("output"), input); } +#[uutests::wasi_ignore(AbsoluteHostTmpdirOutsideGuestRoot)] #[rstest] #[case::single_batch(&[])] #[case::multiple_batches(&["--batch-size=2"])] @@ -2483,9 +2482,9 @@ fn test_merge_output_file_is_truncated() { assert_eq!(at.read("merged"), "damson\nquince\n"); } +#[uutests::wasi_ignore(HostPathsNotVisible)] #[test] #[cfg(unix)] -#[uutests::wasi_ignore(HostPathsNotVisible)] fn test_output_device() { new_ucmd!() .args(&["-o", "/dev/null"]) @@ -2494,7 +2493,6 @@ fn test_output_device() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_empty_input() { new_ucmd!() .args(&["-m", "empty.txt"]) @@ -2518,9 +2516,9 @@ fn test_wrong_args_exit_code() { .stderr_contains("--misspelled"); } +#[uutests::wasi_ignore(NoPipeSignalSupport)] #[test] #[cfg(unix)] -#[uutests::wasi_ignore(NoPipeSignalSupport)] fn test_tmp_files_deleted_on_sigint() { use rand::{RngExt as _, SeedableRng, rngs::SmallRng}; use rustix::process::{Pid, Signal, kill_process}; @@ -2567,6 +2565,7 @@ fn test_tmp_files_deleted_on_sigint() { assert!(read_dir(at.plus("tmp_dir")).unwrap().next().is_none()); } +#[uutests::wasi_ignore(AutomaticBufferSizeDiffers)] #[test] #[cfg(unix)] fn test_tmp_files_are_private() { @@ -2612,6 +2611,7 @@ fn test_tmp_files_are_private() { child.wait().unwrap().code_is(2); } +#[uutests::wasi_ignore(NoFifo)] #[test] #[cfg(all(unix, not(target_os = "redox")))] fn test_tmp_dir_replaced_by_a_symlink() { @@ -2714,8 +2714,8 @@ fn test_args_check_conflict() { } #[cfg(target_os = "linux")] -#[test] #[uutests::wasip2_ignore(StreamWriteGenericIoError)] +#[test] fn test_failed_write_is_reported() { new_ucmd!() .pipe_in("hello") @@ -2834,9 +2834,9 @@ fn test_files0_from_empty_input_file() { .stderr_only("sort: no input from 'file'\n"); } +#[uutests::wasip2_ignore(OsStringRequiresUtf8)] #[test] #[cfg(unix)] -#[uutests::wasip2_ignore(OsStringRequiresUtf8)] fn test_files0_from_non_utf8_filename() { new_ucmd!() .args(&["--files0-from", "-"]) @@ -2845,6 +2845,7 @@ fn test_files0_from_non_utf8_filename() { .stderr_contains("sort: cannot read"); } +#[uutests::wasi_ignore(ErrnoMessageMismatch)] #[rstest::rstest] #[case(&["-c", "dir"])] #[case(&["-C", "dir"])] @@ -2861,9 +2862,9 @@ fn test_read_error_on_reader_thread(#[case] args: &[&str]) { .stderr_does_not_contain("sort-read-failed"); } +#[uutests::wasi_ignore(ErrnoMessageMismatch)] #[test] #[cfg(unix)] -#[uutests::wasip2_ignore(OsErrorMessageDiffers)] fn test_files0_from_unreadable_source() { new_ucmd!() .args(&["--files0-from", "."]) @@ -2872,9 +2873,9 @@ fn test_files0_from_unreadable_source() { } #[cfg(unix)] +#[uutests::wasi_ignore(HostPathsNotVisible)] #[test] // Test files0-from with non-regular empty file -#[uutests::wasi_ignore(HostPathsNotVisible)] fn test_files0_from_dev_null_is_empty() { new_ucmd!() .args(&["--files0-from", "/dev/null"]) @@ -2958,10 +2959,10 @@ fn test_files0_from_two_entries_trailing_nul() { .stdout_only("kiwi\nkiwi\nmango\nmango\n"); } +#[uutests::wasi_ignore(NonUtf8ArgsUnsupported)] #[test] // Test files0-from with non-UTF-8 filenames #[cfg(all(unix, not(target_vendor = "apple")))] -#[uutests::wasi_ignore(NonUtf8ArgsUnsupported)] fn test_files0_from_non_utf8_content() { use std::os::unix::ffi::OsStringExt; let (at, mut ucmd) = at_and_ucmd!(); @@ -3961,8 +3962,8 @@ fn test_locale_collation_utf8() { } } -#[test] #[uutests::wasi_ignore(NoLocaleData)] +#[test] fn test_locale_interleaved_en_us_utf8() { // Test case for issue: locale-based collation support // In en_US.UTF-8, lowercase and uppercase letters should interleave @@ -4034,8 +4035,8 @@ fn test_locale_with_ignore_case_flag() { ); } -#[test] #[uutests::wasi_ignore(NoLocaleData)] +#[test] fn test_locale_complex_utf8_sorting() { // More complex test with mixed case and special characters // In en_US.UTF-8, should respect locale collation rules @@ -4059,8 +4060,8 @@ fn test_locale_posix_sort_debug_message() { .stderr_contains("text ordering performed using simple byte comparison"); } -#[test] #[uutests::wasi_ignore(NoLocaleData)] +#[test] fn test_locale_utf8_sort_debug_message() { new_ucmd!() .env("LC_ALL", "en_US.UTF-8") @@ -4114,8 +4115,8 @@ fn test_empty_input_empty_output() { assert_eq!(at.read("file"), ""); } -#[test] #[uutests::wasi_ignore(NoLocaleData)] +#[test] fn test_consistent_sorting_with_i18n_collate() { // Regression test for issue #11980 // Lexicographic fallback sorting for equal sorting keys for 01 and 0_1 diff --git a/tests/uutests_procs/src/lib.rs b/tests/uutests_procs/src/lib.rs index e12e82b416a..1c27f68d010 100644 --- a/tests/uutests_procs/src/lib.rs +++ b/tests/uutests_procs/src/lib.rs @@ -26,6 +26,9 @@ fn wasi_reason(key: &str) -> Option<&'static str> { "AddressSpaceLimitUnsuitable" => { "WASI runner target is not suitable for this address-space-limit regression test" } + "AutomaticBufferSizeDiffers" => { + "WASI: sort's automatic buffer-size heuristic (based on queried available memory) behaves differently under wasm32, so disk-spill thresholds don't match the host" + } "CannotDetectUnsafeOverwrite" => "WASI: cannot detect unsafe overwrite", "CannotExecShellFromDeletedCwd" => { "WASI: wasmtime cannot exec the binary via a raw shell from a deleted cwd" @@ -80,9 +83,6 @@ fn wasi_reason(key: &str) -> Option<&'static str> { "NoRlimitSetrlimitSupport" => "WASI: rlimit/setrlimit not supported", "NoStdoutFileRedirection" => "WASI: no stdout-to-file redirection", "NoSubprocessSpawning" => "WASI: no subprocess spawning", - "NoThreadSpawning" => { - "WASI: sort -m spawns real OS threads for multi-file merge, unsupported under wasmtime's default config" - } "NoTzdb" => { "WASI: no tzdb; TZ env var is not honoured, so timezone-dependent behaviour (DST validation, timestamps) differs from the host" }