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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
extern crate rand;
use self::rand::Rng;
extern crate theban_interval_tree;
use self::theban_interval_tree::*;
extern crate memrange;
use self::memrange::Range;
use super::*;
use enum_primitive::FromPrimitive;
use std::io::{Write, Read};
use std::ptr::null_mut;
use std::mem::size_of;
fn align_value(val: &mut usize, align: u8) -> u8 {
let tmp: u8 = align-1;
let old_val = *val;
if *val & tmp as usize != 0 {
*val = (*val + tmp as usize) & !(tmp as usize);
}
(*val - old_val) as u8
}
#[repr(C)]
struct MetaDataHeader {
meta_size: u64,
user_size: u64,
num_locks: u64,
num_events: u64,
}
#[repr(C)]
struct LockHeader {
uid: u8,
offset: u64,
length: u64,
}
#[repr(C)]
struct EventHeader {
uid: u8,
}
pub struct SharedMemConf<'a> {
owner: bool,
link_path: Option<PathBuf>,
wanted_os_path: Option<String>,
size: usize,
meta_size: usize,
lock_range_tree: IntervalTree<usize>,
lock_data: Vec<GenericLock<'a>>,
event_data: Vec<GenericEvent<'a>>,
}
impl<'a> SharedMemConf<'a> {
fn valid_lock_range(map_size: usize, offset: usize, length:usize) -> bool {
if length == 0 {
if offset != 0 {
return false;
} else {
return true;
}
}
if offset + (length - 1) >= map_size {
return false;
}
return true;
}
fn add_lock_impl(&mut self, lock_type: LockType, offset: usize, length: usize) -> Result<()> {
if !SharedMemConf::valid_lock_range(self.size, offset, length) {
return Err(From::from(format!(
"add_lock({:?}, {}, {}) : Invalid lock range for map size {}",
lock_type, offset, length, self.size)));
}
if length != 0 {
let start_offset: u64 = offset as u64;
let end_offset: u64 = offset as u64 + (length - 1) as u64;
if let Some(existing_lock) = self.lock_range_tree.range(start_offset, end_offset).next() {
return Err(From::from(format!(
"add_lock({:?}, {}, {}) : Lock #{} already covers this range...",
lock_type, offset, length, existing_lock.1)));
}
self.lock_range_tree.insert(Range::new(start_offset, end_offset), self.lock_data.len());
}
let new_lock = GenericLock {
uid: (lock_type as u8),
offset: offset,
length: length,
lock_ptr: null_mut(),
data_ptr: null_mut(),
interface: os_impl::lockimpl_from_type(&lock_type),
};
self.meta_size += size_of::<LockHeader>() + new_lock.interface.size_of();
self.lock_data.push(new_lock);
Ok(())
}
fn add_event_impl(&mut self, event_type: EventType) -> Result<()> {
let new_event = GenericEvent {
uid: (event_type as u8),
ptr: null_mut(),
interface: os_impl::eventimpl_from_type(&event_type),
};
self.meta_size += size_of::<EventHeader>() + new_event.interface.size_of();
self.event_data.push(new_event);
Ok(())
}
fn calculate_metadata_size(&self) -> usize {
let mut meta_size = size_of::<MetaDataHeader>();
for ref lock in &self.lock_data {
meta_size += size_of::<LockHeader>();
align_value(&mut meta_size, ADDR_ALIGN);
meta_size += lock.interface.size_of();
}
for ref event in &self.event_data {
meta_size += size_of::<EventHeader>();
align_value(&mut meta_size, ADDR_ALIGN);
meta_size += event.interface.size_of();
}
align_value(&mut meta_size, ADDR_ALIGN);
meta_size
}
pub fn new() -> SharedMemConf<'a> {
SharedMemConf {
owner: false,
link_path: None,
wanted_os_path: None,
size: 0,
lock_range_tree: IntervalTree::<usize>::new(),
lock_data: Vec::with_capacity(2),
event_data: Vec::with_capacity(2),
meta_size: size_of::<MetaDataHeader>(),
}
}
pub fn set_size(mut self, wanted_size: usize) -> SharedMemConf<'a> {
self.size = wanted_size;
return self;
}
pub fn set_link_path(mut self, link_path: &OsStr) -> SharedMemConf<'a> {
self.link_path = Some(PathBuf::from(link_path));
return self;
}
pub fn set_os_path(mut self, unique_id: &str) -> SharedMemConf<'a> {
self.wanted_os_path = Some(String::from(unique_id));
return self;
}
pub fn add_lock(mut self, lock_type: LockType, offset: usize, length: usize) -> Result<SharedMemConf<'a>> {
self.add_lock_impl(lock_type, offset, length)?;
Ok(self)
}
pub fn add_event(mut self, event_type: EventType) -> Result<SharedMemConf<'a>> {
self.add_event_impl(event_type)?;
Ok(self)
}
pub fn create(mut self) -> Result<SharedMem<'a>> {
if self.size == 0 {
return Err(From::from("SharedMemConf.create() : Cannot create a mapping of size 0"));
}
let mut cur_link: Option<File> = None;
if let Some(ref file_path) = self.link_path {
if file_path.is_file() {
return Err(From::from("SharedMemConf.create() : Link file already exists"));
} else {
cur_link = Some(File::create(file_path)?);
self.owner = true;
}
}
let unique_id: String = match self.wanted_os_path {
Some(ref s) => s.clone(),
None => {
format!("shmem_rs_{:16X}", rand::thread_rng().gen::<u64>())
},
};
let meta_size: usize = self.calculate_metadata_size();
let os_map: os_impl::MapData = os_impl::create_mapping(&unique_id, meta_size + self.size)?;
if let Some(ref mut openned_link) = cur_link {
match openned_link.write(unique_id.as_bytes()) {
Ok(write_sz) => if write_sz != unique_id.as_bytes().len() {
return Err(From::from("SharedMemConf.create() : Failed to write unique_id to link file"));
},
Err(_) => return Err(From::from("SharedMemConf.create() : Failed to write unique_id to link file")),
};
}
let mut cur_ptr = os_map.map_ptr as usize;
let user_ptr = os_map.map_ptr as usize + meta_size;
let meta_header: &mut MetaDataHeader = unsafe{&mut (*(cur_ptr as *mut MetaDataHeader))};
meta_header.meta_size = meta_size as u64;
meta_header.user_size = self.size as u64;
meta_header.num_locks = self.lock_data.len() as u64;
meta_header.num_events = self.event_data.len() as u64;
cur_ptr += size_of::<MetaDataHeader>();
for lock in &mut self.lock_data {
let lock_header: &mut LockHeader = unsafe{&mut (*(cur_ptr as *mut LockHeader))};
lock_header.uid = lock.uid;
lock_header.offset = lock.offset as u64;
lock_header.length = lock.length as u64;
cur_ptr += size_of::<LockHeader>();
align_value(&mut cur_ptr, ADDR_ALIGN);
lock.lock_ptr = cur_ptr as *mut c_void;
lock.data_ptr = (user_ptr + lock.offset) as *mut c_void;
cur_ptr += lock.interface.size_of();
lock.interface.init(lock, true)?;
}
for event in &mut self.event_data {
let event_header: &mut EventHeader = unsafe{&mut (*(cur_ptr as *mut EventHeader))};
event_header.uid = event.uid;
cur_ptr += size_of::<EventHeader>();
align_value(&mut cur_ptr, ADDR_ALIGN);
event.ptr = cur_ptr as *mut c_void;
cur_ptr += event.interface.size_of();
event.interface.init(event, true)?;
}
align_value(&mut cur_ptr, ADDR_ALIGN);
self.meta_size = meta_size;
Ok(SharedMem {
conf: self,
os_data: os_map,
user_ptr: cur_ptr as *mut c_void,
link_file: cur_link,
})
}
pub fn open(mut self) -> Result<SharedMem<'a>> {
let mut cur_link: Option<File> = None;
let os_map: os_impl::MapData = match self.wanted_os_path {
Some(ref v) => os_impl::open_mapping(v)?,
None => {
if let Some(ref link_file_path) = self.link_path {
if !link_file_path.is_file() {
return Err(From::from("Cannot find unique os path since link_file does not exist"));
}
let mut link_file = File::open(link_file_path)?;
let mut file_contents: Vec<u8> = Vec::new();
link_file.read_to_end(&mut file_contents)?;
cur_link = Some(link_file);
os_impl::open_mapping(&String::from_utf8(file_contents)?)?
} else {
return Err(From::from("Cannot find unique os path since link_file is not set"));
}
}
};
self.lock_range_tree = IntervalTree::<usize>::new();
self.lock_data = Vec::with_capacity(2);
self.event_data = Vec::with_capacity(2);
if size_of::<MetaDataHeader>() > os_map.map_size {
return Err(From::from("Mapping is smaller than our metadata header size !"));
}
let mut cur_ptr = os_map.map_ptr as usize;
let meta_header: &mut MetaDataHeader = unsafe{&mut (*(cur_ptr as *mut MetaDataHeader))};
cur_ptr += size_of::<MetaDataHeader>();
self.size = meta_header.user_size as usize;
if (os_map.map_size as u64) < (meta_header.meta_size + meta_header.user_size) {
return Err(From::from(
format!("Shared memory header contains an invalid mapping size : (map_size: {}, meta_size: {}, user_size: {})",
os_map.map_size,
meta_header.user_size,
meta_header.meta_size)
));
}
let user_ptr = os_map.map_ptr as usize + meta_header.meta_size as usize;
for i in 0..meta_header.num_locks {
let lock_header: &mut LockHeader = unsafe{&mut (*(cur_ptr as *mut LockHeader))};
cur_ptr += size_of::<LockHeader>();
align_value(&mut cur_ptr, ADDR_ALIGN);
if cur_ptr > user_ptr {
return Err(From::from("Shared memory metadata is invalid... Not enought space to read lock header fields"));
}
let lock_type: LockType = match LockType::from_u8(lock_header.uid) {
Some(t) => t,
None => {
return Err(From::from(format!("Shared memory metadata contained invalid lock uid {}", lock_header.uid)));
}
};
println!("\tFound new lock \"{:?}\" : offset {} length {}", lock_type, lock_header.offset, lock_header.length);
self.add_lock_impl(lock_type, lock_header.offset as usize, lock_header.length as usize)?;
let new_lock: &mut GenericLock = self.lock_data.last_mut().unwrap();
new_lock.lock_ptr = cur_ptr as *mut c_void;
new_lock.data_ptr = (user_ptr + lock_header.offset as usize) as *mut c_void;
cur_ptr += new_lock.interface.size_of();
if cur_ptr > user_ptr {
return Err(From::from(
format!("Shared memory metadata is invalid... Trying to read lock {} of size 0x{:x} at address 0x{:x} but user data starts at 0x{:x}..."
, i, new_lock.interface.size_of(), cur_ptr, user_ptr)
));
}
new_lock.interface.init(new_lock, false)?;
}
for i in 0..meta_header.num_events {
let event_header: &mut EventHeader = unsafe{&mut (*(cur_ptr as *mut EventHeader))};
cur_ptr += size_of::<EventHeader>();
align_value(&mut cur_ptr, ADDR_ALIGN);
if cur_ptr > user_ptr {
return Err(From::from("Shared memory metadata is invalid... Not enough space for events"));
}
let event_type: EventType = match EventType::from_u8(event_header.uid) {
Some(t) => t,
None => {
return Err(From::from(format!("Shared memory metadata contained invalid event uid {}", event_header.uid)));
}
};
println!("\tFound new event \"{:?}\"", event_type);
self.add_event_impl(event_type)?;
let new_event: &mut GenericEvent = self.event_data.last_mut().unwrap();
if new_event.interface.size_of() == 0 {
new_event.interface.init(new_event, false)?;
continue;
}
new_event.ptr = cur_ptr as *mut c_void;
cur_ptr += new_event.interface.size_of();
if cur_ptr > user_ptr {
return Err(From::from(
format!("Shared memory metadata is invalid... Trying to read event {} of size 0x{:x} at address 0x{:x} but user data starts at 0x{:x}..."
, i, new_event.interface.size_of(), cur_ptr, user_ptr)
));
}
new_event.interface.init(new_event, false)?;
}
align_value(&mut cur_ptr, ADDR_ALIGN);
self.meta_size = cur_ptr - os_map.map_ptr as usize;
if cur_ptr != user_ptr {
return Err(From::from(format!("Shared memory metadata does not end right before user data ! 0x{:x} != 0x{:x}", cur_ptr, user_ptr)));
} else if self.meta_size as u64 != meta_header.meta_size {
return Err(From::from(format!("Shared memory metadata does not match what was advertised ! {} != {}", self.meta_size, meta_header.meta_size)));
}
Ok(SharedMem {
conf: self,
os_data: os_map,
user_ptr: user_ptr as *mut c_void,
link_file: cur_link,
})
}
#[inline]
pub fn get_link_path(&self) -> Option<&Path> {
let lpath = self.link_path.as_ref();
match lpath {
Some(pbuf) => Some(&**pbuf), None => None,
}
}
#[inline]
pub fn get_os_path(&self) -> Option<&str> {
let path = self.wanted_os_path.as_ref();
match path {
Some(pbuf) => Some(&**pbuf), None => None,
}
}
#[inline]
pub fn get_size(&self) -> usize {
self.size
}
#[inline]
pub fn get_metadata_size(&self) -> usize {
self.meta_size
}
#[inline]
pub fn num_locks(&self) -> usize {
self.lock_data.len()
}
#[inline]
pub fn num_events(&self) -> usize {
self.event_data.len()
}
#[doc(hidden)]
#[inline]
pub fn is_owner(&self) -> bool {
self.owner
}
#[doc(hidden)]
#[inline]
pub fn get_lock(&self, lock_index: usize) -> &GenericLock {
&self.lock_data[lock_index]
}
#[doc(hidden)]
#[inline]
pub fn get_event(&self, event_index: usize) -> &GenericEvent {
&self.event_data[event_index]
}
}