1use {crate::OpcodeError, std::ops::Range, thiserror::Error};
2
3#[derive(Debug, Error)]
4pub enum SBPFError {
5 #[error("Bytecode error: {error}")]
6 BytecodeError {
7 error: String,
8 span: Range<usize>,
9 custom_label: Option<String>,
10 },
11}
12
13impl From<OpcodeError> for SBPFError {
14 fn from(e: OpcodeError) -> Self {
15 match e {
16 OpcodeError::InvalidOpcode { byte } => SBPFError::BytecodeError {
17 error: format!("invalid opcode: 0x{byte:02x}"),
18 span: 0..1,
19 custom_label: Some("Invalid opcode".to_string()),
20 },
21 }
22 }
23}
24
25impl SBPFError {
26 pub fn label(&self) -> &str {
27 match self {
28 Self::BytecodeError { custom_label, .. } => {
29 custom_label.as_deref().unwrap_or("Bytecode error")
30 }
31 }
32 }
33
34 pub fn span(&self) -> &Range<usize> {
35 match self {
36 Self::BytecodeError { span, .. } => span,
37 }
38 }
39}
40
41#[derive(Error, Debug, Clone)]
42pub enum ExecutionError {
43 #[error("Division by zero")]
44 DivisionByZero,
45
46 #[error("Invalid operand")]
47 InvalidOperand,
48
49 #[error("Invalid instruction format")]
50 InvalidInstruction,
51
52 #[error("Call depth exceeded (max {0})")]
53 CallDepthExceeded(usize),
54
55 #[error("Invalid memory access at address {0:#x}")]
56 InvalidMemoryAccess(u64),
57
58 #[error("Syscall error: {0}")]
59 SyscallError(String),
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[test]
67 fn test_bytecode_error() {
68 let error = SBPFError::BytecodeError {
69 error: "Invalid opcode".to_string(),
70 span: 10..20,
71 custom_label: Some("Custom error message".to_string()),
72 };
73
74 assert_eq!(error.label(), "Custom error message");
75 assert_eq!(error.span(), &(10..20));
76 assert_eq!(error.to_string(), "Bytecode error: Invalid opcode");
77 }
78}