| 1 |
//! Helper functions for efficient IO. |
| 2 |
|
| 3 |
#[cfg(feature = "mmap")] |
| 4 |
use std::fs::File; |
| 5 |
use std::io; |
| 6 |
|
| 7 |
#[cfg(feature = "mmap")] |
| 8 |
const MINIMUM_MMAP_SIZE: u64 = 16 * 1024; // 16 KiB |
| 9 |
|
| 10 |
pub(crate) fn copy_wide(mut reader: impl io::Read, hasher: &mut crate::Hasher) -> io::Result<u64> { |
| 11 |
let mut buffer = [0; 65536]; |
| 12 |
let mut total = 0; |
| 13 |
loop { |
| 14 |
match reader.read(&mut buffer) { |
| 15 |
Ok(0) => return Ok(total), |
| 16 |
Ok(n) => { |
| 17 |
hasher.update(&buffer[..n]); |
| 18 |
total += n as u64; |
| 19 |
} |
| 20 |
// see test_update_reader_interrupted |
| 21 |
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, |
| 22 |
Err(e) => return Err(e), |
| 23 |
} |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
// Try to `mmap` a file, unless it's short enough that ordinary reads are faster, currently 16 KiB. |
| 28 |
// Return `Ok(None)` if mapping fails or if we don't attempt it. Only return `Err` for unexpected |
| 29 |
// failures that could leave the `File` in a bad state. |
| 30 |
// |
| 31 |
// We seek to (near) end-of-file to get the length, and the prior cursor position is ignored. If |
| 32 |
// mapping fails, we [`rewind`] the file cursor to start-of-file before returning `None`. We don't |
| 33 |
// `rewind` if the mapping succeeds, however, to avoid unnecessary syscalls. In the unlikely event |
| 34 |
// that the caller wants to do ordinary reads in addition to mapped reads, they need to `rewind` |
| 35 |
// explicitly in that case. (This function isn't public, but that comes up in test cases.) |
| 36 |
// |
| 37 |
// [`rewind`]: https://doc.rust-lang.org/std/io/trait.Seek.html#method.rewind |
| 38 |
// |
| 39 |
// SAFETY: Mmaps are fundamentally unsafe, because you can call invariant-checking functions like |
| 40 |
// str::from_utf8 on them and then have them change out from under you. Letting a safe caller get |
| 41 |
// their hands on an mmap, or even a &[u8] that's backed by an mmap, is unsound. However, because |
| 42 |
// this function is crate-private, we can guarantee that all can ever happen in the event of a race |
| 43 |
// condition is that we either hash nonsense bytes or crash with SIGBUS or similar, neither of |
| 44 |
// which should risk memory corruption in a safe caller. |
| 45 |
// |
| 46 |
// PARANOIA: But a data race...is a data race...is a data race...right? Even if we know that no |
| 47 |
// platform in the "real world" is ever going to do anything other than compute the "wrong answer" |
| 48 |
// if we race on this mmap while we hash it, aren't we still supposed to feel bad about doing this? |
| 49 |
// Well, maybe. This is IO, and IO gets special carve-outs in the memory model. Consider a |
| 50 |
// memory-mapped register that returns random 32-bit words. (This is actually realistic if you have |
| 51 |
// a hardware RNG.) It's probably sound to construct a *const i32 pointing to that register and do |
| 52 |
// some raw pointer reads from it. Those reads should be volatile if you don't want the compiler to |
| 53 |
// coalesce them, but either way the compiler isn't allowed to just _go nuts_ and insert |
| 54 |
// should-never-happen branches to wipe your hard drive if two adjacent reads happen to give |
| 55 |
// different values. As far as I'm aware, there's no such thing as a read that's allowed if it's |
| 56 |
// volatile but prohibited if it's not (unlike atomics). As mentioned above, it's not ok to |
| 57 |
// construct a safe &i32 to the register if you're going to leak that reference to unknown callers. |
| 58 |
// But if you "know what you're doing," I don't think *const i32 and &i32 are fundamentally |
| 59 |
// different here. Feedback needed. |
| 60 |
#[cfg(feature = "mmap")] |
| 61 |
pub(crate) fn maybe_mmap_file(file: &mut File) -> io::Result<Option<memmap2::Mmap>> { |
| 62 |
// Seeking is more reliable than `.metadata()` for getting the length. Either is valid for |
| 63 |
// regular files, but block devices sometimes report zero length despite being mappable. See |
| 64 |
// https://github.com/BLAKE3-team/BLAKE3/pull/487. |
| 65 |
use io::Seek; |
| 66 |
// In debug mode only, check that the cursor is at the beginning. If the seek below fails, |
| 67 |
// we'll leave the cursor where it is, and that can be confusing if it isn't at the beginning. |
| 68 |
// (This function isn't public, but this comes up in test cases.) |
| 69 |
if cfg!(debug_assertions) { |
| 70 |
if let Ok(position) = file.stream_position() { |
| 71 |
assert_eq!(position, 0, "initial file offset isn't at the beginning"); |
| 72 |
} |
| 73 |
} |
| 74 |
// Seek to "16 KiB less 1 byte" from end-of-file. For short files, this will generally fail |
| 75 |
// with an invalid argument error and leave the cursor at the beginning. For a regular file of |
| 76 |
// exactly 16383 bytes, it will succeed and return 0, again leaving the cursor at the |
| 77 |
// beginning. For some special/device files like /dev/random, it will also return 0. In all |
| 78 |
// those cases, we can return without doing any extra syscalls to reset the cursor, and let the |
| 79 |
// caller fall back to ordinary reads. |
| 80 |
let seek_offset = MINIMUM_MMAP_SIZE - 1; |
| 81 |
let seek_target = io::SeekFrom::End(-(seek_offset as i64)); |
| 82 |
let Ok(offset_len) = file.seek(seek_target) else { |
| 83 |
return Ok(None); // short or unseekable files |
| 84 |
}; |
| 85 |
if offset_len == 0 { |
| 86 |
return Ok(None); // either exactly 16383 bytes, or e.g. /dev/random |
| 87 |
} |
| 88 |
// It's UB to produce a slice longer than `isize::MAX`. `memmap2` checks that internally, so |
| 89 |
// it's kind of redundant to check it here, but we need to guard the `usize` cast in any case. |
| 90 |
if offset_len <= isize::MAX as u64 - seek_offset { |
| 91 |
// We have a seekable file that's long enough to be worth mapping, but not too long to map |
| 92 |
// (e.g. on a 32-bit system). Try to map it. If this succeeds, we'll assume the caller |
| 93 |
// isn't going to do any ordinary reads, so we don't need to `rewind`. |
| 94 |
let mut mmap_options = memmap2::MmapOptions::new(); |
| 95 |
mmap_options.len((offset_len + seek_offset) as usize); // checked above |
| 96 |
if let Ok(mmap) = unsafe { mmap_options.map(&*file) } { |
| 97 |
return Ok(Some(mmap)); |
| 98 |
} |
| 99 |
} |
| 100 |
// `mmap` failed (or would've failed), so we need to `rewind` and let the caller do ordinary |
| 101 |
// reads. This is the only failure case where we return `Err`, since if it does fail somehow |
| 102 |
// (not clear if that's possible in practice), the file cursor position will be wrong. |
| 103 |
file.rewind()?; |
| 104 |
Ok(None) |
| 105 |
} |
| 106 |
|
| 107 |
#[cfg(all(test, feature = "mmap"))] |
| 108 |
mod test { |
| 109 |
use super::*; |
| 110 |
use std::io; |
| 111 |
use std::io::prelude::*; |
| 112 |
|
| 113 |
#[test] |
| 114 |
fn test_maybe_mmap_small_files() -> io::Result<()> { |
| 115 |
let test_cases = [0, 1, MINIMUM_MMAP_SIZE - 2, MINIMUM_MMAP_SIZE - 1]; |
| 116 |
for len in test_cases { |
| 117 |
dbg!(len); |
| 118 |
// Create a file smaller than 16 KiB. `maybe_mmap_file` should return `Ok(None)`. |
| 119 |
let mut input = vec![0; len as usize]; |
| 120 |
crate::test::paint_test_input(&mut input); |
| 121 |
let mut f = tempfile::NamedTempFile::new()?; |
| 122 |
f.write_all(&input)?; |
| 123 |
f.flush()?; |
| 124 |
// We have a debug assert that the initial file offset is 0. |
| 125 |
f.rewind()?; |
| 126 |
assert!(maybe_mmap_file(f.as_file_mut())?.is_none()); |
| 127 |
// Check that the file cursor remains at start-of-file. |
| 128 |
assert_eq!(f.stream_position()?, 0); |
| 129 |
assert_eq!( |
| 130 |
crate::hash(&input), |
| 131 |
crate::Hasher::new() |
| 132 |
.update_reader(f.as_file_mut())? |
| 133 |
.finalize(), |
| 134 |
); |
| 135 |
} |
| 136 |
Ok(()) |
| 137 |
} |
| 138 |
|
| 139 |
#[test] |
| 140 |
fn test_maybe_mmap_mappable_files() -> io::Result<()> { |
| 141 |
let test_cases = [MINIMUM_MMAP_SIZE, MINIMUM_MMAP_SIZE + 1]; |
| 142 |
for len in test_cases { |
| 143 |
dbg!(len); |
| 144 |
// Create a file that's 16 KiB or larger. `maybe_mmap_file` should return `Ok(Some(_))`. |
| 145 |
let mut input = vec![0; len as usize]; |
| 146 |
crate::test::paint_test_input(&mut input); |
| 147 |
let mut f = tempfile::NamedTempFile::new()?; |
| 148 |
f.write_all(&input)?; |
| 149 |
f.flush()?; |
| 150 |
// We have a debug assert that the initial file offset is 0. |
| 151 |
f.rewind()?; |
| 152 |
let Ok(Some(mmap)) = maybe_mmap_file(f.as_file_mut()) else { |
| 153 |
panic!("mmap failed"); |
| 154 |
}; |
| 155 |
// `maybe_mmap_file` doesn't `rewind` the file in this case, so we need to do that |
| 156 |
// ourselves. |
| 157 |
assert_ne!(f.stream_position()?, 0); |
| 158 |
f.rewind()?; |
| 159 |
assert_eq!(mmap[..], input[..]); |
| 160 |
assert_eq!(crate::hash(&input), crate::hash(&mmap)); |
| 161 |
assert_eq!( |
| 162 |
crate::hash(&input), |
| 163 |
crate::Hasher::new() |
| 164 |
.update_reader(f.as_file_mut())? |
| 165 |
.finalize(), |
| 166 |
); |
| 167 |
} |
| 168 |
Ok(()) |
| 169 |
} |
| 170 |
|
| 171 |
#[test] |
| 172 |
fn test_maybe_mmap_current_exe() -> io::Result<()> { |
| 173 |
// The current executable should always be a regular file larger than 16 KiB, so mmap |
| 174 |
// should ~always succeed. (A filesystem might not support mmap at all, but we don't test |
| 175 |
// any of those in CI.) |
| 176 |
let mut exe_file = File::open(std::env::current_exe()?)?; |
| 177 |
assert!(exe_file.metadata()?.len() > MINIMUM_MMAP_SIZE); |
| 178 |
let mmap = maybe_mmap_file(&mut exe_file)?.expect("maybe_mmap_file should return Some"); |
| 179 |
// Mainly we're testing that we got `Some` above, but go ahead and read the mmap just to |
| 180 |
// make sure it doesn't bus fault or anything like that. `maybe_mmap_file` doesn't `rewind` |
| 181 |
// the file in this case, so we need to do that ourselves. |
| 182 |
exe_file.rewind()?; |
| 183 |
assert_eq!( |
| 184 |
crate::hash(&mmap), |
| 185 |
crate::Hasher::new().update_reader(&exe_file)?.finalize(), |
| 186 |
); |
| 187 |
Ok(()) |
| 188 |
} |
| 189 |
|
| 190 |
#[cfg(target_os = "linux")] |
| 191 |
#[test] |
| 192 |
fn test_unmappable_linux() -> io::Result<()> { |
| 193 |
// I'm not aware of any similarly unmappable paths on macOS or Windows, so this test is |
| 194 |
// Linux-only for now. |
| 195 |
let unmappable_path = "/sys/kernel/btf/vmlinux"; |
| 196 |
let mut unmappable_file = File::open(unmappable_path)?; |
| 197 |
// The file is large enough to attempt mmapping. |
| 198 |
assert!(unmappable_file.metadata()?.len() > MINIMUM_MMAP_SIZE); |
| 199 |
// We're allowed to read the file. |
| 200 |
assert_eq!(unmappable_file.read(&mut [0])?, 1); |
| 201 |
// But mmapping the file fails. (We have a debug assert that requires `rewind` here.) |
| 202 |
unmappable_file.rewind()?; |
| 203 |
unsafe { memmap2::Mmap::map(&unmappable_file) }.unwrap_err(); |
| 204 |
// `maybe_mmap_file` swallows that error and returns `None`. |
| 205 |
assert!(maybe_mmap_file(&mut unmappable_file)?.is_none()); |
| 206 |
Ok(()) |
| 207 |
} |
| 208 |
} |