Skip to content

zephyr: fix unsafe contracts found while documenting unsafe code - #4

Open
JPHutchins wants to merge 5 commits into
clippy/3-clippy-zephyr-targetfrom
clippy/4-unsafe-contracts
Open

JPHutchins wants to merge 5 commits into
clippy/3-clippy-zephyr-targetfrom
clippy/4-unsafe-contracts

Conversation

@JPHutchins

@JPHutchins JPHutchins commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

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 unsafe contracts, found while documenting the crate's unsafe code:

  • Wrapped::get_wrapped and ThreadData::acquire_old were safe but could put two threads on one stack. Both are now unsafe fns with a one-line contract.
  • StaticKernelObject::new was unsafe with a # Safety section arguing it is safe. It is now safe.
  • thread::ThreadStack::new is safe but documented itself as unsafe. The stale section is gone.
  • The GPIO callback's pin_mask was written from thread and ISR context without synchronization, a data race. Both updates now run under critical_section::with.

Important

Breaking: Wrapped::get_wrapped and ThreadData::acquire_old are now unsafe fn. Code calling StaticKernelObject::new() inside unsafe now gets an unused_unsafe warning.

Stack, merge in order:

  1. ci: run the build and docs workflows on pull requests to any branch #5: CI on pull requests to any branch
  2. zephyr-build, zephyr-macros: pass clippy -D warnings #1: host crates pass clippy
  3. zephyr: pass the module's clippy flags #2: the zephyr crate passes the module's clippy flags
  4. cmake: lint the zephyr crate with a clippy_zephyr target #3: clippy_zephyr target and CI
  5. zephyr: fix unsafe contracts found while documenting unsafe code #4: unsafe-contract fixes (this PR)
  6. zephyr: device: gpio: implement embedded-hal-async digital::Wait #6: embedded_hal_async::digital::Wait for GpioPin
Commits
Testing
  • twister on this PR's head: 17 of 17 executed configurations passed on qemu_cortex_m3, qemu_cortex_m0 and native_sim/native/64. 43 configurations were filtered by platform_allow. That covers the hello_world, blocking, embassy and philosopher samples and the time and timer tests.
  • west build -t clippy_zephyr passes on native_sim/native/64 (maximal, minimal and GPIO-only configs) and qemu_cortex_m0 (maximal).
  • The GPIO race fix is only compile-checked. The module's one async GPIO test, tests/drivers/gpio-async, allows only rpi_pico.
  • Not run: RISC-V, Hexagon, or any hardware.

Review notes

Also noticed, not changed:

  • Thread-only calls are callable from ISRs. Mutex::lock, Condvar::wait, Semaphore::take with a timeout and sleep are 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.0 is pub, but #[zephyr::thread] expansions read it, so it cannot become private without a macro change.
  • Two kobj_define! arms cannot compile. The StaticMutex/StaticCondvar arms call new() on types without a Wrapped impl, so expanding them fails.
  • __pender aliasing. The embassy executor creates the pender pointer from self while run holds &mut self.
  • I2cTarget lifetime. For targets registered through the raw register_target, nothing ties the config's lifetime to I2cTarget.

`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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant