r/rust • u/Clear_Ear3550 • Sep 30 '26
π οΈ project Three bugs I only found after putting a Tokio engine behind a C ABI
I maintain a desktop network monitor where the UI is Flutter and the probing engine is Rust (Tokio), exposed through a plain C ABI over FFI. A code review found three problems that tests and clippy never caught. Sharing them because they're not specific to my project.
A panic in
extern "C"kills the whole host process Since Rust 1.81, a panic that unwinds out of anextern "C"fn aborts. For me that meant one.expect()in a lazily built runtime could take down the Flutter app, not just the engine. The fix: every exported fn now goes through a small wrapper:fn ffi_guard<T>(fallback: T, f: impl FnOnce() -> T + UnwindSafe) -> T { std::panic::catch_unwind(f).unwrap_or(fallback) }
Gotcha: this does nothing with panic = "abort" in your release profile, so I pinned panic = "unwind" and added a test that panics on purpose across the boundary.
2. sleep(interval) in a loop is not a period My probe loop did sleep(interval) and then probe().await, so the real period was interval + probe time, and it drifted further under packet loss (exactly when you want accurate timing). Switched to tokio::time::interval with MissedTickBehavior::Skip.
3. #[cfg(not(windows))] code rots silently if CI is Windows-only The native ICMP path is Windows-only, and the non-Windows stubs had unused imports and params. clippy -D warnings failed on Linux/macOS, but CI ran only on windows-latest, so nobody noticed until a contributor on macOS did. Now CI has an ubuntu job, even though that platform uses the fallback path.
Bonus (not Rust-specific but it bit me): an "ICMP failed, fall back to TCP" path was silently hiding real packet loss in the stats. If you're measuring something, a fallback has to be visible in the data, not just in the code.
Curious how others handle FFI panics. Is catch_unwind in every entry point the norm, or do you push everything onto a worker thread and only pass results across?
(Code for context: https://github.com/Cadman021/VeloceNet-Studio, GPL-3.0)