Skip to main content

solana_program_runtime/
serialization.rs

1#![allow(clippy::arithmetic_side_effects)]
2
3use {
4    crate::memory_context::SerializedAccountMetadata,
5    solana_instruction_error::InstructionError,
6    solana_program_entrypoint::{BPF_ALIGN_OF_U128, MAX_PERMITTED_DATA_INCREASE, NON_DUP_MARKER},
7    solana_pubkey::Pubkey,
8    solana_sbpf::{
9        aligned_memory::{AlignedMemory, Pod},
10        ebpf::{HOST_ALIGN, MM_INPUT_START},
11        memory_region::MemoryRegion,
12    },
13    solana_sdk_ids::bpf_loader_deprecated,
14    solana_system_interface::MAX_PERMITTED_DATA_LENGTH,
15    solana_transaction_context::{
16        IndexOfAccount, MAX_ACCOUNTS_PER_INSTRUCTION, instruction::InstructionContext,
17        instruction_accounts::BorrowedInstructionAccount,
18    },
19    std::mem::{self, size_of},
20};
21
22/// Modifies the memory mapping in serialization and CPI return for virtual_address_space_adjustments
23pub fn modify_memory_region_of_account(
24    account: &mut BorrowedInstructionAccount<'_, '_>,
25    region: &mut MemoryRegion,
26) {
27    let data_ptr = region.host_buffer().ptr() as *mut u8;
28    let new_buffer = std::ptr::slice_from_raw_parts_mut(data_ptr, account.get_data().len());
29    if account.can_data_be_changed().is_ok() {
30        unsafe {
31            // SAFETY:
32            // Contract from `MemoryRegion::redirect`: The memory pointed to by the MemoryRegions
33            // must point to a valid object live for the duration of this MemoryMapping.
34            //
35            // TODO(nagisa): Local reasoning for this contract is infeasible. In particular for the
36            // `serialization.rs` code it is pretty easy to see that the regions passed in will
37            // always be larger than `account.get_data().len()`. However for `cpi.rs` callsite this
38            // is not as easy to prove and relies on careful coordination between any code that
39            // might increase the account data buffer length.
40            region.redirect(new_buffer);
41        }
42        region.access_violation_handler_payload = Some(account.get_index_in_transaction());
43    } else {
44        unsafe {
45            // SAFETY:
46            //
47            // Contract from `MemoryRegion::redirect`: same as for the call above.
48            // Evidence: same as for the call above.
49            region.redirect(new_buffer.cast_const());
50        }
51        region.access_violation_handler_payload = None;
52    }
53}
54
55/// Creates the memory mapping in serialization and CPI return for account_data_direct_mapping
56pub fn create_memory_region_of_account(
57    account: &mut BorrowedInstructionAccount<'_, '_>,
58    vaddr: u64,
59) -> Result<MemoryRegion, InstructionError> {
60    let can_data_be_changed = account.can_data_be_changed().is_ok();
61    let mut memory_region = if can_data_be_changed && !account.is_shared() {
62        MemoryRegion::new(&raw mut account.get_data_mut()?[..], vaddr)
63    } else {
64        MemoryRegion::new(&raw const account.get_data()[..], vaddr)
65    };
66    if can_data_be_changed {
67        memory_region.access_violation_handler_payload = Some(account.get_index_in_transaction());
68    }
69    Ok(memory_region)
70}
71
72#[expect(dead_code)]
73enum SerializeAccount<'a, 'ix_data> {
74    Account(IndexOfAccount, BorrowedInstructionAccount<'a, 'ix_data>),
75    Duplicate(IndexOfAccount),
76}
77
78struct Serializer {
79    buffer: AlignedMemory<HOST_ALIGN>,
80    regions: Vec<MemoryRegion>,
81    vaddr: u64,
82    region_start: usize,
83    is_loader_v1: bool,
84    virtual_address_space_adjustments: bool,
85    account_data_direct_mapping: bool,
86}
87
88impl Serializer {
89    fn new(
90        size: usize,
91        start_addr: u64,
92        is_loader_v1: bool,
93        virtual_address_space_adjustments: bool,
94        account_data_direct_mapping: bool,
95    ) -> Serializer {
96        Serializer {
97            buffer: AlignedMemory::with_capacity(size),
98            regions: Vec::new(),
99            region_start: 0,
100            vaddr: start_addr,
101            is_loader_v1,
102            virtual_address_space_adjustments,
103            account_data_direct_mapping,
104        }
105    }
106
107    fn fill_write(&mut self, num: usize, value: u8) -> std::io::Result<()> {
108        self.buffer.fill_write(num, value)
109    }
110
111    fn write<T: Pod>(&mut self, value: T) -> u64 {
112        self.debug_assert_alignment::<T>();
113        let vaddr = self
114            .vaddr
115            .saturating_add(self.buffer.len() as u64)
116            .saturating_sub(self.region_start as u64);
117        // Safety:
118        // in serialize_parameters_(aligned|unaligned) first we compute the
119        // required size then we write into the newly allocated buffer. There's
120        // no need to check bounds at every write.
121        //
122        // AlignedMemory::write_unchecked _does_ debug_assert!() that the capacity
123        // is enough, so in the unlikely case we introduce a bug in the size
124        // computation, tests will abort.
125        unsafe {
126            self.buffer.write_unchecked(value);
127        }
128
129        vaddr
130    }
131
132    fn write_all(&mut self, value: &[u8]) -> u64 {
133        let vaddr = self
134            .vaddr
135            .saturating_add(self.buffer.len() as u64)
136            .saturating_sub(self.region_start as u64);
137        // Safety:
138        // see write() - the buffer is guaranteed to be large enough
139        unsafe {
140            self.buffer.write_all_unchecked(value);
141        }
142
143        vaddr
144    }
145
146    fn write_account(
147        &mut self,
148        account: &mut BorrowedInstructionAccount<'_, '_>,
149    ) -> Result<u64, InstructionError> {
150        if !self.virtual_address_space_adjustments {
151            let vm_data_addr = self.vaddr.saturating_add(self.buffer.len() as u64);
152            self.write_all(account.get_data());
153            if !self.is_loader_v1 {
154                let align_offset =
155                    (account.get_data().len() as *const u8).align_offset(BPF_ALIGN_OF_U128);
156                self.fill_write(MAX_PERMITTED_DATA_INCREASE + align_offset, 0)
157                    .map_err(|_| InstructionError::InvalidArgument)?;
158            }
159            Ok(vm_data_addr)
160        } else {
161            self.push_region();
162            let vm_data_addr = self.vaddr;
163            if !self.account_data_direct_mapping {
164                self.write_all(account.get_data());
165                if !self.is_loader_v1 {
166                    self.fill_write(MAX_PERMITTED_DATA_INCREASE, 0)
167                        .map_err(|_| InstructionError::InvalidArgument)?;
168                }
169            }
170            let address_space_reserved_for_account = if !self.is_loader_v1 {
171                account
172                    .get_data()
173                    .len()
174                    .saturating_add(MAX_PERMITTED_DATA_INCREASE)
175            } else {
176                account.get_data().len()
177            };
178            if address_space_reserved_for_account > 0 {
179                if !self.account_data_direct_mapping {
180                    self.push_region();
181                    let region = self.regions.last_mut().unwrap();
182                    modify_memory_region_of_account(account, region);
183                } else {
184                    let new_region = create_memory_region_of_account(account, self.vaddr)?;
185                    self.vaddr += address_space_reserved_for_account as u64;
186                    self.regions.push(new_region);
187                }
188            }
189            if !self.is_loader_v1 {
190                let align_offset =
191                    (account.get_data().len() as *const u8).align_offset(BPF_ALIGN_OF_U128);
192                if !self.account_data_direct_mapping {
193                    self.fill_write(align_offset, 0)
194                        .map_err(|_| InstructionError::InvalidArgument)?;
195                } else {
196                    // The deserialization code is going to align the vm_addr to
197                    // BPF_ALIGN_OF_U128. Always add one BPF_ALIGN_OF_U128 worth of
198                    // padding and shift the start of the next region, so that once
199                    // vm_addr is aligned, the corresponding host_addr is aligned
200                    // too.
201                    self.fill_write(BPF_ALIGN_OF_U128, 0)
202                        .map_err(|_| InstructionError::InvalidArgument)?;
203                    self.region_start += BPF_ALIGN_OF_U128.saturating_sub(align_offset);
204                }
205            }
206            Ok(vm_data_addr)
207        }
208    }
209
210    fn push_region(&mut self) {
211        let range = self.region_start..self.buffer.len();
212        let region_slice = self.buffer.as_slice_mut().get_mut(range.clone()).unwrap();
213        self.regions
214            .push(MemoryRegion::new(&raw mut region_slice[..], self.vaddr));
215        self.region_start = range.end;
216        self.vaddr += range.len() as u64;
217    }
218
219    fn finish(mut self) -> (AlignedMemory<HOST_ALIGN>, Vec<MemoryRegion>) {
220        self.push_region();
221        debug_assert_eq!(self.region_start, self.buffer.len());
222        (self.buffer, self.regions)
223    }
224
225    fn debug_assert_alignment<T>(&self) {
226        debug_assert!(
227            self.is_loader_v1
228                || self
229                    .buffer
230                    .as_slice()
231                    .as_ptr_range()
232                    .end
233                    .align_offset(mem::align_of::<T>())
234                    == 0
235        );
236    }
237}
238
239/// The result of serializing the parameters for a program's execution.
240pub struct SerializationResult {
241    /// The serialized parameters for the program's execution.
242    pub parameter_bytes: AlignedMemory<HOST_ALIGN>,
243
244    /// The memory regions that were serialized into `parameter_bytes`.
245    pub regions: Vec<MemoryRegion>,
246
247    /// Metadata about the accounts that were serialized into `parameter_bytes`.
248    pub accounts_metadata: Vec<SerializedAccountMetadata>,
249
250    /// The VM address of the instruction data in `parameter_bytes`.
251    pub instruction_data_offset: usize,
252
253    /// The VM address of the array of account pointers in `parameter_bytes`,
254    /// if `direct_account_pointers_in_program_input` was enabled during
255    /// serialization.
256    pub account_pointers_offset: Option<usize>,
257}
258
259pub fn serialize_parameters(
260    instruction_context: &InstructionContext,
261    virtual_address_space_adjustments: bool,
262    account_data_direct_mapping: bool,
263    direct_account_pointers_in_program_input: bool,
264) -> Result<SerializationResult, InstructionError> {
265    let num_ix_accounts = instruction_context.get_number_of_instruction_accounts();
266    if num_ix_accounts > MAX_ACCOUNTS_PER_INSTRUCTION as IndexOfAccount {
267        return Err(InstructionError::MaxAccountsExceeded);
268    }
269
270    let program_id = *instruction_context.get_program_key()?;
271    let is_loader_deprecated =
272        instruction_context.get_program_owner()? == bpf_loader_deprecated::id();
273
274    let accounts = (0..instruction_context.get_number_of_instruction_accounts())
275        .map(|instruction_account_index| {
276            if let Some(index) = instruction_context
277                .is_instruction_account_duplicate(instruction_account_index)
278                .unwrap()
279            {
280                SerializeAccount::Duplicate(index)
281            } else {
282                let account = instruction_context
283                    .try_borrow_instruction_account(instruction_account_index)
284                    .unwrap();
285                SerializeAccount::Account(instruction_account_index, account)
286            }
287        })
288        // fun fact: jemalloc is good at caching tiny allocations like this one,
289        // so collecting here is actually faster than passing the iterator
290        // around, since the iterator does the work to produce its items each
291        // time it's iterated on.
292        .collect::<Vec<_>>();
293
294    if is_loader_deprecated {
295        // Used by loader-v1 (bpf_loader_deprecated)
296        let (parameter_bytes, regions, accounts_metadata, instruction_data_offset) =
297            serialize_parameters_for_abiv0(
298                accounts,
299                instruction_context.get_instruction_data(),
300                &program_id,
301                virtual_address_space_adjustments,
302                account_data_direct_mapping,
303            )?;
304        Ok(SerializationResult {
305            parameter_bytes,
306            regions,
307            accounts_metadata,
308            instruction_data_offset,
309            account_pointers_offset: None,
310        })
311    } else {
312        // Used by loader-v2 (bpf_loader) and loader-v3 (bpf_loader_upgradeable)
313        serialize_parameters_for_abiv1(
314            accounts,
315            instruction_context.get_instruction_data(),
316            &program_id,
317            virtual_address_space_adjustments,
318            account_data_direct_mapping,
319            // SIMD-0449: only available on ABIv1
320            direct_account_pointers_in_program_input,
321        )
322    }
323}
324
325pub fn deserialize_parameters(
326    instruction_context: &InstructionContext,
327    virtual_address_space_adjustments: bool,
328    account_data_direct_mapping: bool,
329    buffer: &[u8],
330    accounts_metadata: &[SerializedAccountMetadata],
331) -> Result<(), InstructionError> {
332    let is_loader_deprecated =
333        instruction_context.get_program_owner()? == bpf_loader_deprecated::id();
334    let account_lengths = accounts_metadata.iter().map(|a| a.original_data_len);
335    if is_loader_deprecated {
336        // Used by loader-v1 (bpf_loader_deprecated)
337        deserialize_parameters_for_abiv0(
338            instruction_context,
339            virtual_address_space_adjustments,
340            account_data_direct_mapping,
341            buffer,
342            account_lengths,
343        )
344    } else {
345        // Used by loader-v2 (bpf_loader) and loader-v3 (bpf_loader_upgradeable)
346        deserialize_parameters_for_abiv1(
347            instruction_context,
348            virtual_address_space_adjustments,
349            account_data_direct_mapping,
350            buffer,
351            account_lengths,
352        )
353    }
354}
355
356fn serialize_parameters_for_abiv0(
357    accounts: Vec<SerializeAccount>,
358    instruction_data: &[u8],
359    program_id: &Pubkey,
360    virtual_address_space_adjustments: bool,
361    account_data_direct_mapping: bool,
362) -> Result<
363    (
364        AlignedMemory<HOST_ALIGN>,
365        Vec<MemoryRegion>,
366        Vec<SerializedAccountMetadata>,
367        usize,
368    ),
369    InstructionError,
370> {
371    // Calculate size in order to alloc once
372    let mut size = size_of::<u64>();
373    for account in &accounts {
374        size += 1; // dup
375        match account {
376            SerializeAccount::Duplicate(_) => {}
377            SerializeAccount::Account(_, account) => {
378                size += size_of::<u8>() // is_signer
379                + size_of::<u8>() // is_writable
380                + size_of::<Pubkey>() // key
381                + size_of::<u64>()  // lamports
382                + size_of::<u64>()  // data len
383                + size_of::<Pubkey>() // owner
384                + size_of::<u8>() // executable
385                + size_of::<u64>(); // rent_epoch
386                if !(virtual_address_space_adjustments && account_data_direct_mapping) {
387                    size += account.get_data().len();
388                }
389            }
390        }
391    }
392    size += size_of::<u64>() // instruction data len
393         + instruction_data.len() // instruction data
394         + size_of::<Pubkey>(); // program id
395
396    let mut s = Serializer::new(
397        size,
398        MM_INPUT_START,
399        true,
400        virtual_address_space_adjustments,
401        account_data_direct_mapping,
402    );
403
404    let mut accounts_metadata: Vec<SerializedAccountMetadata> = Vec::with_capacity(accounts.len());
405    s.write::<u64>((accounts.len() as u64).to_le());
406    for account in accounts {
407        match account {
408            SerializeAccount::Duplicate(position) => {
409                accounts_metadata.push(accounts_metadata.get(position as usize).unwrap().clone());
410                s.write(position as u8);
411            }
412            SerializeAccount::Account(_, mut account) => {
413                let vm_addr = s.write::<u8>(NON_DUP_MARKER);
414                s.write::<u8>(account.is_signer() as u8);
415                s.write::<u8>(account.is_writable() as u8);
416                let vm_key_addr = s.write_all(account.get_key().as_ref());
417                let vm_lamports_addr = s.write::<u64>(account.get_lamports().to_le());
418                s.write::<u64>((account.get_data().len() as u64).to_le());
419                let vm_data_addr = s.write_account(&mut account)?;
420                let vm_owner_addr = s.write_all(account.get_owner().as_ref());
421                #[expect(deprecated)]
422                s.write::<u8>(account.is_executable() as u8);
423                let rent_epoch = u64::MAX;
424                s.write::<u64>(rent_epoch.to_le());
425                accounts_metadata.push(SerializedAccountMetadata {
426                    vm_addr,
427                    original_data_len: account.get_data().len(),
428                    vm_key_addr,
429                    vm_lamports_addr,
430                    vm_owner_addr,
431                    vm_data_addr,
432                });
433            }
434        };
435    }
436    s.write::<u64>((instruction_data.len() as u64).to_le());
437    let instruction_data_offset = s.write_all(instruction_data);
438    s.write_all(program_id.as_ref());
439
440    let (mem, regions) = s.finish();
441    Ok((
442        mem,
443        regions,
444        accounts_metadata,
445        instruction_data_offset as usize,
446    ))
447}
448
449fn deserialize_parameters_for_abiv0<I: IntoIterator<Item = usize>>(
450    instruction_context: &InstructionContext,
451    virtual_address_space_adjustments: bool,
452    account_data_direct_mapping: bool,
453    buffer: &[u8],
454    account_lengths: I,
455) -> Result<(), InstructionError> {
456    let mut start = size_of::<u64>(); // number of accounts
457    for (instruction_account_index, pre_len) in
458        (0..instruction_context.get_number_of_instruction_accounts()).zip(account_lengths)
459    {
460        let duplicate =
461            instruction_context.is_instruction_account_duplicate(instruction_account_index)?;
462        start += 1; // is_dup
463        if duplicate.is_none() {
464            let mut borrowed_account =
465                instruction_context.try_borrow_instruction_account(instruction_account_index)?;
466            start += size_of::<u8>(); // is_signer
467            start += size_of::<u8>(); // is_writable
468            start += size_of::<Pubkey>(); // key
469            let lamports = buffer
470                .get(start..start.saturating_add(8))
471                .map(<[u8; 8]>::try_from)
472                .and_then(Result::ok)
473                .map(u64::from_le_bytes)
474                .ok_or(InstructionError::InvalidArgument)?;
475            if borrowed_account.get_lamports() != lamports {
476                borrowed_account.set_lamports(lamports)?;
477            }
478            start += size_of::<u64>() // lamports
479                + size_of::<u64>(); // data length
480            if !virtual_address_space_adjustments {
481                let data = buffer
482                    .get(start..start + pre_len)
483                    .ok_or(InstructionError::InvalidArgument)?;
484                // The redundant check helps to avoid the expensive data comparison if we can
485                match borrowed_account.can_data_be_resized(pre_len) {
486                    Ok(()) => borrowed_account.set_data_from_slice(data)?,
487                    Err(err) if borrowed_account.get_data() != data => return Err(err),
488                    _ => {}
489                }
490            } else if !account_data_direct_mapping && borrowed_account.can_data_be_changed().is_ok()
491            {
492                let data = buffer
493                    .get(start..start + pre_len)
494                    .ok_or(InstructionError::InvalidArgument)?;
495                borrowed_account.set_data_from_slice(data)?;
496            } else if borrowed_account.get_data().len() != pre_len {
497                borrowed_account.set_data_length(pre_len)?;
498            }
499            if !(virtual_address_space_adjustments && account_data_direct_mapping) {
500                start += pre_len; // data
501            }
502            start += size_of::<Pubkey>() // owner
503                + size_of::<u8>() // executable
504                + size_of::<u64>(); // rent_epoch
505        }
506    }
507    Ok(())
508}
509
510fn serialize_parameters_for_abiv1(
511    accounts: Vec<SerializeAccount>,
512    instruction_data: &[u8],
513    program_id: &Pubkey,
514    virtual_address_space_adjustments: bool,
515    account_data_direct_mapping: bool,
516    direct_account_pointers_program_input: bool,
517) -> Result<SerializationResult, InstructionError> {
518    let mut accounts_metadata = Vec::with_capacity(accounts.len());
519    // Calculate size in order to alloc once
520    let mut size = size_of::<u64>();
521    for account in &accounts {
522        size += 1; // dup
523        match account {
524            SerializeAccount::Duplicate(_) => size += 7, // padding to 64-bit aligned
525            SerializeAccount::Account(_, account) => {
526                let data_len = account.get_data().len();
527                size += size_of::<u8>() // is_signer
528                + size_of::<u8>() // is_writable
529                + size_of::<u8>() // executable
530                + size_of::<u32>() // original_data_len
531                + size_of::<Pubkey>()  // key
532                + size_of::<Pubkey>() // owner
533                + size_of::<u64>()  // lamports
534                + size_of::<u64>()  // data len
535                + size_of::<u64>(); // rent epoch
536                if !(virtual_address_space_adjustments && account_data_direct_mapping) {
537                    size += data_len
538                        + MAX_PERMITTED_DATA_INCREASE
539                        + (data_len as *const u8).align_offset(BPF_ALIGN_OF_U128);
540                } else {
541                    size += BPF_ALIGN_OF_U128;
542                }
543            }
544        }
545    }
546    size += size_of::<u64>() // data len
547    + instruction_data.len()
548    + size_of::<Pubkey>(); // program id;
549
550    // reserve space for the array of account pointers if SIMD-0449 is enabled
551    let account_pointers_padding = if direct_account_pointers_program_input {
552        let padding = (size as *const u8).align_offset(BPF_ALIGN_OF_U128);
553        size += padding + accounts.len() * size_of::<u64>();
554        Some(padding)
555    } else {
556        None
557    };
558
559    let mut s = Serializer::new(
560        size,
561        MM_INPUT_START,
562        false,
563        virtual_address_space_adjustments,
564        account_data_direct_mapping,
565    );
566
567    // Serialize into the buffer
568    s.write::<u64>((accounts.len() as u64).to_le());
569    for account in accounts {
570        match account {
571            SerializeAccount::Account(_, mut borrowed_account) => {
572                let vm_addr = s.write::<u8>(NON_DUP_MARKER);
573                s.write::<u8>(borrowed_account.is_signer() as u8);
574                s.write::<u8>(borrowed_account.is_writable() as u8);
575                #[expect(deprecated)]
576                s.write::<u8>(borrowed_account.is_executable() as u8);
577                s.write_all(&[0u8, 0, 0, 0]);
578                let vm_key_addr = s.write_all(borrowed_account.get_key().as_ref());
579                let vm_owner_addr = s.write_all(borrowed_account.get_owner().as_ref());
580                let vm_lamports_addr = s.write::<u64>(borrowed_account.get_lamports().to_le());
581                s.write::<u64>((borrowed_account.get_data().len() as u64).to_le());
582                let vm_data_addr = s.write_account(&mut borrowed_account)?;
583                let rent_epoch = u64::MAX;
584                s.write::<u64>(rent_epoch.to_le());
585                accounts_metadata.push(SerializedAccountMetadata {
586                    vm_addr,
587                    original_data_len: borrowed_account.get_data().len(),
588                    vm_key_addr,
589                    vm_owner_addr,
590                    vm_lamports_addr,
591                    vm_data_addr,
592                });
593            }
594            SerializeAccount::Duplicate(position) => {
595                accounts_metadata.push(accounts_metadata.get(position as usize).unwrap().clone());
596                s.write::<u8>(position as u8);
597                s.write_all(&[0u8, 0, 0, 0, 0, 0, 0]);
598            }
599        };
600    }
601    s.write::<u64>((instruction_data.len() as u64).to_le());
602    let instruction_data_offset = s.write_all(instruction_data);
603    // Determines the address of the array of account pointers, if account
604    // pointers are being passed in the program input (SIMD-0449).
605    let account_pointers_offset = {
606        let vaddr = s.write_all(program_id.as_ref()) as usize;
607
608        if let Some(padding) = account_pointers_padding {
609            // Add padding before the array of account pointers to reach
610            // 8-byte alignment (BPF_ALIGN_OF_U128).
611            s.fill_write(padding, 0)
612                .map_err(|_| InstructionError::InvalidArgument)?;
613            for entry in accounts_metadata.iter() {
614                s.write::<u64>(entry.vm_addr.to_le());
615            }
616            // Compute the address of the array of account pointers.
617            Some(vaddr + size_of::<Pubkey>() + padding)
618        } else {
619            None
620        }
621    };
622
623    let (mem, regions) = s.finish();
624    Ok(SerializationResult {
625        parameter_bytes: mem,
626        regions,
627        accounts_metadata,
628        instruction_data_offset: instruction_data_offset as usize,
629        account_pointers_offset,
630    })
631}
632
633fn deserialize_parameters_for_abiv1<I: IntoIterator<Item = usize>>(
634    instruction_context: &InstructionContext,
635    virtual_address_space_adjustments: bool,
636    account_data_direct_mapping: bool,
637    buffer: &[u8],
638    account_lengths: I,
639) -> Result<(), InstructionError> {
640    let mut start = size_of::<u64>(); // number of accounts
641    for (instruction_account_index, pre_len) in
642        (0..instruction_context.get_number_of_instruction_accounts()).zip(account_lengths)
643    {
644        let duplicate =
645            instruction_context.is_instruction_account_duplicate(instruction_account_index)?;
646        start += size_of::<u8>(); // position
647        if duplicate.is_some() {
648            start += 7; // padding to 64-bit aligned
649        } else {
650            let mut borrowed_account =
651                instruction_context.try_borrow_instruction_account(instruction_account_index)?;
652            start += size_of::<u8>() // is_signer
653                + size_of::<u8>() // is_writable
654                + size_of::<u8>() // executable
655                + size_of::<u32>() // original_data_len
656                + size_of::<Pubkey>(); // key
657            let owner = buffer
658                .get(start..start + size_of::<Pubkey>())
659                .ok_or(InstructionError::InvalidArgument)?;
660            start += size_of::<Pubkey>(); // owner
661            let lamports = buffer
662                .get(start..start.saturating_add(8))
663                .map(<[u8; 8]>::try_from)
664                .and_then(Result::ok)
665                .map(u64::from_le_bytes)
666                .ok_or(InstructionError::InvalidArgument)?;
667            if borrowed_account.get_lamports() != lamports {
668                borrowed_account.set_lamports(lamports)?;
669            }
670            start += size_of::<u64>(); // lamports
671            let post_len = buffer
672                .get(start..start.saturating_add(8))
673                .map(<[u8; 8]>::try_from)
674                .and_then(Result::ok)
675                .map(u64::from_le_bytes)
676                .ok_or(InstructionError::InvalidArgument)? as usize;
677            start += size_of::<u64>(); // data length
678            if post_len.saturating_sub(pre_len) > MAX_PERMITTED_DATA_INCREASE
679                || post_len > MAX_PERMITTED_DATA_LENGTH as usize
680            {
681                return Err(InstructionError::InvalidRealloc);
682            }
683            if !virtual_address_space_adjustments {
684                let data = buffer
685                    .get(start..start + post_len)
686                    .ok_or(InstructionError::InvalidArgument)?;
687                // The redundant check helps to avoid the expensive data comparison if we can
688                match borrowed_account.can_data_be_resized(post_len) {
689                    Ok(()) => borrowed_account.set_data_from_slice(data)?,
690                    Err(err) if borrowed_account.get_data() != data => return Err(err),
691                    _ => {}
692                }
693            } else if !account_data_direct_mapping && borrowed_account.can_data_be_changed().is_ok()
694            {
695                let data = buffer
696                    .get(start..start + post_len)
697                    .ok_or(InstructionError::InvalidArgument)?;
698                borrowed_account.set_data_from_slice(data)?;
699            } else if borrowed_account.get_data().len() != post_len {
700                borrowed_account.set_data_length(post_len)?;
701            }
702            start += if !(virtual_address_space_adjustments && account_data_direct_mapping) {
703                let alignment_offset = (pre_len as *const u8).align_offset(BPF_ALIGN_OF_U128);
704                pre_len // data
705                    .saturating_add(MAX_PERMITTED_DATA_INCREASE) // realloc padding
706                    .saturating_add(alignment_offset)
707            } else {
708                // See Serializer::write_account() as to why we have this
709                BPF_ALIGN_OF_U128
710            };
711            start += size_of::<u64>(); // rent_epoch
712            if borrowed_account.get_owner().to_bytes() != owner {
713                // Change the owner at the end so that we are allowed to change the lamports and data before
714                borrowed_account.set_owner(owner)?;
715            }
716        }
717    }
718    Ok(())
719}
720
721#[cfg(test)]
722#[allow(clippy::indexing_slicing)]
723mod tests {
724    use {
725        super::*,
726        crate::{
727            invoke_context::BpfAllocator, memory_context::MemoryContext, with_mock_invoke_context,
728        },
729        solana_account::{Account, AccountSharedData},
730        solana_account_info::AccountInfo,
731        solana_program_entrypoint::deserialize,
732        solana_sbpf::{
733            memory_region::MemoryMapping,
734            program::{BuiltinProgram, SBPFVersion},
735            vm::{Config, EbpfVm},
736        },
737        solana_sdk_ids::{bpf_loader, bpf_loader_upgradeable},
738        solana_system_interface::MAX_PERMITTED_ACCOUNTS_DATA_ALLOCATIONS_PER_TRANSACTION,
739        solana_transaction_context::{
740            MAX_ACCOUNTS_PER_TRANSACTION, instruction_accounts::InstructionAccount,
741        },
742        std::{
743            borrow::Cow,
744            cell::RefCell,
745            mem::transmute,
746            rc::Rc,
747            slice::{from_raw_parts, from_raw_parts_mut},
748            sync::Arc,
749        },
750        test_case::test_case,
751    };
752
753    fn deduplicated_instruction_accounts(
754        transaction_indexes: &[IndexOfAccount],
755        is_writable: fn(usize) -> bool,
756    ) -> Vec<InstructionAccount> {
757        transaction_indexes
758            .iter()
759            .enumerate()
760            .map(|(index_in_instruction, index_in_transaction)| {
761                InstructionAccount::new(
762                    *index_in_transaction,
763                    false,
764                    is_writable(index_in_instruction),
765                )
766            })
767            .collect()
768    }
769
770    #[test_case(false; "direct_account_pointers_in_program_input disabled")]
771    #[test_case(true; "direct_account_pointers_in_program_input enabled")]
772    fn test_serialize_parameters_with_many_accounts(
773        direct_account_pointers_in_program_input: bool,
774    ) {
775        struct TestCase {
776            num_ix_accounts: usize,
777            append_dup_account: bool,
778            expected_err: Option<InstructionError>,
779            name: &'static str,
780        }
781
782        for virtual_address_space_adjustments in [false, true] {
783            for TestCase {
784                num_ix_accounts,
785                append_dup_account,
786                expected_err,
787                name,
788            } in [
789                TestCase {
790                    name: "serialize max accounts with cap",
791                    num_ix_accounts: MAX_ACCOUNTS_PER_INSTRUCTION,
792                    append_dup_account: false,
793                    expected_err: None,
794                },
795                TestCase {
796                    name: "serialize too many accounts with cap",
797                    num_ix_accounts: MAX_ACCOUNTS_PER_INSTRUCTION + 1,
798                    append_dup_account: false,
799                    expected_err: Some(InstructionError::MaxAccountsExceeded),
800                },
801                TestCase {
802                    name: "serialize too many accounts and append dup with cap",
803                    num_ix_accounts: MAX_ACCOUNTS_PER_INSTRUCTION,
804                    append_dup_account: true,
805                    expected_err: Some(InstructionError::MaxAccountsExceeded),
806                },
807            ] {
808                let program_id = solana_pubkey::new_rand();
809                let mut transaction_accounts = vec![(
810                    program_id,
811                    AccountSharedData::from(Account {
812                        lamports: 0,
813                        data: vec![],
814                        owner: bpf_loader::id(),
815                        executable: true,
816                        rent_epoch: 0,
817                    }),
818                )];
819                for _ in 0..num_ix_accounts {
820                    transaction_accounts.push((
821                        Pubkey::new_unique(),
822                        AccountSharedData::from(Account {
823                            lamports: 0,
824                            data: vec![],
825                            owner: program_id,
826                            executable: false,
827                            rent_epoch: 0,
828                        }),
829                    ));
830                }
831
832                let transaction_accounts_indexes: Vec<IndexOfAccount> =
833                    (0..num_ix_accounts as u16).collect();
834                let mut instruction_accounts =
835                    deduplicated_instruction_accounts(&transaction_accounts_indexes, |_| false);
836                if append_dup_account {
837                    instruction_accounts.push(instruction_accounts.last().cloned().unwrap());
838                }
839                let instruction_data = vec![];
840                let num_transaction_accounts =
841                    transaction_accounts.len().min(MAX_ACCOUNTS_PER_TRANSACTION);
842
843                with_mock_invoke_context!(
844                    invoke_context,
845                    transaction_context,
846                    transaction_accounts
847                );
848                if instruction_accounts.len() > MAX_ACCOUNTS_PER_INSTRUCTION {
849                    // Oversized instructions are rejected before serialization.
850                    let dedup_map = vec![u8::MAX; num_transaction_accounts];
851                    assert_eq!(
852                        invoke_context
853                            .transaction_context
854                            .configure_instruction_at_index(
855                                0,
856                                0,
857                                instruction_accounts,
858                                dedup_map,
859                                Cow::Owned(instruction_data.clone()),
860                                Some(0),
861                            ),
862                        Err(InstructionError::MaxAccountsExceeded),
863                        "{name} test case failed",
864                    );
865                    continue;
866                }
867                invoke_context
868                    .transaction_context
869                    .configure_top_level_instruction_for_tests(
870                        0,
871                        instruction_accounts,
872                        instruction_data.clone(),
873                    )
874                    .unwrap();
875                invoke_context.push().unwrap();
876                let instruction_context = invoke_context
877                    .transaction_context
878                    .get_current_instruction_context()
879                    .unwrap();
880
881                let serialization_result = serialize_parameters(
882                    &instruction_context,
883                    virtual_address_space_adjustments,
884                    false, // account_data_direct_mapping
885                    direct_account_pointers_in_program_input,
886                );
887                assert_eq!(
888                    serialization_result.as_ref().err(),
889                    expected_err.as_ref(),
890                    "{name} test case failed",
891                );
892                if expected_err.is_some() {
893                    continue;
894                }
895
896                let SerializationResult {
897                    parameter_bytes: mut serialized,
898                    regions,
899                    account_pointers_offset,
900                    ..
901                } = serialization_result.unwrap();
902                let mut serialized_regions = unsafe {
903                    // SAFETY: test code, serialize_parameters should be constructing valid regions.
904                    concat_regions(&regions)
905                };
906                let (de_program_id, de_accounts, de_instruction_data) = unsafe {
907                    deserialize(
908                        if !virtual_address_space_adjustments {
909                            serialized.as_slice_mut()
910                        } else {
911                            serialized_regions.as_slice_mut()
912                        }
913                        .first_mut()
914                        .unwrap() as *mut u8,
915                    )
916                };
917                assert_eq!(de_program_id, &program_id);
918                assert_eq!(de_instruction_data, &instruction_data);
919                assert_eq!(
920                    direct_account_pointers_in_program_input,
921                    account_pointers_offset.is_some()
922                );
923                for account_info in de_accounts {
924                    let index_in_transaction = invoke_context
925                        .transaction_context
926                        .find_index_of_account(account_info.key)
927                        .unwrap();
928                    let account = invoke_context
929                        .transaction_context
930                        .accounts()
931                        .try_borrow(index_in_transaction)
932                        .unwrap();
933                    assert_eq!(account.lamports(), account_info.lamports());
934                    assert_eq!(account.data(), &account_info.data.borrow()[..]);
935                    assert_eq!(account.owner(), account_info.owner);
936                    assert_eq!(account.executable(), account_info.executable);
937                    #[allow(deprecated)]
938                    {
939                        // Using the sdk entrypoint, the rent-epoch is skipped
940                        assert_eq!(0, account_info._unused);
941                    }
942                }
943            }
944        }
945    }
946
947    #[test_case(false; "direct_account_pointers_in_program_input disabled")]
948    #[test_case(true; "direct_account_pointers_in_program_input enabled")]
949    fn test_serialize_parameters(direct_account_pointers_in_program_input: bool) {
950        for virtual_address_space_adjustments in [false, true] {
951            let program_id = solana_pubkey::new_rand();
952            let transaction_accounts = vec![
953                (
954                    program_id,
955                    AccountSharedData::from(Account {
956                        lamports: 0,
957                        data: vec![],
958                        owner: bpf_loader::id(),
959                        executable: true,
960                        rent_epoch: 0,
961                    }),
962                ),
963                (
964                    solana_pubkey::new_rand(),
965                    AccountSharedData::from(Account {
966                        lamports: 1,
967                        data: vec![1u8, 2, 3, 4, 5],
968                        owner: bpf_loader::id(),
969                        executable: false,
970                        rent_epoch: 100,
971                    }),
972                ),
973                (
974                    solana_pubkey::new_rand(),
975                    AccountSharedData::from(Account {
976                        lamports: 2,
977                        data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
978                        owner: bpf_loader::id(),
979                        executable: true,
980                        rent_epoch: 200,
981                    }),
982                ),
983                (
984                    solana_pubkey::new_rand(),
985                    AccountSharedData::from(Account {
986                        lamports: 3,
987                        data: vec![],
988                        owner: bpf_loader::id(),
989                        executable: false,
990                        rent_epoch: 3100,
991                    }),
992                ),
993                (
994                    solana_pubkey::new_rand(),
995                    AccountSharedData::from(Account {
996                        lamports: 4,
997                        data: vec![1u8, 2, 3, 4, 5],
998                        owner: bpf_loader::id(),
999                        executable: false,
1000                        rent_epoch: 100,
1001                    }),
1002                ),
1003                (
1004                    solana_pubkey::new_rand(),
1005                    AccountSharedData::from(Account {
1006                        lamports: 5,
1007                        data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
1008                        owner: bpf_loader::id(),
1009                        executable: true,
1010                        rent_epoch: 200,
1011                    }),
1012                ),
1013                (
1014                    solana_pubkey::new_rand(),
1015                    AccountSharedData::from(Account {
1016                        lamports: 6,
1017                        data: vec![],
1018                        owner: bpf_loader::id(),
1019                        executable: false,
1020                        rent_epoch: 3100,
1021                    }),
1022                ),
1023                (
1024                    program_id,
1025                    AccountSharedData::from(Account {
1026                        lamports: 0,
1027                        data: vec![],
1028                        owner: bpf_loader_deprecated::id(),
1029                        executable: true,
1030                        rent_epoch: 0,
1031                    }),
1032                ),
1033            ];
1034            let instruction_accounts =
1035                deduplicated_instruction_accounts(&[1, 1, 2, 3, 4, 4, 5, 6], |index| index >= 4);
1036            let instruction_data = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
1037            let original_accounts = transaction_accounts.clone();
1038            with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1039            invoke_context
1040                .transaction_context
1041                .configure_top_level_instruction_for_tests(
1042                    0,
1043                    instruction_accounts.clone(),
1044                    instruction_data.clone(),
1045                )
1046                .unwrap();
1047            invoke_context.push().unwrap();
1048            let instruction_context = invoke_context
1049                .transaction_context
1050                .get_current_instruction_context()
1051                .unwrap();
1052
1053            // check serialize_parameters_for_abiv1
1054            let SerializationResult {
1055                parameter_bytes: mut serialized,
1056                regions,
1057                accounts_metadata,
1058                account_pointers_offset,
1059                ..
1060            } = serialize_parameters(
1061                &instruction_context,
1062                virtual_address_space_adjustments,
1063                false, // account_data_direct_mapping
1064                direct_account_pointers_in_program_input,
1065            )
1066            .unwrap();
1067
1068            let mut serialized_regions = unsafe {
1069                // SAFETY: test code, serialize_parameters should be constructing valid regions.
1070                concat_regions(&regions)
1071            };
1072            if !virtual_address_space_adjustments {
1073                assert_eq!(serialized.as_slice(), serialized_regions.as_slice());
1074            }
1075            let (de_program_id, de_accounts, de_instruction_data) = unsafe {
1076                deserialize(
1077                    if !virtual_address_space_adjustments {
1078                        serialized.as_slice_mut()
1079                    } else {
1080                        serialized_regions.as_slice_mut()
1081                    }
1082                    .first_mut()
1083                    .unwrap() as *mut u8,
1084                )
1085            };
1086
1087            assert_eq!(&program_id, de_program_id);
1088            assert_eq!(instruction_data, de_instruction_data);
1089            assert_eq!(
1090                (de_instruction_data.first().unwrap() as *const u8).align_offset(BPF_ALIGN_OF_U128),
1091                0
1092            );
1093            assert_eq!(
1094                direct_account_pointers_in_program_input,
1095                account_pointers_offset.is_some()
1096            );
1097            for account_info in de_accounts {
1098                let index_in_transaction = invoke_context
1099                    .transaction_context
1100                    .find_index_of_account(account_info.key)
1101                    .unwrap();
1102                let account = invoke_context
1103                    .transaction_context
1104                    .accounts()
1105                    .try_borrow(index_in_transaction)
1106                    .unwrap();
1107                assert_eq!(account.lamports(), account_info.lamports());
1108                assert_eq!(account.data(), &account_info.data.borrow()[..]);
1109                assert_eq!(account.owner(), account_info.owner);
1110                assert_eq!(account.executable(), account_info.executable);
1111                #[allow(deprecated)]
1112                {
1113                    // Using the sdk entrypoint, the rent-epoch is skipped
1114                    assert_eq!(0, account_info._unused);
1115                }
1116
1117                assert_eq!(
1118                    (*account_info.lamports.borrow() as *const u64).align_offset(BPF_ALIGN_OF_U128),
1119                    0
1120                );
1121                assert_eq!(
1122                    account_info
1123                        .data
1124                        .borrow()
1125                        .as_ptr()
1126                        .align_offset(BPF_ALIGN_OF_U128),
1127                    0
1128                );
1129            }
1130
1131            deserialize_parameters(
1132                &instruction_context,
1133                virtual_address_space_adjustments,
1134                false, // account_data_direct_mapping
1135                serialized.as_slice(),
1136                &accounts_metadata,
1137            )
1138            .unwrap();
1139            for (index_in_transaction, (_key, original_account)) in
1140                original_accounts.iter().enumerate()
1141            {
1142                let account = invoke_context
1143                    .transaction_context
1144                    .accounts()
1145                    .try_borrow(index_in_transaction as IndexOfAccount)
1146                    .unwrap();
1147                assert_eq!(&*account, original_account);
1148            }
1149
1150            invoke_context.pop().unwrap();
1151            // check serialize_parameters_for_abiv0
1152            invoke_context
1153                .transaction_context
1154                .configure_top_level_instruction_for_tests(
1155                    7,
1156                    instruction_accounts,
1157                    instruction_data.clone(),
1158                )
1159                .unwrap();
1160            invoke_context.push().unwrap();
1161            let instruction_context = invoke_context
1162                .transaction_context
1163                .get_current_instruction_context()
1164                .unwrap();
1165
1166            let SerializationResult {
1167                parameter_bytes: mut serialized,
1168                regions,
1169                accounts_metadata: account_lengths,
1170                account_pointers_offset,
1171                ..
1172            } = serialize_parameters(
1173                &instruction_context,
1174                virtual_address_space_adjustments,
1175                false, // account_data_direct_mapping
1176                direct_account_pointers_in_program_input,
1177            )
1178            .unwrap();
1179            let mut serialized_regions = unsafe {
1180                // SAFETY: test code, serialize_parameters should be constructing valid regions.
1181                concat_regions(&regions)
1182            };
1183
1184            let (de_program_id, de_accounts, de_instruction_data) = unsafe {
1185                deserialize_for_abiv0(
1186                    if !virtual_address_space_adjustments {
1187                        serialized.as_slice_mut()
1188                    } else {
1189                        serialized_regions.as_slice_mut()
1190                    }
1191                    .first_mut()
1192                    .unwrap() as *mut u8,
1193                )
1194            };
1195            assert_eq!(&program_id, de_program_id);
1196            assert_eq!(instruction_data, de_instruction_data);
1197            // abiv0 does not support direct account pointers in program input.
1198            assert!(account_pointers_offset.is_none());
1199            for account_info in de_accounts {
1200                let index_in_transaction = invoke_context
1201                    .transaction_context
1202                    .find_index_of_account(account_info.key)
1203                    .unwrap();
1204                let account = invoke_context
1205                    .transaction_context
1206                    .accounts()
1207                    .try_borrow(index_in_transaction)
1208                    .unwrap();
1209                assert_eq!(account.lamports(), account_info.lamports());
1210                assert_eq!(account.data(), &account_info.data.borrow()[..]);
1211                assert_eq!(account.owner(), account_info.owner);
1212                assert_eq!(account.executable(), account_info.executable);
1213                #[allow(deprecated)]
1214                {
1215                    assert_eq!(u64::MAX, account_info._unused);
1216                }
1217            }
1218
1219            deserialize_parameters(
1220                &instruction_context,
1221                virtual_address_space_adjustments,
1222                false, // account_data_direct_mapping
1223                serialized.as_slice(),
1224                &account_lengths,
1225            )
1226            .unwrap();
1227            for (index_in_transaction, (_key, original_account)) in
1228                original_accounts.iter().enumerate()
1229            {
1230                let account = invoke_context
1231                    .transaction_context
1232                    .accounts()
1233                    .try_borrow(index_in_transaction as IndexOfAccount)
1234                    .unwrap();
1235                assert_eq!(&*account, original_account);
1236            }
1237        }
1238    }
1239
1240    #[test_case(false; "direct_account_pointers_in_program_input disabled")]
1241    #[test_case(true; "direct_account_pointers_in_program_input enabled")]
1242    fn test_serialize_parameters_mask_out_rent_epoch_in_vm_serialization(
1243        direct_account_pointers_in_program_input: bool,
1244    ) {
1245        let transaction_accounts = vec![
1246            (
1247                solana_pubkey::new_rand(),
1248                AccountSharedData::from(Account {
1249                    lamports: 0,
1250                    data: vec![],
1251                    owner: bpf_loader::id(),
1252                    executable: true,
1253                    rent_epoch: 0,
1254                }),
1255            ),
1256            (
1257                solana_pubkey::new_rand(),
1258                AccountSharedData::from(Account {
1259                    lamports: 1,
1260                    data: vec![1u8, 2, 3, 4, 5],
1261                    owner: bpf_loader::id(),
1262                    executable: false,
1263                    rent_epoch: 100,
1264                }),
1265            ),
1266            (
1267                solana_pubkey::new_rand(),
1268                AccountSharedData::from(Account {
1269                    lamports: 2,
1270                    data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
1271                    owner: bpf_loader::id(),
1272                    executable: true,
1273                    rent_epoch: 200,
1274                }),
1275            ),
1276            (
1277                solana_pubkey::new_rand(),
1278                AccountSharedData::from(Account {
1279                    lamports: 3,
1280                    data: vec![],
1281                    owner: bpf_loader::id(),
1282                    executable: false,
1283                    rent_epoch: 300,
1284                }),
1285            ),
1286            (
1287                solana_pubkey::new_rand(),
1288                AccountSharedData::from(Account {
1289                    lamports: 4,
1290                    data: vec![1u8, 2, 3, 4, 5],
1291                    owner: bpf_loader::id(),
1292                    executable: false,
1293                    rent_epoch: 100,
1294                }),
1295            ),
1296            (
1297                solana_pubkey::new_rand(),
1298                AccountSharedData::from(Account {
1299                    lamports: 5,
1300                    data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
1301                    owner: bpf_loader::id(),
1302                    executable: true,
1303                    rent_epoch: 200,
1304                }),
1305            ),
1306            (
1307                solana_pubkey::new_rand(),
1308                AccountSharedData::from(Account {
1309                    lamports: 6,
1310                    data: vec![],
1311                    owner: bpf_loader::id(),
1312                    executable: false,
1313                    rent_epoch: 3100,
1314                }),
1315            ),
1316            (
1317                solana_pubkey::new_rand(),
1318                AccountSharedData::from(Account {
1319                    lamports: 0,
1320                    data: vec![],
1321                    owner: bpf_loader_deprecated::id(),
1322                    executable: true,
1323                    rent_epoch: 0,
1324                }),
1325            ),
1326        ];
1327        let instruction_accounts =
1328            deduplicated_instruction_accounts(&[1, 1, 2, 3, 4, 4, 5, 6], |index| index >= 4);
1329        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1330        invoke_context
1331            .transaction_context
1332            .configure_top_level_instruction_for_tests(0, instruction_accounts.clone(), vec![])
1333            .unwrap();
1334        invoke_context.push().unwrap();
1335        let instruction_context = invoke_context
1336            .transaction_context
1337            .get_current_instruction_context()
1338            .unwrap();
1339
1340        // check serialize_parameters_for_abiv1
1341        let SerializationResult {
1342            parameter_bytes: _serialized,
1343            regions,
1344            ..
1345        } = serialize_parameters(
1346            &instruction_context,
1347            true,
1348            false, // account_data_direct_mapping
1349            direct_account_pointers_in_program_input,
1350        )
1351        .unwrap();
1352
1353        let mut serialized_regions = unsafe {
1354            // SAFETY: test code, serialize_parameters should be constructing valid regions.
1355            concat_regions(&regions)
1356        };
1357        let (_de_program_id, de_accounts, _de_instruction_data) = unsafe {
1358            deserialize(serialized_regions.as_slice_mut().first_mut().unwrap() as *mut u8)
1359        };
1360
1361        for account_info in de_accounts {
1362            // Using program-entrypoint, the rent-epoch will always be 0
1363            #[allow(deprecated)]
1364            {
1365                assert_eq!(0, account_info._unused);
1366            }
1367        }
1368
1369        // check serialize_parameters_for_abiv0
1370        invoke_context
1371            .transaction_context
1372            .configure_top_level_instruction_for_tests(7, instruction_accounts, vec![])
1373            .unwrap();
1374        invoke_context.push().unwrap();
1375        let instruction_context = invoke_context
1376            .transaction_context
1377            .get_current_instruction_context()
1378            .unwrap();
1379
1380        let SerializationResult {
1381            parameter_bytes: _serialized,
1382            regions,
1383            ..
1384        } = serialize_parameters(
1385            &instruction_context,
1386            true,
1387            false, // account_data_direct_mapping
1388            direct_account_pointers_in_program_input,
1389        )
1390        .unwrap();
1391        let mut serialized_regions = unsafe {
1392            // SAFETY: test code, serialize_parameters should be constructing valid regions.
1393            concat_regions(&regions)
1394        };
1395
1396        let (_de_program_id, de_accounts, _de_instruction_data) = unsafe {
1397            deserialize_for_abiv0(serialized_regions.as_slice_mut().first_mut().unwrap() as *mut u8)
1398        };
1399        for account_info in de_accounts {
1400            #[allow(deprecated)]
1401            {
1402                assert_eq!(account_info._unused, u64::MAX);
1403            }
1404        }
1405    }
1406
1407    // the old bpf_loader in-program deserializer bpf_loader::id()
1408    #[deny(unsafe_op_in_unsafe_fn)]
1409    unsafe fn deserialize_for_abiv0<'a>(
1410        input: *mut u8,
1411    ) -> (&'a Pubkey, Vec<AccountInfo<'a>>, &'a [u8]) {
1412        // this boring boilerplate struct is needed until inline const...
1413        struct Ptr<T>(std::marker::PhantomData<T>);
1414        impl<T> Ptr<T> {
1415            const COULD_BE_UNALIGNED: bool = std::mem::align_of::<T>() > 1;
1416
1417            #[inline(always)]
1418            fn read_possibly_unaligned(input: *mut u8, offset: usize) -> T {
1419                unsafe {
1420                    let src = input.add(offset) as *const T;
1421                    if Self::COULD_BE_UNALIGNED {
1422                        src.read_unaligned()
1423                    } else {
1424                        src.read()
1425                    }
1426                }
1427            }
1428
1429            // rustc inserts debug_assert! for misaligned pointer dereferences when
1430            // deserializing, starting from [1]. so, use std::mem::transmute as the last resort
1431            // while preventing clippy from complaining to suggest not to use it.
1432            // [1]: https://github.com/rust-lang/rust/commit/22a7a19f9333bc1fcba97ce444a3515cb5fb33e6
1433            // as for the ub nature of the misaligned pointer dereference, this is
1434            // acceptable in this code, given that this is cfg(test) and it's cared only with
1435            // x86-64 and the target only incurs some performance penalty, not like segfaults
1436            // in other targets.
1437            #[inline(always)]
1438            fn ref_possibly_unaligned<'a>(input: *mut u8, offset: usize) -> &'a T {
1439                #[allow(clippy::transmute_ptr_to_ref)]
1440                unsafe {
1441                    transmute(input.add(offset) as *const T)
1442                }
1443            }
1444
1445            // See ref_possibly_unaligned's comment
1446            #[inline(always)]
1447            fn mut_possibly_unaligned<'a>(input: *mut u8, offset: usize) -> &'a mut T {
1448                #[allow(clippy::transmute_ptr_to_ref)]
1449                unsafe {
1450                    transmute(input.add(offset) as *mut T)
1451                }
1452            }
1453        }
1454
1455        let mut offset: usize = 0;
1456
1457        // number of accounts present
1458
1459        let num_accounts = Ptr::<u64>::read_possibly_unaligned(input, offset) as usize;
1460        offset += size_of::<u64>();
1461
1462        // account Infos
1463
1464        let mut accounts = Vec::with_capacity(num_accounts);
1465        for _ in 0..num_accounts {
1466            let dup_info = Ptr::<u8>::read_possibly_unaligned(input, offset);
1467            offset += size_of::<u8>();
1468            if dup_info == NON_DUP_MARKER {
1469                let is_signer = Ptr::<u8>::read_possibly_unaligned(input, offset) != 0;
1470                offset += size_of::<u8>();
1471
1472                let is_writable = Ptr::<u8>::read_possibly_unaligned(input, offset) != 0;
1473                offset += size_of::<u8>();
1474
1475                let key = Ptr::<Pubkey>::ref_possibly_unaligned(input, offset);
1476                offset += size_of::<Pubkey>();
1477
1478                let lamports = Rc::new(RefCell::new(Ptr::mut_possibly_unaligned(input, offset)));
1479                offset += size_of::<u64>();
1480
1481                let data_len = Ptr::<u64>::read_possibly_unaligned(input, offset) as usize;
1482                offset += size_of::<u64>();
1483
1484                let data = Rc::new(RefCell::new(unsafe {
1485                    from_raw_parts_mut(input.add(offset), data_len)
1486                }));
1487                offset += data_len;
1488
1489                let owner: &Pubkey = Ptr::<Pubkey>::ref_possibly_unaligned(input, offset);
1490                offset += size_of::<Pubkey>();
1491
1492                let executable = Ptr::<u8>::read_possibly_unaligned(input, offset) != 0;
1493                offset += size_of::<u8>();
1494
1495                let unused = Ptr::<u64>::read_possibly_unaligned(input, offset);
1496                offset += size_of::<u64>();
1497
1498                #[allow(deprecated)]
1499                accounts.push(AccountInfo {
1500                    key,
1501                    is_signer,
1502                    is_writable,
1503                    lamports,
1504                    data,
1505                    owner,
1506                    executable,
1507                    _unused: unused,
1508                });
1509            } else {
1510                // duplicate account, clone the original
1511                accounts.push(accounts.get(dup_info as usize).unwrap().clone());
1512            }
1513        }
1514
1515        // instruction data
1516
1517        let instruction_data_len = Ptr::<u64>::read_possibly_unaligned(input, offset) as usize;
1518        offset += size_of::<u64>();
1519
1520        let instruction_data = unsafe { from_raw_parts(input.add(offset), instruction_data_len) };
1521        offset += instruction_data_len;
1522
1523        // program Id
1524
1525        let program_id = Ptr::<Pubkey>::ref_possibly_unaligned(input, offset);
1526
1527        (program_id, accounts, instruction_data)
1528    }
1529
1530    /// # Safety
1531    ///
1532    /// All memory regions must be pointing to valid to dereference host buffers.
1533    unsafe fn concat_regions(regions: &[MemoryRegion]) -> AlignedMemory<HOST_ALIGN> {
1534        let last_region = regions.last().unwrap();
1535        let last_region_vm_addr = last_region.vm_addr_range().start;
1536        let mut mem = AlignedMemory::zero_filled(
1537            (last_region_vm_addr - MM_INPUT_START + last_region.len() as u64) as usize,
1538        );
1539        for region in regions {
1540            let vm_start = region.vm_addr_range().start;
1541            let buffer = region.host_buffer().ptr();
1542            mem.as_slice_mut()[(vm_start - MM_INPUT_START) as usize..][..buffer.len()]
1543                .copy_from_slice(unsafe {
1544                    // SAFETY:
1545                    // Contract from `<*const [u8]>::as_ref_unchecked`: ensure that the pointer is
1546                    // convertible to reference.
1547                    // Evidence: The contract delegated to the callers.
1548                    buffer.as_ref_unchecked()
1549                })
1550        }
1551        mem
1552    }
1553
1554    #[test]
1555    fn test_access_violation_handler() {
1556        let program_id = Pubkey::new_unique();
1557        let shared_account = AccountSharedData::new_with_data(0, vec![0; 4], &program_id);
1558        let account_start_offsets = [
1559            MM_INPUT_START,
1560            MM_INPUT_START + 4 + MAX_PERMITTED_DATA_INCREASE as u64,
1561            MM_INPUT_START + (4 + MAX_PERMITTED_DATA_INCREASE as u64) * 2,
1562            MM_INPUT_START + (4 + MAX_PERMITTED_DATA_INCREASE as u64) * 3,
1563        ];
1564        let transaction_accounts = vec![
1565            (
1566                Pubkey::new_unique(),
1567                AccountSharedData::new_with_data(0, vec![0; 4], &program_id),
1568            ), // readonly
1569            (Pubkey::new_unique(), shared_account.clone()), // writable shared
1570            (
1571                Pubkey::new_unique(),
1572                AccountSharedData::new(0, 0, &program_id),
1573            ), // another writable account
1574            (
1575                Pubkey::new_unique(),
1576                AccountSharedData::new_with_data(
1577                    0,
1578                    vec![0; MAX_PERMITTED_DATA_LENGTH as usize - 0x100],
1579                    &program_id,
1580                ),
1581            ), // almost max sized writable account
1582            (
1583                Pubkey::new_unique(),
1584                AccountSharedData::new(0, 0, &program_id),
1585            ), // writable dummy to burn accounts_resize_delta
1586            (
1587                Pubkey::new_unique(),
1588                AccountSharedData::new_with_data(0, vec![0; 0x3000], &program_id),
1589            ), // writable dummy to burn accounts_resize_delta
1590            (program_id, AccountSharedData::default()),     // program
1591        ];
1592        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1593        let transaction_accounts_indexes = [0, 1, 2, 3, 4, 5];
1594        let instruction_accounts =
1595            deduplicated_instruction_accounts(&transaction_accounts_indexes, |index| index > 0);
1596        invoke_context
1597            .transaction_context
1598            .configure_top_level_instruction_for_tests(6, instruction_accounts, vec![])
1599            .unwrap();
1600        invoke_context.push().unwrap();
1601
1602        let config = Config {
1603            aligned_memory_mapping: false,
1604            enabled_sbpf_versions: SBPFVersion::V0..=SBPFVersion::V3,
1605            ..Config::default()
1606        };
1607        let memory_mapping = {
1608            let transaction_context = &mut invoke_context.transaction_context;
1609            let instruction_context = transaction_context
1610                .get_current_instruction_context()
1611                .unwrap();
1612            let regions = account_start_offsets
1613                .iter()
1614                .enumerate()
1615                .map(|(index_in_instruction, account_start_offset)| {
1616                    create_memory_region_of_account(
1617                        &mut instruction_context
1618                            .try_borrow_instruction_account(index_in_instruction as IndexOfAccount)
1619                            .unwrap(),
1620                        *account_start_offset,
1621                    )
1622                    .unwrap()
1623                })
1624                .collect::<Vec<_>>();
1625            unsafe {
1626                MemoryMapping::new_with_access_violation_handler(
1627                    regions,
1628                    &config,
1629                    *config.enabled_sbpf_versions.end(),
1630                    transaction_context.access_violation_handler(true, true),
1631                )
1632                .unwrap()
1633            }
1634        };
1635        invoke_context
1636            .memory_contexts
1637            .set_memory_context_abi_v1(MemoryContext::new(
1638                BpfAllocator::new(0),
1639                Vec::new(),
1640                memory_mapping,
1641            ))
1642            .unwrap();
1643        let mut vm = EbpfVm::new(
1644            Arc::new(BuiltinProgram::new_loader(config.clone())),
1645            *config.enabled_sbpf_versions.end(),
1646            &mut invoke_context,
1647            0,
1648        );
1649        let memory_mapping = vm.context().memory_contexts.memory_mapping_mut().unwrap();
1650
1651        // Reading readonly account is allowed
1652        memory_mapping
1653            .load_first_attempt::<u32>(account_start_offsets[0])
1654            .unwrap();
1655
1656        // Reading writable account is allowed
1657        memory_mapping
1658            .load_first_attempt::<u32>(account_start_offsets[1])
1659            .unwrap();
1660
1661        // Reading beyond readonly accounts current size is denied
1662        memory_mapping
1663            .load_first_attempt::<u32>(account_start_offsets[0] + 4)
1664            .unwrap_err();
1665
1666        // Writing to readonly account is denied
1667        memory_mapping
1668            .store_first_attempt::<u32>(0, account_start_offsets[0])
1669            .unwrap_err();
1670
1671        // Writing to shared writable account makes it unique (CoW logic.)
1672        // It has been previously been made non-unique at the beginning of
1673        // the test through a clone.
1674        let _shared_account_ref = shared_account;
1675        let accounts = vm.context().transaction_context.accounts();
1676        assert!(accounts.try_borrow_mut(1).unwrap().is_shared());
1677        let encrypted_vm = vm.encrypted_host_address();
1678        let memory_mapping = vm.context().memory_contexts.memory_mapping_mut().unwrap();
1679        memory_mapping.store_second_attempt::<u32, _>(0, account_start_offsets[1], encrypted_vm);
1680        assert!(vm.program_result.is_ok());
1681        let accounts = vm.context().transaction_context.accounts();
1682        assert!(!accounts.try_borrow_mut(1).unwrap().is_shared());
1683        assert_eq!(accounts.try_borrow(1).unwrap().data().len(), 4);
1684
1685        // Reading beyond writable accounts current size grows is denied
1686        let encrypted_vm = vm.encrypted_host_address();
1687        let memory_mapping = vm.context().memory_contexts.memory_mapping_mut().unwrap();
1688        memory_mapping
1689            .load_first_attempt::<u32>(account_start_offsets[1] + 4)
1690            .unwrap_err();
1691
1692        // Writing beyond writable accounts current size grows it
1693        // to original length plus MAX_PERMITTED_DATA_INCREASE
1694        memory_mapping.store_second_attempt::<u32, _>(
1695            0,
1696            account_start_offsets[1] + 4,
1697            encrypted_vm,
1698        );
1699        assert!(vm.program_result.is_ok());
1700        let accounts = vm.context().transaction_context.accounts();
1701        assert_eq!(
1702            accounts.try_borrow(1).unwrap().data().len(),
1703            4 + MAX_PERMITTED_DATA_INCREASE,
1704        );
1705        assert!(accounts.try_borrow(1).unwrap().data().len() < 0x3000);
1706
1707        // Writing beyond almost max sized writable accounts current size only grows it
1708        // to MAX_PERMITTED_DATA_LENGTH
1709        let encrypted_vm = vm.encrypted_host_address();
1710        let memory_mapping = vm.context().memory_contexts.memory_mapping_mut().unwrap();
1711        memory_mapping.store_second_attempt::<u32, _>(
1712            0,
1713            account_start_offsets[3] + MAX_PERMITTED_DATA_LENGTH - 4,
1714            encrypted_vm,
1715        );
1716        assert!(vm.program_result.is_ok());
1717        let accounts = vm.context().transaction_context.accounts();
1718        assert_eq!(
1719            accounts.try_borrow(3).unwrap().data().len(),
1720            MAX_PERMITTED_DATA_LENGTH as usize,
1721        );
1722
1723        // Accessing the rest of the address space reserved for
1724        // the almost max sized writable account is denied
1725        let encrypted_vm = vm.encrypted_host_address();
1726        let memory_mapping = vm.context().memory_contexts.memory_mapping_mut().unwrap();
1727        memory_mapping
1728            .load_first_attempt::<u32>(account_start_offsets[3] + MAX_PERMITTED_DATA_LENGTH)
1729            .unwrap_err();
1730        memory_mapping.store_second_attempt::<u32, _>(
1731            0,
1732            account_start_offsets[3] + MAX_PERMITTED_DATA_LENGTH,
1733            encrypted_vm,
1734        );
1735        assert!(vm.program_result.is_err());
1736
1737        // Burn through most of the accounts_resize_delta budget
1738        let transaction_context = &mut vm.context().transaction_context;
1739        let instruction_context = transaction_context
1740            .get_current_instruction_context()
1741            .unwrap();
1742        let remaining_allowed_growth: usize = 0x700;
1743        for index_in_instruction in 4..6 {
1744            let mut borrowed_account = instruction_context
1745                .try_borrow_instruction_account(index_in_instruction)
1746                .unwrap();
1747            borrowed_account
1748                .set_data_from_slice(&vec![0u8; MAX_PERMITTED_DATA_LENGTH as usize])
1749                .unwrap();
1750        }
1751        let accounts = vm.context().transaction_context.accounts();
1752        assert_eq!(
1753            accounts.resize_delta(),
1754            MAX_PERMITTED_ACCOUNTS_DATA_ALLOCATIONS_PER_TRANSACTION
1755                - remaining_allowed_growth as i64,
1756        );
1757
1758        // Writing beyond empty writable accounts current size
1759        // only grows it to fill up MAX_PERMITTED_ACCOUNTS_DATA_ALLOCATIONS_PER_TRANSACTION
1760        let encrypted_vm = vm.encrypted_host_address();
1761        let memory_mapping = vm.context().memory_contexts.memory_mapping_mut().unwrap();
1762        memory_mapping.store_second_attempt::<u32, _>(
1763            0,
1764            account_start_offsets[2] + 0x500,
1765            encrypted_vm,
1766        );
1767        assert!(vm.program_result.is_ok());
1768        let accounts = vm.context().transaction_context.accounts();
1769        assert_eq!(
1770            accounts.try_borrow(2).unwrap().data().len(),
1771            remaining_allowed_growth,
1772        );
1773    }
1774
1775    #[test]
1776    fn test_regression_initial_serialized_account_region_does_not_include_resize_affordance() {
1777        let program_id = Pubkey::new_unique();
1778        let transaction_accounts = vec![
1779            (
1780                Pubkey::new_unique(),
1781                AccountSharedData::new_with_data(0, vec![0; 4], &program_id),
1782            ),
1783            (
1784                solana_pubkey::new_rand(),
1785                AccountSharedData::from(Account {
1786                    lamports: 0,
1787                    data: b"agave".into(),
1788                    owner: bpf_loader_upgradeable::id(),
1789                    executable: false,
1790                    rent_epoch: 0,
1791                }),
1792            ),
1793        ];
1794        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1795        invoke_context
1796            .transaction_context
1797            .configure_top_level_instruction_for_tests(
1798                0,
1799                vec![InstructionAccount::new(1, false, true)],
1800                vec![],
1801            )
1802            .unwrap();
1803        invoke_context.push().unwrap();
1804        let instruction_context = invoke_context
1805            .transaction_context
1806            .get_current_instruction_context()
1807            .unwrap();
1808        let SerializationResult {
1809            regions,
1810            accounts_metadata,
1811            ..
1812        } = crate::serialization::serialize_parameters(
1813            &instruction_context,
1814            true,  // virtual_address_space_adjustments
1815            false, // account_data_direct_mapping
1816            false, // direct_account_pointers_in_program_input
1817        )
1818        .unwrap();
1819        let config = Config {
1820            aligned_memory_mapping: false,
1821            ..Config::default()
1822        };
1823        let memory_mapping =
1824            unsafe { MemoryMapping::new(regions, &config, SBPFVersion::V3).unwrap() };
1825        let account_metadata = &accounts_metadata[0];
1826        let vm_data_addr = account_metadata.vm_data_addr;
1827        let (_region_index, region) = memory_mapping.find_region(vm_data_addr).unwrap();
1828        assert_eq!(region.len(), 5);
1829    }
1830}