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
use std::{
    error::Error,
    fmt::Display,
    ops::{Deref, DerefMut},
    ptr::{self, drop_in_place, NonNull},
};

use libc::{
    c_char, c_void, close, ftruncate, mmap, munmap, shm_open, shm_unlink, MAP_SHARED, O_CREAT,
    O_RDWR, PROT_WRITE, S_IRUSR, S_IWUSR,
};

pub struct Builder {
    id: String,
}

impl Builder {
    pub fn new(id: &str) -> Self {
        Self {
            id: String::from(id),
        }
    }

    pub fn with_size(self, size: i64) -> BuilderWithSize {
        BuilderWithSize { id: self.id, size }
    }
}

pub struct BuilderWithSize {
    id: String,
    size: i64,
}
impl BuilderWithSize {
    pub fn open(self) -> Result<ShmemConf, ShmemError> {
        let (fd, is_owner) = unsafe {
            let storage_id: *const c_char = self.id.as_bytes().as_ptr() as *const c_char;

            // open the existing shared memory if exists
            let fd = shm_open(storage_id, O_RDWR, S_IRUSR | S_IWUSR);

            // shared memory didn't exist
            if fd < 0 {
                // create the shared memory
                let fd = shm_open(storage_id, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
                if fd < 0 {
                    return Err(ShmemError::CreateFailedErr);
                }

                // allocate the shared memory with required size
                let res = ftruncate(fd, self.size);
                if res < 0 {
                    return Err(ShmemError::AllocationFailedErr);
                }

                (fd, true)
            } else {
                (fd, false)
            }
        };

        let null = ptr::null_mut();
        let addr = unsafe { mmap(null, self.size as usize, PROT_WRITE, MAP_SHARED, fd, 0) };

        Ok(ShmemConf {
            id: self.id,
            is_owner,
            fd,
            addr: NonNull::new(addr as *mut _).ok_or(ShmemError::NullPointerErr)?,
            size: self.size,
        })
    }
}

#[derive(Debug)]
pub struct ShmemConf {
    id: String,
    is_owner: bool,
    fd: i32,
    addr: NonNull<()>,
    size: i64,
}

impl ShmemConf {
    /// # Safety
    ///
    /// this is unsafe because there is no guarantee that the referred T is initialized.
    /// the caller must ensure that the value behind the pointer is initialzed before use
    pub unsafe fn boxed<T>(self) -> ShmemBox<T> {
        ShmemBox {
            ptr: self.addr.cast(),
            conf: self,
        }
    }
}

/// # Safety
///
/// shared memory is shared between processes.
/// if it can withstand multiple processes mutating it, it can sure handle a thread or two!
unsafe impl<T: Sync> Sync for ShmemBox<T> {}
unsafe impl<T: Send> Send for ShmemBox<T> {}

#[derive(Debug)]
pub struct ShmemBox<T> {
    ptr: NonNull<T>,
    conf: ShmemConf,
}

impl<T> ShmemBox<T> {
    // owns the shared memory. this would result in shared memory cleanup when this pointer goes
    // out of scope
    pub fn own(mut shmem_box: Self) -> Self {
        shmem_box.conf.is_owner = true;

        shmem_box
    }

    // leaks the shared memory and prevents the cleanup if the ShmemBox is the owner of the shared
    // memory.
    // this function is useful when you want to create a shared memory which last longer than the
    // process creating it.
    pub fn leak(mut shmem_box: Self) {
        // disabling cleanup for shared memory
        shmem_box.conf.is_owner = false;
    }
}

impl<T> Drop for ShmemBox<T> {
    fn drop(&mut self) {
        if self.conf.is_owner {
            // # Safety
            //
            // if current process is the owner of the shared_memory,i.e. creator of the shared
            // memory, then it should clean up after, that is, it should drop the inner T
            unsafe { drop_in_place(self.ptr.as_mut()) };
        }
    }
}
impl Drop for ShmemConf {
    fn drop(&mut self) {
        // # Safety
        //
        // if current process is the owner of the shared_memory,i.e. creator of the shared
        // memory, then it should clean up after.
        // the procedure is as follow:
        // 1. unmap the shared memory from processes virtual address space.
        // 2. unlink the shared memory completely from the os if self is the owner
        // 3. close the file descriptor of the shared memory
        if unsafe { munmap(self.addr.as_ptr() as *mut c_void, self.size as usize) } != 0 {
            panic!("failed to unmap shared memory from the virtual memory space")
        }

        if self.is_owner {
            let storage_id: *const c_char = self.id.as_bytes().as_ptr() as *const c_char;
            if unsafe { shm_unlink(storage_id) } != 0 {
                panic!("failed to reclaim shared memory")
            }
        }

        if unsafe { close(self.fd) } != 0 {
            panic!("failed to close shared memory file descriptor")
        }
    }
}

impl<T> Deref for ShmemBox<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { self.ptr.as_ref() }
    }
}

impl<T> DerefMut for ShmemBox<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.ptr.as_mut() }
    }
}

#[derive(Debug)]
pub enum ShmemError {
    CreateFailedErr,
    AllocationFailedErr,
    NullPointerErr,
}
impl Display for ShmemError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}
impl Error for ShmemError {}

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

    #[test]
    fn ownership() {
        #[derive(Debug)]
        struct Data {
            val: i32,
        }

        let shmconf = Builder::new("test-shmem-box-ownership")
            .with_size(std::mem::size_of::<Data>() as i64)
            .open()
            .unwrap();
        let mut data = unsafe { shmconf.boxed::<Data>() };
        assert_eq!(data.val, 0);
        data.val = 1;

        ShmemBox::leak(data);

        let shmconf = Builder::new("test-shmem-box-ownership")
            .with_size(std::mem::size_of::<Data>() as i64)
            .open()
            .unwrap();
        let data = unsafe { shmconf.boxed::<Data>() };
        assert_eq!(data.val, 1);

        let _owned_data = ShmemBox::own(data);
    }

    #[test]
    fn multi_thread() {
        struct Data {
            val: i32,
        }
        // create new shared memory pointer with desired size
        let shared_mem = Builder::new("test-shmem-box-multi-thread.shm")
            .with_size(std::mem::size_of::<Data>() as i64)
            .open()
            .unwrap();

        // wrap the raw shared memory ptr with desired Boxed type
        // user must ensure that the data the pointer is pointing to is initialized and valid for use
        let data = unsafe { shared_mem.boxed::<Data>() };

        // ensure that first process owns the shared memory (used for cleanup)
        let mut data = ShmemBox::own(data);

        // initiate the data behind the boxed pointer
        data.val = 1;

        let new_val = 5;
        std::thread::spawn(move || {
            // create new shared memory pointer with desired size
            let shared_mem = Builder::new("test-shmem-box-multi-thread.shm")
                .with_size(std::mem::size_of::<Data>() as i64)
                .open()
                .unwrap();

            // wrap the raw shared memory ptr with desired Boxed type
            // user must ensure that the data the pointer is pointing to is initialized and valid for use
            let mut data = unsafe { shared_mem.boxed::<Data>() };
            data.val = new_val;
        })
        .join()
        .unwrap();
        // assert that the new process mutated the shared memory
        assert_eq!(data.val, new_val);
    }
}