os_core/
lib.rs

1//! # os_core
2//! Core operating system functions
3//! 
4//! These work on Linux and OSX
5#![allow(unused, non_camel_case_types)]
6pub extern crate libc;
7
8pub mod constants;
9pub mod types;
10pub mod linux;
11pub mod unix;
12
13/// allocate raw program memory (atleast around the size of the system's page-size (usually 4096); ie, not small allocations)
14/// 
15/// ```
16/// # Example
17/// use os_core::{memory, release};
18/// 
19/// let mut mem: *mut u8 = memory(4096, true, true, true);
20/// 
21/// unsafe {*mem} = 0xAB;
22/// 
23/// assert_eq!(unsafe {*mem}, 0xAB);
24/// 
25/// release(mem, 4096);
26/// ```
27/// 
28pub fn memory <T> (size: usize, read: bool, write: bool, exec: bool, shared: bool) -> *mut T {
29    use crate::{constants::{map, mprot}, unix::sys_mmap};
30
31    let mut prot = mprot::NONE;
32    let mut flags = map::ANON;
33
34    if read { prot |= mprot::READ; }
35    if write { prot |= mprot::WRITE; }
36    if exec { prot |= mprot::EXEC; }
37
38    if shared { flags |= map::SHARED; }
39    else { flags |= map::PRIVATE; }
40
41    sys_mmap(0 as *mut (), size, prot, flags, -1, 0) as *mut T
42}
43
44/// release raw program memory (unmanaged memory); ie, allocated with `fn memory` or `fn sys_munmap`
45pub fn release <T> (mem: *mut T, size: usize) {
46    crate::unix::sys_munmap(mem as *mut (), size);
47}
48
49#[cfg(test)]
50mod tests {
51    #[test]
52    fn it_works() {
53        let result = 2 + 2;
54        assert_eq!(result, 4);
55    }
56}