Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
8 values
pull_number
int64
56
4.09k
instance_id
stringlengths
19
31
issue_numbers
sequencelengths
1
2
base_commit
stringlengths
40
40
patch
stringlengths
249
5.94M
test_patch
stringlengths
142
5.5M
problem_statement
stringlengths
18
8.89k
hints_text
stringlengths
0
26.5k
created_at
stringdate
2021-01-03 05:40:59
2025-03-03 13:33:55
version
stringclasses
16 values
updated_at
stringdate
2021-01-04 06:05:18
2025-03-22 06:42:54
environment_setup_commit
stringclasses
16 values
rust-random/getrandom
301
rust-random__getrandom-301
[ "254" ]
bd0654fe70980583e51573e755bafa3b2f8342d9
diff --git a/src/dragonfly.rs b/src/dragonfly.rs --- a/src/dragonfly.rs +++ b/src/dragonfly.rs @@ -12,7 +12,7 @@ use crate::{ util_libc::{sys_fill_exact, Weak}, Error, }; -use std::mem::MaybeUninit; +use core::mem::MaybeUninit; pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; diff --git a/src/dragonfly.rs b/src/dragonfly.rs --- a/src/dragonfly.rs +++ b/src/dragonfly.rs @@ -21,7 +21,9 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // getrandom(2) was introduced in DragonflyBSD 5.7 if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; - return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); + return sys_fill_exact(dest, |buf| unsafe { + func(buf.as_mut_ptr() as *mut u8, buf.len(), 0) + }); } else { use_file::getrandom_inner(dest) } diff --git a/src/openbsd.rs b/src/openbsd.rs --- a/src/openbsd.rs +++ b/src/openbsd.rs @@ -8,6 +8,7 @@ //! Implementation for OpenBSD use crate::{util_libc::last_os_error, Error}; +use core::mem::MaybeUninit; pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally. diff --git a/src/solaris_illumos.rs b/src/solaris_illumos.rs --- a/src/solaris_illumos.rs +++ b/src/solaris_illumos.rs @@ -22,7 +22,7 @@ use crate::{ util_libc::{sys_fill_exact, Weak}, Error, }; -use core::mem; +use core::mem::{self, MaybeUninit}; #[cfg(target_os = "illumos")] type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; diff --git a/src/solaris_illumos.rs b/src/solaris_illumos.rs --- a/src/solaris_illumos.rs +++ b/src/solaris_illumos.rs @@ -38,7 +38,7 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // derived platforms for atomically obtaining random data. for chunk in dest.chunks_mut(256) { sys_fill_exact(chunk, |buf| unsafe { - func(buf.as_mut_ptr(), buf.len(), 0) as libc::ssize_t + func(buf.as_mut_ptr() as *mut u8, buf.len(), 0) as libc::ssize_t })? } Ok(())
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -166,8 +166,9 @@ jobs: strategy: matrix: target: [ - # See: https://github.com/rust-random/getrandom/issues/254 - # sparcv9-sun-solaris, + sparcv9-sun-solaris, + x86_64-unknown-illumos, + x86_64-unknown-freebsd, x86_64-unknown-netbsd, ] steps: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -277,7 +278,6 @@ jobs: strategy: matrix: target: [ - x86_64-unknown-freebsd, x86_64-fuchsia, x86_64-unknown-redox, x86_64-fortanix-unknown-sgx, diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -288,7 +288,7 @@ jobs: with: profile: minimal target: ${{ matrix.target }} - toolchain: nightly # Required to build libc for Redox + toolchain: stable override: true - uses: Swatinem/rust-cache@v1 - name: Build diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -319,6 +319,14 @@ jobs: run: cargo build -Z build-std=core --target=aarch64-kmc-solid_asp3 - name: Nintendo 3DS run: cargo build -Z build-std=core --target=armv6k-nintendo-3ds + - name: RISC-V ESP-IDF + run: cargo build -Z build-std=core --target=riscv32imc-esp-espidf + - name: OpenBSD + run: cargo build -Z build-std=std --target=x86_64-unknown-openbsd --features=std + - name: Dragonfly BSD + run: cargo build -Z build-std=std --target=x86_64-unknown-dragonfly --features=std + - name: Haiku OS + run: cargo build -Z build-std=std --target=x86_64-unknown-haiku --features=std clippy-fmt: name: Clippy + rustfmt
Fix Solaris cross-build job It fails with linker error, e.g. see: https://github.com/rust-random/getrandom/runs/5698849705 Relevant Rust issue: https://github.com/rust-lang/rust/pull/94052 It looks like due to `libc` changes we now need Solaris-specific `sendfile` and `lgrp`.
2022-10-22T00:21:59.000Z
0.2
2022-10-22T20:28:43Z
5e62ce9fadb401539a08b329e4cbd98cc6393f60
rust-random/getrandom
291
rust-random__getrandom-291
[ "226" ]
5c1bb00b74a2c72ba182171b93d1c4b9d30c10c4
diff --git a/CHANGELOG.md b/CHANGELOG.md --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased +### Added +- `getrandom_uninit` [#291] + +### Breaking Changes +- Update MSRV to 1.36 [#291] + +[#291]: https://github.com/rust-random/getrandom/pull/291 + ## [0.2.8] - 2022-10-20 ### Changed - The [Web Cryptography API] will now be preferred on `wasm32-unknown-unknown` diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ crate features, WASM support and Custom RNGs see the ## Minimum Supported Rust Version -This crate requires Rust 1.34.0 or later. +This crate requires Rust 1.36.0 or later. # License diff --git a/src/3ds.rs b/src/3ds.rs --- a/src/3ds.rs +++ b/src/3ds.rs @@ -9,8 +9,9 @@ //! Implementation for Nintendo 3DS use crate::util_libc::sys_fill_exact; use crate::Error; +use core::mem::MaybeUninit; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { sys_fill_exact(dest, |buf| unsafe { libc::getrandom(buf.as_mut_ptr() as *mut libc::c_void, buf.len(), 0) }) diff --git a/src/bsd_arandom.rs b/src/bsd_arandom.rs --- a/src/bsd_arandom.rs +++ b/src/bsd_arandom.rs @@ -8,9 +8,9 @@ //! Implementation for FreeBSD and NetBSD use crate::{util_libc::sys_fill_exact, Error}; -use core::ptr; +use core::{mem::MaybeUninit, ptr}; -fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t { +fn kern_arnd(buf: &mut [MaybeUninit<u8>]) -> libc::ssize_t { static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND]; let mut len = buf.len(); let ret = unsafe { diff --git a/src/bsd_arandom.rs b/src/bsd_arandom.rs --- a/src/bsd_arandom.rs +++ b/src/bsd_arandom.rs @@ -30,7 +30,7 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t { } } -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0 #[cfg(target_os = "freebsd")] { diff --git a/src/bsd_arandom.rs b/src/bsd_arandom.rs --- a/src/bsd_arandom.rs +++ b/src/bsd_arandom.rs @@ -41,7 +41,9 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; - return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); + return sys_fill_exact(dest, |buf| unsafe { + func(buf.as_mut_ptr() as *mut u8, buf.len(), 0) + }); } } // Both FreeBSD and NetBSD will only return up to 256 bytes at a time, and diff --git a/src/custom.rs b/src/custom.rs --- a/src/custom.rs +++ b/src/custom.rs @@ -7,8 +7,8 @@ // except according to those terms. //! An implementation which calls out to an externally defined function. -use crate::Error; -use core::num::NonZeroU32; +use crate::{util::uninit_slice_fill_zero, Error}; +use core::{mem::MaybeUninit, num::NonZeroU32}; /// Register a function to be invoked by `getrandom` on unsupported targets. /// diff --git a/src/custom.rs b/src/custom.rs --- a/src/custom.rs +++ b/src/custom.rs @@ -90,10 +90,16 @@ macro_rules! register_custom_getrandom { } #[allow(dead_code)] -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { extern "C" { fn __getrandom_custom(dest: *mut u8, len: usize) -> u32; } + // Previously we always passed a valid, initialized slice to + // `__getrandom_custom`. Ensure `dest` has been initialized for backward + // compatibility with implementations that rely on that (e.g. Rust + // implementations that construct a `&mut [u8]` slice from `dest` and + // `len`). + let dest = uninit_slice_fill_zero(dest); let ret = unsafe { __getrandom_custom(dest.as_mut_ptr(), dest.len()) }; match NonZeroU32::new(ret) { None => Ok(()), diff --git a/src/dragonfly.rs b/src/dragonfly.rs --- a/src/dragonfly.rs +++ b/src/dragonfly.rs @@ -12,8 +12,9 @@ use crate::{ util_libc::{sys_fill_exact, Weak}, Error, }; +use std::mem::MaybeUninit; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; diff --git a/src/fuchsia.rs b/src/fuchsia.rs --- a/src/fuchsia.rs +++ b/src/fuchsia.rs @@ -8,13 +8,14 @@ //! Implementation for Fuchsia Zircon use crate::Error; +use core::mem::MaybeUninit; #[link(name = "zircon")] extern "C" { fn zx_cprng_draw(buffer: *mut u8, length: usize); } -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - unsafe { zx_cprng_draw(dest.as_mut_ptr(), dest.len()) } +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { + unsafe { zx_cprng_draw(dest.as_mut_ptr() as *mut u8, dest.len()) } Ok(()) } diff --git a/src/ios.rs b/src/ios.rs --- a/src/ios.rs +++ b/src/ios.rs @@ -8,16 +8,16 @@ //! Implementation for iOS use crate::Error; -use core::{ffi::c_void, ptr::null}; +use core::{ffi::c_void, mem::MaybeUninit, ptr::null}; #[link(name = "Security", kind = "framework")] extern "C" { fn SecRandomCopyBytes(rnd: *const c_void, count: usize, bytes: *mut u8) -> i32; } -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // Apple's documentation guarantees kSecRandomDefault is a synonym for NULL. - let ret = unsafe { SecRandomCopyBytes(null(), dest.len(), dest.as_mut_ptr()) }; + let ret = unsafe { SecRandomCopyBytes(null(), dest.len(), dest.as_mut_ptr() as *mut u8) }; // errSecSuccess (from SecBase.h) is always zero. if ret != 0 { Err(Error::IOS_SEC_RANDOM) diff --git a/src/js.rs b/src/js.rs --- a/src/js.rs +++ b/src/js.rs @@ -5,10 +5,10 @@ // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. -use crate::Error; +use crate::{util::uninit_slice_fill_zero, Error}; extern crate std; -use std::thread_local; +use std::{mem::MaybeUninit, thread_local}; use js_sys::{global, Function, Uint8Array}; use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue}; diff --git a/src/js.rs b/src/js.rs --- a/src/js.rs +++ b/src/js.rs @@ -28,12 +28,16 @@ thread_local!( static RNG_SOURCE: Result<RngSource, Error> = getrandom_init(); ); -pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub(crate) fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { RNG_SOURCE.with(|result| { let source = result.as_ref().map_err(|&e| e)?; match source { RngSource::Node(n) => { + // XXX(perf): `random_fill_sync` requires a `&mut [u8]` so we + // have to ensure the memory in `dest` is initialized. + let dest = uninit_slice_fill_zero(dest); + if n.random_fill_sync(dest).is_err() { return Err(Error::NODE_RANDOM_FILL_SYNC); } diff --git a/src/js.rs b/src/js.rs --- a/src/js.rs +++ b/src/js.rs @@ -49,7 +53,9 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { if crypto.get_random_values(&sub_buf).is_err() { return Err(Error::WEB_GET_RANDOM_VALUES); } - sub_buf.copy_to(chunk); + + // SAFETY: `sub_buf`'s length is the same length as `chunk` + unsafe { sub_buf.raw_copy_to_ptr(chunk.as_mut_ptr() as *mut u8) }; } } }; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -186,6 +186,9 @@ #[macro_use] extern crate cfg_if; +use crate::util::{slice_as_uninit_mut, slice_assume_init_mut}; +use core::mem::MaybeUninit; + mod error; mod util; // To prevent a breaking change when targets are added, we always export the diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -199,7 +202,11 @@ pub use crate::error::Error; // System-specific implementations. // -// These should all provide getrandom_inner with the same signature as getrandom. +// These should all provide getrandom_inner with the signature +// `fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>`. +// The function MUST fully initialize `dest` when `Ok(())` is returned. +// The function MUST NOT ever write uninitialized bytes into `dest`, +// regardless of what value it returns. cfg_if! { if #[cfg(any(target_os = "emscripten", target_os = "haiku", target_os = "redox"))] { diff --git a/src/linux_android.rs b/src/linux_android.rs --- a/src/linux_android.rs +++ b/src/linux_android.rs @@ -12,8 +12,9 @@ use crate::{ util_libc::{last_os_error, sys_fill_exact}, {use_file, Error}, }; +use core::mem::MaybeUninit; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // getrandom(2) was introduced in Linux 3.17 static HAS_GETRANDOM: LazyBool = LazyBool::new(); if HAS_GETRANDOM.unsync_init(is_getrandom_available) { diff --git a/src/macos.rs b/src/macos.rs --- a/src/macos.rs +++ b/src/macos.rs @@ -12,17 +12,17 @@ use crate::{ util_libc::{last_os_error, Weak}, Error, }; -use core::mem; +use core::mem::{self, MaybeUninit}; type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // getentropy(2) was added in 10.12, Rust supports 10.7+ static GETENTROPY: Weak = unsafe { Weak::new("getentropy\0") }; if let Some(fptr) = GETENTROPY.ptr() { let func: GetEntropyFn = unsafe { mem::transmute(fptr) }; for chunk in dest.chunks_mut(256) { - let ret = unsafe { func(chunk.as_mut_ptr(), chunk.len()) }; + let ret = unsafe { func(chunk.as_mut_ptr() as *mut u8, chunk.len()) }; if ret != 0 { return Err(last_os_error()); } diff --git a/src/openbsd.rs b/src/openbsd.rs --- a/src/openbsd.rs +++ b/src/openbsd.rs @@ -9,7 +9,7 @@ //! Implementation for OpenBSD use crate::{util_libc::last_os_error, Error}; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally. for chunk in dest.chunks_mut(256) { let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) }; diff --git a/src/rdrand.rs b/src/rdrand.rs --- a/src/rdrand.rs +++ b/src/rdrand.rs @@ -7,8 +7,8 @@ // except according to those terms. //! Implementation for SGX using RDRAND instruction -use crate::Error; -use core::mem; +use crate::{util::slice_as_uninit, Error}; +use core::mem::{self, MaybeUninit}; cfg_if! { if #[cfg(target_arch = "x86_64")] { diff --git a/src/rdrand.rs b/src/rdrand.rs --- a/src/rdrand.rs +++ b/src/rdrand.rs @@ -69,7 +69,7 @@ fn is_rdrand_supported() -> bool { HAS_RDRAND.unsync_init(|| unsafe { (arch::__cpuid(1).ecx & FLAG) != 0 }) } -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { if !is_rdrand_supported() { return Err(Error::NO_RDRAND); } diff --git a/src/rdrand.rs b/src/rdrand.rs --- a/src/rdrand.rs +++ b/src/rdrand.rs @@ -80,18 +80,18 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { } #[target_feature(enable = "rdrand")] -unsafe fn rdrand_exact(dest: &mut [u8]) -> Result<(), Error> { +unsafe fn rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // We use chunks_exact_mut instead of chunks_mut as it allows almost all // calls to memcpy to be elided by the compiler. let mut chunks = dest.chunks_exact_mut(WORD_SIZE); for chunk in chunks.by_ref() { - chunk.copy_from_slice(&rdrand()?); + chunk.copy_from_slice(slice_as_uninit(&rdrand()?)); } let tail = chunks.into_remainder(); let n = tail.len(); if n > 0 { - tail.copy_from_slice(&rdrand()?[..n]); + tail.copy_from_slice(slice_as_uninit(&rdrand()?[..n])); } Ok(()) } diff --git a/src/solaris_illumos.rs b/src/solaris_illumos.rs --- a/src/solaris_illumos.rs +++ b/src/solaris_illumos.rs @@ -29,7 +29,7 @@ type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> #[cfg(target_os = "solaris")] type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::c_int; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // getrandom(2) was introduced in Solaris 11.3 for Illumos in 2015. static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; if let Some(fptr) = GETRANDOM.ptr() { diff --git a/src/solid.rs b/src/solid.rs --- a/src/solid.rs +++ b/src/solid.rs @@ -8,14 +8,14 @@ //! Implementation for SOLID use crate::Error; -use core::num::NonZeroU32; +use core::{mem::MaybeUninit, num::NonZeroU32}; extern "C" { pub fn SOLID_RNG_SampleRandomBytes(buffer: *mut u8, length: usize) -> i32; } -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - let ret = unsafe { SOLID_RNG_SampleRandomBytes(dest.as_mut_ptr(), dest.len()) }; +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { + let ret = unsafe { SOLID_RNG_SampleRandomBytes(dest.as_mut_ptr() as *mut u8, dest.len()) }; if ret >= 0 { Ok(()) } else { diff --git a/src/use_file.rs b/src/use_file.rs --- a/src/use_file.rs +++ b/src/use_file.rs @@ -14,6 +14,7 @@ use crate::{ }; use core::{ cell::UnsafeCell, + mem::MaybeUninit, sync::atomic::{AtomicUsize, Ordering::Relaxed}, }; diff --git a/src/use_file.rs b/src/use_file.rs --- a/src/use_file.rs +++ b/src/use_file.rs @@ -29,9 +30,11 @@ const FILE_PATH: &str = "/dev/random\0"; #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] const FILE_PATH: &str = "/dev/urandom\0"; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { let fd = get_rng_fd()?; - let read = |buf: &mut [u8]| unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) }; + let read = |buf: &mut [MaybeUninit<u8>]| unsafe { + libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) + }; if cfg!(target_os = "emscripten") { // `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes. diff --git a/src/util.rs b/src/util.rs --- a/src/util.rs +++ b/src/util.rs @@ -6,7 +6,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] -use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use core::{ + mem::MaybeUninit, + ptr, + sync::atomic::{AtomicUsize, Ordering::Relaxed}, +}; // This structure represents a lazily initialized static usize value. Useful // when it is preferable to just rerun initialization instead of locking. diff --git a/src/util.rs b/src/util.rs --- a/src/util.rs +++ b/src/util.rs @@ -62,3 +66,36 @@ impl LazyBool { self.0.unsync_init(|| init() as usize) != 0 } } + +/// Polyfill for `maybe_uninit_slice` feature's +/// `MaybeUninit::slice_assume_init_mut`. Every element of `slice` must have +/// been initialized. +#[inline(always)] +pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] { + // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`. + &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) +} + +#[inline] +pub fn uninit_slice_fill_zero(slice: &mut [MaybeUninit<u8>]) -> &mut [u8] { + unsafe { ptr::write_bytes(slice.as_mut_ptr(), 0, slice.len()) }; + unsafe { slice_assume_init_mut(slice) } +} + +#[inline(always)] +pub fn slice_as_uninit<T>(slice: &[T]) -> &[MaybeUninit<T>] { + // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`. + // There is no risk of writing a `MaybeUninit<T>` into the result since + // the result isn't mutable. + unsafe { &*(slice as *const [T] as *const [MaybeUninit<T>]) } +} + +/// View an mutable initialized array as potentially-uninitialized. +/// +/// This is unsafe because it allows assigning uninitialized values into +/// `slice`, which would be undefined behavior. +#[inline(always)] +pub unsafe fn slice_as_uninit_mut<T>(slice: &mut [T]) -> &mut [MaybeUninit<T>] { + // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`. + &mut *(slice as *mut [T] as *mut [MaybeUninit<T>]) +} diff --git a/src/util_libc.rs b/src/util_libc.rs --- a/src/util_libc.rs +++ b/src/util_libc.rs @@ -8,6 +8,7 @@ #![allow(dead_code)] use crate::Error; use core::{ + mem::MaybeUninit, num::NonZeroU32, ptr::NonNull, sync::atomic::{fence, AtomicPtr, Ordering}, diff --git a/src/util_libc.rs b/src/util_libc.rs --- a/src/util_libc.rs +++ b/src/util_libc.rs @@ -59,8 +60,8 @@ pub fn last_os_error() -> Error { // - should return -1 and set errno on failure // - should return the number of bytes written on success pub fn sys_fill_exact( - mut buf: &mut [u8], - sys_fill: impl Fn(&mut [u8]) -> libc::ssize_t, + mut buf: &mut [MaybeUninit<u8>], + sys_fill: impl Fn(&mut [MaybeUninit<u8>]) -> libc::ssize_t, ) -> Result<(), Error> { while !buf.is_empty() { let res = sys_fill(buf); diff --git a/src/vxworks.rs b/src/vxworks.rs --- a/src/vxworks.rs +++ b/src/vxworks.rs @@ -8,9 +8,12 @@ //! Implementation for VxWorks use crate::{util_libc::last_os_error, Error}; -use core::sync::atomic::{AtomicBool, Ordering::Relaxed}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering::Relaxed}, +}; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { static RNG_INIT: AtomicBool = AtomicBool::new(false); while !RNG_INIT.load(Relaxed) { let ret = unsafe { libc::randSecure() }; diff --git a/src/vxworks.rs b/src/vxworks.rs --- a/src/vxworks.rs +++ b/src/vxworks.rs @@ -25,7 +28,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { // Prevent overflow of i32 for chunk in dest.chunks_mut(i32::max_value() as usize) { - let ret = unsafe { libc::randABytes(chunk.as_mut_ptr(), chunk.len() as i32) }; + let ret = unsafe { libc::randABytes(chunk.as_mut_ptr() as *mut u8, chunk.len() as i32) }; if ret != 0 { return Err(last_os_error()); } diff --git a/src/wasi.rs b/src/wasi.rs --- a/src/wasi.rs +++ b/src/wasi.rs @@ -8,10 +8,10 @@ //! Implementation for WASI use crate::Error; -use core::num::NonZeroU32; +use core::{mem::MaybeUninit, num::NonZeroU32}; use wasi::wasi_snapshot_preview1::random_get; -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { match unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) } { 0 => Ok(()), err => Err(unsafe { NonZeroU32::new_unchecked(err as u32) }.into()), diff --git a/src/windows.rs b/src/windows.rs --- a/src/windows.rs +++ b/src/windows.rs @@ -7,7 +7,7 @@ // except according to those terms. use crate::Error; -use core::{ffi::c_void, num::NonZeroU32, ptr}; +use core::{ffi::c_void, mem::MaybeUninit, num::NonZeroU32, ptr}; const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002; diff --git a/src/windows.rs b/src/windows.rs --- a/src/windows.rs +++ b/src/windows.rs @@ -21,14 +21,14 @@ extern "system" { ) -> u32; } -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // Prevent overflow of u32 for chunk in dest.chunks_mut(u32::max_value() as usize) { // BCryptGenRandom was introduced in Windows Vista let ret = unsafe { BCryptGenRandom( ptr::null_mut(), - chunk.as_mut_ptr(), + chunk.as_mut_ptr() as *mut u8, chunk.len() as u32, BCRYPT_USE_SYSTEM_PREFERRED_RNG, )
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -44,7 +44,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, windows-latest] - toolchain: [nightly, beta, stable, 1.34] + toolchain: [nightly, beta, stable, 1.36] # Only Test macOS on stable to reduce macOS CI jobs include: - os: macos-latest diff --git a/benches/mod.rs b/benches/mod.rs --- a/benches/mod.rs +++ b/benches/mod.rs @@ -1,94 +1,64 @@ #![feature(test)] -extern crate test; - -use std::{ - alloc::{alloc_zeroed, dealloc, Layout}, - ptr::NonNull, -}; - -// AlignedBuffer is like a Box<[u8; N]> except that it is always N-byte aligned -struct AlignedBuffer<const N: usize>(NonNull<[u8; N]>); +#![feature(maybe_uninit_as_bytes)] -impl<const N: usize> AlignedBuffer<N> { - fn layout() -> Layout { - Layout::from_size_align(N, N).unwrap() - } - - fn new() -> Self { - let p = unsafe { alloc_zeroed(Self::layout()) } as *mut [u8; N]; - Self(NonNull::new(p).unwrap()) - } - - fn buf(&mut self) -> &mut [u8; N] { - unsafe { self.0.as_mut() } - } -} +extern crate test; -impl<const N: usize> Drop for AlignedBuffer<N> { - fn drop(&mut self) { - unsafe { dealloc(self.0.as_ptr() as *mut u8, Self::layout()) } - } -} +use std::mem::MaybeUninit; // Used to benchmark the throughput of getrandom in an optimal scenario. // The buffer is hot, and does not require initialization. #[inline(always)] -fn bench<const N: usize>(b: &mut test::Bencher) { - let mut ab = AlignedBuffer::<N>::new(); - let buf = ab.buf(); +fn bench_getrandom<const N: usize>(b: &mut test::Bencher) { + b.bytes = N as u64; b.iter(|| { + let mut buf = [0u8; N]; getrandom::getrandom(&mut buf[..]).unwrap(); - test::black_box(&buf); + test::black_box(buf); }); - b.bytes = N as u64; } // Used to benchmark the throughput of getrandom is a slightly less optimal // scenario. The buffer is still hot, but requires initialization. #[inline(always)] -fn bench_with_init<const N: usize>(b: &mut test::Bencher) { - let mut ab = AlignedBuffer::<N>::new(); - let buf = ab.buf(); +fn bench_getrandom_uninit<const N: usize>(b: &mut test::Bencher) { + b.bytes = N as u64; b.iter(|| { - for byte in buf.iter_mut() { - *byte = 0; - } - getrandom::getrandom(&mut buf[..]).unwrap(); - test::black_box(&buf); + let mut buf: MaybeUninit<[u8; N]> = MaybeUninit::uninit(); + let _ = getrandom::getrandom_uninit(buf.as_bytes_mut()).unwrap(); + let buf: [u8; N] = unsafe { buf.assume_init() }; + test::black_box(buf) }); - b.bytes = N as u64; } -// 32 bytes (256-bit) is the seed sized used for rand::thread_rng -const SEED: usize = 32; -// Common size of a page, 4 KiB -const PAGE: usize = 4096; -// Large buffer to get asymptotic performance, 2 MiB -const LARGE: usize = 1 << 21; +macro_rules! bench { + ( $name:ident, $size:expr ) => { + pub mod $name { + #[bench] + pub fn bench_getrandom(b: &mut test::Bencher) { + super::bench_getrandom::<{ $size }>(b); + } -#[bench] -fn bench_seed(b: &mut test::Bencher) { - bench::<SEED>(b); -} -#[bench] -fn bench_seed_init(b: &mut test::Bencher) { - bench_with_init::<SEED>(b); + #[bench] + pub fn bench_getrandom_uninit(b: &mut test::Bencher) { + super::bench_getrandom_uninit::<{ $size }>(b); + } + } + }; } -#[bench] -fn bench_page(b: &mut test::Bencher) { - bench::<PAGE>(b); -} -#[bench] -fn bench_page_init(b: &mut test::Bencher) { - bench_with_init::<PAGE>(b); -} +// 16 bytes (128 bits) is the size of an 128-bit AES key/nonce. +bench!(aes128, 128 / 8); -#[bench] -fn bench_large(b: &mut test::Bencher) { - bench::<LARGE>(b); -} -#[bench] -fn bench_large_init(b: &mut test::Bencher) { - bench_with_init::<LARGE>(b); -} +// 32 bytes (256 bits) is the seed sized used for rand::thread_rng +// and the `random` value in a ClientHello/ServerHello for TLS. +// This is also the size of a 256-bit AES/HMAC/P-256/Curve25519 key +// and/or nonce. +bench!(p256, 256 / 8); + +// A P-384/HMAC-384 key and/or nonce. +bench!(p384, 384 / 8); + +// Initializing larger buffers is not the primary use case of this library, as +// this should normally be done by a userspace CSPRNG. However, we have a test +// here to see the effects of a lower (amortized) syscall overhead. +bench!(page, 4096); diff --git a/src/espidf.rs b/src/espidf.rs --- a/src/espidf.rs +++ b/src/espidf.rs @@ -8,13 +8,13 @@ //! Implementation for ESP-IDF use crate::Error; -use core::ffi::c_void; +use core::{ffi::c_void, mem::MaybeUninit}; extern "C" { fn esp_fill_random(buf: *mut c_void, len: usize) -> u32; } -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { +pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { // Not that NOT enabling WiFi, BT, or the voltage noise entropy source (via `bootloader_random_enable`) // will cause ESP-IDF to return pseudo-random numbers based on the voltage noise entropy, after the initial boot process: // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -283,9 +290,40 @@ cfg_if! { /// In general, `getrandom` will be fast enough for interactive usage, though /// significantly slower than a user-space CSPRNG; for the latter consider /// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html). +#[inline] pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> { - if dest.is_empty() { - return Ok(()); - } - imp::getrandom_inner(dest) + // SAFETY: The `&mut MaybeUninit<_>` reference doesn't escape, and + // `getrandom_uninit` guarantees it will never de-initialize any part of + // `dest`. + getrandom_uninit(unsafe { slice_as_uninit_mut(dest) })?; + Ok(()) +} + +/// Version of the `getrandom` function which fills `dest` with random bytes +/// returns a mutable reference to those bytes. +/// +/// On successful completion this function is guaranteed to return a slice +/// which points to the same memory as `dest` and has the same length. +/// In other words, it's safe to assume that `dest` is initialized after +/// this function has returned `Ok`. +/// +/// No part of `dest` will ever be de-initialized at any point, regardless +/// of what is returned. +/// +/// # Examples +/// +/// ```ignore +/// # // We ignore this test since `uninit_array` is unstable. +/// #![feature(maybe_uninit_uninit_array)] +/// # fn main() -> Result<(), getrandom::Error> { +/// let mut buf = core::mem::MaybeUninit::uninit_array::<1024>(); +/// let buf: &mut [u8] = getrandom::getrandom_uninit(&mut buf)?; +/// # Ok(()) } +/// ``` +#[inline] +pub fn getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> { + imp::getrandom_inner(dest)?; + // SAFETY: `dest` has been fully initialized by `imp::getrandom_inner` + // since it returned `Ok`. + Ok(unsafe { slice_assume_init_mut(dest) }) } diff --git a/tests/rdrand.rs b/tests/rdrand.rs --- a/tests/rdrand.rs +++ b/tests/rdrand.rs @@ -11,5 +11,10 @@ mod rdrand; #[path = "../src/util.rs"] mod util; -use rdrand::getrandom_inner as getrandom_impl; +// The rdrand implementation has the signature of getrandom_uninit(), but our +// tests expect getrandom_impl() to have the signature of getrandom(). +fn getrandom_impl(dest: &mut [u8]) -> Result<(), Error> { + rdrand::getrandom_inner(unsafe { util::slice_as_uninit_mut(dest) })?; + Ok(()) +} mod common;
Expose API interface for MaybeUninit<u8> slice It is inefficient to zero-fill a large byte buffer before actually being initialized with random bytes. Thus, it would be better if getrandom exposes a function that takes a slice of `MaybeUninit<u8>` so that the user will not have to initialize the buffer.
I've seen this type of request a couple of times before, with the rand project, but have never been convinced that this optimisation would be worth the effort. This is even more true of `getrandom` where a slow system call is required to get the random bytes. If a crate is depending on `getrandom()` and it wants to expose an interface where it fills a `MaybeUninit<u8>` slice then it would be good to be able to fill the part of that slice that needs the random bytes using `getrandom` directly, instead of needing to fill a temporary `&[u8]` and then copying that temporary `&[u8]` to the `&[MaybeUninit<u8>]`. In particular, for security reasons, one may wish to ensure (to the extent Rust allows) that the generated random bytes are never copied anywhere except the target buffer. > It is inefficient to zero-fill a large byte buffer before actually being initialized with random bytes. @bdbai do you have any benchmarks on this? Do we know if there's a performance difference between: - Zeroing a buffer then calling `getrandom` - Calling `getrandom` on uninitialized bytes It would be fine to do a comparison in C if getting benchmarks in Rust might be overly complex. > instead of needing to fill a temporary `&[u8]` and then copying that temporary `&[u8]` to the `&[MaybeUninit<u8>]`. > In particular, for security reasons, one may wish to ensure (to the extent Rust allows) that the generated random bytes are never copied anywhere except the target buffer. @briansmith I'm more sensitive to the security concern here (we definitely want it to be possible to initialize random buffers in-place). However, why wouldn't it be possible to just zero the `&mut [MaybeUninit<u8>]`, get a `&mut [u8]` to the same buffer, and then pass the buffer to `getrandom`? That should avoid copying secret data or needing a temporary buffer. In general, I wouldn't be totally opposed to adding such an API, but we would probably want to wait for https://github.com/rust-lang/rfcs/pull/2930 to be implemented (tracked in https://github.com/rust-lang/rust/issues/78485), before adding an API. I don't want to invent our own API for dealing with uninitialized buffers. If we add this, we would want to use the `ReadBuf` type and something like: ```rust pub fn getrandom_readbuf(dest: &mut ReadBuf<'_>) -> Result<(), Error> { // Our implementation dealing with [MaybeUninit<u8>] } ``` Initially, this would need to be behind an unstable feature gate (like `"read_buf"`) until the RFC is stabilized. One advantage of this sort of API is that it might allow for partial reads from the underlying RNG to not be wasted. However, this is a very slight benefit as if the RNG succeeds once, it virtually always succeeds for all future calls. Hopefully we could see readbuf hit nightly soon. > I don't want to invent our own API for dealing with uninitialized buffers. If we add this, we would want to use the `ReadBuf` type and something like: `ReadBuf` is planned to be in `std::io` so it can't be used by getrandom in general, right? Perhaps we should provide feedback that it should be moved to libcore and avoid using `std::io::Error`. However, I think `ReadBuf` is more than what is needed, because it tries to keep track of the intermediate state of a partially-filled/initialized buffer, which isn't applicable here. > @briansmith I'm more sensitive to the security concern here (we definitely want it to be possible to initialize random buffers in-place). However, why wouldn't it be possible to just zero the `&mut [MaybeUninit<u8>]`, get a `&mut [u8]` to the same buffer, and then pass the buffer to `getrandom`? That should avoid copying secret data or needing a temporary buffer. Of course that does work. OTOH, if that's going to be a common pattern then why not encapsulate it within `getrandom` by adding such an API? And then we could (later) optimize the implementation to avoid the initial zeroing. > `ReadBuf` is planned to be in `std::io` so it can't be used by getrandom in general, right? Perhaps we should provide feedback that it should be moved to libcore and avoid using `std::io::Error`. `getrandom` has a `"std"` feature, so we could just gate `getrandom_readbuf` behind that feature. Looking at [the API for `ReadBuf`](https://github.com/rust-lang/rfcs/blob/master/text/2930-read-buf.md#reference-level-explanation), it seems that nothing in its API requires it to be in `libstd`, so it could be in `libcore`. I would encourage people to raise this point in [the `ReadBuf` tracking issue](https://github.com/rust-lang/rust/issues/78485). > OTOH, if that's going to be a common pattern then why not encapsulate it within `getrandom` by adding such an API? It's mostly due a desire to keep the functionality of this crate minimal to reduce our maintenance burden, so I would actually want to know that this is a common pattern across many crates before we commit to supporting it in the long-term. However, if adding this API increases ergonomics for folks, I would support adding it. This would be true even if the *only* benefit is ergonomics (e.g. if there is no significant performance difference). > However, I think `ReadBuf` is more than what is needed, because it tries to keep track of the intermediate state of a partially-filled/initialized buffer, which isn't applicable here. If the main reason for adding this change is ergonomics (i.e. handling common patterns), I would want `getrandom` to integrate well with those common patterns. It looks like `ReadBuf` is going to be "standard way" to express this pattern in Rust, so we would probably want to use that rather than inventing our own API. The latest revision of the PR #279 implements this. Regarding the `ReadBuf` idea, I think that should be a separate proposal with its own issue. It looks like `ReadBuf` is dead, based on https://github.com/rust-lang/rust/pull/97015, and it looks like it might be a while before all that stuff is resolved. And, it isn't clear the resolution will be no_std-compatible. A lot of things need/want a no_std-compatible interface and a `std::io::*`-based one is a non-starter. @bdbai This issue shouldn't be closed yet, since PR #279 hasn't been approved/merged yet, and might not be.
2022-10-13T03:28:37.000Z
0.2
2022-10-21T06:56:11Z
5e62ce9fadb401539a08b329e4cbd98cc6393f60
rust-random/getrandom
284
rust-random__getrandom-284
[ "256" ]
d3aa089bbdefa95da9130b7c633e1f49687f04ce
diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -43,16 +43,19 @@ impl Error { pub const FAILED_RDRAND: Error = internal_error(5); /// RDRAND instruction unsupported on this target. pub const NO_RDRAND: Error = internal_error(6); - /// The browser does not have support for `self.crypto`. + /// The environment does not support the Web Crypto API. pub const WEB_CRYPTO: Error = internal_error(7); - /// The browser does not have support for `crypto.getRandomValues`. + /// Calling Web Crypto API `crypto.getRandomValues` failed. pub const WEB_GET_RANDOM_VALUES: Error = internal_error(8); /// On VxWorks, call to `randSecure` failed (random number generator is not yet initialized). pub const VXWORKS_RAND_SECURE: Error = internal_error(11); - /// NodeJS does not have support for the `crypto` module. + /// Node.js does not have the `crypto` CommonJS module. pub const NODE_CRYPTO: Error = internal_error(12); - /// NodeJS does not have support for `crypto.randomFillSync`. + /// Calling Node.js function `crypto.randomFillSync` failed. pub const NODE_RANDOM_FILL_SYNC: Error = internal_error(13); + /// Called from an ES module on Node.js. This is unsupported, see: + /// <https://docs.rs/getrandom#nodejs-es-module-support>. + pub const NODE_ES_MODULE: Error = internal_error(14); /// Codes below this point represent OS Errors (i.e. positive i32 values). /// Codes at or above this point, but below [`Error::CUSTOM_START`] are diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -166,10 +169,11 @@ fn internal_desc(error: Error) -> Option<&'static str> { Error::FAILED_RDRAND => Some("RDRAND: failed multiple times: CPU issue likely"), Error::NO_RDRAND => Some("RDRAND: instruction not supported"), Error::WEB_CRYPTO => Some("Web Crypto API is unavailable"), - Error::WEB_GET_RANDOM_VALUES => Some("Web API crypto.getRandomValues is unavailable"), + Error::WEB_GET_RANDOM_VALUES => Some("Calling Web API crypto.getRandomValues failed"), Error::VXWORKS_RAND_SECURE => Some("randSecure: VxWorks RNG module is not initialized"), - Error::NODE_CRYPTO => Some("Node.js crypto module is unavailable"), - Error::NODE_RANDOM_FILL_SYNC => Some("Node.js API crypto.randomFillSync is unavailable"), + Error::NODE_CRYPTO => Some("Node.js crypto CommonJS module is unavailable"), + Error::NODE_RANDOM_FILL_SYNC => Some("Calling Node.js API crypto.randomFillSync failed"), + Error::NODE_ES_MODULE => Some("Node.js ES modules are not directly supported, see https://docs.rs/getrandom#nodejs-es-module-support"), _ => None, } } diff --git a/src/js.rs b/src/js.rs --- a/src/js.rs +++ b/src/js.rs @@ -10,15 +10,16 @@ use crate::Error; extern crate std; use std::thread_local; -use js_sys::{global, Uint8Array}; +use js_sys::{global, Function, Uint8Array}; use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue}; +// Size of our temporary Uint8Array buffer used with WebCrypto methods // Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues -const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256; +const WEB_CRYPTO_BUFFER_SIZE: usize = 256; enum RngSource { Node(NodeCrypto), - Browser(BrowserCrypto, Uint8Array), + Web(WebCrypto, Uint8Array), } // JsValues are always per-thread, so we initialize RngSource for each thread. diff --git a/src/js.rs b/src/js.rs --- a/src/js.rs +++ b/src/js.rs @@ -37,10 +38,10 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { return Err(Error::NODE_RANDOM_FILL_SYNC); } } - RngSource::Browser(crypto, buf) => { + RngSource::Web(crypto, buf) => { // getRandomValues does not work with all types of WASM memory, // so we initially write to browser memory to avoid exceptions. - for chunk in dest.chunks_mut(BROWSER_CRYPTO_BUFFER_SIZE) { + for chunk in dest.chunks_mut(WEB_CRYPTO_BUFFER_SIZE) { // The chunk can be smaller than buf's length, so we call to // JS to create a smaller view of buf without allocation. let sub_buf = buf.subarray(0, chunk.len() as u32); diff --git a/src/js.rs b/src/js.rs --- a/src/js.rs +++ b/src/js.rs @@ -58,25 +59,33 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { fn getrandom_init() -> Result<RngSource, Error> { let global: Global = global().unchecked_into(); - if is_node(&global) { - let crypto = NODE_MODULE - .require("crypto") - .map_err(|_| Error::NODE_CRYPTO)?; - return Ok(RngSource::Node(crypto)); - } - // Assume we are in some Web environment (browser or web worker). We get - // `self.crypto` (called `msCrypto` on IE), so we can call - // `crypto.getRandomValues`. If `crypto` isn't defined, we assume that - // we are in an older web browser and the OS RNG isn't available. - let crypto = match (global.crypto(), global.ms_crypto()) { - (c, _) if c.is_object() => c, - (_, c) if c.is_object() => c, - _ => return Err(Error::WEB_CRYPTO), + // Get the Web Crypto interface if we are in a browser, Web Worker, Deno, + // or another environment that supports the Web Cryptography API. This + // also allows for user-provided polyfills in unsupported environments. + let crypto = match global.crypto() { + // Standard Web Crypto interface + c if c.is_object() => c, + // Node.js CommonJS Crypto module + _ if is_node(&global) => { + // If module.require isn't a valid function, we are in an ES module. + match Module::require_fn().and_then(JsCast::dyn_into::<Function>) { + Ok(require_fn) => match require_fn.call1(&global, &JsValue::from_str("crypto")) { + Ok(n) => return Ok(RngSource::Node(n.unchecked_into())), + Err(_) => return Err(Error::NODE_CRYPTO), + }, + Err(_) => return Err(Error::NODE_ES_MODULE), + } + } + // IE 11 Workaround + _ => match global.ms_crypto() { + c if c.is_object() => c, + _ => return Err(Error::WEB_CRYPTO), + }, }; - let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32); - Ok(RngSource::Browser(crypto, buf)) + let buf = Uint8Array::new_with_length(WEB_CRYPTO_BUFFER_SIZE as u32); + Ok(RngSource::Web(crypto, buf)) } // Taken from https://www.npmjs.com/package/browser-or-node diff --git a/src/js.rs b/src/js.rs --- a/src/js.rs +++ b/src/js.rs @@ -93,30 +102,36 @@ fn is_node(global: &Global) -> bool { #[wasm_bindgen] extern "C" { - type Global; // Return type of js_sys::global() + // Return type of js_sys::global() + type Global; - // Web Crypto API (https://www.w3.org/TR/WebCryptoAPI/) - #[wasm_bindgen(method, getter, js_name = "msCrypto")] - fn ms_crypto(this: &Global) -> BrowserCrypto; + // Web Crypto API: Crypto interface (https://www.w3.org/TR/WebCryptoAPI/) + type WebCrypto; + // Getters for the WebCrypto API #[wasm_bindgen(method, getter)] - fn crypto(this: &Global) -> BrowserCrypto; - type BrowserCrypto; + fn crypto(this: &Global) -> WebCrypto; + #[wasm_bindgen(method, getter, js_name = msCrypto)] + fn ms_crypto(this: &Global) -> WebCrypto; + // Crypto.getRandomValues() #[wasm_bindgen(method, js_name = getRandomValues, catch)] - fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>; + fn get_random_values(this: &WebCrypto, buf: &Uint8Array) -> Result<(), JsValue>; - // We use a "module" object here instead of just annotating require() with - // js_name = "module.require", so that Webpack doesn't give a warning. See: - // https://github.com/rust-random/getrandom/issues/224 - type NodeModule; - #[wasm_bindgen(js_name = module)] - static NODE_MODULE: NodeModule; // Node JS crypto module (https://nodejs.org/api/crypto.html) - #[wasm_bindgen(method, catch)] - fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>; type NodeCrypto; + // crypto.randomFillSync() #[wasm_bindgen(method, js_name = randomFillSync, catch)] fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>; + // Ideally, we would just use `fn require(s: &str)` here. However, doing + // this causes a Webpack warning. So we instead return the function itself + // and manually invoke it using call1. This also lets us to check that the + // function actually exists, allowing for better error messages. See: + // https://github.com/rust-random/getrandom/issues/224 + // https://github.com/rust-random/getrandom/issues/256 + type Module; + #[wasm_bindgen(getter, static_method_of = Module, js_class = module, js_name = require, catch)] + fn require_fn() -> Result<JsValue, JsValue>; + // Node JS process Object (https://nodejs.org/api/process.html) #[wasm_bindgen(method, getter)] fn process(this: &Global) -> Process; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -31,7 +31,7 @@ //! | Emscripten | `*‑emscripten` | `/dev/random` (identical to `/dev/urandom`) //! | WASI | `wasm32‑wasi` | [`random_get`] //! | Web Browser | `wasm32‑*‑unknown` | [`Crypto.getRandomValues`], see [WebAssembly support] -//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomBytes`], see [WebAssembly support] +//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomFillSync`], see [WebAssembly support] //! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes` //! | Nintendo 3DS | `armv6k-nintendo-3ds` | [`getrandom`][1] //! diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -91,6 +91,18 @@ //! //! This feature has no effect on targets other than `wasm32-unknown-unknown`. //! +//! #### Node.js ES module support +//! +//! Node.js supports both [CommonJS modules] and [ES modules]. Due to +//! limitations in wasm-bindgen's [`module`] support, we cannot directly +//! support ES Modules running on Node.js. However, on Node v15 and later, the +//! module author can add a simple shim to support the Web Cryptography API: +//! ```js +//! import { webcrypto } from 'node:crypto' +//! globalThis.crypto = webcrypto +//! ``` +//! This crate will then use the provided `webcrypto` implementation. +//! //! ### Custom implementations //! //! The [`register_custom_getrandom!`] macro allows a user to mark their own
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -154,11 +166,14 @@ //! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide //! [`SecRandomCopyBytes`]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc //! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw -//! [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback +//! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size //! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t //! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno //! [WebAssembly support]: #webassembly-support //! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen +//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html +//! [CommonJS modules]: https://nodejs.org/api/modules.html +//! [ES modules]: https://nodejs.org/api/esm.html #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
Javascript code does not work in ESM context Currently wasm-pack has two common build options: - `nodejs` produces a commonjs module for node - `web` produces an es6 module for the web I'd like to use the same wasm module (published in npm) isomorphically for both nodejs and the web. It almost works - but unfortunately getrandom (run from nodejs) doesn't work at all in an es6 context. It produces this code in a esm file: ``` imports.wbg.__wbg_modulerequire_0a83c0c31d12d2c7 = function() { return handleError(function (arg0, arg1) { var ret = module.require(getStringFromWasm0(arg0, arg1)); return addHeapObject(ret); }, arguments) }; ``` ... Which errors, because `module` is not defined in this context. I'm not sure how getrandom should work around this. Any thoughts?
We have run into a bunch of issues like this before (see #214 #224 #234). If you (or anyone else) have an improvement for our code, we would be happy to accept a PR. The current logic for selecting the implementation is here: https://github.com/rust-random/getrandom/blob/9e2c896e653611188df9d835d2570546e2bf1d67/src/js.rs#L59 We have CI tests that make sure our code works w/ Web and NodeJS, so I'm confused as to why you are having issues. The code you have above will only be run in a Node environment. That function will not be called if you are running on a web browser. Oh wait I think this issue was fixed in #234 as the generated JS bindings should now look like: ``` getObject(arg0).require(getStringFromWasm0(arg1, arg2)) ``` not ``` module.require(getStringFromWasm0(arg0, arg1)) ``` Can you make sure you are using the latest version of `getrandom` and see if your issue still persists? > We have CI tests that make sure our code works w/ Web and NodeJS, so I'm confused as to why you are having issues. The code works in web and nodejs, so long as I compile separate wasm modules for each context. And thus, publish separate npm packages for the web and for nodejs. But I hate that - javascript code works on the web and nodejs (thats kind of the whole point of nodejs). Ideally I'd like to be able to just compile my wasm code once and run it in both a nodejs and web context. And I *almost* can do that - but I just can't get getrandom to work in both contexts. I'm not sure what the right answer is here from a library design perspective. The current steps I'm taking: lib.rs: ```rust use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn foo() -> u32 { console_error_panic_hook::set_once(); let mut bytes = [0; 4]; getrandom::getrandom(&mut bytes[..]).expect("getrandom failed"); u32::from_be_bytes(bytes) } ``` Then: ``` wasm-pack build --dev --target web ``` Unfortunately I need to add `"type": "module"` into the generated package.json. Once I've done that I can load the wasm module from nodejs in a kinda manual, hacky way: foo.mjs: ```javascript import {default as init} from "./pkg/rand_wasm.js" import {readFileSync} from 'fs' ;(async () => { let bytes = readFileSync("pkg/rand_wasm_bg.wasm") let module = await init(bytes) console.log(module.foo()) })() ``` All my rust code runs fine - but the getrandom call fails: ``` $ node foo.mjs panicked at 'getrandom failed: Error { internal_code: 2147483660, description: "Node.js crypto module is unavailable" }', src/lib.rs:8:42 (stack follows...) ``` The reason is that the [nodejs codepath](https://github.com/rust-random/getrandom/blob/9e2c896e653611188df9d835d2570546e2bf1d67/src/js.rs#L62-L64) is trying to use `require()`, which is unavailable when using es modules. For now I've given up, and I'm just compiling my wasm module twice (once for node, once for the web). But ideally I'd like to get this fixed. Having a single wasm module which works everywhere would be lovely. Any ideas on how we can make this work? Maybe in the long term I could target WASI instead, which provides an [API for random](https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---result-errno). Thats probably a long ways out though :/ Another approach is to detect nodejs then use a dynamic import if we're in ESM mode - ```javascript let crypto = await import('node:crypto').webcrypto crypto.getRandomValues(buffer) ``` ... But dynamic imports return a promise, and thats really hard to cope with. :/ A cheap workaround is to add this to the end of the generated bindings file: ```ts // workaround for https://github.com/rust-random/getrandom/issues/256 import * as crypto from "crypto" const module = { require: (string) => { if(string !== "crypto") throw new Error("Unexpected require " + string) return crypto } } ``` So it seems like we cannot support both ES6 modules running on Node.js and `wasm_bindgen`'s `--target nodejs` which uses CommonJS modules. I'll try to get some concrete code examples together this week/weekend. Basically, as the object returned by `import()` is a `Promise` and we have no way to "run" this Promise, we can't actually use `import()` as a function call. We can [convert between Promises and Futures](https://rustwasm.github.io/wasm-bindgen/reference/js-promises-and-rust-futures.html) but there's not a way to execute them. We could get around this by using [top-level `await`](https://github.com/tc39/proposal-top-level-await) but that doesn't work with CommonJS. This would also mean losing support for many older environments which currently work. So _if_ we want to support this use-case, we would have to add an additional `js_modules` Cargo feature that: - Allows `getrandom` use features exclusive to ES6 modules - Node.js + ES6 now works - Makes `getrandom` no longer work in older JS environments - Makes `getrandom` incompatible with `wasm_bindgen`'s `--target nodejs` and `--target no-modules` - Only `--target web` and `--target bundler` would be supported > The code works in web and nodejs, so long as I compile separate wasm modules for each context. And thus, publish separate npm packages for the web and for nodejs. But I hate that - javascript code works on the web and nodejs (thats kind of the whole point of nodejs). Ideally I'd like to be able to just compile my wasm code once and run it in both a nodejs and web context. The main issue here is that Node and the Web really are different targets, even if they are superficially similar. We've had a ton of issues targeting Node.js in general (targeting the Web has been bad but not _as bad_). This library attempts to support every Rust target possible, and Node.js has _easily_ has the highest maintenance cost, due to: - A lower level of support in `wasm_bindgen` - The fractured module ecosystem (CommonJS modules vs ES6 modules vs whatever was before ES6) - `global.foo` and `foo` not being being the same (or one will exist and the other will not) - We need to _conditionally_ import a Node.js library (unlike the Web which needs no library imports) - Node.js conditional import story is half-backed: - CommonJS `require()` is only synchronous - ES6 `import()` is only asynchronous - Node.js's only ES6-compatible way to do blocking imports requires [importing another Node.js specific library](https://nodejs.org/api/module.html#modulecreaterequirefilename), making this "solution" circular. I've had a bit of a think about it, and I want to suggest another approach: So right now, the logic is something like this: ```javascript if (process.versions.node != null) { require('crypto').randomFillSync(...) } else { globalThis.crypto.getRandomValues(...) } ``` There are essentially 3 different environments: 1. Nodejs in commonjs mode (supported) 2. Nodejs in esm mode (unsupported - require is not available) 3. Web browsers in any mode (supported) If we invert the logic to do capability detection instead, it would look like this: ```javascript if (globalThis.crypto.getRandomValues != null) { globalThis.crypto.getRandomValues(...) } else if (globalThis.require != null) { // Or keep the existing check for process.version.node require('crypto').randomFillSync(...) } ``` Then I could make my code work with a simple shim: ```javascript import {webcrypto} from 'crypto' // only available from node 16+, but thats not a problem for me. globalThis.crypto = webcrypto // ... wasm.init() ``` This would also work in deno, and any other javascript context which follows web standards. And if nodejs ever implements the web's JS crypto standard, everything will just work.
2022-09-13T07:16:02.000Z
0.2
2022-10-19T21:07:18Z
5e62ce9fadb401539a08b329e4cbd98cc6393f60
rust-random/getrandom
278
rust-random__getrandom-278
[ "277" ]
9a64857ae616b57d7b703706fed2f067153a5212
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -72,8 +72,7 @@ //! that you are building for an environment containing JavaScript, and will //! call the appropriate methods. Both web browser (main window and Web Workers) //! and Node.js environments are supported, invoking the methods -//! [described above](#supported-targets) using the -//! [wasm-bindgen](https://github.com/rust-lang/rust-bindgen) toolchain. +//! [described above](#supported-targets) using the [`wasm-bindgen`] toolchain. //! //! This feature has no effect on targets other than `wasm32-unknown-unknown`. //!
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -154,6 +153,7 @@ //! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t //! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno //! [WebAssembly support]: #webassembly-support +//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
Wrong link in the docs links to rust-bindgen instead of wasm-bindgen The [WebAssemmbely](https://docs.rs/getrandom/latest/getrandom/#webassembly-support) docs section seems want to link to [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen), but links to [rust-bindgen](https://github.com/rust-lang/rust-bindgen) instead. I assume this is an error right? I also noticed the issue https://github.com/rust-random/getrandom/issues/267, which could be fixed at the same time as this one when the documentation is updated.
2022-08-18T02:01:56.000Z
0.2
2022-08-19T01:58:35Z
5e62ce9fadb401539a08b329e4cbd98cc6393f60
rust-random/getrandom
192
rust-random__getrandom-192
[ "181" ]
6c94834850c94810f757658255c7e437db84cc44
diff --git /dev/null b/.clippy.toml new file mode 100644 --- /dev/null +++ b/.clippy.toml @@ -0,0 +1,1 @@ +msrv = "1.34" diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -146,8 +146,6 @@ )] #![no_std] #![warn(rust_2018_idioms, unused_lifetimes, missing_docs)] -// `matches!` macro was added only in Rust 1.42, which is bigger than our MSRV -#![allow(clippy::match_like_matches_macro)] #[macro_use] extern crate cfg_if;
diff --git a/.cargo/config b/.cargo/config --- a/.cargo/config +++ b/.cargo/config @@ -1,5 +1,5 @@ +# Allow normal use of "cargo run" and "cargo test" on these wasm32 platforms. [target.wasm32-unknown-unknown] runner = 'wasm-bindgen-test-runner' - [target.wasm32-wasi] runner = 'wasmtime' diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -14,36 +14,47 @@ env: jobs: check-doc: - name: Doc deadlinks + name: Docs, deadlinks, minimal dependencies runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Install toolchain - uses: actions-rs/toolchain@v1 + - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: nightly + toolchain: nightly # Needed for -Z minimal-versions override: true - - run: cargo install cargo-deadlinks - - run: cargo deadlinks -- --features custom + - name: Install precompiled cargo-deadlinks + run: | + export URL=$(curl -s https://api.github.com/repos/deadlinks/cargo-deadlinks/releases/latest | jq -r '.assets[] | select(.name | contains("cargo-deadlinks-linux")) | .browser_download_url') + wget -O /tmp/cargo-deadlinks $URL + chmod +x /tmp/cargo-deadlinks + mv /tmp/cargo-deadlinks ~/.cargo/bin + - run: cargo deadlinks -- --features=custom,std + - run: | + cargo generate-lockfile -Z minimal-versions + cargo test --features=custom,std main-tests: name: Main tests runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-latest, windows-latest] toolchain: [nightly, beta, stable, 1.34] + # Only Test macOS on stable to reduce macOS CI jobs + include: + - os: macos-latest + toolchain: stable steps: - uses: actions/checkout@v2 - - name: Install toolchain - uses: actions-rs/toolchain@v1 + - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.toolchain }} override: true - run: cargo test - - run: cargo test --features std + - run: cargo test --features=std + - run: cargo test --features=custom # custom should do nothing here - if: ${{ matrix.toolchain == 'nightly' }} run: cargo build --benches diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -59,18 +70,40 @@ jobs: ] steps: - uses: actions/checkout@v2 - - name: Install toolchain - uses: actions-rs/toolchain@v1 + - uses: actions-rs/toolchain@v1 with: profile: minimal target: ${{ matrix.target }} toolchain: stable - override: true - # update is needed to fix the 404 error on install, see: - # https://github.com/actions/virtual-environments/issues/675 - - run: sudo apt-get update - - run: sudo apt-get install gcc-multilib - - run: cargo test --target ${{ matrix.target }} + - name: Install multilib + # update is needed to fix the 404 error on install, see: + # https://github.com/actions/virtual-environments/issues/675 + run: | + sudo apt-get update + sudo apt-get install gcc-multilib + - run: cargo test --target=${{ matrix.target }} --features=std + + # We can only Build/Link on these targets for now. + # TODO: Run the iOS binaries in the simulator + # TODO: build/run aarch64-apple-darwin binaries on a x86_64 Mac + apple-tests: + name: Additional Apple targets + runs-on: macos-latest + strategy: + matrix: + target: [ + aarch64-apple-ios, + x86_64-apple-ios, + ] + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + target: ${{ matrix.target }} + toolchain: stable + - name: Build Tests + run: cargo test --no-run --target=${{ matrix.target }} --features=std windows-tests: name: Additional Windows targets diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -90,63 +123,131 @@ jobs: profile: minimal toolchain: ${{ matrix.toolchain }} override: true - - run: cargo test + - run: cargo test --features=std + # TODO: Add emscripten when it's working with Cross cross-tests: - name: Cross tests - runs-on: ${{ matrix.os }} + name: Cross Test + runs-on: ubuntu-latest strategy: matrix: - include: - - os: ubuntu-latest - target: mips-unknown-linux-gnu - toolchain: stable + target: [ + aarch64-unknown-linux-gnu, + aarch64-linux-android, + mips-unknown-linux-gnu, + ] steps: - uses: actions/checkout@v2 - - name: Install toolchain - uses: actions-rs/toolchain@v1 + - uses: actions-rs/toolchain@v1 with: profile: minimal target: ${{ matrix.target }} - toolchain: ${{ matrix.toolchain }} - override: true - - name: Cache cargo plugins - uses: actions/cache@v1 - with: - path: ~/.cargo/bin/ - key: ${{ runner.os }}-cargo-plugins - - name: Install cross - run: cargo install cross || true + toolchain: stable + - name: Install precompiled cross + run: | + export URL=$(curl -s https://api.github.com/repos/rust-embedded/cross/releases/latest | jq -r '.assets[] | select(.name | contains("x86_64-unknown-linux-gnu.tar.gz")) | .browser_download_url') + wget -O /tmp/binaries.tar.gz $URL + tar -C /tmp -xzf /tmp/binaries.tar.gz + mv /tmp/cross ~/.cargo/bin - name: Test - run: cross test --no-fail-fast --target ${{ matrix.target }} + run: cross test --no-fail-fast --target=${{ matrix.target }} --features=std - build: - name: Build-only + cross-link: + name: Cross Build/Link runs-on: ubuntu-latest strategy: matrix: target: [ x86_64-sun-solaris, + x86_64-unknown-netbsd, + ] + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + target: ${{ matrix.target }} + toolchain: stable + - name: Install precompiled cross + run: | + export URL=$(curl -s https://api.github.com/repos/rust-embedded/cross/releases/latest | jq -r '.assets[] | select(.name | contains("x86_64-unknown-linux-gnu.tar.gz")) | .browser_download_url') + wget -O /tmp/binaries.tar.gz $URL + tar -C /tmp -xzf /tmp/binaries.tar.gz + mv /tmp/cross ~/.cargo/bin + - name: Build Tests + run: cross test --no-run --target=${{ matrix.target }} --features=std + + web-tests: + name: Web tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + target: wasm32-unknown-unknown + toolchain: stable + - name: Install precompiled wasm-bindgen-test-runner + run: | + export VERSION=$(cargo metadata --format-version=1 | jq -r '.packages[] | select ( .name == "wasm-bindgen" ) | .version') + wget -O /tmp/binaries.tar.gz https://github.com/rustwasm/wasm-bindgen/releases/download/$VERSION/wasm-bindgen-$VERSION-x86_64-unknown-linux-musl.tar.gz + tar -C /tmp -xzf /tmp/binaries.tar.gz --strip-components=1 + mv /tmp/wasm-bindgen-test-runner ~/.cargo/bin + - name: Test (Node) + run: cargo test --target=wasm32-unknown-unknown --features=js + - name: Test (Firefox) + env: + GECKODRIVER: /usr/bin/geckodriver + run: cargo test --target=wasm32-unknown-unknown --features=js,test-in-browser + - name: Test (Chrome) + env: + CHROMEDRIVER: /usr/bin/chromedriver + run: cargo test --target=wasm32-unknown-unknown --features=js,test-in-browser + - name: Build Tests (with custom, without JS) + run: cargo test --no-run --target=wasm32-unknown-unknown --features=custom + + wasi-tests: + name: WASI test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + target: wasm32-wasi + toolchain: stable + - name: Install precompiled wasmtime + run: | + export URL=$(curl -s https://api.github.com/repos/bytecodealliance/wasmtime/releases/latest | jq -r '.assets[] | select(.name | contains("x86_64-linux.tar.xz")) | .browser_download_url') + wget -O /tmp/binaries.tar.xz $URL + tar -C /tmp -xf /tmp/binaries.tar.xz --strip-components=1 + mv /tmp/wasmtime ~/.cargo/bin + - run: cargo test --target wasm32-wasi + + build: + name: Build only + runs-on: ubuntu-latest + strategy: + matrix: + target: [ x86_64-unknown-freebsd, x86_64-fuchsia, - x86_64-unknown-netbsd, x86_64-unknown-redox, x86_64-fortanix-unknown-sgx, ] steps: - uses: actions/checkout@v2 - - name: Install toolchain - uses: actions-rs/toolchain@v1 + - uses: actions-rs/toolchain@v1 with: profile: minimal target: ${{ matrix.target }} - toolchain: nightly + toolchain: nightly # Required to build libc for Redox override: true - name: Build - run: cargo build --target ${{ matrix.target }} + run: cargo build --target=${{ matrix.target }} --features=std - build-rdrand: - name: Build-only RDRAND + build-std: + name: Build-only (build-std) runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -154,24 +255,17 @@ jobs: uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: nightly + toolchain: nightly # Required to build libcore components: rust-src override: true - - name: Cache cargo plugins - uses: actions/cache@v1 - with: - path: ~/.cargo/bin/ - key: ${{ runner.os }}-cargo-plugins - - name: Install xbuild - run: cargo install cargo-xbuild || true - - name: UEFI - run: cargo xbuild --features=rdrand --target x86_64-unknown-uefi - - name: Hermit - run: cargo xbuild --features=rdrand --target x86_64-unknown-hermit - - name: L4Re - run: cargo xbuild --features=rdrand --target x86_64-unknown-l4re-uclibc + - name: UEFI (RDRAND) + run: cargo build -Z build-std=core --features=rdrand --target=x86_64-unknown-uefi + - name: Hermit (RDRAND) + run: cargo build -Z build-std=core --features=rdrand --target=x86_64-unknown-hermit + - name: L4Re (RDRAND) + run: cargo build -Z build-std=core --features=rdrand --target=x86_64-unknown-l4re-uclibc - name: VxWorks - run: cargo xbuild --features=rdrand --target x86_64-wrs-vxworks + run: cargo build -Z build-std=core --target=x86_64-wrs-vxworks clippy-fmt: name: Clippy + rustfmt diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -181,9 +275,12 @@ jobs: - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: stable + # https://github.com/rust-lang/rust-clippy/pull/6379 added MSRV + # support, so we need to use nightly until this is on stable. + toolchain: nightly components: rustfmt, clippy + override: true - name: clippy - run: cargo clippy --all + run: cargo clippy --all --features=custom,std - name: fmt run: cargo fmt --all -- --check
Add CI for WASM targets In #180 we have migrated to GitHub Actions almost all tests except related to WASM and Emscripten. [Old Travis config](https://github.com/rust-random/getrandom/blob/2d899940a2a4968f81b3e715deef1a6d47cf5801/.travis.yml#L37-L97)
With the stdweb support removed in #178, this should now be easier to get working. The best approach might be to have a Dockerfile containing the Node/Firefox/Chromium deps, so that we can keep all of those ordered in a single place.
2021-01-03T05:40:59.000Z
0.2
2021-01-04T06:05:18Z
5e62ce9fadb401539a08b329e4cbd98cc6393f60
dtolnay/proc-macro2
438
dtolnay__proc-macro2-438
[ "414" ]
1edd1b993b79d16f60a85f32a320d9430dfde8a8
diff --git a/src/fallback.rs b/src/fallback.rs --- a/src/fallback.rs +++ b/src/fallback.rs @@ -320,17 +320,30 @@ impl Debug for SourceFile { } } +#[cfg(all(span_locations, not(fuzzing)))] +fn dummy_file() -> FileInfo { + FileInfo { + source_text: String::new(), + span: Span { lo: 0, hi: 0 }, + lines: vec![0], + char_index_to_byte_offset: BTreeMap::new(), + } +} + #[cfg(all(span_locations, not(fuzzing)))] thread_local! { static SOURCE_MAP: RefCell<SourceMap> = RefCell::new(SourceMap { // Start with a single dummy file which all call_site() and def_site() // spans reference. - files: vec![FileInfo { - source_text: String::new(), - span: Span { lo: 0, hi: 0 }, - lines: vec![0], - char_index_to_byte_offset: BTreeMap::new(), - }], + files: vec![dummy_file()], + }); +} + +#[cfg(all(span_locations, not(fuzzing)))] +pub fn invalidate_current_thread_spans() { + SOURCE_MAP.with(|sm| { + let mut sm = sm.borrow_mut(); + sm.files = vec![dummy_file()]; }); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -170,6 +170,10 @@ use std::error::Error; #[cfg(procmacro2_semver_exempt)] use std::path::PathBuf; +#[cfg(span_locations)] +#[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))] +pub use crate::imp::invalidate_current_thread_spans; + #[cfg(span_locations)] #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))] pub use crate::location::LineColumn; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1325,4 +1329,4 @@ pub mod token_stream { } } } -} +} \ No newline at end of file diff --git a/src/wrapper.rs b/src/wrapper.rs --- a/src/wrapper.rs +++ b/src/wrapper.rs @@ -928,3 +928,30 @@ impl Debug for Literal { } } } + +/// Invalidates any `proc_macro2::Span` on the current thread +/// +/// The implementation of the `proc_macro2::Span` type relies on thread-local +/// memory and this function clears it. Calling any method on a +/// `proc_macro2::Span` on the current thread and that was created before this +/// function was called will either lead to incorrect results or abort your +/// program. +/// +/// This function is useful for programs that process more than 2^32 bytes of +/// text on a single thread. The internal representation of `proc_macro2::Span` +/// uses 32-bit integers to represent offsets and those will overflow when +/// processing more than 2^32 bytes. This function resets all offsets +/// and thereby also invalidates any previously created `proc_macro2::Span`. +/// +/// This function requires the `span-locations` feature to be enabled. This +/// function is not applicable to and will panic if called from a procedural macro. +#[cfg(span_locations)] +pub fn invalidate_current_thread_spans() { + if inside_proc_macro() { + panic!( + "proc_macro2::invalidate_current_thread_spans is not available in procedural macros" + ); + } else { + crate::fallback::invalidate_current_thread_spans() + } +}
diff --git a/tests/test.rs b/tests/test.rs --- a/tests/test.rs +++ b/tests/test.rs @@ -757,3 +757,40 @@ fn byte_order_mark() { let string = "foo\u{feff}"; string.parse::<TokenStream>().unwrap_err(); } + +// Creates a new Span from a TokenStream +#[cfg(all(test, span_locations))] +fn create_span() -> proc_macro2::Span { + let tts: TokenStream = "1".parse().unwrap(); + match tts.into_iter().next().unwrap() { + TokenTree::Literal(literal) => literal.span(), + _ => unreachable!(), + } +} + +#[cfg(span_locations)] +#[test] +fn test_invalidate_current_thread_spans() { + let actual = format!("{:#?}", create_span()); + assert_eq!(actual, "bytes(1..2)"); + let actual = format!("{:#?}", create_span()); + assert_eq!(actual, "bytes(3..4)"); + + proc_macro2::invalidate_current_thread_spans(); + + let actual = format!("{:#?}", create_span()); + // Test that span offsets have been reset after the call + // to invalidate_current_thread_spans() + assert_eq!(actual, "bytes(1..2)"); +} + +#[cfg(span_locations)] +#[test] +#[should_panic] +fn test_use_span_after_invalidation() { + let span = create_span(); + + proc_macro2::invalidate_current_thread_spans(); + + span.source_text(); +}
Consider an API to reset thread-local Span data Basically truncate this thing: https://github.com/dtolnay/proc-macro2/blob/fecb02df0e2966c7eb39e020dbf650fa8bafd0c5/src/fallback.rs#L323-L325 Resetting would be a claim that all currently existing non-call-site spans on the current thread are no longer in use, or it's okay if methods like `line`/`column` and `source_text` crash or produce wrong results. A workload that involves parsing all versions of all crates on a thread pool of 64 threads would need this, because otherwise our 32-bit positions would overflow. See https://github.com/dtolnay/proc-macro2/issues/413#issuecomment-1754216797.
Adding such an API would be much appreciated. My workload is similar to what you described in your comment. David, did you already have an API in mind? I'd be happy to file a PR. Also for my understanding: The idea behind the thread-local source map is to avoid a ref on Span to safe bytes? Something like `proc_macro2::invalidate_current_thread_spans()` with a realistic code example. > The idea behind the thread-local source map is to avoid a ref on Span to safe bytes? `Span` needs to be Copy and 'static. I don't know any other way to implement that, regardless of how many bytes big Span is.
2024-01-18T12:23:20.000Z
1.0
2024-01-20T23:45:53Z
1edd1b993b79d16f60a85f32a320d9430dfde8a8
dtolnay/proc-macro2
411
dtolnay__proc-macro2-411
[ "410" ]
12eddc03a40e8393e82f7ef1dadbaaabdcb00a08
diff --git a/src/fallback.rs b/src/fallback.rs --- a/src/fallback.rs +++ b/src/fallback.rs @@ -364,7 +364,10 @@ impl FileInfo { fn source_text(&self, span: Span) -> String { let lo = (span.lo - self.span.lo) as usize; - let trunc_lo = &self.source_text[lo..]; + let trunc_lo = match self.source_text.char_indices().nth(lo) { + Some((offset, _ch)) => &self.source_text[offset..], + None => return String::new(), + }; let char_len = (span.hi - span.lo) as usize; let source_text = match trunc_lo.char_indices().nth(char_len) { Some((offset, _ch)) => &trunc_lo[..offset],
diff --git a/tests/test.rs b/tests/test.rs --- a/tests/test.rs +++ b/tests/test.rs @@ -328,10 +328,17 @@ fn literal_span() { #[cfg(span_locations)] #[test] fn source_text() { - let input = " 𓀕 "; - let tokens = input.parse::<proc_macro2::TokenStream>().unwrap(); - let ident = tokens.into_iter().next().unwrap(); + let input = " 𓀕 c "; + let mut tokens = input + .parse::<proc_macro2::TokenStream>() + .unwrap() + .into_iter(); + + let ident = tokens.next().unwrap(); assert_eq!("𓀕", ident.span().source_text().unwrap()); + + let ident = tokens.next().unwrap(); + assert_eq!("c", ident.span().source_text().unwrap()); } #[test]
Issue with multibyte chars in source_text() computation It treats `lo` as a byte index, while it is actually a character index: https://github.com/dtolnay/proc-macro2/blob/7f5533d6cc9ff783d174aec4e3be2caa202b62ca/src/fallback.rs#L367 I expect this test to pass, but it does not: ```rust #[cfg(span_locations)] #[test] fn source_text() { let input = " 𓀕 c "; let mut tokens = input .parse::<proc_macro2::TokenStream>() .unwrap() .into_iter(); let ident1 = tokens.next().unwrap(); assert_eq!("𓀕", ident1.span().source_text().unwrap()); let ident2 = tokens.next().unwrap(); assert_eq!("𓀕", ident2.span().source_text().unwrap()); } ``` Panics with (as character `𓀕` occupies byte 5 and 6) ``` ---- source_text stdout ---- thread 'source_text' panicked at 'byte index 6 is not a char boundary; it is inside '𓀕' (bytes 4..8) of ` 𓀕 c `', src/fallback.rs:367:25 ```
2023-10-09T00:56:29.000Z
1.0
2023-10-09T01:07:12Z
1edd1b993b79d16f60a85f32a320d9430dfde8a8
dtolnay/proc-macro2
409
dtolnay__proc-macro2-409
[ "408" ]
07bb590e9706c65f4c850f0163ec05333ab636c9
diff --git a/src/fallback.rs b/src/fallback.rs --- a/src/fallback.rs +++ b/src/fallback.rs @@ -364,8 +364,13 @@ impl FileInfo { fn source_text(&self, span: Span) -> String { let lo = (span.lo - self.span.lo) as usize; - let hi = (span.hi - self.span.lo) as usize; - self.source_text[lo..hi].to_owned() + let trunc_lo = &self.source_text[lo..]; + let char_len = (span.hi - span.lo) as usize; + let source_text = match trunc_lo.char_indices().nth(char_len) { + Some((offset, _ch)) => &trunc_lo[..offset], + None => trunc_lo, + }; + source_text.to_owned() } }
diff --git a/tests/test.rs b/tests/test.rs --- a/tests/test.rs +++ b/tests/test.rs @@ -325,6 +325,15 @@ fn literal_span() { assert!(positive.subspan(1..4).is_none()); } +#[cfg(span_locations)] +#[test] +fn source_text() { + let input = " 𓀕 "; + let tokens = input.parse::<proc_macro2::TokenStream>().unwrap(); + let ident = tokens.into_iter().next().unwrap(); + assert_eq!("𓀕", ident.span().source_text().unwrap()); +} + #[test] fn roundtrip() { fn roundtrip(p: &str) {
`Span::source_text` panics with multibyte source ```rust #[test] fn proc_macro2_source_text_is_correct_for_single_byte() { let source_code = "const FOO: () = ();"; let ast = syn::parse_str::<syn::ItemConst>(source_code).unwrap(); assert_eq!("FOO", ast.ident.span().source_text().unwrap()) } #[test] #[should_panic = "is not a char boundary"] fn proc_macro2_source_text_is_incorrect_for_multibyte() { let source_code = "const 𓀕: () = ();"; let ast = syn::parse_str::<syn::ItemConst>(source_code).unwrap(); let reported = ast.ident.span().source_text(); // boom assert_eq!("𓀕", reported.unwrap()) } ``` Note this is just _calling the method_, not unwrapping the `Option`: ``` thread 'tests::proc_macro2_source_text_is_incorrect_for_multibyte' panicked at 'byte index 7 is not a char boundary; it is inside '𓀕' (bytes 6..10) of `const 𓀕: () = ();`', /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:369:9 ... 6: <alloc::string::String as core::ops::index::Index<core::ops::range::Range<usize>>>::index at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/alloc/src/string.rs:2350:10 7: proc_macro2::fallback::FileInfo::source_text at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:369:9 8: proc_macro2::fallback::Span::source_text::{{closure}} at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:569:43 9: std::thread::local::LocalKey<T>::try_with at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/std/src/thread/local.rs:270:16 10: std::thread::local::LocalKey<T>::with at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/std/src/thread/local.rs:246:9 11: proc_macro2::fallback::Span::source_text at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:569:22 12: proc_macro2::Span::source_text at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/lib.rs:522:9 13: synsert::tests::proc_macro2_source_text_is_incorrect_for_multibyte at ./src/lib.rs:165:24 14: synsert::tests::proc_macro2_source_text_is_incorrect_for_multibyte::{{closure}} at ./src/lib.rs:162:61 ... ``` `proc-macro2 1.0.67` (latest) Not called from a `proc-macro` context
2023-10-06T04:04:55.000Z
1.0
2023-10-06T04:16:15Z
1edd1b993b79d16f60a85f32a320d9430dfde8a8
dtolnay/proc-macro2
380
dtolnay__proc-macro2-380
[ "363" ]
c4a3e197f086b9f21880c979f7c87a04808660ac
diff --git a/src/fallback.rs b/src/fallback.rs --- a/src/fallback.rs +++ b/src/fallback.rs @@ -958,12 +958,20 @@ impl Literal { pub fn string(t: &str) -> Literal { let mut repr = String::with_capacity(t.len() + 2); repr.push('"'); - for c in t.chars() { - if c == '\'' { + let mut chars = t.chars(); + while let Some(ch) = chars.next() { + if ch == '\0' + && chars + .as_str() + .starts_with(|next| '0' <= next && next <= '7') + { + // circumvent clippy::octal_escapes lint + repr.push_str("\\x00"); + } else if ch == '\'' { // escape_debug turns this into "\'" which is unnecessary. - repr.push(c); + repr.push(ch); } else { - repr.extend(c.escape_debug()); + repr.extend(ch.escape_debug()); } } repr.push('"'); diff --git a/src/fallback.rs b/src/fallback.rs --- a/src/fallback.rs +++ b/src/fallback.rs @@ -985,16 +993,21 @@ impl Literal { pub fn byte_string(bytes: &[u8]) -> Literal { let mut escaped = "b\"".to_string(); - for b in bytes { + let mut bytes = bytes.iter(); + while let Some(&b) = bytes.next() { #[allow(clippy::match_overlapping_arm)] - match *b { - b'\0' => escaped.push_str(r"\0"), + match b { + b'\0' => escaped.push_str(match bytes.as_slice().first() { + // circumvent clippy::octal_escapes lint + Some(b'0'..=b'7') => r"\x00", + _ => r"\0", + }), b'\t' => escaped.push_str(r"\t"), b'\n' => escaped.push_str(r"\n"), b'\r' => escaped.push_str(r"\r"), b'"' => escaped.push_str("\\\""), b'\\' => escaped.push_str("\\\\"), - b'\x20'..=b'\x7E' => escaped.push(*b as char), + b'\x20'..=b'\x7E' => escaped.push(b as char), _ => { let _ = write!(escaped, "\\x{:02X}", b); }
diff --git a/tests/test.rs b/tests/test.rs --- a/tests/test.rs +++ b/tests/test.rs @@ -1,7 +1,8 @@ #![allow( clippy::assertions_on_result_states, clippy::items_after_statements, - clippy::non_ascii_literal + clippy::non_ascii_literal, + clippy::octal_escapes )] use proc_macro2::{Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; diff --git a/tests/test.rs b/tests/test.rs --- a/tests/test.rs +++ b/tests/test.rs @@ -114,6 +115,11 @@ fn literal_string() { assert_eq!(Literal::string("foo").to_string(), "\"foo\""); assert_eq!(Literal::string("\"").to_string(), "\"\\\"\""); assert_eq!(Literal::string("didn't").to_string(), "\"didn't\""); + + let repr = Literal::string("a\00b\07c\08d\0e\0").to_string(); + if repr != "\"a\\x000b\\x007c\\u{0}8d\\u{0}e\\u{0}\"" { + assert_eq!(repr, "\"a\\x000b\\x007c\\08d\\0e\\0\""); + } } #[test] diff --git a/tests/test.rs b/tests/test.rs --- a/tests/test.rs +++ b/tests/test.rs @@ -147,6 +153,10 @@ fn literal_byte_string() { Literal::byte_string(b"\0\t\n\r\"\\2\x10").to_string(), "b\"\\0\\t\\n\\r\\\"\\\\2\\x10\"", ); + assert_eq!( + Literal::byte_string(b"a\00b\07c\08d\0e\0").to_string(), + "b\"a\\x000b\\x007c\\08d\\0e\\0\"", + ); } #[test]
`LitByteStr` produces tokens that trigger `clippy::octal-escapes` Not sure whether to file this here or in `quote`. `LitByteStr::new(&[65, 0], ...)` quotes as `b"a\0"`, which triggers [this default clippy lint](https://rust-lang.github.io/rust-clippy/master/#octal_escapes). Whether that lint should be default is a different question, but it'd be nice if syn output would be clippy clean. This would mean representing `0u8` by `\x00` instead of `\0`.
https://github.com/dtolnay/proc-macro2/blob/master/src/fallback.rs#L932 Actually this only triggers if the `\0` is followed by a digit.
2023-04-03T06:04:06.000Z
1.0
2023-04-03T06:18:33Z
1edd1b993b79d16f60a85f32a320d9430dfde8a8
dtolnay/proc-macro2
354
dtolnay__proc-macro2-354
[ "353" ]
f26128d5d6c94c62ce70683f6f4363766963a256
diff --git a/src/fallback.rs b/src/fallback.rs --- a/src/fallback.rs +++ b/src/fallback.rs @@ -182,7 +182,13 @@ impl FromStr for TokenStream { fn from_str(src: &str) -> Result<TokenStream, LexError> { // Create a dummy file & add it to the source map - let cursor = get_cursor(src); + let mut cursor = get_cursor(src); + + // Strip a byte order mark if present + const BYTE_ORDER_MARK: &str = "\u{feff}"; + if cursor.starts_with(BYTE_ORDER_MARK) { + cursor = cursor.advance(BYTE_ORDER_MARK.len()); + } parse::token_stream(cursor) } diff --git a/src/parse.rs b/src/parse.rs --- a/src/parse.rs +++ b/src/parse.rs @@ -14,7 +14,7 @@ pub(crate) struct Cursor<'a> { } impl<'a> Cursor<'a> { - fn advance(&self, bytes: usize) -> Cursor<'a> { + pub fn advance(&self, bytes: usize) -> Cursor<'a> { let (_front, rest) = self.rest.split_at(bytes); Cursor { rest, diff --git a/src/parse.rs b/src/parse.rs --- a/src/parse.rs +++ b/src/parse.rs @@ -23,7 +23,7 @@ impl<'a> Cursor<'a> { } } - fn starts_with(&self, s: &str) -> bool { + pub fn starts_with(&self, s: &str) -> bool { self.rest.starts_with(s) }
diff --git a/tests/test.rs b/tests/test.rs --- a/tests/test.rs +++ b/tests/test.rs @@ -630,3 +630,16 @@ fn check_spans_internal(ts: TokenStream, lines: &mut &[(usize, usize, usize, usi } } } + +#[test] +fn byte_order_mark() { + let string = "\u{feff}foo"; + let tokens = string.parse::<TokenStream>().unwrap(); + match tokens.into_iter().next().unwrap() { + TokenTree::Ident(ident) => assert_eq!(ident, "foo"), + _ => unreachable!(), + } + + let string = "foo\u{feff}"; + string.parse::<TokenStream>().unwrap_err(); +}
Fails to parse string starting with byte order mark ```rust let string = "\u{feff}foo"; eprintln!("{:?}", string.parse::<TokenStream>()); ``` proc_macro::TokenStream: ```console Ok(TokenStream [Ident { ident: "foo", span: #6 bytes(31..42) }]) ``` proc_macro2::TokenStream: ```console Err(LexError { span: Span }) ```
2022-09-29T01:55:02.000Z
1.0
2022-09-29T01:58:44Z
1edd1b993b79d16f60a85f32a320d9430dfde8a8
marshallpierce/rust-base64
238
marshallpierce__rust-base64-238
[ "226" ]
f766bc684779b32a3c6df0ea198a8b8df7c440b8
diff --git a/.circleci/config.yml b/.circleci/config.yml --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -14,7 +14,7 @@ workflows: # be easier on the CI hosts since presumably those fat lower layers will already be cached, and # therefore faster than a minimal, customized alpine. # MSRV - 'rust:1.57.0' + 'rust:1.60.0' ] # a hacky scheme to work around CircleCI's inability to deal with mutable docker tags, forcing us to # get a nightly or stable toolchain via rustup instead of a mutable docker tag diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "base64" -version = "0.21.0" +version = "0.21.1" authors = ["Alice Maz <alice@alicemaz.com>", "Marshall Pierce <marshall@mpierce.org>"] description = "encodes and decodes base64 as bytes or utf8" repository = "https://github.com/marshallpierce/rust-base64" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ keywords = ["base64", "utf8", "encode", "decode", "no_std"] categories = ["encoding"] license = "MIT OR Apache-2.0" edition = "2021" -rust-version = "1.57.0" +rust-version = "1.60.0" [[bench]] name = "benchmarks" diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ optionally may allow other behaviors. ## Rust version compatibility -The minimum supported Rust version is 1.57.0. +The minimum supported Rust version is 1.60.0. # Contributing diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -1,6 +1,13 @@ # 0.21.1 - Remove the possibility of panicking during decoded length calculations +- `DecoderReader` no longer sometimes erroneously ignores padding [#226](https://github.com/marshallpierce/rust-base64/issues/226) + +## Breaking changes + +- `Engine.internal_decode` return type changed +- Update MSRV to 1.60.0 + # 0.21.0 diff --git a/clippy.toml b/clippy.toml --- a/clippy.toml +++ b/clippy.toml @@ -1,1 +1,1 @@ -msrv = "1.57.0" +msrv = "1.60.0" diff --git a/src/engine/general_purpose/decode.rs b/src/engine/general_purpose/decode.rs --- a/src/engine/general_purpose/decode.rs +++ b/src/engine/general_purpose/decode.rs @@ -1,5 +1,5 @@ use crate::{ - engine::{general_purpose::INVALID_VALUE, DecodeEstimate, DecodePaddingMode}, + engine::{general_purpose::INVALID_VALUE, DecodeEstimate, DecodeMetadata, DecodePaddingMode}, DecodeError, PAD_BYTE, }; diff --git a/src/engine/general_purpose/decode.rs b/src/engine/general_purpose/decode.rs --- a/src/engine/general_purpose/decode.rs +++ b/src/engine/general_purpose/decode.rs @@ -46,7 +46,7 @@ impl DecodeEstimate for GeneralPurposeEstimate { } /// Helper to avoid duplicating num_chunks calculation, which is costly on short inputs. -/// Returns the number of bytes written, or an error. +/// Returns the decode metadata, or an error. // We're on the fragile edge of compiler heuristics here. If this is not inlined, slow. If this is // inlined(always), a different slow. plain ol' inline makes the benchmarks happiest at the moment, // but this is fragile and the best setting changes with only minor code modifications. diff --git a/src/engine/general_purpose/decode.rs b/src/engine/general_purpose/decode.rs --- a/src/engine/general_purpose/decode.rs +++ b/src/engine/general_purpose/decode.rs @@ -58,7 +58,7 @@ pub(crate) fn decode_helper( decode_table: &[u8; 256], decode_allow_trailing_bits: bool, padding_mode: DecodePaddingMode, -) -> Result<usize, DecodeError> { +) -> Result<DecodeMetadata, DecodeError> { let remainder_len = input.len() % INPUT_CHUNK_LEN; // Because the fast decode loop writes in groups of 8 bytes (unrolled to diff --git a/src/engine/general_purpose/decode_suffix.rs b/src/engine/general_purpose/decode_suffix.rs --- a/src/engine/general_purpose/decode_suffix.rs +++ b/src/engine/general_purpose/decode_suffix.rs @@ -1,13 +1,13 @@ use crate::{ - engine::{general_purpose::INVALID_VALUE, DecodePaddingMode}, + engine::{general_purpose::INVALID_VALUE, DecodeMetadata, DecodePaddingMode}, DecodeError, PAD_BYTE, }; /// Decode the last 1-8 bytes, checking for trailing set bits and padding per the provided /// parameters. /// -/// Returns the total number of bytes decoded, including the ones indicated as already written by -/// `output_index`. +/// Returns the decode metadata representing the total number of bytes decoded, including the ones +/// indicated as already written by `output_index`. pub(crate) fn decode_suffix( input: &[u8], input_index: usize, diff --git a/src/engine/general_purpose/decode_suffix.rs b/src/engine/general_purpose/decode_suffix.rs --- a/src/engine/general_purpose/decode_suffix.rs +++ b/src/engine/general_purpose/decode_suffix.rs @@ -16,7 +16,7 @@ pub(crate) fn decode_suffix( decode_table: &[u8; 256], decode_allow_trailing_bits: bool, padding_mode: DecodePaddingMode, -) -> Result<usize, DecodeError> { +) -> Result<DecodeMetadata, DecodeError> { // Decode any leftovers that aren't a complete input block of 8 bytes. // Use a u64 as a stack-resident 8 byte buffer. let mut leftover_bits: u64 = 0; diff --git a/src/engine/general_purpose/decode_suffix.rs b/src/engine/general_purpose/decode_suffix.rs --- a/src/engine/general_purpose/decode_suffix.rs +++ b/src/engine/general_purpose/decode_suffix.rs @@ -157,5 +157,12 @@ pub(crate) fn decode_suffix( leftover_bits_appended_to_buf += 8; } - Ok(output_index) + Ok(DecodeMetadata::new( + output_index, + if padding_bytes > 0 { + Some(input_index + first_padding_index) + } else { + None + }, + )) } diff --git a/src/engine/general_purpose/mod.rs b/src/engine/general_purpose/mod.rs --- a/src/engine/general_purpose/mod.rs +++ b/src/engine/general_purpose/mod.rs @@ -2,13 +2,14 @@ use crate::{ alphabet, alphabet::Alphabet, - engine::{Config, DecodePaddingMode}, + engine::{Config, DecodeMetadata, DecodePaddingMode}, DecodeError, }; use core::convert::TryInto; mod decode; pub(crate) mod decode_suffix; + pub use decode::GeneralPurposeEstimate; pub(crate) const INVALID_VALUE: u8 = 255; diff --git a/src/engine/general_purpose/mod.rs b/src/engine/general_purpose/mod.rs --- a/src/engine/general_purpose/mod.rs +++ b/src/engine/general_purpose/mod.rs @@ -170,7 +171,7 @@ impl super::Engine for GeneralPurpose { input: &[u8], output: &mut [u8], estimate: Self::DecodeEstimate, - ) -> Result<usize, DecodeError> { + ) -> Result<DecodeMetadata, DecodeError> { decode::decode_helper( input, estimate, diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -73,8 +73,6 @@ pub trait Engine: Send + Sync { /// `decode_estimate` is the result of [Engine::internal_decoded_len_estimate()], which is passed in to avoid /// calculating it again (expensive on short inputs).` /// - /// Returns the number of bytes written to `output`. - /// /// Each complete 4-byte chunk of encoded data decodes to 3 bytes of decoded data, but this /// function must also handle the final possibly partial chunk. /// If the input length is not a multiple of 4, or uses padding bytes to reach a multiple of 4, diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -95,7 +93,7 @@ pub trait Engine: Send + Sync { input: &[u8], output: &mut [u8], decode_estimate: Self::DecodeEstimate, - ) -> Result<usize, DecodeError>; + ) -> Result<DecodeMetadata, DecodeError>; /// Returns the config for this engine. fn config(&self) -> &Self::Config; diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -202,8 +200,7 @@ pub trait Engine: Send + Sync { Ok(encoded_size) } - /// Decode from string reference as octets using the specified [Engine]. - /// Returns a `Result` containing a `Vec<u8>`. + /// Decode the input into a new `Vec`. /// /// # Example /// diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -228,13 +225,16 @@ pub trait Engine: Send + Sync { let estimate = self.internal_decoded_len_estimate(input_bytes.len()); let mut buffer = vec![0; estimate.decoded_len_estimate()]; - let bytes_written = self.internal_decode(input_bytes, &mut buffer, estimate)?; + let bytes_written = self + .internal_decode(input_bytes, &mut buffer, estimate)? + .decoded_len; buffer.truncate(bytes_written); Ok(buffer) } - /// Decode from string reference as octets. + /// Decode the `input` into the supplied `buffer`. + /// /// Writes into the supplied `Vec`, which may allocate if its internal buffer isn't big enough. /// Returns a `Result` containing an empty tuple, aka `()`. /// diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -281,7 +281,9 @@ pub trait Engine: Send + Sync { buffer.resize(total_len_estimate, 0); let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..]; - let bytes_written = self.internal_decode(input_bytes, buffer_slice, estimate)?; + let bytes_written = self + .internal_decode(input_bytes, buffer_slice, estimate)? + .decoded_len; buffer.truncate(starting_output_len + bytes_written); diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -290,7 +292,8 @@ pub trait Engine: Send + Sync { /// Decode the input into the provided output slice. /// - /// Returns an error if `output` is smaller than the estimated decoded length. + /// Returns the number of bytes written to the slice, or an error if `output` is smaller than + /// the estimated decoded length. /// /// This will not write any bytes past exactly what is decoded (no stray garbage bytes at the end). /// diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -312,10 +315,13 @@ pub trait Engine: Send + Sync { self.internal_decode(input_bytes, output, estimate) .map_err(|e| e.into()) + .map(|dm| dm.decoded_len) } /// Decode the input into the provided output slice. /// + /// Returns the number of bytes written to the slice. + /// /// This will not write any bytes past exactly what is decoded (no stray garbage bytes at the end). /// /// See [crate::decoded_len_estimate] for calculating buffer sizes. diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -338,6 +344,7 @@ pub trait Engine: Send + Sync { output, self.internal_decoded_len_estimate(input_bytes.len()), ) + .map(|dm| dm.decoded_len) } } diff --git a/src/engine/mod.rs b/src/engine/mod.rs --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -381,3 +388,21 @@ pub enum DecodePaddingMode { /// Padding must be absent -- for when you want predictable padding, without any wasted bytes. RequireNone, } + +/// Metadata about the result of a decode operation +#[derive(PartialEq, Eq, Debug)] +pub struct DecodeMetadata { + /// Number of decoded bytes output + pub(crate) decoded_len: usize, + /// Offset of the first padding byte in the input, if any + pub(crate) padding_offset: Option<usize>, +} + +impl DecodeMetadata { + pub(crate) fn new(decoded_bytes: usize, padding_index: Option<usize>) -> Self { + Self { + decoded_len: decoded_bytes, + padding_offset: padding_index, + } + } +} diff --git a/src/engine/naive.rs b/src/engine/naive.rs --- a/src/engine/naive.rs +++ b/src/engine/naive.rs @@ -2,7 +2,7 @@ use crate::{ alphabet::Alphabet, engine::{ general_purpose::{self, decode_table, encode_table}, - Config, DecodeEstimate, DecodePaddingMode, Engine, + Config, DecodeEstimate, DecodeMetadata, DecodePaddingMode, Engine, }, DecodeError, PAD_BYTE, }; diff --git a/src/engine/naive.rs b/src/engine/naive.rs --- a/src/engine/naive.rs +++ b/src/engine/naive.rs @@ -112,7 +112,7 @@ impl Engine for Naive { input: &[u8], output: &mut [u8], estimate: Self::DecodeEstimate, - ) -> Result<usize, DecodeError> { + ) -> Result<DecodeMetadata, DecodeError> { if estimate.rem == 1 { // trailing whitespace is so common that it's worth it to check the last byte to // possibly return a better error message diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -1,4 +1,4 @@ -use crate::{engine::Engine, DecodeError}; +use crate::{engine::Engine, DecodeError, PAD_BYTE}; use std::{cmp, fmt, io}; // This should be large, but it has to fit on the stack. diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -46,13 +46,15 @@ pub struct DecoderReader<'e, E: Engine, R: io::Read> { // Technically we only need to hold 2 bytes but then we'd need a separate temporary buffer to // decode 3 bytes into and then juggle copying one byte into the provided read buf and the rest // into here, which seems like a lot of complexity for 1 extra byte of storage. - decoded_buffer: [u8; 3], + decoded_buffer: [u8; DECODED_CHUNK_SIZE], // index of start of decoded data decoded_offset: usize, // length of decoded data decoded_len: usize, // used to provide accurate offsets in errors total_b64_decoded: usize, + // offset of previously seen padding, if any + padding_offset: Option<usize>, } impl<'e, E: Engine, R: io::Read> fmt::Debug for DecoderReader<'e, E, R> { diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -64,6 +66,7 @@ impl<'e, E: Engine, R: io::Read> fmt::Debug for DecoderReader<'e, E, R> { .field("decoded_offset", &self.decoded_offset) .field("decoded_len", &self.decoded_len) .field("total_b64_decoded", &self.total_b64_decoded) + .field("padding_offset", &self.padding_offset) .finish() } } diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -81,6 +84,7 @@ impl<'e, E: Engine, R: io::Read> DecoderReader<'e, E, R> { decoded_offset: 0, decoded_len: 0, total_b64_decoded: 0, + padding_offset: None, } } diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -127,20 +131,28 @@ impl<'e, E: Engine, R: io::Read> DecoderReader<'e, E, R> { /// caller's responsibility to choose the number of b64 bytes to decode correctly. /// /// Returns a Result with the number of decoded bytes written to `buf`. - fn decode_to_buf(&mut self, num_bytes: usize, buf: &mut [u8]) -> io::Result<usize> { - debug_assert!(self.b64_len >= num_bytes); + fn decode_to_buf(&mut self, b64_len_to_decode: usize, buf: &mut [u8]) -> io::Result<usize> { + debug_assert!(self.b64_len >= b64_len_to_decode); debug_assert!(self.b64_offset + self.b64_len <= BUF_SIZE); debug_assert!(!buf.is_empty()); - let decoded = self + let b64_to_decode = &self.b64_buffer[self.b64_offset..self.b64_offset + b64_len_to_decode]; + let decode_metadata = self .engine .internal_decode( - &self.b64_buffer[self.b64_offset..self.b64_offset + num_bytes], + b64_to_decode, buf, - self.engine.internal_decoded_len_estimate(num_bytes), + self.engine.internal_decoded_len_estimate(b64_len_to_decode), ) .map_err(|e| match e { DecodeError::InvalidByte(offset, byte) => { + // This can be incorrect, but not in a way that probably matters to anyone: + // if there was padding handled in a previous decode, and we are now getting + // InvalidByte due to more padding, we should arguably report InvalidByte with + // PAD_BYTE at the original padding position (`self.padding_offset`), but we + // don't have a good way to tie those two cases together, so instead we + // just report the invalid byte as if the previous padding, and its possibly + // related downgrade to a now invalid byte, didn't happen. DecodeError::InvalidByte(self.total_b64_decoded + offset, byte) } DecodeError::InvalidLength => DecodeError::InvalidLength, diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -151,13 +163,27 @@ impl<'e, E: Engine, R: io::Read> DecoderReader<'e, E, R> { }) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; - self.total_b64_decoded += num_bytes; - self.b64_offset += num_bytes; - self.b64_len -= num_bytes; + if let Some(offset) = self.padding_offset { + // we've already seen padding + if decode_metadata.decoded_len > 0 { + // we read more after already finding padding; report error at first padding byte + return Err(io::Error::new( + io::ErrorKind::InvalidData, + DecodeError::InvalidByte(offset, PAD_BYTE), + )); + } + } + + self.padding_offset = self.padding_offset.or(decode_metadata + .padding_offset + .map(|offset| self.total_b64_decoded + offset)); + self.total_b64_decoded += b64_len_to_decode; + self.b64_offset += b64_len_to_decode; + self.b64_len -= b64_len_to_decode; debug_assert!(self.b64_offset + self.b64_len <= BUF_SIZE); - Ok(decoded) + Ok(decode_metadata.decoded_len) } /// Unwraps this `DecoderReader`, returning the base reader which it reads base64 encoded diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -205,9 +231,9 @@ impl<'e, E: Engine, R: io::Read> io::Read for DecoderReader<'e, E, R> { self.decoded_offset < DECODED_CHUNK_SIZE }); - // We shouldn't ever decode into here when we can't immediately write at least one byte into - // the provided buf, so the effective length should only be 3 momentarily between when we - // decode and when we copy into the target buffer. + // We shouldn't ever decode into decoded_buffer when we can't immediately write at least one + // byte into the provided buf, so the effective length should only be 3 momentarily between + // when we decode and when we copy into the target buffer. debug_assert!(self.decoded_len < DECODED_CHUNK_SIZE); debug_assert!(self.decoded_len + self.decoded_offset <= DECODED_CHUNK_SIZE); diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -217,20 +243,15 @@ impl<'e, E: Engine, R: io::Read> io::Read for DecoderReader<'e, E, R> { } else { let mut at_eof = false; while self.b64_len < BASE64_CHUNK_SIZE { - // Work around lack of copy_within, which is only present in 1.37 // Copy any bytes we have to the start of the buffer. - // We know we have < 1 chunk, so we can use a tiny tmp buffer. - let mut memmove_buf = [0_u8; BASE64_CHUNK_SIZE]; - memmove_buf[..self.b64_len].copy_from_slice( - &self.b64_buffer[self.b64_offset..self.b64_offset + self.b64_len], - ); - self.b64_buffer[0..self.b64_len].copy_from_slice(&memmove_buf[..self.b64_len]); + self.b64_buffer + .copy_within(self.b64_offset..self.b64_offset + self.b64_len, 0); self.b64_offset = 0; // then fill in more data let read = self.read_from_delegate()?; if read == 0 { - // we never pass in an empty buf, so 0 => we've hit EOF + // we never read into an empty buf, so 0 => we've hit EOF at_eof = true; break; }
diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -8,13 +8,16 @@ use rand::{ }; use rstest::rstest; use rstest_reuse::{apply, template}; -use std::{collections, fmt}; +use std::{collections, fmt, io::Read as _}; use crate::{ alphabet::{Alphabet, STANDARD}, encode::add_padding, encoded_len, - engine::{general_purpose, naive, Config, DecodeEstimate, DecodePaddingMode, Engine}, + engine::{ + general_purpose, naive, Config, DecodeEstimate, DecodeMetadata, DecodePaddingMode, Engine, + }, + read::DecoderReader, tests::{assert_encode_sanity, random_alphabet, random_config}, DecodeError, PAD_BYTE, }; diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -24,9 +27,20 @@ use crate::{ #[rstest(engine_wrapper, case::general_purpose(GeneralPurposeWrapper {}), case::naive(NaiveWrapper {}), +case::decoder_reader(DecoderReaderEngineWrapper {}), )] fn all_engines<E: EngineWrapper>(engine_wrapper: E) {} +/// Some decode tests don't make sense for use with `DecoderReader` as they are difficult to +/// reason about or otherwise inapplicable given how DecoderReader slice up its input along +/// chunk boundaries. +#[template] +#[rstest(engine_wrapper, +case::general_purpose(GeneralPurposeWrapper {}), +case::naive(NaiveWrapper {}), +)] +fn all_engines_except_decoder_reader<E: EngineWrapper>(engine_wrapper: E) {} + #[apply(all_engines)] fn rfc_test_vectors_std_alphabet<E: EngineWrapper>(engine_wrapper: E) { let data = vec![ diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -552,7 +566,7 @@ fn decode_invalid_byte_error<E: EngineWrapper>(engine_wrapper: E) { let len_range = distributions::Uniform::new(1, 1_000); - for _ in 0..10_000 { + for _ in 0..100_000 { let alphabet = random_alphabet(&mut rng); let engine = E::random_alphabet(&mut rng, alphabet); diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -576,7 +590,7 @@ fn decode_invalid_byte_error<E: EngineWrapper>(engine_wrapper: E) { let invalid_byte: u8 = loop { let byte: u8 = rng.gen(); - if alphabet.symbols.contains(&byte) { + if alphabet.symbols.contains(&byte) || byte == PAD_BYTE { continue; } else { break byte; diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -600,7 +614,9 @@ fn decode_invalid_byte_error<E: EngineWrapper>(engine_wrapper: E) { /// Any amount of padding anywhere before the final non padding character = invalid byte at first /// pad byte. /// From this, we know padding must extend to the end of the input. -#[apply(all_engines)] +// DecoderReader pseudo-engine detects InvalidLastSymbol instead of InvalidLength because it +// can end a decode on the quad that happens to contain the start of the padding +#[apply(all_engines_except_decoder_reader)] fn decode_padding_before_final_non_padding_char_error_invalid_byte<E: EngineWrapper>( engine_wrapper: E, ) { diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -644,10 +660,13 @@ fn decode_padding_before_final_non_padding_char_error_invalid_byte<E: EngineWrap } } -/// Any amount of padding before final chunk that crosses over into final chunk with 1-4 bytes = -/// invalid byte at first pad byte (except for 1 byte suffix = invalid length). -/// From this we know the padding must start in the final chunk. -#[apply(all_engines)] +/// Any amount of padding before final chunk that crosses over into final chunk with 2-4 bytes = +/// invalid byte at first pad byte. +/// From this and [decode_padding_starts_before_final_chunk_error_invalid_length] we know the +/// padding must start in the final chunk. +// DecoderReader pseudo-engine detects InvalidLastSymbol instead of InvalidLength because it +// can end a decode on the quad that happens to contain the start of the padding +#[apply(all_engines_except_decoder_reader)] fn decode_padding_starts_before_final_chunk_error_invalid_byte<E: EngineWrapper>( engine_wrapper: E, ) { diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -655,8 +674,8 @@ fn decode_padding_starts_before_final_chunk_error_invalid_byte<E: EngineWrapper> // must have at least one prefix quad let prefix_quads_range = distributions::Uniform::from(1..256); - // including 1 just to make sure that it really does produce invalid length - let suffix_pad_len_range = distributions::Uniform::from(1..=4); + // excluding 1 since we don't care about invalid length in this test + let suffix_pad_len_range = distributions::Uniform::from(2..=4); for mode in all_pad_modes() { // we don't encode so we don't care about encode padding let engine = E::standard_with_pad_mode(true, mode); diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -674,14 +693,48 @@ fn decode_padding_starts_before_final_chunk_error_invalid_byte<E: EngineWrapper> let padding_start = encoded.len() - padding_len; encoded[padding_start..].fill(PAD_BYTE); - if suffix_len == 1 { - assert_eq!(Err(DecodeError::InvalidLength), engine.decode(&encoded),); - } else { - assert_eq!( - Err(DecodeError::InvalidByte(padding_start, PAD_BYTE)), - engine.decode(&encoded), - ); - } + assert_eq!( + Err(DecodeError::InvalidByte(padding_start, PAD_BYTE)), + engine.decode(&encoded), + "suffix_len: {}, padding_len: {}, b64: {}", + suffix_len, + padding_len, + std::str::from_utf8(&encoded).unwrap() + ); + } + } +} + +/// Any amount of padding before final chunk that crosses over into final chunk with 1 byte = +/// invalid length. +/// From this we know the padding must start in the final chunk. +// DecoderReader pseudo-engine detects InvalidByte instead of InvalidLength because it starts by +// decoding only the available complete quads +#[apply(all_engines_except_decoder_reader)] +fn decode_padding_starts_before_final_chunk_error_invalid_length<E: EngineWrapper>( + engine_wrapper: E, +) { + let mut rng = seeded_rng(); + + // must have at least one prefix quad + let prefix_quads_range = distributions::Uniform::from(1..256); + for mode in all_pad_modes() { + // we don't encode so we don't care about encode padding + let engine = E::standard_with_pad_mode(true, mode); + for _ in 0..100_000 { + let mut encoded = "ABCD" + .repeat(prefix_quads_range.sample(&mut rng)) + .into_bytes(); + encoded.resize(encoded.len() + 1, PAD_BYTE); + + // amount of padding must be long enough to extend back from suffix into previous + // quads + let padding_len = rng.gen_range(1 + 1..encoded.len()); + // no non-padding after padding in this test, so padding goes to the end + let padding_start = encoded.len() - padding_len; + encoded[padding_start..].fill(PAD_BYTE); + + assert_eq!(Err(DecodeError::InvalidLength), engine.decode(&encoded),); } } } diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -790,7 +843,9 @@ fn decode_malleability_test_case_2_byte_suffix_no_padding<E: EngineWrapper>(engi } // https://eprint.iacr.org/2022/361.pdf table 2, test 7 -#[apply(all_engines)] +// DecoderReader pseudo-engine gets InvalidByte at 8 (extra padding) since it decodes the first +// two complete quads correctly. +#[apply(all_engines_except_decoder_reader)] fn decode_malleability_test_case_2_byte_suffix_too_much_padding<E: EngineWrapper>( engine_wrapper: E, ) { diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -864,7 +919,11 @@ fn decode_pad_mode_indifferent_padding_accepts_anything<E: EngineWrapper>(engine } //this is a MAY in the rfc: https://tools.ietf.org/html/rfc4648#section-3.3 -#[apply(all_engines)] +// DecoderReader pseudo-engine finds the first padding, but doesn't report it as an error, +// because in the next decode it finds more padding, which is reported as InvalidByte, just +// with an offset at its position in the second decode, rather than being linked to the start +// of the padding that was first seen in the previous decode. +#[apply(all_engines_except_decoder_reader)] fn decode_pad_byte_in_penultimate_quad_error<E: EngineWrapper>(engine_wrapper: E) { for mode in all_pad_modes() { // we don't encode so we don't care about encode padding diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -898,7 +957,7 @@ fn decode_pad_byte_in_penultimate_quad_error<E: EngineWrapper>(engine_wrapper: E num_prefix_quads * 4 + num_valid_bytes_penultimate_quad, b'=', ), - engine.decode(&s).unwrap_err() + engine.decode(&s).unwrap_err(), ); } } diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -958,7 +1017,9 @@ fn decode_absurd_pad_error<E: EngineWrapper>(engine_wrapper: E) { } } -#[apply(all_engines)] +// DecoderReader pseudo-engine detects InvalidByte instead of InvalidLength because it starts by +// decoding only the available complete quads +#[apply(all_engines_except_decoder_reader)] fn decode_too_much_padding_returns_error<E: EngineWrapper>(engine_wrapper: E) { for mode in all_pad_modes() { // we don't encode so we don't care about encode padding diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -984,7 +1045,9 @@ fn decode_too_much_padding_returns_error<E: EngineWrapper>(engine_wrapper: E) { } } -#[apply(all_engines)] +// DecoderReader pseudo-engine detects InvalidByte instead of InvalidLength because it starts by +// decoding only the available complete quads +#[apply(all_engines_except_decoder_reader)] fn decode_padding_followed_by_non_padding_returns_error<E: EngineWrapper>(engine_wrapper: E) { for mode in all_pad_modes() { // we don't encode so we don't care about encode padding diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -1082,27 +1145,43 @@ fn decode_too_few_symbols_in_final_quad_error<E: EngineWrapper>(engine_wrapper: } } -#[apply(all_engines)] +// DecoderReader pseudo-engine can't handle DecodePaddingMode::RequireNone since it will decode +// a complete quad with padding in it before encountering the stray byte that makes it an invalid +// length +#[apply(all_engines_except_decoder_reader)] fn decode_invalid_trailing_bytes<E: EngineWrapper>(engine_wrapper: E) { for mode in all_pad_modes() { - // we don't encode so we don't care about encode padding - let engine = E::standard_with_pad_mode(true, mode); + do_invalid_trailing_byte(E::standard_with_pad_mode(true, mode), mode); + } +} - for num_prefix_quads in 0..256 { - let mut s: String = "ABCD".repeat(num_prefix_quads); - s.push_str("Cg==\n"); +#[apply(all_engines)] +fn decode_invalid_trailing_bytes_all_modes<E: EngineWrapper>(engine_wrapper: E) { + // excluding no padding mode because the DecoderWrapper pseudo-engine will fail with + // InvalidPadding because it will decode the last complete quad with padding first + for mode in pad_modes_allowing_padding() { + do_invalid_trailing_byte(E::standard_with_pad_mode(true, mode), mode); + } +} - // The case of trailing newlines is common enough to warrant a test for a good error - // message. - assert_eq!( - Err(DecodeError::InvalidByte(num_prefix_quads * 4 + 4, b'\n')), - engine.decode(&s) - ); +#[apply(all_engines)] +fn decode_invalid_trailing_padding_as_invalid_length<E: EngineWrapper>(engine_wrapper: E) { + // excluding no padding mode because the DecoderWrapper pseudo-engine will fail with + // InvalidPadding because it will decode the last complete quad with padding first + for mode in pad_modes_allowing_padding() { + do_invalid_trailing_padding_as_invalid_length(E::standard_with_pad_mode(true, mode), mode); + } +} - // extra padding, however, is still InvalidLength - let s = s.replace('\n', "="); - assert_eq!(Err(DecodeError::InvalidLength), engine.decode(s)); - } +// DecoderReader pseudo-engine can't handle DecodePaddingMode::RequireNone since it will decode +// a complete quad with padding in it before encountering the stray byte that makes it an invalid +// length +#[apply(all_engines_except_decoder_reader)] +fn decode_invalid_trailing_padding_as_invalid_length_all_modes<E: EngineWrapper>( + engine_wrapper: E, +) { + for mode in all_pad_modes() { + do_invalid_trailing_padding_as_invalid_length(E::standard_with_pad_mode(true, mode), mode); } } diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -1180,6 +1259,53 @@ fn decode_into_slice_fits_in_precisely_sized_slice<E: EngineWrapper>(engine_wrap } } +#[apply(all_engines)] +fn inner_decode_reports_padding_position<E: EngineWrapper>(engine_wrapper: E) { + let mut b64 = String::new(); + let mut decoded = Vec::new(); + let engine = E::standard(); + + for pad_position in 1..10_000 { + b64.clear(); + decoded.clear(); + // plenty of room for original data + decoded.resize(pad_position, 0); + + for _ in 0..pad_position { + b64.push('A'); + } + // finish the quad with padding + for _ in 0..(4 - (pad_position % 4)) { + b64.push('='); + } + + let decode_res = engine.internal_decode( + b64.as_bytes(), + &mut decoded[..], + engine.internal_decoded_len_estimate(b64.len()), + ); + if pad_position % 4 < 2 { + // impossible padding + assert_eq!( + Err(DecodeError::InvalidByte(pad_position, PAD_BYTE)), + decode_res + ); + } else { + let decoded_bytes = pad_position / 4 * 3 + + match pad_position % 4 { + 0 => 0, + 2 => 1, + 3 => 2, + _ => unreachable!(), + }; + assert_eq!( + Ok(DecodeMetadata::new(decoded_bytes, Some(pad_position))), + decode_res + ); + } + } +} + #[apply(all_engines)] fn decode_length_estimate_delta<E: EngineWrapper>(engine_wrapper: E) { for engine in [E::standard(), E::standard_unpadded()] { diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -1229,6 +1355,38 @@ fn estimate_via_u128_inflation<E: EngineWrapper>(engine_wrapper: E) { }) } +fn do_invalid_trailing_byte(engine: impl Engine, mode: DecodePaddingMode) { + for num_prefix_quads in 0..256 { + let mut s: String = "ABCD".repeat(num_prefix_quads); + s.push_str("Cg==\n"); + + // The case of trailing newlines is common enough to warrant a test for a good error + // message. + assert_eq!( + Err(DecodeError::InvalidByte(num_prefix_quads * 4 + 4, b'\n')), + engine.decode(&s), + "mode: {:?}, input: {}", + mode, + s + ); + } +} + +fn do_invalid_trailing_padding_as_invalid_length(engine: impl Engine, mode: DecodePaddingMode) { + for num_prefix_quads in 0..256 { + let mut s: String = "ABCD".repeat(num_prefix_quads); + s.push_str("Cg==="); + + assert_eq!( + Err(DecodeError::InvalidLength), + engine.decode(&s), + "mode: {:?}, input: {}", + mode, + s + ); + } +} + /// Returns a tuple of the original data length, the encoded data length (just data), and the length including padding. /// /// Vecs provided should be empty. diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -1430,6 +1588,103 @@ impl EngineWrapper for NaiveWrapper { } } +/// A pseudo-Engine that routes all decoding through [DecoderReader] +struct DecoderReaderEngine<E: Engine> { + engine: E, +} + +impl<E: Engine> From<E> for DecoderReaderEngine<E> { + fn from(value: E) -> Self { + Self { engine: value } + } +} + +impl<E: Engine> Engine for DecoderReaderEngine<E> { + type Config = E::Config; + type DecodeEstimate = E::DecodeEstimate; + + fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize { + self.engine.internal_encode(input, output) + } + + fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate { + self.engine.internal_decoded_len_estimate(input_len) + } + + fn internal_decode( + &self, + input: &[u8], + output: &mut [u8], + decode_estimate: Self::DecodeEstimate, + ) -> Result<DecodeMetadata, DecodeError> { + let mut reader = DecoderReader::new(input, &self.engine); + let mut buf = vec![0; input.len()]; + // to avoid effects like not detecting invalid length due to progressively growing + // the output buffer in read_to_end etc, read into a big enough buffer in one go + // to make behavior more consistent with normal engines + let _ = reader + .read(&mut buf) + .and_then(|len| { + buf.truncate(len); + // make sure we got everything + reader.read_to_end(&mut buf) + }) + .map_err(|io_error| { + *io_error + .into_inner() + .and_then(|inner| inner.downcast::<DecodeError>().ok()) + .unwrap() + })?; + output[..buf.len()].copy_from_slice(&buf); + Ok(DecodeMetadata::new( + buf.len(), + input + .iter() + .enumerate() + .filter(|(_offset, byte)| **byte == PAD_BYTE) + .map(|(offset, _byte)| offset) + .next(), + )) + } + + fn config(&self) -> &Self::Config { + self.engine.config() + } +} + +struct DecoderReaderEngineWrapper {} + +impl EngineWrapper for DecoderReaderEngineWrapper { + type Engine = DecoderReaderEngine<general_purpose::GeneralPurpose>; + + fn standard() -> Self::Engine { + GeneralPurposeWrapper::standard().into() + } + + fn standard_unpadded() -> Self::Engine { + GeneralPurposeWrapper::standard_unpadded().into() + } + + fn standard_with_pad_mode( + encode_pad: bool, + decode_pad_mode: DecodePaddingMode, + ) -> Self::Engine { + GeneralPurposeWrapper::standard_with_pad_mode(encode_pad, decode_pad_mode).into() + } + + fn standard_allow_trailing_bits() -> Self::Engine { + GeneralPurposeWrapper::standard_allow_trailing_bits().into() + } + + fn random<R: rand::Rng>(rng: &mut R) -> Self::Engine { + GeneralPurposeWrapper::random(rng).into() + } + + fn random_alphabet<R: rand::Rng>(rng: &mut R, alphabet: &Alphabet) -> Self::Engine { + GeneralPurposeWrapper::random_alphabet(rng, alphabet).into() + } +} + fn seeded_rng() -> impl rand::Rng { rngs::SmallRng::from_entropy() } diff --git a/src/engine/tests.rs b/src/engine/tests.rs --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -1442,6 +1697,13 @@ fn all_pad_modes() -> Vec<DecodePaddingMode> { ] } +fn pad_modes_allowing_padding() -> Vec<DecodePaddingMode> { + vec![ + DecodePaddingMode::Indifferent, + DecodePaddingMode::RequireCanonical, + ] +} + fn assert_all_suffixes_ok<E: Engine>(engine: E, suffixes: Vec<&str>) { for num_prefix_quads in 0..256 { for &suffix in suffixes.iter() { diff --git a/src/read/decoder_tests.rs b/src/read/decoder_tests.rs --- a/src/read/decoder_tests.rs +++ b/src/read/decoder_tests.rs @@ -8,9 +8,10 @@ use rand::{Rng as _, RngCore as _}; use super::decoder::{DecoderReader, BUF_SIZE}; use crate::{ + alphabet, engine::{general_purpose::STANDARD, Engine, GeneralPurpose}, tests::{random_alphabet, random_config, random_engine}, - DecodeError, + DecodeError, PAD_BYTE, }; #[test] diff --git a/src/read/decoder_tests.rs b/src/read/decoder_tests.rs --- a/src/read/decoder_tests.rs +++ b/src/read/decoder_tests.rs @@ -247,19 +248,21 @@ fn reports_invalid_byte_correctly() { let mut rng = rand::thread_rng(); let mut bytes = Vec::new(); let mut b64 = String::new(); - let mut decoded = Vec::new(); + let mut stream_decoded = Vec::new(); + let mut bulk_decoded = Vec::new(); for _ in 0..10_000 { bytes.clear(); b64.clear(); - decoded.clear(); + stream_decoded.clear(); + bulk_decoded.clear(); let size = rng.gen_range(1..(10 * BUF_SIZE)); bytes.extend(iter::repeat(0).take(size)); rng.fill_bytes(&mut bytes[..size]); assert_eq!(size, bytes.len()); - let engine = random_engine(&mut rng); + let engine = GeneralPurpose::new(&alphabet::STANDARD, random_config(&mut rng)); engine.encode_string(&bytes[..], &mut b64); // replace one byte, somewhere, with '*', which is invalid diff --git a/src/read/decoder_tests.rs b/src/read/decoder_tests.rs --- a/src/read/decoder_tests.rs +++ b/src/read/decoder_tests.rs @@ -270,9 +273,8 @@ fn reports_invalid_byte_correctly() { let mut wrapped_reader = io::Cursor::new(b64_bytes.clone()); let mut decoder = DecoderReader::new(&mut wrapped_reader, &engine); - // some gymnastics to avoid double-moving the io::Error, which is not Copy let read_decode_err = decoder - .read_to_end(&mut decoded) + .read_to_end(&mut stream_decoded) .map_err(|e| { let kind = e.kind(); let inner = e diff --git a/src/read/decoder_tests.rs b/src/read/decoder_tests.rs --- a/src/read/decoder_tests.rs +++ b/src/read/decoder_tests.rs @@ -283,8 +285,7 @@ fn reports_invalid_byte_correctly() { .err() .and_then(|o| o); - let mut bulk_buf = Vec::new(); - let bulk_decode_err = engine.decode_vec(&b64_bytes[..], &mut bulk_buf).err(); + let bulk_decode_err = engine.decode_vec(&b64_bytes[..], &mut bulk_decoded).err(); // it's tricky to predict where the invalid data's offset will be since if it's in the last // chunk it will be reported at the first padding location because it's treated as invalid diff --git a/src/read/decoder_tests.rs b/src/read/decoder_tests.rs --- a/src/read/decoder_tests.rs +++ b/src/read/decoder_tests.rs @@ -296,6 +297,134 @@ fn reports_invalid_byte_correctly() { } } +#[test] +fn internal_padding_error_with_short_read_concatenated_texts_invalid_byte_error() { + let mut rng = rand::thread_rng(); + let mut bytes = Vec::new(); + let mut b64 = String::new(); + let mut reader_decoded = Vec::new(); + let mut bulk_decoded = Vec::new(); + + // encodes with padding, requires that padding be present so we don't get InvalidPadding + // just because padding is there at all + let engine = STANDARD; + + for _ in 0..10_000 { + bytes.clear(); + b64.clear(); + reader_decoded.clear(); + bulk_decoded.clear(); + + // at least 2 bytes so there can be a split point between bytes + let size = rng.gen_range(2..(10 * BUF_SIZE)); + bytes.resize(size, 0); + rng.fill_bytes(&mut bytes[..size]); + + // Concatenate two valid b64s, yielding padding in the middle. + // This avoids scenarios that are challenging to assert on, like random padding location + // that might be InvalidLastSymbol when decoded at certain buffer sizes but InvalidByte + // when done all at once. + let split = loop { + // find a split point that will produce padding on the first part + let s = rng.gen_range(1..size); + if s % 3 != 0 { + // short enough to need padding + break s; + }; + }; + + engine.encode_string(&bytes[..split], &mut b64); + assert!(b64.contains('='), "split: {}, b64: {}", split, b64); + let bad_byte_pos = b64.find('=').unwrap(); + engine.encode_string(&bytes[split..], &mut b64); + let b64_bytes = b64.as_bytes(); + + // short read to make it plausible for padding to happen on a read boundary + let read_len = rng.gen_range(1..10); + let mut wrapped_reader = ShortRead { + max_read_len: read_len, + delegate: io::Cursor::new(&b64_bytes), + }; + + let mut decoder = DecoderReader::new(&mut wrapped_reader, &engine); + + let read_decode_err = decoder + .read_to_end(&mut reader_decoded) + .map_err(|e| { + *e.into_inner() + .and_then(|e| e.downcast::<DecodeError>().ok()) + .unwrap() + }) + .unwrap_err(); + + let bulk_decode_err = engine.decode_vec(b64_bytes, &mut bulk_decoded).unwrap_err(); + + assert_eq!( + bulk_decode_err, + read_decode_err, + "read len: {}, bad byte pos: {}, b64: {}", + read_len, + bad_byte_pos, + std::str::from_utf8(b64_bytes).unwrap() + ); + assert_eq!( + DecodeError::InvalidByte( + split / 3 * 4 + + match split % 3 { + 1 => 2, + 2 => 3, + _ => unreachable!(), + }, + PAD_BYTE + ), + read_decode_err + ); + } +} + +#[test] +fn internal_padding_anywhere_error() { + let mut rng = rand::thread_rng(); + let mut bytes = Vec::new(); + let mut b64 = String::new(); + let mut reader_decoded = Vec::new(); + + // encodes with padding, requires that padding be present so we don't get InvalidPadding + // just because padding is there at all + let engine = STANDARD; + + for _ in 0..10_000 { + bytes.clear(); + b64.clear(); + reader_decoded.clear(); + + bytes.resize(10 * BUF_SIZE, 0); + rng.fill_bytes(&mut bytes[..]); + + // Just shove a padding byte in there somewhere. + // The specific error to expect is challenging to predict precisely because it + // will vary based on the position of the padding in the quad and the read buffer + // length, but SOMETHING should go wrong. + + engine.encode_string(&bytes[..], &mut b64); + let mut b64_bytes = b64.as_bytes().to_vec(); + // put padding somewhere other than the last quad + b64_bytes[rng.gen_range(0..bytes.len() - 4)] = PAD_BYTE; + + // short read to make it plausible for padding to happen on a read boundary + let read_len = rng.gen_range(1..10); + let mut wrapped_reader = ShortRead { + max_read_len: read_len, + delegate: io::Cursor::new(&b64_bytes), + }; + + let mut decoder = DecoderReader::new(&mut wrapped_reader, &engine); + + let result = decoder.read_to_end(&mut reader_decoded); + assert!(result.is_err()); + } +} + fn consume_with_short_reads_and_validate<R: io::Read>( rng: &mut rand::rngs::ThreadRng, expected_bytes: &[u8], diff --git a/src/read/decoder_tests.rs b/src/read/decoder_tests.rs --- a/src/read/decoder_tests.rs +++ b/src/read/decoder_tests.rs @@ -344,3 +473,15 @@ impl<'a, 'b, R: io::Read, N: rand::Rng> io::Read for RandomShortRead<'a, 'b, R, self.delegate.read(&mut buf[..effective_len]) } } + +struct ShortRead<R: io::Read> { + delegate: R, + max_read_len: usize, +} + +impl<R: io::Read> io::Read for ShortRead<R> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + let len = self.max_read_len.max(buf.len()); + self.delegate.read(&mut buf[..len]) + } +}
DecoderReader accepts incorrect input When parts read from underlying reader include valid padding the reader accepts the input even if there’s more data to follow. In this example the reader produces string `AA==AA==AA==` which should result in an error but instead generates three zero bytes. ```rust struct Foo(usize); impl std::io::Read for Foo { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { if self.0 == 0 { return Ok(0); } self.0 -= 1; buf[..4].copy_from_slice(b"AA=="); Ok(4) } } fn main() { use std::io::Read; use base64::engine::general_purpose::STANDARD; let mut decoder = base64::read::DecoderReader::new(Foo(3), &STANDARD); let mut vec = Vec::new(); let res = decoder.read_to_end(&mut vec); print!("{res:?} {vec:?}"); } ```
Good find, thanks for the heads up.
2023-05-21T23:43:53.000Z
0.21
2023-05-25T13:35:34Z
f766bc684779b32a3c6df0ea198a8b8df7c440b8
marshallpierce/rust-base64
152
marshallpierce__rust-base64-152
[ "151" ]
b4fc91325ec985e2a18e83e95a3c08eebd636af4
diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -29,10 +29,10 @@ const DECODED_CHUNK_SIZE: usize = 3; /// assert_eq!(b"asdf", &result[..]); /// /// ``` -pub struct DecoderReader<'a, R: 'a + io::Read> { +pub struct DecoderReader<R: io::Read> { config: Config, /// Where b64 data is read from - r: &'a mut R, + inner: R, // Holds b64 data read from the delegate reader. b64_buffer: [u8; BUF_SIZE], diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -54,7 +54,7 @@ pub struct DecoderReader<'a, R: 'a + io::Read> { total_b64_decoded: usize, } -impl<'a, R: io::Read> fmt::Debug for DecoderReader<'a, R> { +impl<R: io::Read> fmt::Debug for DecoderReader<R> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("DecoderReader") .field("config", &self.config) diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -68,12 +68,12 @@ impl<'a, R: io::Read> fmt::Debug for DecoderReader<'a, R> { } } -impl<'a, R: io::Read> DecoderReader<'a, R> { - /// Create a new decoder that will read from the provided reader `r`. - pub fn new(r: &'a mut R, config: Config) -> Self { +impl<R: io::Read> DecoderReader<R> { + /// Create a new decoder that will read from the provided reader. + pub fn new(reader: R, config: Config) -> Self { DecoderReader { config, - r, + inner: reader, b64_buffer: [0; BUF_SIZE], b64_offset: 0, b64_len: 0, diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -114,7 +114,7 @@ impl<'a, R: io::Read> DecoderReader<'a, R> { debug_assert!(self.b64_offset + self.b64_len < BUF_SIZE); let read = self - .r + .inner .read(&mut self.b64_buffer[self.b64_offset + self.b64_len..])?; self.b64_len += read; diff --git a/src/read/decoder.rs b/src/read/decoder.rs --- a/src/read/decoder.rs +++ b/src/read/decoder.rs @@ -156,9 +156,19 @@ impl<'a, R: io::Read> DecoderReader<'a, R> { Ok(decoded) } + + /// Unwraps this `DecoderReader`, returning the base reader which it reads base64 encoded + /// input from. + /// + /// Because `DecoderReader` performs internal buffering, the state of the inner reader is + /// unspecified. This function is mainly provided because the inner reader type may provide + /// additional functionality beyond the `Read` implementation which may still be useful. + pub fn into_inner(self) -> R { + self.inner + } } -impl<'a, R: Read> Read for DecoderReader<'a, R> { +impl<R: Read> Read for DecoderReader<R> { /// Decode input from the wrapped reader. /// /// Under non-error circumstances, this returns `Ok` with the value being the number of bytes diff --git a/src/write/encoder.rs b/src/write/encoder.rs --- a/src/write/encoder.rs +++ b/src/write/encoder.rs @@ -215,6 +215,25 @@ impl<W: Write> EncoderWriter<W> { debug_assert_eq!(0, self.output_occupied_len); Ok(()) } + + /// Unwraps this `EncoderWriter`, returning the base writer it writes base64 encoded output + /// to. + /// + /// Normally this method should not be needed, since `finish()` returns the inner writer if + /// it completes successfully. That will also ensure all data has been flushed, which the + /// `into_inner()` function does *not* do. + /// + /// Calling this method after `finish()` has completed successfully will panic, since the + /// writer has already been returned. + /// + /// This method may be useful if the writer implements additional APIs beyond the `Write` + /// trait. Note that the inner writer might be in an error state or have an incomplete + /// base64 string written to it. + pub fn into_inner(mut self) -> W { + self.delegate + .take() + .expect("Encoder has already had finish() called") + } } impl<W: Write> Write for EncoderWriter<W> {
diff --git a/src/encode.rs b/src/encode.rs --- a/src/encode.rs +++ b/src/encode.rs @@ -1,6 +1,6 @@ -use crate::{Config, PAD_BYTE}; #[cfg(any(feature = "alloc", feature = "std", test))] use crate::{chunked_encoder, STANDARD}; +use crate::{Config, PAD_BYTE}; #[cfg(any(feature = "alloc", feature = "std", test))] use alloc::{string::String, vec}; use core::convert::TryInto;
Inconsistency between `EncoderWriter` and `DecoderReader` with 0.13 I had wrappers for decoders and encoders they can own their respective reader or writer and saw that 0.13 already changed this for encoders, but not for decoders. I was wondering if this is intentional, or could be changed for >=0.14?
`EncoderWriter` owns its delegate `Write` because as I was adding `EncoderStringWriter` I realized that `Write` is [implemented](https://doc.rust-lang.org/src/std/io/impls.rs.html#52-82) for `&mut Write`. `Read` has the [same thing](https://doc.rust-lang.org/src/std/io/impls.rs.html#15-50) in place, but I didn't think to apply the corresponding improvement in `DecoderReader`. So no, it wasn't intentional -- just an oversight. I don't see any reason to not also put it in place for decoding in the next release.
2021-01-21T17:10:05.000Z
0.13
2021-02-09T14:56:41Z
b4fc91325ec985e2a18e83e95a3c08eebd636af4
BurntSushi/memchr
153
BurntSushi__memchr-153
[ "152" ]
ad08893ecd23a21dc2fdb27cdaf04f64f4834270
diff --git a/benchmarks/engines/rust-memchr/Cargo.lock b/benchmarks/engines/rust-memchr/Cargo.lock --- a/benchmarks/engines/rust-memchr/Cargo.lock +++ b/benchmarks/engines/rust-memchr/Cargo.lock @@ -14,28 +14,28 @@ version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05efc5cfd9110c8416e471df0e96702d58690178e206e61b7173706673c93706" dependencies = [ - "memchr 2.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.7.2", "serde", ] [[package]] name = "main" -version = "2.7.2" +version = "2.7.3" dependencies = [ "anyhow", - "memchr 2.7.2", + "memchr 2.7.3", "shared", ] [[package]] name = "memchr" version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" [[package]] name = "memchr" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" +version = "2.7.3" [[package]] name = "proc-macro2" diff --git a/benchmarks/engines/rust-memchr/Cargo.toml b/benchmarks/engines/rust-memchr/Cargo.toml --- a/benchmarks/engines/rust-memchr/Cargo.toml +++ b/benchmarks/engines/rust-memchr/Cargo.toml @@ -1,7 +1,7 @@ [package] publish = false name = "main" -version = "2.7.2" # should match current 'memchr' version +version = "2.7.3" # should match current 'memchr' version edition = "2021" [workspace] diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -141,8 +141,8 @@ impl One { // The start of the search may not be aligned to `*const usize`, // so we do an unaligned load here. let chunk = start.cast::<usize>().read_unaligned(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(start.add(index)); + if self.has_needle(chunk) { + return generic::fwd_byte_by_byte(start, end, confirm); } // And now we start our search at a guaranteed aligned position. diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -153,33 +153,21 @@ impl One { let mut cur = start.add(USIZE_BYTES - (start.as_usize() & USIZE_ALIGN)); debug_assert!(cur > start); - while end.distance(cur) >= One::LOOP_BYTES { + if len <= One::LOOP_BYTES { + return generic::fwd_byte_by_byte(cur, end, confirm); + } + debug_assert!(end.sub(One::LOOP_BYTES) >= start); + while cur <= end.sub(One::LOOP_BYTES) { debug_assert_eq!(0, cur.as_usize() % USIZE_BYTES); let a = cur.cast::<usize>().read(); let b = cur.add(USIZE_BYTES).cast::<usize>().read(); - if let Some(index) = self.index_of_needle(a) { - return Some(cur.add(index)); - } - if let Some(index) = self.index_of_needle(b) { - return Some(cur.add(USIZE_BYTES + index)); + if self.has_needle(a) || self.has_needle(b) { + break; } cur = cur.add(One::LOOP_BYTES); } - if end.distance(cur) > USIZE_BYTES { - let chunk = cur.cast::<usize>().read(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(cur.add(index)); - } - cur = cur.add(USIZE_BYTES); - } - debug_assert!(cur >= end.sub(USIZE_BYTES)); - cur = end.sub(USIZE_BYTES); - let chunk = cur.cast::<usize>().read_unaligned(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(cur.add(index)); - } - None + generic::fwd_byte_by_byte(cur, end, confirm) } /// Like `rfind`, but accepts and returns raw pointers. diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -221,39 +209,26 @@ impl One { } let chunk = end.sub(USIZE_BYTES).cast::<usize>().read_unaligned(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(end.sub(USIZE_BYTES).add(index)); + if self.has_needle(chunk) { + return generic::rev_byte_by_byte(start, end, confirm); } let mut cur = end.sub(end.as_usize() & USIZE_ALIGN); debug_assert!(start <= cur && cur <= end); - while cur.distance(start) >= One::LOOP_BYTES { + if len <= One::LOOP_BYTES { + return generic::rev_byte_by_byte(start, cur, confirm); + } + while cur >= start.add(One::LOOP_BYTES) { debug_assert_eq!(0, cur.as_usize() % USIZE_BYTES); let a = cur.sub(2 * USIZE_BYTES).cast::<usize>().read(); let b = cur.sub(1 * USIZE_BYTES).cast::<usize>().read(); - if let Some(index) = self.rindex_of_needle(b) { - return Some(cur.sub(1 * USIZE_BYTES).add(index)); - } - if let Some(index) = self.rindex_of_needle(a) { - return Some(cur.sub(2 * USIZE_BYTES).add(index)); + if self.has_needle(a) || self.has_needle(b) { + break; } cur = cur.sub(One::LOOP_BYTES); } - if cur > start.add(USIZE_BYTES) { - let chunk = cur.sub(USIZE_BYTES).cast::<usize>().read(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(cur.sub(USIZE_BYTES).add(index)); - } - cur = cur.sub(USIZE_BYTES); - } - debug_assert!(start.add(USIZE_BYTES) >= cur); - cur = start; - let chunk = cur.cast::<usize>().read_unaligned(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(cur.add(index)); - } - None + generic::rev_byte_by_byte(start, cur, confirm) } /// Counts all occurrences of this byte in the given haystack represented diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -303,13 +278,8 @@ impl One { } #[inline(always)] - fn index_of_needle(&self, chunk: usize) -> Option<usize> { - find_zero_in_chunk(self.v1 ^ chunk) - } - - #[inline(always)] - fn rindex_of_needle(&self, chunk: usize) -> Option<usize> { - rfind_zero_in_chunk(self.v1 ^ chunk) + fn has_needle(&self, chunk: usize) -> bool { + has_zero_byte(self.v1 ^ chunk) } #[inline(always)] diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -481,8 +451,8 @@ impl Two { // The start of the search may not be aligned to `*const usize`, // so we do an unaligned load here. let chunk = start.cast::<usize>().read_unaligned(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(start.add(index)); + if self.has_needle(chunk) { + return generic::fwd_byte_by_byte(start, end, confirm); } // And now we start our search at a guaranteed aligned position. diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -494,22 +464,16 @@ impl Two { start.add(USIZE_BYTES - (start.as_usize() & USIZE_ALIGN)); debug_assert!(cur > start); debug_assert!(end.sub(USIZE_BYTES) >= start); - while cur < end.sub(USIZE_BYTES) { + while cur <= end.sub(USIZE_BYTES) { debug_assert_eq!(0, cur.as_usize() % USIZE_BYTES); let chunk = cur.cast::<usize>().read(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(cur.add(index)); + if self.has_needle(chunk) { + break; } cur = cur.add(USIZE_BYTES); } - debug_assert!(cur >= end.sub(USIZE_BYTES) && cur <= end); - cur = end.sub(USIZE_BYTES); - let chunk = cur.cast::<usize>().read_unaligned(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(cur.add(index)); - } - None + generic::fwd_byte_by_byte(cur, end, confirm) } /// Like `rfind`, but accepts and returns raw pointers. diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -551,28 +515,22 @@ impl Two { } let chunk = end.sub(USIZE_BYTES).cast::<usize>().read_unaligned(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(end.sub(USIZE_BYTES).add(index)); + if self.has_needle(chunk) { + return generic::rev_byte_by_byte(start, end, confirm); } let mut cur = end.sub(end.as_usize() & USIZE_ALIGN); debug_assert!(start <= cur && cur <= end); - while cur > start.add(USIZE_BYTES) { + while cur >= start.add(USIZE_BYTES) { debug_assert_eq!(0, cur.as_usize() % USIZE_BYTES); let chunk = cur.sub(USIZE_BYTES).cast::<usize>().read(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(cur.sub(USIZE_BYTES).add(index)); + if self.has_needle(chunk) { + break; } cur = cur.sub(USIZE_BYTES); } - debug_assert!(cur >= start && start.add(USIZE_BYTES) >= cur); - cur = start; - let chunk = cur.cast::<usize>().read_unaligned(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(cur.add(index)); - } - None + generic::rev_byte_by_byte(start, cur, confirm) } /// Returns an iterator over all occurrences of one of the needle bytes in diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -585,29 +543,8 @@ impl Two { } #[inline(always)] - fn index_of_needle(&self, chunk: usize) -> Option<usize> { - match ( - find_zero_in_chunk(self.v1 ^ chunk), - find_zero_in_chunk(self.v2 ^ chunk), - ) { - (Some(a), Some(b)) => Some(a.min(b)), - (Some(a), None) => Some(a), - (None, Some(b)) => Some(b), - (None, None) => None, - } - } - - #[inline(always)] - fn rindex_of_needle(&self, chunk: usize) -> Option<usize> { - match ( - rfind_zero_in_chunk(self.v1 ^ chunk), - rfind_zero_in_chunk(self.v2 ^ chunk), - ) { - (Some(a), Some(b)) => Some(a.max(b)), - (Some(a), None) => Some(a), - (None, Some(b)) => Some(b), - (None, None) => None, - } + fn has_needle(&self, chunk: usize) -> bool { + has_zero_byte(self.v1 ^ chunk) || has_zero_byte(self.v2 ^ chunk) } #[inline(always)] diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -778,8 +715,8 @@ impl Three { // The start of the search may not be aligned to `*const usize`, // so we do an unaligned load here. let chunk = start.cast::<usize>().read_unaligned(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(start.add(index)); + if self.has_needle(chunk) { + return generic::fwd_byte_by_byte(start, end, confirm); } // And now we start our search at a guaranteed aligned position. diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -791,22 +728,16 @@ impl Three { start.add(USIZE_BYTES - (start.as_usize() & USIZE_ALIGN)); debug_assert!(cur > start); debug_assert!(end.sub(USIZE_BYTES) >= start); - while cur < end.sub(USIZE_BYTES) { + while cur <= end.sub(USIZE_BYTES) { debug_assert_eq!(0, cur.as_usize() % USIZE_BYTES); let chunk = cur.cast::<usize>().read(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(cur.add(index)); + if self.has_needle(chunk) { + break; } cur = cur.add(USIZE_BYTES); } - debug_assert!(cur >= end.sub(USIZE_BYTES) && cur <= end); - cur = end.sub(USIZE_BYTES); - let chunk = cur.cast::<usize>().read_unaligned(); - if let Some(index) = self.index_of_needle(chunk) { - return Some(cur.add(index)); - } - None + generic::fwd_byte_by_byte(cur, end, confirm) } /// Like `rfind`, but accepts and returns raw pointers. diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -848,28 +779,22 @@ impl Three { } let chunk = end.sub(USIZE_BYTES).cast::<usize>().read_unaligned(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(end.sub(USIZE_BYTES).add(index)); + if self.has_needle(chunk) { + return generic::rev_byte_by_byte(start, end, confirm); } let mut cur = end.sub(end.as_usize() & USIZE_ALIGN); debug_assert!(start <= cur && cur <= end); - while cur > start.add(USIZE_BYTES) { + while cur >= start.add(USIZE_BYTES) { debug_assert_eq!(0, cur.as_usize() % USIZE_BYTES); let chunk = cur.sub(USIZE_BYTES).cast::<usize>().read(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(cur.sub(USIZE_BYTES).add(index)); + if self.has_needle(chunk) { + break; } cur = cur.sub(USIZE_BYTES); } - debug_assert!(cur >= start && start.add(USIZE_BYTES) >= cur); - cur = start; - let chunk = cur.cast::<usize>().read_unaligned(); - if let Some(index) = self.rindex_of_needle(chunk) { - return Some(cur.add(index)); - } - None + generic::rev_byte_by_byte(start, cur, confirm) } /// Returns an iterator over all occurrences of one of the needle bytes in diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -882,45 +807,10 @@ impl Three { } #[inline(always)] - fn index_of_needle(&self, chunk: usize) -> Option<usize> { - #[inline(always)] - fn min_index(a: Option<usize>, b: Option<usize>) -> Option<usize> { - match (a, b) { - (Some(a), Some(b)) => Some(a.min(b)), - (Some(a), None) => Some(a), - (None, Some(b)) => Some(b), - (None, None) => None, - } - } - - min_index( - min_index( - find_zero_in_chunk(self.v1 ^ chunk), - find_zero_in_chunk(self.v2 ^ chunk), - ), - find_zero_in_chunk(self.v3 ^ chunk), - ) - } - - #[inline(always)] - fn rindex_of_needle(&self, chunk: usize) -> Option<usize> { - #[inline(always)] - fn max_index(a: Option<usize>, b: Option<usize>) -> Option<usize> { - match (a, b) { - (Some(a), Some(b)) => Some(a.max(b)), - (Some(a), None) => Some(a), - (None, Some(b)) => Some(b), - (None, None) => None, - } - } - - max_index( - max_index( - rfind_zero_in_chunk(self.v1 ^ chunk), - rfind_zero_in_chunk(self.v2 ^ chunk), - ), - rfind_zero_in_chunk(self.v3 ^ chunk), - ) + fn has_needle(&self, chunk: usize) -> bool { + has_zero_byte(self.v1 ^ chunk) + || has_zero_byte(self.v2 ^ chunk) + || has_zero_byte(self.v3 ^ chunk) } #[inline(always)] diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -977,59 +867,21 @@ impl<'a, 'h> DoubleEndedIterator for ThreeIter<'a, 'h> { } } -/// Return the index of the least significant zero byte in `x`. +/// Return `true` if `x` contains any zero byte. /// /// That is, this routine treats `x` as a register of 8-bit lanes and returns -/// the index of the least significant lane that is `0`. +/// true when any of those lanes is `0`. /// -/// Based on "Matters Computational" by J. Arndt. +/// From "Matters Computational" by J. Arndt. #[inline(always)] -fn lowest_zero_byte(x: usize) -> Option<usize> { +fn has_zero_byte(x: usize) -> bool { // "The idea is to subtract one from each of the bytes and then look for // bytes where the borrow propagated all the way to the most significant // bit." const LO: usize = splat(0x01); const HI: usize = splat(0x80); - let y = x.wrapping_sub(LO) & !x & HI; - if y == 0 { - None - } else { - Some(y.trailing_zeros() as usize / 8) - } -} - -/// Return the index of the most significant zero byte in `x`. -/// -/// That is, this routine treats `x` as a register of 8-bit lanes and returns -/// the index of the most significant lane that is `0`. -/// -/// Based on "Hacker's Delight" by Henry S. Warren. -#[inline(always)] -fn highest_zero_byte(x: usize) -> Option<usize> { - const SEVEN_F: usize = splat(0x7F); - - let y = (x & SEVEN_F).wrapping_add(SEVEN_F); - let y = !(y | x | SEVEN_F); - (USIZE_BYTES - 1).checked_sub(y.leading_zeros() as usize / 8) -} - -#[inline(always)] -fn find_zero_in_chunk(x: usize) -> Option<usize> { - if cfg!(target_endian = "little") { - lowest_zero_byte(x) - } else { - highest_zero_byte(x) - } -} - -#[inline(always)] -fn rfind_zero_in_chunk(x: usize) -> Option<usize> { - if cfg!(target_endian = "little") { - highest_zero_byte(x) - } else { - lowest_zero_byte(x) - } + (x.wrapping_sub(LO) & !x & HI) != 0 } /// Repeat the given byte into a word size number. That is, every 8 bits
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -122,13 +122,13 @@ jobs: - name: Show byte order for debugging run: ${{ env.CARGO }} test --verbose $TARGET byte_order -- --nocapture - name: Run tests - run: cargo test --verbose + run: ${{ env.CARGO }} test --verbose - name: Run with only 'alloc' enabled - run: cargo test --verbose --no-default-features --features alloc + run: ${{ env.CARGO }} test --verbose --no-default-features --features alloc - name: Run tests without any features enabled (core-only) - run: cargo test --verbose --no-default-features + run: ${{ env.CARGO }} test --verbose --no-default-features - name: Run tests with miscellaneous features - run: cargo test --verbose --features logging + run: ${{ env.CARGO }} test --verbose --features logging # Setup and run tests on the wasm32-wasi target via wasmtime. wasm: diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -1045,7 +897,6 @@ const fn splat(b: u8) -> usize { #[cfg(test)] mod tests { use super::*; - use std::cfg; define_memchr_quickcheck!(super, try_new); diff --git a/src/arch/all/memchr.rs b/src/arch/all/memchr.rs --- a/src/arch/all/memchr.rs +++ b/src/arch/all/memchr.rs @@ -1143,89 +994,29 @@ mod tests { assert_eq!(4, count); } - /// Generate 500K values. - fn special_values() -> impl Iterator<Item = usize> { - fn all_bytes() -> impl Iterator<Item = u8> { - 0..=0xff - } - - fn some_bytes() -> impl Iterator<Item = u8> { - [0x00, 0x01, 0x02, 0x10, 0x11, 0x8f, 0xff].into_iter() - } - - all_bytes().flat_map(move |first_byte| { - some_bytes().flat_map(move |middle_byte| { - all_bytes().map(move |last_byte| { - splat(middle_byte) & !0xff & !(0xff << (usize::BITS - 8)) - | ((first_byte as usize) << (usize::BITS - 8)) - | (last_byte as usize) - }) - }) - }) - } - - fn lowest_zero_byte_simple(value: usize) -> Option<usize> { - value.to_le_bytes().iter().position(|&b| b == 0) - } - - fn highest_zero_byte_simple(value: usize) -> Option<usize> { - value.to_le_bytes().iter().rposition(|&b| b == 0) - } - - #[test] - fn test_lowest_zero_byte() { - assert_eq!(Some(0), lowest_zero_byte(0x00000000)); - assert_eq!(Some(0), lowest_zero_byte(0x01000000)); - assert_eq!(Some(1), lowest_zero_byte(0x00000001)); - assert_eq!(Some(1), lowest_zero_byte(0x00000010)); - assert_eq!(Some(1), lowest_zero_byte(0x00220010)); - assert_eq!(Some(1), lowest_zero_byte(0xff220010)); - assert_eq!(Some(USIZE_BYTES - 1), lowest_zero_byte(usize::MAX >> 8)); - assert_eq!(Some(USIZE_BYTES - 1), lowest_zero_byte(usize::MAX >> 9)); - assert_eq!(Some(USIZE_BYTES - 2), lowest_zero_byte(usize::MAX >> 16)); - assert_eq!(None, lowest_zero_byte(usize::MAX >> 7)); - assert_eq!(None, lowest_zero_byte(usize::MAX)); - } - + // A test[1] that failed on some big endian targets after a perf + // improvement was merged[2]. + // + // At first it seemed like the test suite somehow missed the regression, + // but in actuality, CI was not running tests with `cross` but instead with + // `cargo` specifically. This is because those steps were using `cargo` + // instead of `${{ env.CARGO }}`. So adding this regression test doesn't + // really help catch that class of failure, but we add it anyway for good + // measure. + // + // [1]: https://github.com/BurntSushi/memchr/issues/152 + // [2]: https://github.com/BurntSushi/memchr/pull/151 #[test] - fn test_highest_zero_byte() { - assert_eq!(Some(USIZE_BYTES - 1), highest_zero_byte(0x00000000)); - assert_eq!(Some(USIZE_BYTES - 1), highest_zero_byte(0x00345678)); - assert_eq!(Some(USIZE_BYTES - 1), highest_zero_byte(usize::MAX >> 8)); - assert_eq!(Some(USIZE_BYTES - 1), highest_zero_byte(usize::MAX >> 9)); - assert_eq!(Some(USIZE_BYTES - 1), highest_zero_byte(usize::MAX >> 9)); - assert_eq!( - Some(USIZE_BYTES - 1), - highest_zero_byte((usize::MAX >> 9) & !0xff) - ); - assert_eq!(None, highest_zero_byte(usize::MAX >> 3)); - } - - #[test] - fn test_lowest_zero_bytes_special_values() { - if cfg!(miri) { - return; - } - - for value in special_values() { - assert_eq!( - lowest_zero_byte_simple(value), - lowest_zero_byte(value) - ); - } + fn regression_big_endian1() { + assert_eq!(One::new(b':').find(b"1:23"), Some(1)); } + // Interestingly, I couldn't get `regression_big_endian1` to fail for me + // on the `powerpc64-unknown-linux-gnu` target. But I found another case + // through quickcheck that does. #[test] - fn test_highest_zero_bytes_special_values() { - if cfg!(miri) { - return; - } - - for value in special_values() { - assert_eq!( - highest_zero_byte_simple(value), - highest_zero_byte(value) - ); - } + fn regression_big_endian2() { + let data = [0, 0, 0, 0, 0, 0, 0, 0]; + assert_eq!(One::new(b'\x00').find(&data), Some(0)); } }
`v2.7.3` breaks big endian targets The latest version `2.7.3` apparently broke on all big endian targets. It does not identify the positions correctly anymore. I'll look deeper into what might've caused it.
Hmmm I thought `powerpc64-unknown-linux-gnu` and `s390x-unknown-linux-gnu` were both big endian targets. Did I get that wrong? (Because of that, I perhaps have overvalued confidence in CI passing.) That's indeed the targets that fail for me with 2.7.3: https://github.com/LiveSplit/livesplit-core/actions/runs/9507202428/job/26206138350 I can try to modify my CI further to get actual example values that fail. I'm somewhat guessing your CI doesn't hit the code paths which according to what I see in the PR might be only for short strings. Alright, this fails: ```rust assert_eq!(memchr::memchr(b':', b"1:23").unwrap(), 1); ``` ``` assertion `left == right` failed left: 2 right: 1 ```
2024-06-14T00:06:25.000Z
2.7
2024-06-14T19:09:16Z
ad08893ecd23a21dc2fdb27cdaf04f64f4834270
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5