Skip to main content

near_vm_engine/trap/
error.rs

1use super::frame_info::{FRAME_INFO, FrameInfo, GlobalFrameInfo};
2use backtrace::Backtrace;
3use near_vm_vm::{Trap, TrapCode, raise_user_trap};
4use std::error::Error;
5use std::fmt;
6use std::sync::Arc;
7
8/// A struct representing an aborted instruction execution, with a message
9/// indicating the cause.
10#[derive(Clone)]
11pub struct RuntimeError {
12    inner: Arc<RuntimeErrorInner>,
13}
14
15/// The source of the `RuntimeError`.
16#[derive(Debug)]
17enum RuntimeErrorSource {
18    Generic(String),
19    OOM,
20    User(Box<dyn Error + Send + Sync>),
21    Trap(TrapCode),
22}
23
24impl fmt::Display for RuntimeErrorSource {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::Generic(s) => write!(f, "{}", s),
28            Self::User(s) => write!(f, "{}", s),
29            Self::OOM => write!(f, "Wasmer VM out of memory"),
30            Self::Trap(s) => write!(f, "{}", s.message()),
31        }
32    }
33}
34
35struct RuntimeErrorInner {
36    /// The source error (this can be a custom user `Error` or a [`TrapCode`])
37    source: RuntimeErrorSource,
38    /// The reconstructed Wasm trace (from the native trace and the `GlobalFrameInfo`).
39    wasm_trace: Vec<FrameInfo>,
40    /// The native backtrace
41    native_trace: Backtrace,
42}
43
44fn _assert_trap_is_sync_and_send(t: &Trap) -> (&dyn Sync, &dyn Send) {
45    (t, t)
46}
47
48impl RuntimeError {
49    /// Creates a new generic `RuntimeError` with the given `message`.
50    ///
51    /// # Example
52    /// ```
53    /// let trap = near_vm_engine::RuntimeError::new("unexpected error");
54    /// assert_eq!("unexpected error", trap.message());
55    /// ```
56    pub fn new<I: Into<String>>(message: I) -> Self {
57        let info = FRAME_INFO.read();
58        let msg = message.into();
59        Self::new_with_trace(
60            &info,
61            None,
62            RuntimeErrorSource::Generic(msg),
63            Backtrace::new_unresolved(),
64        )
65    }
66
67    /// Create a new RuntimeError from a Trap.
68    pub fn from_trap(trap: Trap) -> Self {
69        let info = FRAME_INFO.read();
70        match trap {
71            // A user error
72            Trap::User(error) => {
73                match error.downcast::<Self>() {
74                    // The error is already a RuntimeError, we return it directly
75                    Ok(runtime_error) => *runtime_error,
76                    Err(e) => Self::new_with_trace(
77                        &info,
78                        None,
79                        RuntimeErrorSource::User(e),
80                        Backtrace::new_unresolved(),
81                    ),
82                }
83            }
84            // A trap caused by the VM being Out of Memory
85            Trap::OOM { backtrace } => {
86                Self::new_with_trace(&info, None, RuntimeErrorSource::OOM, backtrace)
87            }
88            // A trap caused by an error on the generated machine code for a Wasm function
89            Trap::Wasm { pc, signal_trap, backtrace } => {
90                let code = info.lookup_trap_info(pc).map_or_else(
91                    || signal_trap.unwrap_or(TrapCode::StackOverflow),
92                    |info| info.trap_code,
93                );
94                Self::new_with_trace(&info, Some(pc), RuntimeErrorSource::Trap(code), backtrace)
95            }
96            // A trap triggered manually from the Wasmer runtime
97            Trap::Lib { trap_code, backtrace } => {
98                Self::new_with_trace(&info, None, RuntimeErrorSource::Trap(trap_code), backtrace)
99            }
100        }
101    }
102
103    /// Raises a custom user Error
104    pub fn raise(error: Box<dyn Error + Send + Sync>) -> ! {
105        unsafe { raise_user_trap(error) }
106    }
107
108    fn new_with_trace(
109        info: &GlobalFrameInfo,
110        trap_pc: Option<usize>,
111        source: RuntimeErrorSource,
112        native_trace: Backtrace,
113    ) -> Self {
114        let wasm_trace = native_trace
115            .frames()
116            .iter()
117            .filter_map(|frame| {
118                let pc = frame.ip() as usize;
119                if pc == 0 {
120                    None
121                } else {
122                    // Note that we need to be careful about the pc we pass in here to
123                    // lookup frame information. This program counter is used to
124                    // translate back to an original source location in the origin wasm
125                    // module. If this pc is the exact pc that the trap happened at,
126                    // then we look up that pc precisely. Otherwise backtrace
127                    // information typically points at the pc *after* the call
128                    // instruction (because otherwise it's likely a call instruction on
129                    // the stack). In that case we want to lookup information for the
130                    // previous instruction (the call instruction) so we subtract one as
131                    // the lookup.
132                    let pc = if Some(pc) == trap_pc { pc } else { pc - 1 };
133                    info.lookup_frame_info(pc)
134                }
135            })
136            .collect();
137
138        Self { inner: Arc::new(RuntimeErrorInner { source, wasm_trace, native_trace }) }
139    }
140
141    /// Returns a reference the `message` stored in `Trap`.
142    pub fn message(&self) -> String {
143        self.inner.source.to_string()
144    }
145
146    /// Returns a list of function frames in WebAssembly code that led to this
147    /// trap happening.
148    pub fn trace(&self) -> &[FrameInfo] {
149        &self.inner.wasm_trace
150    }
151
152    /// Attempts to downcast the `RuntimeError` to a concrete type.
153    pub fn downcast<T: Error + 'static>(self) -> Result<T, Self> {
154        match Arc::try_unwrap(self.inner) {
155            // We only try to downcast user errors
156            Ok(RuntimeErrorInner { source: RuntimeErrorSource::User(err), .. })
157                if err.is::<T>() =>
158            {
159                Ok(*err.downcast::<T>().unwrap())
160            }
161            Ok(inner) => Err(Self { inner: Arc::new(inner) }),
162            Err(inner) => Err(Self { inner }),
163        }
164    }
165
166    /// Returns trap code, if it's a Trap
167    pub fn to_trap(self) -> Option<TrapCode> {
168        if let RuntimeErrorSource::Trap(trap_code) = self.inner.source {
169            Some(trap_code)
170        } else {
171            None
172        }
173    }
174
175    /// Returns true if the `RuntimeError` is the same as T
176    pub fn is<T: Error + 'static>(&self) -> bool {
177        match &self.inner.source {
178            RuntimeErrorSource::User(err) => err.is::<T>(),
179            _ => false,
180        }
181    }
182}
183
184impl fmt::Debug for RuntimeError {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        f.debug_struct("RuntimeError")
187            .field("source", &self.inner.source)
188            .field("wasm_trace", &self.inner.wasm_trace)
189            .field("native_trace", &self.inner.native_trace)
190            .finish()
191    }
192}
193
194impl fmt::Display for RuntimeError {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        write!(f, "RuntimeError: {}", self.message())?;
197        let trace = self.trace();
198        if trace.is_empty() {
199            return Ok(());
200        }
201        for frame in self.trace() {
202            let name = frame.module_name();
203            let func_index = frame.func_index();
204            writeln!(f)?;
205            write!(f, "    at ")?;
206            match frame.function_name() {
207                Some(name) => match rustc_demangle::try_demangle(name) {
208                    Ok(name) => write!(f, "{}", name)?,
209                    Err(_) => write!(f, "{}", name)?,
210                },
211                None => write!(f, "<unnamed>")?,
212            }
213            write!(f, " ({}[{}]:0x{:x})", name, func_index, frame.module_offset())?;
214        }
215        Ok(())
216    }
217}
218
219impl std::error::Error for RuntimeError {
220    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
221        match &self.inner.source {
222            RuntimeErrorSource::User(err) => Some(&**err),
223            RuntimeErrorSource::Trap(err) => Some(err),
224            _ => None,
225        }
226    }
227}
228
229impl From<Trap> for RuntimeError {
230    fn from(trap: Trap) -> Self {
231        Self::from_trap(trap)
232    }
233}