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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use super::errors::{
    EnforcedLimitsError,
    FuelError,
    FuncError,
    GlobalError,
    InstantiationError,
    LinkerError,
    MemoryError,
    TableError,
};
use crate::{
    core::{HostError, TrapCode},
    engine::{ResumableHostError, TranslationError},
    module::ReadError,
};
use core::{fmt, fmt::Display};
use std::{boxed::Box, string::String};
use wasmparser::BinaryReaderError as WasmError;

/// The generic Wasmi root error type.
#[derive(Debug)]
pub struct Error {
    /// The underlying kind of the error and its specific information.
    kind: Box<ErrorKind>,
}

#[test]
fn error_size() {
    use core::mem;
    assert_eq!(mem::size_of::<Error>(), 8);
}

impl Error {
    /// Creates a new [`Error`] from the [`ErrorKind`].
    fn from_kind(kind: ErrorKind) -> Self {
        Self {
            kind: Box::new(kind),
        }
    }

    /// Creates a new [`Error`] described by a `message`.
    #[inline]
    #[cold]
    pub fn new<T>(message: T) -> Self
    where
        T: Into<String>,
    {
        Self::from_kind(ErrorKind::Message(message.into().into_boxed_str()))
    }

    /// Creates a custom [`HostError`].
    #[inline]
    #[cold]
    pub fn host<E>(host_error: E) -> Self
    where
        E: HostError,
    {
        Self::from_kind(ErrorKind::Host(Box::new(host_error)))
    }

    /// Creates a new `Error` representing an explicit program exit with a classic `i32` exit status value.
    ///
    /// # Note
    ///
    /// This is usually used as return code by WASI applications.
    #[inline]
    #[cold]
    pub fn i32_exit(status: i32) -> Self {
        Self::from_kind(ErrorKind::I32ExitStatus(status))
    }

    /// Returns the [`ErrorKind`] of the [`Error`].
    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }

    /// Returns a reference to [`TrapCode`] if [`Error`] is a [`TrapCode`].
    pub fn as_trap_code(&self) -> Option<TrapCode> {
        self.kind().as_trap_code()
    }

    /// Returns the classic `i32` exit program code of a `Trap` if any.
    ///
    /// Otherwise returns `None`.
    pub fn i32_exit_status(&self) -> Option<i32> {
        self.kind().as_i32_exit_status()
    }

    /// Downcasts the [`Error`] into the `T: HostError` if possible.
    ///
    /// Returns `None` otherwise.
    #[inline]
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: HostError,
    {
        self.kind
            .as_host()
            .and_then(<(dyn HostError + 'static)>::downcast_ref)
    }

    /// Downcasts the [`Error`] into the `T: HostError` if possible.
    ///
    /// Returns `None` otherwise.
    #[inline]
    pub fn downcast_mut<T>(&mut self) -> Option<&mut T>
    where
        T: HostError,
    {
        self.kind
            .as_host_mut()
            .and_then(<(dyn HostError + 'static)>::downcast_mut)
    }

    /// Consumes `self` to downcast the [`Error`] into the `T: HostError` if possible.
    ///
    /// Returns `None` otherwise.
    #[inline]
    pub fn downcast<T>(self) -> Option<T>
    where
        T: HostError,
    {
        self.kind
            .into_host()
            .and_then(|error| error.downcast().ok())
            .map(|boxed| *boxed)
    }

    pub(crate) fn into_resumable(self) -> Result<ResumableHostError, Error> {
        if matches!(&*self.kind, ErrorKind::ResumableHost(_)) {
            let ErrorKind::ResumableHost(error) = *self.kind else {
                unreachable!("asserted that host error is resumable")
            };
            return Ok(error);
        }
        Err(self)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(&self.kind, f)
    }
}

/// An error that may occur upon operating on Wasm modules or module instances.
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorKind {
    /// A trap code as defined by the WebAssembly specification.
    TrapCode(TrapCode),
    /// A message usually provided by Wasmi users of host function calls.
    Message(Box<str>),
    /// An `i32` exit status usually used by WASI applications.
    I32ExitStatus(i32),
    /// A trap as defined by the WebAssembly specification.
    Host(Box<dyn HostError>),
    /// An error stemming from a host function call with resumable state information.
    ///
    /// # Note
    ///
    /// This variant is meant for internal uses only in order to store data necessary
    /// to resume a call after a host function returned an error. This should never
    /// actually reach user code thus we hide its documentation.
    #[doc(hidden)]
    ResumableHost(ResumableHostError),
    /// A global variable error.
    Global(GlobalError),
    /// A linear memory error.
    Memory(MemoryError),
    /// A table error.
    Table(TableError),
    /// A linker error.
    Linker(LinkerError),
    /// A module instantiation error.
    Instantiation(InstantiationError),
    /// A fuel error.
    Fuel(FuelError),
    /// A function error.
    Func(FuncError),
    /// Encountered when there is a problem with the Wasm input stream.
    Read(ReadError),
    /// Encountered when there is a Wasm parsing or validation error.
    Wasm(WasmError),
    /// Encountered when there is a Wasm to Wasmi translation error.
    Translation(TranslationError),
    /// Encountered when an enforced limit is exceeded.
    Limits(EnforcedLimitsError),
}

impl ErrorKind {
    /// Returns a reference to [`TrapCode`] if [`ErrorKind`] is a [`TrapCode`].
    pub fn as_trap_code(&self) -> Option<TrapCode> {
        match self {
            Self::TrapCode(trap_code) => Some(*trap_code),
            _ => None,
        }
    }

    /// Returns a [`i32`] if [`ErrorKind`] is an [`ErrorKind::I32ExitStatus`].
    pub fn as_i32_exit_status(&self) -> Option<i32> {
        match self {
            Self::I32ExitStatus(exit_status) => Some(*exit_status),
            _ => None,
        }
    }

    /// Returns a dynamic reference to [`HostError`] if [`ErrorKind`] is a [`HostError`].
    pub fn as_host(&self) -> Option<&dyn HostError> {
        match self {
            Self::Host(error) => Some(error.as_ref()),
            _ => None,
        }
    }

    /// Returns a dynamic reference to [`HostError`] if [`ErrorKind`] is a [`HostError`].
    pub fn as_host_mut(&mut self) -> Option<&mut dyn HostError> {
        match self {
            Self::Host(error) => Some(error.as_mut()),
            _ => None,
        }
    }

    /// Returns the [`HostError`] if [`ErrorKind`] is a [`HostError`].
    pub fn into_host(self) -> Option<Box<dyn HostError>> {
        match self {
            Self::Host(error) => Some(error),
            _ => None,
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ErrorKind {}

impl Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::TrapCode(error) => Display::fmt(error, f),
            Self::I32ExitStatus(status) => writeln!(f, "Exited with i32 exit status {status}"),
            Self::Message(message) => Display::fmt(message, f),
            Self::Host(error) => Display::fmt(error, f),
            Self::Global(error) => Display::fmt(error, f),
            Self::Memory(error) => Display::fmt(error, f),
            Self::Table(error) => Display::fmt(error, f),
            Self::Linker(error) => Display::fmt(error, f),
            Self::Func(error) => Display::fmt(error, f),
            Self::Instantiation(error) => Display::fmt(error, f),
            Self::Fuel(error) => Display::fmt(error, f),
            Self::Read(error) => Display::fmt(error, f),
            Self::Wasm(error) => Display::fmt(error, f),
            Self::Translation(error) => Display::fmt(error, f),
            Self::Limits(error) => Display::fmt(error, f),
            Self::ResumableHost(error) => Display::fmt(error, f),
        }
    }
}

macro_rules! impl_from {
    ( $( impl From<$from:ident> for Error::$name:ident );* $(;)? ) => {
        $(
            impl From<$from> for Error {
                #[inline]
                #[cold]
                fn from(error: $from) -> Self {
                    Self::from_kind(ErrorKind::$name(error))
                }
            }
        )*
    }
}
impl_from! {
    impl From<TrapCode> for Error::TrapCode;
    impl From<GlobalError> for Error::Global;
    impl From<MemoryError> for Error::Memory;
    impl From<TableError> for Error::Table;
    impl From<LinkerError> for Error::Linker;
    impl From<InstantiationError> for Error::Instantiation;
    impl From<TranslationError> for Error::Translation;
    impl From<WasmError> for Error::Wasm;
    impl From<ReadError> for Error::Read;
    impl From<FuelError> for Error::Fuel;
    impl From<FuncError> for Error::Func;
    impl From<EnforcedLimitsError> for Error::Limits;
    impl From<ResumableHostError> for Error::ResumableHost;
}

/// An error that can occur upon `memory.grow` or `table.grow`.
#[derive(Copy, Clone)]
pub enum EntityGrowError {
    /// Usually a [`TrapCode::OutOfFuel`] trap.
    TrapCode(TrapCode),
    /// Encountered when `memory.grow` or `table.grow` fails.
    InvalidGrow,
}

impl EntityGrowError {
    /// The WebAssembly specification demands to return this value
    /// if the `memory.grow` or `table.grow` operations fail.
    pub const ERROR_CODE: u32 = u32::MAX;
}

impl From<TrapCode> for EntityGrowError {
    fn from(trap_code: TrapCode) -> Self {
        Self::TrapCode(trap_code)
    }
}