1 //! Trap codes describing the reason for a trap.
2 
3 use core::fmt::{self, Display, Formatter};
4 use core::str::FromStr;
5 #[cfg(feature = "enable-serde")]
6 use serde::{Deserialize, Serialize};
7 
8 /// A trap code describing the reason for a trap.
9 ///
10 /// All trap instructions have an explicit trap code.
11 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
12 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
13 pub enum TrapCode {
14     /// The current stack space was exhausted.
15     StackOverflow,
16 
17     /// A `heap_addr` instruction detected an out-of-bounds error.
18     ///
19     /// Note that not all out-of-bounds heap accesses are reported this way;
20     /// some are detected by a segmentation fault on the heap unmapped or
21     /// offset-guard pages.
22     HeapOutOfBounds,
23 
24     /// A wasm atomic operation was presented with a not-naturally-aligned linear-memory address.
25     HeapMisaligned,
26 
27     /// A `table_addr` instruction detected an out-of-bounds error.
28     TableOutOfBounds,
29 
30     /// Indirect call to a null table entry.
31     IndirectCallToNull,
32 
33     /// Signature mismatch on indirect call.
34     BadSignature,
35 
36     /// An integer arithmetic operation caused an overflow.
37     IntegerOverflow,
38 
39     /// An integer division by zero.
40     IntegerDivisionByZero,
41 
42     /// Failed float-to-int conversion.
43     BadConversionToInteger,
44 
45     /// Code that was supposed to have been unreachable was reached.
46     UnreachableCodeReached,
47 
48     /// Execution has potentially run too long and may be interrupted.
49     /// This trap is resumable.
50     Interrupt,
51 
52     /// A user-defined trap code.
53     User(u16),
54 
55     /// A null reference was encountered which was required to be non-null.
56     NullReference,
57 }
58 
59 impl TrapCode {
60     /// Returns a slice of all traps except `TrapCode::User` traps
61     pub const fn non_user_traps() -> &'static [TrapCode] {
62         &[
63             TrapCode::StackOverflow,
64             TrapCode::HeapOutOfBounds,
65             TrapCode::HeapMisaligned,
66             TrapCode::TableOutOfBounds,
67             TrapCode::IndirectCallToNull,
68             TrapCode::BadSignature,
69             TrapCode::IntegerOverflow,
70             TrapCode::IntegerDivisionByZero,
71             TrapCode::BadConversionToInteger,
72             TrapCode::UnreachableCodeReached,
73             TrapCode::Interrupt,
74             TrapCode::NullReference,
75         ]
76     }
77 }
78 
79 impl Display for TrapCode {
80     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
81         use self::TrapCode::*;
82         let identifier = match *self {
83             StackOverflow => "stk_ovf",
84             HeapOutOfBounds => "heap_oob",
85             HeapMisaligned => "heap_misaligned",
86             TableOutOfBounds => "table_oob",
87             IndirectCallToNull => "icall_null",
88             BadSignature => "bad_sig",
89             IntegerOverflow => "int_ovf",
90             IntegerDivisionByZero => "int_divz",
91             BadConversionToInteger => "bad_toint",
92             UnreachableCodeReached => "unreachable",
93             Interrupt => "interrupt",
94             User(x) => return write!(f, "user{}", x),
95             NullReference => "null_reference",
96         };
97         f.write_str(identifier)
98     }
99 }
100 
101 impl FromStr for TrapCode {
102     type Err = ();
103 
104     fn from_str(s: &str) -> Result<Self, Self::Err> {
105         use self::TrapCode::*;
106         match s {
107             "stk_ovf" => Ok(StackOverflow),
108             "heap_oob" => Ok(HeapOutOfBounds),
109             "heap_misaligned" => Ok(HeapMisaligned),
110             "table_oob" => Ok(TableOutOfBounds),
111             "icall_null" => Ok(IndirectCallToNull),
112             "bad_sig" => Ok(BadSignature),
113             "int_ovf" => Ok(IntegerOverflow),
114             "int_divz" => Ok(IntegerDivisionByZero),
115             "bad_toint" => Ok(BadConversionToInteger),
116             "unreachable" => Ok(UnreachableCodeReached),
117             "interrupt" => Ok(Interrupt),
118             "null_reference" => Ok(NullReference),
119             _ if s.starts_with("user") => s[4..].parse().map(User).map_err(|_| ()),
120             _ => Err(()),
121         }
122     }
123 }
124 
125 #[cfg(test)]
126 mod tests {
127     use super::*;
128     use alloc::string::ToString;
129 
130     #[test]
131     fn display() {
132         for r in TrapCode::non_user_traps() {
133             let tc = *r;
134             assert_eq!(tc.to_string().parse(), Ok(tc));
135         }
136         assert_eq!("bogus".parse::<TrapCode>(), Err(()));
137 
138         assert_eq!(TrapCode::User(17).to_string(), "user17");
139         assert_eq!("user22".parse(), Ok(TrapCode::User(22)));
140         assert_eq!("user".parse::<TrapCode>(), Err(()));
141         assert_eq!("user-1".parse::<TrapCode>(), Err(()));
142         assert_eq!("users".parse::<TrapCode>(), Err(()));
143     }
144 }
145