blob: 68cbd65368f4a3b7f229c4f5f163c5a4b697ff52 [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Verification-friendly `#![no_std]` Zircon port reactor mirroring Fuchsia's
//! `fuchsia_async::LocalExecutor` + `PacketReceiver` layer.
//!
//! Provides a slice-backed [`Executor`] and parametric [`ReceiverSlot`] table
//! with zero heap allocation, zero panics, and RAII handle-ownership invariants:
//!
//! - [`Executor`]: owns a [`Port`] and borrows `&'a mut [ReceiverSlot]`,
//! providing [`Executor::new`], [`Executor::register`],
//! [`Executor::close_all`], and [`Executor::run_singlethreaded`], with RAII
//! [`Drop`] closing every active slot and the port on any exit path.
//! - [`find_free_slot`]: pure read-only 0B-frame leaf returning `Some(idx)` for
//! the first invalid slot in `slots`, or `None`.
//! - [`arm_slot`]: arms a one-shot `zx_object_wait_async` wait on `port` for
//! `handle` with `key` and `signals`.
//! - [`register_slot`]: finds a free slot, arms `handle` on `port`, and stores
//! the [`ReceiverSlot`] entry; closes `handle` cleanly via RAII on failure.
//! - [`close_all`] / [`run_singlethreaded`]: convenience wrappers over
//! [`Executor::from_parts`].
//! - [`timer`]: virtualized cooperative guest timers ([`Timer`], [`sleep_until`]).
#![no_std]
pub mod timer;
use vx_types::{ZX_PKT_TYPE_SIGNAL_ONE, ZX_TIME_INFINITE, ZX_WAIT_ASYNC_ONCE};
pub use timer::{Timer, sleep_until};
pub use vx_zx::{AsHandleRef, Channel, Handle, HandleRef, NullableHandle, Port, Signals, Status};
/// Action returned by a [`PacketReceiverFn`] callback after handling a packet.
#[repr(u32)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum PacketAction {
/// Close the slot's handle and free the slot.
Close = 0,
/// Re-arm the same handle and signals on the port.
Rearm = 1,
/// Stop the single-threaded executor loop cleanly.
Stop = 2,
}
/// Packet receiver callback invoked when an armed handle fires on `port`.
///
/// A receiver may also register new handles into `slots` using [`register_slot`].
pub type PacketReceiverFn = fn(
port: &Port,
slots: &mut [ReceiverSlot],
slot_idx: usize,
handle: HandleRef<'_>,
observed: Signals,
ctx: *mut u8,
) -> PacketAction;
/// Entry in the executor's parametric packet-receiver table (`24` bytes,
/// `8`-byte aligned for `+strict-align`).
///
/// `handle.is_invalid()` marks an empty slot.
#[repr(C)]
pub struct ReceiverSlot {
pub handle: NullableHandle,
pub signals: Signals,
pub receiver: Option<PacketReceiverFn>,
pub ctx: *mut u8,
}
impl ReceiverSlot {
/// Empty (zeroed) slot sentinel.
pub const EMPTY: Self = Self {
handle: NullableHandle::invalid(),
signals: Signals::NONE,
receiver: None,
ctx: core::ptr::null_mut(),
};
/// Close any owned handle and reset this slot to [`ReceiverSlot::EMPTY`].
#[inline(always)]
pub fn clear(&mut self) {
drop(self.handle.take());
self.signals = Signals::NONE;
self.receiver = None;
self.ctx = core::ptr::null_mut();
}
}
const _: () = assert!(core::mem::size_of::<ReceiverSlot>() == 24);
const _: () = assert!(core::mem::align_of::<ReceiverSlot>() == 8);
const _: () = assert!(core::mem::offset_of!(ReceiverSlot, handle) == 0);
const _: () = assert!(core::mem::offset_of!(ReceiverSlot, signals) == 4);
const _: () = assert!(core::mem::offset_of!(ReceiverSlot, receiver) == 8);
const _: () = assert!(core::mem::offset_of!(ReceiverSlot, ctx) == 16);
/// Single-threaded Zircon port reactor owning a [`Port`] and borrowing a
/// caller-supplied [`ReceiverSlot`] table.
///
/// Closes every remaining active slot handle and the port automatically on
/// [`Drop`].
pub struct Executor<'a> {
slots: &'a mut [ReceiverSlot],
port: Port,
}
impl Drop for Executor<'_> {
#[inline(always)]
fn drop(&mut self) {
for slot in self.slots.iter_mut() {
slot.clear();
}
}
}
impl<'a> Executor<'a> {
/// Create a fresh [`Port`], clear all entries in `slots` to
/// [`ReceiverSlot::EMPTY`], and return a new [`Executor`].
#[curry::verified]
pub fn new(slots: &'a mut [ReceiverSlot]) -> Result<Self, Status> {
let port = Port::create()?;
for slot in slots.iter_mut() {
slot.clear();
}
Ok(Self { slots, port })
}
/// Construct an [`Executor`] from an existing [`Port`] and pre-initialized
/// `slots` slice.
#[inline(always)]
pub fn from_parts(port: Port, slots: &'a mut [ReceiverSlot]) -> Self {
Self { slots, port }
}
/// Borrow the underlying Zircon [`Port`].
#[inline(always)]
pub const fn port(&self) -> &Port {
&self.port
}
/// Borrow the underlying [`ReceiverSlot`] slice.
#[inline(always)]
pub fn slots(&mut self) -> &mut [ReceiverSlot] {
self.slots
}
/// Register `handle` into the first free slot, arming it on this
/// executor's port with key equal to the slot index and `signals`.
#[curry::verified]
pub fn register(
&mut self,
handle: Handle,
signals: Signals,
receiver: PacketReceiverFn,
ctx: *mut u8,
) -> Result<usize, Status> {
register_slot(&self.port, self.slots, handle, signals, receiver, ctx)
}
/// Close every valid handle in `slots` (clearing each slot to
/// [`ReceiverSlot::EMPTY`]) and close the port.
#[curry::verified]
pub fn close_all(self) {
drop(self);
}
/// Run the single-threaded Zircon port reactor over `self`.
///
/// Loops `port.wait(ZX_TIME_INFINITE)`. For each packet with
/// `key < slots.len()` whose slot is active (`!handle.is_invalid()` and
/// `receiver == Some(f)`), invokes `f(&port, slots, idx, h_ref, observed, ctx)`:
/// - [`PacketAction::Stop`]: exits the loop cleanly (`Ok(())`).
/// - [`PacketAction::Rearm`]: re-arms the slot's current handle and signals
/// (clearing and closing the slot if re-arm fails).
/// - [`PacketAction::Close`]: closes the slot's handle and clears the slot.
///
/// Closes all remaining active slot handles and the port before returning.
#[curry::verified]
pub fn run_singlethreaded(self) -> Result<(), Status> {
loop {
let pkt = self.port.wait(ZX_TIME_INFINITE)?;
if pkt.pkt_type != ZX_PKT_TYPE_SIGNAL_ONE {
continue;
}
let observed = Signals::from_bits_retain(pkt.signal.observed);
if let Ok(idx) = usize::try_from(pkt.key)
&& let Some(slot) = self.slots.get_mut(idx)
{
if !slot.handle.is_invalid() {
if let Some(recv) = slot.receiver {
let ctx = slot.ctx;
// Move the handle out into a local binding for the duration of `recv` so
// `h_ref` can never dangle even if `recv` clears `slots[idx]`, while
// keeping `slot.receiver` non-`None` so `find_free_slot` will not reuse
// `idx` while `recv` is executing.
let owned_handle = slot.handle.take();
let action = recv(
&self.port,
self.slots,
idx,
owned_handle.as_handle_ref(),
observed,
ctx,
);
match action {
PacketAction::Stop => {
drop(owned_handle);
break;
}
PacketAction::Rearm => {
if let Some(slot_after) = self.slots.get_mut(idx)
&& slot_after.handle.is_invalid()
&& slot_after.receiver.is_some()
{
let sig = slot_after.signals;
if arm_slot(
&self.port,
owned_handle.as_handle_ref(),
idx as u64,
sig,
)
.is_ok()
{
slot_after.handle = owned_handle;
} else {
drop(owned_handle);
slot_after.clear();
}
} else {
drop(owned_handle);
}
}
PacketAction::Close => {
drop(owned_handle);
if let Some(slot_after) = self.slots.get_mut(idx)
&& slot_after.handle.is_invalid()
{
slot_after.clear();
}
}
}
} else {
slot.clear();
}
}
}
}
Ok(())
}
}
/// Return `Some(idx)` for the first empty (`handle.is_invalid()` and
/// `receiver.is_none()`) slot in `slots`, or `None` if all slots are occupied.
///
/// Pure read-only leaf (zero writes, zero stack frame).
#[curry::verified]
pub fn find_free_slot(slots: &[ReceiverSlot]) -> Option<usize> {
slots.iter().position(|slot| slot.handle.is_invalid() && slot.receiver.is_none())
}
/// Arm a one-shot `zx_object_wait_async` on `handle` delivering packets to
/// `port` with `key` and `signals`.
#[curry::verified]
pub fn arm_slot(
port: &Port,
handle: HandleRef<'_>,
key: u64,
signals: Signals,
) -> Result<(), Status> {
handle.wait_async(port, key, signals, ZX_WAIT_ASYNC_ONCE)
}
/// Find a free slot in `slots`, arm `handle` on `port` with key equal to the
/// slot index, and store `(handle, signals, receiver, ctx)` into the slot.
///
/// Returns `Ok(idx)` (`< slots.len()`) on success, or `Err(status)` on failure
/// (`Status::NO_RESOURCES` if full, or the `zx_object_wait_async` error), closing
/// `handle` cleanly via RAII on every error path.
#[curry::verified]
pub fn register_slot(
port: &Port,
slots: &mut [ReceiverSlot],
handle: Handle,
signals: Signals,
receiver: PacketReceiverFn,
ctx: *mut u8,
) -> Result<usize, Status> {
let idx = find_free_slot(slots).ok_or(Status::NO_RESOURCES)?;
arm_slot(port, handle.as_handle_ref(), idx as u64, signals)?;
let Some(slot) = slots.get_mut(idx) else {
return Err(Status::NO_RESOURCES);
};
slot.handle = handle.into();
slot.signals = signals;
slot.receiver = Some(receiver);
slot.ctx = ctx;
Ok(idx)
}
/// Close every valid handle in `slots` (clearing each slot to
/// [`ReceiverSlot::EMPTY`]), then drop `port`.
#[curry::verified]
pub fn close_all(port: Port, slots: &mut [ReceiverSlot]) {
Executor::from_parts(port, slots).close_all();
}
/// Run the single-threaded Zircon port reactor over `port` and `slots`.
///
/// Convenience wrapper around [`Executor::from_parts`] and
/// [`Executor::run_singlethreaded`].
#[curry::verified]
pub fn run_singlethreaded(port: Port, slots: &mut [ReceiverSlot]) -> Result<(), Status> {
Executor::from_parts(port, slots).run_singlethreaded()
}