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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#![doc = include_str!("../README.md")]

pub mod error;
mod os_impl;

#[cfg(unix)]
use os_impl::unix as platform;

#[cfg(windows)]
use os_impl::windows as platform;

use bitflags::bitflags;
use crate::error::Error;
use std::fs::File;
use std::ops::{Deref, DerefMut, Range};

bitflags! {
    /// The available flags to configure the allocated mapping.
    pub struct MmapFlags: u32 {
        /// May initially map the pages as shared between multiple mappings, but creates a private
        /// copy when writing to the pages such that any modifications are not visible to any other
        /// processes.
        const COPY_ON_WRITE = 1 << 0;

        /// Ensure the allocated pages are populated, such that they do not cause page faults.
        const POPULATE      = 1 << 1;

        /// Do not reserve swap space for this allocation.
        const NO_RESERVE    = 1 << 2;

        /// Use huge pages for this allocation.
        const HUGE_PAGES    = 1 << 3;

        /// The region grows downward like a stack.
        const STACK         = 1 << 4;

        /// The pages will not be included in a core dump.
        const NO_CORE_DUMP  = 1 << 5;

        /// Lock the physical memory to prevent page faults from happening when accessing the
        /// pages.
        const LOCKED        = 1 << 6;
    }

    /// The available flags to configure the allocated mapping, but that are considered unsafe to
    /// use.
    pub struct UnsafeMmapFlags: u32 {
        /// Maps the memory mapping at the address specified, replacing any pages that have been
        /// mapped at that address range.
        ///
        /// This is not supported on Microsoft Windows.
        const MAP_FIXED = 1 << 0;

        /// Allows mapping the page as RWX. While this may seem useful for self-modifying code and
        /// JIT engines, it is instead recommended to convert between mutable and executable
        /// mappings using [`Mmap::make_mut()`] and [`MmapMut::make_exec()`] instead.
        ///
        /// As it may be tempting to use this flag, this flag has been (indirectly) marked as
        /// **unsafe**. Make sure to read the text below to understand the complications of this
        /// flag before using it.
        ///
        /// RWX pages are an interesting targets to attackers, e.g. for buffer overflow attacks, as
        /// RWX mappings can potentially simplify such attacks. Without RWX mappings, attackers
        /// instead have to resort to return-oriented programming (ROP) gadgets. To prevent buffer
        /// overflow attacks, contemporary CPUs allow pages to be marked as non-executable which is
        /// then used by the operating system to ensure that pages are either marked as writeable
        /// or as executable, but not both. This is also known as W^X.
        ///
        /// While the x86 and x86-64 architectures guarantee cache coherency between the L1
        /// instruction and the L1 data cache, other architectures such as Arm and AArch64 do not.
        /// If the user modified the pages, then executing the code may result in undefined
        /// behavior. To ensure correct behavior a user has to flush the instruction cache after
        /// modifying and before executing the page.
        const JIT       = 1 << 1;
    }
}

/// The preferred size of the pages uses, where the size is in log2 notation.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PageSize(pub usize);

impl PageSize {
    pub const _4K:   Self = Self(12);
    pub const _64K:  Self = Self(16);
    pub const _512K: Self = Self(19);
    pub const _1M:   Self = Self(20);
    pub const _2M:   Self = Self(21);
    pub const _4M:   Self = Self(22);
    pub const _8M:   Self = Self(23);
    pub const _16M:  Self = Self(24);
    pub const _32M:  Self = Self(25);
    pub const _256M: Self = Self(28);
    pub const _512M: Self = Self(29);
    pub const _1G:   Self = Self(30);
    pub const _2G:   Self = Self(31);
    pub const _16G:  Self = Self(34);
}

macro_rules! mmap_impl {
    ($t:ident) => {
        impl $t {
            /// Yields the file backing this mapping, if this mapping is backed by a file.
            #[inline]
            pub fn file(&self) -> Option<&File> {
                self.inner.file()
            }

            /// Yields a raw immutable pointer of this mapping.
            #[inline]
            pub fn as_ptr(&self) -> *const u8 {
                self.inner.as_ptr()
            }

            /// Yields the size of this mapping.
            #[inline]
            pub fn size(&self) -> usize {
                self.inner.size()
            }

            /// Locks the physical pages in memory such that accessing the mapping causes no page faults.
            pub fn lock(&mut self) -> Result<(), Error> {
                self.inner.lock()
            }

            /// Unlocks the physical pages in memory, allowing the operating system to swap out the pages
            /// backing this memory mapping.
            pub fn unlock(&mut self) -> Result<(), Error> {
                self.inner.unlock()
            }

            /// Flushes the memory mapping synchronously, i.e. this function waits for the flush to
            /// complete.
            pub fn flush(&self, range: Range<usize>) -> Result<(), Error> {
                self.inner.flush(range)
            }

            /// Flushes the memory mapping asynchronously.
            pub fn flush_async(&self, range: Range<usize>) -> Result<(), Error> {
                self.inner.flush_async(range)
            }

            /// This function can be used to flush the instruction cache on architectures where
            /// this is required.
            ///
            /// While the x86 and x86-64 architectures guarantee cache coherency between the L1 instruction
            /// and the L1 data cache, other architectures such as Arm and AArch64 do not. If the user
            /// modified the pages, then executing the code may result in undefined behavior. To ensure
            /// correct behavior a user has to flush the instruction cache after modifying and before
            /// executing the page.
            pub fn flush_icache(self) -> Result<(), Error> {
                self.inner.flush_icache()
            }

            /// Remaps this memory mapping as inaccessible.
            pub fn make_none(self) -> Result<MmapNone, Error> {
                self.inner.make_none()?;

                Ok(MmapNone {
                    inner: self.inner,
                })
            }

            /// Remaps this memory mapping as immutable.
            pub fn make_read_only(self) -> Result<Mmap, Error> {
                self.inner.make_read_only()?;

                Ok(Mmap {
                    inner: self.inner,
                })
            }

            /// Remaps this memory mapping as executable.
            pub fn make_exec(self) -> Result<Mmap, Error> {
                self.inner.make_exec()?;
                self.inner.flush_icache()?;

                Ok(Mmap {
                    inner: self.inner,
                })
            }

            /// Remaps this memory mapping as executable, but does not flush the instruction cache.
            /// Note that this is **unsafe**.
            ///
            /// While the x86 and x86-64 architectures guarantee cache coherency between the L1 instruction
            /// and the L1 data cache, other architectures such as Arm and AArch64 do not. If the user
            /// modified the pages, then executing the code may result in undefined behavior. To ensure
            /// correct behavior a user has to flush the instruction cache after modifying and before
            /// executing the page.
            pub unsafe fn make_exec_no_flush(self) -> Result<Mmap, Error> {
                self.inner.make_exec()?;

                Ok(Mmap {
                    inner: self.inner,
                })
            }


            /// Remaps this mapping to be mutable.
            ///
            /// In case of failure, this returns the ownership of `self`.
            pub fn make_mut(self) -> Result<MmapMut, (Self, Error)> {
                if let Err(e) = self.inner.make_mut() {
                    return Err((self, e));
                }

                Ok(MmapMut {
                    inner: self.inner,
                })
            }

            /// Remaps this mapping to be executable and mutable.
            ///
            /// While this may seem useful for self-modifying
            /// code and JIT engines, it is instead recommended to convert between mutable and executable
            /// mappings using [`Mmap::make_mut()`] and [`MmapMut::make_exec()`] instead.
            ///
            /// As it may be tempting to use this function, this function has been marked as **unsafe**.
            /// Make sure to read the text below to understand the complications of this function before
            /// using it. The [`UnsafeMmapFlags::JIT`] flag must be set for this function to succeed.
            ///
            /// RWX pages are an interesting targets to attackers, e.g. for buffer overflow attacks, as RWX
            /// mappings can potentially simplify such attacks. Without RWX mappings, attackers instead
            /// have to resort to return-oriented programming (ROP) gadgets. To prevent buffer overflow
            /// attacks, contemporary CPUs allow pages to be marked as non-executable which is then used by
            /// the operating system to ensure that pages are either marked as writeable or as executable,
            /// but not both. This is also known as W^X.
            ///
            /// While the x86 and x86-64 architectures guarantee cache coherency between the L1 instruction
            /// and the L1 data cache, other architectures such as Arm and AArch64 do not. If the user
            /// modified the pages, then executing the code may result in undefined behavior. To ensure
            /// correct behavior a user has to flush the instruction cache after modifying and before
            /// executing the page.
            ///
            /// In case of failure, this returns the ownership of `self`.
            pub unsafe fn make_exec_mut(self) -> Result<MmapMut, (Self, Error)> {
                if let Err(e) = self.inner.make_exec_mut() {
                    return Err((self, e));
                }

                Ok(MmapMut {
                    inner: self.inner,
                })
            }
        }
    }
}

/// Represents an inaccessible memory mapping.
pub struct MmapNone {
    inner: platform::Mmap,
}

mmap_impl!(MmapNone);

/// Represents an immutable memory mapping.
pub struct Mmap {
    inner: platform::Mmap,
}

mmap_impl!(Mmap);

impl Deref for Mmap {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        unsafe {
            std::slice::from_raw_parts(self.as_ptr(), self.size())
        }
    }
}

impl AsRef<[u8]> for Mmap {
    fn as_ref(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(self.as_ptr(), self.size())
        }
    }
}

/// Represents a mutable memory mapping.
pub struct MmapMut {
    inner: platform::Mmap,
}

mmap_impl!(MmapMut);

impl MmapMut {
    /// Yields a raw mutable pointer to this mapping.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        self.inner.as_mut_ptr()
    }
}

impl Deref for MmapMut {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        unsafe {
            std::slice::from_raw_parts(self.as_ptr(), self.size())
        }
    }
}

impl DerefMut for MmapMut {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe {
            std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.size())
        }
    }
}

impl AsRef<[u8]> for MmapMut {
    fn as_ref(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(self.as_ptr(), self.size())
        }
    }
}

impl AsMut<[u8]> for MmapMut {
    fn as_mut(&mut self) -> &mut [u8] {
        unsafe {
            std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.size())
        }
    }
}

/// Represents the options for the memory mapping.
pub struct MmapOptions {
    inner: platform::MmapOptions,
}

impl MmapOptions {
    /// Construct the `MmapOptions` builder.
    pub fn new() -> Self {
        Self {
            inner: platform::MmapOptions::new(),
        }
    }

    /// Returns the smallest possible page size for the current platform as well as the allocation
    /// granularity. On some platforms the allocation granularity may be a multiple of the page
    /// size. The start address of the allocation must be aligned to the allocation granularity,
    /// while the allocation size must be aligned to the page size for the allocation to succeed.
    pub fn page_size() -> (usize, usize) {
        platform::MmapOptions::page_size()
    }

    /// The desired address at which the memory should be mapped.
    pub fn with_address(self, address: Option<usize>) -> Self {
        Self {
            inner: self.inner.with_address(address),
        }
    }

    /// Whether the memory mapping should be backed by a [`File`] or not. If the memory mapping
    /// should be mapped by a [`File`], then the user can also specify the offset within the file
    /// at which the mapping should start.
    ///
    /// On Microsoft Windows, it may not be possible to extend the protection beyond the access
    /// mask that has been used to open the file. For instance, if a file has been opened with read
    /// access, then [`Mmap::make_mut()`] will not work. Furthermore, [`std::fs::OpenOptions`] does
    /// not in itself provide a standardized way to open the file with executable access. However,
    /// if the file is not opened with executable access, then it may not be possible to use
    /// [`Mmap::make_exec()`]. Fortunately, Rust provides [`std::os::windows::fs::OpenOptionsExt`]
    /// that allows you to open the file with executable access rights. See
    /// [`std::os::windows::fs::OpenOptionsExt::access_mode`] for more information.
    ///
    /// This function is marked as **unsafe** as the user should be aware that even in the case
    /// that a file is mapped as immutable in the address space of the current process, it does not
    /// guarantee that there does not exist any other mutable mapping to the file.
    ///
    /// On Microsoft Windows, it is possible to limit the access to shared reading or to be fully
    /// exclusive using [`std::os::windows::fs::OpenOptionsExt::share_mode`].
    ///
    /// On most Unix systems, it is possible to use [`nix::fcntl::flock`]. However, keep in mind
    /// that this provides an **advisory** locking scheme, and that implementations are therefore
    /// required to be co-operative.
    pub unsafe fn with_file(self, file: Option<(File, u64)>) -> Self {
        Self {
            inner: self.inner.with_file(file),
        }
    }

    /// The size of the mapping to be allocated.
    pub fn with_size(self, size: usize) -> Self {
        Self {
            inner: self.inner.with_size(size),
        }
    }

    /// The desired configuration of the mapping. See [`MmapFlags`] for available options.
    pub fn with_flags(self, flags: MmapFlags) -> Self {
        Self {
            inner: self.inner.with_flags(flags),
        }
    }

    /// The desired configuration of the mapping. See [`UnsafeMmapFlags`] for available options.
    ///
    /// Note this function is **unsafe** as the flags that can be passed to this function have
    /// unsafe behavior associated with them.
    pub unsafe fn with_unsafe_flags(self, flags: UnsafeMmapFlags) -> Self {
        Self {
            inner: self.inner.with_unsafe_flags(flags),
        }
    }

    /// Whether this memory mapped should be backed by a specific page size or not.
    pub fn with_page_size(self, page_size: Option<PageSize>) -> Self {
        Self {
            inner: self.inner.with_page_size(page_size),
        }
    }

    /// Maps the memory as inaccessible.
    pub fn map_none(self) -> Result<MmapNone, Error> {
        Ok(MmapNone {
            inner: self.inner.map_none()?,
        })
    }

    /// Maps the memory as immutable.
    pub fn map(self) -> Result<Mmap, Error> {
        Ok(Mmap {
            inner: self.inner.map()?,
        })
    }

    /// Maps the memory as executable.
    pub fn map_exec(self) -> Result<Mmap, Error> {
        Ok(Mmap {
            inner: self.inner.map_exec()?,
        })
    }

    /// Maps the memory as mutable.
    pub fn map_mut(self) -> Result<MmapMut, Error> {
        Ok(MmapMut {
            inner: self.inner.map_mut()?,
        })
    }

    /// Maps the memory as executable and mutable. While this may seem useful for self-modifying
    /// code and JIT engines, it is instead recommended to convert between mutable and executable
    /// mappings using [`Mmap::make_mut()`] and [`MmapMut::make_exec()`] instead.
    ///
    /// As it may be tempting to use this function, this function has been marked as **unsafe**.
    /// Make sure to read the text below to understand the complications of this function before
    /// using it. The [`UnsafeMmapFlags::JIT`] flag must be set for this function to succeed.
    ///
    /// RWX pages are an interesting targets to attackers, e.g. for buffer overflow attacks, as RWX
    /// mappings can potentially simplify such attacks. Without RWX mappings, attackers instead
    /// have to resort to return-oriented programming (ROP) gadgets. To prevent buffer overflow
    /// attacks, contemporary CPUs allow pages to be marked as non-executable which is then used by
    /// the operating system to ensure that pages are either marked as writeable or as executable,
    /// but not both. This is also known as W^X.
    ///
    /// While the x86 and x86-64 architectures guarantee cache coherency between the L1 instruction
    /// and the L1 data cache, other architectures such as Arm and AArch64 do not. If the user
    /// modified the pages, then executing the code may result in undefined behavior. To ensure
    /// correct behavior a user has to flush the instruction cache after  modifying and before
    /// executing the page.
    pub unsafe fn map_exec_mut(self) -> Result<MmapMut, Error> {
        Ok(MmapMut {
            inner: self.inner.map_exec_mut()?,
        })
    }
}