Skip to main content

solana_program_runtime/
serialization.rs

1#![allow(clippy::arithmetic_side_effects)]
2
3use {
4    crate::{abi::ABI, memory_context::SerializedAccountMetadata},
5    solana_instruction_error::InstructionError,
6    solana_program_entrypoint::{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_system_interface::MAX_PERMITTED_DATA_LENGTH,
14    solana_transaction_context::{
15        IndexOfAccount, MAX_ACCOUNTS_PER_INSTRUCTION, instruction::InstructionContext,
16        instruction_accounts::BorrowedInstructionAccount,
17    },
18    std::mem::{self, size_of},
19};
20
21/// Modifies the memory mapping in serialization and CPI return for virtual_address_space_adjustments
22pub fn modify_memory_region_of_account(
23    account: &mut BorrowedInstructionAccount<'_, '_>,
24    region: &mut MemoryRegion,
25) {
26    let data_ptr = region.host_buffer().ptr() as *mut u8;
27    let new_buffer = std::ptr::slice_from_raw_parts_mut(data_ptr, account.get_data().len());
28    if account.can_data_be_changed().is_ok() {
29        unsafe {
30            // SAFETY:
31            // Contract from `MemoryRegion::redirect`: The memory pointed to by the MemoryRegions
32            // must point to a valid object live for the duration of this MemoryMapping.
33            //
34            // TODO(nagisa): Local reasoning for this contract is infeasible. In particular for the
35            // `serialization.rs` code it is pretty easy to see that the regions passed in will
36            // always be larger than `account.get_data().len()`. However for `cpi.rs` callsite this
37            // is not as easy to prove and relies on careful coordination between any code that
38            // might increase the account data buffer length.
39            region.redirect(new_buffer);
40        }
41        region.access_violation_handler_payload = Some(account.get_index_in_transaction());
42    } else {
43        unsafe {
44            // SAFETY:
45            //
46            // Contract from `MemoryRegion::redirect`: same as for the call above.
47            // Evidence: same as for the call above.
48            region.redirect(new_buffer.cast_const());
49        }
50        region.access_violation_handler_payload = None;
51    }
52}
53
54/// Creates the memory mapping in serialization and CPI return for account_data_direct_mapping
55pub fn create_memory_region_of_account(
56    account: &mut BorrowedInstructionAccount<'_, '_>,
57    vaddr: u64,
58) -> Result<MemoryRegion, InstructionError> {
59    let can_data_be_changed = account.can_data_be_changed().is_ok();
60    let mut memory_region = if can_data_be_changed && !account.is_shared() {
61        MemoryRegion::new(&raw mut account.get_data_mut()?[..], vaddr)
62    } else {
63        MemoryRegion::new(&raw const account.get_data()[..], vaddr)
64    };
65    if can_data_be_changed {
66        memory_region.access_violation_handler_payload = Some(account.get_index_in_transaction());
67    }
68    Ok(memory_region)
69}
70
71#[expect(dead_code)]
72enum SerializeAccount<'a, 'ix_data> {
73    Account(IndexOfAccount, BorrowedInstructionAccount<'a, 'ix_data>),
74    Duplicate(IndexOfAccount),
75}
76
77struct Serializer {
78    buffer: AlignedMemory<HOST_ALIGN>,
79    regions: Vec<MemoryRegion>,
80    vaddr: u64,
81    region_start: usize,
82    abi: ABI,
83    virtual_address_space_adjustments: bool,
84    account_data_direct_mapping: bool,
85}
86
87impl Serializer {
88    fn new(
89        size: usize,
90        start_addr: u64,
91        abi: ABI,
92        virtual_address_space_adjustments: bool,
93        account_data_direct_mapping: bool,
94    ) -> Serializer {
95        Serializer {
96            buffer: AlignedMemory::with_capacity(size),
97            regions: Vec::new(),
98            region_start: 0,
99            vaddr: start_addr,
100            abi,
101            virtual_address_space_adjustments,
102            account_data_direct_mapping,
103        }
104    }
105
106    fn fill_write(&mut self, num: usize, value: u8) -> std::io::Result<()> {
107        self.buffer.fill_write(num, value)
108    }
109
110    fn write<T: Pod>(&mut self, value: T) -> u64 {
111        self.debug_assert_alignment::<T>();
112        let vaddr = self
113            .vaddr
114            .saturating_add(self.buffer.len() as u64)
115            .saturating_sub(self.region_start as u64);
116        // Safety:
117        // in serialize_parameters_(aligned|unaligned) first we compute the
118        // required size then we write into the newly allocated buffer. There's
119        // no need to check bounds at every write.
120        //
121        // AlignedMemory::write_unchecked _does_ debug_assert!() that the capacity
122        // is enough, so in the unlikely case we introduce a bug in the size
123        // computation, tests will abort.
124        unsafe {
125            self.buffer.write_unchecked(value);
126        }
127
128        vaddr
129    }
130
131    fn write_all(&mut self, value: &[u8]) -> u64 {
132        let vaddr = self
133            .vaddr
134            .saturating_add(self.buffer.len() as u64)
135            .saturating_sub(self.region_start as u64);
136        // Safety:
137        // see write() - the buffer is guaranteed to be large enough
138        unsafe {
139            self.buffer.write_all_unchecked(value);
140        }
141
142        vaddr
143    }
144
145    fn write_account(
146        &mut self,
147        account: &mut BorrowedInstructionAccount<'_, '_>,
148    ) -> Result<u64, InstructionError> {
149        if !self.virtual_address_space_adjustments {
150            let vm_data_addr = self.vaddr.saturating_add(self.buffer.len() as u64);
151            self.write_all(account.get_data());
152            if self.abi == ABI::V1 {
153                let align_offset =
154                    (account.get_data().len() as *const u8).align_offset(self.abi.alignment());
155                self.fill_write(self.abi.account_realloc_padding() + align_offset, 0)
156                    .map_err(|_| InstructionError::InvalidArgument)?;
157            }
158            Ok(vm_data_addr)
159        } else {
160            self.push_region();
161            let vm_data_addr = self.vaddr;
162            if !self.account_data_direct_mapping {
163                self.write_all(account.get_data());
164                self.fill_write(self.abi.account_realloc_padding(), 0)
165                    .map_err(|_| InstructionError::InvalidArgument)?;
166            }
167            let address_space_reserved_for_account = account
168                .get_data()
169                .len()
170                .saturating_add(self.abi.account_realloc_padding());
171            if address_space_reserved_for_account > 0 {
172                if !self.account_data_direct_mapping {
173                    self.push_region();
174                    let region = self.regions.last_mut().unwrap();
175                    modify_memory_region_of_account(account, region);
176                } else {
177                    let new_region = create_memory_region_of_account(account, self.vaddr)?;
178                    self.vaddr += address_space_reserved_for_account as u64;
179                    self.regions.push(new_region);
180                }
181            }
182            if self.abi == ABI::V1 {
183                let align_offset =
184                    (account.get_data().len() as *const u8).align_offset(self.abi.alignment());
185                if !self.account_data_direct_mapping {
186                    self.fill_write(align_offset, 0)
187                        .map_err(|_| InstructionError::InvalidArgument)?;
188                } else {
189                    // The deserialization code is going to align the vm_addr to
190                    // the ABI's alignment. Always add one alignment worth of
191                    // padding and shift the start of the next region, so that once
192                    // vm_addr is aligned, the corresponding host_addr is aligned
193                    // too.
194                    self.fill_write(self.abi.alignment(), 0)
195                        .map_err(|_| InstructionError::InvalidArgument)?;
196                    self.region_start += self.abi.alignment().saturating_sub(align_offset);
197                }
198            }
199            Ok(vm_data_addr)
200        }
201    }
202
203    fn push_region(&mut self) {
204        let range = self.region_start..self.buffer.len();
205        let region_slice = self.buffer.as_slice_mut().get_mut(range.clone()).unwrap();
206        self.regions
207            .push(MemoryRegion::new(&raw mut region_slice[..], self.vaddr));
208        self.region_start = range.end;
209        self.vaddr += range.len() as u64;
210    }
211
212    fn finish(mut self) -> (AlignedMemory<HOST_ALIGN>, Vec<MemoryRegion>) {
213        self.push_region();
214        debug_assert_eq!(self.region_start, self.buffer.len());
215        (self.buffer, self.regions)
216    }
217
218    fn debug_assert_alignment<T>(&self) {
219        debug_assert!(
220            self.abi == ABI::V0
221                || self
222                    .buffer
223                    .as_slice()
224                    .as_ptr_range()
225                    .end
226                    .align_offset(mem::align_of::<T>())
227                    == 0
228        );
229    }
230}
231
232/// The result of serializing the parameters for a program's execution.
233pub struct SerializationResult {
234    /// The serialized parameters for the program's execution.
235    pub parameter_bytes: AlignedMemory<HOST_ALIGN>,
236
237    /// The memory regions that were serialized into `parameter_bytes`.
238    pub regions: Vec<MemoryRegion>,
239
240    /// Metadata about the accounts that were serialized into `parameter_bytes`.
241    pub accounts_metadata: Vec<SerializedAccountMetadata>,
242
243    /// The VM address of the instruction data in `parameter_bytes`.
244    pub instruction_data_offset: usize,
245
246    /// The VM address of the array of account pointers in `parameter_bytes`,
247    /// if `direct_account_pointers_in_program_input` was enabled during
248    /// serialization.
249    pub account_pointers_offset: Option<usize>,
250}
251
252pub fn serialize_parameters(
253    instruction_context: &InstructionContext,
254    abi: ABI,
255    virtual_address_space_adjustments: bool,
256    account_data_direct_mapping: bool,
257    direct_account_pointers_in_program_input: bool,
258) -> Result<SerializationResult, InstructionError> {
259    let num_ix_accounts = instruction_context.get_number_of_instruction_accounts();
260    if num_ix_accounts > MAX_ACCOUNTS_PER_INSTRUCTION as IndexOfAccount {
261        return Err(InstructionError::MaxAccountsExceeded);
262    }
263
264    let program_id = *instruction_context.get_program_key()?;
265
266    let accounts = (0..instruction_context.get_number_of_instruction_accounts())
267        .map(|instruction_account_index| {
268            if let Some(index) = instruction_context
269                .is_instruction_account_duplicate(instruction_account_index)
270                .unwrap()
271            {
272                SerializeAccount::Duplicate(index)
273            } else {
274                let account = instruction_context
275                    .try_borrow_instruction_account(instruction_account_index)
276                    .unwrap();
277                SerializeAccount::Account(instruction_account_index, account)
278            }
279        })
280        // fun fact: jemalloc is good at caching tiny allocations like this one,
281        // so collecting here is actually faster than passing the iterator
282        // around, since the iterator does the work to produce its items each
283        // time it's iterated on.
284        .collect::<Vec<_>>();
285
286    match abi {
287        ABI::V0 => {
288            let (parameter_bytes, regions, accounts_metadata, instruction_data_offset) =
289                serialize_parameters_for_abiv0(
290                    accounts,
291                    instruction_context.get_instruction_data(),
292                    &program_id,
293                    virtual_address_space_adjustments,
294                    account_data_direct_mapping,
295                )?;
296            Ok(SerializationResult {
297                parameter_bytes,
298                regions,
299                accounts_metadata,
300                instruction_data_offset,
301                account_pointers_offset: None,
302            })
303        }
304        ABI::V1 => serialize_parameters_for_abiv1(
305            accounts,
306            instruction_context.get_instruction_data(),
307            &program_id,
308            virtual_address_space_adjustments,
309            account_data_direct_mapping,
310            // SIMD-0449: only available on ABIv1
311            direct_account_pointers_in_program_input,
312        ),
313    }
314}
315
316pub fn deserialize_parameters(
317    instruction_context: &InstructionContext,
318    abi: ABI,
319    virtual_address_space_adjustments: bool,
320    account_data_direct_mapping: bool,
321    buffer: &[u8],
322    accounts_metadata: &[SerializedAccountMetadata],
323) -> Result<(), InstructionError> {
324    let account_lengths = accounts_metadata.iter().map(|a| a.original_data_len);
325    match abi {
326        ABI::V0 => deserialize_parameters_for_abiv0(
327            instruction_context,
328            virtual_address_space_adjustments,
329            account_data_direct_mapping,
330            buffer,
331            account_lengths,
332        ),
333        ABI::V1 => deserialize_parameters_for_abiv1(
334            instruction_context,
335            virtual_address_space_adjustments,
336            account_data_direct_mapping,
337            buffer,
338            account_lengths,
339        ),
340    }
341}
342
343fn serialize_parameters_for_abiv0(
344    accounts: Vec<SerializeAccount>,
345    instruction_data: &[u8],
346    program_id: &Pubkey,
347    virtual_address_space_adjustments: bool,
348    account_data_direct_mapping: bool,
349) -> Result<
350    (
351        AlignedMemory<HOST_ALIGN>,
352        Vec<MemoryRegion>,
353        Vec<SerializedAccountMetadata>,
354        usize,
355    ),
356    InstructionError,
357> {
358    const ABI_VERSION: ABI = ABI::V0;
359
360    // Calculate size in order to alloc once
361    let mut size = size_of::<u64>();
362    for account in &accounts {
363        size += 1; // dup
364        match account {
365            SerializeAccount::Duplicate(_) => {}
366            SerializeAccount::Account(_, account) => {
367                size += size_of::<u8>() // is_signer
368                + size_of::<u8>() // is_writable
369                + size_of::<Pubkey>() // key
370                + size_of::<u64>()  // lamports
371                + size_of::<u64>()  // data len
372                + size_of::<Pubkey>() // owner
373                + size_of::<u8>() // executable
374                + size_of::<u64>(); // rent_epoch
375                if !(virtual_address_space_adjustments && account_data_direct_mapping) {
376                    size += account.get_data().len();
377                }
378            }
379        }
380    }
381    size += size_of::<u64>() // instruction data len
382         + instruction_data.len() // instruction data
383         + size_of::<Pubkey>(); // program id
384
385    let mut s = Serializer::new(
386        size,
387        MM_INPUT_START,
388        ABI_VERSION,
389        virtual_address_space_adjustments,
390        account_data_direct_mapping,
391    );
392
393    let mut accounts_metadata: Vec<SerializedAccountMetadata> = Vec::with_capacity(accounts.len());
394    s.write::<u64>((accounts.len() as u64).to_le());
395    for account in accounts {
396        match account {
397            SerializeAccount::Duplicate(position) => {
398                accounts_metadata.push(accounts_metadata.get(position as usize).unwrap().clone());
399                s.write(position as u8);
400            }
401            SerializeAccount::Account(_, mut account) => {
402                let vm_addr = s.write::<u8>(NON_DUP_MARKER);
403                s.write::<u8>(account.is_signer() as u8);
404                s.write::<u8>(account.is_writable() as u8);
405                let vm_key_addr = s.write_all(account.get_key().as_ref());
406                let vm_lamports_addr = s.write::<u64>(account.get_lamports().to_le());
407                s.write::<u64>((account.get_data().len() as u64).to_le());
408                let vm_data_addr = s.write_account(&mut account)?;
409                let vm_owner_addr = s.write_all(account.get_owner().as_ref());
410                #[expect(deprecated)]
411                s.write::<u8>(account.is_executable() as u8);
412                let rent_epoch = u64::MAX;
413                s.write::<u64>(rent_epoch.to_le());
414                accounts_metadata.push(SerializedAccountMetadata {
415                    vm_addr,
416                    original_data_len: account.get_data().len(),
417                    vm_key_addr,
418                    vm_lamports_addr,
419                    vm_owner_addr,
420                    vm_data_addr,
421                });
422            }
423        };
424    }
425    s.write::<u64>((instruction_data.len() as u64).to_le());
426    let instruction_data_offset = s.write_all(instruction_data);
427    s.write_all(program_id.as_ref());
428
429    let (mem, regions) = s.finish();
430    Ok((
431        mem,
432        regions,
433        accounts_metadata,
434        instruction_data_offset as usize,
435    ))
436}
437
438fn deserialize_parameters_for_abiv0<I: IntoIterator<Item = usize>>(
439    instruction_context: &InstructionContext,
440    virtual_address_space_adjustments: bool,
441    account_data_direct_mapping: bool,
442    buffer: &[u8],
443    account_lengths: I,
444) -> Result<(), InstructionError> {
445    let mut start = size_of::<u64>(); // number of accounts
446    for (instruction_account_index, pre_len) in
447        (0..instruction_context.get_number_of_instruction_accounts()).zip(account_lengths)
448    {
449        let duplicate =
450            instruction_context.is_instruction_account_duplicate(instruction_account_index)?;
451        start += 1; // is_dup
452        if duplicate.is_none() {
453            let mut borrowed_account =
454                instruction_context.try_borrow_instruction_account(instruction_account_index)?;
455            start += size_of::<u8>(); // is_signer
456            start += size_of::<u8>(); // is_writable
457            start += size_of::<Pubkey>(); // key
458            let lamports = buffer
459                .get(start..start.saturating_add(8))
460                .map(<[u8; 8]>::try_from)
461                .and_then(Result::ok)
462                .map(u64::from_le_bytes)
463                .ok_or(InstructionError::InvalidArgument)?;
464            if borrowed_account.get_lamports() != lamports {
465                borrowed_account.set_lamports(lamports)?;
466            }
467            start += size_of::<u64>() // lamports
468                + size_of::<u64>(); // data length
469            if !virtual_address_space_adjustments {
470                let data = buffer
471                    .get(start..start + pre_len)
472                    .ok_or(InstructionError::InvalidArgument)?;
473                // The redundant check helps to avoid the expensive data comparison if we can
474                match borrowed_account.can_data_be_resized(pre_len) {
475                    Ok(()) => borrowed_account.set_data_from_slice(data)?,
476                    Err(err) if borrowed_account.get_data() != data => return Err(err),
477                    _ => {}
478                }
479            } else if !account_data_direct_mapping && borrowed_account.can_data_be_changed().is_ok()
480            {
481                let data = buffer
482                    .get(start..start + pre_len)
483                    .ok_or(InstructionError::InvalidArgument)?;
484                borrowed_account.set_data_from_slice(data)?;
485            } else if borrowed_account.get_data().len() != pre_len {
486                borrowed_account.set_data_length(pre_len)?;
487            }
488            if !(virtual_address_space_adjustments && account_data_direct_mapping) {
489                start += pre_len; // data
490            }
491            start += size_of::<Pubkey>() // owner
492                + size_of::<u8>() // executable
493                + size_of::<u64>(); // rent_epoch
494        }
495    }
496    Ok(())
497}
498
499fn serialize_parameters_for_abiv1(
500    accounts: Vec<SerializeAccount>,
501    instruction_data: &[u8],
502    program_id: &Pubkey,
503    virtual_address_space_adjustments: bool,
504    account_data_direct_mapping: bool,
505    direct_account_pointers_program_input: bool,
506) -> Result<SerializationResult, InstructionError> {
507    const ABI_VERSION: ABI = ABI::V1;
508
509    let mut accounts_metadata = Vec::with_capacity(accounts.len());
510    // Calculate size in order to alloc once
511    let mut size = size_of::<u64>();
512    for account in &accounts {
513        size += 1; // dup
514        match account {
515            SerializeAccount::Duplicate(_) => size += 7, // padding to 64-bit aligned
516            SerializeAccount::Account(_, account) => {
517                let data_len = account.get_data().len();
518                size += size_of::<u8>() // is_signer
519                + size_of::<u8>() // is_writable
520                + size_of::<u8>() // executable
521                + size_of::<u32>() // original_data_len
522                + size_of::<Pubkey>()  // key
523                + size_of::<Pubkey>() // owner
524                + size_of::<u64>()  // lamports
525                + size_of::<u64>()  // data len
526                + size_of::<u64>(); // rent epoch
527                if !(virtual_address_space_adjustments && account_data_direct_mapping) {
528                    size += data_len
529                        + MAX_PERMITTED_DATA_INCREASE
530                        + (data_len as *const u8).align_offset(ABI_VERSION.alignment());
531                } else {
532                    size += ABI_VERSION.alignment();
533                }
534            }
535        }
536    }
537    size += size_of::<u64>() // data len
538    + instruction_data.len()
539    + size_of::<Pubkey>(); // program id;
540
541    // reserve space for the array of account pointers if SIMD-0449 is enabled
542    let account_pointers_padding = if direct_account_pointers_program_input {
543        let padding = (size as *const u8).align_offset(ABI_VERSION.alignment());
544        size += padding + accounts.len() * size_of::<u64>();
545        Some(padding)
546    } else {
547        None
548    };
549
550    let mut s = Serializer::new(
551        size,
552        MM_INPUT_START,
553        ABI_VERSION,
554        virtual_address_space_adjustments,
555        account_data_direct_mapping,
556    );
557
558    // Serialize into the buffer
559    s.write::<u64>((accounts.len() as u64).to_le());
560    for account in accounts {
561        match account {
562            SerializeAccount::Account(_, mut borrowed_account) => {
563                let vm_addr = s.write::<u8>(NON_DUP_MARKER);
564                s.write::<u8>(borrowed_account.is_signer() as u8);
565                s.write::<u8>(borrowed_account.is_writable() as u8);
566                #[expect(deprecated)]
567                s.write::<u8>(borrowed_account.is_executable() as u8);
568                s.write_all(&[0u8, 0, 0, 0]);
569                let vm_key_addr = s.write_all(borrowed_account.get_key().as_ref());
570                let vm_owner_addr = s.write_all(borrowed_account.get_owner().as_ref());
571                let vm_lamports_addr = s.write::<u64>(borrowed_account.get_lamports().to_le());
572                s.write::<u64>((borrowed_account.get_data().len() as u64).to_le());
573                let vm_data_addr = s.write_account(&mut borrowed_account)?;
574                let rent_epoch = u64::MAX;
575                s.write::<u64>(rent_epoch.to_le());
576                accounts_metadata.push(SerializedAccountMetadata {
577                    vm_addr,
578                    original_data_len: borrowed_account.get_data().len(),
579                    vm_key_addr,
580                    vm_owner_addr,
581                    vm_lamports_addr,
582                    vm_data_addr,
583                });
584            }
585            SerializeAccount::Duplicate(position) => {
586                accounts_metadata.push(accounts_metadata.get(position as usize).unwrap().clone());
587                s.write::<u8>(position as u8);
588                s.write_all(&[0u8, 0, 0, 0, 0, 0, 0]);
589            }
590        };
591    }
592    s.write::<u64>((instruction_data.len() as u64).to_le());
593    let instruction_data_offset = s.write_all(instruction_data);
594    // Determines the address of the array of account pointers, if account
595    // pointers are being passed in the program input (SIMD-0449).
596    let account_pointers_offset = {
597        let vaddr = s.write_all(program_id.as_ref()) as usize;
598
599        if let Some(padding) = account_pointers_padding {
600            // Add padding before the array of account pointers to reach
601            // 8-byte alignment (`ABI_VERSION.alignment()`).
602            s.fill_write(padding, 0)
603                .map_err(|_| InstructionError::InvalidArgument)?;
604            for entry in accounts_metadata.iter() {
605                s.write::<u64>(entry.vm_addr.to_le());
606            }
607            // Compute the address of the array of account pointers.
608            Some(vaddr + size_of::<Pubkey>() + padding)
609        } else {
610            None
611        }
612    };
613
614    let (mem, regions) = s.finish();
615    Ok(SerializationResult {
616        parameter_bytes: mem,
617        regions,
618        accounts_metadata,
619        instruction_data_offset: instruction_data_offset as usize,
620        account_pointers_offset,
621    })
622}
623
624fn deserialize_parameters_for_abiv1<I: IntoIterator<Item = usize>>(
625    instruction_context: &InstructionContext,
626    virtual_address_space_adjustments: bool,
627    account_data_direct_mapping: bool,
628    buffer: &[u8],
629    account_lengths: I,
630) -> Result<(), InstructionError> {
631    const ABI_VERSION: ABI = ABI::V1;
632
633    let mut start = size_of::<u64>(); // number of accounts
634    for (instruction_account_index, pre_len) in
635        (0..instruction_context.get_number_of_instruction_accounts()).zip(account_lengths)
636    {
637        let duplicate =
638            instruction_context.is_instruction_account_duplicate(instruction_account_index)?;
639        start += size_of::<u8>(); // position
640        if duplicate.is_some() {
641            start += 7; // padding to 64-bit aligned
642        } else {
643            let mut borrowed_account =
644                instruction_context.try_borrow_instruction_account(instruction_account_index)?;
645            start += size_of::<u8>() // is_signer
646                + size_of::<u8>() // is_writable
647                + size_of::<u8>() // executable
648                + size_of::<u32>() // original_data_len
649                + size_of::<Pubkey>(); // key
650            let owner = buffer
651                .get(start..start + size_of::<Pubkey>())
652                .ok_or(InstructionError::InvalidArgument)?;
653            start += size_of::<Pubkey>(); // owner
654            let lamports = buffer
655                .get(start..start.saturating_add(8))
656                .map(<[u8; 8]>::try_from)
657                .and_then(Result::ok)
658                .map(u64::from_le_bytes)
659                .ok_or(InstructionError::InvalidArgument)?;
660            if borrowed_account.get_lamports() != lamports {
661                borrowed_account.set_lamports(lamports)?;
662            }
663            start += size_of::<u64>(); // lamports
664            let post_len = buffer
665                .get(start..start.saturating_add(8))
666                .map(<[u8; 8]>::try_from)
667                .and_then(Result::ok)
668                .map(u64::from_le_bytes)
669                .ok_or(InstructionError::InvalidArgument)? as usize;
670            start += size_of::<u64>(); // data length
671            if post_len.saturating_sub(pre_len) > MAX_PERMITTED_DATA_INCREASE
672                || post_len > MAX_PERMITTED_DATA_LENGTH as usize
673            {
674                return Err(InstructionError::InvalidRealloc);
675            }
676            if !virtual_address_space_adjustments {
677                let data = buffer
678                    .get(start..start + post_len)
679                    .ok_or(InstructionError::InvalidArgument)?;
680                // The redundant check helps to avoid the expensive data comparison if we can
681                match borrowed_account.can_data_be_resized(post_len) {
682                    Ok(()) => borrowed_account.set_data_from_slice(data)?,
683                    Err(err) if borrowed_account.get_data() != data => return Err(err),
684                    _ => {}
685                }
686            } else if !account_data_direct_mapping && borrowed_account.can_data_be_changed().is_ok()
687            {
688                let data = buffer
689                    .get(start..start + post_len)
690                    .ok_or(InstructionError::InvalidArgument)?;
691                borrowed_account.set_data_from_slice(data)?;
692            } else if borrowed_account.get_data().len() != post_len {
693                borrowed_account.set_data_length(post_len)?;
694            }
695            start += if !(virtual_address_space_adjustments && account_data_direct_mapping) {
696                let alignment_offset = (pre_len as *const u8).align_offset(ABI_VERSION.alignment());
697                pre_len // data
698                    .saturating_add(MAX_PERMITTED_DATA_INCREASE) // realloc padding
699                    .saturating_add(alignment_offset)
700            } else {
701                // See Serializer::write_account() as to why we have this
702                ABI_VERSION.alignment()
703            };
704            start += size_of::<u64>(); // rent_epoch
705            if borrowed_account.get_owner().to_bytes() != owner {
706                // Change the owner at the end so that we are allowed to change the lamports and data before
707                borrowed_account.set_owner(owner)?;
708            }
709        }
710    }
711    Ok(())
712}
713
714#[cfg(test)]
715#[allow(clippy::indexing_slicing)]
716mod tests {
717    use {
718        super::*,
719        crate::{
720            invoke_context::BpfAllocator, memory_context::MemoryContext, with_mock_invoke_context,
721        },
722        solana_account::{Account, AccountSharedData},
723        solana_account_info::AccountInfo,
724        solana_program_entrypoint::{BPF_ALIGN_OF_U128, deserialize},
725        solana_sbpf::{
726            memory_region::MemoryMapping,
727            program::{BuiltinProgram, SBPFVersion},
728            vm::{Config, EbpfVm},
729        },
730        solana_sdk_ids::{bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable},
731        solana_system_interface::MAX_PERMITTED_ACCOUNTS_DATA_ALLOCATIONS_PER_TRANSACTION,
732        solana_transaction_context::{
733            MAX_ACCOUNTS_PER_TRANSACTION, instruction_accounts::InstructionAccount,
734        },
735        std::{
736            borrow::Cow,
737            cell::RefCell,
738            mem::transmute,
739            rc::Rc,
740            slice::{from_raw_parts, from_raw_parts_mut},
741            sync::Arc,
742        },
743        test_case::test_case,
744    };
745
746    fn deduplicated_instruction_accounts(
747        transaction_indexes: &[IndexOfAccount],
748        is_writable: fn(usize) -> bool,
749    ) -> Vec<InstructionAccount> {
750        transaction_indexes
751            .iter()
752            .enumerate()
753            .map(|(index_in_instruction, index_in_transaction)| {
754                InstructionAccount::new(
755                    *index_in_transaction,
756                    false,
757                    is_writable(index_in_instruction),
758                )
759            })
760            .collect()
761    }
762
763    #[test_case(false; "direct_account_pointers_in_program_input disabled")]
764    #[test_case(true; "direct_account_pointers_in_program_input enabled")]
765    fn test_serialize_parameters_with_many_accounts(
766        direct_account_pointers_in_program_input: bool,
767    ) {
768        struct TestCase {
769            num_ix_accounts: usize,
770            append_dup_account: bool,
771            expected_err: Option<InstructionError>,
772            name: &'static str,
773        }
774
775        for virtual_address_space_adjustments in [false, true] {
776            for TestCase {
777                num_ix_accounts,
778                append_dup_account,
779                expected_err,
780                name,
781            } in [
782                TestCase {
783                    name: "serialize max accounts with cap",
784                    num_ix_accounts: MAX_ACCOUNTS_PER_INSTRUCTION,
785                    append_dup_account: false,
786                    expected_err: None,
787                },
788                TestCase {
789                    name: "serialize too many accounts with cap",
790                    num_ix_accounts: MAX_ACCOUNTS_PER_INSTRUCTION + 1,
791                    append_dup_account: false,
792                    expected_err: Some(InstructionError::MaxAccountsExceeded),
793                },
794                TestCase {
795                    name: "serialize too many accounts and append dup with cap",
796                    num_ix_accounts: MAX_ACCOUNTS_PER_INSTRUCTION,
797                    append_dup_account: true,
798                    expected_err: Some(InstructionError::MaxAccountsExceeded),
799                },
800            ] {
801                let program_id = solana_pubkey::new_rand();
802                let mut transaction_accounts = vec![(
803                    program_id,
804                    AccountSharedData::from(Account {
805                        lamports: 0,
806                        data: vec![],
807                        owner: bpf_loader::id(),
808                        executable: true,
809                        rent_epoch: 0,
810                    }),
811                )];
812                for _ in 0..num_ix_accounts {
813                    transaction_accounts.push((
814                        Pubkey::new_unique(),
815                        AccountSharedData::from(Account {
816                            lamports: 0,
817                            data: vec![],
818                            owner: program_id,
819                            executable: false,
820                            rent_epoch: 0,
821                        }),
822                    ));
823                }
824
825                let transaction_accounts_indexes: Vec<IndexOfAccount> =
826                    (0..num_ix_accounts as u16).collect();
827                let mut instruction_accounts =
828                    deduplicated_instruction_accounts(&transaction_accounts_indexes, |_| false);
829                if append_dup_account {
830                    instruction_accounts.push(instruction_accounts.last().cloned().unwrap());
831                }
832                let instruction_data = vec![];
833                let num_transaction_accounts =
834                    transaction_accounts.len().min(MAX_ACCOUNTS_PER_TRANSACTION);
835
836                with_mock_invoke_context!(
837                    invoke_context,
838                    transaction_context,
839                    transaction_accounts
840                );
841                if instruction_accounts.len() > MAX_ACCOUNTS_PER_INSTRUCTION {
842                    // Oversized instructions are rejected before serialization.
843                    let dedup_map = vec![u8::MAX; num_transaction_accounts];
844                    assert_eq!(
845                        invoke_context
846                            .transaction_context
847                            .configure_instruction_at_index(
848                                0,
849                                0,
850                                instruction_accounts,
851                                dedup_map,
852                                Cow::Owned(instruction_data.clone()),
853                                Some(0),
854                            ),
855                        Err(InstructionError::MaxAccountsExceeded),
856                        "{name} test case failed",
857                    );
858                    continue;
859                }
860                invoke_context
861                    .transaction_context
862                    .configure_top_level_instruction_for_tests(
863                        0,
864                        instruction_accounts,
865                        instruction_data.clone(),
866                    )
867                    .unwrap();
868                invoke_context.push().unwrap();
869                let instruction_context = invoke_context
870                    .transaction_context
871                    .get_current_instruction_context()
872                    .unwrap();
873
874                let serialization_result = serialize_parameters(
875                    &instruction_context,
876                    ABI::V1,
877                    virtual_address_space_adjustments,
878                    false, // account_data_direct_mapping
879                    direct_account_pointers_in_program_input,
880                );
881                assert_eq!(
882                    serialization_result.as_ref().err(),
883                    expected_err.as_ref(),
884                    "{name} test case failed",
885                );
886                if expected_err.is_some() {
887                    continue;
888                }
889
890                let SerializationResult {
891                    parameter_bytes: mut serialized,
892                    regions,
893                    account_pointers_offset,
894                    ..
895                } = serialization_result.unwrap();
896                let mut serialized_regions = unsafe {
897                    // SAFETY: test code, serialize_parameters should be constructing valid regions.
898                    concat_regions(&regions)
899                };
900                let (de_program_id, de_accounts, de_instruction_data) = unsafe {
901                    deserialize(
902                        if !virtual_address_space_adjustments {
903                            serialized.as_slice_mut()
904                        } else {
905                            serialized_regions.as_slice_mut()
906                        }
907                        .first_mut()
908                        .unwrap() as *mut u8,
909                    )
910                };
911                assert_eq!(de_program_id, &program_id);
912                assert_eq!(de_instruction_data, &instruction_data);
913                assert_eq!(
914                    direct_account_pointers_in_program_input,
915                    account_pointers_offset.is_some()
916                );
917                for account_info in de_accounts {
918                    let index_in_transaction = invoke_context
919                        .transaction_context
920                        .find_index_of_account(account_info.key)
921                        .unwrap();
922                    let account = invoke_context
923                        .transaction_context
924                        .accounts()
925                        .try_borrow(index_in_transaction)
926                        .unwrap();
927                    assert_eq!(account.lamports(), account_info.lamports());
928                    assert_eq!(account.data(), &account_info.data.borrow()[..]);
929                    assert_eq!(account.owner(), account_info.owner);
930                    assert_eq!(account.executable(), account_info.executable);
931                    #[allow(deprecated)]
932                    {
933                        // Using the sdk entrypoint, the rent-epoch is skipped
934                        assert_eq!(0, account_info._unused);
935                    }
936                }
937            }
938        }
939    }
940
941    #[test_case(false; "direct_account_pointers_in_program_input disabled")]
942    #[test_case(true; "direct_account_pointers_in_program_input enabled")]
943    fn test_serialize_parameters(direct_account_pointers_in_program_input: bool) {
944        for virtual_address_space_adjustments in [false, true] {
945            let program_id = solana_pubkey::new_rand();
946            let transaction_accounts = vec![
947                (
948                    program_id,
949                    AccountSharedData::from(Account {
950                        lamports: 0,
951                        data: vec![],
952                        owner: bpf_loader::id(),
953                        executable: true,
954                        rent_epoch: 0,
955                    }),
956                ),
957                (
958                    solana_pubkey::new_rand(),
959                    AccountSharedData::from(Account {
960                        lamports: 1,
961                        data: vec![1u8, 2, 3, 4, 5],
962                        owner: bpf_loader::id(),
963                        executable: false,
964                        rent_epoch: 100,
965                    }),
966                ),
967                (
968                    solana_pubkey::new_rand(),
969                    AccountSharedData::from(Account {
970                        lamports: 2,
971                        data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
972                        owner: bpf_loader::id(),
973                        executable: true,
974                        rent_epoch: 200,
975                    }),
976                ),
977                (
978                    solana_pubkey::new_rand(),
979                    AccountSharedData::from(Account {
980                        lamports: 3,
981                        data: vec![],
982                        owner: bpf_loader::id(),
983                        executable: false,
984                        rent_epoch: 3100,
985                    }),
986                ),
987                (
988                    solana_pubkey::new_rand(),
989                    AccountSharedData::from(Account {
990                        lamports: 4,
991                        data: vec![1u8, 2, 3, 4, 5],
992                        owner: bpf_loader::id(),
993                        executable: false,
994                        rent_epoch: 100,
995                    }),
996                ),
997                (
998                    solana_pubkey::new_rand(),
999                    AccountSharedData::from(Account {
1000                        lamports: 5,
1001                        data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
1002                        owner: bpf_loader::id(),
1003                        executable: true,
1004                        rent_epoch: 200,
1005                    }),
1006                ),
1007                (
1008                    solana_pubkey::new_rand(),
1009                    AccountSharedData::from(Account {
1010                        lamports: 6,
1011                        data: vec![],
1012                        owner: bpf_loader::id(),
1013                        executable: false,
1014                        rent_epoch: 3100,
1015                    }),
1016                ),
1017                (
1018                    program_id,
1019                    AccountSharedData::from(Account {
1020                        lamports: 0,
1021                        data: vec![],
1022                        owner: bpf_loader_deprecated::id(),
1023                        executable: true,
1024                        rent_epoch: 0,
1025                    }),
1026                ),
1027            ];
1028            let instruction_accounts =
1029                deduplicated_instruction_accounts(&[1, 1, 2, 3, 4, 4, 5, 6], |index| index >= 4);
1030            let instruction_data = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
1031            let original_accounts = transaction_accounts.clone();
1032            with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1033            invoke_context
1034                .transaction_context
1035                .configure_top_level_instruction_for_tests(
1036                    0,
1037                    instruction_accounts.clone(),
1038                    instruction_data.clone(),
1039                )
1040                .unwrap();
1041            invoke_context.push().unwrap();
1042            let instruction_context = invoke_context
1043                .transaction_context
1044                .get_current_instruction_context()
1045                .unwrap();
1046
1047            // check serialize_parameters_for_abiv1
1048            let SerializationResult {
1049                parameter_bytes: mut serialized,
1050                regions,
1051                accounts_metadata,
1052                account_pointers_offset,
1053                ..
1054            } = serialize_parameters(
1055                &instruction_context,
1056                ABI::V1,
1057                virtual_address_space_adjustments,
1058                false, // account_data_direct_mapping
1059                direct_account_pointers_in_program_input,
1060            )
1061            .unwrap();
1062
1063            let mut serialized_regions = unsafe {
1064                // SAFETY: test code, serialize_parameters should be constructing valid regions.
1065                concat_regions(&regions)
1066            };
1067            if !virtual_address_space_adjustments {
1068                assert_eq!(serialized.as_slice(), serialized_regions.as_slice());
1069            }
1070            let (de_program_id, de_accounts, de_instruction_data) = unsafe {
1071                deserialize(
1072                    if !virtual_address_space_adjustments {
1073                        serialized.as_slice_mut()
1074                    } else {
1075                        serialized_regions.as_slice_mut()
1076                    }
1077                    .first_mut()
1078                    .unwrap() as *mut u8,
1079                )
1080            };
1081
1082            assert_eq!(&program_id, de_program_id);
1083            assert_eq!(instruction_data, de_instruction_data);
1084            assert_eq!(
1085                (de_instruction_data.first().unwrap() as *const u8).align_offset(BPF_ALIGN_OF_U128),
1086                0
1087            );
1088            assert_eq!(
1089                direct_account_pointers_in_program_input,
1090                account_pointers_offset.is_some()
1091            );
1092            for account_info in de_accounts {
1093                let index_in_transaction = invoke_context
1094                    .transaction_context
1095                    .find_index_of_account(account_info.key)
1096                    .unwrap();
1097                let account = invoke_context
1098                    .transaction_context
1099                    .accounts()
1100                    .try_borrow(index_in_transaction)
1101                    .unwrap();
1102                assert_eq!(account.lamports(), account_info.lamports());
1103                assert_eq!(account.data(), &account_info.data.borrow()[..]);
1104                assert_eq!(account.owner(), account_info.owner);
1105                assert_eq!(account.executable(), account_info.executable);
1106                #[allow(deprecated)]
1107                {
1108                    // Using the sdk entrypoint, the rent-epoch is skipped
1109                    assert_eq!(0, account_info._unused);
1110                }
1111
1112                assert_eq!(
1113                    (*account_info.lamports.borrow() as *const u64).align_offset(BPF_ALIGN_OF_U128),
1114                    0
1115                );
1116                assert_eq!(
1117                    account_info
1118                        .data
1119                        .borrow()
1120                        .as_ptr()
1121                        .align_offset(BPF_ALIGN_OF_U128),
1122                    0
1123                );
1124            }
1125
1126            deserialize_parameters(
1127                &instruction_context,
1128                ABI::V1,
1129                virtual_address_space_adjustments,
1130                false, // account_data_direct_mapping
1131                serialized.as_slice(),
1132                &accounts_metadata,
1133            )
1134            .unwrap();
1135            for (index_in_transaction, (_key, original_account)) in
1136                original_accounts.iter().enumerate()
1137            {
1138                let account = invoke_context
1139                    .transaction_context
1140                    .accounts()
1141                    .try_borrow(index_in_transaction as IndexOfAccount)
1142                    .unwrap();
1143                assert_eq!(&*account, original_account);
1144            }
1145
1146            invoke_context.pop().unwrap();
1147            // check serialize_parameters_for_abiv0
1148            invoke_context
1149                .transaction_context
1150                .configure_top_level_instruction_for_tests(
1151                    7,
1152                    instruction_accounts,
1153                    instruction_data.clone(),
1154                )
1155                .unwrap();
1156            invoke_context.push().unwrap();
1157            let instruction_context = invoke_context
1158                .transaction_context
1159                .get_current_instruction_context()
1160                .unwrap();
1161
1162            let SerializationResult {
1163                parameter_bytes: mut serialized,
1164                regions,
1165                accounts_metadata: account_lengths,
1166                account_pointers_offset,
1167                ..
1168            } = serialize_parameters(
1169                &instruction_context,
1170                ABI::V0,
1171                virtual_address_space_adjustments,
1172                false, // account_data_direct_mapping
1173                direct_account_pointers_in_program_input,
1174            )
1175            .unwrap();
1176            let mut serialized_regions = unsafe {
1177                // SAFETY: test code, serialize_parameters should be constructing valid regions.
1178                concat_regions(&regions)
1179            };
1180
1181            let (de_program_id, de_accounts, de_instruction_data) = unsafe {
1182                deserialize_for_abiv0(
1183                    if !virtual_address_space_adjustments {
1184                        serialized.as_slice_mut()
1185                    } else {
1186                        serialized_regions.as_slice_mut()
1187                    }
1188                    .first_mut()
1189                    .unwrap() as *mut u8,
1190                )
1191            };
1192            assert_eq!(&program_id, de_program_id);
1193            assert_eq!(instruction_data, de_instruction_data);
1194            // abiv0 does not support direct account pointers in program input.
1195            assert!(account_pointers_offset.is_none());
1196            for account_info in de_accounts {
1197                let index_in_transaction = invoke_context
1198                    .transaction_context
1199                    .find_index_of_account(account_info.key)
1200                    .unwrap();
1201                let account = invoke_context
1202                    .transaction_context
1203                    .accounts()
1204                    .try_borrow(index_in_transaction)
1205                    .unwrap();
1206                assert_eq!(account.lamports(), account_info.lamports());
1207                assert_eq!(account.data(), &account_info.data.borrow()[..]);
1208                assert_eq!(account.owner(), account_info.owner);
1209                assert_eq!(account.executable(), account_info.executable);
1210                #[allow(deprecated)]
1211                {
1212                    assert_eq!(u64::MAX, account_info._unused);
1213                }
1214            }
1215
1216            deserialize_parameters(
1217                &instruction_context,
1218                ABI::V0,
1219                virtual_address_space_adjustments,
1220                false, // account_data_direct_mapping
1221                serialized.as_slice(),
1222                &account_lengths,
1223            )
1224            .unwrap();
1225            for (index_in_transaction, (_key, original_account)) in
1226                original_accounts.iter().enumerate()
1227            {
1228                let account = invoke_context
1229                    .transaction_context
1230                    .accounts()
1231                    .try_borrow(index_in_transaction as IndexOfAccount)
1232                    .unwrap();
1233                assert_eq!(&*account, original_account);
1234            }
1235        }
1236    }
1237
1238    #[test_case(false; "direct_account_pointers_in_program_input disabled")]
1239    #[test_case(true; "direct_account_pointers_in_program_input enabled")]
1240    fn test_serialize_parameters_mask_out_rent_epoch_in_vm_serialization(
1241        direct_account_pointers_in_program_input: bool,
1242    ) {
1243        let transaction_accounts = vec![
1244            (
1245                solana_pubkey::new_rand(),
1246                AccountSharedData::from(Account {
1247                    lamports: 0,
1248                    data: vec![],
1249                    owner: bpf_loader::id(),
1250                    executable: true,
1251                    rent_epoch: 0,
1252                }),
1253            ),
1254            (
1255                solana_pubkey::new_rand(),
1256                AccountSharedData::from(Account {
1257                    lamports: 1,
1258                    data: vec![1u8, 2, 3, 4, 5],
1259                    owner: bpf_loader::id(),
1260                    executable: false,
1261                    rent_epoch: 100,
1262                }),
1263            ),
1264            (
1265                solana_pubkey::new_rand(),
1266                AccountSharedData::from(Account {
1267                    lamports: 2,
1268                    data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
1269                    owner: bpf_loader::id(),
1270                    executable: true,
1271                    rent_epoch: 200,
1272                }),
1273            ),
1274            (
1275                solana_pubkey::new_rand(),
1276                AccountSharedData::from(Account {
1277                    lamports: 3,
1278                    data: vec![],
1279                    owner: bpf_loader::id(),
1280                    executable: false,
1281                    rent_epoch: 300,
1282                }),
1283            ),
1284            (
1285                solana_pubkey::new_rand(),
1286                AccountSharedData::from(Account {
1287                    lamports: 4,
1288                    data: vec![1u8, 2, 3, 4, 5],
1289                    owner: bpf_loader::id(),
1290                    executable: false,
1291                    rent_epoch: 100,
1292                }),
1293            ),
1294            (
1295                solana_pubkey::new_rand(),
1296                AccountSharedData::from(Account {
1297                    lamports: 5,
1298                    data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
1299                    owner: bpf_loader::id(),
1300                    executable: true,
1301                    rent_epoch: 200,
1302                }),
1303            ),
1304            (
1305                solana_pubkey::new_rand(),
1306                AccountSharedData::from(Account {
1307                    lamports: 6,
1308                    data: vec![],
1309                    owner: bpf_loader::id(),
1310                    executable: false,
1311                    rent_epoch: 3100,
1312                }),
1313            ),
1314            (
1315                solana_pubkey::new_rand(),
1316                AccountSharedData::from(Account {
1317                    lamports: 0,
1318                    data: vec![],
1319                    owner: bpf_loader_deprecated::id(),
1320                    executable: true,
1321                    rent_epoch: 0,
1322                }),
1323            ),
1324        ];
1325        let instruction_accounts =
1326            deduplicated_instruction_accounts(&[1, 1, 2, 3, 4, 4, 5, 6], |index| index >= 4);
1327        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1328        invoke_context
1329            .transaction_context
1330            .configure_top_level_instruction_for_tests(0, instruction_accounts.clone(), vec![])
1331            .unwrap();
1332        invoke_context.push().unwrap();
1333        let instruction_context = invoke_context
1334            .transaction_context
1335            .get_current_instruction_context()
1336            .unwrap();
1337
1338        // check serialize_parameters_for_abiv1
1339        let SerializationResult {
1340            parameter_bytes: _serialized,
1341            regions,
1342            ..
1343        } = serialize_parameters(
1344            &instruction_context,
1345            ABI::V1,
1346            true,
1347            false, // account_data_direct_mapping
1348            direct_account_pointers_in_program_input,
1349        )
1350        .unwrap();
1351
1352        let mut serialized_regions = unsafe {
1353            // SAFETY: test code, serialize_parameters should be constructing valid regions.
1354            concat_regions(&regions)
1355        };
1356        let (_de_program_id, de_accounts, _de_instruction_data) = unsafe {
1357            deserialize(serialized_regions.as_slice_mut().first_mut().unwrap() as *mut u8)
1358        };
1359
1360        for account_info in de_accounts {
1361            // Using program-entrypoint, the rent-epoch will always be 0
1362            #[allow(deprecated)]
1363            {
1364                assert_eq!(0, account_info._unused);
1365            }
1366        }
1367
1368        // check serialize_parameters_for_abiv0
1369        invoke_context
1370            .transaction_context
1371            .configure_top_level_instruction_for_tests(7, instruction_accounts, vec![])
1372            .unwrap();
1373        invoke_context.push().unwrap();
1374        let instruction_context = invoke_context
1375            .transaction_context
1376            .get_current_instruction_context()
1377            .unwrap();
1378
1379        let SerializationResult {
1380            parameter_bytes: _serialized,
1381            regions,
1382            ..
1383        } = serialize_parameters(
1384            &instruction_context,
1385            ABI::V0,
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::empty(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::empty(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            ABI::V1,
1815            true,  // virtual_address_space_adjustments
1816            false, // account_data_direct_mapping
1817            false, // direct_account_pointers_in_program_input
1818        )
1819        .unwrap();
1820        let config = Config {
1821            aligned_memory_mapping: false,
1822            ..Config::default()
1823        };
1824        let memory_mapping =
1825            unsafe { MemoryMapping::new(regions, &config, SBPFVersion::V3).unwrap() };
1826        let account_metadata = &accounts_metadata[0];
1827        let vm_data_addr = account_metadata.vm_data_addr;
1828        let (_region_index, region) = memory_mapping.find_region(vm_data_addr).unwrap();
1829        assert_eq!(region.len(), 5);
1830    }
1831
1832    // V0 serializes the owner, executable and rent epoch after the data, V1 only the rent epoch.
1833    #[test_case(ABI::V0, 0, 1, 41; "abi_v0")]
1834    #[test_case(ABI::V1, MAX_PERMITTED_DATA_INCREASE, BPF_ALIGN_OF_U128, 8; "abi_v1")]
1835    fn test_direct_mapping_reserves_account_realloc_padding(
1836        abi: ABI,
1837        realloc_padding: usize,
1838        alignment: usize,
1839        bytes_after_data: usize,
1840    ) {
1841        // Unaligned, aligned and empty account data, followed by another account.
1842        let account_data: [&[u8]; 4] = [b"agave", &[1; 8], &[], b"anza"];
1843        let program_id = Pubkey::new_unique();
1844        let mut transaction_accounts = vec![(
1845            program_id,
1846            AccountSharedData::from(Account {
1847                executable: true,
1848                owner: bpf_loader::id(),
1849                ..Account::default()
1850            }),
1851        )];
1852        transaction_accounts.extend(account_data.iter().map(|data| {
1853            (
1854                Pubkey::new_unique(),
1855                AccountSharedData::new_with_data(0, data.to_vec(), &program_id),
1856            )
1857        }));
1858        let instruction_accounts = (1..=account_data.len() as u16)
1859            .map(|index_in_transaction| InstructionAccount::new(index_in_transaction, false, true))
1860            .collect();
1861        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1862        invoke_context
1863            .transaction_context
1864            .configure_top_level_instruction_for_tests(0, instruction_accounts, vec![])
1865            .unwrap();
1866        invoke_context.push().unwrap();
1867        let instruction_context = invoke_context
1868            .transaction_context
1869            .get_current_instruction_context()
1870            .unwrap();
1871
1872        let SerializationResult {
1873            regions,
1874            accounts_metadata,
1875            ..
1876        } = serialize_parameters(
1877            &instruction_context,
1878            abi,
1879            true,  // virtual_address_space_adjustments
1880            true,  // account_data_direct_mapping
1881            false, // direct_account_pointers_in_program_input
1882        )
1883        .unwrap();
1884
1885        assert_eq!(accounts_metadata.len(), account_data.len());
1886        for (index, data) in account_data.iter().enumerate() {
1887            let reserved_end =
1888                accounts_metadata[index].vm_data_addr + (data.len() + realloc_padding) as u64;
1889            assert!(
1890                regions
1891                    .iter()
1892                    .any(|region| region.vm_addr_range().start == reserved_end)
1893            );
1894
1895            // The next account starts past the remaining fields, realigned for the ABI.
1896            if let Some(next_account) = accounts_metadata.get(index + 1) {
1897                let align_offset = (data.len() as *const u8).align_offset(alignment);
1898                assert_eq!(
1899                    next_account.vm_addr,
1900                    reserved_end + (align_offset + bytes_after_data) as u64,
1901                );
1902                assert_eq!(next_account.vm_addr % alignment as u64, 0);
1903            }
1904        }
1905    }
1906}