Safe Rust FFI: Ownership Boundaries, Error Mapping, and ABI Tests
Rust's FFI (Foreign Function Interface) with C is powerful but treacherous due to Rust's ownership model clashing with C's manual memory management. The goal is safety: no use-after-free, leaks, double-frees, or UB. Use std::ffi::{CString, CStr}, libc, #[repr(C)], and explicit ownership contracts. Always generate headers with cbindgen and test exhaustively.
1. Ownership Boundaries
Rust owns nothing across the FFI boundary by default. Define explicit contracts:
- Inputs: Borrowed (
*const T, *const T + usize len). Rust validates before passing.
- Outputs: Callee allocates (Rust
Box::into_raw), caller frees via explicit free func. Or vice versa (caller allocs via malloc, Rust consumes).
- No Rust types: Only primitives (
c_int, c_char, *mut c_void), #[repr(C)] structs/enums.
- Strings: Null-terminated (
*mut c_char) or length-prefixed.
- Slices:
*const T + *mut usize for len (out-param).
Best Practices
- Pair alloc/free: Export
my_alloc, my_free.
- Use
MaybeUninit for zeroed init.
- Avoid
Vec/String directly: Convert explicitly.
Example: Safe Vec-like API
// lib.rs
use std::ffi::{c_char, c_int, CStr, CString};
use std::mem;
use std::ptr::{self, NonNull};
#[repr(C)]
pub struct MyVec {
data: *mut c_int,
len: usize,
cap: usize,
}
#[no_mangle]
pub extern "C" fn myvec_new() -> *mut MyVec {
Box::into_raw(Box::new(MyVec {
data: ptr::null_mut(),
len: 0,
cap: 0,
}))
}
#[no_mangle]
pub extern "C" fn myvec_push(vec: *mut MyVec, val: c_int) -> c_int {
unsafe {
let vec = &mut *vec;
if vec.len == vec.cap {
let new_cap = vec.cap * 2 + 1;
let new_data = libc::realloc(vec.data as *mut _, new_cap * mem::size_of::<c_int>()) as *mut c_int;
if new_data.is_null() { return -1; } // OOM
vec.data = new_data;
vec.cap = new_cap;
}
*vec.data.add(vec.len) = val;
vec.len += 1;
0
}
}
#[no_mangle]
pub extern "C" fn myvec_free(vec: *mut MyVec) {
if vec.is_null() { return; }
unsafe {
if !(*vec).data.is_null() {
libc::free((*vec).data as *mut _);
}
drop(Box::from_raw(vec));
}
}
C Usage (ownership transfers to C):
MyVec* v = myvec_new();
myvec_push(v, 42);
myvec_free(v); // Must call!
Why Safe? Explicit free prevents leaks. No hidden ownership.
2. Error Mapping
Rust's Result doesn't cross FFI. Map to:
- Error codes:
c_int (0=OK, negative=error).
- Out-params: Results via pointers.
- errno: Set
libc::errno for POSIX.
Use enums for typed errors, map via as c_int.
Best Practices
- Define
#[repr(C)] pub enum ErrorCode { Ok=0, InvalidInput=-1, OutOfMemory=-2, ... }.
- Custom error:
thiserror + into_raw mapping.
- Panic=abort:
panic=abort in [lib] to avoid unwinding across FFI.
Example: Error-Mapped String Dup
use std::ffi::{c_char, c_int, CString};
use std::ptr;
#[repr(C)]
pub enum DupError {
Ok = 0,
NullInput = -1,
InvalidUtf8 = -2,
OutOfMemory = -3,
}
#[no_mangle]
pub extern "C" fn str_dup(input: *const c_char, out_len: *mut usize) -> *mut c_char {
unsafe {
if input.is_null() {
*libc::errno() = libc::EINVAL as i32;
return ptr::null_mut();
}
let cstr = CStr::from_ptr(input);
match cstr.to_str() {
Ok(s) => {
let cstring = CString::new(s).unwrap(); // or map OOM
let ptr = CString::into_raw(cstring);
*out_len = cstr.to_bytes().len();
ptr
}
Err(_) => ptr::null_mut(),
}
}
// Return NULL + check errno or out_len=0
}
#[no_mangle]
pub extern "C" fn str_dup_error(input: *const c_char) -> c_int {
unsafe {
if input.is_null() { return DupError::NullInput as c_int; }
let cstr = CStr::from_ptr(input);
match cstr.to_str() {
Ok(_) => DupError::Ok as c_int,
Err(_) => DupError::InvalidUtf8 as c_int,
}
}
}
C Usage:
size_t len;
char* dup = str_dup("hello", &len); // NULL on error
if (dup) { free(dup); }
int err = str_dup_error(NULL); // -1
3. ABI Tests
ABI stability: Ensure lib signature doesn't change (layout, calling convention). Rust doesn't guarantee ABI stability, so test it.
Tools & Methods
- cbindgen:
cargo install cbindgen, generate include/my.h.
- cc + cargo test: Link C test harness.
- abitest crate: Automated ABI diffs.
- Manual: Compile lib, dump symbols (
nm), compare.
- wasm-bindgen/uniffi: For higher-level bindings.
Example Test Setup
Cargo.toml:
[dev-dependencies]
cc = "1.0"
abitest = "0.1" # Or similar
tests/ffi.rs:
#[test]
fn test_ffi() {
cc::Build::new()
.file("tests/ffi.c") // C test using your FFI
.compile("ffi");
// Run via `extern crate ffi;`
}
#[test]
fn abi_stable() {
abitest::test_abi("target/debug/libyourlib.so", "abi-stable.json");
}
tests/ffi.c:
#include "../include/my.h" // From cbindgen
#include <assert.h>
int main() {
MyVec* v = myvec_new();
assert(myvec_push(v, 42) == 0);
myvec_free(v);
return 0;
}
Run: cargo test --test ffi.
Cross-Compilation
Test on target: cargo test --target x86_64-unknown-linux-gnu.
Additional Best Practices & Tools
- Panic Safety:
#[no_mangle] pub extern "C" fn ... { std::panic::catch_unwind(...).unwrap_or_default() } (but prefer panic=abort).
- Threading:
extern "C" fn is Send+Sync; use std::sync::Mutex if needed.
- Zero-Copy:
bytemuck for POD types.
- Full Bindings: uniffi for Kotlin/Swift/Python.
- CI: GitHub Actions with multiple Rust/toolchain versions.
- Debug:
RUST_LOG=trace cargo test; Valgrind/ASan.
This setup ensures zero-cost abstractions with ironclad safety. For production, audit with Miri (cargo miri test) and fuzz with cargo-fuzz. Questions on specifics?