Safe Rust deleted an Xila window, returned Ok(()), and left another owner holding its corpse. Core issue #661 records the bug: deleting a top-level window through &mut Lvgl left OwnedWindow and the Wasm host holding raw pointers to freed memory. The next event could use it again. A supposedly safe call had become a use-after-free with excellent manners.
Then the harmless setter arrived. lv_obj_set_hidden can move focus to a dropdown, whose handler opens its list and reparents it. The generated access table classifies that setter as exclusive because the path reaches lv_obj_remove_child. The button was hiding. The object tree was rearranging furniture.
I hit this while building Xila, an open source operating system for microcontrollers with an LVGL interface. Calculator and Clock run as WebAssembly on an ESP32-S3 board, in a browser and on Linux, as shown by the board and browser examples. I am building an operating system for microcontrollers, and the button lifetime got promoted to a kernel concern. Today, C deletes that button and Rust keeps the wreckage typed.
The bug that compiles
This hypothetical raw-pointer wrapper compiles, then calls LVGL with a freed child.
// Hypothetical naive binding. The pointer is not a lifetime proof.
#[allow(non_camel_case_types)]
type lv_obj_t = core::ffi::c_void;
struct Widget(*mut lv_obj_t);
unsafe extern "C" {
fn lv_obj_delete(obj: *mut lv_obj_t);
fn lv_obj_set_hidden(obj: *mut lv_obj_t, hidden: bool);
}
unsafe fn broken(panel: *mut lv_obj_t, button: Widget) {
unsafe {
lv_obj_delete(panel); // LVGL also frees button.
lv_obj_set_hidden(button.0, false); // Use after free.
}
}
lvgl_rust makes the dangerous interval visible to the borrow checker. Its compile-fail case keeps a view, runs timer_handler that may delete objects, then uses the view.
use lvgl_rust::{Lvgl, LvglAccess};
struct Guard;
unsafe impl LvglAccess for Guard {}
fn main() {
let mut guard = Guard;
let mut lv = Lvgl::enter(&mut guard).unwrap();
let screen = lv.screen_active().unwrap();
lv.timer_handler();
let _ = screen.child(0);
}
The exact command was DEP_LV_CONFIG_PATH=$HOME/.cache/xila-scratch/blog-rust-c-ownership/compile-config CARGO_BUILD_JOBS=4 CARGO_TARGET_DIR=$HOME/.cache/xila-scratch/blog-rust-c-ownership/target-rustc-197 LVGL_RUST_HANDLE_SLOTS=32 cargo +1.97.0 test --locked --test compile_fail -- --ignored. Rust 1.97 rejected the case with E0502:
error[E0502]: cannot borrow `lv` as mutable because it is also borrowed as immutable
--> tests/compile-fail/view_after_timer_handler.rs:14:5
|
13 | let screen = lv.screen_active().unwrap();
| -- immutable borrow occurs here
14 | lv.timer_handler();
| ^^ mutable borrow occurs here
15 | let _ = screen.child(0);
| ------ immutable borrow later used here
The handler variant gets E0596 when shared callback access tries to call the exclusive timer handler. The compiler is now the one holding the funeral clipboard.
A child disappears with its parent
LVGL is a C library for building interfaces. It arranges widgets in a tree. A screen contains a panel, the panel contains a button, and the button can contain a label. Delete the panel and LVGL frees the descendants. That is useful when closing a window. It is less useful when Rust still has a reference to the button.
The obvious wrapper puts an LVGL pointer in a Rust value. A consuming destructor prevents use after explicit deletion, but LVGL can delete the panel while the button wrapper remains in a valid Rust variable. The pointer looks unchanged after the funeral.
Tying the button to a Rust parent wrapper rules out some sequences. The parent can still be alive when LVGL tears the panel down. Rust enforces the lifetime you declare. Proving that C respects it is your job, and C never signed the contract.
Find every way the tree can change
I started with deletion and found that the API name was a lousy witness.
An animated screen change can delete the old screen. A message box can close itself. A timer can run code that deletes a widget. A C function can call a handler synchronously, then resume at its next instruction. Any pointers saved before that call remain on its stack. This can all happen on one thread. A mutex can keep out another thread while the current thread ruins its own afternoon. The object lifetime guide and event handler guide describe those boundaries.
There is a second problem. A call can invalidate an internal pointer without deleting a widget. Reparenting removes an entry from one parent’s children array and adds it to another’s. A C function still walking the original array may hold a pointer into storage that changed. I had to account for those changes too. Deletion was only the loudest failure.
The generator audits LVGL’s call graph. It follows event dispatch and records paths to removing a child or freeing an object. It also flags C code that keeps a pointer into a region across an event dispatch. An ordinary setter can therefore move to the exclusive interface. Your callers find out at compile time, before production finds out for you. The access model explains the decision.
Split a view from an identity
I wanted to set properties while building an interface and remember a widget between passes through the event loop. Those jobs need different types.
A view such as &Obj or &Label borrows access to LVGL. Its Rust type is zero-sized, and the reference carries the C object’s address. The setter can use that address directly. The borrow blocks anything that could invalidate the view until its final use. One lookup then serves a whole run of compatible calls. That is why a view costs nothing. The view implementation is deliberately small.
A Handle<W> is an identity I can keep between sessions. It stores a slot index plus one in the low 16 bits and the slot generation in the high 16 bits. The slot holds the pointer and its current generation. get checks the slot before lending a view tied to the current session. A Handle<Label> also checks the object’s class. If LVGL deleted the widget, lookup returns Error::Dead. The handle never extends the widget’s lifetime. Keeping the number is easy. Getting the widget back is conditional. The handle layout and registry lookup show the details.
The registry is a fixed array of slots kept in static memory. LVGL calls lv_obj_free_id during destruction, including for every descendant it tears down. The binding uses LVGL’s object ID field to find a tracked slot. Freeing a slot advances its generation, so a stale handle fails even if the allocator reuses the same address. An outstanding Owned wrapper keeps its slot marked dead until the owner releases it. The registry returns Error::RegistryFull when it runs out. The 16-bit generation can wrap after 65,536 reuses of one slot. An old handle can then resolve to a different live object of a compatible class. C keeps one last escape hatch, naturally. The destructor and invalidation code connect the two sides.
Choose shared and exclusive calls
The borrow is from the whole LVGL session. A deletion can cross object boundaries, so checking whether I have a mutable borrow of one button misses the point. I use &Lvgl for operations compatible with live views, including getters and some setters. Deleting, cleaning, reparenting and running timers need exclusive access. An ObjMut<'_, W> borrows that exclusive access for one widget. Its delete(self) consumes the wrapper. The session and exclusive widget access implement that split.
Here is a working sketch using the real API. I copy out the fact I need before timers can change the tree.
use lvgl_rust::Lvgl;
fn run_tick(lvgl: &mut Lvgl) -> Option<(bool, u32)> {
let screen = lvgl.screen_active()?;
let had_children = screen.child(0).is_some();
let next_tick_ms = lvgl.timer_handler();
Some((had_children, next_tick_ms))
}
The binding gets its session from a guard supplied by the program. The unsafe LvglAccess implementation promises serialized, non-recursive access with synchronization between holders. In other words, it behaves like a mutex guard turned into a type. The session borrows that guard and takes no lock itself. Raw FFI calls, meaning calls from Rust into C, must follow the same rules. The Rust types enforce the safe half. The unsafe half is a promise you make, not a proof you get. The guard contract states it directly.
In Xila, the graphics subsystem opens a session from its process-wide graphics lock. GraphicsGuard::with_lvgl lends a &mut Lvgl to a synchronous closure. Creating or deleting a window requires exclusive session access. Reading its pending event needs shared access only. Some raw LVGL calls remain under the same lock. The method signature shows the access requirement, which beats leaving the lock in a comment and hoping everybody reads it.
Defer callback work
Giving every operation exclusive access would simplify the audit. It would also make handlers spectators at their own events.
An ordinary event handler gets shared access through Event::lv(). LVGL may still be walking the event list or holding pointers from its own work. For draw and layout queries it hands over only the event’s typed parameter. The C frame can hold memory that even a shared setter would replace, so those handlers get nothing else. The event access tiers document the difference.
A shared handler can request deletion with obj.delete_later(). For a normal registered object, pending work lives as a flag on a registry slot. The method takes a temporary slot if the widget has none. The drain, a pass that runs pending deletions and posted work, processes the flag at session entry and around timer_handler, where the binding has exclusive access. A successful request can make a handle lookup fail before LVGL frees the object. If a parent deletion takes out a queued child first, the destructor updates the slot and the drain finds no live child to delete. The request code and drain code make the timing explicit.
The same arrangement lets an Owned<W> request deletion when its Rust owner drops, even outside a session. It records work for the drain. For other tasks, a handler can use Lvgl::post to queue a small function and its data. That function receives exclusive access when it runs. The callback asks for demolition. The crew waits until the building is empty. The owned handle and posted work cover the two queues.
Measure the registry and test the lifetime rules
The numbers below are my own run on a clean checkout: lvgl_rust main at c8bde00b, LVGL 9.6.0, Rust 1.97.0. The host is an Intel Core i7-1370P running Debian 13 on x86-64, kernel 6.12.117. Cargo runs the bench profile, which is optimized like release, with the heap feature and the crate’s vendored LVGL config header, at the default 32 handle slots. Each time is the median of 21 batch averages after warm-up. The safe and raw samples alternate, so both paths see the same machine load. The benchmark source defines the method. Trust me bro, the laptop was awake.
| Operation | Safe path | Raw path |
|---|---|---|
set_ext_click_area through a view |
1.8 ns | 1.8 ns |
| Resolve a handle and call the setter | 4.8 ns | 1.8 ns for the setter |
Resolve Handle<Obj> |
3.4 ns | Already holds the pointer |
Resolve Handle<Label> |
4.2 ns | Already holds the pointer |
| Dispatch to a handler without captures | 29.4 ns | 26.4 ns |
| Create and defer deletion until the next session | 1,986.6 ns | 1,581.8 ns to create and delete directly |
The table’s punchline is blunt: 1.8 ns safe equals 1.8 ns raw. Rust brought a borrow checker to a tie.
Resolve a handle once, then use the view while its borrow permits it. The deferred deletion row includes a session per operation and object creation in both paths. It does not measure how long an application waits for its next drain. These are host timings. They say nothing about the time an ESP32 spends pushing pixels. The microcontroller remains unimpressed.
The size reference builds for thumbv6m-none-eabi, the ARMv6-M target of a Cortex-M0, with Arm GCC 14.2.1 on the C side. It uses the repository’s size profile: opt-level = "s", and LTO off, since LTO merges code at link time. The gate counts symbols in one linked image. These are the totals the committed feature reference prints, object ID hooks included; the generated overhead page prints slightly different code bytes for the same rows. The size gate contains the command.
| Configuration | Binding code and read-only data | Zero-initialized RAM (.bss) |
Initialized RAM (.data) |
|---|---|---|---|
| 16 handle slots | 4,878 B | 188 B | 0 B |
| Views only | 2,610 B | 44 B | 0 B |
The handle build uses 152 of its 188 bytes for the registry. The posted-function queue uses the other 36. The views-only build has an 8-byte registry header and the same queue. Code and read-only data live in flash on a microcontroller. The handle build also reserves a 4-byte ID field per LVGL object on this target, including objects without a handle. The size gate measures one linked program, with the operations that program uses.
At runtime, the parent deletion test confirms that child and grandchild handles come back Error::Dead. The timer case, handler case and parent deletion test are all in the repository.
use lvgl_rust::{Error, Lvgl, LvglAccess, Obj, WidgetExt};
fn check_parent_deletion(guard: &mut impl LvglAccess) {
let mut lv = Lvgl::enter(guard).unwrap();
let parent = Obj::create_owned(&mut lv.screen_active_mut().unwrap()).unwrap();
let child = Obj::create(&mut parent.get_mut(&mut lv).unwrap())
.unwrap()
.handle()
.unwrap();
let grandchild = Obj::create_owned(&mut child.get_mut(&mut lv).unwrap()).unwrap();
parent.delete(&mut lv).unwrap();
assert_eq!(child.get(&lv).err(), Some(Error::Dead));
assert_eq!(grandchild.get(&lv).err(), Some(Error::Dead));
}
Sources
The object lifetime, access model, overhead, feature reference, Core PR #626, and decisions 0041 and 0067 contain the design and measurements.
Conclusion
Why not the existing lvgl-rs? It provides typed wrappers with PhantomData, explicit raw lv_obj_del calls, and callback closures that reconstruct a widget from LVGL’s raw event target. Its Widget::from_raw contract leaves pointer lifetime responsibility with the caller. The maintained rs_lvgl line targets LVGL 9.6, reconciles and deletes UI subtrees, and queues native callback actions instead of running application updates in C callbacks. Those bindings are useful thin wrappers. lvgl_rust adds audited shared and exclusive access, generation-checked handles, and deferred callback work because this project needed the compiler to police arbitrary tree mutations. Thin wrappers are fast. So are thin ice sheets.
When a foreign library owns an object tree, list everything that can change it while your wrapper is alive. Qt’s guarded pointer and GObject’s strong reference answer different questions about what survives. Here I needed both: a handle to ask whether a widget still exists later, and a view to protect it during a call. SDL has the same trap when SDL_DestroyRenderer frees every texture with the renderer. The SDL renderer documentation states that ownership rule.
Back to the opening: delete the panel and C buries the button. With a view and a handle, Rust at least knows the funeral happened. Keep access and identity in separate types. Let the C library keep its ownership rules, and give Rust something it can enforce.
The binding is lvgl_rust. Start with documentation/explanation/object-lifetime.md and access-model.md, then read Xila Core PR #626 and browse the Xila organization. If your C UI has ever freed something you still pointed at, those references are a useful place to begin. This has been Rust trying to keep the button alive. See you in the next article.