clone_solana_program_entrypoint/lib.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 alloc::vec::Vec,
10 clone_solana_account_info::AccountInfo,
11 clone_solana_pubkey::Pubkey,
12 std::{
13 alloc::Layout,
14 cell::RefCell,
15 mem::{size_of, MaybeUninit},
16 ptr::null_mut,
17 rc::Rc,
18 slice::{from_raw_parts, from_raw_parts_mut},
19 },
20};
21// need to re-export msg for custom_heap_default macro
22pub use {
23 clone_solana_account_info::MAX_PERMITTED_DATA_INCREASE, clone_solana_msg::msg as __msg,
24 clone_solana_program_error::ProgramResult,
25};
26
27/// User implemented function to process an instruction
28///
29/// program_id: Program ID of the currently executing program accounts: Accounts
30/// passed as part of the instruction instruction_data: Instruction data
31pub type ProcessInstruction =
32 fn(program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult;
33
34/// Programs indicate success with a return value of 0
35pub const SUCCESS: u64 = 0;
36
37/// Start address of the memory region used for program heap.
38pub const HEAP_START_ADDRESS: u64 = 0x300000000;
39/// Length of the heap memory region used for program heap.
40pub const HEAP_LENGTH: usize = 32 * 1024;
41
42/// Value used to indicate that a serialized account is not a duplicate
43pub const NON_DUP_MARKER: u8 = u8::MAX;
44
45/// Declare the program entrypoint and set up global handlers.
46///
47/// This macro emits the common boilerplate necessary to begin program
48/// execution, calling a provided function to process the program instruction
49/// supplied by the runtime, and reporting its result to the runtime.
50///
51/// It also sets up a [global allocator] and [panic handler], using the
52/// [`custom_heap_default`] and [`custom_panic_default`] macros.
53///
54/// [`custom_heap_default`]: crate::custom_heap_default
55/// [`custom_panic_default`]: crate::custom_panic_default
56///
57/// [global allocator]: https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html
58/// [panic handler]: https://doc.rust-lang.org/nomicon/panic-handler.html
59///
60/// The argument is the name of a function with this type signature:
61///
62/// ```ignore
63/// fn process_instruction(
64/// program_id: &Pubkey, // Public key of the account the program was loaded into
65/// accounts: &[AccountInfo], // All accounts required to process the instruction
66/// instruction_data: &[u8], // Serialized instruction-specific data
67/// ) -> ProgramResult;
68/// ```
69///
70/// # Cargo features
71///
72/// This macro emits symbols and definitions that may only be defined once
73/// globally. As such, if linked to other Rust crates it will cause compiler
74/// errors. To avoid this, it is common for Solana programs to define an
75/// optional [Cargo feature] called `no-entrypoint`, and use it to conditionally
76/// disable the `entrypoint` macro invocation, as well as the
77/// `process_instruction` function. See a typical pattern for this in the
78/// example below.
79///
80/// [Cargo feature]: https://doc.rust-lang.org/cargo/reference/features.html
81///
82/// The code emitted by this macro can be customized by adding cargo features
83/// _to your own crate_ (the one that calls this macro) and enabling them:
84///
85/// - If the `custom-heap` feature is defined then the macro will not set up the
86/// global allocator, allowing `entrypoint` to be used with your own
87/// allocator. See documentation for the [`custom_heap_default`] macro for
88/// details of customizing the global allocator.
89///
90/// - If the `custom-panic` feature is defined then the macro will not define a
91/// panic handler, allowing `entrypoint` to be used with your own panic
92/// handler. See documentation for the [`custom_panic_default`] macro for
93/// details of customizing the panic handler.
94///
95/// # Examples
96///
97/// Defining an entrypoint and making it conditional on the `no-entrypoint`
98/// feature. Although the `entrypoint` module is written inline in this example,
99/// it is common to put it into its own file.
100///
101/// ```no_run
102/// #[cfg(not(feature = "no-entrypoint"))]
103/// pub mod entrypoint {
104///
105/// use clone_solana_account_info::AccountInfo;
106/// use clone_solana_program_entrypoint::entrypoint;
107/// use clone_solana_program_entrypoint::ProgramResult;
108/// use clone_solana_msg::msg;
109/// use clone_solana_pubkey::Pubkey;
110///
111/// entrypoint!(process_instruction);
112///
113/// pub fn process_instruction(
114/// program_id: &Pubkey,
115/// accounts: &[AccountInfo],
116/// instruction_data: &[u8],
117/// ) -> ProgramResult {
118/// msg!("Hello world");
119///
120/// Ok(())
121/// }
122///
123/// }
124/// ```
125#[macro_export]
126macro_rules! entrypoint {
127 ($process_instruction:ident) => {
128 /// # Safety
129 #[no_mangle]
130 pub unsafe extern "C" fn entrypoint(input: *mut u8) -> u64 {
131 let (program_id, accounts, instruction_data) = unsafe { $crate::deserialize(input) };
132 match $process_instruction(program_id, &accounts, instruction_data) {
133 Ok(()) => $crate::SUCCESS,
134 Err(error) => error.into(),
135 }
136 }
137 $crate::custom_heap_default!();
138 $crate::custom_panic_default!();
139 };
140}
141
142/// Declare the program entrypoint and set up global handlers.
143///
144/// This is similar to the `entrypoint!` macro, except that it does not perform
145/// any dynamic allocations, and instead writes the input accounts into a pre-
146/// allocated array.
147///
148/// This version reduces compute unit usage by 20-30 compute units per unique
149/// account in the instruction. It may become the default option in a future
150/// release.
151///
152/// For more information about how the program entrypoint behaves and what it
153/// does, please see the documentation for [`entrypoint!`].
154///
155/// NOTE: This entrypoint has a hard-coded limit of 64 input accounts.
156#[macro_export]
157macro_rules! entrypoint_no_alloc {
158 ($process_instruction:ident) => {
159 /// # Safety
160 #[no_mangle]
161 pub unsafe extern "C" fn entrypoint(input: *mut u8) -> u64 {
162 use std::mem::MaybeUninit;
163 // Clippy complains about this because a `const` with interior
164 // mutability `RefCell` should use `static` instead to make it
165 // clear that it can change.
166 // In our case, however, we want to create an array of `AccountInfo`s,
167 // and the only way to do it is through a `const` expression, and
168 // we don't expect to mutate the internals of this `const` type.
169 #[allow(clippy::declare_interior_mutable_const)]
170 const UNINIT_ACCOUNT_INFO: MaybeUninit<AccountInfo> =
171 MaybeUninit::<AccountInfo>::uninit();
172 const MAX_ACCOUNT_INFOS: usize = 64;
173 let mut accounts = [UNINIT_ACCOUNT_INFO; MAX_ACCOUNT_INFOS];
174 let (program_id, num_accounts, instruction_data) =
175 unsafe { $crate::deserialize_into(input, &mut accounts) };
176 // Use `slice_assume_init_ref` once it's stabilized
177 let accounts = &*(&accounts[..num_accounts] as *const [MaybeUninit<AccountInfo<'_>>]
178 as *const [AccountInfo<'_>]);
179
180 #[inline(never)]
181 fn call_program(program_id: &Pubkey, accounts: &[AccountInfo], data: &[u8]) -> u64 {
182 match $process_instruction(program_id, accounts, data) {
183 Ok(()) => $crate::SUCCESS,
184 Err(error) => error.into(),
185 }
186 }
187
188 call_program(&program_id, accounts, &instruction_data)
189 }
190 $crate::custom_heap_default!();
191 $crate::custom_panic_default!();
192 };
193}
194
195/// Define the default global allocator.
196///
197/// The default global allocator is enabled only if the calling crate has not
198/// disabled it using [Cargo features] as described below. It is only defined
199/// for [BPF] targets.
200///
201/// [Cargo features]: https://doc.rust-lang.org/cargo/reference/features.html
202/// [BPF]: https://solana.com/docs/programs/faq#berkeley-packet-filter-bpf
203///
204/// # Cargo features
205///
206/// A crate that calls this macro can provide its own custom heap
207/// implementation, or allow others to provide their own custom heap
208/// implementation, by adding a `custom-heap` feature to its `Cargo.toml`. After
209/// enabling the feature, one may define their own [global allocator] in the
210/// standard way.
211///
212/// [global allocator]: https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html
213///
214#[macro_export]
215macro_rules! custom_heap_default {
216 () => {
217 #[cfg(all(not(feature = "custom-heap"), target_os = "solana"))]
218 #[global_allocator]
219 static A: $crate::BumpAllocator = $crate::BumpAllocator {
220 start: $crate::HEAP_START_ADDRESS as usize,
221 len: $crate::HEAP_LENGTH,
222 };
223 };
224}
225
226/// Define the default global panic handler.
227///
228/// This must be used if the [`entrypoint`] macro is not used, and no other
229/// panic handler has been defined; otherwise compilation will fail with a
230/// missing `custom_panic` symbol.
231///
232/// The default global allocator is enabled only if the calling crate has not
233/// disabled it using [Cargo features] as described below. It is only defined
234/// for [BPF] targets.
235///
236/// [Cargo features]: https://doc.rust-lang.org/cargo/reference/features.html
237/// [BPF]: https://solana.com/docs/programs/faq#berkeley-packet-filter-bpf
238///
239/// # Cargo features
240///
241/// A crate that calls this macro can provide its own custom panic handler, or
242/// allow others to provide their own custom panic handler, by adding a
243/// `custom-panic` feature to its `Cargo.toml`. After enabling the feature, one
244/// may define their own panic handler.
245///
246/// A good way to reduce the final size of the program is to provide a
247/// `custom_panic` implementation that does nothing. Doing so will cut ~25kb
248/// from a noop program. That number goes down the more the programs pulls in
249/// Rust's standard library for other purposes.
250///
251/// # Defining a panic handler for Solana
252///
253/// _The mechanism for defining a Solana panic handler is different [from most
254/// Rust programs][rpanic]._
255///
256/// [rpanic]: https://doc.rust-lang.org/nomicon/panic-handler.html
257///
258/// To define a panic handler one must define a `custom_panic` function
259/// with the `#[no_mangle]` attribute, as below:
260///
261/// ```ignore
262/// #[cfg(all(feature = "custom-panic", target_os = "solana"))]
263/// #[no_mangle]
264/// fn custom_panic(info: &core::panic::PanicInfo<'_>) {
265/// $crate::msg!("{}", info);
266/// }
267/// ```
268///
269/// The above is how Solana defines the default panic handler.
270#[macro_export]
271macro_rules! custom_panic_default {
272 () => {
273 #[cfg(all(not(feature = "custom-panic"), target_os = "solana"))]
274 #[no_mangle]
275 fn custom_panic(info: &core::panic::PanicInfo<'_>) {
276 // Full panic reporting
277 $crate::__msg!("{}", info);
278 }
279 };
280}
281
282/// The bump allocator used as the default rust heap when running programs.
283pub struct BumpAllocator {
284 #[deprecated(
285 since = "2.2.2",
286 note = "This field should not be accessed directly. It will become private in future versions"
287 )]
288 pub start: usize,
289 #[deprecated(
290 since = "2.2.2",
291 note = "This field should not be accessed directly. It will become private in future versions"
292 )]
293 pub len: usize,
294}
295
296impl BumpAllocator {
297 /// Creates the allocator tied to a provided slice.
298 /// This will not initialize the provided memory, except for the first
299 /// bytes where the pointer is stored.
300 ///
301 /// # Safety
302 /// As long as BumpAllocator or any of its allocations are alive,
303 /// writing into or deallocating the arena will cause UB.
304 ///
305 /// Integer arithmetic in this global allocator implementation is safe when
306 /// operating on the prescribed `HEAP_START_ADDRESS` and `HEAP_LENGTH`. Any
307 /// other use may overflow and is thus unsupported and at one's own risk.
308 #[inline]
309 #[allow(clippy::arithmetic_side_effects)]
310 pub unsafe fn new(arena: &mut [u8]) -> Self {
311 debug_assert!(
312 arena.len() > size_of::<usize>(),
313 "Arena should be larger than usize"
314 );
315
316 // create a pointer to the start of the arena
317 // that will hold an address of the byte following free space
318 let pos_ptr = arena.as_mut_ptr() as *mut usize;
319 // initialize the data there
320 *pos_ptr = pos_ptr as usize + arena.len();
321
322 #[allow(deprecated)] //we get to use deprecated pub fields
323 Self {
324 start: pos_ptr as usize,
325 len: arena.len(),
326 }
327 }
328}
329
330/// Integer arithmetic in this global allocator implementation is safe when
331/// operating on the prescribed `HEAP_START_ADDRESS` and `HEAP_LENGTH`. Any
332/// other use may overflow and is thus unsupported and at one's own risk.
333#[allow(clippy::arithmetic_side_effects)]
334unsafe impl std::alloc::GlobalAlloc for BumpAllocator {
335 #[inline]
336 #[allow(deprecated)] //we get to use deprecated pub fields
337 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
338 let pos_ptr = self.start as *mut usize;
339 let mut pos = *pos_ptr;
340 if pos == 0 {
341 // First time, set starting position
342 pos = self.start + self.len;
343 }
344 pos = pos.saturating_sub(layout.size());
345 pos &= !(layout.align().wrapping_sub(1));
346 if pos < self.start + size_of::<*mut u8>() {
347 return null_mut();
348 }
349 *pos_ptr = pos;
350 pos as *mut u8
351 }
352 #[inline]
353 unsafe fn dealloc(&self, _: *mut u8, _: Layout) {
354 // I'm a bump allocator, I don't free
355 }
356}
357
358/// `assert_eq(std::mem::align_of::<u128>(), 8)` is true for BPF but not for some host machines
359pub const BPF_ALIGN_OF_U128: usize = 8;
360
361#[allow(clippy::arithmetic_side_effects)]
362#[inline(always)] // this reduces CU usage
363unsafe fn deserialize_instruction_data<'a>(input: *mut u8, mut offset: usize) -> (&'a [u8], usize) {
364 #[allow(clippy::cast_ptr_alignment)]
365 let instruction_data_len = *(input.add(offset) as *const u64) as usize;
366 offset += size_of::<u64>();
367
368 let instruction_data = { from_raw_parts(input.add(offset), instruction_data_len) };
369 offset += instruction_data_len;
370
371 (instruction_data, offset)
372}
373
374#[allow(clippy::arithmetic_side_effects)]
375#[inline(always)] // this reduces CU usage by half!
376unsafe fn deserialize_account_info<'a>(
377 input: *mut u8,
378 mut offset: usize,
379) -> (AccountInfo<'a>, usize) {
380 #[allow(clippy::cast_ptr_alignment)]
381 let is_signer = *(input.add(offset) as *const u8) != 0;
382 offset += size_of::<u8>();
383
384 #[allow(clippy::cast_ptr_alignment)]
385 let is_writable = *(input.add(offset) as *const u8) != 0;
386 offset += size_of::<u8>();
387
388 #[allow(clippy::cast_ptr_alignment)]
389 let executable = *(input.add(offset) as *const u8) != 0;
390 offset += size_of::<u8>();
391
392 // The original data length is stored here because these 4 bytes were
393 // originally only used for padding and served as a good location to
394 // track the original size of the account data in a compatible way.
395 let original_data_len_offset = offset;
396 offset += size_of::<u32>();
397
398 let key: &Pubkey = &*(input.add(offset) as *const Pubkey);
399 offset += size_of::<Pubkey>();
400
401 let owner: &Pubkey = &*(input.add(offset) as *const Pubkey);
402 offset += size_of::<Pubkey>();
403
404 #[allow(clippy::cast_ptr_alignment)]
405 let lamports = Rc::new(RefCell::new(&mut *(input.add(offset) as *mut u64)));
406 offset += size_of::<u64>();
407
408 #[allow(clippy::cast_ptr_alignment)]
409 let data_len = *(input.add(offset) as *const u64) as usize;
410 offset += size_of::<u64>();
411
412 // Store the original data length for detecting invalid reallocations and
413 // requires that MAX_PERMITTED_DATA_LENGTH fits in a u32
414 *(input.add(original_data_len_offset) as *mut u32) = data_len as u32;
415
416 let data = Rc::new(RefCell::new({
417 from_raw_parts_mut(input.add(offset), data_len)
418 }));
419 offset += data_len + MAX_PERMITTED_DATA_INCREASE;
420 offset += (offset as *const u8).align_offset(BPF_ALIGN_OF_U128); // padding
421
422 #[allow(clippy::cast_ptr_alignment)]
423 let rent_epoch = *(input.add(offset) as *const u64);
424 offset += size_of::<u64>();
425
426 (
427 AccountInfo {
428 key,
429 is_signer,
430 is_writable,
431 lamports,
432 data,
433 owner,
434 executable,
435 rent_epoch,
436 },
437 offset,
438 )
439}
440
441/// Deserialize the input arguments
442///
443/// The integer arithmetic in this method is safe when called on a buffer that was
444/// serialized by runtime. Use with buffers serialized otherwise is unsupported and
445/// done at one's own risk.
446///
447/// # Safety
448#[allow(clippy::arithmetic_side_effects)]
449pub unsafe fn deserialize<'a>(input: *mut u8) -> (&'a Pubkey, Vec<AccountInfo<'a>>, &'a [u8]) {
450 let mut offset: usize = 0;
451
452 // Number of accounts present
453
454 #[allow(clippy::cast_ptr_alignment)]
455 let num_accounts = *(input.add(offset) as *const u64) as usize;
456 offset += size_of::<u64>();
457
458 // Account Infos
459
460 let mut accounts = Vec::with_capacity(num_accounts);
461 for _ in 0..num_accounts {
462 let dup_info = *(input.add(offset) as *const u8);
463 offset += size_of::<u8>();
464 if dup_info == NON_DUP_MARKER {
465 let (account_info, new_offset) = deserialize_account_info(input, offset);
466 offset = new_offset;
467 accounts.push(account_info);
468 } else {
469 offset += 7; // padding
470
471 // Duplicate account, clone the original
472 accounts.push(accounts[dup_info as usize].clone());
473 }
474 }
475
476 // Instruction data
477
478 let (instruction_data, new_offset) = deserialize_instruction_data(input, offset);
479 offset = new_offset;
480
481 // Program Id
482
483 let program_id: &Pubkey = &*(input.add(offset) as *const Pubkey);
484
485 (program_id, accounts, instruction_data)
486}
487
488/// Deserialize the input arguments
489///
490/// Differs from `deserialize` by writing the account infos into an uninitialized
491/// slice, which provides better performance, roughly 30 CUs per unique account
492/// provided to the instruction.
493///
494/// Panics if the input slice is not large enough.
495///
496/// The integer arithmetic in this method is safe when called on a buffer that was
497/// serialized by runtime. Use with buffers serialized otherwise is unsupported and
498/// done at one's own risk.
499///
500/// # Safety
501#[allow(clippy::arithmetic_side_effects)]
502pub unsafe fn deserialize_into<'a>(
503 input: *mut u8,
504 accounts: &mut [MaybeUninit<AccountInfo<'a>>],
505) -> (&'a Pubkey, usize, &'a [u8]) {
506 let mut offset: usize = 0;
507
508 // Number of accounts present
509
510 #[allow(clippy::cast_ptr_alignment)]
511 let num_accounts = *(input.add(offset) as *const u64) as usize;
512 offset += size_of::<u64>();
513
514 if num_accounts > accounts.len() {
515 panic!(
516 "{} accounts provided, but only {} are supported",
517 num_accounts,
518 accounts.len()
519 );
520 }
521
522 // Account Infos
523
524 for i in 0..num_accounts {
525 let dup_info = *(input.add(offset) as *const u8);
526 offset += size_of::<u8>();
527 if dup_info == NON_DUP_MARKER {
528 let (account_info, new_offset) = deserialize_account_info(input, offset);
529 offset = new_offset;
530 accounts[i].write(account_info);
531 } else {
532 offset += 7; // padding
533
534 // Duplicate account, clone the original
535 accounts[i].write(accounts[dup_info as usize].assume_init_ref().clone());
536 }
537 }
538
539 // Instruction data
540
541 let (instruction_data, new_offset) = deserialize_instruction_data(input, offset);
542 offset = new_offset;
543
544 // Program Id
545
546 let program_id: &Pubkey = &*(input.add(offset) as *const Pubkey);
547
548 (program_id, num_accounts, instruction_data)
549}
550
551#[cfg(test)]
552mod test {
553 use {super::*, std::alloc::GlobalAlloc};
554
555 #[test]
556 fn test_bump_allocator() {
557 // alloc the entire
558 {
559 let mut heap = [0u8; 128];
560 let allocator = unsafe { BumpAllocator::new(&mut heap) };
561 for i in 0..128 - size_of::<*mut u8>() {
562 let ptr = unsafe {
563 allocator.alloc(Layout::from_size_align(1, size_of::<u8>()).unwrap())
564 };
565 assert_eq!(ptr as usize, heap.as_ptr() as usize + heap.len() - 1 - i);
566 }
567 assert_eq!(null_mut(), unsafe {
568 allocator.alloc(Layout::from_size_align(1, 1).unwrap())
569 });
570 }
571 // check alignment
572 {
573 let mut heap = [0u8; 128];
574 let allocator = unsafe { BumpAllocator::new(&mut heap) };
575 let ptr =
576 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u8>()).unwrap()) };
577 assert_eq!(0, ptr.align_offset(size_of::<u8>()));
578 let ptr =
579 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u16>()).unwrap()) };
580 assert_eq!(0, ptr.align_offset(size_of::<u16>()));
581 let ptr =
582 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u32>()).unwrap()) };
583 assert_eq!(0, ptr.align_offset(size_of::<u32>()));
584 let ptr =
585 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u64>()).unwrap()) };
586 assert_eq!(0, ptr.align_offset(size_of::<u64>()));
587 let ptr =
588 unsafe { allocator.alloc(Layout::from_size_align(1, size_of::<u128>()).unwrap()) };
589 assert_eq!(0, ptr.align_offset(size_of::<u128>()));
590 let ptr = unsafe { allocator.alloc(Layout::from_size_align(1, 64).unwrap()) };
591 assert_eq!(0, ptr.align_offset(64));
592 }
593 // alloc entire block (minus the pos ptr)
594 {
595 let mut heap = [0u8; 128];
596 let allocator = unsafe { BumpAllocator::new(&mut heap) };
597 let ptr = unsafe {
598 allocator.alloc(
599 Layout::from_size_align(heap.len() - size_of::<usize>(), size_of::<u8>())
600 .unwrap(),
601 )
602 };
603 assert_ne!(ptr, null_mut());
604 assert_eq!(0, ptr.align_offset(size_of::<u64>()));
605 }
606 }
607}