I have code which performs chunked reads of framed data via an (unsafe) ioctl call, with the following basic shape (after removing a load of additional validations, abstractions, etc):
let zeroes = Box::<[u8]>::new_zeroed_slice(frames.size()); // SAFETY: `\0` is valid as `u8` let mut buf = unsafe { zeroes.assume_init() }; let chunk_bufs = buf.chunks_mut(self.chunk_size()); for chunk_buf in chunk_bufs { // SAFETY: we own the underlying buffer, which is not moved and well-sized unsafe { ioctl_call(chunk_buf as *mut [u8] as *mut c_void, frames.count() }; } I'm adding a type-safe wrapper around the buffer that handles initialisation in a way that enforces invariants related to the size (must be a multiple of 2352 bytes) and provide helpful methods & traits for using the data later.
The wrapper needs to be Send (Sync would be nice) so that I can have one thread dedicated to long-running io and another to CPU-intensive and/or real-time processing once a full set of data is available.
With the above code it is easy to reason locally that the buffer will not move in memory while the ioctl loop is executing, so casting via a raw pointer is sound.
As I move the buffer type into a wrapper, that reasoning gets less local and the possibility for someone consuming the crate to try and use some form of multi-threaded or async approach which may lead to the whole thing being moved grows. (I can't think of a viable case myself, at the moment, but that isn't a good argument when it comes to soundness IMV
)
One option is to consider this "their problem" & document accordingly. Ideally, I'd like to enforce validity for the intended use case (buffer for slow, chunked, unsafe io via raw pointers) at a type-level.
- I'm not expecting the compiler to provide any guarantees that a
Box<[u8]>will not be moved, above those which are already available from ownership or holding an &mut. Am I being overly pessimistic? - Would adding a
Pinwrapper and forcingUnpinprovide meaningful guarantees at the cost of usability? ThePindocs are highly tailored towards async and only talk about pinning on the stack, I would need a pin on the heap
2 posts - 2 participants
![When is the memory location of `Box<[u8]>` guaranteed to remain stable?](https://emoji.discourse-cdn.com/twitter/wink.png?v=16)