Repository navigation
zephyr: fix unsafe contracts found while documenting unsafe code - #4
Open
JPHutchins wants to merge 5 commits into
Open
JPHutchins wants to merge 5 commits into
JPHutchins wants to merge 5 commits into
Conversation
This was referenced Oct 28, 2026
`thread::ThreadStack::<SIZE>::new` is a safe `const fn`, but its doc carries a `# Safety` section that calls it unsafe. A zeroed stack is a valid value, and its memory is only ever handed to the kernel, so there is no contract for a caller to uphold. Keep the usage note that a stack belongs to a single thread. Assisted-by: Claude:claude-opus-5-5
`StaticKernelObject::<T>::new` is a `const unsafe fn` whose `# Safety` section argues that it is safe, and it has no contract a caller could uphold. Zero-filling `T` is sound for every `T` it can be called with. The `StaticKernelObject<T>: Wrapped` bound restricts `T`, and the orphan rule means only this crate can implement `Wrapped` for `StaticKernelObject<T>`. It does so only for C kernel objects (`k_thread`, `k_timer` and the static thread stack), for which all-zero bytes is the uninitialized state. Drop `unsafe` and the `# Safety` heading, keep the explanation, and move the soundness argument into the SAFETY comment on the zeroing. The exported `kernel_thread_define!` macro calls `new()` outside an `unsafe` block, so expanding it was an error before this change. No sample or test uses it. Callers that still wrap the call in `unsafe` get an `unused_unsafe` warning. Assisted-by: Claude:claude-opus-5-5
`Wrapped::get_wrapped` builds the Rust handle for a static kernel object and is meant to run once per object, from `StaticKernelObject::init_once`. It is a safe method of a public trait, so safe code can call it directly and skip the once-only check. For `StaticThread` that hands out two `Thread`s over the same `k_thread`, and for `StaticThreadStack` two `ThreadStack`s over the same stack. The safe `Thread::spawn` can then start two threads on one stack. Declare the method `unsafe` with a `# Safety` contract (at most one call per object). `init_once` upholds it through its compare-exchange on `init`. The three in-crate impls (k_thread, k_timer, the static thread stack) and the trait's doc example follow. Assisted-by: Claude:claude-opus-5-5
`ThreadData::acquire_old` is a safe `pub fn` that starts a thread on a caller-supplied `&'static ThreadStack`. Nothing stops the same stack from being passed to two `ThreadData`s, which runs two threads on one stack. Unlike `acquire`, it also does not take a stack from a pool. Declare it `unsafe` with the contract that no other thread may ever run on `stack`. Nothing in the tree calls it. Assisted-by: Claude:claude-opus-5-5
`GpioStatic::register` does `(*cb).pin_mask |= 1 << pin` from thread context while the GPIO callback handler does `&= !(1 << pin)` on the same plain `u32` from the ISR. The existing comments accept this as a benign race, but non-atomic concurrent access is a data race and therefore undefined behavior in Rust. On the C side, Zephyr's `gpio_fire_callbacks` also reads `pin_mask` without synchronization. Wrap both read-modify-writes in `critical_section::with` (irq_lock in this crate), as `install` already does for the rest of the callback struct. The ISR cannot interleave with the thread-side update, and nesting irq_lock inside the handler is allowed. Atomics on the Rust side alone would not help, because the C reader stays non-atomic. Only compile-checked: the module's only async GPIO test (tests/drivers/gpio-async) is restricted to rpi_pico. Assisted-by: Claude:claude-opus-5-5
JPHutchins
force-pushed
the
clippy/3-clippy-zephyr-target
branch
from
October 28, 2026 23:34
30a9fe7 to
365f6c2
Compare
JPHutchins
force-pushed
the
clippy/4-unsafe-contracts
branch
from
October 28, 2026 23:34
3461bca to
9d82edc
Compare
This was referenced Oct 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Warning
LLM Disclosure
This post was authored by claude-opus-5-5 on behalf of @JPHutchins. JP asked to bring zephyr-lang-rust under strict clippy rules matching embassy's (default groups,
-D warnings), to report deficiencies found along the way, and to open the work as a stacked series of review PRs on the intercreate fork.Five fixes to
unsafecontracts, found while documenting the crate's unsafe code:Wrapped::get_wrappedandThreadData::acquire_oldwere safe but could put two threads on one stack. Both are nowunsafe fns with a one-line contract.StaticKernelObject::newwasunsafewith a# Safetysection arguing it is safe. It is now safe.thread::ThreadStack::newis safe but documented itself as unsafe. The stale section is gone.pin_maskwas written from thread and ISR context without synchronization, a data race. Both updates now run undercritical_section::with.Important
Breaking:
Wrapped::get_wrappedandThreadData::acquire_oldare nowunsafe fn. Code callingStaticKernelObject::new()insideunsafenow gets anunused_unsafewarning.Stack, merge in order:
zephyrcrate passes the module's clippy flagsclippy_zephyrtarget and CIembedded_hal_async::digital::WaitforGpioPinCommits
7280dbba797czephyr: thread: drop the stale Safety section of ThreadStack::newda8e5087df38zephyr: object: make StaticKernelObject::new safe6f05ed706c6ezephyr: object: make Wrapped::get_wrapped an unsafe fn05f8e642c09czephyr: thread: make ThreadData::acquire_old an unsafe fn9d82edc1fb3dzephyr: device: gpio: serialize pin_mask updates with the ISRzephyr/src/object.rs#L288zephyr/src/thread.rs#L97zephyr/src/object.rs#L331The race, before:
zephyr/src/device/gpio.rs#L107; after:zephyr/src/device/gpio.rs#L144Testing
platform_allow. That covers the hello_world, blocking, embassy and philosopher samples and the time and timer tests.west build -t clippy_zephyrpasses on native_sim/native/64 (maximal, minimal and GPIO-only configs) and qemu_cortex_m0 (maximal).tests/drivers/gpio-async, allows only rpi_pico.Review notes
Also noticed, not changed:
Mutex::lock,Condvar::wait,Semaphore::takewith a timeout andsleepare safe and nothing stops them running in an ISR. A thread-context token would make that a compile error; JP likes this design, and it is a separate RFC.InitData.0ispub, but#[zephyr::thread]expansions read it, so it cannot become private without a macro change.kobj_define!arms cannot compile. TheStaticMutex/StaticCondvararms callnew()on types without aWrappedimpl, so expanding them fails.__penderaliasing. The embassy executor creates the pender pointer fromselfwhilerunholds&mut self.I2cTargetlifetime. For targets registered through the rawregister_target, nothing ties the config's lifetime toI2cTarget.