wasmtime_c_api/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use crate::{wasm_frame_vec_t, wasm_name_t};
use anyhow::{anyhow, Error, Result};

#[repr(C)]
pub struct wasmtime_error_t {
    error: Error,
}

wasmtime_c_api_macros::declare_own!(wasmtime_error_t);

impl From<Error> for wasmtime_error_t {
    fn from(error: Error) -> wasmtime_error_t {
        wasmtime_error_t { error }
    }
}

impl Into<Error> for wasmtime_error_t {
    fn into(self) -> Error {
        self.error
    }
}

#[no_mangle]
pub extern "C" fn wasmtime_error_new(
    msg: *const std::ffi::c_char,
) -> Option<Box<wasmtime_error_t>> {
    let msg_bytes = unsafe { std::ffi::CStr::from_ptr(msg).to_bytes() };
    let msg_string = String::from_utf8_lossy(msg_bytes).into_owned();
    Some(Box::new(wasmtime_error_t::from(anyhow!(msg_string))))
}

pub(crate) fn handle_result<T>(
    result: Result<T>,
    ok: impl FnOnce(T),
) -> Option<Box<wasmtime_error_t>> {
    match result {
        Ok(value) => {
            ok(value);
            None
        }
        Err(error) => Some(Box::new(wasmtime_error_t { error })),
    }
}

pub(crate) fn bad_utf8() -> Option<Box<wasmtime_error_t>> {
    Some(Box::new(wasmtime_error_t {
        error: anyhow!("input was not valid utf-8"),
    }))
}

#[no_mangle]
pub extern "C" fn wasmtime_error_message(error: &wasmtime_error_t, message: &mut wasm_name_t) {
    message.set_buffer(format!("{:?}", error.error).into_bytes());
}

#[no_mangle]
pub extern "C" fn wasmtime_error_exit_status(raw: &wasmtime_error_t, status: &mut i32) -> bool {
    #[cfg(feature = "wasi")]
    if let Some(exit) = raw.error.downcast_ref::<wasmtime_wasi::I32Exit>() {
        *status = exit.0;
        return true;
    }

    // Squash unused warnings in wasi-disabled builds.
    drop((raw, status));

    false
}

#[no_mangle]
pub extern "C" fn wasmtime_error_wasm_trace<'a>(
    raw: &'a wasmtime_error_t,
    out: &mut wasm_frame_vec_t<'a>,
) {
    crate::trap::error_trace(&raw.error, out)
}