weaveffi/rt/error.rs
1//! The error struct every fallible symbol reports through, the reserved
2//! runtime codes, and the [`ErrorType`] trait every error a callable may
3//! return implements.
4//!
5//! A synchronous call takes a caller-owned `{prefix}_error* out_err` slot; an
6//! async completion receives a heap-boxed one it releases with
7//! `{prefix}_error_free`. Either way the producer allocates the message (a
8//! UTF-8 run, not NUL-terminated) and the optional payload (a value buffer),
9//! both as ordinary 8-aligned byte runs, so the producer is also the one
10//! that frees them.
11
12use std::ptr;
13
14use crate::rt::meta::Name;
15use crate::rt::run::Run;
16
17/// The reserved error code for an **untyped producer error**: a callable
18/// declared `throws any` reports every failure with it, its message the
19/// error's `Display` output. An async call the executor couldn't start
20/// completes with it too.
21pub const GENERIC_ERROR_CODE: i32 = -1;
22
23/// The reserved error code reporting a producer **panic**.
24///
25/// Generated thunks wrap the producer call in `catch_unwind`; a panic is
26/// reported through `out_err` with this code so the consumer can distinguish
27/// "the producer has a bug" from any declared domain error. Validation rejects
28/// error domains that try to claim a reserved code (`0`, which means success,
29/// or any negative value).
30pub const PANIC_ERROR_CODE: i32 = -2;
31
32/// The reserved error code reporting a **marshalling failure**: an argument
33/// that could not be lifted at the boundary (a null pointer with a non-zero
34/// length, a non-UTF-8 string, an out-of-range enum discriminant or integer,
35/// a misaligned typed array, a malformed value buffer, or a value a custom
36/// type's `lift` rejected).
37///
38/// Both sides are generated from the same IDL, so a marshalling failure is a
39/// producer/consumer contract violation, not a domain error; wrappers surface
40/// it through the same trap channel as [`PANIC_ERROR_CODE`].
41pub const MARSHAL_ERROR_CODE: i32 = -3;
42
43/// The reserved error code reporting that a **consumer callback-interface
44/// implementation failed**, or that a thread-affine callback was called off
45/// its thread.
46///
47/// A consumer's method implementation that raises reports it through the
48/// vtable entry's `out_err` slot (via `{prefix}_error_set`). The producer
49/// sees every failure with this code, except a declared code of the method's
50/// own error domain (see [`ForeignError`](crate::rt::ForeignError)).
51pub const FOREIGN_ERROR_CODE: i32 = -4;
52
53/// The reserved error code reporting that an async call was **cancelled**:
54/// its cancel token fired, or the executor dropped the future before it
55/// completed. The completion callback still fires exactly once, with this
56/// code.
57pub const CANCELLED_ERROR_CODE: i32 = -5;
58
59/// The error struct passed across the C ABI boundary (`{prefix}_error` in C).
60///
61/// `code == 0` means success and every pointer is null. Otherwise
62/// `message_ptr`/`message_len` hold a UTF-8 message (not NUL-terminated) and
63/// `payload_ptr`/`payload_len` optionally hold the matched error code's
64/// fields serialized in the [`buffer`](crate::rt::buffer) format. The
65/// producer allocates both as byte runs, and [`error_clear`] (the body of
66/// `{prefix}_error_clear`) frees them.
67///
68/// The struct owns its allocations, so it must not be copied bitwise while
69/// it holds any; a copy would double-free on clear.
70#[repr(C)]
71#[derive(Debug)]
72pub struct FfiError {
73 /// Status code. `0` means success; a positive value is a domain error
74 /// code and a negative value is one of the reserved runtime codes.
75 pub code: i32,
76 /// Owned UTF-8 message describing the failure (not NUL-terminated), or
77 /// null when it's empty.
78 pub message_ptr: *const u8,
79 /// Byte length of [`message_ptr`](Self::message_ptr); `0` when null.
80 pub message_len: usize,
81 /// Owned value buffer holding the matched error code's payload fields, or
82 /// null when the code declares no fields.
83 pub payload_ptr: *const u8,
84 /// Byte length of [`payload_ptr`](Self::payload_ptr); `0` when null.
85 pub payload_len: usize,
86}
87
88impl Default for FfiError {
89 fn default() -> Self {
90 Self {
91 code: 0,
92 message_ptr: ptr::null(),
93 message_len: 0,
94 payload_ptr: ptr::null(),
95 payload_len: 0,
96 }
97 }
98}
99
100// SAFETY: an `FfiError` exclusively owns the message and payload it points
101// to (both are producer heap allocations with no thread affinity), so moving
102// it to another thread moves that ownership with it. Async launchers rely on
103// this to carry a boxed error from the future to the completion.
104unsafe impl Send for FfiError {}
105
106impl FfiError {
107 /// Build an owned error with `code` and `message`.
108 #[must_use]
109 pub fn new(code: i32, message: &str) -> Self {
110 let mut err = Self::default();
111 err.set(code, message);
112 err
113 }
114
115 /// Build the error an untyped failure (`throws any`) reports: the
116 /// [`GENERIC_ERROR_CODE`] with `e`'s `Display` output as the message.
117 #[must_use]
118 pub fn untyped<E: std::fmt::Display + ?Sized>(e: &E) -> Self {
119 Self::new(GENERIC_ERROR_CODE, &e.to_string())
120 }
121
122 /// Build the error a caught unwind payload describes: a producer panic,
123 /// reported with [`PANIC_ERROR_CODE`].
124 #[must_use]
125 pub fn from_panic(payload: &(dyn std::any::Any + Send)) -> Self {
126 Self::new(
127 PANIC_ERROR_CODE,
128 &format!("producer panicked: {}", panic_message(payload)),
129 )
130 }
131
132 /// The error a cancelled async call completes with.
133 #[must_use]
134 pub fn cancelled() -> Self {
135 Self::new(CANCELLED_ERROR_CODE, "cancelled")
136 }
137
138 /// The message as a string slice, or `None` when it's empty, malformed,
139 /// or not UTF-8.
140 ///
141 /// # Safety
142 ///
143 /// `message_ptr` must be null or point to `message_len` bytes that stay
144 /// valid for the borrow, which holds for any error this runtime filled.
145 #[must_use]
146 pub unsafe fn message_str(&self) -> Option<&str> {
147 if self.message_ptr.is_null() {
148 return (self.code != 0).then_some("");
149 }
150 // SAFETY: the caller guarantees the run is live.
151 let bytes = unsafe { std::slice::from_raw_parts(self.message_ptr, self.message_len) };
152 std::str::from_utf8(bytes).ok()
153 }
154
155 /// Release the message and payload, leaving the error in the success
156 /// state.
157 fn release(&mut self) {
158 // SAFETY: every non-null message and payload was allocated by
159 // `Run::copy_of` with its recorded length, and each is released
160 // exactly once because the pointers are nulled right after.
161 unsafe {
162 Run {
163 ptr: self.message_ptr,
164 len: self.message_len,
165 }
166 .free();
167 Run {
168 ptr: self.payload_ptr,
169 len: self.payload_len,
170 }
171 .free();
172 }
173 self.message_ptr = ptr::null();
174 self.message_len = 0;
175 self.payload_ptr = ptr::null();
176 self.payload_len = 0;
177 self.code = 0;
178 }
179
180 fn set(&mut self, code: i32, message: &str) {
181 self.release();
182 self.code = code;
183 let run = Run::copy_of(message.as_bytes());
184 self.message_ptr = run.ptr;
185 self.message_len = run.len;
186 }
187
188 /// Replace the payload with a copy of `payload` (a value buffer of the
189 /// code's fields).
190 pub fn set_payload(&mut self, payload: &[u8]) {
191 // SAFETY: a non-null payload was allocated by `Run::copy_of` with
192 // this length, and is replaced right after.
193 unsafe {
194 Run {
195 ptr: self.payload_ptr,
196 len: self.payload_len,
197 }
198 .free();
199 }
200 let run = Run::copy_of(payload);
201 self.payload_ptr = run.ptr;
202 self.payload_len = run.len;
203 }
204
205 /// The payload as a byte slice (empty when there is none).
206 #[must_use]
207 pub fn payload(&self) -> &[u8] {
208 if self.payload_ptr.is_null() {
209 return &[];
210 }
211 // SAFETY: a non-null payload is an owned run of `payload_len` bytes
212 // (see `set_payload`), alive as long as `self`.
213 unsafe { std::slice::from_raw_parts(self.payload_ptr, self.payload_len) }
214 }
215}
216
217impl Drop for FfiError {
218 fn drop(&mut self) {
219 self.release();
220 }
221}
222
223/// Fill the caller's `out_err` slot with `code` and a copy of `message`,
224/// releasing anything it held before. A null `out_err` is a no-op.
225///
226/// # Safety
227///
228/// `out_err` must be null or point to a valid, writable [`FfiError`] whose
229/// pointers are null or owned by this runtime.
230pub unsafe fn error_set(out_err: *mut FfiError, code: i32, message: &str) {
231 // SAFETY: forwarded from the caller.
232 if let Some(err) = unsafe { out_err.as_mut() } {
233 err.set(code, message);
234 }
235}
236
237/// Write `value` into the caller's `out_err` slot, **overwriting** whatever
238/// it held without reading or releasing it. A null `out_err` drops `value`.
239///
240/// A synchronous call writes its outcome this way, so the slot's prior
241/// contents never matter: a consumer that reuses one struct for many calls
242/// releases each failure with `{prefix}_error_clear` after reading it, and an
243/// uninitialized struct is safe to pass.
244///
245/// # Safety
246///
247/// `out_err` must be null or point to writable memory for an [`FfiError`].
248pub unsafe fn error_store(out_err: *mut FfiError, value: FfiError) {
249 if out_err.is_null() {
250 return;
251 }
252 // SAFETY: forwarded from the caller; the old contents are overwritten
253 // without being dropped.
254 unsafe { std::ptr::write(out_err, value) };
255}
256
257/// The body of `{prefix}_error_set`: fill `out_err` with `code` and a copy
258/// of the `len` message bytes at `message`, which the consumer owns.
259///
260/// Callback-interface implementations call it to report a failure so that
261/// the message is allocated by the producer, which is the side that frees
262/// it. A null `message` yields an empty message, and bytes that aren't
263/// UTF-8 are replaced with U+FFFD; the code is always recorded.
264///
265/// # Safety
266///
267/// Same contract as [`error_set`] for `out_err`. `message` must be null or
268/// point to `len` readable bytes for the duration of the call.
269pub unsafe fn error_set_c(out_err: *mut FfiError, code: i32, message: *const u8, len: usize) {
270 // SAFETY: forwarded from the caller.
271 let bytes = unsafe { Run { ptr: message, len }.bytes() }.unwrap_or(&[]);
272 // SAFETY: forwarded from the caller.
273 unsafe { error_set(out_err, code, &String::from_utf8_lossy(bytes)) };
274}
275
276/// The body of `{prefix}_error_set_payload`: replace `out_err`'s payload
277/// with a producer-owned copy of the `len` bytes at `ptr`. A null `out_err`
278/// is a no-op; a null `ptr` (or a `len` of `0`) clears the payload.
279///
280/// A callback-interface implementation of a method that throws a domain
281/// calls it after `{prefix}_error_set` to attach a code's fields, encoded as
282/// a value buffer, so the producer can decode the typed error.
283///
284/// # Safety
285///
286/// Same contract as [`error_set`] for `out_err`. `ptr` must be null or point
287/// to `len` readable bytes for the duration of the call.
288pub unsafe fn error_set_payload_c(out_err: *mut FfiError, ptr: *const u8, len: usize) {
289 // SAFETY: forwarded from the caller.
290 let Some(err) = (unsafe { out_err.as_mut() }) else {
291 return;
292 };
293 // SAFETY: forwarded from the caller.
294 let bytes = unsafe { Run { ptr, len }.bytes() }.unwrap_or(&[]);
295 err.set_payload(bytes);
296}
297
298/// The body of `{prefix}_error_clear`: free any message and payload and set
299/// the code to `0`. A null `err` is a no-op.
300///
301/// # Safety
302///
303/// Same contract as [`error_set`].
304pub unsafe fn error_clear(err: *mut FfiError) {
305 // SAFETY: forwarded from the caller.
306 if let Some(err) = unsafe { err.as_mut() } {
307 err.release();
308 }
309}
310
311/// The body of `{prefix}_error_free`: release a heap-boxed error delivered
312/// through an async completion, including the box. A null `err` is a no-op.
313///
314/// # Safety
315///
316/// `err` must be null or a pointer this runtime handed to a completion
317/// callback (see [`boxed_error`]), released exactly once.
318pub unsafe fn error_free(err: *mut FfiError) {
319 if !err.is_null() {
320 // SAFETY: the caller guarantees `err` came from `Box::into_raw`.
321 drop(unsafe { Box::from_raw(err) });
322 }
323}
324
325/// Box `err` for an async completion callback, which hands ownership to the
326/// consumer (released with `{prefix}_error_free`).
327#[must_use]
328pub fn boxed_error(err: FfiError) -> *mut FfiError {
329 Box::into_raw(Box::new(err))
330}
331
332/// An error a callable may return: a declared error domain (the
333/// `#[weaveffi::error]` expansion implements this), or an untyped error
334/// (`String`, `&'static str`, [`std::io::Error`], a boxed error,
335/// [`Error`], [`ForeignError`](crate::rt::ForeignError), and,
336/// with the `anyhow` feature, `anyhow::Error`).
337///
338/// `UT` is the producer crate's tag type, so a crate can implement this for
339/// its own error types.
340#[diagnostic::on_unimplemented(
341 message = "`{Self}` isn't a WeaveFFI error type",
342 label = "not a `#[weaveffi::error]` domain or an untyped error",
343 note = "declare a domain with `#[weaveffi::error]`, or return `weaveffi::Error`, which any \
344 `std::error::Error` converts into with `?`"
345)]
346pub trait ErrorType<UT>: Sized {
347 /// What a callable returning this error throws: the domain's name, or
348 /// `any` for an untyped error.
349 const DOMAIN: Name;
350
351 /// The error this value reports through `out_err`: a domain's code,
352 /// message, and payload, or [`GENERIC_ERROR_CODE`] and the value's
353 /// `Display` text.
354 fn into_ffi(self) -> FfiError;
355
356 /// Decode a typed failure a consumer's callback method reported: `Some`
357 /// when this is a domain, `code` is one of its codes, and `payload`
358 /// holds that code's fields. `None` for an untyped error.
359 fn from_code(code: i32, payload: &[u8]) -> Option<Self> {
360 let _ = (code, payload);
361 None
362 }
363}
364
365macro_rules! untyped_error {
366 ($($t:ty),* $(,)?) => {
367 $(impl<UT> ErrorType<UT> for $t {
368 const DOMAIN: Name = Name::new("any");
369 fn into_ffi(self) -> FfiError {
370 FfiError::untyped(&self)
371 }
372 })*
373 };
374}
375
376untyped_error!(
377 String,
378 &'static str,
379 std::io::Error,
380 Box<dyn std::error::Error + Send + Sync>,
381 Box<dyn std::error::Error>,
382 Error,
383);
384
385#[cfg(feature = "anyhow")]
386untyped_error!(anyhow::Error);
387
388/// An untyped error: any failure, reported to the consumer as `throws any`
389/// (code `-1`) with its `Display` text.
390///
391/// Every `std::error::Error` converts into it with `?`, so a function can
392/// return `Result<T, weaveffi::Error>` and propagate any error type. (It
393/// doesn't implement `std::error::Error` itself, which is what lets that
394/// conversion exist, as with `anyhow::Error`.)
395#[derive(Debug, Clone, PartialEq, Eq)]
396pub struct Error {
397 message: String,
398}
399
400impl Error {
401 /// An error with `message`.
402 pub fn msg(message: impl std::fmt::Display) -> Self {
403 Self {
404 message: message.to_string(),
405 }
406 }
407
408 /// The message.
409 #[must_use]
410 pub fn message(&self) -> &str {
411 &self.message
412 }
413}
414
415impl std::fmt::Display for Error {
416 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417 f.write_str(&self.message)
418 }
419}
420
421impl<E: std::error::Error> From<E> for Error {
422 fn from(e: E) -> Self {
423 Self::msg(e)
424 }
425}
426
427/// Best-effort extraction of a panic payload's message (`&str` and `String`
428/// payloads; anything else yields a fixed placeholder).
429#[must_use]
430pub fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
431 if let Some(s) = payload.downcast_ref::<&str>() {
432 (*s).to_string()
433 } else if let Some(s) = payload.downcast_ref::<String>() {
434 s.clone()
435 } else {
436 "producer panicked".to_string()
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443
444 #[test]
445 fn set_clear_and_overwrite() {
446 let mut err = FfiError::new(PANIC_ERROR_CODE, "boom");
447 assert_eq!(unsafe { err.message_str() }, Some("boom"));
448 assert_eq!(err.message_ptr as usize % crate::rt::run::RUN_ALIGN, 0);
449 unsafe { error_set_payload_c(&mut err, b"xy".as_ptr(), 2) };
450 assert_eq!(err.payload(), b"xy");
451 unsafe { error_clear(&mut err) };
452 assert_eq!(err.code, 0);
453 assert!(err.message_ptr.is_null() && err.payload_ptr.is_null());
454
455 // An uninitialized slot is overwritten, never read.
456 let mut slot = std::mem::MaybeUninit::<FfiError>::uninit();
457 unsafe { error_store(slot.as_mut_ptr(), FfiError::new(-1, "x")) };
458 let stored = unsafe { slot.assume_init() };
459 assert_eq!(stored.code, -1);
460
461 unsafe { error_set_c(&mut err, 7, std::ptr::null(), 5) };
462 assert_eq!((err.code, unsafe { err.message_str() }), (7, Some("")));
463 let bad = [0xff, b'a'];
464 unsafe { error_set_c(&mut err, 3, bad.as_ptr(), 2) };
465 assert_eq!(unsafe { err.message_str() }, Some("\u{fffd}a"));
466 let boxed = boxed_error(FfiError::cancelled());
467 unsafe { error_free(boxed) };
468 unsafe { error_free(std::ptr::null_mut()) };
469 }
470
471 #[test]
472 fn untyped_errors_report_their_text() {
473 let e = <String as ErrorType<()>>::into_ffi("no".to_string());
474 assert_eq!(
475 (e.code, unsafe { e.message_str() }),
476 (GENERIC_ERROR_CODE, Some("no"))
477 );
478 assert!(<std::io::Error as ErrorType<()>>::DOMAIN.is("any"));
479 assert!(<String as ErrorType<()>>::from_code(1, &[]).is_none());
480 assert_eq!(panic_message(&"x"), "x");
481 }
482}