It is `*mut UnsafePinned<[u8]>` sound for shared mutating memory (in process or inter process)?

⚓ Rust    📅 2025-07-12    👤 surdeus    đŸ‘ī¸ 3      

surdeus

Shared memory is often useful in IPC or other lock-free data structures. But it is hard to use shared memory soundly without breaking the memory safety and aliasing rules.

Image we have a SeqLockWriter<T: zerocopy::IntoBytes>and SeqLockReader<T: zerocopy::TryFromBytes>[1] [2], we need to hold some form of &T or *T inside SeqLockReader<T> and some form of &mut T or *mut T inside SeqLockWriter simultaneously, because the memory region may be mutated by others, wrappers at at lease UnsafeCell-level is required, but the aliasing rules are still broken (when dereferencing the pointer).
So as the UnsafePinned make its way into nightly, can we soundly implement SeqLockWriter and SeqLockReader with it:

struct SeqLockWriter<T: zerocopy::IntoBytes> {
    seq: *const AtomicUsize,
    data: *mut UnsafePinned<[u8; size_of::<T>()]>,
}

struct SeqLockReader<T: zerocopy::TryFromBytes> {
    seq: *const AtomicUsize,
    data: *const UnsafePinned<[u8; size_of::<T>()]>,
}

, when the writer and reader are in the same process, or they are in different processes but the memory region of T is shared?

Assuming read-write race can be fixed by AtomicPerByte RFC or atomic-memcpy crate.

Related:
How unsafe is mmap? - #20 by newpavlov
Abstraction of shared memory
Ralf Jung's answer about UnsafeCell


  1. SeqLock is a reader-writer consistency mechanism with
    lockless readers (read-only retry loops), and no writer starvation. â†Šī¸Ž

  2. zerocopy::IntoBytes are required to opt-out the padding bytes which is unsound to read from. â†Šī¸Ž

1 post - 1 participant

Read full topic

đŸˇī¸ rust_feed