Skip to main content

solana_program_runtime/
abi.rs

1//! The ABI between the program runtime and an executing program.
2
3use {
4    solana_program_entrypoint::{BPF_ALIGN_OF_U128, MAX_PERMITTED_DATA_INCREASE},
5    solana_pubkey::Pubkey,
6    solana_sdk_ids::bpf_loader_deprecated,
7};
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum ABI {
11    /// Program Runtime ABI V0.
12    ///
13    /// The legacy ABI, supported only for programs owned by the deprecated
14    /// Loader V1. Input is unaligned and accounts cannot be reallocated.
15    V0,
16    /// Program Runtime ABI V1.
17    ///
18    /// The current ABI, supported for programs owned by the deprecated Loader
19    /// V2 and the upgradeable Loader V3. Input is aligned to
20    /// [`BPF_ALIGN_OF_U128`] (8 bytes) and each account reserves
21    /// [`MAX_PERMITTED_DATA_INCREASE`] bytes past its data for reallocations.
22    V1,
23}
24
25impl ABI {
26    /// Resolves the ABI of a program from the owner of its program account.
27    pub fn resolve(program_owner: &Pubkey) -> Self {
28        if bpf_loader_deprecated::check_id(program_owner) {
29            Self::V0
30        } else {
31            Self::V1
32        }
33    }
34
35    /// The alignment of the program's input and heap allocations.
36    pub const fn alignment(self) -> usize {
37        match self {
38            Self::V0 => align_of::<u8>(),
39            Self::V1 => BPF_ALIGN_OF_U128,
40        }
41    }
42
43    /// The address space reserved past an account's data for it to grow into.
44    pub const fn account_realloc_padding(self) -> usize {
45        match self {
46            Self::V0 => 0,
47            Self::V1 => MAX_PERMITTED_DATA_INCREASE,
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use {
55        super::*,
56        solana_sdk_ids::{bpf_loader, bpf_loader_upgradeable, loader_v4, native_loader},
57        test_case::test_case,
58    };
59
60    #[test_case(bpf_loader_deprecated::id(), ABI::V0; "loader_v1")]
61    #[test_case(bpf_loader::id(), ABI::V1; "loader_v2")]
62    #[test_case(bpf_loader_upgradeable::id(), ABI::V1; "loader_v3")]
63    #[test_case(loader_v4::id(), ABI::V1; "loader_v4")]
64    #[test_case(native_loader::id(), ABI::V1; "native_loader")]
65    fn test_resolve(program_owner: Pubkey, expected: ABI) {
66        assert_eq!(ABI::resolve(&program_owner), expected);
67    }
68
69    #[test]
70    fn test_v0_properties() {
71        assert_eq!(ABI::V0.alignment(), 1);
72        assert_eq!(ABI::V0.account_realloc_padding(), 0);
73    }
74
75    #[test]
76    fn test_v1_properties() {
77        assert_eq!(ABI::V1.alignment(), BPF_ALIGN_OF_U128);
78        assert_eq!(
79            ABI::V1.account_realloc_padding(),
80            MAX_PERMITTED_DATA_INCREASE,
81        );
82    }
83}