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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Memory functionality that needs a refactor.

use std::ops::Deref;
use std::ops::DerefMut;
use std::slice;
use std::sync::atomic::AtomicU8;
#[cfg(unix)]
use unix as sys;
#[cfg(windows)]
use windows as sys;

#[derive(Debug)]
pub struct Allocation {
    ptr: *mut u8,
    size: usize,
    _dummy: std::marker::PhantomData<[u8]>,
}

unsafe impl Send for Allocation {}
unsafe impl Sync for Allocation {}

impl Allocation {
    pub fn new(size: usize) -> Result<Self, std::io::Error> {
        let ptr = sys::alloc(size)?;
        Ok(Allocation {
            ptr,
            size,
            _dummy: std::marker::PhantomData,
        })
    }
}

impl DerefMut for Allocation {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe { slice::from_raw_parts_mut(self.ptr, self.size) }
    }
}

impl Deref for Allocation {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        unsafe { slice::from_raw_parts(self.ptr, self.size) }
    }
}

impl Drop for Allocation {
    fn drop(&mut self) {
        unsafe {
            sys::free(self.ptr, self.size);
        }
    }
}

#[derive(Debug)]
pub struct SharedMem {
    alloc: Allocation,
}

impl SharedMem {
    pub fn new(alloc: Allocation) -> Self {
        SharedMem { alloc }
    }
}

impl Deref for SharedMem {
    type Target = [AtomicU8];

    fn deref(&self) -> &Self::Target {
        unsafe { slice::from_raw_parts(self.alloc.ptr as *const AtomicU8, self.alloc.size) }
    }
}

#[cfg(windows)]
mod windows {
    use std::ptr;
    use windows_sys::Win32::System::Memory::VirtualAlloc;
    use windows_sys::Win32::System::Memory::VirtualFree;
    use windows_sys::Win32::System::Memory::MEM_COMMIT;
    use windows_sys::Win32::System::Memory::MEM_RELEASE;
    use windows_sys::Win32::System::Memory::MEM_RESERVE;
    use windows_sys::Win32::System::Memory::PAGE_READWRITE;

    pub fn alloc(size: usize) -> std::io::Result<*mut u8> {
        let ptr = unsafe {
            VirtualAlloc(
                ptr::null_mut(),
                size,
                MEM_RESERVE | MEM_COMMIT,
                PAGE_READWRITE,
            )
        };
        if ptr.is_null() {
            return Err(std::io::Error::last_os_error());
        }
        Ok(ptr.cast::<u8>())
    }

    pub unsafe fn free(ptr: *mut u8, _size: usize) {
        let ret = unsafe { VirtualFree(ptr.cast(), 0, MEM_RELEASE) };
        assert!(ret != 0);
    }
}

#[cfg(unix)]
mod unix {
    use std::ptr;

    pub fn alloc(size: usize) -> std::io::Result<*mut u8> {
        let ptr = unsafe {
            libc::mmap(
                ptr::null_mut(),
                size,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
                -1,
                0,
            )
        };
        if ptr == libc::MAP_FAILED {
            return Err(std::io::Error::last_os_error());
        }
        Ok(ptr.cast::<u8>())
    }

    pub unsafe fn free(ptr: *mut u8, size: usize) {
        let ret = unsafe { libc::munmap(ptr.cast::<libc::c_void>(), size) };
        assert!(ret == 0);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_alloc_free() -> Result<(), Box<dyn std::error::Error>> {
        unsafe {
            let x = sys::alloc(4096)?;
            sys::free(x, 4096);
            Ok(())
        }
    }
}