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