Skip to main content

alef_component_abi/
producer.rs

1//! Producer-side helpers every generated component crate calls instead of carrying its own copy.
2//!
3//! Generated producers hand owned buffers, task handles and static descriptor tables across the
4//! C boundary. The code for that is identical in every producer, so it lives here once, where it
5//! is documented and tested, rather than being pasted into each generated `src/lib.rs`.
6
7use crate::{AlefOwnedBuffer, AlefStatus, AlefTaskV1};
8use alloc::boxed::Box;
9use alloc::string::{String, ToString};
10use alloc::sync::Arc;
11use alloc::vec::Vec;
12use core::any::Any;
13use core::ffi::c_void;
14use core::fmt;
15use core::mem::ManuallyDrop;
16use core::sync::atomic::{AtomicBool, Ordering};
17
18/// A `static`-friendly wrapper for an immutable C table that carries raw pointers.
19///
20/// Component descriptors ([`AlefComponentV1`](crate::AlefComponentV1)) and generated contract
21/// tables hold raw pointers, which makes them `!Sync`, so they cannot be plain `static`s. Before
22/// this wrapper existed producers declared them `static mut` purely to get past that check. The
23/// wrapper restores an ordinary immutable `static`: the value is only ever read, and the
24/// constructor's safety contract is what makes sharing it between threads sound.
25#[repr(transparent)]
26pub struct SyncStatic<T>(T);
27
28// SAFETY: `SyncStatic::new` requires the wrapped value to be immutable plain data whose raw
29// pointers refer to immutable, process-lifetime data (or are null); `SyncStatic` exposes no
30// mutation, so concurrent shared reads from any thread are sound.
31unsafe impl<T> Sync for SyncStatic<T> {}
32
33impl<T> SyncStatic<T> {
34    /// Wrap `value` for use in a `static`.
35    ///
36    /// # Safety
37    ///
38    /// `value` must be safe to read concurrently from any thread for the life of the process: it
39    /// has no interior mutability, and every raw pointer it holds is null or points to immutable
40    /// data that lives for the rest of the process (string literals, other statics, functions).
41    #[must_use]
42    pub const unsafe fn new(value: T) -> Self {
43        Self(value)
44    }
45
46    /// The wrapped value.
47    #[must_use]
48    pub const fn get(&self) -> &T {
49        &self.0
50    }
51
52    /// A raw pointer to the wrapped value, valid for the life of a `static` wrapper.
53    #[must_use]
54    pub const fn as_ptr(&self) -> *const T {
55        &raw const self.0
56    }
57}
58
59/// The `free` callback of every buffer [`owned_buffer`] produces.
60///
61/// # Safety
62///
63/// `ptr`, `len` and `capacity` must be the parts of one buffer [`owned_buffer`] produced, and the
64/// buffer must be released exactly once. A null `ptr` is ignored.
65pub unsafe extern "C" fn free_owned_buffer(_context: *mut c_void, ptr: *mut u8, len: usize, capacity: usize) {
66    if !ptr.is_null() {
67        // SAFETY: the caller contract says these are the parts of a `Vec<u8>` `owned_buffer`
68        // leaked, released once.
69        drop(unsafe { Vec::from_raw_parts(ptr, len, capacity) });
70    }
71}
72
73/// Hand `bytes` across the boundary as an [`AlefOwnedBuffer`] the receiver releases through the
74/// buffer's own `free` callback ([`free_owned_buffer`]).
75#[must_use]
76pub fn owned_buffer(bytes: Vec<u8>) -> AlefOwnedBuffer {
77    let mut bytes = ManuallyDrop::new(bytes);
78    AlefOwnedBuffer {
79        ptr: bytes.as_mut_ptr(),
80        len: bytes.len(),
81        capacity: bytes.capacity(),
82        context: core::ptr::null_mut(),
83        free: Some(free_owned_buffer),
84    }
85}
86
87/// An owned buffer holding `message` as UTF-8, for a producer's `out_error`.
88#[must_use]
89pub fn error_buffer(message: impl fmt::Display) -> AlefOwnedBuffer {
90    owned_buffer(message.to_string().into_bytes())
91}
92
93/// Copy an owned buffer's bytes into a `Vec<u8>` and release the original allocation through its
94/// own `free` callback.
95///
96/// This is the receiving side of [`owned_buffer`]: hosts call it on a component's results, and
97/// components on buffers the host returns from a service call.
98///
99/// # Safety
100///
101/// `buffer` must be a valid `AlefOwnedBuffer`: `ptr` must be non-null and valid for `len` bytes
102/// whenever `len > 0`, and `free` (if present) must be safe to call with this buffer's own
103/// `context`, `ptr`, `len`, and `capacity`. The buffer must not be used again afterwards.
104#[must_use]
105pub unsafe fn take_owned_bytes(buffer: AlefOwnedBuffer) -> Vec<u8> {
106    let bytes = if buffer.ptr.is_null() || buffer.len == 0 {
107        Vec::new()
108    } else {
109        // SAFETY: upheld by this function's caller contract.
110        unsafe { core::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec()
111    };
112    if let Some(free) = buffer.free {
113        // SAFETY: upheld by this function's caller contract.
114        unsafe { free(buffer.context, buffer.ptr, buffer.len, buffer.capacity) };
115    }
116    bytes
117}
118
119/// Best-effort text of a caught panic payload (`&'static str` or `String`).
120#[must_use]
121pub fn panic_message(payload: &(dyn Any + Send)) -> String {
122    if let Some(message) = payload.downcast_ref::<&'static str>() {
123        String::from(*message)
124    } else if let Some(message) = payload.downcast_ref::<String>() {
125        message.clone()
126    } else {
127        String::from("non-string panic payload")
128    }
129}
130
131/// An [`AlefTaskV1`] whose `cancel` sets `cancelled` and whose `drop` releases the task's own
132/// reference to it.
133///
134/// A producer's async wrapper keeps a clone of `cancelled`, checks it before starting the work,
135/// and owns nothing else about the handle: the host calls `cancel` and `drop` through the task.
136#[must_use]
137pub fn cancel_flag_task(cancelled: Arc<AtomicBool>) -> AlefTaskV1 {
138    AlefTaskV1 {
139        struct_size: core::mem::size_of::<AlefTaskV1>(),
140        context: Box::into_raw(Box::new(cancelled)).cast(),
141        start: None,
142        cancel: Some(cancel_flag),
143        drop: Some(drop_cancel_flag),
144    }
145}
146
147/// # Safety
148///
149/// `context` must be null or the context of a live task [`cancel_flag_task`] built.
150unsafe extern "C" fn cancel_flag(context: *mut c_void) -> AlefStatus {
151    if context.is_null() {
152        return AlefStatus::INVALID_ARGUMENT;
153    }
154    // SAFETY: a non-null context is the `Box<Arc<AtomicBool>>` `cancel_flag_task` leaked, and the
155    // task has not been dropped yet.
156    unsafe { &*context.cast::<Arc<AtomicBool>>() }.store(true, Ordering::Release);
157    AlefStatus::OK
158}
159
160/// # Safety
161///
162/// `context` must be null or the context of a task [`cancel_flag_task`] built, dropped once.
163unsafe extern "C" fn drop_cancel_flag(context: *mut c_void) {
164    if !context.is_null() {
165        // SAFETY: a non-null context is the `Box<Arc<AtomicBool>>` `cancel_flag_task` leaked, and
166        // the host drops each task once.
167        drop(unsafe { Box::from_raw(context.cast::<Arc<AtomicBool>>()) });
168    }
169}
170
171/// Construct a component implementation, preferring [`FromHost`](crate::FromHost) when the type
172/// implements it and falling back to [`Default`].
173///
174/// Expands to the autoref-specialization call over [`Construct`](crate::Construct), with both
175/// candidate traits in scope, so generated producers need neither import nor lint allowance.
176#[macro_export]
177macro_rules! construct_component {
178    ($implementation:ty, $host:expr) => {{
179        #[allow(unused_imports, reason = "only one of the two traits applies to a given type")]
180        use $crate::{ConstructDefault as _, ConstructFromHost as _};
181        #[allow(clippy::needless_borrow, reason = "the borrow selects the `Default` fallback")]
182        let value: $implementation = (&$crate::Construct::<$implementation>::new()).construct($host);
183        value
184    }};
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::{AlefComponentV1, AlefStr, FromHost, HostApi};
191
192    #[test]
193    fn owned_buffer_round_trips_through_take_owned_bytes() {
194        let buffer = owned_buffer(alloc::vec![1, 2, 3]);
195        assert!(buffer.free.is_some());
196        // SAFETY: `buffer` was just built by `owned_buffer` and is consumed once.
197        assert_eq!(unsafe { take_owned_bytes(buffer) }, [1, 2, 3]);
198        // SAFETY: an empty buffer with no `free` is valid and needs no release.
199        assert!(unsafe { take_owned_bytes(AlefOwnedBuffer::EMPTY) }.is_empty());
200    }
201
202    #[test]
203    fn error_buffer_holds_the_display_text() {
204        let buffer = error_buffer(format_args!("bad {}", 7));
205        // SAFETY: `buffer` was just built by `owned_buffer` and is consumed once.
206        assert_eq!(unsafe { take_owned_bytes(buffer) }, b"bad 7");
207    }
208
209    #[test]
210    fn free_owned_buffer_ignores_null() {
211        // SAFETY: a null pointer is documented as ignored.
212        unsafe { free_owned_buffer(core::ptr::null_mut(), core::ptr::null_mut(), 0, 0) };
213    }
214
215    #[test]
216    fn panic_message_reads_str_and_string_payloads() {
217        let text: Box<dyn Any + Send> = Box::new("static");
218        assert_eq!(panic_message(&*text), "static");
219        let owned: Box<dyn Any + Send> = Box::new(String::from("owned"));
220        assert_eq!(panic_message(&*owned), "owned");
221        let other: Box<dyn Any + Send> = Box::new(7_u8);
222        assert_eq!(panic_message(&*other), "non-string panic payload");
223    }
224
225    #[test]
226    fn cancel_flag_task_sets_the_shared_flag_and_releases_its_reference() {
227        let cancelled = Arc::new(AtomicBool::new(false));
228        let task = cancel_flag_task(Arc::clone(&cancelled));
229        assert_eq!(Arc::strong_count(&cancelled), 2);
230        let cancel = task.cancel.expect("cancel callback");
231        let drop_task = task.drop.expect("drop callback");
232        // SAFETY: `task` is live and its context came from `cancel_flag_task`.
233        assert_eq!(unsafe { cancel(task.context) }, AlefStatus::OK);
234        assert!(cancelled.load(Ordering::Acquire));
235        // SAFETY: as above; a null context is rejected rather than dereferenced.
236        assert_eq!(unsafe { cancel(core::ptr::null_mut()) }, AlefStatus::INVALID_ARGUMENT);
237        // SAFETY: the task is dropped exactly once.
238        unsafe { drop_task(task.context) };
239        assert_eq!(Arc::strong_count(&cancelled), 1);
240    }
241
242    const ID: &[u8] = b"demo";
243
244    // SAFETY: every pointer in the descriptor is null or points at the `ID` literal.
245    static DESCRIPTOR: SyncStatic<AlefComponentV1> = unsafe {
246        SyncStatic::new(AlefComponentV1 {
247            struct_size: core::mem::size_of::<AlefComponentV1>(),
248            abi_major: 1,
249            abi_minor: 0,
250            component_id: AlefStr {
251                ptr: ID.as_ptr().cast(),
252                len: ID.len(),
253            },
254            component_version: AlefStr::EMPTY,
255            contract_hash: [0; 32],
256            feature_set_hash: [0; 32],
257            contract: core::ptr::null(),
258            contract_size: 0,
259            create: None,
260            destroy: None,
261        })
262    };
263
264    #[test]
265    fn sync_static_is_a_transparent_plain_static() {
266        assert_eq!(
267            core::mem::size_of::<SyncStatic<AlefComponentV1>>(),
268            core::mem::size_of::<AlefComponentV1>()
269        );
270        assert_eq!(DESCRIPTOR.as_ptr(), core::ptr::from_ref(DESCRIPTOR.get()));
271        assert_eq!(DESCRIPTOR.get().component_id.len, 4);
272    }
273
274    #[derive(Default)]
275    struct OnlyDefault(u8);
276
277    struct Configured(bool);
278
279    impl FromHost for Configured {
280        fn from_host(host: &HostApi) -> Self {
281            Self(host.has_log())
282        }
283    }
284
285    #[test]
286    fn construct_component_prefers_from_host_and_falls_back_to_default() {
287        let host = HostApi::detached();
288        let configured = construct_component!(Configured, &host);
289        assert!(!configured.0);
290        let fallback = construct_component!(OnlyDefault, &host);
291        assert_eq!(fallback.0, 0);
292    }
293}