wasmer_types/
error.rs

1//! The WebAssembly possible errors
2use crate::{ExternType, Pages};
3use std::io;
4use thiserror::Error;
5
6/// The Serialize error can occur when serializing a
7/// compiled Module into a binary.
8#[derive(Error, Debug)]
9pub enum SerializeError {
10    /// An IO error
11    #[error(transparent)]
12    Io(#[from] io::Error),
13    /// A generic serialization error
14    #[error("{0}")]
15    Generic(String),
16}
17
18/// The Deserialize error can occur when loading a
19/// compiled Module from a binary.
20#[derive(Error, Debug)]
21pub enum DeserializeError {
22    /// An IO error
23    #[error(transparent)]
24    Io(#[from] io::Error),
25    /// A generic deserialization error
26    #[error("{0}")]
27    Generic(String),
28    /// Incompatible serialized binary
29    #[error("incompatible binary: {0}")]
30    Incompatible(String),
31    /// The provided binary is corrupted
32    #[error("corrupted binary: {0}")]
33    CorruptedBinary(String),
34    /// The binary was valid, but we got an error when
35    /// trying to allocate the required resources.
36    #[error(transparent)]
37    Compiler(#[from] CompileError),
38    /// Input artifact bytes have an invalid length
39    #[error("invalid input bytes: expected {expected} bytes, got {got}")]
40    InvalidByteLength {
41        /// How many bytes were expected
42        expected: usize,
43        /// How many bytes the artifact contained
44        got: usize,
45    },
46}
47
48/// Error type describing things that can go wrong when operating on Wasm Memories.
49#[derive(Error, Debug, Clone, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51pub enum MemoryError {
52    /// Low level error with mmap.
53    #[error("Error when allocating memory: {0}")]
54    Region(String),
55    /// The operation would cause the size of the memory to exceed the maximum or would cause
56    /// an overflow leading to unindexable memory.
57    #[error("The memory could not grow: current size {} pages, requested increase: {} pages", current.0, attempted_delta.0)]
58    CouldNotGrow {
59        /// The current size in pages.
60        current: Pages,
61        /// The attempted amount to grow by in pages.
62        attempted_delta: Pages,
63    },
64    /// Invalid memory was provided.
65    #[error("The memory is invalid because {}", reason)]
66    InvalidMemory {
67        /// The reason why the provided memory is invalid.
68        reason: String,
69    },
70    /// Caller asked for more minimum memory than we can give them.
71    #[error("The minimum requested ({} pages) memory is greater than the maximum allowed memory ({} pages)", min_requested.0, max_allowed.0)]
72    MinimumMemoryTooLarge {
73        /// The number of pages requested as the minimum amount of memory.
74        min_requested: Pages,
75        /// The maximum amount of memory we can allocate.
76        max_allowed: Pages,
77    },
78    /// Caller asked for a maximum memory greater than we can give them.
79    #[error("The maximum requested memory ({} pages) is greater than the maximum allowed memory ({} pages)", max_requested.0, max_allowed.0)]
80    MaximumMemoryTooLarge {
81        /// The number of pages requested as the maximum amount of memory.
82        max_requested: Pages,
83        /// The number of pages requested as the maximum amount of memory.
84        max_allowed: Pages,
85    },
86    /// Returned when a shared memory is required, but the given memory is not shared.
87    #[error("The memory is not shared")]
88    MemoryNotShared,
89    /// Returned when trying to call a memory operation that is not supported by
90    /// the particular memory implementation.
91    #[error("tried to call an unsupported memory operation: {message}")]
92    UnsupportedOperation {
93        /// Message describing the unsupported operation.
94        message: String,
95    },
96    /// The memory does not support atomic operations.
97    #[error("The memory does not support atomic operations")]
98    AtomicsNotSupported,
99    /// A user defined error value, used for error cases not listed above.
100    #[error("A user-defined error occurred: {0}")]
101    Generic(String),
102}
103
104/// An ImportError.
105///
106/// Note: this error is not standard to WebAssembly, but it's
107/// useful to determine the import issue on the API side.
108#[derive(Error, Debug, Clone)]
109pub enum ImportError {
110    /// Incompatible Import Type.
111    /// This error occurs when the import types mismatch.
112    #[error("incompatible import type. Expected {0:?} but received {1:?}")]
113    IncompatibleType(ExternType, ExternType),
114
115    /// Unknown Import.
116    /// This error occurs when an import was expected but not provided.
117    #[error("unknown import. Expected {0:?}")]
118    UnknownImport(ExternType),
119
120    /// Memory Error
121    #[error("memory error. {0}")]
122    MemoryError(String),
123}
124
125/// An error while preinstantiating a module.
126///
127#[derive(Error, Debug)]
128pub enum PreInstantiationError {
129    /// The module was compiled with a CPU feature that is not available on
130    /// the current host.
131    #[error("module compiled with CPU feature that is missing from host")]
132    CpuFeature(String),
133}
134
135use crate::lib::std::string::String;
136
137// Compilation Errors
138//
139// If `std` feature is enable, we can't use `thiserror` until
140// https://github.com/dtolnay/thiserror/pull/64 is merged.
141
142/// The WebAssembly.CompileError object indicates an error during
143/// WebAssembly decoding or validation.
144///
145/// This mirrors the WebAssembly `CompileError` API described at
146/// <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError>.
147#[derive(Debug)]
148#[cfg_attr(feature = "std", derive(Error))]
149pub enum CompileError {
150    /// A Wasm translation error occured.
151    #[cfg_attr(feature = "std", error("WebAssembly translation error: {0}"))]
152    Wasm(WasmError),
153
154    /// A compilation error occured.
155    #[cfg_attr(feature = "std", error("Compilation error: {0}"))]
156    Codegen(String),
157
158    /// The module did not pass validation.
159    #[cfg_attr(feature = "std", error("Validation error: {0}"))]
160    Validate(String),
161
162    /// The compiler doesn't support a Wasm feature
163    #[cfg_attr(feature = "std", error("Feature {0} is not yet supported"))]
164    UnsupportedFeature(String),
165
166    /// The compiler cannot compile for the given target.
167    /// This can refer to the OS, the chipset or any other aspect of the target system.
168    #[cfg_attr(
169        feature = "std",
170        error("The target {0} is not yet supported (see https://docs.wasmer.io/runtime/features)")
171    )]
172    UnsupportedTarget(String),
173
174    /// Insufficient resources available for execution.
175    #[cfg_attr(feature = "std", error("Insufficient resources: {0}"))]
176    Resource(String),
177
178    /// Middleware error occurred.
179    #[cfg_attr(feature = "std", error("Middleware error: {0}"))]
180    MiddlewareError(String),
181}
182
183impl From<WasmError> for CompileError {
184    fn from(original: WasmError) -> Self {
185        Self::Wasm(original)
186    }
187}
188
189/// A error in the middleware.
190#[derive(Debug)]
191#[cfg_attr(feature = "std", derive(Error))]
192#[cfg_attr(feature = "std", error("Error in middleware {name}: {message}"))]
193pub struct MiddlewareError {
194    /// The name of the middleware where the error was created
195    pub name: String,
196    /// The error message
197    pub message: String,
198}
199
200impl MiddlewareError {
201    /// Create a new `MiddlewareError`
202    pub fn new<A: Into<String>, B: Into<String>>(name: A, message: B) -> Self {
203        Self {
204            name: name.into(),
205            message: message.into(),
206        }
207    }
208}
209
210/// A WebAssembly translation error.
211///
212/// When a WebAssembly function can't be translated, one of these error codes will be returned
213/// to describe the failure.
214#[derive(Debug)]
215#[cfg_attr(feature = "std", derive(Error))]
216pub enum WasmError {
217    /// The input WebAssembly code is invalid.
218    ///
219    /// This error code is used by a WebAssembly translator when it encounters invalid WebAssembly
220    /// code. This should never happen for validated WebAssembly code.
221    #[cfg_attr(
222        feature = "std",
223        error("Invalid input WebAssembly code at offset {offset}: {message}")
224    )]
225    InvalidWebAssembly {
226        /// A string describing the validation error.
227        message: String,
228        /// The bytecode offset where the error occurred.
229        offset: usize,
230    },
231
232    /// A feature used by the WebAssembly code is not supported by the embedding environment.
233    ///
234    /// Embedding environments may have their own limitations and feature restrictions.
235    #[cfg_attr(feature = "std", error("Unsupported feature: {0}"))]
236    Unsupported(String),
237
238    /// An implementation limit was exceeded.
239    #[cfg_attr(feature = "std", error("Implementation limit exceeded"))]
240    ImplLimitExceeded,
241
242    /// An error from the middleware error.
243    #[cfg_attr(feature = "std", error("{0}"))]
244    Middleware(MiddlewareError),
245
246    /// A generic error.
247    #[cfg_attr(feature = "std", error("{0}"))]
248    Generic(String),
249}
250
251impl From<MiddlewareError> for WasmError {
252    fn from(original: MiddlewareError) -> Self {
253        Self::Middleware(original)
254    }
255}
256
257/// The error that can happen while parsing a `str`
258/// to retrieve a [`CpuFeature`](crate::target::CpuFeature).
259#[derive(Debug)]
260#[cfg_attr(feature = "std", derive(Error))]
261pub enum ParseCpuFeatureError {
262    /// The provided string feature doesn't exist
263    #[cfg_attr(feature = "std", error("CpuFeature {0} not recognized"))]
264    Missing(String),
265}
266
267/// A convenient alias for a `Result` that uses `WasmError` as the error type.
268pub type WasmResult<T> = Result<T, WasmError>;
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn middleware_error_can_be_created() {
276        let msg = String::from("Something went wrong");
277        let error = MiddlewareError::new("manipulator3000", msg);
278        assert_eq!(error.name, "manipulator3000");
279        assert_eq!(error.message, "Something went wrong");
280    }
281
282    #[test]
283    fn middleware_error_be_converted_to_wasm_error() {
284        let error = WasmError::from(MiddlewareError::new("manipulator3000", "foo"));
285        match error {
286            WasmError::Middleware(MiddlewareError { name, message }) => {
287                assert_eq!(name, "manipulator3000");
288                assert_eq!(message, "foo");
289            }
290            err => panic!("Unexpected error: {err:?}"),
291        }
292    }
293}