wasmtime/runtime/vm/
mmap.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Low-level abstraction for allocating and managing zero-filled pages
//! of memory.

use super::HostAlignedByteCount;
use crate::prelude::*;
use crate::runtime::vm::sys::{mmap, vm::MemoryImageSource};
use alloc::sync::Arc;
use core::ops::Range;
use core::ptr::NonNull;
#[cfg(feature = "std")]
use std::fs::File;

/// A marker type for an [`Mmap`] where both the start address and length are a
/// multiple of the host page size.
///
/// For more information, see the documentation on [`Mmap`].
#[derive(Clone, Debug)]
pub struct AlignedLength {}

/// A type of [`Mmap`] where the start address is host page-aligned, but the
/// length is possibly not a multiple of the host page size.
///
/// For more information, see the documentation on [`Mmap`].
#[derive(Clone, Debug)]
pub struct UnalignedLength {
    #[cfg(feature = "std")]
    file: Option<Arc<File>>,
}

/// A platform-independent abstraction over memory-mapped data.
///
/// The type parameter can be one of:
///
/// * [`AlignedLength`]: Both the start address and length are page-aligned
/// (i.e. a multiple of the host page size). This is always the result of an
/// mmap backed by anonymous memory.
///
/// * [`UnalignedLength`]: The start address is host page-aligned, but the
/// length is not necessarily page-aligned. This is usually backed by a file,
/// but can also be backed by anonymous memory.
///
/// ## Notes
///
/// If the length of a file is not a multiple of the host page size, [POSIX does
/// not specify any semantics][posix-mmap] for the rest of the last page. Linux
/// [does say][linux-mmap] that the rest of the page is reserved and zeroed out,
/// but for portability it's best to not assume anything about the rest of
/// memory. `UnalignedLength` achieves a type-level distinction between an mmap
/// that is backed purely by memory, and one that is possibly backed by a file.
///
/// Currently, the OS-specific `mmap` implementations in this crate do not make
/// this this distinction -- alignment is managed at this platform-independent
/// layer. It might make sense to add this distinction to the OS-specific
/// implementations in the future.
///
/// [posix-mmap]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/mmap.html
/// [linux-mmap]: https://man7.org/linux/man-pages/man2/mmap.2.html#NOTES
#[derive(Debug)]
pub struct Mmap<T> {
    sys: mmap::Mmap,
    data: T,
}

impl Mmap<AlignedLength> {
    /// Create a new `Mmap` pointing to at least `size` bytes of page-aligned
    /// accessible memory.
    pub fn with_at_least(size: usize) -> Result<Self> {
        let rounded_size = HostAlignedByteCount::new_rounded_up(size)?;
        Self::accessible_reserved(rounded_size, rounded_size)
    }

    /// Create a new `Mmap` pointing to `accessible_size` bytes of page-aligned
    /// accessible memory, within a reserved mapping of `mapping_size` bytes.
    /// `accessible_size` and `mapping_size` must be native page-size multiples.
    ///
    /// # Panics
    ///
    /// This function will panic if `accessible_size` is greater than
    /// `mapping_size`.
    pub fn accessible_reserved(
        accessible_size: HostAlignedByteCount,
        mapping_size: HostAlignedByteCount,
    ) -> Result<Self> {
        assert!(accessible_size <= mapping_size);

        if mapping_size.is_zero() {
            Ok(Mmap {
                sys: mmap::Mmap::new_empty(),
                data: AlignedLength {},
            })
        } else if accessible_size == mapping_size {
            Ok(Mmap {
                sys: mmap::Mmap::new(mapping_size)
                    .context(format!("mmap failed to allocate {mapping_size:#x} bytes"))?,
                data: AlignedLength {},
            })
        } else {
            let result = Mmap {
                sys: mmap::Mmap::reserve(mapping_size)
                    .context(format!("mmap failed to reserve {mapping_size:#x} bytes"))?,
                data: AlignedLength {},
            };
            if !accessible_size.is_zero() {
                // SAFETY: result was just created and is not in use.
                unsafe {
                    result
                        .make_accessible(HostAlignedByteCount::ZERO, accessible_size)
                        .context(format!(
                            "mmap failed to allocate {accessible_size:#x} bytes"
                        ))?;
                }
            }
            Ok(result)
        }
    }

    /// Converts this `Mmap` into a `Mmap<UnalignedLength>`.
    ///
    /// `UnalignedLength` really means "_possibly_ unaligned length", so it can
    /// be freely converted over at the cost of losing the alignment guarantee.
    pub fn into_unaligned(self) -> Mmap<UnalignedLength> {
        Mmap {
            sys: self.sys,
            data: UnalignedLength {
                #[cfg(feature = "std")]
                file: None,
            },
        }
    }

    /// Returns the length of the memory mapping as an aligned byte count.
    pub fn len_aligned(&self) -> HostAlignedByteCount {
        // SAFETY: The type parameter indicates that self.sys.len() is aligned.
        unsafe { HostAlignedByteCount::new_unchecked(self.sys.len()) }
    }

    /// Return a struct representing a page-aligned offset into the mmap.
    ///
    /// Returns an error if `offset > self.len_aligned()`.
    pub fn offset(self: &Arc<Self>, offset: HostAlignedByteCount) -> Result<MmapOffset> {
        if offset > self.len_aligned() {
            bail!(
                "offset {} is not in bounds for mmap: {}",
                offset,
                self.len_aligned()
            );
        }

        Ok(MmapOffset::new(self.clone(), offset))
    }

    /// Return an `MmapOffset` corresponding to zero bytes into the mmap.
    pub fn zero_offset(self: &Arc<Self>) -> MmapOffset {
        MmapOffset::new(self.clone(), HostAlignedByteCount::ZERO)
    }

    /// Make the memory starting at `start` and extending for `len` bytes
    /// accessible. `start` and `len` must be native page-size multiples and
    /// describe a range within `self`'s reserved memory.
    ///
    /// # Safety
    ///
    /// There must not be any other references to the region of memory being
    /// made accessible.
    ///
    /// # Panics
    ///
    /// Panics if `start + len >= self.len()`.
    pub unsafe fn make_accessible(
        &self,
        start: HostAlignedByteCount,
        len: HostAlignedByteCount,
    ) -> Result<()> {
        if len.is_zero() {
            // A zero-sized mprotect (or equivalent) is allowed on some
            // platforms but not others (notably Windows). Treat it as a no-op
            // everywhere.
            return Ok(());
        }

        let end = start
            .checked_add(len)
            .expect("start + len must not overflow");
        assert!(
            end <= self.len_aligned(),
            "start + len ({end}) must be <= mmap region {}",
            self.len_aligned()
        );

        self.sys.make_accessible(start, len)
    }
}

#[cfg(feature = "std")]
impl Mmap<UnalignedLength> {
    /// Creates a new `Mmap` by opening the file located at `path` and mapping
    /// it into memory.
    ///
    /// The memory is mapped in read-only mode for the entire file. If portions
    /// of the file need to be modified then the `region` crate can be use to
    /// alter permissions of each page.
    ///
    /// The memory mapping and the length of the file within the mapping are
    /// returned.
    pub fn from_file(file: Arc<File>) -> Result<Self> {
        let sys = mmap::Mmap::from_file(&file)?;
        Ok(Mmap {
            sys,
            data: UnalignedLength { file: Some(file) },
        })
    }

    /// Returns the underlying file that this mmap is mapping, if present.
    pub fn original_file(&self) -> Option<&Arc<File>> {
        self.data.file.as_ref()
    }
}

impl<T> Mmap<T> {
    /// Return the allocated memory as a slice of u8.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the range of bytes is accessible to the
    /// program and additionally has previously been initialized.
    ///
    /// # Panics
    ///
    /// Panics of the `range` provided is outside of the limits of this mmap.
    #[inline]
    pub unsafe fn slice(&self, range: Range<usize>) -> &[u8] {
        assert!(range.start <= range.end);
        assert!(range.end <= self.len());
        core::slice::from_raw_parts(self.as_ptr().add(range.start), range.end - range.start)
    }

    /// Return the allocated memory as a mutable slice of u8.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the range of bytes is accessible to the
    /// program and additionally has previously been initialized.
    ///
    /// # Panics
    ///
    /// Panics of the `range` provided is outside of the limits of this mmap.
    pub unsafe fn slice_mut(&mut self, range: Range<usize>) -> &mut [u8] {
        assert!(range.start <= range.end);
        assert!(range.end <= self.len());
        core::slice::from_raw_parts_mut(self.as_mut_ptr().add(range.start), range.end - range.start)
    }

    /// Return the allocated memory as a pointer to u8.
    #[inline]
    pub fn as_ptr(&self) -> *const u8 {
        self.sys.as_send_sync_ptr().as_ptr() as *const u8
    }

    /// Return the allocated memory as a mutable pointer to u8.
    #[inline]
    pub fn as_mut_ptr(&self) -> *mut u8 {
        self.sys.as_send_sync_ptr().as_ptr()
    }

    /// Return the allocated memory as a mutable pointer to u8.
    #[inline]
    pub fn as_non_null(&self) -> NonNull<u8> {
        self.sys.as_send_sync_ptr().as_non_null()
    }

    /// Return the length of the allocated memory.
    ///
    /// This is the byte length of this entire mapping which includes both
    /// addressable and non-addressable memory.
    ///
    /// If the length is statically known to be page-aligned via the
    /// [`AlignedLength`] type parameter, use [`Self::len_aligned`].
    #[inline]
    pub fn len(&self) -> usize {
        self.sys.len()
    }

    /// Makes the specified `range` within this `Mmap` to be read/execute.
    ///
    /// # Unsafety
    ///
    /// This method is unsafe as it's generally not valid to simply make memory
    /// executable, so it's up to the caller to ensure that everything is in
    /// order and this doesn't overlap with other memory that should only be
    /// read or only read/write.
    ///
    /// # Panics
    ///
    /// Panics of `range` is out-of-bounds or not page-aligned.
    pub unsafe fn make_executable(
        &self,
        range: Range<usize>,
        enable_branch_protection: bool,
    ) -> Result<()> {
        assert!(range.start <= self.len());
        assert!(range.end <= self.len());
        assert!(range.start <= range.end);
        assert!(
            range.start % crate::runtime::vm::host_page_size() == 0,
            "changing of protections isn't page-aligned",
        );

        if range.start == range.end {
            // A zero-sized mprotect (or equivalent) is allowed on some
            // platforms but not others (notably Windows). Treat it as a no-op
            // everywhere.
            return Ok(());
        }

        self.sys
            .make_executable(range, enable_branch_protection)
            .context("failed to make memory executable")
    }

    /// Makes the specified `range` within this `Mmap` to be readonly.
    pub unsafe fn make_readonly(&self, range: Range<usize>) -> Result<()> {
        assert!(range.start <= self.len());
        assert!(range.end <= self.len());
        assert!(range.start <= range.end);
        assert!(
            range.start % crate::runtime::vm::host_page_size() == 0,
            "changing of protections isn't page-aligned",
        );

        if range.start == range.end {
            // A zero-sized mprotect (or equivalent) is allowed on some
            // platforms but not others (notably Windows). Treat it as a no-op
            // everywhere.
            return Ok(());
        }

        self.sys
            .make_readonly(range)
            .context("failed to make memory readonly")
    }
}

fn _assert() {
    fn _assert_send_sync<T: Send + Sync>() {}
    _assert_send_sync::<Mmap<AlignedLength>>();
    _assert_send_sync::<Mmap<UnalignedLength>>();
}

impl From<Mmap<AlignedLength>> for Mmap<UnalignedLength> {
    fn from(mmap: Mmap<AlignedLength>) -> Mmap<UnalignedLength> {
        mmap.into_unaligned()
    }
}

/// A reference to an [`Mmap`], along with a host-page-aligned index within it.
///
/// The main invariant this type asserts is that the index is in bounds within
/// the `Mmap` (i.e. `self.mmap[self.offset]` is valid). In the future, this
/// type may also assert other invariants.
#[derive(Clone, Debug)]
pub struct MmapOffset {
    mmap: Arc<Mmap<AlignedLength>>,
    offset: HostAlignedByteCount,
}

impl MmapOffset {
    #[inline]
    fn new(mmap: Arc<Mmap<AlignedLength>>, offset: HostAlignedByteCount) -> Self {
        assert!(
            offset <= mmap.len_aligned(),
            "offset {} is in bounds (< {})",
            offset,
            mmap.len_aligned(),
        );
        Self { mmap, offset }
    }

    /// Returns the mmap this offset is within.
    #[inline]
    pub fn mmap(&self) -> &Arc<Mmap<AlignedLength>> {
        &self.mmap
    }

    /// Returns the host-page-aligned offset within the mmap.
    #[inline]
    pub fn offset(&self) -> HostAlignedByteCount {
        self.offset
    }

    /// Returns the raw pointer in memory represented by this offset.
    #[inline]
    pub fn as_mut_ptr(&self) -> *mut u8 {
        self.as_non_null().as_ptr()
    }

    /// Returns the raw pointer in memory represented by this offset.
    #[inline]
    pub fn as_non_null(&self) -> NonNull<u8> {
        // SAFETY: constructor checks that offset is within this allocation.
        unsafe { self.mmap().as_non_null().byte_add(self.offset.byte_count()) }
    }

    /// Maps an image into the mmap with read/write permissions.
    ///
    /// The image is mapped at `self.mmap.as_ptr() + self.offset +
    /// memory_offset`.
    ///
    /// ## Safety
    ///
    /// The caller must ensure that noone else has a reference to this memory.
    pub unsafe fn map_image_at(
        &self,
        image_source: &MemoryImageSource,
        source_offset: u64,
        memory_offset: HostAlignedByteCount,
        memory_len: HostAlignedByteCount,
    ) -> Result<()> {
        let total_offset = self
            .offset
            .checked_add(memory_offset)
            .expect("self.offset + memory_offset is in bounds");
        self.mmap
            .sys
            .map_image_at(image_source, source_offset, total_offset, memory_len)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Test zero-length calls to mprotect (or the OS equivalent).
    ///
    /// These should be treated as no-ops on all platforms. This test ensures
    /// that such calls at least don't error out.
    #[test]
    fn mprotect_zero_length() {
        let page_size = HostAlignedByteCount::host_page_size();
        let pagex2 = page_size.checked_mul(2).unwrap();
        let pagex3 = page_size.checked_mul(3).unwrap();
        let pagex4 = page_size.checked_mul(4).unwrap();

        let mem = Mmap::accessible_reserved(pagex2, pagex4).expect("allocated memory");

        unsafe {
            mem.make_accessible(pagex3, HostAlignedByteCount::ZERO)
                .expect("make_accessible succeeded");

            mem.make_executable(pagex3.byte_count()..pagex3.byte_count(), false)
                .expect("make_executable succeeded");

            mem.make_readonly(pagex3.byte_count()..pagex3.byte_count())
                .expect("make_readonly succeeded");
        };
    }
}