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
/*
 * garbage-collected memory manager in Rust
 * Copyright (C) 2020  Xie Ruifeng
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

//! Memory allocation primitives for UNIX-like systems.

#![cfg(unix)]

use super::MMapError;
use super::Result;

use enumflags2::BitFlags;
use libc::{c_int, c_void, off_t};

/// Memory protection flags.
///
/// These can be combined together using the `|` operator:
///
/// ```
/// use memory_manager::allocate::Protection;
/// let protection = Protection::Read | Protection::Write;
/// ```
///
/// If no access should be performed to the memory, use `Protection::NONE`:
///
/// ```
/// use memory_manager::allocate::Protection;
/// let protection = Protection::NONE;
/// ```
///
/// Note that not all combinations are supported on Windows: `Write` will always imply `Read`.
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, BitFlags)]
pub enum Protection {
    /// Pages may be read.
    Read = libc::PROT_READ as u32,
    /// Pages may be written.
    Write = libc::PROT_WRITE as u32,
    /// Pages may be executed.
    Exec = libc::PROT_EXEC as u32,
}

impl Protection {
    /// Pages may not be accessed.
    #[allow(dead_code)]
    pub const NONE: BitFlags<Protection> = unsafe { core::mem::transmute(0u32) };
}

/// `mmap` flags on UNIX-like systems.
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, BitFlags)]
pub enum MapFlags {
    /// Share this mapping (updates visible to other processes).
    Shared = libc::MAP_SHARED as u32,
    /// Private copy-on-write mapping.
    Private = libc::MAP_PRIVATE as u32,
    /// The mapping is not backed by any file; its contents are initialized to zero.
    Anonymous = libc::MAP_ANONYMOUS as u32,
    /// Do not reserve swap space for this mapping.
    NoReserve = libc::MAP_NORESERVE as u32,
}

const INVALID_FILE_DESCRIPTOR: libc::c_int = -1;

unsafe fn wrapped_mmap(
    addr: *mut c_void, len: usize,
    prot: BitFlags<Protection>, flags: BitFlags<MapFlags>,
    fd: c_int, offset: off_t) -> *mut c_void {
    libc::mmap(addr, len, prot.bits() as c_int, flags.bits() as c_int, fd, offset)
}

// the following copied from nix
#[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))]
use libc::__errno as errno_location;
#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "redox"))]
use libc::__errno_location as errno_location;
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
use libc::___errno as errno_location;
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
use libc::__error as errno_location;
#[cfg(target_os = "haiku")]
use libc::_errnop as errno_location;

unsafe fn get_errno() -> c_int { *errno_location() }

unsafe fn set_errno(e: c_int) { *errno_location() = e; }

impl MMapError {
    /// Get `MMapError` from an `errno` value.
    pub fn from_errno(e: c_int) -> MMapError {
        match e {
            libc::EINVAL => MMapError::InvalidArguments,
            libc::EAGAIN => MMapError::TryAgain,
            libc::ENOMEM => MMapError::NoMemory,
            libc::EOVERFLOW => MMapError::LengthOverflow,
            0 => MMapError::NoError,
            _ => MMapError::UnknownError(e as u32),
        }
    }

    /// Get `MMapError` from the current `errno` value.
    pub unsafe fn get() -> MMapError {
        Self::from_errno(get_errno())
    }
}

/// According to the Linux manual for `_SC_PAGESIZE`:
///   Size of a page in bytes.  Must not be less than 1.
static mut PAGE_SIZE: Option<core::num::NonZeroUsize> = None;

/// Get the `PAGE_SIZE`. This function is cached.
pub fn get_page_size() -> Result<usize> {
    // use the cached value if successful calls have been made
    unsafe { if let Some(res) = PAGE_SIZE { return Ok(res.get()); } }
    // acquire the value
    unsafe { set_errno(0) }
    let sz = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
    if sz < 0 {
        Err(unsafe { MMapError::get() })
    } else {
        unsafe { PAGE_SIZE = Some(core::num::NonZeroUsize::new_unchecked(sz as usize)) }
        Ok(sz as usize)
    }
}

/// Get the minimum alignment of memory chunks.
/// On UNIX-like systems it is the same as `PAGE_SIZE`.
#[inline]
pub fn get_minimum_alignment() -> Result<usize> {
    get_page_size()
}

/// Allocate a memory chunk with the given size and protection flags.
pub unsafe fn allocate_chunk(size: usize, protection: BitFlags<Protection>) -> Result<*mut c_void> {
    if size == 0 { return Err(MMapError::InvalidArguments); }
    set_errno(0);
    let addr = wrapped_mmap(
        core::ptr::null_mut(), size,
        protection,
        MapFlags::Private | MapFlags::Anonymous,
        INVALID_FILE_DESCRIPTOR, 0);
    if addr == libc::MAP_FAILED {
        Err(MMapError::get())
    } else {
        Ok(addr)
    }
}

/// Deallocate a memory chunk.
pub unsafe fn deallocate_chunk(addr: *mut c_void, size: usize) -> Result<()> {
    set_errno(0);
    if libc::munmap(addr, size) < 0 {
        Err(MMapError::get())
    } else {
        Ok(())
    }
}

fn is_power_of_2(x: usize) -> bool {
    (x - 1) & x == 0
}

/// Allocate an aligned memory chunk with the given alignment, size and protection flags.
///
/// The size is rounded up to a multiple of the alignment.
///
/// # Panics
///
/// The alignment is asserted to be a multiple of `PAGE_SIZE` **AND** a power of 2.
pub unsafe fn aligned_allocate_chunk(
    alignment: usize, size: usize, protection: BitFlags<Protection>) -> Result<*mut c_void> {
    assert!(is_power_of_2(alignment));
    let alignment_mask = alignment - 1;
    let size = (size + alignment - 1) & !alignment_mask;
    let res = allocate_chunk(size + alignment, protection)?;
    let back_padding = res as usize & alignment_mask;
    let front_padding = alignment - back_padding;
    deallocate_chunk(res, front_padding)?;
    let start_addr = res.offset(front_padding as isize);
    if back_padding > 0 {
        deallocate_chunk(start_addr, back_padding)?;
    }
    Ok(start_addr)
}

#[cfg(test)]
mod tests {
    extern crate std;

    use super::is_power_of_2;

    #[test]
    fn test_is_power_of_2() {
        assert!(is_power_of_2(1));
        assert!(is_power_of_2(2));
        assert!(is_power_of_2(256));
        assert!(!is_power_of_2(257));
    }
}