diff --git a/.github/workflows/wasi.yml b/.github/workflows/wasi.yml index e09bad73322..1bf4a26009f 100644 --- a/.github/workflows/wasi.yml +++ b/.github/workflows/wasi.yml @@ -92,6 +92,6 @@ 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_sum:: test_tail:: test_tee:: \ + test_sort::sort_multiple test_sort::test_check 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 118d2d0fa6a..867df884186 100644 --- a/src/uu/sort/src/check.rs +++ b/src/uu/sort/src/check.rs @@ -11,9 +11,9 @@ use crate::{ compare_by, open, }; use itertools::Itertools; +use std::{cmp::Ordering, ffi::OsStr}; +#[cfg(not(target_os = "wasi"))] use std::{ - cmp::Ordering, - ffi::OsStr, io::Read, iter, sync::mpsc::{Receiver, SyncSender, sync_channel}, @@ -21,11 +21,75 @@ use std::{ }; use uucore::error::UResult; +fn buffer_size(settings: &GlobalSettings) -> usize { + if settings.buffer_size < 100 * 1024 { + // when the buffer size is smaller than 100KiB we choose it instead of the default. + // this improves testability. + settings.buffer_size + } else { + 100 * 1024 + } +} + +/// Checks `chunk` against the end of `prev_chunk` (if any) and within itself. +/// +/// Returns [`SortError::Disorder`] for the first line that violates the requested +/// ordering. `line_idx` is the running line count and is advanced as lines are checked. +fn check_chunk( + path: &OsStr, + settings: &GlobalSettings, + max_allowed_cmp: Ordering, + prev_chunk: Option<&Chunk>, + chunk: &Chunk, + line_idx: &mut usize, +) -> UResult<()> { + *line_idx += 1; + if let Some(prev_chunk) = prev_chunk { + // Check if the first element of the new chunk is greater than the last + // element from the previous chunk + let prev_last = prev_chunk.lines().last().unwrap(); + let new_first = chunk.lines().first().unwrap(); + + if compare_by( + prev_last, + new_first, + settings, + prev_chunk.line_data(), + chunk.line_data(), + ) > max_allowed_cmp + { + return Err(SortError::Disorder { + file: path.to_owned(), + line_number: *line_idx, + line: String::from_utf8_lossy(new_first.line).into_owned(), + silent: settings.check_silent, + } + .into()); + } + } + + for (a, b) in chunk.lines().iter().tuple_windows() { + *line_idx += 1; + if compare_by(a, b, settings, chunk.line_data(), chunk.line_data()) > max_allowed_cmp { + return Err(SortError::Disorder { + file: path.to_owned(), + line_number: *line_idx, + line: String::from_utf8_lossy(b.line).into_owned(), + silent: settings.check_silent, + } + .into()); + } + } + + Ok(()) +} + /// Check if the file at `path` is ordered. /// /// # Returns /// /// The code we should exit with. +#[cfg(not(target_os = "wasi"))] pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { let max_allowed_cmp = if settings.unique { // If `unique` is enabled, the previous line must compare _less_ to the next one. @@ -42,13 +106,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { move || reader(file, &recycled_receiver, &loaded_sender, &settings) }); for _ in 0..2 { - let _ = recycled_sender.send(RecycledChunk::new(if settings.buffer_size < 100 * 1024 { - // when the buffer size is smaller than 100KiB we choose it instead of the default. - // this improves testability. - settings.buffer_size - } else { - 100 * 1024 - })); + let _ = recycled_sender.send(RecycledChunk::new(buffer_size(settings))); } let mut prev_chunk: Option = None; @@ -60,47 +118,21 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { // disorder, the reader is usually still working at that point, so we shut it down // in an orderly fashion below instead of just dropping our end. 'outer: for chunk in &loaded_receiver { - line_idx += 1; + if let Err(e) = check_chunk( + path, + settings, + max_allowed_cmp, + prev_chunk.as_ref(), + &chunk, + &mut line_idx, + ) { + result = Err(e); + break 'outer; + } if let Some(prev_chunk) = prev_chunk.take() { - // Check if the first element of the new chunk is greater than the last - // element from the previous chunk - let prev_last = prev_chunk.lines().last().unwrap(); - let new_first = chunk.lines().first().unwrap(); - - if compare_by( - prev_last, - new_first, - settings, - prev_chunk.line_data(), - chunk.line_data(), - ) > max_allowed_cmp - { - result = Err(SortError::Disorder { - file: path.to_owned(), - line_number: line_idx, - line: String::from_utf8_lossy(new_first.line).into_owned(), - silent: settings.check_silent, - } - .into()); - break 'outer; - } let _ = recycled_sender.send(prev_chunk.recycle()); } - for (a, b) in chunk.lines().iter().tuple_windows() { - line_idx += 1; - if compare_by(a, b, settings, chunk.line_data(), chunk.line_data()) > max_allowed_cmp { - result = Err(SortError::Disorder { - file: path.to_owned(), - line_number: line_idx, - line: String::from_utf8_lossy(b.line).into_owned(), - silent: settings.check_silent, - } - .into()); - break 'outer; - } - } - prev_chunk = Some(chunk); } @@ -117,7 +149,55 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { result.and(reader_result) } +/// Check if the file at `path` is ordered. +/// +/// WASI has no threads, so chunks are read and checked on the current thread, +/// one chunk at a time, stopping as soon as a disorder is found. +#[cfg(target_os = "wasi")] +pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { + let max_allowed_cmp = if settings.unique { + Ordering::Less + } else { + Ordering::Equal + }; + + 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; + loop { + let recycled = RecycledChunk::new(buffer_size(settings)); + let should_continue = chunks::read( + &sender, + recycled, + None, + &mut carry_over, + &mut file, + &mut std::iter::empty(), + settings.line_ending.into(), + settings, + )?; + while let Ok(chunk) = receiver.try_recv() { + check_chunk( + path, + settings, + max_allowed_cmp, + prev_chunk.as_ref(), + &chunk, + &mut line_idx, + )?; + prev_chunk = Some(chunk); + } + if !should_continue { + break; + } + } + Ok(()) +} + /// The function running on the reader thread. +#[cfg(not(target_os = "wasi"))] fn reader( mut file: Box, receiver: &Receiver, diff --git a/src/uu/sort/src/ext_sort/wasi.rs b/src/uu/sort/src/ext_sort/wasi.rs index fb0577324d5..a18c1190041 100644 --- a/src/uu/sort/src/ext_sort/wasi.rs +++ b/src/uu/sort/src/ext_sort/wasi.rs @@ -32,6 +32,10 @@ pub fn ext_sort( // moderately sized inputs; very large files may cause OOM. let mut input = Vec::new(); for file in files { + // Without a separator the last line of one file merges with the first line of the next. + if !input.is_empty() && input.last() != Some(&separator) { + input.push(separator); + } file?.read_to_end(&mut input)?; } diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index eb2c60aea74..20cfeb0d933 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -57,7 +57,8 @@ fn test_buffer_sizes() { .stdout_is_fixture("ext_sort.expected"); } - #[cfg(not(target_pointer_width = "32"))] + // The WASI guest is always 32-bit, so these values overflow there. + #[cfg(not(any(target_pointer_width = "32", wasi_runner)))] { let buffer_sizes = ["1000G", "10T"]; for buffer_size in &buffer_sizes { @@ -842,6 +843,7 @@ 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) { @@ -885,6 +887,7 @@ 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) { @@ -928,6 +931,7 @@ 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) { @@ -992,6 +996,7 @@ 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) { @@ -1377,6 +1382,7 @@ fn test_unterminated_file_not_fused_across_chunk_boundary() { } #[test] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_interleaved() { new_ucmd!() .arg("-m") @@ -1388,6 +1394,7 @@ fn test_merge_interleaved() { } #[test] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_preserves_long_lines() { use std::fmt::Write; @@ -1447,6 +1454,7 @@ 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; @@ -1547,6 +1555,7 @@ fn test_merge_flush_error_is_reported() { } #[test] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_unique() { new_ucmd!() .arg("-m") @@ -1562,6 +1571,7 @@ fn test_merge_unique() { } #[test] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_stable() { new_ucmd!() .arg("-m") @@ -1574,6 +1584,7 @@ fn test_merge_stable() { } #[test] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_reversed() { new_ucmd!() .arg("-m") @@ -1855,6 +1866,7 @@ fn test_compress() { #[test] #[cfg(any(target_os = "linux", target_os = "android"))] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_compress_merge() { new_ucmd!() .args(&[ @@ -1878,6 +1890,7 @@ fn test_compress_merge() { #[test] #[cfg(not(target_os = "android"))] +#[uutests::wasi_ignore(CompressProgramBypassed)] fn test_compress_fail() { let result = new_ucmd!() .args(&[ @@ -1940,7 +1953,7 @@ fn test_batch_size_too_large() { "--batch-size argument '{large_batch_size}' too large" )); - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", not(wasi_runner)))] new_ucmd!() .arg(format!("--batch-size={large_batch_size}")) .fails_with_code(2) @@ -1948,6 +1961,7 @@ fn test_batch_size_too_large() { } #[test] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_batch_size() { new_ucmd!() .arg("--batch-size=2") @@ -1967,6 +1981,7 @@ 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 @@ -2206,6 +2221,7 @@ fn test_verifies_files_after_keys() { #[test] #[cfg(unix)] +#[uutests::wasi_ignore(HostPathsNotVisible)] fn test_verifies_input_files() { new_ucmd!() .args(&["/dev/random", "nonexistent_file"]) @@ -2343,6 +2359,7 @@ fn test_merge_output_file_is_truncated() { #[test] #[cfg(unix)] +#[uutests::wasi_ignore(HostPathsNotVisible)] fn test_output_device() { new_ucmd!() .args(&["-o", "/dev/null"]) @@ -2351,6 +2368,7 @@ fn test_output_device() { } #[test] +#[uutests::wasi_ignore(NoThreadSpawning)] fn test_merge_empty_input() { new_ucmd!() .args(&["-m", "empty.txt"]) @@ -2376,6 +2394,7 @@ fn test_wrong_args_exit_code() { #[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}; @@ -2570,6 +2589,7 @@ fn test_args_check_conflict() { #[cfg(target_os = "linux")] #[test] +#[uutests::wasip2_ignore(StreamWriteGenericIoError)] fn test_failed_write_is_reported() { new_ucmd!() .pipe_in("hello") @@ -2690,6 +2710,7 @@ fn test_files0_from_empty_input_file() { #[test] #[cfg(unix)] +#[uutests::wasip2_ignore(OsStringRequiresUtf8)] fn test_files0_from_non_utf8_filename() { new_ucmd!() .args(&["--files0-from", "-"]) @@ -2716,6 +2737,7 @@ fn test_read_error_on_reader_thread(#[case] args: &[&str]) { #[test] #[cfg(unix)] +#[uutests::wasip2_ignore(OsErrorMessageDiffers)] fn test_files0_from_unreadable_source() { new_ucmd!() .args(&["--files0-from", "."]) @@ -2726,6 +2748,7 @@ fn test_files0_from_unreadable_source() { #[cfg(unix)] #[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"]) @@ -2812,6 +2835,7 @@ fn test_files0_from_two_entries_trailing_nul() { #[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!(); @@ -3798,6 +3822,7 @@ fn test_locale_collation_utf8() { } #[test] +#[uutests::wasi_ignore(NoLocaleData)] 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 @@ -3870,6 +3895,7 @@ fn test_locale_with_ignore_case_flag() { } #[test] +#[uutests::wasi_ignore(NoLocaleData)] 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 @@ -3894,6 +3920,7 @@ fn test_locale_posix_sort_debug_message() { } #[test] +#[uutests::wasi_ignore(NoLocaleData)] fn test_locale_utf8_sort_debug_message() { new_ucmd!() .env("LC_ALL", "en_US.UTF-8") @@ -3914,7 +3941,7 @@ fn test_failed_to_set_locale_debug_message() { result.stderr_contains("text ordering performed using simple byte comparison"); - #[cfg(all(target_os = "linux", target_env = "gnu"))] + #[cfg(all(target_os = "linux", target_env = "gnu", not(wasi_runner)))] result.stderr_contains("failed to set locale"); } @@ -3948,6 +3975,7 @@ fn test_empty_input_empty_output() { } #[test] +#[uutests::wasi_ignore(NoLocaleData)] 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 ea27a15419c..c1c16bc31b7 100644 --- a/tests/uutests_procs/src/lib.rs +++ b/tests/uutests_procs/src/lib.rs @@ -33,6 +33,9 @@ fn wasi_reason(key: &str) -> Option<&'static str> { "ClosedStdoutGenericIoError" => { "WASI: closed stdout reports a generic I/O error rather than BrokenPipe" } + "CompressProgramBypassed" => { + "WASI: ext_sort bypasses --compress-program entirely (single-threaded in-memory path)" + } "DebugReportsUnsupported" => { "WASI: --debug reports 'unsupported' instead of 'unknown' for this platform" } @@ -77,6 +80,9 @@ 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" } @@ -127,6 +133,9 @@ fn wasip2_reason(key: &str) -> Option<&'static str> { "StreamWriteGenericIoError" => { "WASI P2: stream write errors report a generic I/O error instead of their errno, for example ENOSPC on a full device" } + "OsErrorMessageDiffers" => { + "WASI P2: the error message text for this OS error differs from native Unix" + } "OsStringRequiresUtf8" => "WASI P2: OsString requires valid UTF-8, unlike unix and WASI P1", _ => return None, })