Skip to main content

sp1_primitives/
consts.rs

1use alloc::{
2    string::{String, ToString},
3    vec::Vec,
4};
5use elf::abi::{PF_NONE, PF_R, PF_W, PF_X};
6
7/// The maximum size of the memory in bytes.
8pub const MAXIMUM_MEMORY_SIZE: u64 = (1u64 << 48) - 1;
9
10/// The maximum log2 size of native executor's memory
11pub const MAX_JIT_LOG_ADDR: usize = 40;
12
13/// The number of bits in a byte.
14pub const BYTE_SIZE: usize = 8;
15
16/// The number of bits in a limb.
17pub const LIMB_SIZE: usize = 16;
18
19/// The size of a word in limbs.
20pub const WORD_SIZE: usize = 4;
21
22/// The size of a word in bytes.
23pub const WORD_BYTE_SIZE: usize = 2 * WORD_SIZE;
24
25/// The size of an instruction in bytes.
26pub const INSTRUCTION_WORD_SIZE: usize = 4;
27
28/// The number of bytes necessary to represent a 128-bit integer.
29pub const LONG_WORD_BYTE_SIZE: usize = 2 * WORD_BYTE_SIZE;
30
31/// The log2 page size (in bytes).
32pub const LOG_PAGE_SIZE: usize = 12;
33
34/// The size of a page in bytes.
35pub const PAGE_SIZE: usize = 1 << LOG_PAGE_SIZE;
36
37/// MProtect flags.
38pub const PROT_NONE: u8 = PF_NONE as u8;
39pub const PROT_READ: u8 = PF_R as u8;
40pub const PROT_WRITE: u8 = PF_W as u8;
41pub const PROT_EXEC: u8 = PF_X as u8;
42pub const DEFAULT_PAGE_PROT: u8 = PROT_READ | PROT_WRITE;
43
44/// Permitted page protection combinations:
45/// * Inaccessible: not readable, not writable, not executable
46/// * Read-write: readable, writable, not executable
47/// * Read-execute: readable, not writable, executable
48/// * Read: readable, not writable, not executable
49pub const PERMITTED_PROTS: [u8; 4] =
50    [PROT_NONE, PROT_READ | PROT_WRITE, PROT_READ | PROT_EXEC, PROT_READ];
51
52/// The values here are chosen based on RISC-V's specifications.
53pub const PROT_FAILURE_EXEC: u64 = 1;
54pub const PROT_FAILURE_READ: u64 = 5;
55pub const PROT_FAILURE_WRITE: u64 = 7;
56
57/// ELF segment flag indicating untrusted code.
58pub const PF_UNTRUSTED: u32 = 0x0010_0000;
59
60/// The name of the note section for enabling untrusted programs.
61pub const NOTE_NAME: [u8; 9] = *b"SUCCINCT\0";
62/// The type for the ELF note for enabling untrusted programs.
63pub const NOTE_UNTRUSTED_PROGRAM_ENABLED: u32 = 1;
64/// The ELF note header for untrusted programs.
65pub const NOTE_DESC_HEADER: [u8; 4] = [b'1', 0, 0, 0];
66/// In current version the full desc holds a 4 byte header, and 2 64-bit integers
67/// denoting heap start/end. This is also the memory region mprotect can work on.
68pub const NOTE_DESC_SIZE: usize = NOTE_DESC_HEADER.len() + 8 + 8;
69/// Padding size for note name.
70pub const NOTE_NAME_PADDING_SIZE: usize = (4 - NOTE_NAME.len() % 4) % 4;
71/// Padding size for note desc.
72pub const NOTE_DESC_PADDING_SIZE: usize = (4 - NOTE_DESC_SIZE % 4) % 4;
73
74/// The name of the custom ELF section for the profiler stack.
75pub const PROFILER_STACK_CUSTOM_SECTION_NAME: &str = "__sp1_profiler_stack";
76
77/// The stack top for the 64-bit zkvm.
78/// Programs which might dump elf will have an extra 16MB area used as stack.
79pub const DUMP_ELF_EXTRA_STACK: u64 = 0x100_0000;
80pub const STACK_TOP: u64 = 0x7800_0000;
81
82/// The maximum number of distinct page permission regions generated
83/// in `DUMP_ELF` syscall.
84pub const MAXIMUM_DUMPED_PERMISSIONS: usize = 128;
85
86/// The length of permission array used in `DUMP_ELF` syscall (counting raw u64).
87pub const PERMISSION_ARRAY_LENGTH: usize = MAXIMUM_DUMPED_PERMISSIONS * 3 + 1;
88/// The size of permission array (in bytes) used in `DUMP_ELF` syscall.
89/// It is aligned to 16 bytes so stack can be aligned.
90pub const PERMISSION_BUFFER_SIZE: usize = (PERMISSION_ARRAY_LENGTH * 8).div_ceil(16) * 16;
91
92/// The maximum number of LOAD segments accepted by SP1.
93pub const MAXIMUM_ELF_SEGMENTS: usize = 256;
94
95pub mod fd {
96    /// The minimum file descriptor.
97    ///
98    /// Any file descriptor must be greater than this value, otherwise the executor will panic.
99    ///
100    /// This is useful for deprecating file descriptors.
101    pub const LOWEST_ALLOWED_FD: u32 = 10;
102
103    /// Creates a file descriptor constant, with respect to the minimum file descriptor.
104    macro_rules! create_fd {
105        ($(
106            #[$attr:meta]
107            pub const $name:ident: u32 = $value:expr;
108        )*) => {
109            $(
110                #[$attr]
111                pub const $name: u32 = $value + $crate::consts::fd::LOWEST_ALLOWED_FD;
112            )*
113        }
114    }
115
116    create_fd! {
117        /// The file descriptor for public values.
118        pub const FD_PUBLIC_VALUES: u32 = 3;
119
120        /// The file descriptor for hints.
121        pub const FD_HINT: u32 = 4;
122
123        /// The file descriptor through which to access `hook_ecrecover`.
124        pub const FD_ECRECOVER_HOOK: u32 = 5;
125
126        /// The file descriptor through which to access `hook_ed_decompress`.
127        pub const FD_EDDECOMPRESS: u32 = 6;
128
129        /// The file descriptor through which to access `hook_rsa_mul_mod`.
130        pub const FD_RSA_MUL_MOD: u32 = 7;
131
132        /// The file descriptor through which to access `hook_bls12_381_sqrt`.
133        pub const FD_BLS12_381_SQRT: u32 = 8;
134
135        /// The file descriptor through which to access `hook_bls12_381_inverse`.
136        pub const FD_BLS12_381_INVERSE: u32 = 9;
137
138        /// The file descriptor through which to access `hook_fp_sqrt`.
139        pub const FD_FP_SQRT: u32 = 10;
140
141        /// The file descriptor through which to access `hook_fp_inverse`.
142        pub const FD_FP_INV: u32 = 11;
143    }
144}
145
146/// Converts a slice of words to a byte vector in little endian.
147pub fn words_to_bytes_le_vec<'a>(words: impl IntoIterator<Item = &'a u64>) -> Vec<u8> {
148    words.into_iter().flat_map(|word| word.to_le_bytes().into_iter()).collect::<Vec<_>>()
149}
150
151/// Converts a slice of words to a slice of bytes in little endian.
152pub fn words_to_bytes_le<'a, const B: usize>(words: impl IntoIterator<Item = &'a u64>) -> [u8; B] {
153    let mut iter = words.into_iter().flat_map(|word| word.to_le_bytes().into_iter());
154    core::array::from_fn(|_| iter.next().unwrap())
155}
156
157/// Converts a byte array in little endian to a slice of words.
158pub fn bytes_to_words_le<const W: usize>(bytes: &[u8]) -> [u64; W] {
159    debug_assert_eq!(bytes.len(), W * 8);
160    let mut iter = bytes.chunks_exact(8).map(|chunk| u64::from_le_bytes(chunk.try_into().unwrap()));
161    core::array::from_fn(|_| iter.next().unwrap())
162}
163
164/// Converts a byte array in little endian to a vector of words.
165pub fn bytes_to_words_le_vec(bytes: &[u8]) -> Vec<u64> {
166    bytes
167        .chunks_exact(8)
168        .map(|chunk| u64::from_le_bytes(chunk.try_into().unwrap()))
169        .collect::<Vec<_>>()
170}
171
172// Converts a num to a string with commas every 3 digits.
173pub fn num_to_comma_separated<T: ToString>(value: T) -> String {
174    value
175        .to_string()
176        .chars()
177        .rev()
178        .collect::<Vec<_>>()
179        .chunks(3)
180        .map(|chunk| chunk.iter().collect::<String>())
181        .collect::<Vec<_>>()
182        .join(",")
183        .chars()
184        .rev()
185        .collect()
186}
187
188/// Converts a little endian u32 array into u64 array.
189pub fn u32_to_u64(limbs: &[u32]) -> Vec<u64> {
190    debug_assert!(limbs.len().is_multiple_of(2), "need an even number of u32s");
191    limbs.chunks_exact(2).map(|pair| (pair[0] as u64) | ((pair[1] as u64) << 32)).collect()
192}
193
194/// Converts a little endian u64 array into u32 array.
195pub fn u64_to_u32<'a>(limbs: impl IntoIterator<Item = &'a u64>) -> Vec<u32> {
196    limbs
197        .into_iter()
198        .flat_map(|x| {
199            let lo = *x as u32;
200            let hi = (*x >> 32) as u32;
201            [lo, hi]
202        })
203        .collect()
204}
205
206/// Converts a 32-bit integer to a pair of 16-bit integers.
207pub fn u32_to_u16_limbs(value: u32) -> [u16; 2] {
208    [(value & 0xFFFF) as u16, (value >> 16) as u16]
209}
210
211/// Converts a 64-bit integer to four 16-bit integers.
212pub fn u64_to_u16_limbs(value: u64) -> [u16; 4] {
213    [(value & 0xFFFF) as u16, (value >> 16) as u16, (value >> 32) as u16, (value >> 48) as u16]
214}
215
216// Utility function to split a 64 bit page index into 3 limbs sized 4 bit, 16 bit, and 16 bit (least
217// significant first).
218pub fn split_page_idx(page_idx: u64) -> [u16; 3] {
219    [(page_idx & 0xF) as u16, ((page_idx >> 4) & 0xFFFF) as u16, ((page_idx >> 20) & 0xFFFF) as u16]
220}