Skip to content

Commit 0db5406

Browse files
committed
Lock mmapped files to at least get some safety out of it
1 parent cb4e806 commit 0db5406

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

compiler/rustc_data_structures/src/memmap.rs

+19-8
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,19 @@ use std::io;
33
use std::ops::{Deref, DerefMut};
44
use std::path::Path;
55

6+
use crate::flock::Lock;
7+
68
/// A trivial wrapper for [`memmap2::Mmap`] (or `Vec<u8>` on WASM).
79
#[cfg(not(any(miri, target_arch = "wasm32")))]
8-
pub struct Mmap(memmap2::Mmap);
10+
pub struct Mmap {
11+
map: memmap2::Mmap,
12+
_lock: Option<Lock>,
13+
}
914

1015
#[cfg(any(miri, target_arch = "wasm32"))]
11-
pub struct Mmap(Vec<u8>);
16+
pub struct Mmap {
17+
map: Vec<u8>,
18+
}
1219

1320
#[cfg(not(any(miri, target_arch = "wasm32")))]
1421
impl Mmap {
@@ -19,15 +26,19 @@ impl Mmap {
1926
/// However in practice most callers do not ensure this, so uses of this function are likely unsound.
2027
#[inline]
2128
pub unsafe fn map(path: impl AsRef<Path>) -> io::Result<Self> {
29+
let path = path.as_ref();
2230
let file = File::open(path)?;
31+
let _lock = Some(Lock::new(path, true, false, false)?);
2332
// By default, memmap2 creates shared mappings, implying that we could see updates to the
2433
// file through the mapping. That would violate our precondition; so by requesting a
2534
// map_copy_read_only we do not lose anything.
2635
// This mapping mode also improves our support for filesystems such as cacheless virtiofs.
2736
// For more details see https://github.com/rust-lang/rust/issues/122262
2837
//
2938
// SAFETY: The caller must ensure that this is safe.
30-
unsafe { Ok(Self(memmap2::MmapOptions::new().map_copy_read_only(&file)?)) }
39+
40+
let map = unsafe { memmap2::MmapOptions::new().map_copy_read_only(&file)? };
41+
Ok(Self { _lock, map })
3142
}
3243
}
3344

@@ -44,13 +55,13 @@ impl Deref for Mmap {
4455

4556
#[inline]
4657
fn deref(&self) -> &[u8] {
47-
&self.0
58+
&self.map
4859
}
4960
}
5061

5162
impl AsRef<[u8]> for Mmap {
5263
fn as_ref(&self) -> &[u8] {
53-
&self.0
64+
&self.map
5465
}
5566
}
5667

@@ -75,8 +86,8 @@ impl MmapMut {
7586

7687
#[inline]
7788
pub fn make_read_only(self) -> std::io::Result<Mmap> {
78-
let mmap = self.0.make_read_only()?;
79-
Ok(Mmap(mmap))
89+
let map = self.0.make_read_only()?;
90+
Ok(Mmap { map, _lock: None })
8091
}
8192
}
8293

@@ -95,7 +106,7 @@ impl MmapMut {
95106

96107
#[inline]
97108
pub fn make_read_only(self) -> std::io::Result<Mmap> {
98-
Ok(Mmap(self.0))
109+
Ok(Mmap { map: self.0 })
99110
}
100111
}
101112

0 commit comments

Comments
 (0)