diff --git a/Cargo.lock b/Cargo.lock index dcc22d52233..0a8f4c723fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4433,6 +4433,7 @@ dependencies = [ "xattr", "xxhash-rust", "z85", + "zerocopy", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index c71f768e5ef..6e5f39eb393 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -141,6 +141,7 @@ wild = "2.2.1" windows-sys = { version = ">=0.60, <0.62", default-features = false } xattr = { version = "1.3.1", default-features = false } z85 = "3.0.5" +zerocopy = { version = "0.8.57", default-features = false } zip = { version = "9.0.0", default-features = false, features = [ "deflate-flate2-zlib-rs", ] } diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 328447ce434..6b14180bd41 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -1839,6 +1839,7 @@ dependencies = [ "windows-sys", "xxhash-rust", "z85", + "zerocopy", ] [[package]] @@ -1980,6 +1981,26 @@ version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6e61e59a957b7ccee15d2049f86e8bfd6f66968fcd88f018950662d9b86e675" +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" diff --git a/src/uu/cp/Cargo.toml b/src/uu/cp/Cargo.toml index 43666874ca9..7a70e483de6 100644 --- a/src/uu/cp/Cargo.toml +++ b/src/uu/cp/Cargo.toml @@ -40,6 +40,7 @@ uucore = { workspace = true, features = ["fsxattr"] } [target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] selinux = { workspace = true, optional = true } +uucore = { workspace = true, features = ["zeroed-alloc"] } [target.'cfg(any(target_os = "linux", target_os = "android", target_os = "wasi"))'.dependencies] rustix = { workspace = true, features = ["fs"] } diff --git a/src/uu/cp/src/platform/linux.rs b/src/uu/cp/src/platform/linux.rs index de523cf5343..51405a41eee 100644 --- a/src/uu/cp/src/platform/linux.rs +++ b/src/uu/cp/src/platform/linux.rs @@ -163,7 +163,7 @@ fn sparse_copy_without_hole_fd(src_file: &File, dst_file: &File, context: &str) // At least 1 byte, so that a source that was empty at fstat time but // gained data before the SEEK_DATA loop cannot make `step_by` panic. let step = size.clamp(1, 16 * 1024 * 1024) as usize; - let mut buf: Vec = vec![0x0; step]; + let mut buf = uucore::zeroed_alloc::try_new_vec(step).map_err(ctx_err)?; while let Ok(data) = seek(src_file, SeekFrom::Data(current_offset)) { current_offset = data; let Ok(hole) = seek(src_file, SeekFrom::Hole(current_offset)) else { diff --git a/src/uu/dd/Cargo.toml b/src/uu/dd/Cargo.toml index df7e9aba07f..f1318ded2e7 100644 --- a/src/uu/dd/Cargo.toml +++ b/src/uu/dd/Cargo.toml @@ -27,6 +27,7 @@ uucore = { workspace = true, features = [ "quoting-style", "fs", "signals", + "zeroed-alloc", ] } [target.'cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))'.dependencies] diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index 6d6978cd2c0..37879396ec1 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -163,11 +163,11 @@ impl Num { /// /// `O_DIRECT` fails reads with `EINVAL` when the user buffer does not meet /// the device's DMA alignment (typically 512 bytes; 4 KiB covers every -/// mainline Linux block driver). Over-allocates [`alloc_copy_buffer`] -/// storage by one alignment unit and slices at the first aligned byte, -/// keeping the pages zeroed and not faulted in. +/// mainline Linux block driver). Over-allocates the backing storage by one +/// alignment unit and slices at the first aligned byte, keeping the pages +/// zeroed and not faulted in. struct AlignedBuf { - storage: Vec, + storage: Box<[u8]>, /// Distance from the start of `storage` to the first aligned byte; /// `offset + len <= storage.len()` since `storage` is over-allocated /// by `ALIGNMENT`. @@ -183,7 +183,7 @@ impl AlignedBuf { let total = size .checked_add(Self::ALIGNMENT) .ok_or_else(|| io::Error::from(io::ErrorKind::OutOfMemory))?; - let storage = alloc_copy_buffer(total)?; + let storage = uucore::zeroed_alloc::try_new_boxed_slice::(total)?; let misalignment = storage.as_ptr().addr() % Self::ALIGNMENT; let offset = if misalignment == 0 { 0 @@ -1461,26 +1461,6 @@ fn make_linux_oflags(oflags: &OFlags) -> Option { if flag == 0 { None } else { Some(flag) } } -/// The copy buffer, `bsize` bytes long and ready to be read into. -/// -/// `Read::read` fills an initialized slice, and zeroed pages are the only -/// initialization that costs nothing: `vec![0; n]` allocates through -/// `alloc_zeroed`, so the pages arrive from the kernel already zero and stay -/// untouched until something is read into them. Writing a fill byte over -/// reserved capacity instead faults in the whole of `bs=` before the first -/// read, which is what made a large `bs=` cost its full size in time and in -/// resident memory even with nothing to copy. -/// -/// The reservation still happens first, because `vec![0; n]` aborts when the -/// allocation fails and `dd` reports that as an error instead. -fn alloc_copy_buffer(bsize: usize) -> io::Result> { - let mut probe: Vec = Vec::new(); - // try_with_capacity is unstable https://github.com/rust-lang/rust/issues/91913 - probe.try_reserve(bsize)?; - drop(probe); - Ok(vec![0u8; bsize]) -} - /// Read one block worth of data, applying `conv=sync` and `conv=swab`. /// /// `read_buf` is the page-aligned scratch read into directly. The other diff --git a/src/uu/split/Cargo.toml b/src/uu/split/Cargo.toml index 8bbeea0ca68..2e7bd5f8665 100644 --- a/src/uu/split/Cargo.toml +++ b/src/uu/split/Cargo.toml @@ -21,7 +21,7 @@ fluent = { workspace = true } memchr = { workspace = true } tempfile = { workspace = true } thiserror = { workspace = true } -uucore = { workspace = true, features = ["fs", "parser-size"] } +uucore = { workspace = true, features = ["fs", "parser-size", "zeroed-alloc"] } [target.'cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))'.dependencies] rustix = { workspace = true, features = ["fs"] } diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index 7cd4283bdd0..65a7e872216 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -656,7 +656,7 @@ impl ByteChunkWriter<'_> { // different underlying writers. In that case, each iteration of // this loop writes to the underlying writer that corresponds to // the current chunk number. - let mut io_blk = vec![0u8; io_blksize]; + let mut io_blk = uucore::zeroed_alloc::try_new_vec(io_blksize)?; while let mut buf = reader.read(&mut io_blk).map(|n| &io_blk[..n])? && !buf.is_empty() { @@ -796,7 +796,7 @@ impl<'a> LineChunkWriter<'a> { // multiple different underlying writers. In that case, each // run of lines is written to the underlying writer that // corresponds to its chunk number. - let mut io_blk = vec![0u8; io_blksize]; + let mut io_blk = uucore::zeroed_alloc::try_new_vec(io_blksize)?; while let buf = reader.read(&mut io_blk).map(|n| &io_blk[..n])? && !buf.is_empty() { diff --git a/src/uucore/Cargo.toml b/src/uucore/Cargo.toml index 3d08f9a0443..0aec8f2c1ce 100644 --- a/src/uucore/Cargo.toml +++ b/src/uucore/Cargo.toml @@ -42,6 +42,7 @@ unicode-width = { workspace = true } unit-prefix = { workspace = true, optional = true } uucore_procs = { workspace = true } z85 = { workspace = true, optional = true } +zerocopy = { workspace = true, optional = true, features = ["alloc"] } # Benchmark dependencies (optional) tempfile = { workspace = true, optional = true } @@ -230,6 +231,7 @@ sum = [ "xxhash-rust", "crc-fast", "data-encoding", + "zeroed-alloc", ] systemd_logind = ["utmpx", "libc"] # Use OpenSSL (libcrypto) for md5/sha1/sha2-family digests instead of the @@ -241,6 +243,7 @@ utf8 = [] utmpx = ["time", "time/macros", "libc", "dns-lookup"] version-cmp = [] wide = [] +zeroed-alloc = ["dep:zerocopy"] time = ["jiff"] uptime = ["jiff", "libc", "rustix/time", "utmp-classic", "utmpx", "windows-sys"] benchmark = ["itertools", "tempfile"] diff --git a/src/uucore/src/lib/features.rs b/src/uucore/src/lib/features.rs index b6677a6ec51..1c33b8e1672 100644 --- a/src/uucore/src/lib/features.rs +++ b/src/uucore/src/lib/features.rs @@ -69,6 +69,8 @@ pub mod update_control; pub mod uptime; #[cfg(feature = "version-cmp")] pub mod version_cmp; +#[cfg(feature = "zeroed-alloc")] +pub mod zeroed_alloc; // * (platform-specific) feature-gated modules // ** non-windows (i.e. Unix + Fuchsia) diff --git a/src/uucore/src/lib/features/sum.rs b/src/uucore/src/lib/features/sum.rs index 00782bb190f..68993c8ad14 100644 --- a/src/uucore/src/lib/features/sum.rs +++ b/src/uucore/src/lib/features/sum.rs @@ -68,23 +68,12 @@ pub trait Digest { } fn result(&mut self) -> io::Result { - let mut buf: Vec = Vec::new(); - try_reserve_zeroed(&mut buf, self.output_bytes())?; + let mut buf = crate::zeroed_alloc::try_new_vec(self.output_bytes())?; self.hash_finalize(&mut buf); Ok(DigestOutput::Vec(buf)) } } -/// Grows `buf` to `len` zero bytes, returning an [`io::Error`] with -/// [`io::ErrorKind::OutOfMemory`] instead of aborting the process if the -/// allocation can't be satisfied (e.g. an absurdly large `--length`, #12869). -fn try_reserve_zeroed(buf: &mut Vec, len: usize) -> io::Result<()> { - buf.try_reserve_exact(len) - .map_err(|e| io::Error::new(io::ErrorKind::OutOfMemory, e))?; - buf.resize(len, 0); - Ok(()) -} - /// first element of the tuple is the blake2b state /// second is the number of output bits pub struct Blake2b { @@ -504,8 +493,7 @@ macro_rules! impl_digest_shake { } fn result(&mut self) -> io::Result { - let mut bytes = Vec::new(); - try_reserve_zeroed(&mut bytes, self.output_bits().div_ceil(8))?; + let mut bytes = crate::zeroed_alloc::try_new_vec(self.output_bits().div_ceil(8))?; self.hash_finalize(&mut bytes); Ok(DigestOutput::Vec(bytes)) } diff --git a/src/uucore/src/lib/features/zeroed_alloc.rs b/src/uucore/src/lib/features/zeroed_alloc.rs new file mode 100644 index 00000000000..a4aaf7d5f22 --- /dev/null +++ b/src/uucore/src/lib/features/zeroed_alloc.rs @@ -0,0 +1,48 @@ +// This file is part of the uutils coreutils package. +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +//! Fallible zero-initialized allocations. + +/// Creates a zero-initialized boxed slice, returning an error if allocation fails. +/// +/// `T` must implement [`zerocopy::FromZeros`], which guarantees that an all-zero +/// byte sequence is a valid value of that type. +pub fn try_new_boxed_slice(len: usize) -> std::io::Result> { + <[T] as zerocopy::FromZeros>::new_box_zeroed_with_elems(len) + .map_err(|_| std::io::Error::from(std::io::ErrorKind::OutOfMemory)) +} + +/// Creates a zero-initialized vector, returning an error if allocation fails. +/// +/// `T` must implement [`zerocopy::FromZeros`], which guarantees that an all-zero +/// byte sequence is a valid value of that type. +pub fn try_new_vec(len: usize) -> std::io::Result> { + ::new_vec_zeroed(len) + .map_err(|_| std::io::Error::from(std::io::ErrorKind::OutOfMemory)) +} + +#[cfg(test)] +mod tests { + use super::{try_new_boxed_slice, try_new_vec}; + + #[test] + fn test_try_new_vec() { + assert_eq!(try_new_vec::(3).unwrap(), [0_u16; 3]); + assert_eq!( + try_new_vec::(usize::MAX).unwrap_err().kind(), + std::io::ErrorKind::OutOfMemory + ); + } + + #[test] + fn test_try_new_boxed_slice() { + assert_eq!(&*try_new_boxed_slice::(3).unwrap(), &[0_u16; 3]); + assert_eq!(&*try_new_boxed_slice::(0).unwrap(), &[]); + assert_eq!( + try_new_boxed_slice::(usize::MAX).unwrap_err().kind(), + std::io::ErrorKind::OutOfMemory + ); + } +} diff --git a/src/uucore/src/lib/lib.rs b/src/uucore/src/lib/lib.rs index b8232e7bb52..afd6846359f 100644 --- a/src/uucore/src/lib/lib.rs +++ b/src/uucore/src/lib/lib.rs @@ -97,6 +97,8 @@ pub use crate::features::update_control; pub use crate::features::uptime; #[cfg(feature = "version-cmp")] pub use crate::features::version_cmp; +#[cfg(feature = "zeroed-alloc")] +pub use crate::features::zeroed_alloc; pub use crate::features::{char_width, diagnostics}; // * (platform-specific) feature-gated modules