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
use crate::error::MemoryCreationError;
use crate::error::MemoryProtectionError;
use crate::sys::{round_down_to_page_size, round_up_to_page_size};
use errno;
use nix::libc;
use page_size;
use std::ops::{Bound, RangeBounds};
use std::{fs::File, os::unix::io::IntoRawFd, path::Path, ptr, slice, sync::Arc};

unsafe impl Send for Memory {}
unsafe impl Sync for Memory {}

/// Data for a sized and protected region of memory.
#[derive(Debug)]
pub struct Memory {
    ptr: *mut u8,
    size: usize,
    protection: Protect,
    fd: Option<Arc<RawFd>>,
}

impl Memory {
    /// Create a new memory from the given path value and protection.
    pub fn from_file_path<P>(path: P, protection: Protect) -> Result<Self, MemoryCreationError>
    where
        P: AsRef<Path>,
    {
        let file = File::open(path)?;

        let file_len = file.metadata()?.len();

        let raw_fd = RawFd::from_file(file);

        let ptr = unsafe {
            libc::mmap(
                ptr::null_mut(),
                file_len as usize,
                protection.to_protect_const() as i32,
                libc::MAP_PRIVATE,
                raw_fd.0,
                0,
            )
        };

        if ptr == -1 as _ {
            Err(MemoryCreationError::VirtualMemoryAllocationFailed(
                file_len as usize,
                errno::errno().to_string(),
            ))
        } else {
            Ok(Self {
                ptr: ptr as *mut u8,
                size: file_len as usize,
                protection,
                fd: Some(Arc::new(raw_fd)),
            })
        }
    }

    /// Create a new memory with the given size and protection.
    pub fn with_size_protect(size: usize, protection: Protect) -> Result<Self, String> {
        if size == 0 {
            return Ok(Self {
                ptr: ptr::null_mut(),
                size: 0,
                protection,
                fd: None,
            });
        }

        let size = round_up_to_page_size(size, page_size::get());

        let ptr = unsafe {
            libc::mmap(
                ptr::null_mut(),
                size,
                protection.to_protect_const() as i32,
                libc::MAP_PRIVATE | libc::MAP_ANON,
                -1,
                0,
            )
        };

        if ptr == -1 as _ {
            Err(errno::errno().to_string())
        } else {
            Ok(Self {
                ptr: ptr as *mut u8,
                size,
                protection,
                fd: None,
            })
        }
    }

    /// Create a new memory with the given size.
    pub fn with_size(size: usize) -> Result<Self, MemoryCreationError> {
        if size == 0 {
            return Ok(Self {
                ptr: ptr::null_mut(),
                size: 0,
                protection: Protect::None,
                fd: None,
            });
        }

        let size = round_up_to_page_size(size, page_size::get());

        let ptr = unsafe {
            libc::mmap(
                ptr::null_mut(),
                size,
                libc::PROT_NONE,
                libc::MAP_PRIVATE | libc::MAP_ANON,
                -1,
                0,
            )
        };

        if ptr == -1 as _ {
            Err(MemoryCreationError::VirtualMemoryAllocationFailed(
                size,
                errno::errno().to_string(),
            ))
        } else {
            Ok(Self {
                ptr: ptr as *mut u8,
                size,
                protection: Protect::None,
                fd: None,
            })
        }
    }

    /// Protect this memory with the given range bounds and protection.
    pub unsafe fn protect(
        &mut self,
        range: impl RangeBounds<usize>,
        protection: Protect,
    ) -> Result<(), MemoryProtectionError> {
        let protect = protection.to_protect_const();

        let range_start = match range.start_bound() {
            Bound::Included(start) => *start,
            Bound::Excluded(start) => *start,
            Bound::Unbounded => 0,
        };

        let range_end = match range.end_bound() {
            Bound::Included(end) => *end,
            Bound::Excluded(end) => *end,
            Bound::Unbounded => self.size(),
        };

        let page_size = page_size::get();
        let start = self
            .ptr
            .add(round_down_to_page_size(range_start, page_size));
        let size = round_up_to_page_size(range_end - range_start, page_size);
        assert!(size <= self.size);

        let success = libc::mprotect(start as _, size, protect as i32);
        if success == -1 {
            Err(MemoryProtectionError::ProtectionFailed(
                start as usize,
                size,
                errno::errno().to_string(),
            ))
        } else {
            self.protection = protection;
            Ok(())
        }
    }

    /// Split this memory into multiple memories by the given offset.
    pub fn split_at(mut self, offset: usize) -> (Memory, Memory) {
        let page_size = page_size::get();
        if offset % page_size == 0 {
            let second_ptr = unsafe { self.ptr.add(offset) };
            let second_size = self.size - offset;

            self.size = offset;

            let second = Memory {
                ptr: second_ptr,
                size: second_size,
                protection: self.protection,
                fd: self.fd.clone(),
            };

            (self, second)
        } else {
            panic!("offset must be multiple of page size: {}", offset)
        }
    }

    /// Gets the size of this memory.
    pub fn size(&self) -> usize {
        self.size
    }

    /// Gets a slice for this memory.
    pub unsafe fn as_slice(&self) -> &[u8] {
        slice::from_raw_parts(self.ptr, self.size)
    }

    /// Gets a mutable slice for this memory.
    pub unsafe fn as_slice_mut(&mut self) -> &mut [u8] {
        slice::from_raw_parts_mut(self.ptr, self.size)
    }

    /// Gets the protect kind of this memory.
    pub fn protection(&self) -> Protect {
        self.protection
    }

    /// Gets mutable pointer to the memory.
    pub fn as_ptr(&self) -> *mut u8 {
        self.ptr
    }
}

impl Drop for Memory {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            let success = unsafe { libc::munmap(self.ptr as _, self.size) };
            assert_eq!(success, 0, "failed to unmap memory: {}", errno::errno());
        }
    }
}

impl Clone for Memory {
    fn clone(&self) -> Self {
        let temp_protection = if self.protection.is_writable() {
            self.protection
        } else {
            Protect::ReadWrite
        };

        let mut new = Memory::with_size_protect(self.size, temp_protection).unwrap();
        unsafe {
            new.as_slice_mut().copy_from_slice(self.as_slice());

            if temp_protection != self.protection {
                new.protect(.., self.protection).unwrap();
            }
        }

        new
    }
}

/// Kinds of memory protection.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)]
#[allow(dead_code)]
pub enum Protect {
    /// Read/write/exec allowed.
    None,
    /// Read only.
    Read,
    /// Read/write only.
    ReadWrite,
    /// Read/exec only.
    ReadExec,
    /// Read/write/exec only.
    ReadWriteExec,
}

impl Protect {
    fn to_protect_const(self) -> u32 {
        match self {
            Protect::None => 0,
            Protect::Read => 1,
            Protect::ReadWrite => 1 | 2,
            Protect::ReadExec => 1 | 4,
            Protect::ReadWriteExec => 1 | 2 | 4,
        }
    }

    /// Returns true if this memory is readable.
    pub fn is_readable(self) -> bool {
        match self {
            Protect::Read | Protect::ReadWrite | Protect::ReadExec | Protect::ReadWriteExec => true,
            _ => false,
        }
    }

    /// Returns true if this memory is writable.
    pub fn is_writable(self) -> bool {
        match self {
            Protect::ReadWrite | Protect::ReadWriteExec => true,
            _ => false,
        }
    }
}

#[derive(Debug)]
struct RawFd(i32);

impl RawFd {
    fn from_file(f: File) -> Self {
        RawFd(f.into_raw_fd())
    }
}

impl Drop for RawFd {
    fn drop(&mut self) {
        let success = unsafe { libc::close(self.0) };
        assert_eq!(
            success,
            0,
            "failed to close mmapped file descriptor: {}",
            errno::errno()
        );
    }
}