Skip to content

Commit 3534629

Browse files
authored
Improve sysvar get error handling (#181)
* Improve sysvar get error handling * Address review comments * Simplify match arm
1 parent 7500305 commit 3534629

File tree

1 file changed

+23
-4
lines changed
  • sdk/pinocchio/src/sysvars

1 file changed

+23
-4
lines changed

sdk/pinocchio/src/sysvars/mod.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,19 @@ pub mod fees;
1111
pub mod instructions;
1212
pub mod rent;
1313

14+
/// Return value indicating that the `offset + length` is greater than the length of
15+
/// the sysvar data.
16+
//
17+
// Defined in the bpf loader as [`OFFSET_LENGTH_EXCEEDS_SYSVAR`](https://github.com/anza-xyz/agave/blob/master/programs/bpf_loader/src/syscalls/sysvar.rs#L172).
18+
#[cfg(target_os = "solana")]
19+
const OFFSET_LENGTH_EXCEEDS_SYSVAR: u64 = 1;
20+
21+
/// Return value indicating that the sysvar was not found.
22+
//
23+
// Defined in the bpf loader as [`SYSVAR_NOT_FOUND`](https://github.com/anza-xyz/agave/blob/master/programs/bpf_loader/src/syscalls/sysvar.rs#L171).
24+
#[cfg(target_os = "solana")]
25+
const SYSVAR_NOT_FOUND: u64 = 2;
26+
1427
/// A type that holds sysvar data.
1528
pub trait Sysvar: Default + Sized {
1629
/// Load the sysvar directly from the runtime.
@@ -41,9 +54,12 @@ macro_rules! impl_sysvar_get {
4154
let result = core::hint::black_box(var_addr as *const _ as u64);
4255

4356
match result {
44-
// SAFETY: The syscall initialized the memory.
45-
$crate::SUCCESS => Ok(unsafe { var.assume_init() }),
46-
e => Err(e.into()),
57+
$crate::SUCCESS => {
58+
// SAFETY: The syscall initialized the memory.
59+
Ok(unsafe { var.assume_init() })
60+
}
61+
// Unexpected errors are folded into `UnsupportedSysvar`.
62+
_ => Err($crate::program_error::ProgramError::UnsupportedSysvar),
4763
}
4864
}
4965
};
@@ -76,7 +92,10 @@ pub unsafe fn get_sysvar_unchecked(
7692

7793
match result {
7894
crate::SUCCESS => Ok(()),
79-
e => Err(e.into()),
95+
OFFSET_LENGTH_EXCEEDS_SYSVAR => Err(ProgramError::InvalidArgument),
96+
SYSVAR_NOT_FOUND => Err(ProgramError::UnsupportedSysvar),
97+
// Unexpected errors are folded into `UnsupportedSysvar`.
98+
_ => Err(ProgramError::UnsupportedSysvar),
8099
}
81100
}
82101

0 commit comments

Comments
 (0)