diff --git a/.github/workflows/wasi.yml b/.github/workflows/wasi.yml index 7312282557f..a06ba521a03 100644 --- a/.github/workflows/wasi.yml +++ b/.github/workflows/wasi.yml @@ -76,7 +76,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 ls rm seq sort + # csplit ls rm seq # 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" \ @@ -92,7 +92,7 @@ jobs: test_paste:: test_pathchk:: test_pr:: test_printenv:: test_printf:: test_ptx:: \ test_pwd:: test_readlink:: test_realpath:: test_rmdir:: 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..cc071304003 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,99 @@ 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), +} + +/// 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 +448,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,16 +465,17 @@ impl FileMerger<'_> { out: &mut impl Write, ctx: impl FnOnce() -> String, ) -> UResult<()> { - let write_result = loop { + let write_result: UResult<()> = 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 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. + Err(WriteNextError::Write(error)) => break Err(error).map_err_context(ctx), + // `advance` never errors on this platform: chunks are always read on the + // reader thread, whose errors are reported separately via `reader_result`. + Err(WriteNextError::Chunk(error)) => break Err(error), } }; @@ -400,66 +502,225 @@ 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, + })); + } + + 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(), 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, + }) +} - 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 `chunks::read` has reported there is nothing left to read. + /// + /// `chunks::read` can leave unused, zero-filled buffer space in + /// `carry_over` once it has reported `false`; calling it again would + /// misparse that padding as a spurious extra chunk, so this must be + /// checked instead of only looking at whether a chunk was sent. + finished: bool, + /// A finished chunk's buffer, handed back by `FileMerger::write_next` once + /// nothing references it anymore, to reuse for this file's next read + /// instead of allocating a fresh one. There is no reader thread to send it + /// to here, so it is kept on the file itself until the 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, +} - 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<()> { + loop { + match self.write_next(out, settings) { + Ok(true) => (), + Ok(false) => break Ok(()), + // A read failure already has its own context; wrapping it as a write + // failure here would be misleading. + Err(WriteNextError::Write(error)) => break Err(error).map_err_context(ctx), + Err(WriteNextError::Chunk(error)) => break Err(error), } } - Ok(!self.heap.is_empty()) + } + + fn write_next( + &mut self, + writer: &mut impl Write, + settings: &GlobalSettings, + ) -> Result { + let Self { + heap, + reader_files, + prev, + separator, + } = self; + let mut source = WasiChunkSource { + reader_files, + 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()); + } } } diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index 87e8d259dc3..cc8bab5326e 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(all(unix, not(target_os = "fuchsia"))))] 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 30937762dc6..fea2e1ef6b7 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -73,8 +73,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); @@ -591,8 +591,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; @@ -864,7 +864,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) { @@ -908,7 +907,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) { @@ -952,7 +950,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) { @@ -1017,7 +1014,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) { @@ -1403,7 +1399,6 @@ fn test_unterminated_file_not_fused_across_chunk_boundary() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_interleaved() { new_ucmd!() .arg("-m") @@ -1415,7 +1410,6 @@ fn test_merge_interleaved() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_preserves_long_lines() { use std::fmt::Write; @@ -1475,7 +1469,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; @@ -1576,7 +1569,6 @@ fn test_merge_flush_error_is_reported() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_unique() { new_ucmd!() .arg("-m") @@ -1592,7 +1584,6 @@ fn test_merge_unique() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_stable() { new_ucmd!() .arg("-m") @@ -1605,7 +1596,6 @@ fn test_merge_stable() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_reversed() { new_ucmd!() .arg("-m") @@ -1887,7 +1877,6 @@ fn test_compress() { #[test] #[cfg(any(target_os = "linux", target_os = "android"))] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_compress_merge() { new_ucmd!() .args(&[ @@ -1909,9 +1898,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(&[ @@ -1981,8 +1970,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") @@ -2002,7 +1991,6 @@ fn test_merge_batch_size() { // 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 @@ -2155,6 +2143,7 @@ fn test_sigpipe_panic() { child.wait().unwrap().no_stderr(); } +#[uutests::wasi_ignore(NoFifo)] #[test] #[cfg(unix)] fn test_fifo_without_trailing_newline() { @@ -2240,9 +2229,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"]) @@ -2250,6 +2239,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() { @@ -2331,6 +2321,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"; @@ -2344,6 +2335,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"])] @@ -2371,6 +2363,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"])] @@ -2439,9 +2432,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"]) @@ -2450,7 +2443,6 @@ fn test_output_device() { } #[test] -#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_empty_input() { new_ucmd!() .args(&["-m", "empty.txt"]) @@ -2474,9 +2466,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}; @@ -2523,6 +2515,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() { @@ -2568,6 +2561,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() { @@ -2670,8 +2664,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") @@ -2790,9 +2784,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", "-"]) @@ -2817,9 +2811,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", "."]) @@ -2828,9 +2822,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"]) @@ -3917,8 +3911,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 @@ -3990,8 +3984,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 @@ -4015,8 +4009,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") @@ -4070,8 +4064,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 3abb8a19964..f108543d31c 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" @@ -83,9 +86,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" }