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
#![cfg(unix)]
use super::MMapError;
use super::Result;
use enumflags2::BitFlags;
use libc::{c_int, c_void, off_t};
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, BitFlags)]
pub enum Protection {
Read = libc::PROT_READ as u32,
Write = libc::PROT_WRITE as u32,
Exec = libc::PROT_EXEC as u32,
}
impl Protection {
#[allow(dead_code)]
pub const NONE: BitFlags<Protection> = unsafe { core::mem::transmute(0u32) };
}
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, BitFlags)]
pub enum MapFlags {
Shared = libc::MAP_SHARED as u32,
Private = libc::MAP_PRIVATE as u32,
Anonymous = libc::MAP_ANONYMOUS as u32,
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)
}
#[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 {
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),
}
}
pub unsafe fn get() -> MMapError {
Self::from_errno(get_errno())
}
}
static mut PAGE_SIZE: Option<core::num::NonZeroUsize> = None;
pub fn get_page_size() -> Result<usize> {
unsafe { if let Some(res) = PAGE_SIZE { return Ok(res.get()); } }
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)
}
}
#[inline]
pub fn get_minimum_alignment() -> Result<usize> {
get_page_size()
}
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)
}
}
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
}
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));
}
}