Skip to main content

rialo_s_program_entrypoint/
lib.rs

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