My account

Unsafe Rust and FFI

Safe Rust checks memory rules for you. An unsafe block lets you do five extra things the compiler cannot check, like reading a raw pointer or calling C code. It does not turn the borrow checker off. A specialist keeps unsafe code small, writes down why each block is correct, hides it behind a safe API, and is very careful about who owns memory at the border with C. Miri and a few lints help find mistakes.

Not reviewedWritten with AI helpReading time: 17 minOnline shop exampleRust 2024 edition

Author: bezzad

Contents

The problem: a C library from the shipping company

Our online shop ships parcels with a delivery company. The company gives us only a C library, called libparcel, to build shipping labels and tracking links. There is no Rust version. Its header file looks like this:

// Writes the label for an address into out.
// Returns the number of bytes written, or -1 on error.
int parcel_label(const char *address, char *out, size_t out_len);

// Returns a new string. Free it with parcel_free.
char *parcel_track_url(const char *parcel_id);
void parcel_free(char *s);

The Rust compiler cannot see inside this C code. It does not know if a pointer is valid, who frees the memory, or if the function keeps a pointer for later. So every call into C is unsafe: we, not the compiler, must promise that the rules are kept.

What unsafe allows

Inside an unsafe block or an unsafe function you can do five extra things:

  1. Dereference a raw pointer: read or write the memory it points to.
  2. Call an unsafe function, including every C function.
  3. Read or write a static mut value.
  4. Implement an unsafe trait, like Send or Sync by hand.
  5. Read a field of a union.

That is all. Unsafe does not turn off the borrow checker, type checks or lifetimes. A mutable reference inside an unsafe block still must be the only reference to its data. Unsafe only means: “the compiler cannot check this one thing, so I check it myself.”

If you break a rule in unsafe code, the result is undefined behavior (UB). The program may work today, crash tomorrow, or give wrong numbers only in release mode. The compiler is allowed to assume UB never happens, so the bug can show up far away from the real mistake.

Safe wrapper: the most important pattern

Shop codesafe onlymodule parcelpub fn label()1. check input3. check resultsafe APIunsafe block2. call C+ SAFETY commentlibparcelC codeThe compiler checks everything outside the yellow box. You check the yellow box.
The rest of the shop calls only the safe function. The unsafe block is small, sits in one module, and checks every input before it talks to C.

The goal is never “use unsafe everywhere”. The goal is: a small unsafe core, a safe API around it. Code that uses the API cannot cause UB, whatever it does. Such an API is called sound.

use std::ffi::{c_char, c_int, CString};

unsafe extern "C" {
    fn parcel_label(
        address: *const c_char,
        out: *mut c_char,
        out_len: usize,
    ) -> c_int;
}

pub fn label(address: &str) -> Result<Vec<u8>, LabelError> {
    // C strings end at the first zero byte, so it must not appear inside.
    let address = CString::new(address).map_err(|_| LabelError::NulByte)?;
    let mut out = vec![0u8; 512];

    // SAFETY: address is a valid C string and lives until the end of
    // this function. out is a writable buffer of out.len() bytes.
    // libparcel does not keep either pointer after it returns.
    let n = unsafe {
        parcel_label(address.as_ptr(), out.as_mut_ptr().cast(), out.len())
    };

    if n < 0 || n as usize > out.len() {
        return Err(LabelError::Library(n));
    }
    out.truncate(n as usize);
    Ok(out)
}
  1. Rust 2024 edition: an extern block must be written as unsafe extern. This reminds you that you promise the signatures are correct. A wrong signature is UB, and the compiler cannot see the header file.
  2. Check before the call: CString::new fails if the text has a zero byte inside. A C function would stop reading there.
  3. Check after the call: never trust a length that comes back from C. We check that n fits in the buffer.
  4. The SAFETY comment says which rules the block needs and why they hold. A reviewer checks this comment, not just the code. Clippy has a lint, undocumented_unsafe_blocks, that asks for it.
  5. Only the safe function is public. The raw C function stays private in this module.

Who owns the memory?

Rust sideC sideCString::newreads, does not keepRust drops itas_ptr()allocated by Rust, freed by Rustparcel_track_urlcopy into Stringparcel_freeallocated by C, freed by C
Memory must be freed by the side that allocated it. A string from libparcel goes back to parcel_free. A CString from Rust is dropped by Rust, after C has stopped using it.

Rust and C use different memory allocators. The most common FFI bugs are about ownership:

use std::ffi::{c_char, CStr, CString};

unsafe extern "C" {
    fn parcel_track_url(parcel_id: *const c_char) -> *mut c_char;
    fn parcel_free(s: *mut c_char);
}

pub fn track_url(parcel_id: &str) -> Option<String> {
    let id = CString::new(parcel_id).ok()?;

    // SAFETY: id is a valid C string that lives across the call.
    let raw = unsafe { parcel_track_url(id.as_ptr()) };
    if raw.is_null() {
        return None;
    }

    // SAFETY: libparcel returns a valid zero-ended string.
    // We copy it into a Rust String, then give it back to C.
    let url = unsafe { CStr::from_ptr(raw) }.to_string_lossy().into_owned();
    unsafe { parcel_free(raw) };
    Some(url)
}
  1. Memory from C goes back to C. Never free it with Rust (for example with CString::from_raw). Use the free function of the library.
  2. Memory from Rust goes back to Rust. If C must own a Rust string for a while, use CString::into_raw, and later CString::from_raw to take it back and drop it.
  3. Check for null. C uses a null pointer to say “no value” or “error”.
  4. Copy early. We copy the text into a String at once, so no Rust code holds a pointer into C memory after parcel_free.
  5. Lifetimes across the border: if a C function keeps a pointer (for example in a callback list), your Rust value must live at least as long. A pointer to a temporary value is the classic bug.

More rules at the border

  1. Structs: a struct shared with C needs #[repr(C)]. Without it, Rust may change the order of the fields.
  2. Panics: a panic must not cross into C. Since Rust 1.81, a panic that tries to leave an extern “C” function stops the process (abort). Catch it with std::panic::catch_unwind in callbacks, and return an error code.
  3. Exporting Rust to C: in the 2024 edition the no_mangle attribute is written as #[unsafe(no_mangle)], because a name clash can break the program.
  4. Do not write bindings by hand for a big header. bindgen generates Rust declarations from C headers. cbindgen does the opposite.
  5. Threads: a C library may not be thread safe. If the docs do not say it is, guard calls with a Mutex, and do not mark your wrapper Send or Sync by hand without proof.

Unsafe functions and unsafe traits

An unsafe function says: “the caller must keep some rules”. Write them in a Safety section of the docs:

/// Reads the price at index i without a bounds check.
///
/// # Safety
/// i must be smaller than prices.len().
pub unsafe fn price_unchecked(prices: &[u32], i: usize) -> u32 {
    // SAFETY: the caller promises i is in bounds.
    unsafe { *prices.get_unchecked(i) }
}
  1. In the 2024 edition, the body of an unsafe fn is not one big unsafe block anymore. The lint unsafe_op_in_unsafe_fn warns by default, so you still write small unsafe blocks with their own SAFETY comments.
  2. Measure first. A bounds check is often removed by the optimizer anyway. Use unchecked code only when a profile shows a real gain.
  3. An unsafe impl of Send or Sync is a promise to the whole program. Get it wrong and you bring back data races.

Tools that find UB

  1. Miri runs your tests in an interpreter that checks many memory rules: cargo +nightly miri test. It finds use after free, out of bounds reads and some aliasing bugs. It cannot run real C code, so test the Rust side with fake C functions.
  2. Sanitizers (AddressSanitizer, ThreadSanitizer on nightly) also check the C side while the program runs.
  3. Clippy lints like undocumented_unsafe_blocks and multiple_unsafe_ops_per_block keep unsafe blocks small and explained.
  4. cargo geiger and code search for the word unsafe show how much unsafe code a project and its dependencies have.

Common mistakes

Mistake Result Better way
CString::new(s).unwrap().as_ptr() in one line The CString is dropped at once, the pointer dangles. Keep the CString in a variable while C uses it.
Freeing C memory with Rust, or the other way Crash or memory damage. Free on the side that allocated it.
Big unsafe blocks with no comment No one can check the code. Small blocks, each with a SAFETY comment.
Public function that takes a raw pointer but is not unsafe Safe code can cause UB, so the API is not sound. Make it unsafe fn, or take a reference or slice.
Trusting lengths or pointers from C Out of bounds reads. Check null and lengths after every call.
Panic inside a callback called by C The process aborts. catch_unwind and return an error code.
unsafe impl Send for a wrapper of a C handle Data races if the library is not thread safe. Prove it from the docs, or guard with a Mutex.

Summary in 7 lines

  1. Unsafe allows five extra actions. It does not turn off the borrow checker.
  2. Breaking a rule in unsafe code is undefined behavior, which can show up anywhere.
  3. Keep unsafe code small, in one module, behind a sound, safe API.
  4. Every unsafe block gets a SAFETY comment. Every unsafe fn gets a Safety section.
  5. At the C border: check inputs, check null and lengths, and free memory on the side that allocated it.
  6. Use repr(C) for shared structs, never let a panic cross into C, and generate bindings with bindgen.
  7. Run Miri and the sanitizers on the tests of unsafe code.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.