Skip to main content

wasmtime_c_api/
trap.rs

1use crate::{wasm_frame_vec_t, wasm_instance_t, wasm_name_t, wasm_store_t};
2use std::sync::OnceLock;
3use wasmtime::{Error, Trap, WasmBacktrace, format_err};
4
5// Help ensure the Rust enum matches the C one.  If any of these assertions
6// fail, please update both this code and `trap.h` to sync them with
7// `trap_encoding.rs`.
8const _: () = {
9    assert!(Trap::StackOverflow as u8 == 0);
10    assert!(Trap::MemoryOutOfBounds as u8 == 1);
11    assert!(Trap::HeapMisaligned as u8 == 2);
12    assert!(Trap::TableOutOfBounds as u8 == 3);
13    assert!(Trap::IndirectCallToNull as u8 == 4);
14    assert!(Trap::BadSignature as u8 == 5);
15    assert!(Trap::IntegerOverflow as u8 == 6);
16    assert!(Trap::IntegerDivisionByZero as u8 == 7);
17    assert!(Trap::BadConversionToInteger as u8 == 8);
18    assert!(Trap::UnreachableCodeReached as u8 == 9);
19    assert!(Trap::Interrupt as u8 == 10);
20    assert!(Trap::OutOfFuel as u8 == 11);
21    assert!(Trap::AtomicWaitNonSharedMemory as u8 == 12);
22    assert!(Trap::NullReference as u8 == 13);
23    assert!(Trap::ArrayOutOfBounds as u8 == 14);
24    assert!(Trap::AllocationTooLarge as u8 == 15);
25    assert!(Trap::CastFailure as u8 == 16);
26    assert!(Trap::CannotEnterComponent as u8 == 17);
27    assert!(Trap::NoAsyncResult as u8 == 18);
28    assert!(Trap::UnhandledTag as u8 == 19);
29    assert!(Trap::ContinuationAlreadyConsumed as u8 == 20);
30    assert!(Trap::DisabledOpcode as u8 == 21);
31    assert!(Trap::AsyncDeadlock as u8 == 22);
32    assert!(Trap::CannotLeaveComponent as u8 == 23);
33    assert!(Trap::CannotBlockSyncTask as u8 == 24);
34    assert!(Trap::InvalidChar as u8 == 25);
35    assert!(Trap::DebugAssertStringEncodingFinished as u8 == 26);
36    assert!(Trap::DebugAssertEqualCodeUnits as u8 == 27);
37    assert!(Trap::DebugAssertPointerAligned as u8 == 28);
38    assert!(Trap::DebugAssertUpperBitsUnset as u8 == 29);
39    assert!(Trap::StringOutOfBounds as u8 == 30);
40    assert!(Trap::ListOutOfBounds as u8 == 31);
41    assert!(Trap::InvalidDiscriminant as u8 == 32);
42    assert!(Trap::UnalignedPointer as u8 == 33);
43    assert!(Trap::TaskCancelNotCancelled as u8 == 34);
44    assert!(Trap::TaskCancelOrReturnTwice as u8 == 35);
45    assert!(Trap::SubtaskCancelAfterTerminal as u8 == 36);
46    assert!(Trap::TaskReturnInvalid as u8 == 37);
47    assert!(Trap::WaitableSetDropHasWaiters as u8 == 38);
48    assert!(Trap::SubtaskDropNotResolved as u8 == 39);
49    assert!(Trap::ThreadNewIndirectInvalidType as u8 == 40);
50    assert!(Trap::ThreadNewIndirectUninitialized as u8 == 41);
51    assert!(Trap::BackpressureOverflow as u8 == 42);
52    assert!(Trap::UnsupportedCallbackCode as u8 == 43);
53    assert!(Trap::CannotResumeThread as u8 == 44);
54    assert!(Trap::ConcurrentFutureStreamOp as u8 == 45);
55    assert!(Trap::ReferenceCountOverflow as u8 == 46);
56    assert!(Trap::StreamOpTooBig as u8 == 47);
57    assert!(Trap::WaitableSyncAndAsync as u8 == 48);
58    assert!(Trap::UncaughtException as u8 == 49);
59    assert!(Trap::ReadFromDroppedStream as u8 == 50);
60    assert!(Trap::WriteToDroppedStream as u8 == 51);
61    assert!(Trap::WriteToDroppedFuture as u8 == 52);
62    assert!(Trap::LiftDroppedStream as u8 == 53);
63};
64
65#[repr(C)]
66pub struct wasm_trap_t {
67    pub(crate) error: Error,
68}
69
70// This is currently only needed for the `wasm_trap_copy` API in the C API.
71//
72// For now the impl here is "fake it til you make it" since this is losing
73// context by only cloning the error string.
74impl Clone for wasm_trap_t {
75    fn clone(&self) -> wasm_trap_t {
76        wasm_trap_t {
77            error: format_err!("{:?}", self.error),
78        }
79    }
80}
81
82wasmtime_c_api_macros::declare_ref!(wasm_trap_t);
83
84impl wasm_trap_t {
85    pub(crate) fn new(error: Error) -> wasm_trap_t {
86        wasm_trap_t { error }
87    }
88}
89
90#[repr(C)]
91#[derive(Clone)]
92pub struct wasm_frame_t<'a> {
93    trace: &'a WasmBacktrace,
94    idx: usize,
95    func_name: OnceLock<Option<wasm_name_t>>,
96    module_name: OnceLock<Option<wasm_name_t>>,
97}
98
99wasmtime_c_api_macros::declare_own!(wasm_frame_t);
100
101pub type wasm_message_t = wasm_name_t;
102
103#[unsafe(no_mangle)]
104pub extern "C" fn wasm_trap_new(
105    _store: &wasm_store_t,
106    message: &wasm_message_t,
107) -> Box<wasm_trap_t> {
108    let message = message.as_slice();
109    if message[message.len() - 1] != 0 {
110        panic!("wasm_trap_new message stringz expected");
111    }
112    let message = String::from_utf8_lossy(&message[..message.len() - 1]);
113    Box::new(wasm_trap_t {
114        error: Error::msg(message.into_owned()),
115    })
116}
117
118#[unsafe(no_mangle)]
119pub unsafe extern "C" fn wasmtime_trap_new(message: *const u8, len: usize) -> Box<wasm_trap_t> {
120    let bytes = crate::slice_from_raw_parts(message, len);
121    let message = String::from_utf8_lossy(&bytes);
122    Box::new(wasm_trap_t {
123        error: Error::msg(message.into_owned()),
124    })
125}
126
127#[unsafe(no_mangle)]
128pub unsafe extern "C" fn wasmtime_trap_new_code(code: u8) -> Box<wasm_trap_t> {
129    let trap = Trap::from_u8(code).unwrap();
130    Box::new(wasm_trap_t {
131        error: Error::new(trap),
132    })
133}
134
135#[unsafe(no_mangle)]
136pub extern "C" fn wasm_trap_message(trap: &wasm_trap_t, out: &mut wasm_message_t) {
137    let mut buffer = Vec::new();
138    buffer.extend_from_slice(format!("{:?}", trap.error).as_bytes());
139    buffer.reserve_exact(1);
140    buffer.push(0);
141    out.set_buffer(buffer);
142}
143
144#[unsafe(no_mangle)]
145pub extern "C" fn wasm_trap_origin(raw: &wasm_trap_t) -> Option<Box<wasm_frame_t<'_>>> {
146    let trace = match raw.error.downcast_ref::<WasmBacktrace>() {
147        Some(trap) => trap,
148        None => return None,
149    };
150    if trace.frames().len() > 0 {
151        Some(Box::new(wasm_frame_t {
152            trace,
153            idx: 0,
154            func_name: OnceLock::new(),
155            module_name: OnceLock::new(),
156        }))
157    } else {
158        None
159    }
160}
161
162#[unsafe(no_mangle)]
163pub extern "C" fn wasm_trap_trace<'a>(raw: &'a wasm_trap_t, out: &mut wasm_frame_vec_t<'a>) {
164    error_trace(&raw.error, out)
165}
166
167pub(crate) fn error_trace<'a>(error: &'a Error, out: &mut wasm_frame_vec_t<'a>) {
168    let trace = match error.downcast_ref::<WasmBacktrace>() {
169        Some(trap) => trap,
170        None => return out.set_buffer(Vec::new()),
171    };
172    let vec = (0..trace.frames().len())
173        .map(|idx| {
174            Some(Box::new(wasm_frame_t {
175                trace,
176                idx,
177                func_name: OnceLock::new(),
178                module_name: OnceLock::new(),
179            }))
180        })
181        .collect();
182    out.set_buffer(vec);
183}
184
185#[unsafe(no_mangle)]
186pub extern "C" fn wasmtime_trap_code(raw: &wasm_trap_t, code: &mut u8) -> bool {
187    let trap = match raw.error.downcast_ref::<Trap>() {
188        Some(trap) => trap,
189        None => return false,
190    };
191    *code = *trap as u8;
192    true
193}
194
195#[unsafe(no_mangle)]
196pub extern "C" fn wasm_frame_func_index(frame: &wasm_frame_t<'_>) -> u32 {
197    frame.trace.frames()[frame.idx].func_index()
198}
199
200#[unsafe(no_mangle)]
201pub extern "C" fn wasmtime_frame_func_name<'a>(
202    frame: &'a wasm_frame_t<'_>,
203) -> Option<&'a wasm_name_t> {
204    frame
205        .func_name
206        .get_or_init(|| {
207            frame.trace.frames()[frame.idx]
208                .func_name()
209                .map(|s| wasm_name_t::from(s.to_string().into_bytes()))
210        })
211        .as_ref()
212}
213
214#[unsafe(no_mangle)]
215pub extern "C" fn wasmtime_frame_module_name<'a>(
216    frame: &'a wasm_frame_t<'_>,
217) -> Option<&'a wasm_name_t> {
218    frame
219        .module_name
220        .get_or_init(|| {
221            frame.trace.frames()[frame.idx]
222                .module()
223                .name()
224                .map(|s| wasm_name_t::from(s.to_string().into_bytes()))
225        })
226        .as_ref()
227}
228
229#[unsafe(no_mangle)]
230pub extern "C" fn wasm_frame_func_offset(frame: &wasm_frame_t<'_>) -> usize {
231    frame.trace.frames()[frame.idx]
232        .func_offset()
233        .unwrap_or(usize::MAX)
234}
235
236#[unsafe(no_mangle)]
237pub extern "C" fn wasm_frame_instance(_arg1: *const wasm_frame_t<'_>) -> *mut wasm_instance_t {
238    unimplemented!("wasm_frame_instance")
239}
240
241#[unsafe(no_mangle)]
242pub extern "C" fn wasm_frame_module_offset(frame: &wasm_frame_t<'_>) -> usize {
243    frame.trace.frames()[frame.idx]
244        .module_offset()
245        .unwrap_or(usize::MAX)
246}
247
248#[unsafe(no_mangle)]
249pub extern "C" fn wasm_frame_copy<'a>(frame: &wasm_frame_t<'a>) -> Box<wasm_frame_t<'a>> {
250    Box::new(frame.clone())
251}