Unsafe Rust and FFI
What `unsafe` unlocks, raw pointers, undefined behavior, calling C through FFI, and safe abstractions over unsafe code.
12 questions
JuniorCodeCommonChange a variable through a raw pointer — which of the steps actually needs unsafe?
Change a variable through a raw pointer — which of the steps actually needs unsafe?
Creating the pointers with &raw const x and &raw mut x is safe; only *p += 1 and the read of *p go in unsafe. That block asserts each pointer is non-null, aligned and points to a live i32, with no reference to x alive meanwhile.
Common mistakes
- ✗Putting pointer creation inside
unsafe, as if taking an address were dangerous - ✗Believing
unsafeswitches off borrow checking for the code inside the block - ✗Thinking two raw pointers to one value fail to compile the way two
&mutdo
Follow-up questions
- →Why can
&x as *const i32be wrong where&raw const xis fine, as for a packed struct field? - →What does
p.add(2)do, and when is merely computing it undefined behaviour?
MiddleTheoryCommonWhat exactly does unsafe unlock in Rust, and which checks stay switched on inside it?
What exactly does unsafe unlock in Rust, and which checks stay switched on inside it?
Five operations: dereferencing a raw pointer, calling an unsafe fn, accessing a static mut, implementing an unsafe trait and reading a union field. Types, ownership, borrows and lifetimes are checked inside unsafe as everywhere else.
Common mistakes
- ✗Believing
unsafeswitches off borrow checking or lifetime analysis - ✗Listing the creation of a raw pointer as an
unsafeoperation, though only dereferencing is - ✗Thinking indexing inside
unsafeskips the bounds check
Follow-up questions
- →How does an
unsafe fndiffer in meaning from anunsafeblock? - →Why does edition 2024 want an
unsafeblock inside the body of anunsafe fn?
SeniorDesignCommonA pull request adds a fast path to a parsing library: the public function get_column(row: &[u8], idx: usize) -> u8 now reads with unsafe { *row.get_unchecked(idx) } instead of row[idx], because a profile showed bounds checks in a hot loop. The author's comment says callers always pass an index taken from the header, which is shorter than every row. There is no // SAFETY: comment, and the crate has no Miri job in CI. Constraints: keep the speed-up if it is real; no safe caller, today or in the future, may be able to trigger undefined behaviour; the review must end with a decision the author can act on. Explain how you review this block: which invariant it relies on, where that invariant must be written down or enforced, whether the public function is sound as written, and what alternatives you would suggest.
A pull request adds a fast path to a parsing library: the public function get_column(row: &[u8], idx: usize) -> u8 now reads with unsafe { *row.get_unchecked(idx) } instead of row[idx], because a profile showed bounds checks in a hot loop. The author's comment says callers always pass an index taken from the header, which is shorter than every row. There is no // SAFETY: comment, and the crate has no Miri job in CI. Constraints: keep the speed-up if it is real; no safe caller, today or in the future, may be able to trigger undefined behaviour; the review must end with a decision the author can act on. Explain how you review this block: which invariant it relies on, where that invariant must be written down or enforced, whether the public function is sound as written, and what alternatives you would suggest.
It relies on idx < row.len(), which nothing enforces, so a safe caller can read out of bounds: the function is unsound. Enforce it with assert!, a type or iterators, or make it unsafe fn with # Safety; add // SAFETY:, a benchmark and Miri.
Common mistakes
- ✗Judging soundness by today's callers instead of by every possible safe call
- ✗Thinking
get_uncheckedpanics on a bad index the way ordinary indexing does - ✗Approving the block without a measured gain or a Miri run over its tests
Follow-up questions
- →When would you turn the function into an
unsafe fninstead of adding anassert!? - →How can one length check before the loop let the compiler drop the per-element bounds checks?
SeniorTheoryCommonWhat does safe Rust guarantee, what does it not, and why is the line drawn there?
What does safe Rust guarantee, what does it not, and why is the line drawn there?
Safe Rust rules out undefined behaviour: memory errors and data races. Leaks, deadlocks, logic bugs and wrapping overflow in release stay possible: their behaviour is defined, and leaks are reachable anyway through Rc cycles.
Common mistakes
- ✗Believing safe Rust prevents memory leaks, though
Rccycles andmem::forgetare safe - ✗Calling integer overflow in release undefined behaviour, though it wraps by definition
- ✗Expecting the compiler to rule out deadlocks between threads
Follow-up questions
- →Why is
std::mem::forgeta safe function? - →How do the
overflow-checksprofile setting and thechecked_*methods change overflow?
SeniorDesignCommonYour service links a C client library for a key-value store. A connection is an opaque kv_conn *; the library's documentation says a connection may be used from any thread, but never from two threads at the same time, and that kv_free must be called on it exactly once. You wrap it as struct Conn { raw: *mut kv_conn }, and now the compiler refuses to move a Conn into thread::spawn or to share an Arc<Conn> between worker threads, because *mut kv_conn is neither Send nor Sync. Constraints: a pool of 8 worker threads must be able to use connections; you cannot change the C library; any data race on a connection is a production incident. Decide what unsafe impl Send and unsafe impl Sync would each promise for Conn, which of them the library's guarantees justify, and how you would let all 8 threads use connections safely.
Your service links a C client library for a key-value store. A connection is an opaque kv_conn *; the library's documentation says a connection may be used from any thread, but never from two threads at the same time, and that kv_free must be called on it exactly once. You wrap it as struct Conn { raw: *mut kv_conn }, and now the compiler refuses to move a Conn into thread::spawn or to share an Arc<Conn> between worker threads, because *mut kv_conn is neither Send nor Sync. Constraints: a pool of 8 worker threads must be able to use connections; you cannot change the C library; any data race on a connection is a production incident. Decide what unsafe impl Send and unsafe impl Sync would each promise for Conn, which of them the library's guarantees justify, and how you would let all 8 threads use connections safely.
Send promises a Conn may move to another thread; Sync promises a &Conn may be used from two threads at once. The library allows any thread but no concurrent use, so implement only Send, and share through Mutex<Conn> or a connection pool.
Common mistakes
- ✗Adding
unsafe impl Syncjust to silence the compiler, as if it were a cast - ✗Confusing
Send, which moves ownership, withSync, which allows shared access at once - ✗Forgetting that
Arc<T>isSendonly whenTis bothSendandSync
Follow-up questions
- →What would change if the library required a connection to stay on the thread that opened it?
- →Why is
Mutex<T>SyncwhenTis onlySend?
MiddleDebuggingOccasionalFix a call that passes s.as_ptr() from a Rust &str to C's strlen
Fix a call that passes s.as_ptr() from a Rust &str to C's strlen
A &str has no trailing NUL, so strlen reads past its end: undefined behaviour. Declare unsafe extern "C", keep a CString::new(s).ok()? in a variable and pass its as_ptr(); a literal like c"hello" is already a &CStr.
Common mistakes
- ✗Believing Rust strings end with a NUL byte the way C strings do
- ✗Taking
as_ptr()from a temporaryCString, which is dropped at the end of the statement - ✗Thinking
unsafe externalone makes the call correct, when it only states a promise
Follow-up questions
- →How do you turn a
*const c_charreturned by C back into a RustStringsafely? - →Why does
strlenreturn 12 for the Russian word «привет» rather than 6?
MiddleTheoryOccasionalWhat does a reference &T guarantee that a raw pointer *const T does not?
What does a reference &T guarantee that a raw pointer *const T does not?
A &T is non-null, aligned, points to a live T, obeys borrowing rules for its lifetime, and is Send/Sync per T. A *const T is a bare address: maybe null or dangling, no lifetime or aliasing rules, neither Send nor Sync.
Common mistakes
- ✗Thinking a raw pointer obeys the borrowing rules or carries a lifetime
- ✗Assuming
*const TisSendandSyncwheneverTis - ✗Expecting a raw-pointer dereference to be validated at run time
Follow-up questions
- →What does
NonNull<T>add over*mut T, and what does it still not promise? - →Why can a
&Talways become a*const T, but not the other way round withoutunsafe?
SeniorTheoryOccasionalWhat do #[repr(C)], #[repr(transparent)], #[repr(packed)] and #[repr(u8)] each guarantee for FFI?
What do #[repr(C)], #[repr(transparent)], #[repr(packed)] and #[repr(u8)] each guarantee for FFI?
repr(C): C field order, alignment and padding. transparent: the layout and ABI of its one non-zero-sized field. packed: no padding, so fields may be misaligned and &p.field is rejected (E0793). repr(u8): a u8 enum discriminant.
Common mistakes
- ✗Assuming a plain Rust struct already has C field order
- ✗Taking a reference to a field of a packed struct, which would be misaligned
- ✗Thinking
repr(transparent)allows several non-zero-sized fields
Follow-up questions
- →How do you read a misaligned field of a
#[repr(C, packed)]struct without UB? - →Why can
Option<NonNull<T>>be passed to C as a nullable pointer?
SeniorTheoryOccasionalWhy is std::mem::transmute dangerous, and what safer alternatives exist?
Why is std::mem::transmute dangerous, and what safer alternatives exist?
It reinterprets bits, checking only that sizes match (E0512): a u8 of 2 as bool is UB, and non-repr(C) layouts are unspecified. Prefer as, from_ne_bytes or to_bits, TryFrom for validated values, or bytemuck for plain data.
Common mistakes
- ✗Believing any bit pattern is a valid value of any type, such as a
boolof 2 - ✗Expecting
transmuteto pad or truncate between types of different sizes - ✗Relying on the field layout of a struct without
#[repr(C)]
Follow-up questions
- →What does the plain-data marker trait
Podfrom the cratebytemuckrequire of a type? - →Why is transmuting a
&Tinto a&mut Talways undefined behaviour?
SeniorTheoryOccasionalWhat counts as undefined behaviour in Rust, and how far can the interpreter Miri detect it?
What counts as undefined behaviour in Rust, and how far can the interpreter Miri detect it?
Dangling, null or misaligned derefs, data races, a write under a live &T or a second &mut, invalid values like a bool of 2. Miri interprets tests and checks each step against Stacked or Tree Borrows, but only executed paths, not most C calls.
Common mistakes
- ✗Calling a leak, an overflow or a panic undefined behaviour, though their behaviour is defined
- ✗Treating a clean Miri run as proof that no input can trigger UB
- ✗Expecting Miri to check what happens inside calls to C libraries
Follow-up questions
- →Why can a program with UB pass every test in a debug build and break only in release?
- →Which patterns does the aliasing model Tree Borrows accept that Stacked Borrows rejects?
SeniorTheoryOccasionalWhy is UnsafeCell the only legal way to mutate through a &T, and what is built on it?
Why is UnsafeCell the only legal way to mutate through a &T, and what is built on it?
The compiler assumes data behind a live &T never changes and optimizes on it, so writing through a pointer cast from &T is UB. UnsafeCell<T> lifts that assumption; Cell, RefCell, Mutex, RwLock and atomics build on it.
Common mistakes
- ✗Casting
&Tto*mut Tand writing, believingunsafemakes it legal - ✗Thinking
UnsafeCellmakes its contents thread-safe, though it is notSync - ✗Believing
UnsafeCellallows two live&mut Tto its contents
Follow-up questions
- →Why is
UnsafeCell<T>notSync, and what mustMutexadd to becomeSync? - →What does
UnsafeCell::getreturn, and when is dereferencing it sound?
SeniorDesignOccasionalYou must expose a C image-decoding library to Rust code. Its header declares img_t *img_open(const char *path), which returns NULL on failure and sets a thread-local error code; img_frame_t *img_next_frame(img_t *), whose frame is owned by the image and invalidated by the next call; and void img_close(img_t *). A frame is the C struct { uint32_t width; uint32_t height; uint8_t *pixels; }. The library also takes a progress callback, a plain C function pointer, which it calls from inside img_next_frame. Constraints: users of your crate must never need unsafe; every image is closed exactly once, even on an early return; a frame must not be usable after the next frame is requested; a panic in the user's progress callback must not take the process down. Design the wrapper: its types, how NULL and errors are handled, who frees what, and how you deal with the callback.
You must expose a C image-decoding library to Rust code. Its header declares img_t *img_open(const char *path), which returns NULL on failure and sets a thread-local error code; img_frame_t *img_next_frame(img_t *), whose frame is owned by the image and invalidated by the next call; and void img_close(img_t *). A frame is the C struct { uint32_t width; uint32_t height; uint8_t *pixels; }. The library also takes a progress callback, a plain C function pointer, which it calls from inside img_next_frame. Constraints: users of your crate must never need unsafe; every image is closed exactly once, even on an early return; a frame must not be usable after the next frame is requested; a panic in the user's progress callback must not take the process down. Design the wrapper: its types, how NULL and errors are handled, who frees what, and how you deal with the callback.
Bind the API in unsafe extern "C" with #[repr(C)] structs; an owning Image calls img_close in Drop; NULL becomes Err; paths go in as CString; a frame borrows &mut Image; the callback trampoline runs user code in catch_unwind.
Common mistakes
- ✗Letting a frame outlive the next
img_next_framecall instead of tying its borrow to the image - ✗Passing a
&strpointer to C instead of a NUL-terminatedCString - ✗Letting a panic reach the C frames of a callback, which aborts the process
Follow-up questions
- →How would you pass a Rust closure as the progress callback through a
void *user-data pointer? - →Would you make
ImageSend, and what would you need to learn about the library first?