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::cell::OnceCell;
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};
59
60#[repr(C)]
61pub struct wasm_trap_t {
62    pub(crate) error: Error,
63}
64
65// This is currently only needed for the `wasm_trap_copy` API in the C API.
66//
67// For now the impl here is "fake it til you make it" since this is losing
68// context by only cloning the error string.
69impl Clone for wasm_trap_t {
70    fn clone(&self) -> wasm_trap_t {
71        wasm_trap_t {
72            error: format_err!("{:?}", self.error),
73        }
74    }
75}
76
77wasmtime_c_api_macros::declare_ref!(wasm_trap_t);
78
79impl wasm_trap_t {
80    pub(crate) fn new(error: Error) -> wasm_trap_t {
81        wasm_trap_t { error }
82    }
83}
84
85#[repr(C)]
86#[derive(Clone)]
87pub struct wasm_frame_t<'a> {
88    trace: &'a WasmBacktrace,
89    idx: usize,
90    func_name: OnceCell<Option<wasm_name_t>>,
91    module_name: OnceCell<Option<wasm_name_t>>,
92}
93
94wasmtime_c_api_macros::declare_own!(wasm_frame_t);
95
96pub type wasm_message_t = wasm_name_t;
97
98#[unsafe(no_mangle)]
99pub extern "C" fn wasm_trap_new(
100    _store: &wasm_store_t,
101    message: &wasm_message_t,
102) -> Box<wasm_trap_t> {
103    let message = message.as_slice();
104    if message[message.len() - 1] != 0 {
105        panic!("wasm_trap_new message stringz expected");
106    }
107    let message = String::from_utf8_lossy(&message[..message.len() - 1]);
108    Box::new(wasm_trap_t {
109        error: Error::msg(message.into_owned()),
110    })
111}
112
113#[unsafe(no_mangle)]
114pub unsafe extern "C" fn wasmtime_trap_new(message: *const u8, len: usize) -> Box<wasm_trap_t> {
115    let bytes = crate::slice_from_raw_parts(message, len);
116    let message = String::from_utf8_lossy(&bytes);
117    Box::new(wasm_trap_t {
118        error: Error::msg(message.into_owned()),
119    })
120}
121
122#[unsafe(no_mangle)]
123pub unsafe extern "C" fn wasmtime_trap_new_code(code: u8) -> Box<wasm_trap_t> {
124    let trap = Trap::from_u8(code).unwrap();
125    Box::new(wasm_trap_t {
126        error: Error::new(trap),
127    })
128}
129
130#[unsafe(no_mangle)]
131pub extern "C" fn wasm_trap_message(trap: &wasm_trap_t, out: &mut wasm_message_t) {
132    let mut buffer = Vec::new();
133    buffer.extend_from_slice(format!("{:?}", trap.error).as_bytes());
134    buffer.reserve_exact(1);
135    buffer.push(0);
136    out.set_buffer(buffer);
137}
138
139#[unsafe(no_mangle)]
140pub extern "C" fn wasm_trap_origin(raw: &wasm_trap_t) -> Option<Box<wasm_frame_t<'_>>> {
141    let trace = match raw.error.downcast_ref::<WasmBacktrace>() {
142        Some(trap) => trap,
143        None => return None,
144    };
145    if trace.frames().len() > 0 {
146        Some(Box::new(wasm_frame_t {
147            trace,
148            idx: 0,
149            func_name: OnceCell::new(),
150            module_name: OnceCell::new(),
151        }))
152    } else {
153        None
154    }
155}
156
157#[unsafe(no_mangle)]
158pub extern "C" fn wasm_trap_trace<'a>(raw: &'a wasm_trap_t, out: &mut wasm_frame_vec_t<'a>) {
159    error_trace(&raw.error, out)
160}
161
162pub(crate) fn error_trace<'a>(error: &'a Error, out: &mut wasm_frame_vec_t<'a>) {
163    let trace = match error.downcast_ref::<WasmBacktrace>() {
164        Some(trap) => trap,
165        None => return out.set_buffer(Vec::new()),
166    };
167    let vec = (0..trace.frames().len())
168        .map(|idx| {
169            Some(Box::new(wasm_frame_t {
170                trace,
171                idx,
172                func_name: OnceCell::new(),
173                module_name: OnceCell::new(),
174            }))
175        })
176        .collect();
177    out.set_buffer(vec);
178}
179
180#[unsafe(no_mangle)]
181pub extern "C" fn wasmtime_trap_code(raw: &wasm_trap_t, code: &mut u8) -> bool {
182    let trap = match raw.error.downcast_ref::<Trap>() {
183        Some(trap) => trap,
184        None => return false,
185    };
186    *code = *trap as u8;
187    true
188}
189
190#[unsafe(no_mangle)]
191pub extern "C" fn wasm_frame_func_index(frame: &wasm_frame_t<'_>) -> u32 {
192    frame.trace.frames()[frame.idx].func_index()
193}
194
195#[unsafe(no_mangle)]
196pub extern "C" fn wasmtime_frame_func_name<'a>(
197    frame: &'a wasm_frame_t<'_>,
198) -> Option<&'a wasm_name_t> {
199    frame
200        .func_name
201        .get_or_init(|| {
202            frame.trace.frames()[frame.idx]
203                .func_name()
204                .map(|s| wasm_name_t::from(s.to_string().into_bytes()))
205        })
206        .as_ref()
207}
208
209#[unsafe(no_mangle)]
210pub extern "C" fn wasmtime_frame_module_name<'a>(
211    frame: &'a wasm_frame_t<'_>,
212) -> Option<&'a wasm_name_t> {
213    frame
214        .module_name
215        .get_or_init(|| {
216            frame.trace.frames()[frame.idx]
217                .module()
218                .name()
219                .map(|s| wasm_name_t::from(s.to_string().into_bytes()))
220        })
221        .as_ref()
222}
223
224#[unsafe(no_mangle)]
225pub extern "C" fn wasm_frame_func_offset(frame: &wasm_frame_t<'_>) -> usize {
226    frame.trace.frames()[frame.idx]
227        .func_offset()
228        .unwrap_or(usize::MAX)
229}
230
231#[unsafe(no_mangle)]
232pub extern "C" fn wasm_frame_instance(_arg1: *const wasm_frame_t<'_>) -> *mut wasm_instance_t {
233    unimplemented!("wasm_frame_instance")
234}
235
236#[unsafe(no_mangle)]
237pub extern "C" fn wasm_frame_module_offset(frame: &wasm_frame_t<'_>) -> usize {
238    frame.trace.frames()[frame.idx]
239        .module_offset()
240        .unwrap_or(usize::MAX)
241}
242
243#[unsafe(no_mangle)]
244pub extern "C" fn wasm_frame_copy<'a>(frame: &wasm_frame_t<'a>) -> Box<wasm_frame_t<'a>> {
245    Box::new(frame.clone())
246}