cbe_program/entrypoint.rs
1//! The Rust-based BPF program entrypoint supported by the latest BPF loader.
2//!
3//! For more information see the [`bpf_loader`] module.
4//!
5//! [`bpf_loader`]: crate::bpf_loader
6
7extern crate alloc;
8use {
9 crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey},
10 alloc::vec::Vec,
11 std::{
12 alloc::Layout,
13 cell::RefCell,
14 mem::size_of,
15 ptr::null_mut,
16 rc::Rc,
17 result::Result as ResultGeneric,
18 slice::{from_raw_parts, from_raw_parts_mut},
19 },
20};
21
22pub type ProgramResult = ResultGeneric<(), ProgramError>;
23
24/// User implemented function to process an instruction
25///
26/// program_id: Program ID of the currently executing program accounts: Accounts
27/// passed as part of the instruction instruction_data: Instruction data
28pub type ProcessInstruction =
29 fn(program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult;
30
31/// Programs indicate success with a return value of 0
32pub const SUCCESS: u64 = 0;
33
34/// Start address of the memory region used for program heap.
35pub const HEAP_START_ADDRESS: u64 = 0x300000000;
36/// Length of the heap memory region used for program heap.
37pub const HEAP_LENGTH: usize = 32 * 1024;
38
39/// Value used to indicate that a serialized account is not a duplicate
40pub const NON_DUP_MARKER: u8 = u8::MAX;
41
42/// Declare the program entrypoint and set up global handlers.
43///
44/// This macro emits the common boilerplate necessary to begin program
45/// execution, calling a provided function to process the program instruction
46/// supplied by the runtime, and reporting its result to the runtime.
47///
48/// It also sets up a [global allocator] and [panic handler], using the
49/// [`custom_heap_default`] and [`custom_panic_default`] macros.
50///
51/// [`custom_heap_default`]: crate::custom_heap_default
52/// [`custom_panic_default`]: crate::custom_panic_default
53///
54/// [global allocator]: https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html
55/// [panic handler]: https://doc.rust-lang.org/nomicon/panic-handler.html
56///
57/// The argument is the name of a function with this type signature:
58///
59/// ```ignore
60/// fn process_instruction(
61/// program_id: &Pubkey, // Public key of the account the program was loaded into
62/// accounts: &[AccountInfo], // All accounts required to process the instruction
63/// instruction_data: &[u8], // Serialized instruction-specific data
64/// ) -> ProgramResult;
65/// ```
66///
67/// # Cargo features
68///
69/// This macro emits symbols and definitions that may only be defined once
70/// globally. As such, if linked to other Rust crates it will cause compiler
71/// errors. To avoid this, it is common for Cartallum CBE programs to define an
72/// optional [Cargo feature] called `no-entrypoint`, and use it to conditionally
73/// disable the `entrypoint` macro invocation, as well as the
74/// `process_instruction` function. See a typical pattern for this in the
75/// example below.
76///
77/// [Cargo feature]: https://doc.rust-lang.org/cargo/reference/features.html
78///
79/// The code emitted by this macro can be customized by adding cargo features
80/// _to your own crate_ (the one that calls this macro) and enabling them:
81///
82/// - If the `custom-heap` feature is defined then the macro will not set up the
83/// global allocator, allowing `entrypoint` to be used with your own
84/// allocator. See documentation for the [`custom_heap_default`] macro for
85/// details of customizing the global allocator.
86///
87/// - If the `custom-panic` feature is defined then the macro will not define a
88/// panic handler, allowing `entrypoint` to be used with your own panic
89/// handler. See documentation for the [`custom_panic_default`] macro for
90/// details of customizing the panic handler.
91///
92/// # Examples
93///
94/// Defining an entrypoint and making it conditional on the `no-entrypoint`
95/// feature. Although the `entrypoint` module is written inline in this example,
96/// it is common to put it into its own file.
97///
98/// ```no_run
99/// #[cfg(not(feature = "no-entrypoint"))]
100/// pub mod entrypoint {
101///
102/// use cbe_program::{
103/// account_info::AccountInfo,
104/// entrypoint,
105/// entrypoint::ProgramResult,
106/// msg,
107/// pubkey::Pubkey,
108/// };
109///
110/// entrypoint!(process_instruction);
111///
112/// pub fn process_instruction(
113/// program_id: &Pubkey,
114/// accounts: &[AccountInfo],
115/// instruction_data: &[u8],
116/// ) -> ProgramResult {
117/// msg!("Hello world");
118///
119/// Ok(())
120/// }
121///
122/// }
123/// ```
124#[macro_export]
125macro_rules! entrypoint {
126 ($process_instruction:ident) => {
127 /// # Safety
128 #[no_mangle]
129 pub unsafe extern "C" fn entrypoint(input: *mut u8) -> u64 {
130 let (program_id, accounts, instruction_data) =
131 unsafe { $crate::entrypoint::deserialize(input) };
132 match $process_instruction(&program_id, &accounts, &instruction_data) {
133 Ok(()) => $crate::entrypoint::SUCCESS,
134 Err(error) => error.into(),
135 }
136 }
137 $crate::custom_heap_default!();
138 $crate::custom_panic_default!();
139 };
140}
141
142/// Define the default global allocator.
143///
144/// The default global allocator is enabled only if the calling crate has not
145/// disabled it using [Cargo features] as described below. It is only defined
146/// for [BPF] targets.
147///
148/// [Cargo features]: https://doc.rust-lang.org/cargo/reference/features.html
149/// [BPF]: https://docs.cartallum.com/developing/on-chain-programs/overview#berkeley-packet-filter-bpf
150///
151/// # Cargo features
152///
153/// A crate that calls this macro can provide its own custom heap
154/// implementation, or allow others to provide their own custom heap
155/// implementation, by adding a `custom-heap` feature to its `Cargo.toml`. After
156/// enabling the feature, one may define their own [global allocator] in the
157/// standard way.
158///
159/// [global allocator]: https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html
160///
161#[macro_export]
162macro_rules! custom_heap_default {
163 () => {
164 #[cfg(all(not(feature = "custom-heap"), target_os = "cbe"))]
165 #[global_allocator]
166 static A: $crate::entrypoint::BumpAllocator = $crate::entrypoint::BumpAllocator {
167 start: $crate::entrypoint::HEAP_START_ADDRESS as usize,
168 len: $crate::entrypoint::HEAP_LENGTH,
169 };
170 };
171}
172
173/// Define the default global panic handler.
174///
175/// This must be used if the [`entrypoint`] macro is not used, and no other
176/// panic handler has been defined; otherwise compilation will fail with a
177/// missing `custom_panic` symbol.
178///
179/// The default global allocator is enabled only if the calling crate has not
180/// disabled it using [Cargo features] as described below. It is only defined
181/// for [BPF] targets.
182///
183/// [Cargo features]: https://doc.rust-lang.org/cargo/reference/features.html
184/// [BPF]: https://docs.cartallum.com/developing/on-chain-programs/overview#berkeley-packet-filter-bpf
185///
186/// # Cargo features
187///
188/// A crate that calls this macro can provide its own custom panic handler, or
189/// allow others to provide their own custom panic handler, by adding a
190/// `custom-panic` feature to its `Cargo.toml`. After enabling the feature, one
191/// may define their own panic handler.
192///
193/// A good way to reduce the final size of the program is to provide a
194/// `custom_panic` implementation that does nothing. Doing so will cut ~25kb
195/// from a noop program. That number goes down the more the programs pulls in
196/// Rust's standard library for other purposes.
197///
198/// # Defining a panic handler for Cartallum CBE
199///
200/// _The mechanism for defining a Cartallum CBE panic handler is different [from most
201/// Rust programs][rpanic]._
202///
203/// [rpanic]: https://doc.rust-lang.org/nomicon/panic-handler.html
204///
205/// To define a panic handler one must define a `custom_panic` function
206/// with the `#[no_mangle]` attribute, as below:
207///
208/// ```ignore
209/// #[cfg(all(feature = "custom-panic", target_os = "cbe"))]
210/// #[no_mangle]
211/// fn custom_panic(info: &core::panic::PanicInfo<'_>) {
212/// $crate::msg!("{}", info);
213/// }
214/// ```
215///
216/// The above is how Cartallum CBE defines the default panic handler.
217#[macro_export]
218macro_rules! custom_panic_default {
219 () => {
220 #[cfg(all(not(feature = "custom-panic"), target_os = "cbe"))]
221 #[no_mangle]
222 fn custom_panic(info: &core::panic::PanicInfo<'_>) {
223 // Full panic reporting
224 $crate::msg!("{}", info);
225 }
226 };
227}
228
229/// The bump allocator used as the default rust heap when running programs.
230pub struct BumpAllocator {
231 pub start: usize,
232 pub len: usize,
233}
234/// Integer arithmetic in this global allocator implementation is safe when
235/// operating on the prescribed `HEAP_START_ADDRESS` and `HEAP_LENGTH`. Any
236/// other use may overflow and is thus unsupported and at one's own risk.
237#[allow(clippy::integer_arithmetic)]
238unsafe impl std::alloc::GlobalAlloc for BumpAllocator {
239 #[inline]
240 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
241 let pos_ptr = self.start as *mut usize;
242
243 let mut pos = *pos_ptr;
244 if pos == 0 {
245 // First time, set starting position
246 pos = self.start + self.len;
247 }
248 pos = pos.saturating_sub(layout.size());
249 pos &= !(layout.align().wrapping_sub(1));
250 if pos < self.start + size_of::<*mut u8>() {
251 return null_mut();
252 }
253 *pos_ptr = pos;
254 pos as *mut u8
255 }
256 #[inline]
257 unsafe fn dealloc(&self, _: *mut u8, _: Layout) {
258 // I'm a bump allocator, I don't free
259 }
260}
261
262/// Maximum number of bytes a program may add to an account during a single realloc
263pub const MAX_PERMITTED_DATA_INCREASE: usize = 1_024 * 10;
264
265/// `assert_eq(std::mem::align_of::<u128>(), 8)` is true for BPF but not for some host machines
266pub const BPF_ALIGN_OF_U128: usize = 8;
267
268/// Deserialize the input arguments
269///
270/// The integer arithmetic in this method is safe when called on a buffer that was
271/// serialized by runtime. Use with buffers serialized otherwise is unsupported and
272/// done at one's own risk.
273///
274/// # Safety
275#[allow(clippy::integer_arithmetic)]
276#[allow(clippy::type_complexity)]
277pub unsafe fn deserialize<'a>(input: *mut u8) -> (&'a Pubkey, Vec<AccountInfo<'a>>, &'a [u8]) {
278 let mut offset: usize = 0;
279
280 // Number of accounts present
281
282 #[allow(clippy::cast_ptr_alignment)]
283 let num_accounts = *(input.add(offset) as *const u64) as usize;
284 offset += size_of::<u64>();
285
286 // Account Infos
287
288 let mut accounts = Vec::with_capacity(num_accounts);
289 for _ in 0..num_accounts {
290 let dup_info = *(input.add(offset) as *const u8);
291 offset += size_of::<u8>();
292 if dup_info == NON_DUP_MARKER {
293 #[allow(clippy::cast_ptr_alignment)]
294 let is_signer = *(input.add(offset) as *const u8) != 0;
295 offset += size_of::<u8>();
296
297 #[allow(clippy::cast_ptr_alignment)]
298 let is_writable = *(input.add(offset) as *const u8) != 0;
299 offset += size_of::<u8>();
300
301 #[allow(clippy::cast_ptr_alignment)]
302 let executable = *(input.add(offset) as *const u8) != 0;
303 offset += size_of::<u8>();
304
305 // The original data length is stored here because these 4 bytes were
306 // originally only used for padding and served as a good location to
307 // track the original size of the account data in a compatible way.
308 let original_data_len_offset = offset;
309 offset += size_of::<u32>();
310
311 let key: &Pubkey = &*(input.add(offset) as *const Pubkey);
312 offset += size_of::<Pubkey>();
313
314 let owner: &Pubkey = &*(input.add(offset) as *const Pubkey);
315 offset += size_of::<Pubkey>();
316
317 #[allow(clippy::cast_ptr_alignment)]
318 let scoobies = Rc::new(RefCell::new(&mut *(input.add(offset) as *mut u64)));
319 offset += size_of::<u64>();
320
321 #[allow(clippy::cast_ptr_alignment)]
322 let data_len = *(input.add(offset) as *const u64) as usize;
323 offset += size_of::<u64>();
324
325 // Store the original data length for detecting invalid reallocations and
326 // requires that MAX_PERMITTED_DATA_LENGTH fits in a u32
327 *(input.add(original_data_len_offset) as *mut u32) = data_len as u32;
328
329 let data = Rc::new(RefCell::new({
330 from_raw_parts_mut(input.add(offset), data_len)
331 }));
332 offset += data_len + MAX_PERMITTED_DATA_INCREASE;
333 offset += (offset as *const u8).align_offset(BPF_ALIGN_OF_U128); // padding
334
335 #[allow(clippy::cast_ptr_alignment)]
336 let rent_epoch = *(input.add(offset) as *const u64);
337 offset += size_of::<u64>();
338
339 accounts.push(AccountInfo {
340 key,
341 is_signer,
342 is_writable,
343 scoobies,
344 data,
345 owner,
346 executable,
347 rent_epoch,
348 });
349 } else {
350 offset += 7; // padding
351
352 // Duplicate account, clone the original
353 accounts.push(accounts[dup_info as usize].clone());
354 }
355 }
356
357 // Instruction data
358
359 #[allow(clippy::cast_ptr_alignment)]
360 let instruction_data_len = *(input.add(offset) as *const u64) as usize;
361 offset += size_of::<u64>();
362
363 let instruction_data = { from_raw_parts(input.add(offset), instruction_data_len) };
364 offset += instruction_data_len;
365
366 // Program Id
367
368 let program_id: &Pubkey = &*(input.add(offset) as *const Pubkey);
369
370 (program_id, accounts, instruction_data)
371}
372
373#[cfg(test)]
374mod test {
375 use {super::*, std::alloc::GlobalAlloc};
376
377 #[test]
378 fn test_bump_allocator() {
379 // alloc the entire
380 {
381 let heap = vec![0u8; 128];
382 let allocator = BumpAllocator {
383 start: heap.as_ptr() as *const _ as usize,
384 len: heap.len(),
385 };
386 for i in 0..128 - size_of::<*mut u8>() {
387 let ptr = unsafe {
388 allocator.alloc(Layout::from_size_align(1, size_of::<u8>()).unwrap())
389 };
390 assert_eq!(
391 ptr as *const _ as usize,
392 heap.as_ptr() as *const _ as usize + heap.len() - 1 - i
393 );
394 }
395 assert_eq!(null_mut(), unsafe {
396 allocator.alloc(Layout::from_size_align(1, 1).unwrap())
397 });
398 }
399 // check alignment
400 {
401 let heap = vec![0u8; 128];
402 let allocator = BumpAllocator {
403 start: heap.as_ptr() as *const _ as usize,
404 len: heap.len(),
405 };
406 let ptr =
407 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u8>()).unwrap()) };
408 assert_eq!(0, ptr.align_offset(size_of::<u8>()));
409 let ptr =
410 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u16>()).unwrap()) };
411 assert_eq!(0, ptr.align_offset(size_of::<u16>()));
412 let ptr =
413 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u32>()).unwrap()) };
414 assert_eq!(0, ptr.align_offset(size_of::<u32>()));
415 let ptr =
416 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u64>()).unwrap()) };
417 assert_eq!(0, ptr.align_offset(size_of::<u64>()));
418 let ptr =
419 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u128>()).unwrap()) };
420 assert_eq!(0, ptr.align_offset(size_of::<u128>()));
421 let ptr = unsafe { allocator.alloc(Layout::from_size_align(1, 64).unwrap()) };
422 assert_eq!(0, ptr.align_offset(64));
423 }
424 // alloc entire block (minus the pos ptr)
425 {
426 let heap = vec![0u8; 128];
427 let allocator = BumpAllocator {
428 start: heap.as_ptr() as *const _ as usize,
429 len: heap.len(),
430 };
431 let ptr =
432 unsafe { allocator.alloc(Layout::from_size_align(120, size_of::<u8>()).unwrap()) };
433 assert_ne!(ptr, null_mut());
434 assert_eq!(0, ptr.align_offset(size_of::<u64>()));
435 }
436 }
437}