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
//! A user friendly crate that allows you to share memory between __processes__
//!
//! For help on how to get started, take a look at the examples !

#[macro_use]
extern crate cfg_if;
#[macro_use]
extern crate enum_primitive;

use std::path::PathBuf;
use std::fs::{File};
use std::fs::remove_file;
use std::slice;
use std::os::raw::c_void;
use std::fmt;

//Lock definitions
mod locks;
pub use locks::*;

//Event definitions
mod events;
pub use events::*;

//Load up the proper OS implementation
cfg_if! {
    if #[cfg(target_os="windows")] {
        mod windows;
        use windows as os_impl;
    } else if #[cfg(any(target_os="freebsd", target_os="linux", target_os="macos"))] {
        mod nix;
        use nix as os_impl;
    } else {
        compile_error!("shared_memory isnt implemented for this platform...");
    }
}

//The alignment of addresses. This affects the alignment of the user data and the
//locks/events in the metadata section.
const ADDR_ALIGN: u8 = 4;

//TODO : Replace this with proper error handling, failure crate maybe
type Result<T> = std::result::Result<T, Box<std::error::Error>>;

///Defines different variants to specify timeouts
pub enum Timeout {
    ///Wait forever for an event to be signaled
    Infinite,
    ///Duration in seconds for a timeout
    Sec(usize),
    ///Duration in milliseconds for a timeout
    Milli(usize),
    ///Duration in microseconds for a timeout
    Micro(usize),
    ///Duration in nanoseconds for a timeout
    Nano(usize),
}

//List of "safe" types that the memory can be cast to
mod cast;
pub use cast::*;

//Implementation of SharedMemConf
mod conf;
pub use conf::*;

//Implementation of SharedMemRaw
mod raw;
pub use raw::*;

///Default shared mapping structure
pub struct SharedMem<'a> {
    //Config that describes this mapping
    conf: SharedMemConf<'a>,
    //The currently in use link file
    link_file: Option<File>,
    //Os specific data for the mapping
    os_data: os_impl::MapData,
    //User data start address
    user_ptr: *mut c_void,
}
impl<'a> SharedMem<'a> {

    ///Creates a memory mapping with no link file of specified size controlled by a single lock.
    pub fn create(lock_type: LockType, size: usize) -> Result<SharedMem<'a>> {
        SharedMemConf::new()
            .set_size(size)
            .add_lock(lock_type, 0, size).unwrap().create()
    }

    pub fn open(unique_id: &str) -> Result<SharedMem<'a>> {
        SharedMemConf::new()
            .set_os_path(unique_id)
            .open()
    }

    pub fn create_linked(new_link_path: &PathBuf, lock_type: LockType, size: usize) -> Result<SharedMem<'a>> {
        SharedMemConf::new()
            .set_link_path(new_link_path)
            .set_size(size)
            .add_lock(lock_type, 0, size).unwrap().create()
    }
    pub fn open_linked(existing_link_path: PathBuf) -> Result<SharedMem<'a>> {
        SharedMemConf::new()
            .set_link_path(&existing_link_path)
            .open()
    }

    ///Returns the size of the SharedMem
    #[inline]
    pub fn get_size(&self) -> usize {
        self.conf.get_size()
    }
    #[inline]
    pub fn get_metadata_size(&self) -> usize {
        self.conf.get_metadata_size()
    }
    #[inline]
    pub fn num_locks(&self) -> usize {
        self.conf.num_locks()
    }
    #[inline]
    pub fn num_events(&self) -> usize {
        self.conf.num_events()
    }
    ///Returns the link_path of the SharedMem
    #[inline]
    pub fn get_link_path(&self) -> Option<&PathBuf> {
        self.conf.get_link_path()
    }
    ///Returns the OS specific path of the shared memory object
    ///
    /// Usualy on Linux, this will point to a file under /dev/shm/
    ///
    /// On Windows, this returns a namespace
    #[inline]
    pub fn get_os_path(&self) -> &String {
        &self.os_data.unique_id
    }

    #[inline]
    pub fn get_ptr(&self) -> *mut c_void {
        self.user_ptr
    }
}
impl<'a> Drop for SharedMem<'a> {

    ///Deletes the SharedMemConf artifacts
    fn drop(&mut self) {

        //Close the openned link file
        drop(&self.link_file);

        //Delete link file if we own it
        if self.conf.is_owner() {
            if let Some(ref file_path) = self.conf.get_link_path() {
                if file_path.is_file() {
                    match remove_file(file_path) {_=>{},};
                }
            }
        }
    }
}
impl<'a> fmt::Display for SharedMem<'a> {

    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "
        Created : {}
        link : \"{}\"
        os_id : \"{}\"
        MetaSize : {}
        Size : {}
        Num locks : {}
        Num Events : {}
        MetaAddr : {:p}
        UserAddr : {:p}",
            self.conf.is_owner(),
            self.get_link_path().unwrap_or(&PathBuf::from("[NONE]")).to_string_lossy(),
            self.get_os_path(),
            self.get_metadata_size(),
            self.get_size(),
            self.num_locks(),
            self.num_events(),
            self.os_data.map_ptr,
            self.get_ptr(),
        )
    }
}
impl<'a>ReadLockable for SharedMem<'a> {
    fn rlock<D: SharedMemCast>(&self, lock_index: usize) -> Result<ReadLockGuard<D>> {

        let lock: &GenericLock = self.conf.get_lock(lock_index);

        //Make sure that we can cast our memory to the type
        let type_size = std::mem::size_of::<D>();
        if type_size > lock.length {
            return Err(From::from(
                format!("Tried to map type of {} bytes to a lock holding only {} bytes", type_size, lock.length)
            ));
        }

        //Return data wrapped in a lock
        Ok(
            //Unsafe required to cast shared memory to our type
            unsafe {
                ReadLockGuard::lock(
                    &(*(lock.data_ptr as *const D)),
                    lock.interface,
                    &mut (*lock.lock_ptr),
                )
            }
        )
    }

    fn rlock_as_slice<D: SharedMemCast>(&self, lock_index: usize) -> Result<ReadLockGuardSlice<D>>{

        let lock: &GenericLock = self.conf.get_lock(lock_index);

        //Make sure that we can cast our memory to the slice
        let item_size = std::mem::size_of::<D>();
        if item_size > lock.length {
            return Err(From::from(
                format!("Tried to map type of {} bytes to a lock holding only {} bytes", item_size, lock.length)
            ));
        }
        let num_items: usize = lock.length / item_size;

        //Return data wrapped in a lock
        Ok(
            //Unsafe required to cast shared memory to array
            unsafe {
                ReadLockGuardSlice::lock(
                    slice::from_raw_parts(lock.data_ptr as *const D, num_items),
                    lock.interface,
                    &mut (*lock.lock_ptr),
                )
            }
        )
    }
}
impl<'a>WriteLockable for SharedMem<'a> {
    fn wlock<D: SharedMemCast>(&mut self, lock_index: usize) -> Result<WriteLockGuard<D>> {

        let lock: &GenericLock = self.conf.get_lock(lock_index);

        //Make sure that we can cast our memory to the type
        let type_size = std::mem::size_of::<D>();
        if type_size > lock.length {
            return Err(From::from(
                format!("Tried to map type of {} bytes to a lock holding only {} bytes", type_size, lock.length)
            ));
        }

        //Return data wrapped in a lock
        Ok(
            //Unsafe required to cast shared memory to our type
            unsafe {
                WriteLockGuard::lock(
                    &mut (*(lock.data_ptr as *mut D)),
                    lock.interface,
                    &mut (*lock.lock_ptr),
                )
            }
        )
    }

    fn wlock_as_slice<D: SharedMemCast>(&mut self, lock_index: usize) -> Result<WriteLockGuardSlice<D>> {

        let lock: &GenericLock = self.conf.get_lock(lock_index);

        //Make sure that we can cast our memory to the slice
        let item_size = std::mem::size_of::<D>();
        if item_size > lock.length {
            return Err(From::from(
                format!("Tried to map type of {} bytes to a lock holding only {} bytes", item_size, lock.length)
            ));
        }
        //Calculate how many items our slice will have
        let num_items: usize = lock.length / item_size;

        //Return data wrapped in a lock
        Ok(
            //Unsafe required to cast shared memory to array
            unsafe {
                WriteLockGuardSlice::lock(
                    slice::from_raw_parts_mut((lock.data_ptr as usize + 0) as *mut D, num_items),
                    lock.interface,
                    &mut (*lock.lock_ptr),
                )
            }
        )
    }
}
impl<'a> ReadRaw for SharedMem<'a> {
    unsafe fn get_raw<D: SharedMemCast>(&self) -> &D {
        let user_data = self.os_data.map_ptr as usize + self.conf.get_metadata_size();
        return &(*(user_data as *const D))
    }

    unsafe fn get_raw_slice<D: SharedMemCast>(&self) -> &[D] {
        //Make sure that we can cast our memory to the slice
        let item_size = std::mem::size_of::<D>();
        if item_size > self.conf.get_size() {
            panic!("Tried to map type of {} bytes to a lock holding only {} bytes", item_size, self.conf.get_size());
        }
        let num_items: usize = self.conf.get_size() / item_size;
        let user_data = self.os_data.map_ptr as usize + self.conf.get_metadata_size();

        return slice::from_raw_parts(user_data as *const D, num_items);
    }
}
impl<'a> WriteRaw for SharedMem<'a> {
    unsafe fn get_raw_mut<D: SharedMemCast>(&mut self) -> &mut D {
        let user_data = self.os_data.map_ptr as usize + self.conf.get_metadata_size();
        return &mut (*(user_data as *mut D))
    }
    unsafe fn get_raw_slice_mut<D: SharedMemCast>(&mut self) -> &mut[D] {
        //Make sure that we can cast our memory to the slice
        let item_size = std::mem::size_of::<D>();
        if item_size > self.conf.get_size() {
            panic!("Tried to map type of {} bytes to a lock holding only {} bytes", item_size, self.conf.get_size());
        }
        let num_items: usize = self.conf.get_size() / item_size;
        let user_data = self.os_data.map_ptr as usize + self.conf.get_metadata_size();

        return slice::from_raw_parts_mut(user_data as *mut D, num_items);
    }
}
impl<'a> EventSet for SharedMem<'a> {
    fn set(&mut self, event_index: usize, state: EventState) -> Result<()> {
        let lock: &GenericEvent = self.conf.get_event(event_index);
        lock.interface.set(lock.ptr, state)
    }
}
impl<'a> EventWait for SharedMem<'a> {
    fn wait(&self, event_index: usize, timeout: Timeout) -> Result<()> {
        let lock: &GenericEvent = self.conf.get_event(event_index);
        lock.interface.wait(lock.ptr, timeout)
    }
}