-
Notifications
You must be signed in to change notification settings - Fork 824
/
trap.rs
286 lines (258 loc) · 8.76 KB
/
trap.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
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
// use super::frame_info::{FrameInfo, GlobalFrameInfo, FRAME_INFO};
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use wasm_bindgen::convert::FromWasmAbi;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsValue;
pub trait CoreError: fmt::Debug + fmt::Display {
fn source(&self) -> Option<&(dyn CoreError + 'static)> {
None
}
fn type_id(&self) -> core::any::TypeId
where
Self: 'static,
{
core::any::TypeId::of::<Self>()
}
fn description(&self) -> &str {
"description() is deprecated; use Display"
}
fn cause(&self) -> Option<&dyn CoreError> {
self.source()
}
}
impl<T: fmt::Debug + fmt::Display> CoreError for T {}
impl dyn CoreError + 'static {
/// Returns `true` if the inner type is the same as `T`.
pub fn core_is_equal<T: CoreError + 'static>(&self) -> bool {
let t = core::any::TypeId::of::<T>();
let concrete = self.type_id();
t == concrete
}
}
impl dyn CoreError + Send + Sync + 'static {
/// Returns `true` if the inner type is the same as `T`.
pub fn core_is_equal<T: CoreError + 'static>(&self) -> bool {
let t = core::any::TypeId::of::<T>();
let concrete = self.type_id();
t == concrete
}
}
impl dyn CoreError + Send {
#[inline]
/// Attempts to downcast the box to a concrete type.
pub fn downcast_core<T: CoreError + 'static>(
self: Box<Self>,
) -> Result<Box<T>, Box<dyn CoreError + Send>> {
let err: Box<dyn CoreError> = self;
<dyn CoreError>::downcast_core(err).map_err(|s| unsafe {
// Reapply the `Send` marker.
core::mem::transmute::<Box<dyn CoreError>, Box<dyn CoreError + Send>>(s)
})
}
}
impl dyn CoreError + Send + Sync {
#[inline]
/// Attempts to downcast the box to a concrete type.
pub fn downcast_core<T: CoreError + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
let err: Box<dyn CoreError> = self;
<dyn CoreError>::downcast_core(err).map_err(|s| unsafe {
// Reapply the `Send + Sync` marker.
core::mem::transmute::<Box<dyn CoreError>, Box<dyn CoreError + Send + Sync>>(s)
})
}
}
impl dyn CoreError {
#[inline]
/// Attempts to downcast the box to a concrete type.
pub fn downcast_core<T: CoreError + 'static>(
self: Box<Self>,
) -> Result<Box<T>, Box<dyn CoreError>> {
if self.core_is_equal::<T>() {
unsafe {
let raw: *mut dyn CoreError = Box::into_raw(self);
Ok(Box::from_raw(raw as *mut T))
}
} else {
Err(self)
}
}
}
/// A struct representing an aborted instruction execution, with a message
/// indicating the cause.
#[wasm_bindgen]
#[derive(Clone)]
pub struct WasmerRuntimeError {
inner: Arc<RuntimeErrorSource>,
}
/// This type is the same as `WasmerRuntimeError`.
///
/// We use the `WasmerRuntimeError` name to not collide with the
/// `RuntimeError` in JS.
pub type RuntimeError = WasmerRuntimeError;
impl PartialEq for RuntimeError {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
/// The source of the `RuntimeError`.
#[derive(Debug)]
enum RuntimeErrorSource {
Generic(String),
#[cfg(feature = "std")]
User(Box<dyn Error + Send + Sync>),
#[cfg(feature = "core")]
User(Box<dyn CoreError + Send + Sync>),
Js(JsValue),
}
/// This is a hack to ensure the error type is Send+Sync
unsafe impl Send for RuntimeErrorSource {}
unsafe impl Sync for RuntimeErrorSource {}
impl fmt::Display for RuntimeErrorSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Generic(s) => write!(f, "{}", s),
Self::User(s) => write!(f, "{}", s),
Self::Js(s) => write!(f, "{:?}", s),
}
}
}
impl RuntimeError {
/// Creates a new generic `RuntimeError` with the given `message`.
///
/// # Example
/// ```
/// let trap = wasmer_compiler::RuntimeError::new("unexpected error");
/// assert_eq!("unexpected error", trap.message());
/// ```
pub fn new<I: Into<String>>(message: I) -> Self {
RuntimeError {
inner: Arc::new(RuntimeErrorSource::Generic(message.into())),
}
}
/// Raises a custom user Error
#[deprecated(since = "2.1.1", note = "return a Result from host functions instead")]
#[cfg(feature = "std")]
pub(crate) fn raise(error: Box<dyn Error + Send + Sync>) -> ! {
let error = Self::user(error);
let js_error: JsValue = error.into();
wasm_bindgen::throw_val(js_error)
}
/// Raises a custom user Error
#[deprecated(since = "2.1.1", note = "return a Result from host functions instead")]
#[cfg(feature = "core")]
pub(crate) fn raise(error: Box<dyn CoreError + Send + Sync>) -> ! {
let error = Self::user(error);
let js_error: JsValue = error.into();
wasm_bindgen::throw_val(js_error)
}
/// Creates a custom user Error.
///
/// This error object can be passed through Wasm frames and later retrieved
/// using the `downcast` method.
#[cfg(feature = "std")]
pub fn user(error: Box<dyn Error + Send + Sync>) -> Self {
match error.downcast::<Self>() {
// The error is already a RuntimeError, we return it directly
Ok(runtime_error) => *runtime_error,
Err(error) => RuntimeError {
inner: Arc::new(RuntimeErrorSource::User(error)),
},
}
}
#[cfg(feature = "core")]
pub fn user(error: Box<dyn CoreError + Send + Sync>) -> Self {
match error.downcast_core::<Self>() {
// The error is already a RuntimeError, we return it directly
Ok(runtime_error) => *runtime_error,
Err(error) => RuntimeError {
inner: Arc::new(RuntimeErrorSource::User(error)),
},
}
}
/// Returns a reference the `message` stored in `Trap`.
pub fn message(&self) -> String {
format!("{}", self.inner)
}
/// Attempts to downcast the `RuntimeError` to a concrete type.
pub fn downcast<T: Error + 'static>(self) -> Result<T, Self> {
match Arc::try_unwrap(self.inner) {
// We only try to downcast user errors
#[cfg(feature = "std")]
Ok(RuntimeErrorSource::User(err)) if err.is::<T>() => Ok(*err.downcast::<T>().unwrap()),
#[cfg(feature = "core")]
Ok(RuntimeErrorSource::User(err)) if (*err).core_is_equal::<T>() => {
Ok(*err.downcast_core::<T>().unwrap())
}
Ok(inner) => Err(Self {
inner: Arc::new(inner),
}),
Err(inner) => Err(Self { inner }),
}
}
/// Returns true if the `RuntimeError` is the same as T
pub fn is<T: Error + 'static>(&self) -> bool {
match self.inner.as_ref() {
#[cfg(feature = "std")]
RuntimeErrorSource::User(err) => err.is::<T>(),
#[cfg(feature = "core")]
RuntimeErrorSource::User(err) => (*err).core_is_equal::<T>(),
_ => false,
}
}
}
impl fmt::Debug for RuntimeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RuntimeError")
.field("source", &self.inner)
.finish()
}
}
impl fmt::Display for RuntimeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RuntimeError: {}", self.message())?;
Ok(())
}
}
#[cfg(feature = "std")]
impl std::error::Error for RuntimeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self.inner.as_ref() {
RuntimeErrorSource::User(err) => Some(&**err),
_ => None,
}
}
}
pub fn generic_of_jsval<T: FromWasmAbi<Abi = u32>>(
js: JsValue,
classname: &str,
) -> Result<T, JsValue> {
use js_sys::{Object, Reflect};
let ctor_name = Object::get_prototype_of(&js).constructor().name();
if ctor_name == classname {
let ptr = Reflect::get(&js, &JsValue::from_str("ptr"))?;
match ptr.as_f64() {
Some(ptr_f64) => {
let foo = unsafe { T::from_abi(ptr_f64 as u32) };
Ok(foo)
}
None => {
// We simply relay the js value
Err(js)
}
}
} else {
Err(js)
}
}
impl From<JsValue> for RuntimeError {
fn from(original: JsValue) -> Self {
// We try to downcast the error and see if it's
// an instance of RuntimeError instead, so we don't need
// to re-wrap it.
generic_of_jsval(original, "WasmerRuntimeError").unwrap_or_else(|js| RuntimeError {
inner: Arc::new(RuntimeErrorSource::Js(js)),
})
}
}