evering 0.1.0

Typed shared-memory communication across processes
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
use core::ptr::NonNull;
pub use nix::{
    libc::off_t,
    sys::mman::{MapFlags, ProtFlags},
    unistd,
};
use std::{
    os::fd::{AsFd, BorrowedFd, OwnedFd},
    path::{Path, PathBuf},
};

use crate::mem::{Access, Map, Request, Source};

#[cfg(feature = "process")]
pub mod process;

type Addr = usize;

fn shm_path<P: AsRef<Path> + ?Sized>(name: &P) -> PathBuf {
    const SHM_BASE: &str = "/dev/shm";
    const TMP_BASE: &str = "/tmp";
    let base = {
        let sbase = Path::new(SHM_BASE);
        if sbase.exists() {
            sbase
        } else {
            Path::new(TMP_BASE)
        }
    };

    base.join(name)
}

#[derive(Debug, Clone)]
enum FdKind {
    MemFd,
    Shm,
    FromFd,
}

pub struct UnixFd<F: AsFd> {
    fd: F,
    size: usize,
    kind: FdKind,
}

impl<F: AsFd> core::fmt::Debug for UnixFd<F> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("UnixFd")
            .field("size", &self.size)
            .field("fdkind", &self.kind)
            .finish()
    }
}

impl UnixFd<OwnedFd> {
    /// Creates an anonymous file in memory (memfd_create).
    pub fn memfd(name: &str, size: usize, sealing: bool) -> nix::Result<Self> {
        use nix::sys::memfd;
        let flags = if sealing {
            memfd::MFdFlags::MFD_ALLOW_SEALING
        } else {
            memfd::MFdFlags::empty()
        };

        let fd = memfd::memfd_create(name, flags)?;
        unistd::ftruncate(fd.as_fd(), size as off_t)?;
        Ok(Self {
            fd,
            kind: FdKind::MemFd,
            size,
        })
    }

    pub fn shm_create<P: AsRef<Path> + ?Sized>(name: &P, size: usize) -> nix::Result<Self> {
        use nix::fcntl;
        use nix::sys::stat;
        let path = shm_path(name);
        let oflags = fcntl::OFlag::O_RDWR
            .union(fcntl::OFlag::O_CREAT)
            .union(fcntl::OFlag::O_EXCL);
        let mode = stat::Mode::from_bits_truncate(0o600);
        let fd = fcntl::open(&path, oflags, mode)?;
        unistd::ftruncate(fd.as_fd(), size as off_t)?;
        Ok(Self {
            fd,
            kind: FdKind::Shm,
            size,
        })
    }

    pub fn shm_open<P: AsRef<Path> + ?Sized>(name: &P) -> nix::Result<Self> {
        use nix::fcntl;
        use nix::sys::stat;
        let path = shm_path(name);
        let fd = fcntl::open(&path, fcntl::OFlag::O_RDWR, stat::Mode::empty())?;
        let size = stat::fstat(fd.as_fd())?.st_size as usize;
        Ok(Self {
            fd,
            kind: FdKind::Shm,
            size,
        })
    }

    pub fn shm_unlink<P: AsRef<Path> + ?Sized>(name: &P) -> nix::Result<()> {
        let path = shm_path(name);
        unistd::unlink(&path)
    }

    pub fn from_fd(fd: OwnedFd) -> nix::Result<Self> {
        use nix::sys::stat;
        let size = stat::fstat(fd.as_fd())?.st_size as usize;
        Ok(Self {
            fd,
            kind: FdKind::FromFd,
            size,
        })
    }
}

impl<F: AsFd> UnixFd<F> {
    pub fn borrow(&self) -> UnixFd<BorrowedFd<'_>> {
        UnixFd {
            fd: self.fd.as_fd(),
            kind: self.kind.clone(),
            size: self.size,
        }
    }

    pub fn dup(&self) -> nix::Result<UnixFd<OwnedFd>> {
        let fd = unistd::dup(self.fd.as_fd())?;
        Ok(UnixFd {
            fd,
            kind: self.kind.clone(),
            size: self.size,
        })
    }

    pub fn as_fd(&self) -> BorrowedFd<'_> {
        self.fd.as_fd()
    }

    pub fn size(&self) -> usize {
        self.size
    }
}

impl const From<Access> for ProtFlags {
    fn from(value: Access) -> Self {
        let mut prot = ProtFlags::empty();
        if value.contains(Access::READ) {
            prot = prot.union(ProtFlags::PROT_READ);
        }
        if value.contains(Access::WRITE) {
            prot = prot.union(ProtFlags::PROT_WRITE);
        }
        if value.contains(Access::EXEC) {
            prot = prot.union(ProtFlags::PROT_EXEC);
        }
        prot
    }
}

pub struct FdMap<F: AsFd> {
    fd: UnixFd<F>,
    start: Option<Addr>,
    flags: MapFlags,
}

impl<F: AsFd> UnixFd<F> {
    pub fn mapping(self) -> FdMap<F> {
        FdMap {
            fd: self,
            start: None,
            flags: MapFlags::MAP_SHARED,
        }
    }
}

impl<F: AsFd> FdMap<F> {
    pub fn at(mut self, address: usize) -> Self {
        self.start = Some(address);
        self
    }

    pub fn with_flags(mut self, flags: MapFlags) -> Self {
        self.flags = flags;
        self
    }
}

unsafe fn release(start: NonNull<u8>, len: usize) -> bool {
    unsafe { nix::sys::mman::munmap(start.cast(), len) }.is_ok()
}

unsafe impl<F: AsFd> Source for FdMap<F> {
    type Error = nix::Error;

    fn map(self, request: Request) -> Result<Map, Self::Error> {
        use core::num::NonZeroUsize;
        use nix::sys::mman;

        let fd = self.fd.fd.as_fd();
        let fsize = nix::sys::stat::fstat(fd)?.st_size;
        let rsize = request.len as off_t;
        if fsize < rsize {
            unistd::ftruncate(fd, rsize)?;
        }

        let start = self.start.and_then(NonZeroUsize::new);
        let size = NonZeroUsize::new(request.len).ok_or(nix::Error::EINVAL)?;
        let access = request.access;

        unsafe {
            let ptr = mman::mmap(start, size, access.into(), self.flags, fd, 0)?;
            Ok(Map::from_raw_parts(ptr.cast(), size.get(), access, release))
        }
    }
}

unsafe impl<F: AsFd> Source for UnixFd<F> {
    type Error = nix::Error;

    fn map(self, request: Request) -> Result<Map, Self::Error> {
        self.mapping().map(request)
    }
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    use super::UnixFd;

    use crate::mem::{Access, Map, Request, Source};
    use crate::tests::MemBlkTestIO;

    use nix::libc::off_t;
    use nix::unistd;

    struct TestMap;

    impl TestMap {
        fn shared(
            self,
            size: usize,
            access: Access,
            fd: UnixFd<std::os::fd::OwnedFd>,
        ) -> nix::Result<Map> {
            fd.map(Request::new(size, access))
        }
    }

    #[test]
    fn memfd_rw() {
        const SIZE: usize = 4096;
        const NAME: &str = "fd";
        const VALUE: &[u8] = b"hello";

        let fd = UnixFd::memfd(NAME, SIZE, false).expect("should create");
        let blk = TestMap
            .shared(SIZE, Access::READ | Access::WRITE, fd)
            .expect("should create");

        unsafe {
            blk.write(VALUE);
            let buf = blk.read(VALUE.len());
            assert_eq!(buf, VALUE)
        }

        drop(blk);
    }

    #[test]
    fn memfd_resize() {
        const SIZE: usize = 1024;
        const GROW_SIZE: usize = SIZE * 4;
        const NAME: &str = "grow";
        const VALUE: &[u8] = b"hello";

        let fd = UnixFd::memfd(NAME, SIZE, false).expect("should create");
        let bk = TestMap;

        unistd::ftruncate(fd.as_fd(), GROW_SIZE as off_t).unwrap();

        let blk = bk
            .shared(GROW_SIZE, Access::READ | Access::WRITE, fd)
            .expect("should create");

        unsafe {
            blk.write(VALUE);
            let buf = blk.read(VALUE.len());
            assert_eq!(buf, VALUE)
        }

        drop(blk);
    }

    #[test]
    fn memfd_dup() {
        const SIZE: usize = 4096;
        const NAME: &str = "dup";
        const VALUE: &[u8] = b"hello";

        let fd1 = UnixFd::memfd(NAME, SIZE, false).expect("should create");
        let fd2 = fd1.dup().expect("should dup");

        let bk = TestMap;
        let blk1 = bk
            .shared(SIZE, Access::READ | Access::WRITE, fd1)
            .expect("should create");

        unsafe {
            blk1.write(VALUE);
        }

        drop(blk1);

        let bk2 = TestMap;
        let blk2 = bk2
            .shared(SIZE, Access::READ | Access::WRITE, fd2)
            .expect("should create");

        unsafe {
            let buf = blk2.read(VALUE.len());
            assert_eq!(&buf, VALUE)
        }

        drop(blk2);
    }

    #[test]
    fn shm_persist() {
        const NAME: &str = "shm_persist";
        const SIZE: usize = 4096;
        const VALUE: &[u8] = b"hello";

        let fd1 = UnixFd::shm_create(NAME, SIZE).expect("should create");
        let bk = TestMap;
        let blk1 = bk
            .shared(SIZE, Access::READ | Access::WRITE, fd1)
            .expect("should create");
        unsafe {
            blk1.write(VALUE);
        }
        drop(blk1);

        let fd2 = UnixFd::shm_open(NAME).expect("should open");
        let bk2 = TestMap;
        let blk2 = bk2
            .shared(SIZE, Access::READ | Access::WRITE, fd2)
            .expect("should create");
        unsafe {
            let buf = blk2.read(VALUE.len());
            assert_eq!(buf, VALUE)
        }
        drop(blk2);

        UnixFd::shm_unlink(NAME).expect("should unlink")
    }

    #[test]
    fn shm_unlink() {
        const NAME: &str = "shm_unlink";
        const SIZE: usize = 4096;
        const VALUE: &[u8] = b"hello";

        let fd = UnixFd::shm_create(NAME, SIZE).expect("should create");
        let bk = TestMap;
        let blk = bk
            .shared(SIZE, Access::READ | Access::WRITE, fd)
            .expect("should create");
        unsafe {
            blk.write(VALUE);
        }
        drop(blk);

        UnixFd::shm_unlink(NAME).expect("should unlink");
        assert!(UnixFd::shm_open(NAME).is_err())
    }

    #[test]
    fn zero_size() {
        const NAME: &str = "zero_size";
        const SIZE: usize = 1;

        let fd = UnixFd::shm_create(NAME, SIZE).expect("should create");
        let bk = TestMap;
        let res = bk.shared(0, Access::READ | Access::WRITE, fd);
        assert!(res.is_err());

        UnixFd::shm_unlink(NAME).expect("should unlink");
    }

    #[test]
    fn multiple_map() {
        const NAME: &str = "multi";
        const SIZE: usize = 1024;
        const VALUE: &[u8] = b"hello";
        const VALUE2: &[u8] = b"hello2";

        let fd1 = UnixFd::shm_create(NAME, SIZE).expect("should create");
        let fd2 = fd1.dup().expect("should dup");
        let blk1 = TestMap
            .shared(SIZE, Access::READ | Access::WRITE, fd1)
            .unwrap();
        let blk2 = TestMap
            .shared(SIZE, Access::READ | Access::WRITE, fd2)
            .unwrap();

        unsafe {
            blk1.write_in(VALUE, 0);
            blk2.write_in(VALUE2, VALUE.len());

            let buf1 = blk1.read_in(VALUE.len(), 0);
            let buf2 = blk2.read_in(VALUE2.len(), VALUE.len());
            assert_eq!(buf1, VALUE);
            assert_eq!(buf2, VALUE2);
        }

        drop(blk1);
        drop(blk2);
        let _ = UnixFd::shm_unlink(NAME);
    }
}