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 
56 impl Display for TrapCode {
57     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
58         use self::TrapCode::*;
59         let identifier = match *self {
60             StackOverflow => "stk_ovf",
61             HeapOutOfBounds => "heap_oob",
62             HeapMisaligned => "heap_misaligned",
63             TableOutOfBounds => "table_oob",
64             IndirectCallToNull => "icall_null",
65             BadSignature => "bad_sig",
66             IntegerOverflow => "int_ovf",
67             IntegerDivisionByZero => "int_divz",
68             BadConversionToInteger => "bad_toint",
69             UnreachableCodeReached => "unreachable",
70             Interrupt => "interrupt",
71             User(x) => return write!(f, "user{}", x),
72         };
73         f.write_str(identifier)
74     }
75 }
76 
77 impl FromStr for TrapCode {
78     type Err = ();
79 
80     fn from_str(s: &str) -> Result<Self, Self::Err> {
81         use self::TrapCode::*;
82         match s {
83             "stk_ovf" => Ok(StackOverflow),
84             "heap_oob" => Ok(HeapOutOfBounds),
85             "heap_misaligned" => Ok(HeapMisaligned),
86             "table_oob" => Ok(TableOutOfBounds),
87             "icall_null" => Ok(IndirectCallToNull),
88             "bad_sig" => Ok(BadSignature),
89             "int_ovf" => Ok(IntegerOverflow),
90             "int_divz" => Ok(IntegerDivisionByZero),
91             "bad_toint" => Ok(BadConversionToInteger),
92             "unreachable" => Ok(UnreachableCodeReached),
93             "interrupt" => Ok(Interrupt),
94             _ if s.starts_with("user") => s[4..].parse().map(User).map_err(|_| ()),
95             _ => Err(()),
96         }
97     }
98 }
99 
100 #[cfg(test)]
101 mod tests {
102     use super::*;
103     use alloc::string::ToString;
104 
105     // Everything but user-defined codes.
106     const CODES: [TrapCode; 11] = [
107         TrapCode::StackOverflow,
108         TrapCode::HeapOutOfBounds,
109         TrapCode::HeapMisaligned,
110         TrapCode::TableOutOfBounds,
111         TrapCode::IndirectCallToNull,
112         TrapCode::BadSignature,
113         TrapCode::IntegerOverflow,
114         TrapCode::IntegerDivisionByZero,
115         TrapCode::BadConversionToInteger,
116         TrapCode::UnreachableCodeReached,
117         TrapCode::Interrupt,
118     ];
119 
120     #[test]
121     fn display() {
122         for r in &CODES {
123             let tc = *r;
124             assert_eq!(tc.to_string().parse(), Ok(tc));
125         }
126         assert_eq!("bogus".parse::<TrapCode>(), Err(()));
127 
128         assert_eq!(TrapCode::User(17).to_string(), "user17");
129         assert_eq!("user22".parse(), Ok(TrapCode::User(22)));
130         assert_eq!("user".parse::<TrapCode>(), Err(()));
131         assert_eq!("user-1".parse::<TrapCode>(), Err(()));
132         assert_eq!("users".parse::<TrapCode>(), Err(()));
133     }
134 }
135