wasmer_types/
trapcode.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4//! Trap codes describing the reason for a trap.
5
6use core::fmt::{self, Display, Formatter};
7use core::str::FromStr;
8use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
9#[cfg(feature = "enable-serde")]
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13/// A trap code describing the reason for a trap.
14///
15/// All trap instructions have an explicit trap code.
16#[derive(
17    Clone, Copy, PartialEq, Eq, Debug, Hash, Error, RkyvSerialize, RkyvDeserialize, Archive,
18)]
19#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
20#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
21#[rkyv(derive(Debug), compare(PartialEq))]
22#[repr(u32)]
23pub enum TrapCode {
24    /// The current stack space was exhausted.
25    ///
26    /// On some platforms, a stack overflow may also be indicated by a segmentation fault from the
27    /// stack guard page.
28    StackOverflow = 0,
29
30    /// A `heap_addr` instruction detected an out-of-bounds error.
31    ///
32    /// Note that not all out-of-bounds heap accesses are reported this way;
33    /// some are detected by a segmentation fault on the heap unmapped or
34    /// offset-guard pages.
35    HeapAccessOutOfBounds = 1,
36
37    /// A `heap_addr` instruction was misaligned.
38    HeapMisaligned = 2,
39
40    /// A `table_addr` instruction detected an out-of-bounds error.
41    TableAccessOutOfBounds = 3,
42
43    /// Indirect call to a null table entry.
44    IndirectCallToNull = 4,
45
46    /// Signature mismatch on indirect call.
47    BadSignature = 5,
48
49    /// An integer arithmetic operation caused an overflow.
50    IntegerOverflow = 6,
51
52    /// An integer division by zero.
53    IntegerDivisionByZero = 7,
54
55    /// Failed float-to-int conversion.
56    BadConversionToInteger = 8,
57
58    /// Code that was supposed to have been unreachable was reached.
59    UnreachableCodeReached = 9,
60
61    /// An atomic memory access was attempted with an unaligned pointer.
62    UnalignedAtomic = 10,
63
64    /// An exception was thrown but it was left uncaught.
65    UncaughtException = 11,
66}
67
68impl TrapCode {
69    /// Gets the message for this trap code
70    pub fn message(&self) -> &str {
71        match self {
72            Self::StackOverflow => "call stack exhausted",
73            Self::HeapAccessOutOfBounds => "out of bounds memory access",
74            Self::HeapMisaligned => "misaligned heap",
75            Self::TableAccessOutOfBounds => "undefined element: out of bounds table access",
76            Self::IndirectCallToNull => "uninitialized element",
77            Self::BadSignature => "indirect call type mismatch",
78            Self::IntegerOverflow => "integer overflow",
79            Self::IntegerDivisionByZero => "integer divide by zero",
80            Self::BadConversionToInteger => "invalid conversion to integer",
81            Self::UnreachableCodeReached => "unreachable",
82            Self::UnalignedAtomic => "unaligned atomic access",
83            Self::UncaughtException => "uncaught exception",
84        }
85    }
86}
87
88impl Display for TrapCode {
89    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
90        let identifier = match *self {
91            Self::StackOverflow => "stk_ovf",
92            Self::HeapAccessOutOfBounds => "heap_get_oob",
93            Self::HeapMisaligned => "heap_misaligned",
94            Self::TableAccessOutOfBounds => "table_get_oob",
95            Self::IndirectCallToNull => "icall_null",
96            Self::BadSignature => "bad_sig",
97            Self::IntegerOverflow => "int_ovf",
98            Self::IntegerDivisionByZero => "int_divz",
99            Self::BadConversionToInteger => "bad_toint",
100            Self::UnreachableCodeReached => "unreachable",
101            Self::UnalignedAtomic => "unalign_atom",
102            Self::UncaughtException => "uncaught_exception",
103        };
104        f.write_str(identifier)
105    }
106}
107
108impl FromStr for TrapCode {
109    type Err = ();
110
111    fn from_str(s: &str) -> Result<Self, Self::Err> {
112        match s {
113            "stk_ovf" => Ok(Self::StackOverflow),
114            "heap_get_oob" => Ok(Self::HeapAccessOutOfBounds),
115            "heap_misaligned" => Ok(Self::HeapMisaligned),
116            "table_get_oob" => Ok(Self::TableAccessOutOfBounds),
117            "icall_null" => Ok(Self::IndirectCallToNull),
118            "bad_sig" => Ok(Self::BadSignature),
119            "int_ovf" => Ok(Self::IntegerOverflow),
120            "int_divz" => Ok(Self::IntegerDivisionByZero),
121            "bad_toint" => Ok(Self::BadConversionToInteger),
122            "unreachable" => Ok(Self::UnreachableCodeReached),
123            "unalign_atom" => Ok(Self::UnalignedAtomic),
124            _ => Err(()),
125        }
126    }
127}
128
129// TODO: OnCalledAction is needed for asyncify. It will be refactored with https://github.com/wasmerio/wasmer/issues/3451
130/// After the stack is unwound via asyncify what
131/// should the call loop do next
132#[derive(Debug)]
133pub enum OnCalledAction {
134    /// Will call the function again
135    InvokeAgain,
136    /// Will return the result of the invocation
137    Finish,
138    /// Traps with an error
139    Trap(Box<dyn std::error::Error + Send + Sync>),
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    // Everything but user-defined codes.
147    const CODES: [TrapCode; 11] = [
148        TrapCode::StackOverflow,
149        TrapCode::HeapAccessOutOfBounds,
150        TrapCode::HeapMisaligned,
151        TrapCode::TableAccessOutOfBounds,
152        TrapCode::IndirectCallToNull,
153        TrapCode::BadSignature,
154        TrapCode::IntegerOverflow,
155        TrapCode::IntegerDivisionByZero,
156        TrapCode::BadConversionToInteger,
157        TrapCode::UnreachableCodeReached,
158        TrapCode::UnalignedAtomic,
159    ];
160
161    #[test]
162    fn display() {
163        for r in &CODES {
164            let tc = *r;
165            assert_eq!(tc.to_string().parse(), Ok(tc));
166        }
167        assert_eq!("bogus".parse::<TrapCode>(), Err(()));
168
169        // assert_eq!(TrapCode::User(17).to_string(), "user17");
170        // assert_eq!("user22".parse(), Ok(TrapCode::User(22)));
171        assert_eq!("user".parse::<TrapCode>(), Err(()));
172        assert_eq!("user-1".parse::<TrapCode>(), Err(()));
173        assert_eq!("users".parse::<TrapCode>(), Err(()));
174    }
175}