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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
extern crate libc;

use std::error::Error;
use std::io;
use std::fmt;
use std::ptr;
use std::ops::Drop;
use libc::{c_void, c_int};

#[cfg(windows)]
use std::mem;

fn errno() -> i32 {
    io::Error::last_os_error().raw_os_error().unwrap_or(-1)
}

#[cfg(unix)]
fn page_size() -> usize {
    unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
}

#[cfg(windows)]
fn page_size() -> usize {
    unsafe {
        let mut info = mem::zeroed();
        libc::GetSystemInfo(&mut info);

        info.dwPageSize as usize
    }
}

// Round up `from` to be divisible by `to`
fn round_up(from: usize, to: usize) -> usize {
    let r = if from % to == 0 {
        from
    } else {
        from + to - (from % to)
    };
    if r == 0 {
        to
    } else {
        r
    }
}

/// Type of memory map
#[derive(Copy,Clone)]
pub enum MemoryMapKind {
    /// Virtual memory map. Usually used to change the permissions of a given
    /// chunk of memory.  Corresponds to `VirtualAlloc` on Windows.
    File(*const u8),
    /// Virtual memory map. Usually used to change the permissions of a given
    /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
    /// Windows.
    Virtual,
}

/// Options memory map created with.
#[derive(Copy,Clone)]
pub enum MemoryMapOption {
    /// The memory should be readable.
    Readable,
    /// The memory should be writable.
    Writable,
    /// The memory should be executable.
    Executable,
    /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
    /// POSIX.
    Addr(*const u8),
    /// Create a memory mapping for a file with a given HANDLE.
    #[cfg(windows)]
    Fd(libc::HANDLE),
    /// Create a memory mapping for a file with a given fd.
    #[cfg(not(windows))]
    Fd(c_int),
    /// When using `MapFd`, the start of the map is `usize` bytes from the start
    /// of the file.
    Offset(usize),
    /// On POSIX, this can be used to specify the default flags passed to
    /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
    /// `MAP_ANON`. This will override both of those. This is platform-specific
    /// (the exact values used) and ignored on Windows.
    NonStandardFlags(c_int),
}

/// Possible errors when creating a map.
#[derive(Debug,Clone,Copy)]
pub enum MemoryMapError {
    /// # The following are POSIX-specific
    ///
    /// fd was not open for reading or, if using `MapWritable`, was not open for
    /// writing.
    FdNotAvail,
    /// fd was not valid
    InvalidFd,
    /// Either the address given by `MapAddr` or offset given by `MapOffset` was
    /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
    Unaligned,
    /// With `MapFd`, the fd does not support mapping.
    NoMapSupport,
    /// If using `MapAddr`, the address + `min_len` was outside of the process's
    /// address space. If using `MapFd`, the target of the fd didn't have enough
    /// resources to fulfill the request.
    NoMem,
    /// A zero-length map was requested. This is invalid according to
    /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
    /// Not all platforms obey this, but this wrapper does.
    ZeroLength,
    /// Unrecognized error. The inner value is the unrecognized errno.
    Unknown(isize),
    /// # The following are Windows-specific
    ///
    /// Unsupported combination of protection flags
    /// (`MapReadable`/`MapWritable`/`MapExecutable`).
    UnsupProt,
    /// When using `MapFd`, `MapOffset` was given (Windows does not support this
    /// at all)
    UnsupOffset,
    /// When using `MapFd`, there was already a mapping to the file.
    AlreadyExists,
    /// Unrecognized error from `VirtualAlloc`. The inner value is the return
    /// value of GetLastError.
    VirtualAlloc(i32),
    /// Unrecognized error from `CreateFileMapping`. The inner value is the
    /// return value of `GetLastError`.
    CreateFileMappingW(i32),
    /// Unrecognized error from `MapViewOfFile`. The inner value is the return
    /// value of `GetLastError`.
    MapViewOfFile(i32),
}

impl fmt::Display for MemoryMapError {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        let str = match *self {
            MemoryMapError::FdNotAvail => "fd not available for reading or writing",
            MemoryMapError::InvalidFd => "Invalid fd",
            MemoryMapError::Unaligned => {
                "Unaligned address, invalid flags, negative length or unaligned offset"
            }
            MemoryMapError::NoMapSupport => "File doesn't support mapping",
            MemoryMapError::NoMem => "Invalid address, or not enough available memory",
            MemoryMapError::UnsupProt => "Protection mode unsupported",
            MemoryMapError::UnsupOffset => "Offset in virtual memory mode is unsupported",
            MemoryMapError::AlreadyExists => "File mapping for specified file already exists",
            MemoryMapError::ZeroLength => "Zero-length mapping not allowed",
            MemoryMapError::Unknown(code) => return write!(out, "Unknown error = {}", code),
            MemoryMapError::VirtualAlloc(code) => {
                return write!(out, "VirtualAlloc failure = {}", code)
            }
            MemoryMapError::CreateFileMappingW(code) => {
                return write!(out, "CreateFileMappingW failure = {}", code)
            }
            MemoryMapError::MapViewOfFile(code) => {
                return write!(out, "MapViewOfFile failure = {}", code)
            }
        };
        write!(out, "{}", str)
    }
}

impl Error for MemoryMapError {
    fn description(&self) -> &str {
        "memory map error"
    }
}

/// A memory mapped file or chunk of memory. This is a very system-specific
/// interface to the OS's memory mapping facilities (`mmap` on POSIX,
/// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
/// abstracting platform differences, besides in error values returned. Consider
/// yourself warned.
///
/// The memory map is released (unmapped) when the destructor is run, so don't
/// let it leave scope by accident if you want it to stick around.
pub struct MemoryMap {
    data: *mut u8,
    len: usize,
    kind: MemoryMapKind,
}

#[cfg(unix)]
impl MemoryMap {
    /// Create a new mapping with the given `options`, at least `min_len` bytes
    /// long. `min_len` must be greater than zero; see the note on
    /// `ErrZeroLength`.
    pub fn new(min_len: usize, options: &[MemoryMapOption]) -> Result<MemoryMap, MemoryMapError> {
        use libc::off_t;

        if min_len == 0 {
            return Err(MemoryMapError::ZeroLength);
        }

        let mut addr: *const u8 = ptr::null();
        let mut prot = 0;
        let mut flags = libc::MAP_PRIVATE;
        let mut fd = -1;
        let mut offset = 0;
        let mut custom_flags = false;
        let len = round_up(min_len, page_size());

        for &option in options {
            match option {
                MemoryMapOption::Readable => prot |= libc::PROT_READ,
                MemoryMapOption::Writable => prot |= libc::PROT_WRITE,
                MemoryMapOption::Executable => prot |= libc::PROT_EXEC,
                MemoryMapOption::Addr(addr_) => {
                    flags |= libc::MAP_FIXED;
                    addr = addr_;
                }
                MemoryMapOption::Fd(fd_) => {
                    flags |= libc::MAP_FILE;
                    fd = fd_;
                }
                MemoryMapOption::Offset(offset_) => offset = offset_ as off_t,
                MemoryMapOption::NonStandardFlags(f) => {
                    custom_flags = true;
                    flags = f;
                }
            }
        }

        if fd == -1 && !custom_flags {
            flags |= libc::MAP_ANON;
        }

        let r: *mut libc::c_void = unsafe {
            libc::mmap(addr as *mut c_void,
                       len as libc::size_t,
                       prot,
                       flags,
                       fd,
                       offset)
        };

        if r == libc::MAP_FAILED {
            Err(match errno() {
                libc::EACCES => MemoryMapError::FdNotAvail,
                libc::EBADF => MemoryMapError::InvalidFd,
                libc::EINVAL => MemoryMapError::Unaligned,
                libc::ENODEV => MemoryMapError::NoMapSupport,
                libc::ENOMEM => MemoryMapError::NoMem,
                code => MemoryMapError::Unknown(code as isize),
            })
        } else {
            let mut kind = MemoryMapKind::File(ptr::null());
            if fd == -1 {
                kind = MemoryMapKind::Virtual;
            }

            Ok(MemoryMap {
                data: r as *mut u8,
                len: len,
                kind: kind,
            })
        }
    }

    /// Granularity that the offset or address must be for `MapOffset` and
    /// `MapAddr` respectively.
    pub fn granularity() -> usize {
        page_size()
    }

    /// Flushes changes in memory back to the filesystem.
    pub fn flush(&self, offset: usize, len: usize) -> Result<(), MemoryMapError> {
        let flags = libc::MS_SYNC | libc::MS_INVALIDATE;
        let alignment = (self.data as usize + offset) % page_size();
        let aligned_offset = offset as isize - alignment as isize;
        let aligned_len = len + alignment;

        let result = unsafe {
            libc::msync(self.data.offset(aligned_offset) as *mut c_void,
                        aligned_len as libc::size_t,
                        flags)
        };

        match result {
            0 => Ok(()),
            _ => Err(MemoryMapError::Unknown(result as isize)),
        }
    }

    /// Flushes changes in memory back to the filesystem asynchronously.
    pub fn flush_async(&self, offset: usize, len: usize) -> Result<(), MemoryMapError> {
        let flags = libc::MS_ASYNC | libc::MS_INVALIDATE;
        let alignment = (self.data as usize + offset) % page_size();
        let aligned_offset = offset - alignment;
        let aligned_len = len + alignment;

        let result = unsafe {
            libc::msync(self.data.offset(aligned_offset as isize) as *mut c_void,
                        aligned_len as libc::size_t,
                        flags)
        };

        match result {
            0 => Ok(()),
            _ => Err(MemoryMapError::Unknown(result as isize)),
        }

    }
}

#[cfg(unix)]
impl Drop for MemoryMap {
    /// Unmap the mapping. Panics if `munmap` panics.
    fn drop(&mut self) {
        if self.len == 0 {
            return;
        }

        unsafe {
            // `munmap` only panics due to logic errors.
            libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
        }
    }
}

#[cfg(windows)]
impl MemoryMap {
    /// Create a new mapping with given `options`, at least `min_len` bytes long.
    pub fn new(min_len: usize, options: &[MemoryMapOption]) -> Result<MemoryMap, MemoryMapError> {
        use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T};

        let mut lp_address: LPVOID = ptr::null_mut();
        let (mut readable, mut writable, mut executable) = (false, false, false);
        let mut handle = None;
        let mut offset: usize = 0;
        let mut len = round_up(min_len, page_size());

        for &option in options {
            match option {
                MemoryMapOption::MapReadable => readable = true,
                MemoryMapOption::MapWritable => writable = true,
                MemoryMapOption::MapExecutable => executable = true,
                MemoryMapOption::MapAddr(addr_) => lp_address = addr_ as LPVOID,
                MemoryMapOption::MapFd(handle_) => handle = Some(handle_),
                MemoryMapOption::MapOffset(offset_) => offset = offset_,
                MemoryMapOption::MapNonStandardFlags(..) => {}
            }
        }

        let fl_protect = match (executable, readable, writable) {
            (false, false, false) if handle.is_none() => libc::PAGE_NOACCESS,
            (false, true, false) => libc::PAGE_READONLY,
            (false, true, true) => libc::PAGE_READWRITE,
            (true, false, false) if handle.is_none() => libc::PAGE_EXECUTE,
            (true, true, false) => libc::PAGE_EXECUTE_READ,
            (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
            _ => return Err(MemoryMapError::ErrUnsupProt),
        };

        if let Some(handle) = handle {
            let dw_desired_access = match (executable, readable, writable) {
                (false, true, false) => libc::FILE_MAP_READ,
                (false, true, true) => libc::FILE_MAP_WRITE,
                (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
                (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
                // In reality, we should never get here, because of the check above.
                _ => return Err(MemoryMapError::ErrUnsupProt),
            };

            unsafe {
                let h_file = handle;
                let mapping = libc::CreateFileMapping(h_file,
                                                      ptr::null_mut(),
                                                      fl_protect,
                                                      0,
                                                      0,
                                                      ptr::null());
                if mapping == ptr::null_mut() {
                    return Err(MemoryMapError::ErrCreateFileMappingW(errno()));
                }

                if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
                    return Err(MemoryMapError::ErrAlreadyExists);
                }

                let r = libc::MapViewOfFile(mapping,
                                            dw_desired_access,
                                            ((len as u64) >> 32) as DWORD,
                                            (offset & 0xffff_ffff) as DWORD,
                                            0);
                match r as usize {
                    0 => return Err(MemoryMapError::ErrMapViewOfFile(errno())),
                    _ => {
                        return Ok(MemoryMap {
                            data: r as *mut u8,
                            len: len,
                            kind: MapFile(mapping as *const u8),
                        })
                    }
                }
            }
        } else {
            if offset != 0 {
                return Err(MemoryMapError::ErrUnsupOffset);
            }

            let r = unsafe {
                libc::VirtualAlloc(lp_address,
                                   len as SIZE_T,
                                   libc::MEM_COMMIT | libc::MEM_RESERVE,
                                   fl_protect)
            };

            match r as usize {
                0 => return Err(MemoryMapError::ErrVirtualAlloc()),
                _ => {
                    return Ok(MemoryMap {
                        data: r as *mut u8,
                        len: len,
                        kind: MemoryMapKind::MapVirtual,
                    })
                }
            }
        }
    }

    /// Granularity of MapAddr() and MapOffset parameter values.
    /// This may be greater than the value returned by page_size().
    pub fn granularity() -> usize {
        use std::mem;
        unsafe {
            let mut info = mem::zeroed();
            libc::GetSystemInfo(&mut info);

            return info.dwAllocationGranularity as usize;
        }
    }
}

#[cfg(windows)]
impl Drop for MemoryMap {
    /// Unmap the mapping. Panics the task if any of `VirtualFree`,
    /// `UnmapViewOfFile` or `CloseHandle` fail.
    fn drop(&mut self) {
        use libc::types::os::arch::extra::{LPCVOID, HANDLE};
        use libc::consts::os::extra::FALSE;

        if self.len == 0 {
            return;
        }

        unsafe {
            match self.kind {
                MemoryMapKind::MapVirtual => {
                    if libc::VirtualFree(self.data as *mut c_void, 0, libc::MEM_RELEASE) == 0 {
                        println!("VirtualFree failed: {}", errno());
                    }
                }
                MemoryMapKind::MapFile => {
                    if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
                        println!("UnmapViewOfFile failed: {}", errno());
                    }
                    if libc::CloseHandle(mapping as HANDLE) == FALSE {
                        println!("CloseHandle failed: {}", errno());
                    }
                }
            }
        }
    }
}


impl MemoryMap {
    ///Returns pointer to the memory created or modified by this map.
    pub fn data(&self) -> *mut u8 {
        self.data
    }

    /// Returns the number of bytes this map applies to.
    pub fn len(&self) -> usize {
        self.len
    }

    // Returns true if this map has length equal to 0.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the type of mapping this represents.
    pub fn kind(&self) -> MemoryMapKind {
        self.kind
    }

    pub fn set_data(&mut self, data: *mut u8) {
        self.data = data;
    }
}