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