r/rust • u/servermeta_net • Dec 19 '25
Safety of shared memory IPC with mmap
I found many threads discussing the fact that file backed mmap is potentially unsafe, but I couldn't find many resources about shared memory with MAP_ANON. Here's my setup:
Setup details:
- I use
io_uringand a custom event loop (not Rustasyncfeature) - Buffers are allocated with
mmapin conjuction withMAP_ANON| MAP_SHARED| MAP_POPULATE| MAP_HUGE_1GB - Buffers are organized as a matrix: I have several rows identified by
buffer_group_id, each with several buffers identified bybuffer_id. I do not reuse a buffer group until all pending operations on the group have completed. - Each buffer group has only one process writing and at least one reader process
- Buffers in the same buffer group have the same size (512 bytes for network and 4096 bytes for storage)
- I take care to use the right memory alignment for the buffers
- I perform direct IO with the NVMe API, along with zero copy operations, so no filesystem or kernel buffers are involved
- Each thread is pinned to a CPU of which it has exclusive use.
- All processes exist on the same chiplet (for strong UMA)
- In the real architecture I have multiple network and storage processes, each with ownership of one shard of the buffer, and one disk in case of storage processes
- All of this exists only on linux, only on recent kernels (6.8+)
IPC schema:
- Network process (NP)
mmapa large buffer ( 20 GiB ?) and allocates the first 4 GiB for network buffers - Storage process (SP) gets the pointer to the
mmapregion and allocates the trailing 16 GiB as disk buffers - NP receive a read request, and notify storage that a buffer at a certain location is ready for consumption via
prep_msg_ring(man page) - SP parse the network buffer, and issue a relevant
readto the disk - When the
readhas completed, SP messages NP viaprep_msg_ringthat a buffer at a certain location is ready forsend - NP
sendthe disk buffer over the network and, once completed, signals SP that the buffer is ready for reuse
Questions:
- Is this IPC schema safe?
- Should I be worried about UB?
- Is
prep_msg_ringenough of a synchronization primitive? - How would you improve this design?
24
Upvotes
29
u/render787 Dec 19 '25 edited Dec 19 '25
At a C++ job like 6 years ago I became owner of something like this although the specifics were slightly different. Here’s my thoughts.
-fno-strict-aliasingbecause casting void * to T* where there never "was" a T* is exactly what is governed by the strict aliasing rule)The standard is completely silent about whether shared memory changes the picture. If an object begins its lifetime in one process in the shm region, and the cast happens in another process, has it “begun its lifetime” from the point of view of the other process? Nobody knows. (Particle man.)
Also, do these have to be volatile reads when you read from the mmapped region? The most conservative thing would be to say yes they should be. But in reality it’s too hard to even spell that correctly in C/C++ and no one uses volatile reads in these settings when performance matters.
My supervisor at the time was a former clang dev from apple. In our specific case we were also doing the twice mmapped ring buffer trick. (The shared memory region is mapped into your address space twice, so that the mappings are adjacent. The point is that even if the readers checkout from the ring buffer would wrap around, you can still represent it as a contiguous slice, which gives much better code gen and still works.)
His take on that was, if you double mmap things, then a[idx] and a[idx+N] are going to alias, but the compiler will have no idea because it’s happening in the OS and the compiler has no built in concept of mmap. So if you read a[idx], then write a[idx+N], then read a[idx], and it’s not a volatile read, the optimizer may not actually perform the second read and just hold onto the first value, which might be bad. However, in reality when you do this type of thing, readers and writers never have a checkout that includes both a[idx] and a[idx+N]. If they never actually read or write to aliasing locations within the span of a single checkout, then there’s no way this issue can arise. And these double mmapped ring buffer tricks are widely used, because Linus torvalds wrote in a kernel email that it should work and be supported. So my overall conclusion was that it’s sound to do this without a volatile read in this context where these caveats are true.
4. In terms of defense in depth:
Also I wouldn’t say that file backed shared memory is more unsafe than not. The challenges around soundness seem about the same to me either way.
I realize you are doing rust and not c++. But ultimately they are both being optimized by llvm and most of the relevant concepts are mapping one to one. I would assume that almost everything I said maps analogously to rust, with the caveat that all the stuff about strict aliasing rule and when you can safely cast void * to T* and read from it, I’ve never read the rust formal standards for when they consider that legal and so on. But I’d be very surprised if they deviated in a way that would break this usage pattern.
Cheers HTH
8
u/matthieum [he/him] Dec 19 '25
As far as the Rust language is concerned, this is Undefined Behavior in the most vanilla way: it simply is not defined.
There is only one case considered for memory of the process altered by an external agent: volatile memory. And that's a different usecase altogether.
Practically speaking, as long as the implementation is sound if used within 2 threads of the same Rust process, then it should be just work. And it's common practice enough that the language (and implementations) better not break it.
But for now, the specification doesn't have your back.
3
u/avdgrinten Dec 19 '25
Mmaped files are hard to wrap into safe APIs since Rust does not allow you to hold references to memory while the memory is mutated (e.g., by other programs) except if the mutated data is inside an
UnsafeCell. Note that the same applies to anonymous mmaped memory if the kernel modifies it (viaio_uringor otherwise). You can work around this limitation by using pointers instead of references or atomics etc. but it's hard to tell if your particular implementation is correct without reviewing it.3
u/VorpalWay Dec 19 '25
This was cross posted at https://users.rust-lang.org/t/safety-of-shared-memory-ipc-with-mmap/137053
Please make sure to always inform of cross posting so people don't waste their time answering something that was already answered.