Skip to main content

weaveffi/rt/
callback.rs

1//! Consumer-implemented callback interfaces: the producer half of the ABI's
2//! vtable contract.
3//!
4//! A callback-interface argument is one [`CallbackArg`] (`{prefix}_{Cb}` in
5//! C): a `void* ctx` the consumer owns and a pointer to its vtable. Every
6//! vtable starts with the same header ([`VtableHeader`]: its `size`, its
7//! `flags`, and the `free(ctx)` release hook), followed by one function
8//! pointer per method, in declaration order. The
9//! `#[weaveffi::callback_interface]` expansion wraps the argument in a
10//! [`ForeignCallback`], implements the producer's trait on it, and hands
11//! the producer an `Arc<dyn Trait>`. When the last `Arc` drops,
12//! [`ForeignCallback`] calls `free(ctx)` exactly once.
13//!
14//! **Vtables are open.** A consumer generated from an older contract passes
15//! a shorter vtable (its `size` says how long), and a newer one may pass
16//! methods this producer doesn't know. The producer accepts any vtable whose
17//! header is complete; calling a method past the consumer's `size` (or one
18//! whose entry is null) fails that call with [`FOREIGN_ERROR_CODE`] and a
19//! message naming the method, so appending a method never breaks a deployed
20//! binding.
21//!
22//! A vtable whose `flags` include [`VTABLE_THREAD_AFFINE`] may only have its
23//! value-returning methods called on the thread that passed it in (a Dart
24//! isolate's callbacks, say); called from another thread, such a method
25//! fails with [`FOREIGN_ERROR_CODE`] and [`OFF_THREAD_MESSAGE`] without
26//! calling the consumer.
27//!
28//! A callback method returns `Result<T, E>` with `E: From<ForeignError>`.
29//! A failure the consumer reports becomes the `Err`: a code of `E`'s own
30//! domain (with a payload that decodes) arrives typed, and every other
31//! failure is a [`ForeignError`] converted with `From`.
32
33use std::ffi::c_void;
34use std::sync::Arc;
35
36use crate::rt::buffer::BufferReader;
37use crate::rt::error::{ErrorType, FfiError, FOREIGN_ERROR_CODE, MARSHAL_ERROR_CODE};
38use crate::rt::meta::Name;
39use crate::rt::types::FfiType;
40
41/// The vtable `flags` bit (`{P}_VTABLE_THREAD_AFFINE` in C) declaring that
42/// the consumer's value-returning methods may only be called on the thread
43/// that passed the vtable to the producer.
44pub const VTABLE_THREAD_AFFINE: u32 = 1;
45
46/// The message a thread-affine callback method fails with when it's called
47/// from another thread.
48pub const OFF_THREAD_MESSAGE: &str = "callback called off its thread";
49
50/// The fixed header every callback-interface vtable starts with
51/// (`{prefix}_{Cb}_vtable` in C).
52#[repr(C)]
53#[derive(Debug, Clone, Copy)]
54pub struct VtableHeader {
55    /// `sizeof` the whole vtable as the consumer compiled it.
56    pub size: u32,
57    /// Behavior flags: [`VTABLE_THREAD_AFFINE`], or `0`.
58    pub flags: u32,
59    /// The consumer's release hook, called exactly once (from any producer
60    /// thread) when the producer drops its last reference; null for none.
61    pub free: Option<unsafe extern "C" fn(ctx: *mut c_void)>,
62}
63
64/// Implemented by every generated `#[repr(C)]` vtable struct, whose first
65/// field is its [`VtableHeader`].
66///
67/// # Safety
68///
69/// The implementing type must be `#[repr(C)]`, start with a
70/// [`VtableHeader`], and hold only `Option` function pointers after it.
71pub unsafe trait Vtable: 'static {}
72
73/// A callback-interface argument (`{prefix}_{Cb}`): the consumer's context
74/// and its vtable, passed by value. A null `vtable` is none.
75#[repr(C)]
76#[derive(Debug)]
77pub struct CallbackArg<V> {
78    /// The consumer's context, handed back to every entry.
79    pub ctx: *mut c_void,
80    /// The consumer's vtable.
81    pub vtable: *const V,
82}
83
84impl<V> Clone for CallbackArg<V> {
85    fn clone(&self) -> Self {
86        *self
87    }
88}
89
90impl<V> Copy for CallbackArg<V> {}
91
92/// Ties a callback interface's `dyn Trait` to its generated vtable and
93/// foreign wrapper; the `#[weaveffi::callback_interface]` expansion
94/// implements it.
95#[diagnostic::on_unimplemented(
96    message = "`{Self}` isn't a WeaveFFI callback interface",
97    label = "not a `#[weaveffi::callback_interface]` trait",
98    note = "a callback parameter is `Arc<dyn Trait>` (or `Option<Arc<dyn Trait>>`) for a trait \
99            declared with `#[weaveffi::callback_interface]`"
100)]
101pub trait CallbackType<UT> {
102    /// The interface's IDL name.
103    const NAME: Name;
104    /// The generated vtable struct.
105    type Vtable: Vtable;
106    /// Wrap a lifted foreign callback as a shared trait object.
107    fn wrap(cb: ForeignCallback<Self::Vtable>) -> Arc<Self>;
108}
109
110/// Lift a callback-interface parameter.
111///
112/// # Errors
113///
114/// Returns a marshalling error for a null vtable or an incomplete header.
115///
116/// # Safety
117///
118/// Same contract as [`ForeignCallback::adopt`].
119pub unsafe fn lift_callback<UT, C: CallbackType<UT> + ?Sized>(
120    arg: CallbackArg<C::Vtable>,
121) -> Result<Arc<C>, FfiError> {
122    // SAFETY: forwarded from the caller.
123    unsafe { lift_callback_opt::<UT, C>(arg) }?
124        .ok_or_else(|| FfiError::new(MARSHAL_ERROR_CODE, "a callback argument is null"))
125}
126
127/// Lift an optional callback-interface parameter (`Cb?`): a null vtable is
128/// `None`.
129///
130/// # Errors
131///
132/// Returns a marshalling error for an incomplete header.
133///
134/// # Safety
135///
136/// Same contract as [`ForeignCallback::adopt`].
137pub unsafe fn lift_callback_opt<UT, C: CallbackType<UT> + ?Sized>(
138    arg: CallbackArg<C::Vtable>,
139) -> Result<Option<Arc<C>>, FfiError> {
140    // SAFETY: forwarded from the caller.
141    Ok(unsafe { ForeignCallback::adopt(arg) }?.map(C::wrap))
142}
143
144/// A consumer-implemented callback interface held by the producer.
145pub struct ForeignCallback<V: Vtable> {
146    ctx: *mut c_void,
147    vtable: *const V,
148    /// The consumer's vtable size.
149    size: usize,
150    free: Option<unsafe extern "C" fn(*mut c_void)>,
151    /// The adopting thread, for a vtable flagged [`VTABLE_THREAD_AFFINE`].
152    owner: Option<std::thread::ThreadId>,
153}
154
155// SAFETY: the ABI obliges the consumer to make every vtable entry (including
156// `free`) callable from any thread, thread-affine methods excepted, which
157// `check_thread` guards; the producer never dereferences `ctx` itself.
158unsafe impl<V: Vtable> Send for ForeignCallback<V> {}
159// SAFETY: see the `Send` impl; the vtable is immutable consumer data.
160unsafe impl<V: Vtable> Sync for ForeignCallback<V> {}
161
162impl<V: Vtable> ForeignCallback<V> {
163    /// Adopt a callback argument, recording the calling thread when the
164    /// vtable is thread-affine. `Ok(None)` for a null vtable.
165    ///
166    /// # Errors
167    ///
168    /// Returns a marshalling error when the vtable's `size` is smaller than
169    /// its header.
170    ///
171    /// # Safety
172    ///
173    /// `arg.vtable` must be null or point to a vtable whose first `size`
174    /// bytes are initialized and stay valid and unmodified for the life of
175    /// the returned value (consumers use a process-wide static). `arg.ctx`
176    /// must remain valid until the vtable's `free` is called with it.
177    pub unsafe fn adopt(arg: CallbackArg<V>) -> Result<Option<Self>, FfiError> {
178        if arg.vtable.is_null() {
179            return Ok(None);
180        }
181        // SAFETY: the caller guarantees the header's first field, `size`, is
182        // readable.
183        let size = unsafe { arg.vtable.cast::<u32>().read() } as usize;
184        if size < std::mem::size_of::<VtableHeader>() {
185            return Err(FfiError::new(
186                MARSHAL_ERROR_CODE,
187                &format!("a callback vtable is {size} bytes, shorter than its header"),
188            ));
189        }
190        // SAFETY: the header is complete.
191        let header = unsafe { arg.vtable.cast::<VtableHeader>().read() };
192        crate::rt::leak::track(crate::rt::leak::CALLBACKS, 1);
193        let owner = (header.flags & VTABLE_THREAD_AFFINE != 0).then(|| std::thread::current().id());
194        Ok(Some(Self {
195            ctx: arg.ctx,
196            vtable: arg.vtable,
197            size,
198            free: header.free,
199            owner,
200        }))
201    }
202
203    /// The vtable entry at `offset` (from `std::mem::offset_of!`), named
204    /// `name` for the error.
205    ///
206    /// # Errors
207    ///
208    /// Returns a [`FOREIGN_ERROR_CODE`] failure when the consumer's vtable
209    /// ends before the entry or the entry is null: the binding was generated
210    /// before the method existed.
211    pub fn entry<F: Copy>(&self, offset: usize, name: &str) -> Result<F, ForeignError> {
212        let missing = || {
213            ForeignError::new(
214                FOREIGN_ERROR_CODE,
215                format!("the binding doesn't implement callback method `{name}`; regenerate it"),
216            )
217        };
218        if offset + std::mem::size_of::<Option<F>>() > self.size {
219            return Err(missing());
220        }
221        // SAFETY: the consumer's vtable covers the entry, which is an
222        // `Option` of the entry's function pointer type (see `Vtable`).
223        let entry = unsafe {
224            self.vtable
225                .cast::<u8>()
226                .add(offset)
227                .cast::<Option<F>>()
228                .read()
229        };
230        entry.ok_or_else(missing)
231    }
232
233    /// Whether a value-returning method may be called on this thread.
234    ///
235    /// # Errors
236    ///
237    /// Returns a [`FOREIGN_ERROR_CODE`] failure with [`OFF_THREAD_MESSAGE`]
238    /// on any thread but the adopting one, for a thread-affine vtable.
239    pub fn check_thread(&self) -> Result<(), ForeignError> {
240        match self.owner {
241            Some(owner) if owner != std::thread::current().id() => {
242                Err(ForeignError::new(FOREIGN_ERROR_CODE, OFF_THREAD_MESSAGE))
243            }
244            _ => Ok(()),
245        }
246    }
247
248    /// The consumer's context, the first argument of every entry.
249    #[must_use]
250    pub fn ctx(&self) -> *mut c_void {
251        self.ctx
252    }
253}
254
255impl<V: Vtable> Drop for ForeignCallback<V> {
256    fn drop(&mut self) {
257        crate::rt::leak::track(crate::rt::leak::CALLBACKS, -1);
258        if let Some(free) = self.free {
259            // SAFETY: `ctx` goes back to the consumer's release hook exactly
260            // once, as the ABI requires.
261            unsafe { free(self.ctx) };
262        }
263    }
264}
265
266/// A failure a consumer's callback-interface implementation reported, or a
267/// value it returned that the producer couldn't accept.
268///
269/// A callback method's error type converts from it (`E:
270/// From<ForeignError>`), and it's a valid error type itself (`throws any`).
271/// `code` is [`FOREIGN_ERROR_CODE`] for a consumer failure, and
272/// [`MARSHAL_ERROR_CODE`] for a return the producer couldn't accept. A
273/// declared code of the method's own domain never arrives as a
274/// `ForeignError`; it's decoded into the typed error instead.
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct ForeignError {
277    /// The failure's code.
278    pub code: i32,
279    /// The consumer's message.
280    pub message: String,
281}
282
283impl ForeignError {
284    /// A failure with `code` and `message`.
285    #[must_use]
286    pub fn new(code: i32, message: impl Into<String>) -> Self {
287        Self {
288            code,
289            message: message.into(),
290        }
291    }
292
293    fn marshal(message: &str) -> Self {
294        Self::new(MARSHAL_ERROR_CODE, message)
295    }
296}
297
298impl std::fmt::Display for ForeignError {
299    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300        f.write_str(&self.message)
301    }
302}
303
304impl std::error::Error for ForeignError {}
305
306impl<UT> ErrorType<UT> for ForeignError {
307    const DOMAIN: Name = Name::new("any");
308    fn into_ffi(self) -> FfiError {
309        FfiError::untyped(&self.message)
310    }
311}
312
313/// The consumer's failure in `err` as `E`: a declared code of `E`'s domain
314/// arrives typed, and anything else as a [`FOREIGN_ERROR_CODE`]
315/// [`ForeignError`].
316fn failure<UT, E: ErrorType<UT> + From<ForeignError>>(err: &FfiError) -> E {
317    if err.code > 0 {
318        if let Some(typed) = E::from_code(err.code, err.payload()) {
319            return typed;
320        }
321    }
322    // SAFETY: the consumer fills `out_err` only through `{prefix}_error_set`,
323    // so a non-null message is a run this runtime owns.
324    let message = match unsafe { err.message_str() } {
325        Some(m) if !m.is_empty() => m.to_string(),
326        _ => "callback interface implementation failed".to_string(),
327    };
328    E::from(ForeignError::new(FOREIGN_ERROR_CODE, message))
329}
330
331/// The outcome of a vtable call that returns nothing.
332///
333/// # Errors
334///
335/// Returns the consumer's failure when `err.code` isn't `0`.
336pub fn callback_unit<UT, E: ErrorType<UT> + From<ForeignError>>(err: &FfiError) -> Result<(), E> {
337    if err.code == 0 {
338        Ok(())
339    } else {
340        Err(failure::<UT, E>(err))
341    }
342}
343
344/// The outcome of a vtable call that returns `R`: the return is adopted
345/// whether or not the consumer failed (so a consumer that fails after
346/// allocating doesn't leak), then the failure, if any, wins.
347///
348/// # Errors
349///
350/// Returns the consumer's failure, or a marshalling failure for a return
351/// the producer can't accept.
352///
353/// # Safety
354///
355/// `ret` must be the C value the vtable entry returned.
356pub unsafe fn callback_value<UT, R: FfiType<UT>, E: ErrorType<UT> + From<ForeignError>>(
357    ret: R::Abi,
358    err: &FfiError,
359) -> Result<R, E> {
360    // SAFETY: forwarded from the caller; the producer adopts the return.
361    let value = unsafe { R::adopt(ret) };
362    callback_unit::<UT, E>(err)?;
363    value.map_err(|e| {
364        // SAFETY: a runtime-built error owns its message.
365        let why = unsafe { e.message_str() }.unwrap_or("").to_string();
366        E::from(ForeignError::marshal(&format!(
367            "a callback interface returned an invalid value: {why}"
368        )))
369    })
370}
371
372/// Decode a domain code's payload for [`ErrorType::from_code`]: the
373/// generated domain impls read each code's fields through this, from a
374/// token-free reader, so a payload can never adopt an object.
375pub fn payload_reader(payload: &[u8]) -> BufferReader<'_> {
376    BufferReader::token_free(payload)
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use std::sync::atomic::{AtomicUsize, Ordering};
383
384    #[repr(C)]
385    struct TestVtable {
386        header: VtableHeader,
387        ping: Option<unsafe extern "C" fn(*mut c_void, i32, *mut FfiError) -> i32>,
388        pong: Option<unsafe extern "C" fn(*mut c_void, *mut FfiError)>,
389    }
390
391    // SAFETY: `#[repr(C)]`, the header first, then entries.
392    unsafe impl Vtable for TestVtable {}
393
394    type Ping = unsafe extern "C" fn(*mut c_void, i32, *mut FfiError) -> i32;
395    type Pong = unsafe extern "C" fn(*mut c_void, *mut FfiError);
396
397    unsafe extern "C" fn ping(_ctx: *mut c_void, x: i32, out_err: *mut FfiError) -> i32 {
398        if x < 0 {
399            unsafe { crate::rt::error::error_set(out_err, 7, "negative") };
400            return 0;
401        }
402        x * 2
403    }
404
405    unsafe extern "C" fn free(ctx: *mut c_void) {
406        unsafe { &*ctx.cast::<AtomicUsize>() }.fetch_add(1, Ordering::SeqCst);
407    }
408
409    fn vtable(size: usize) -> TestVtable {
410        TestVtable {
411            header: VtableHeader {
412                size: size as u32,
413                flags: 0,
414                free: Some(free),
415            },
416            ping: Some(ping),
417            pong: None,
418        }
419    }
420
421    #[test]
422    fn entries_are_called_and_free_runs_once() {
423        let freed = AtomicUsize::new(0);
424        let vt = vtable(std::mem::size_of::<TestVtable>());
425        let arg = CallbackArg {
426            ctx: std::ptr::from_ref(&freed).cast_mut().cast(),
427            vtable: &vt,
428        };
429        let cb = unsafe { ForeignCallback::adopt(arg) }.unwrap().unwrap();
430        let f: Ping = cb
431            .entry(std::mem::offset_of!(TestVtable, ping), "ping")
432            .unwrap();
433        let mut err = FfiError::default();
434        assert_eq!(unsafe { f(cb.ctx(), 21, &mut err) }, 42);
435        // A null entry is a method the binding doesn't implement.
436        let missing = cb.entry::<Pong>(std::mem::offset_of!(TestVtable, pong), "pong");
437        assert_eq!(missing.unwrap_err().code, FOREIGN_ERROR_CODE);
438        drop(cb);
439        assert_eq!(freed.load(Ordering::SeqCst), 1);
440    }
441
442    #[test]
443    fn a_short_vtable_is_accepted_and_its_missing_methods_fail() {
444        let freed = AtomicUsize::new(0);
445        // A binding generated before `ping` existed.
446        let vt = vtable(std::mem::size_of::<VtableHeader>());
447        let arg = CallbackArg {
448            ctx: std::ptr::from_ref(&freed).cast_mut().cast(),
449            vtable: &vt,
450        };
451        let cb = unsafe { ForeignCallback::adopt(arg) }.unwrap().unwrap();
452        let err = cb
453            .entry::<Ping>(std::mem::offset_of!(TestVtable, ping), "ping")
454            .unwrap_err();
455        assert_eq!(err.code, FOREIGN_ERROR_CODE);
456        assert!(err.message.contains("`ping`"), "{}", err.message);
457        drop(cb);
458        assert_eq!(freed.load(Ordering::SeqCst), 1);
459
460        let vt = vtable(4);
461        let arg = CallbackArg {
462            ctx: std::ptr::null_mut(),
463            vtable: &vt,
464        };
465        assert!(unsafe { ForeignCallback::adopt(arg) }.is_err());
466        let null = CallbackArg::<TestVtable> {
467            ctx: std::ptr::null_mut(),
468            vtable: std::ptr::null(),
469        };
470        assert!(unsafe { ForeignCallback::adopt(null) }.unwrap().is_none());
471    }
472
473    #[test]
474    fn failures_convert_to_the_method_error() {
475        let ok = FfiError::default();
476        assert!(callback_unit::<(), ForeignError>(&ok).is_ok());
477        let failed = FfiError::new(-1, "nope");
478        let e = callback_unit::<(), ForeignError>(&failed).unwrap_err();
479        assert_eq!((e.code, e.message.as_str()), (FOREIGN_ERROR_CODE, "nope"));
480        let run = crate::rt::run::Run::copy_of(b"hi");
481        let value = unsafe { callback_value::<(), String, ForeignError>(run, &ok) };
482        assert_eq!(value.unwrap(), "hi");
483        let bad = [0xffu8];
484        let run = crate::rt::run::Run::copy_of(&bad);
485        let value = unsafe { callback_value::<(), String, ForeignError>(run, &ok) };
486        assert_eq!(value.unwrap_err().code, MARSHAL_ERROR_CODE);
487    }
488}