Skip to main content

solana_program_runtime/
cpi.rs

1//! Cross-Program Invocation (CPI) error types
2
3use {
4    crate::{
5        abi::ABI,
6        invoke_context::InvokeContext,
7        memory::{translate_slice, translate_type, translate_type_mut_for_cpi, translate_vm_slice},
8        memory_context::SerializedAccountMetadata,
9        serialization::{create_memory_region_of_account, modify_memory_region_of_account},
10    },
11    solana_account_view::RuntimeAccount,
12    solana_instruction::{AccountMeta, Instruction},
13    solana_instruction_error::InstructionError,
14    solana_loader_v3_interface::instruction as bpf_loader_upgradeable,
15    solana_pubkey::{MAX_SEEDS, Pubkey, PubkeyError},
16    solana_sbpf::{ebpf, memory_region::MemoryMapping},
17    solana_sdk_ids::{bpf_loader, bpf_loader_deprecated, native_loader},
18    solana_stable_layout::stable_instruction::StableInstruction,
19    solana_svm_log_collector::ic_msg,
20    solana_svm_timings::ExecuteTimings,
21    solana_transaction_context::{
22        IndexOfAccount, MAX_ACCOUNTS_PER_INSTRUCTION, MAX_INSTRUCTION_DATA_LEN,
23        instruction_accounts::BorrowedInstructionAccount, vm_slice::VmSlice,
24    },
25    std::mem,
26    thiserror::Error,
27};
28
29/// CPI-specific error types
30#[derive(Clone, Debug, Error, PartialEq, Eq)]
31pub enum CpiError {
32    #[error("Invalid pointer")]
33    InvalidPointer,
34    #[error("Too many signers")]
35    TooManySigners,
36    #[error("Could not create program address with signer seeds: {0}")]
37    BadSeeds(PubkeyError),
38    #[error("InvalidLength")]
39    InvalidLength,
40    #[error("Invoked an instruction with too many accounts ({num_accounts} > {max_accounts})")]
41    MaxInstructionAccountsExceeded {
42        num_accounts: u64,
43        max_accounts: u64,
44    },
45    #[error("Invoked an instruction with data that is too large ({data_len} > {max_data_len})")]
46    MaxInstructionDataLenExceeded { data_len: u64, max_data_len: u64 },
47    #[error(
48        "Invoked an instruction with too many account info's ({num_account_infos} > \
49         {max_account_infos})"
50    )]
51    MaxInstructionAccountInfosExceeded {
52        num_account_infos: u64,
53        max_account_infos: u64,
54    },
55    #[error("Program {0} not supported by inner instructions")]
56    ProgramNotSupported(Pubkey),
57}
58
59type Error = Box<dyn std::error::Error>;
60
61const SUCCESS: u64 = 0;
62/// Maximum signers
63const MAX_SIGNERS: usize = 16;
64///SIMD-0339 based calculation of AccountInfo translation byte size. Fixed size of **80 bytes** for each AccountInfo broken down as:
65/// - 32 bytes for account address
66/// - 32 bytes for owner address
67/// - 8 bytes for lamport balance
68/// - 8 bytes for data length
69const ACCOUNT_INFO_BYTE_SIZE: usize = 80;
70
71/// Rust representation of C's SolInstruction
72#[derive(Debug)]
73#[repr(C)]
74pub struct SolInstruction {
75    pub program_id_addr: u64,
76    pub accounts_addr: u64,
77    pub accounts_len: u64,
78    pub data_addr: u64,
79    pub data_len: u64,
80}
81
82/// Rust representation of C's SolAccountMeta
83#[derive(Debug)]
84#[repr(C)]
85struct SolAccountMeta {
86    pub pubkey_addr: u64,
87    pub is_writable: bool,
88    pub is_signer: bool,
89}
90
91/// Rust representation of C's SolAccountInfo
92#[derive(Debug)]
93#[repr(C)]
94struct SolAccountInfo {
95    pub key_addr: u64,
96    pub lamports_addr: u64,
97    pub data_len: u64,
98    pub data_addr: u64,
99    pub owner_addr: u64,
100    pub rent_epoch: u64,
101    pub is_signer: bool,
102    pub is_writable: bool,
103    pub executable: bool,
104}
105
106/// Representation of an `AccountMeta` used in `invoke_signed_v2` syscall.
107#[derive(Debug)]
108#[repr(C)]
109struct SolAccountMetaV2 {
110    pub account_index: u16,
111    pub is_writable: u8,
112    pub is_signer: u8,
113}
114
115impl SolAccountMetaV2 {
116    #[inline(always)]
117    pub fn is_writable(&self) -> bool {
118        self.is_writable != 0
119    }
120
121    #[inline(always)]
122    pub fn is_signer(&self) -> bool {
123        self.is_signer != 0
124    }
125}
126
127mod stable {
128    /// Stable BPF representation of Rust [`solana_account_info::AccountInfo`].
129    #[derive(Debug)]
130    #[repr(C)]
131    pub struct AccountInfo {
132        key_addr: u64,
133        /// This address is pointing at `Rc<RefCell<T>>`'s internal data first. Use the
134        /// [`AccountInfo::lamports_addr()`] method to get the pointer to contained `T`.
135        lamports_addr: u64,
136        /// This address is pointing at `Rc<RefCell<T>>`'s internal data first. Use the
137        /// [`AccountInfo::data_addr()`] method to get the pointer to contained `T`.
138        data_addr: u64,
139        owner_addr: u64,
140        _unused: u64,
141        _is_signer: u8,
142        _is_writable: u8,
143        _executable: u8,
144    }
145
146    impl AccountInfo {
147        const LAMPORTS_DATA_OFFSET: u64 = 24;
148        const DATA_DATA_OFFSET: u64 = 24;
149        const DATA_LEN_OFFSET: u64 = 32;
150        pub(crate) fn owner_addr(&self) -> u64 {
151            self.owner_addr
152        }
153        pub(crate) fn key_addr(&self) -> u64 {
154            self.key_addr
155        }
156        pub(crate) fn lamports_addr(&self) -> u64 {
157            self.lamports_addr.wrapping_add(Self::LAMPORTS_DATA_OFFSET)
158        }
159        pub(crate) fn data_addr(&self) -> u64 {
160            self.data_addr.wrapping_add(Self::DATA_DATA_OFFSET)
161        }
162        pub(crate) fn data_len_addr(&self) -> u64 {
163            self.data_addr.wrapping_add(Self::DATA_LEN_OFFSET)
164        }
165    }
166
167    const _FOR_NOW_THESE_ARE_THE_SAME_BUT_IF_ACCOUNT_INFO_CHANGES_SDK_HAS_TO_FIX_IT: () = const {
168        use {
169            solana_account_info::AccountInfo as SdkAccountInfo,
170            std::mem::{align_of, offset_of, size_of},
171        };
172        assert!(offset_of!(AccountInfo, key_addr) == offset_of!(SdkAccountInfo, key));
173        assert!(offset_of!(AccountInfo, lamports_addr) == offset_of!(SdkAccountInfo, lamports));
174        assert!(offset_of!(AccountInfo, data_addr) == offset_of!(SdkAccountInfo, data));
175        assert!(offset_of!(AccountInfo, owner_addr) == offset_of!(SdkAccountInfo, owner));
176        assert!(offset_of!(AccountInfo, _is_signer) == offset_of!(SdkAccountInfo, is_signer));
177        assert!(offset_of!(AccountInfo, _is_writable) == offset_of!(SdkAccountInfo, is_writable));
178        assert!(offset_of!(AccountInfo, _executable) == offset_of!(SdkAccountInfo, executable));
179        assert!(size_of::<AccountInfo>() == size_of::<SdkAccountInfo>());
180        assert!(align_of::<SdkAccountInfo>() >= align_of::<AccountInfo>());
181    };
182}
183
184/// Maximum number of account info structs that can be used in a single CPI invocation
185const MAX_CPI_ACCOUNT_INFOS: usize = 255;
186
187/// Check that an account info pointer field points to the expected address
188fn check_account_info_pointer(
189    invoke_context: &InvokeContext,
190    vm_addr: u64,
191    expected_vm_addr: u64,
192    field: &str,
193) -> Result<(), Error> {
194    if vm_addr != expected_vm_addr {
195        ic_msg!(
196            invoke_context,
197            "Invalid account info pointer `{}': {:#x} != {:#x}",
198            field,
199            vm_addr,
200            expected_vm_addr
201        );
202        return Err(Box::new(CpiError::InvalidPointer));
203    }
204    Ok(())
205}
206
207/// Check that an instruction's account and data lengths are within limits
208fn check_instruction_size(num_accounts: usize, data_len: usize) -> Result<(), Error> {
209    if num_accounts > MAX_ACCOUNTS_PER_INSTRUCTION {
210        return Err(Box::new(CpiError::MaxInstructionAccountsExceeded {
211            num_accounts: num_accounts as u64,
212            max_accounts: MAX_ACCOUNTS_PER_INSTRUCTION as u64,
213        }));
214    }
215    if data_len > MAX_INSTRUCTION_DATA_LEN {
216        return Err(Box::new(CpiError::MaxInstructionDataLenExceeded {
217            data_len: data_len as u64,
218            max_data_len: MAX_INSTRUCTION_DATA_LEN as u64,
219        }));
220    }
221    Ok(())
222}
223
224/// Check that the number of account infos is within the CPI limit
225fn check_account_infos(num_account_infos: usize) -> Result<(), Error> {
226    let num_account_infos = num_account_infos as u64;
227    let max_account_infos = MAX_CPI_ACCOUNT_INFOS as u64;
228    if num_account_infos > max_account_infos {
229        return Err(Box::new(CpiError::MaxInstructionAccountInfosExceeded {
230            num_account_infos,
231            max_account_infos,
232        }));
233    }
234    Ok(())
235}
236
237/// Check whether a program is authorized for CPI
238fn check_authorized_program(
239    program_id: &Pubkey,
240    instruction_data: &[u8],
241    invoke_context: &InvokeContext,
242) -> Result<(), Error> {
243    if native_loader::check_id(program_id)
244        || bpf_loader::check_id(program_id)
245        || bpf_loader_deprecated::check_id(program_id)
246        || (solana_sdk_ids::bpf_loader_upgradeable::check_id(program_id)
247            && !(bpf_loader_upgradeable::is_upgrade_instruction(instruction_data)
248                || bpf_loader_upgradeable::is_set_authority_instruction(instruction_data)
249                || (invoke_context
250                    .get_feature_set()
251                    .enable_bpf_loader_set_authority_checked_ix
252                    && bpf_loader_upgradeable::is_set_authority_checked_instruction(
253                        instruction_data,
254                    ))
255                || bpf_loader_upgradeable::is_close_instruction(instruction_data)))
256        || invoke_context.is_precompile(program_id)
257    {
258        return Err(Box::new(CpiError::ProgramNotSupported(*program_id)));
259    }
260    Ok(())
261}
262
263/// Host side representation of AccountInfo or SolAccountInfo passed to the CPI syscall.
264///
265/// At the start of a CPI, this can be different from the data stored in the
266/// corresponding BorrowedAccount, and needs to be synched.
267#[derive(Debug)]
268pub struct CallerAccount<'a> {
269    pub lamports: &'a mut u64,
270    pub owner: &'a mut Pubkey,
271    // The original data length of the account at the start of the current
272    // instruction. We use this to determine whether an account was shrunk or
273    // grown before or after CPI, and to derive the vm address of the realloc
274    // region.
275    pub original_data_len: usize,
276    // This points to the data section for this account, as serialized and
277    // mapped inside the vm (see serialize_parameters() in
278    // BpfExecutor::execute).
279    //
280    // This is only set when account_data_direct_mapping is off.
281    pub serialized_data: &'a mut [u8],
282    // Given the corresponding input AccountInfo::data, vm_data_addr points to
283    // the pointer field and ref_to_len_in_vm points to the length field.
284    pub vm_data_addr: u64,
285    pub ref_to_len_in_vm: &'a mut u64,
286}
287
288impl<'a> CallerAccount<'a> {
289    /// Returns the length of the addres space reserved depending on the ABI version
290    pub fn address_space_reserved_for_account(&self, abi: ABI) -> usize {
291        self.original_data_len
292            .saturating_add(abi.account_realloc_padding())
293    }
294
295    /// # Safety
296    ///
297    /// * The caller must ensure that this function does not violate mutable reference uniqueness
298    ///   constraints;
299    /// * The caller must ensure that the lifetime of the returned slice does not outlive the
300    ///   backing data;
301    /// * If `virtual_address_space_adjustments` is enabled and
302    ///   `account_data_direct_mapping` is disabled, the caller must ensure that the full
303    ///   `[vm_addr, vm_addr + len)` range is valid for the account.
304    pub unsafe fn get_serialized_data(
305        memory_mapping: &solana_sbpf::memory_region::MemoryMapping,
306        abi: ABI,
307        vm_addr: u64,
308        original_data_len: usize,
309        len: usize,
310        virtual_address_space_adjustments: bool,
311        account_data_direct_mapping: bool,
312    ) -> Result<&'a mut [u8], Error> {
313        use crate::memory::translate_slice_mut_for_cpi;
314
315        let address_space_reserved_for_account =
316            original_data_len.saturating_add(abi.account_realloc_padding());
317        if len > address_space_reserved_for_account {
318            return Err(InstructionError::InvalidRealloc.into());
319        }
320        if virtual_address_space_adjustments && account_data_direct_mapping {
321            Ok(&mut [])
322        } else if virtual_address_space_adjustments {
323            // Workaround the memory permissions (as these are from the PoV of being inside the VM)
324            unsafe {
325                // SAFETY: Invariants for constructing a mutable reference delegated to the caller.
326                let serialization_ptr: &'a mut [u8] = translate_slice_mut_for_cpi::<u8>(
327                    memory_mapping,
328                    solana_sbpf::ebpf::MM_INPUT_START,
329                    1,
330                    ABI::V0, // Don't care since it is byte aligned
331                )?;
332                Ok(std::slice::from_raw_parts_mut(
333                    serialization_ptr
334                        .as_mut_ptr()
335                        .add(vm_addr.saturating_sub(solana_sbpf::ebpf::MM_INPUT_START) as usize),
336                    len,
337                ))
338            }
339        } else {
340            unsafe {
341                // SAFETY: Invariants for constructing a mutable reference delegated to the caller.
342                translate_slice_mut_for_cpi::<u8>(
343                    memory_mapping,
344                    vm_addr,
345                    len as u64,
346                    ABI::V0, // Don't care since it is byte aligned
347                )
348            }
349        }
350    }
351
352    // Create a CallerAccount given an AccountInfo.
353    pub fn from_account_info(
354        invoke_context: &InvokeContext,
355        memory_mapping: &MemoryMapping,
356        abi: ABI,
357        _vm_addr: u64,
358        account_info: &stable::AccountInfo,
359        account_metadata: &crate::memory_context::SerializedAccountMetadata,
360    ) -> Result<CallerAccount<'a>, Error> {
361        use crate::memory::{translate_type, translate_type_mut_for_cpi};
362
363        let virtual_address_space_adjustments = invoke_context
364            .get_feature_set()
365            .virtual_address_space_adjustments;
366        let account_data_direct_mapping =
367            invoke_context.get_feature_set().account_data_direct_mapping;
368
369        check_account_info_pointer(
370            invoke_context,
371            account_info.key_addr(),
372            account_metadata.vm_key_addr,
373            "key",
374        )?;
375        check_account_info_pointer(
376            invoke_context,
377            account_info.owner_addr(),
378            account_metadata.vm_owner_addr,
379            "owner",
380        )?;
381
382        // account_info points to host memory. The addresses used internally are
383        // in vm space so they need to be translated.
384        let lamports = {
385            // Double dereference lamports out
386            let ptr = translate_type::<u64>(memory_mapping, account_info.lamports_addr(), abi)?;
387            if account_info.lamports_addr() >= solana_sbpf::ebpf::MM_INPUT_START {
388                return Err(Box::new(CpiError::InvalidPointer));
389            }
390
391            check_account_info_pointer(
392                invoke_context,
393                *ptr,
394                account_metadata.vm_lamports_addr,
395                "lamports",
396            )?;
397
398            translate_type_mut_for_cpi::<u64>(memory_mapping, *ptr, abi)?
399        };
400
401        let owner =
402            translate_type_mut_for_cpi::<Pubkey>(memory_mapping, account_info.owner_addr(), abi)?;
403
404        let (serialized_data, vm_data_addr, ref_to_len_in_vm) = {
405            if account_info.data_addr() >= solana_sbpf::ebpf::MM_INPUT_START {
406                return Err(Box::new(CpiError::InvalidPointer));
407            }
408
409            // Double dereference data pointer out
410            // NOTE: we must obtain an owned copy to VmSlice<u8> right away in order to make
411            // the mutable reference to the length sound.
412            let data_slice =
413                *translate_type::<VmSlice<u8>>(memory_mapping, account_info.data_addr(), abi)?;
414            check_account_info_pointer(
415                invoke_context,
416                data_slice.ptr(),
417                account_metadata.vm_data_addr,
418                "data",
419            )?;
420
421            // In the same vein as the other check_account_info_pointer() checks, we don't lock
422            // this pointer to a specific address but we don't want it to be inside accounts, or
423            // callees might be able to write to the pointed memory.
424            if account_info.data_len_addr() >= solana_sbpf::ebpf::MM_INPUT_START {
425                return Err(Box::new(CpiError::InvalidPointer));
426            }
427            let ref_to_len_in_vm = translate_type_mut_for_cpi::<u64>(
428                memory_mapping,
429                account_info.data_len_addr(),
430                ABI::V0,
431            )?;
432            let serialized_data = unsafe {
433                CallerAccount::get_serialized_data(
434                    memory_mapping,
435                    abi,
436                    data_slice.ptr(),
437                    account_metadata.original_data_len,
438                    *ref_to_len_in_vm as usize,
439                    virtual_address_space_adjustments,
440                    account_data_direct_mapping,
441                )?
442            };
443            (serialized_data, data_slice.ptr(), ref_to_len_in_vm)
444        };
445
446        Ok(CallerAccount {
447            lamports,
448            owner,
449            original_data_len: account_metadata.original_data_len,
450            serialized_data,
451            vm_data_addr,
452            ref_to_len_in_vm,
453        })
454    }
455
456    // Create a CallerAccount given a SolAccountInfo.
457    fn from_sol_account_info(
458        invoke_context: &InvokeContext,
459        memory_mapping: &MemoryMapping,
460        abi: ABI,
461        vm_addr: u64,
462        account_info: &SolAccountInfo,
463        account_metadata: &crate::memory_context::SerializedAccountMetadata,
464    ) -> Result<CallerAccount<'a>, Error> {
465        use crate::memory::translate_type_mut_for_cpi;
466
467        let virtual_address_space_adjustments = invoke_context
468            .get_feature_set()
469            .virtual_address_space_adjustments;
470        let account_data_direct_mapping =
471            invoke_context.get_feature_set().account_data_direct_mapping;
472
473        check_account_info_pointer(
474            invoke_context,
475            account_info.key_addr,
476            account_metadata.vm_key_addr,
477            "key",
478        )?;
479
480        check_account_info_pointer(
481            invoke_context,
482            account_info.owner_addr,
483            account_metadata.vm_owner_addr,
484            "owner",
485        )?;
486
487        check_account_info_pointer(
488            invoke_context,
489            account_info.lamports_addr,
490            account_metadata.vm_lamports_addr,
491            "lamports",
492        )?;
493
494        check_account_info_pointer(
495            invoke_context,
496            account_info.data_addr,
497            account_metadata.vm_data_addr,
498            "data",
499        )?;
500
501        // account_info points to host memory. The addresses used internally are
502        // in vm space so they need to be translated.
503        let lamports =
504            translate_type_mut_for_cpi::<u64>(memory_mapping, account_info.lamports_addr, abi)?;
505        let owner =
506            translate_type_mut_for_cpi::<Pubkey>(memory_mapping, account_info.owner_addr, abi)?;
507
508        // we already have the host addr we want: &mut account_info.data_len.
509        // The account info might be read only in the vm though, so we translate
510        // to ensure we can write. This is tested by programs/sbf/rust/ro_modify
511        // which puts SolAccountInfo in rodata.
512        let vm_len_addr = vm_addr
513            .saturating_add(&account_info.data_len as *const u64 as u64)
514            .saturating_sub(account_info as *const _ as *const u64 as u64);
515        // In the same vein as the other check_account_info_pointer() checks, we don't lock
516        // this pointer to a specific address but we don't want it to be inside accounts, or
517        // callees might be able to write to the pointed memory.
518        if vm_len_addr >= solana_sbpf::ebpf::MM_INPUT_START {
519            return Err(Box::new(CpiError::InvalidPointer));
520        }
521        let ref_to_len_in_vm =
522            translate_type_mut_for_cpi::<u64>(memory_mapping, vm_len_addr, ABI::V0)?;
523        let serialized_data = unsafe {
524            CallerAccount::get_serialized_data(
525                memory_mapping,
526                abi,
527                account_info.data_addr,
528                account_metadata.original_data_len,
529                *ref_to_len_in_vm as usize,
530                virtual_address_space_adjustments,
531                account_data_direct_mapping,
532            )?
533        };
534
535        Ok(CallerAccount {
536            lamports,
537            owner,
538            original_data_len: account_metadata.original_data_len,
539            serialized_data,
540            vm_data_addr: account_info.data_addr,
541            ref_to_len_in_vm,
542        })
543    }
544
545    // Create a `CallerAccount` given a `SolAccountMetaV2`.
546    fn from_account_meta_v2(
547        invoke_context: &InvokeContext,
548        memory_mapping: &MemoryMapping,
549        abi: ABI,
550        _vm_addr: u64,
551        account_meta: &SolAccountMetaV2,
552        account_metadata: &crate::memory_context::SerializedAccountMetadata,
553    ) -> Result<CallerAccount<'a>, Error> {
554        use crate::memory::translate_type_mut_for_cpi;
555
556        let virtual_address_space_adjustments = invoke_context
557            .get_feature_set()
558            .virtual_address_space_adjustments;
559        let account_data_direct_mapping =
560            invoke_context.get_feature_set().account_data_direct_mapping;
561
562        let accounts_metadata = &invoke_context
563            .memory_contexts
564            .memory_context_abi_v1()
565            .unwrap()
566            .accounts_metadata;
567        let account = accounts_metadata
568            .get(account_meta.account_index as usize)
569            .ok_or(InstructionError::MissingAccount)?;
570
571        check_account_info_pointer(
572            invoke_context,
573            account.vm_addr,
574            account_metadata.vm_addr,
575            "account",
576        )?;
577
578        let runtime_account =
579            translate_type_mut_for_cpi::<RuntimeAccount>(memory_mapping, account.vm_addr, abi)?;
580        let lamports = &mut runtime_account.lamports;
581        let owner = &mut runtime_account.owner;
582
583        let serialized_data = unsafe {
584            CallerAccount::get_serialized_data(
585                memory_mapping,
586                abi,
587                account.vm_data_addr,
588                account_metadata.original_data_len,
589                runtime_account.data_len as usize,
590                virtual_address_space_adjustments,
591                account_data_direct_mapping,
592            )?
593        };
594
595        Ok(CallerAccount {
596            lamports,
597            owner,
598            original_data_len: account_metadata.original_data_len,
599            serialized_data,
600            vm_data_addr: account.vm_data_addr,
601            ref_to_len_in_vm: &mut runtime_account.data_len,
602        })
603    }
604}
605
606/// Implemented by language specific data structure translators
607pub trait SyscallInvokeSigned {
608    fn translate_instruction(
609        addr: u64,
610        invoke_context: &InvokeContext,
611    ) -> Result<Instruction, Error>;
612    fn translate_accounts<'a>(
613        account_infos_addr: u64,
614        account_infos_len: u64,
615        invoke_context: &InvokeContext,
616    ) -> Result<Vec<TranslatedAccount<'a>>, Error>;
617}
618
619pub fn translate_instruction_rust(
620    addr: u64,
621    invoke_context: &InvokeContext,
622) -> Result<Instruction, Error> {
623    let abi = invoke_context.abi();
624    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
625    let ix = translate_type::<StableInstruction>(memory_mapping, addr, abi)?;
626    let account_metas = translate_slice::<mem::MaybeUninit<AccountMeta>>(
627        memory_mapping,
628        ix.accounts.as_vaddr(),
629        ix.accounts.len(),
630        abi,
631    )?;
632    let data = translate_slice::<u8>(memory_mapping, ix.data.as_vaddr(), ix.data.len(), abi)?;
633
634    check_instruction_size(account_metas.len(), data.len())?;
635
636    let mut total_cu_translation_cost: u64 = (data.len() as u64)
637        .checked_div(invoke_context.get_execution_cost().cpi_bytes_per_unit)
638        .unwrap_or(u64::MAX);
639
640    // Each account meta is 34 bytes (32 for pubkey, 1 for is_signer, 1 for is_writable)
641    let account_meta_translation_cost =
642        (account_metas.len().saturating_mul(size_of::<AccountMeta>()) as u64)
643            .checked_div(invoke_context.get_execution_cost().cpi_bytes_per_unit)
644            .unwrap_or(u64::MAX);
645
646    total_cu_translation_cost =
647        total_cu_translation_cost.saturating_add(account_meta_translation_cost);
648
649    invoke_context.consume_checked(total_cu_translation_cost)?;
650
651    let mut accounts = Vec::with_capacity(account_metas.len());
652    for account_meta in account_metas {
653        // Before using `account_meta` directly, verify that `is_signer` and `is_writable`
654        // contain valid boolean values to prevent UB.
655        let account_meta = unsafe {
656            let ptr = account_meta.as_ptr();
657            if (&raw const (*ptr).is_signer).cast::<u8>().read_volatile() > 1
658                || (&raw const (*ptr).is_writable).cast::<u8>().read_volatile() > 1
659            {
660                return Err(Box::new(InstructionError::InvalidArgument));
661            }
662            // SAFETY: VM memory is initialized, and we have validated that the boolean fields
663            // contain valid data.
664            account_meta.assume_init_ref()
665        };
666
667        accounts.push(account_meta.clone());
668    }
669
670    Ok(Instruction {
671        accounts,
672        data: data.to_vec(),
673        program_id: ix.program_id,
674    })
675}
676
677pub fn translate_accounts_rust<'a>(
678    account_infos_addr: u64,
679    account_infos_len: u64,
680    invoke_context: &InvokeContext,
681) -> Result<Vec<TranslatedAccount<'a>>, Error> {
682    let abi = invoke_context.abi();
683    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
684    translate_account_infos(
685        account_infos_addr,
686        account_infos_len,
687        |account_info: &stable::AccountInfo| Ok(account_info.key_addr()),
688        invoke_context,
689        memory_mapping,
690        abi,
691        |account_infos, account_info_keys| {
692            translate_accounts_common(
693                &account_info_keys,
694                account_infos,
695                account_infos_addr,
696                invoke_context,
697                memory_mapping,
698                abi,
699                CallerAccount::from_account_info,
700            )
701        },
702    )?
703}
704
705pub fn translate_signers(
706    program_id: &Pubkey,
707    signers_seeds_addr: u64,
708    signers_seeds_len: u64,
709    invoke_context: &InvokeContext,
710) -> Result<Vec<Pubkey>, Error> {
711    let abi = invoke_context.abi();
712    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
713    if signers_seeds_len > 0 {
714        let signers_seeds = translate_slice::<VmSlice<VmSlice<u8>>>(
715            memory_mapping,
716            signers_seeds_addr,
717            signers_seeds_len,
718            abi,
719        )?;
720        if signers_seeds.len() > MAX_SIGNERS {
721            return Err(Box::new(CpiError::TooManySigners));
722        }
723        Ok(signers_seeds
724            .iter()
725            .map(|signer_seeds| {
726                let untranslated_seeds = translate_slice::<VmSlice<u8>>(
727                    memory_mapping,
728                    signer_seeds.ptr(),
729                    signer_seeds.len(),
730                    abi,
731                )?;
732                if untranslated_seeds.len() > MAX_SEEDS {
733                    return Err(Box::new(InstructionError::MaxSeedLengthExceeded) as Error);
734                }
735                let seeds_bytes = untranslated_seeds
736                    .iter()
737                    .map(|untranslated_seed| {
738                        translate_vm_slice(untranslated_seed, memory_mapping, abi)
739                    })
740                    .collect::<Result<Vec<_>, Error>>()?;
741                Pubkey::create_program_address(&seeds_bytes, program_id)
742                    .map_err(|err| Box::new(CpiError::BadSeeds(err)) as Error)
743            })
744            .collect::<Result<Vec<_>, Error>>()?)
745    } else {
746        Ok(vec![])
747    }
748}
749
750// Translate the shared `SolInstruction` layout before resolving specific account metas.
751fn translate_instruction_common<T>(
752    addr: u64,
753    invoke_context: &InvokeContext,
754    translate_account_metas: impl FnOnce(
755        &[mem::MaybeUninit<T>],
756        &MemoryMapping,
757        ABI,
758    ) -> Result<Vec<AccountMeta>, Error>,
759) -> Result<Instruction, Error> {
760    let abi = invoke_context.abi();
761    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
762    let ix_c = translate_type::<SolInstruction>(memory_mapping, addr, abi)?;
763
764    let program_id = translate_type::<Pubkey>(memory_mapping, ix_c.program_id_addr, abi)?;
765    let account_metas = translate_slice::<mem::MaybeUninit<T>>(
766        memory_mapping,
767        ix_c.accounts_addr,
768        ix_c.accounts_len,
769        abi,
770    )?;
771    let data = translate_slice::<u8>(memory_mapping, ix_c.data_addr, ix_c.data_len, abi)?;
772
773    check_instruction_size(ix_c.accounts_len as usize, data.len())?;
774
775    let instruction_data_translation_cost: u64 = (data.len() as u64)
776        .checked_div(invoke_context.get_execution_cost().cpi_bytes_per_unit)
777        .unwrap_or(u64::MAX);
778
779    // Charge for the translated `AccountMeta` (34 bytes) regardless of the input layout
780    // since the translated layout is what will be used for the CPI.
781    let account_meta_translation_cost = (ix_c
782        .accounts_len
783        .saturating_mul(size_of::<AccountMeta>() as u64))
784    .checked_div(invoke_context.get_execution_cost().cpi_bytes_per_unit)
785    .unwrap_or(u64::MAX);
786
787    invoke_context.consume_checked(
788        instruction_data_translation_cost.saturating_add(account_meta_translation_cost),
789    )?;
790
791    let accounts = translate_account_metas(account_metas, memory_mapping, abi)?;
792
793    Ok(Instruction {
794        accounts,
795        data: data.to_vec(),
796        program_id: *program_id,
797    })
798}
799
800pub fn translate_instruction_c(
801    addr: u64,
802    invoke_context: &InvokeContext,
803) -> Result<Instruction, Error> {
804    translate_instruction_common::<SolAccountMeta>(
805        addr,
806        invoke_context,
807        |account_metas, memory_mapping, abi| {
808            let mut accounts = Vec::with_capacity(account_metas.len());
809            for account_meta in account_metas {
810                // Before using `account_meta` directly, verify that `is_signer` and `is_writable`
811                // contain valid boolean values to prevent UB.
812                let account_meta = unsafe {
813                    let ptr = account_meta.as_ptr();
814                    if (&raw const (*ptr).is_signer).cast::<u8>().read_volatile() > 1
815                        || (&raw const (*ptr).is_writable).cast::<u8>().read_volatile() > 1
816                    {
817                        return Err(Box::new(InstructionError::InvalidArgument));
818                    }
819                    // SAFETY: VM memory is initialized, and we have validated that the boolean fields
820                    // contain valid data.
821                    account_meta.assume_init_ref()
822                };
823                let pubkey =
824                    translate_type::<Pubkey>(memory_mapping, account_meta.pubkey_addr, abi)?;
825                accounts.push(AccountMeta {
826                    pubkey: *pubkey,
827                    is_signer: account_meta.is_signer,
828                    is_writable: account_meta.is_writable,
829                });
830            }
831            Ok(accounts)
832        },
833    )
834}
835
836pub fn translate_accounts_c<'a>(
837    account_infos_addr: u64,
838    account_infos_len: u64,
839    invoke_context: &InvokeContext,
840) -> Result<Vec<TranslatedAccount<'a>>, Error> {
841    let abi = invoke_context.abi();
842    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
843    translate_account_infos(
844        account_infos_addr,
845        account_infos_len,
846        |account_info: &SolAccountInfo| Ok(account_info.key_addr),
847        invoke_context,
848        memory_mapping,
849        abi,
850        |account_infos, account_info_keys| {
851            translate_accounts_common(
852                &account_info_keys,
853                account_infos,
854                account_infos_addr,
855                invoke_context,
856                memory_mapping,
857                abi,
858                CallerAccount::from_sol_account_info,
859            )
860        },
861    )?
862}
863
864pub fn translate_accounts_v2<'a>(
865    account_metas_addr: u64,
866    account_metas_len: u64,
867    invoke_context: &InvokeContext,
868) -> Result<Vec<TranslatedAccount<'a>>, Error> {
869    let abi = invoke_context.abi();
870    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
871    let accounts_metadata = &invoke_context
872        .memory_contexts
873        .memory_context_abi_v1()
874        .unwrap()
875        .accounts_metadata;
876
877    translate_account_infos(
878        account_metas_addr,
879        account_metas_len,
880        |account_meta: &SolAccountMetaV2| {
881            Ok(accounts_metadata
882                .get(account_meta.account_index as usize)
883                .ok_or(InstructionError::MissingAccount)?
884                .vm_key_addr)
885        },
886        invoke_context,
887        memory_mapping,
888        abi,
889        |account_metas, account_meta_keys| {
890            translate_accounts_common(
891                &account_meta_keys,
892                account_metas,
893                account_metas_addr,
894                invoke_context,
895                memory_mapping,
896                abi,
897                CallerAccount::from_account_meta_v2,
898            )
899        },
900    )?
901}
902
903pub fn translate_instruction_v2(
904    addr: u64,
905    invoke_context: &InvokeContext,
906) -> Result<Instruction, Error> {
907    translate_instruction_common::<SolAccountMetaV2>(
908        addr,
909        invoke_context,
910        // ABI is unused here because this syscall is only availabe to ABIv1 programs.
911        |account_metas, _memory_mapping, _abi| {
912            let instruction_context = invoke_context
913                .transaction_context
914                .get_current_instruction_context()?;
915
916            let mut accounts = Vec::with_capacity(account_metas.len());
917            for account_meta in account_metas {
918                // Before using `account_meta` directly, verify that `is_signer` and `is_writable`
919                // contain valid boolean values to prevent UB.
920                let account_meta = unsafe {
921                    let ptr = account_meta.as_ptr();
922                    if (&raw const (*ptr).is_signer).cast::<u8>().read_volatile() > 1
923                        || (&raw const (*ptr).is_writable).cast::<u8>().read_volatile() > 1
924                    {
925                        return Err(Box::new(InstructionError::InvalidArgument));
926                    }
927                    // SAFETY: VM memory is initialized, and we have validated that the boolean fields
928                    // contain valid data.
929                    account_meta.assume_init_ref()
930                };
931
932                let instruction_account = instruction_context
933                    .try_borrow_instruction_account(account_meta.account_index)?;
934
935                accounts.push(AccountMeta {
936                    pubkey: *invoke_context
937                        .transaction_context
938                        .get_key_of_account_at_index(
939                            instruction_account.get_index_in_transaction(),
940                        )?,
941                    is_signer: account_meta.is_signer(),
942                    is_writable: account_meta.is_writable(),
943                });
944            }
945            Ok(accounts)
946        },
947    )
948}
949
950/// Call process instruction, common to both Rust and C
951pub fn cpi_common<S: SyscallInvokeSigned>(
952    invoke_context: &mut InvokeContext,
953    instruction_addr: u64,
954    account_infos_addr: u64,
955    account_infos_len: u64,
956    signers_seeds_addr: u64,
957    signers_seeds_len: u64,
958) -> Result<u64, Error> {
959    // CPI entry.
960    //
961    // Translate the inputs to the syscall and synchronize the caller's account
962    // changes so the callee can see them.
963    let amount = invoke_context.get_execution_cost().invoke_units;
964    invoke_context.consume_checked(amount)?;
965    let virtual_address_space_adjustments = invoke_context
966        .get_feature_set()
967        .virtual_address_space_adjustments;
968    let account_data_direct_mapping = invoke_context.get_feature_set().account_data_direct_mapping;
969    let abi = invoke_context.abi();
970
971    let instruction = S::translate_instruction(instruction_addr, invoke_context)?;
972    let instruction_context = invoke_context
973        .transaction_context
974        .get_current_instruction_context()?;
975    let caller_program_id = instruction_context.get_program_key()?;
976    let signers = translate_signers(
977        caller_program_id,
978        signers_seeds_addr,
979        signers_seeds_len,
980        invoke_context,
981    )?;
982    check_authorized_program(&instruction.program_id, &instruction.data, invoke_context)?;
983    invoke_context.build_instruction_frame(instruction)?;
984    invoke_context.verify_instruction_accounts(&signers)?;
985
986    let mut accounts =
987        S::translate_accounts(account_infos_addr, account_infos_len, invoke_context)?;
988
989    // before initiating CPI, the caller may have modified the
990    // account (caller_account). We need to update the corresponding
991    // BorrowedAccount (callee_account) so the callee can see the
992    // changes.
993    let transaction_context = &invoke_context.transaction_context;
994    let instruction_context = transaction_context.get_current_instruction_context()?;
995    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
996    for translated_account in accounts.iter_mut() {
997        let callee_account = instruction_context
998            .try_borrow_instruction_account(translated_account.index_in_caller)?;
999        let update_caller = update_callee_account(
1000            memory_mapping,
1001            abi,
1002            &translated_account.caller_account,
1003            callee_account,
1004            virtual_address_space_adjustments,
1005            account_data_direct_mapping,
1006        )?;
1007        translated_account.update_caller_account_region =
1008            translated_account.update_caller_account_info || update_caller;
1009    }
1010
1011    // Process the callee instruction
1012    let mut compute_units_consumed = 0;
1013    invoke_context
1014        .process_instruction(&mut compute_units_consumed, &mut ExecuteTimings::default())?;
1015
1016    // re-bind to please the borrow checker
1017    let transaction_context = &invoke_context.transaction_context;
1018    let instruction_context = transaction_context.get_current_instruction_context()?;
1019
1020    // CPI exit.
1021    //
1022    // Synchronize the callee's account changes so the caller can see them.
1023    for translated_account in accounts.iter_mut() {
1024        let mut callee_account = instruction_context
1025            .try_borrow_instruction_account(translated_account.index_in_caller)?;
1026        if translated_account.update_caller_account_info {
1027            update_caller_account(
1028                invoke_context,
1029                abi,
1030                &mut translated_account.caller_account,
1031                &mut callee_account,
1032                virtual_address_space_adjustments,
1033                account_data_direct_mapping,
1034            )?;
1035        }
1036    }
1037
1038    if virtual_address_space_adjustments {
1039        let memory_mapping = invoke_context.memory_contexts.memory_mapping_mut()?;
1040        for translated_account in accounts.iter() {
1041            let mut callee_account = instruction_context
1042                .try_borrow_instruction_account(translated_account.index_in_caller)?;
1043            if translated_account.update_caller_account_region {
1044                unsafe {
1045                    // SAFETY: lifetime is valid by construction: we're resetting the caller memory
1046                    // region back to the account that was here before the CPI call, meaning that
1047                    // the memory region was guaranteed to be live for sufficient duration upon
1048                    // call of this function.
1049                    update_caller_account_region(
1050                        memory_mapping,
1051                        abi,
1052                        &translated_account.caller_account,
1053                        &mut callee_account,
1054                        account_data_direct_mapping,
1055                    )?;
1056                }
1057            }
1058        }
1059    }
1060
1061    Ok(SUCCESS)
1062}
1063
1064/// Account data and metadata that has been translated from caller space.
1065pub struct TranslatedAccount<'a> {
1066    pub index_in_caller: IndexOfAccount,
1067    pub caller_account: CallerAccount<'a>,
1068    pub update_caller_account_region: bool,
1069    pub update_caller_account_info: bool,
1070}
1071
1072fn translate_account_infos<T, R>(
1073    account_infos_addr: u64,
1074    account_infos_len: u64,
1075    key_addr: impl Fn(&T) -> Result<u64, Error>,
1076    invoke_context: &InvokeContext,
1077    memory_mapping: &MemoryMapping,
1078    abi: ABI,
1079    cb: impl FnOnce(&[T], Vec<&Pubkey>) -> R,
1080) -> Result<R, Error> {
1081    // In the same vein as the other check_account_info_pointer() checks, we don't lock
1082    // this pointer to a specific address but we don't want it to be inside accounts, or
1083    // callees might be able to write to the pointed memory.
1084    if account_infos_addr
1085        .saturating_add(account_infos_len.saturating_mul(std::mem::size_of::<T>() as u64))
1086        >= ebpf::MM_INPUT_START
1087    {
1088        return Err(CpiError::InvalidPointer.into());
1089    }
1090
1091    let account_infos =
1092        translate_slice::<T>(memory_mapping, account_infos_addr, account_infos_len, abi)?;
1093    check_account_infos(account_infos.len())?;
1094
1095    let account_infos_bytes = account_infos.len().saturating_mul(ACCOUNT_INFO_BYTE_SIZE);
1096
1097    let amount = (account_infos_bytes as u64)
1098        .checked_div(invoke_context.get_execution_cost().cpi_bytes_per_unit)
1099        .unwrap_or(u64::MAX);
1100    invoke_context.consume_checked(amount)?;
1101
1102    let mut account_info_keys = Vec::with_capacity(account_infos_len as usize);
1103    #[expect(clippy::needless_range_loop)]
1104    for account_index in 0..account_infos_len as usize {
1105        #[expect(clippy::indexing_slicing)]
1106        let account_info = &account_infos[account_index];
1107        account_info_keys.push(translate_type::<Pubkey>(
1108            memory_mapping,
1109            key_addr(account_info)?,
1110            abi,
1111        )?);
1112    }
1113    Ok(cb(account_infos, account_info_keys))
1114}
1115
1116// Finish translating accounts and build TranslatedAccount from CallerAccount.
1117fn translate_accounts_common<'a, T, F>(
1118    account_info_keys: &[&Pubkey],
1119    account_infos: &[T],
1120    account_infos_addr: u64,
1121    invoke_context: &InvokeContext,
1122    memory_mapping: &MemoryMapping,
1123    abi: ABI,
1124    do_translate: F,
1125) -> Result<Vec<TranslatedAccount<'a>>, Error>
1126where
1127    F: Fn(
1128        &InvokeContext,
1129        &MemoryMapping,
1130        ABI,
1131        u64,
1132        &T,
1133        &SerializedAccountMetadata,
1134    ) -> Result<CallerAccount<'a>, Error>,
1135{
1136    let transaction_context = &invoke_context.transaction_context;
1137    let next_instruction_context = transaction_context.get_next_instruction_context()?;
1138    let next_instruction_accounts = next_instruction_context.instruction_accounts();
1139    let instruction_context = transaction_context.get_current_instruction_context()?;
1140    let mut accounts = Vec::with_capacity(next_instruction_accounts.len());
1141
1142    // unwrapping here is fine: we're in a syscall and the method below fails
1143    // only outside syscalls
1144    let accounts_metadata = &invoke_context
1145        .memory_contexts
1146        .memory_context_abi_v1()
1147        .unwrap()
1148        .accounts_metadata;
1149
1150    for (instruction_account_index, instruction_account) in
1151        next_instruction_accounts.iter().enumerate()
1152    {
1153        if next_instruction_context
1154            .is_instruction_account_duplicate(instruction_account_index as IndexOfAccount)?
1155            .is_some()
1156        {
1157            continue; // Skip duplicate account
1158        }
1159
1160        let index_in_caller = instruction_context
1161            .get_index_of_account_in_instruction(instruction_account.index_in_transaction)?;
1162        let callee_account = instruction_context.try_borrow_instruction_account(index_in_caller)?;
1163        let account_key = invoke_context
1164            .transaction_context
1165            .get_key_of_account_at_index(instruction_account.index_in_transaction)?;
1166
1167        #[expect(deprecated)]
1168        if callee_account.is_executable() {
1169            // Use the known account
1170            let amount = (callee_account.get_data().len() as u64)
1171                .checked_div(invoke_context.get_execution_cost().cpi_bytes_per_unit)
1172                .unwrap_or(u64::MAX);
1173            invoke_context.consume_checked(amount)?;
1174        } else if let Some(caller_account_index) =
1175            account_info_keys.iter().position(|key| *key == account_key)
1176        {
1177            let serialized_metadata =
1178                accounts_metadata
1179                    .get(index_in_caller as usize)
1180                    .ok_or_else(|| {
1181                        ic_msg!(
1182                            invoke_context,
1183                            "Internal error: index mismatch for account {}",
1184                            account_key
1185                        );
1186                        Box::new(InstructionError::MissingAccount) as Error
1187                    })?;
1188
1189            // build the CallerAccount corresponding to this account.
1190            if caller_account_index >= account_infos.len() {
1191                return Err(Box::new(CpiError::InvalidLength));
1192            }
1193            #[expect(clippy::indexing_slicing)]
1194            let caller_account =
1195                do_translate(
1196                    invoke_context,
1197                    memory_mapping,
1198                    abi,
1199                    account_infos_addr.saturating_add(
1200                        caller_account_index.saturating_mul(mem::size_of::<T>()) as u64,
1201                    ),
1202                    &account_infos[caller_account_index],
1203                    serialized_metadata,
1204                )?;
1205
1206            let amount = (*caller_account.ref_to_len_in_vm)
1207                .checked_div(invoke_context.get_execution_cost().cpi_bytes_per_unit)
1208                .unwrap_or(u64::MAX);
1209            invoke_context.consume_checked(amount)?;
1210
1211            accounts.push(TranslatedAccount {
1212                index_in_caller,
1213                caller_account,
1214                update_caller_account_region: true, // overwritten in `cpi_common` via `update_callee_acccount()`
1215                update_caller_account_info: instruction_account.is_writable(),
1216            });
1217        } else {
1218            ic_msg!(
1219                invoke_context,
1220                "Instruction references an unknown account {}",
1221                account_key
1222            );
1223            return Err(Box::new(InstructionError::MissingAccount));
1224        }
1225    }
1226
1227    Ok(accounts)
1228}
1229
1230// Update the given account before executing CPI.
1231//
1232// caller_account and callee_account describe the same account. At CPI entry
1233// caller_account might include changes the caller has made to the account
1234// before executing CPI.
1235//
1236// This method updates callee_account so the CPI callee can see the caller's
1237// changes.
1238//
1239// When true is returned, the caller account must be updated after CPI. This
1240// is only set for virtual_address_space_adjustments when the pointer may have changed.
1241fn update_callee_account(
1242    memory_mapping: &MemoryMapping,
1243    abi: ABI,
1244    caller_account: &CallerAccount,
1245    mut callee_account: BorrowedInstructionAccount<'_, '_>,
1246    virtual_address_space_adjustments: bool,
1247    account_data_direct_mapping: bool,
1248) -> Result<bool, Error> {
1249    let mut must_update_caller = false;
1250
1251    if callee_account.get_lamports() != *caller_account.lamports {
1252        callee_account.set_lamports(*caller_account.lamports)?;
1253    }
1254
1255    if virtual_address_space_adjustments {
1256        let prev_len = callee_account.get_data().len();
1257        let post_len = *caller_account.ref_to_len_in_vm as usize;
1258        if prev_len != post_len {
1259            if !account_data_direct_mapping && post_len < prev_len {
1260                // If the account has been shrunk, we're going to zero the unused memory
1261                // *that was previously used*.
1262                let serialized_data = unsafe {
1263                    CallerAccount::get_serialized_data(
1264                        memory_mapping,
1265                        abi,
1266                        caller_account.vm_data_addr,
1267                        caller_account.original_data_len,
1268                        prev_len,
1269                        virtual_address_space_adjustments,
1270                        account_data_direct_mapping,
1271                    )?
1272                };
1273                serialized_data
1274                    .get_mut(post_len..)
1275                    .ok_or_else(|| Box::new(InstructionError::AccountDataTooSmall) as Error)?
1276                    .fill(0);
1277            }
1278            callee_account.set_data_length(post_len)?;
1279            // pointer to data may have changed, so caller must be updated
1280            must_update_caller = true;
1281        }
1282        if !account_data_direct_mapping && callee_account.can_data_be_changed().is_ok() {
1283            callee_account.set_data_from_slice(caller_account.serialized_data)?;
1284        }
1285    } else {
1286        // The redundant check helps to avoid the expensive data comparison if we can
1287        match callee_account.can_data_be_resized(caller_account.serialized_data.len()) {
1288            Ok(()) => callee_account.set_data_from_slice(caller_account.serialized_data)?,
1289            Err(err) if callee_account.get_data() != caller_account.serialized_data => {
1290                return Err(Box::new(err));
1291            }
1292            _ => {}
1293        }
1294    }
1295
1296    // Change the owner at the end so that we are allowed to change the lamports and data before
1297    if callee_account.get_owner() != caller_account.owner {
1298        callee_account.set_owner(caller_account.owner.as_ref())?;
1299        // caller gave ownership and thus write access away, so caller must be updated
1300        must_update_caller = true;
1301    }
1302
1303    Ok(must_update_caller)
1304}
1305
1306/// # Safety
1307///
1308/// The the account data pointed to by `callee_account` must outlive the uses of the
1309/// [`MemoryMapping`].
1310unsafe fn update_caller_account_region(
1311    memory_mapping: &mut MemoryMapping,
1312    abi: ABI,
1313    caller_account: &CallerAccount,
1314    callee_account: &mut BorrowedInstructionAccount<'_, '_>,
1315    account_data_direct_mapping: bool,
1316) -> Result<(), Error> {
1317    let address_space_reserved_for_account = caller_account.address_space_reserved_for_account(abi);
1318
1319    if address_space_reserved_for_account > 0 {
1320        // We can trust vm_data_addr to point to the correct region because we
1321        // enforce that in CallerAccount::from_(sol_)account_info.
1322        let (region_index, region) = memory_mapping
1323            .find_region(caller_account.vm_data_addr)
1324            .ok_or_else(|| Box::new(InstructionError::MissingAccount) as Error)?;
1325        // vm_data_addr must always point to the beginning of the region
1326        let region_start_vm_addr = region.vm_addr_range().start;
1327        debug_assert_eq!(region_start_vm_addr, caller_account.vm_data_addr);
1328        let mut new_region;
1329        if !account_data_direct_mapping {
1330            new_region = region.clone();
1331            modify_memory_region_of_account(callee_account, &mut new_region);
1332        } else {
1333            new_region = create_memory_region_of_account(callee_account, region_start_vm_addr)?;
1334        }
1335        unsafe {
1336            // SAFETY: the lifetime invariants are delegated to the callers of this function. Both
1337            // `modify_memory_region_of_account` and `create_memory_region_of_account` create memory
1338            // regions pointing to valid buffers by the virtue of the region being produced out of
1339            // an intermediate slice, which itself must be wholly valid.
1340            memory_mapping.replace_region(region_index, new_region)?;
1341        }
1342    }
1343
1344    Ok(())
1345}
1346
1347// Update the given account after executing CPI.
1348//
1349// caller_account and callee_account describe to the same account. At CPI exit
1350// callee_account might include changes the callee has made to the account
1351// after executing.
1352//
1353// This method updates caller_account so the CPI caller can see the callee's
1354// changes.
1355fn update_caller_account(
1356    invoke_context: &InvokeContext,
1357    abi: ABI,
1358    caller_account: &mut CallerAccount<'_>,
1359    callee_account: &mut BorrowedInstructionAccount<'_, '_>,
1360    virtual_address_space_adjustments: bool,
1361    account_data_direct_mapping: bool,
1362) -> Result<(), Error> {
1363    *caller_account.lamports = callee_account.get_lamports();
1364    *caller_account.owner = *callee_account.get_owner();
1365
1366    let prev_len = *caller_account.ref_to_len_in_vm as usize;
1367    let post_len = callee_account.get_data().len();
1368    let address_space_reserved_for_account = caller_account.address_space_reserved_for_account(abi);
1369
1370    if post_len > address_space_reserved_for_account {
1371        let max_increase =
1372            address_space_reserved_for_account.saturating_sub(caller_account.original_data_len);
1373        ic_msg!(
1374            invoke_context,
1375            "Account data size realloc limited to {max_increase} in inner instructions",
1376        );
1377        return Err(Box::new(InstructionError::InvalidRealloc));
1378    }
1379
1380    let memory_mapping = invoke_context.memory_contexts.memory_mapping()?;
1381    if prev_len != post_len {
1382        // when virtual_address_space_adjustments is enabled we don't cache the serialized data in
1383        // caller_account.serialized_data. See CallerAccount::from_account_info.
1384        if !(virtual_address_space_adjustments && account_data_direct_mapping) {
1385            // If the account has been shrunk, we're going to zero the unused memory
1386            // *that was previously used*.
1387            if post_len < prev_len {
1388                caller_account
1389                    .serialized_data
1390                    .get_mut(post_len..)
1391                    .ok_or_else(|| Box::new(InstructionError::AccountDataTooSmall) as Error)?
1392                    .fill(0);
1393            }
1394            // Set the length of caller_account.serialized_data to post_len.
1395            unsafe {
1396                caller_account.serialized_data = CallerAccount::get_serialized_data(
1397                    memory_mapping,
1398                    abi,
1399                    caller_account.vm_data_addr,
1400                    caller_account.original_data_len,
1401                    post_len,
1402                    virtual_address_space_adjustments,
1403                    account_data_direct_mapping,
1404                )?;
1405            }
1406        }
1407        // this is the len field in the AccountInfo::data slice
1408        *caller_account.ref_to_len_in_vm = post_len as u64;
1409
1410        // this is the len field in the serialized parameters
1411        let serialized_len_ptr = translate_type_mut_for_cpi::<u64>(
1412            memory_mapping,
1413            caller_account
1414                .vm_data_addr
1415                .saturating_sub(std::mem::size_of::<u64>() as u64),
1416            abi,
1417        )?;
1418        *serialized_len_ptr = post_len as u64;
1419    }
1420
1421    if !(virtual_address_space_adjustments && account_data_direct_mapping) {
1422        // Propagate changes in the callee up to the caller.
1423        let to_slice = &mut caller_account.serialized_data;
1424        let from_slice = callee_account
1425            .get_data()
1426            .get(0..post_len)
1427            .ok_or(CpiError::InvalidLength)?;
1428        if to_slice.len() != from_slice.len() {
1429            return Err(Box::new(InstructionError::AccountDataTooSmall));
1430        }
1431        to_slice.copy_from_slice(from_slice);
1432    }
1433
1434    Ok(())
1435}
1436
1437#[allow(clippy::indexing_slicing)]
1438#[allow(clippy::arithmetic_side_effects)]
1439#[cfg(test)]
1440mod tests {
1441    use {
1442        super::*,
1443        crate::{
1444            invoke_context::BpfAllocator,
1445            memory::translate_type,
1446            memory_context::{MemoryContext, SerializedAccountMetadata},
1447            with_mock_invoke_context_with_feature_set,
1448        },
1449        solana_account::{Account, AccountSharedData, ReadableAccount},
1450        solana_account_info::AccountInfo,
1451        solana_program_entrypoint::MAX_PERMITTED_DATA_INCREASE,
1452        solana_sbpf::{
1453            ebpf::{MM_INPUT_START, MM_STACK_START},
1454            memory_region::MemoryRegion,
1455            program::SBPFVersion,
1456            vm::Config,
1457        },
1458        solana_sdk_ids::{bpf_loader, system_program},
1459        solana_svm_feature_set::SVMFeatureSet,
1460        solana_transaction_context::{
1461            IndexOfAccount, instruction_accounts::InstructionAccount,
1462            transaction_accounts::KeyedAccountSharedData,
1463        },
1464        std::{
1465            assert_matches,
1466            cell::{Cell, RefCell},
1467            mem, ptr,
1468            rc::Rc,
1469            slice,
1470        },
1471        test_case::{case, test_case},
1472    };
1473
1474    macro_rules! mock_invoke_context {
1475        ($invoke_context:ident,
1476         $transaction_context:ident,
1477         $instruction_data:expr,
1478         $transaction_accounts:expr,
1479         $program_account:expr,
1480         $instruction_accounts:expr) => {
1481            let instruction_data = $instruction_data;
1482            let instruction_accounts = $instruction_accounts
1483                .iter()
1484                .map(|index_in_transaction| {
1485                    InstructionAccount::new(
1486                        *index_in_transaction as IndexOfAccount,
1487                        false,
1488                        $transaction_accounts[*index_in_transaction as usize].2,
1489                    )
1490                })
1491                .collect::<Vec<_>>();
1492            let transaction_accounts = $transaction_accounts
1493                .into_iter()
1494                .map(|a| (a.0, a.1))
1495                .collect::<Vec<KeyedAccountSharedData>>();
1496            let mut feature_set = SVMFeatureSet::all_enabled();
1497            feature_set.virtual_address_space_adjustments = false;
1498            feature_set.account_data_direct_mapping = false;
1499            let feature_set = &feature_set;
1500            with_mock_invoke_context_with_feature_set!(
1501                $invoke_context,
1502                $transaction_context,
1503                feature_set,
1504                transaction_accounts
1505            );
1506            $invoke_context
1507                .transaction_context
1508                .configure_top_level_instruction_for_tests(
1509                    $program_account,
1510                    instruction_accounts,
1511                    instruction_data.to_vec(),
1512                )
1513                .unwrap();
1514            $invoke_context.push().unwrap();
1515        };
1516    }
1517
1518    macro_rules! borrow_instruction_account {
1519        ($borrowed_account:ident, $invoke_context:expr, $index:expr) => {
1520            let instruction_context = $invoke_context
1521                .transaction_context
1522                .get_current_instruction_context()
1523                .unwrap();
1524            let $borrowed_account = instruction_context
1525                .try_borrow_instruction_account($index)
1526                .unwrap();
1527        };
1528    }
1529
1530    fn is_zeroed(data: &[u8]) -> bool {
1531        data.iter().all(|b| *b == 0)
1532    }
1533
1534    struct MockCallerAccount {
1535        lamports: u64,
1536        owner: Pubkey,
1537        vm_addr: u64,
1538        data: Vec<u8>,
1539        len: u64,
1540        regions: Vec<MemoryRegion>,
1541        virtual_address_space_adjustments: bool,
1542    }
1543
1544    impl MockCallerAccount {
1545        fn new(
1546            lamports: u64,
1547            owner: Pubkey,
1548            data: &[u8],
1549            virtual_address_space_adjustments: bool,
1550        ) -> MockCallerAccount {
1551            let vm_addr = MM_INPUT_START;
1552            let mut region_addr = vm_addr;
1553            let region_len = mem::size_of::<u64>()
1554                + if virtual_address_space_adjustments {
1555                    0
1556                } else {
1557                    data.len() + MAX_PERMITTED_DATA_INCREASE
1558                };
1559            let mut d = vec![0; region_len];
1560            let mut regions = vec![];
1561
1562            // always write the [len] part even when virtual_address_space_adjustments
1563            unsafe { ptr::write_unaligned::<u64>(d.as_mut_ptr().cast(), data.len() as u64) };
1564
1565            // write the account data when not virtual_address_space_adjustments
1566            if !virtual_address_space_adjustments {
1567                d[mem::size_of::<u64>()..][..data.len()].copy_from_slice(data);
1568            }
1569
1570            // create a region for [len][data+realloc if !virtual_address_space_adjustments]
1571            regions.push(MemoryRegion::new(&raw mut d[..region_len], vm_addr));
1572            region_addr += region_len as u64;
1573
1574            if virtual_address_space_adjustments {
1575                // create a region for the directly mapped data
1576                regions.push(MemoryRegion::new(&raw const data[..], region_addr));
1577                region_addr += data.len() as u64;
1578
1579                // create a region for the realloc padding
1580                regions.push(MemoryRegion::new(
1581                    &raw mut d[mem::size_of::<u64>()..],
1582                    region_addr,
1583                ));
1584            } else {
1585                // caller_account.serialized_data must have the actual data length
1586                d.truncate(mem::size_of::<u64>() + data.len());
1587            }
1588
1589            MockCallerAccount {
1590                lamports,
1591                owner,
1592                vm_addr,
1593                data: d,
1594                len: data.len() as u64,
1595                regions,
1596                virtual_address_space_adjustments,
1597            }
1598        }
1599
1600        fn data_slice<'a>(&self) -> &'a [u8] {
1601            // lifetime crimes
1602            unsafe {
1603                slice::from_raw_parts(
1604                    self.data[mem::size_of::<u64>()..].as_ptr(),
1605                    self.data.capacity() - mem::size_of::<u64>(),
1606                )
1607            }
1608        }
1609
1610        fn caller_account(&mut self) -> CallerAccount<'_> {
1611            let data = if self.virtual_address_space_adjustments {
1612                &mut []
1613            } else {
1614                &mut self.data[mem::size_of::<u64>()..]
1615            };
1616            CallerAccount {
1617                lamports: &mut self.lamports,
1618                owner: &mut self.owner,
1619                original_data_len: self.len as usize,
1620                serialized_data: data,
1621                vm_data_addr: self.vm_addr + mem::size_of::<u64>() as u64,
1622                ref_to_len_in_vm: &mut self.len,
1623            }
1624        }
1625    }
1626
1627    struct MockAccountInfo<'a> {
1628        key: Pubkey,
1629        is_signer: bool,
1630        is_writable: bool,
1631        lamports: u64,
1632        data: &'a [u8],
1633        owner: Pubkey,
1634        executable: bool,
1635        _unused: u64,
1636    }
1637
1638    impl MockAccountInfo<'_> {
1639        fn new(key: Pubkey, account: &AccountSharedData) -> MockAccountInfo<'_> {
1640            MockAccountInfo {
1641                key,
1642                is_signer: false,
1643                is_writable: false,
1644                lamports: account.lamports(),
1645                data: account.data(),
1646                owner: *account.owner(),
1647                executable: account.executable(),
1648                _unused: account.rent_epoch(),
1649            }
1650        }
1651
1652        fn into_region(self, vm_addr: u64) -> (Vec<u8>, MemoryRegion, SerializedAccountMetadata) {
1653            let size = mem::size_of::<AccountInfo>()
1654                + mem::size_of::<Pubkey>() * 2
1655                + mem::size_of::<RcBox<RefCell<&mut u64>>>()
1656                + mem::size_of::<u64>()
1657                + mem::size_of::<RcBox<RefCell<&mut [u8]>>>()
1658                + self.data.len();
1659            let mut data = vec![0; size];
1660
1661            let vm_addr = vm_addr as usize;
1662            let key_addr = vm_addr + mem::size_of::<AccountInfo>();
1663            let lamports_cell_addr = key_addr + mem::size_of::<Pubkey>();
1664            let lamports_addr = lamports_cell_addr + mem::size_of::<RcBox<RefCell<&mut u64>>>();
1665            let owner_addr = lamports_addr + mem::size_of::<u64>();
1666            let data_cell_addr = owner_addr + mem::size_of::<Pubkey>();
1667            let data_addr = data_cell_addr + mem::size_of::<RcBox<RefCell<&mut [u8]>>>();
1668
1669            #[allow(deprecated)]
1670            #[allow(clippy::used_underscore_binding)]
1671            let info = AccountInfo {
1672                key: unsafe { (key_addr as *const Pubkey).as_ref() }.unwrap(),
1673                is_signer: self.is_signer,
1674                is_writable: self.is_writable,
1675                lamports: unsafe {
1676                    Rc::from_raw((lamports_cell_addr + RcBox::<&mut u64>::VALUE_OFFSET) as *const _)
1677                },
1678                data: unsafe {
1679                    Rc::from_raw((data_cell_addr + RcBox::<&mut [u8]>::VALUE_OFFSET) as *const _)
1680                },
1681                owner: unsafe { (owner_addr as *const Pubkey).as_ref() }.unwrap(),
1682                executable: self.executable,
1683                _unused: self._unused,
1684            };
1685
1686            unsafe {
1687                ptr::write_unaligned(data.as_mut_ptr().cast(), info);
1688                ptr::write_unaligned(
1689                    (data.as_mut_ptr() as usize + key_addr - vm_addr) as *mut _,
1690                    self.key,
1691                );
1692                ptr::write_unaligned(
1693                    (data.as_mut_ptr() as usize + lamports_cell_addr - vm_addr) as *mut _,
1694                    RcBox::new(RefCell::new((lamports_addr as *mut u64).as_mut().unwrap())),
1695                );
1696                ptr::write_unaligned(
1697                    (data.as_mut_ptr() as usize + lamports_addr - vm_addr) as *mut _,
1698                    self.lamports,
1699                );
1700                ptr::write_unaligned(
1701                    (data.as_mut_ptr() as usize + owner_addr - vm_addr) as *mut _,
1702                    self.owner,
1703                );
1704                ptr::write_unaligned(
1705                    (data.as_mut_ptr() as usize + data_cell_addr - vm_addr) as *mut _,
1706                    RcBox::new(RefCell::new(slice::from_raw_parts_mut(
1707                        data_addr as *mut u8,
1708                        self.data.len(),
1709                    ))),
1710                );
1711                data[data_addr - vm_addr..].copy_from_slice(self.data);
1712            }
1713
1714            let region = MemoryRegion::new(&raw mut data[..], vm_addr as u64);
1715            (
1716                data,
1717                region,
1718                SerializedAccountMetadata {
1719                    vm_addr: vm_addr as u64,
1720                    original_data_len: self.data.len(),
1721                    vm_key_addr: key_addr as u64,
1722                    vm_lamports_addr: lamports_addr as u64,
1723                    vm_owner_addr: owner_addr as u64,
1724                    vm_data_addr: data_addr as u64,
1725                },
1726            )
1727        }
1728    }
1729
1730    struct MockAccountMetaV2<'a> {
1731        key: Pubkey,
1732        account: &'a AccountSharedData,
1733    }
1734
1735    impl<'a> MockAccountMetaV2<'a> {
1736        fn new(key: Pubkey, account: &'a AccountSharedData) -> Self {
1737            Self { key, account }
1738        }
1739
1740        fn into_regions(
1741            self,
1742            account_metas_addr: u64,
1743        ) -> (
1744            Vec<u64>,
1745            Vec<SolAccountMetaV2>,
1746            Vec<MemoryRegion>,
1747            SerializedAccountMetadata,
1748        ) {
1749            let original_data_len = self.account.data().len();
1750            let runtime_account_size = mem::size_of::<RuntimeAccount>();
1751            let runtime_memory_size = runtime_account_size + original_data_len;
1752            let mut runtime_memory =
1753                vec![0u64; runtime_memory_size.div_ceil(mem::size_of::<u64>())];
1754            let runtime_account_ptr = runtime_memory.as_mut_ptr().cast::<RuntimeAccount>();
1755            unsafe {
1756                ptr::write(
1757                    runtime_account_ptr,
1758                    RuntimeAccount {
1759                        borrow_state: u8::MAX,
1760                        is_signer: 0,
1761                        is_writable: 1,
1762                        executable: self.account.executable() as u8,
1763                        padding: [0; 4],
1764                        address: self.key,
1765                        owner: *self.account.owner(),
1766                        lamports: self.account.lamports(),
1767                        data_len: original_data_len as u64,
1768                    },
1769                );
1770                ptr::copy_nonoverlapping(
1771                    self.account.data().as_ptr(),
1772                    runtime_account_ptr.cast::<u8>().add(runtime_account_size),
1773                    original_data_len,
1774                );
1775            }
1776
1777            let runtime_account_addr = runtime_account_ptr as u64;
1778            let data_addr = runtime_account_addr + runtime_account_size as u64;
1779            let runtime_memory_slice = unsafe {
1780                slice::from_raw_parts_mut(runtime_account_ptr.cast::<u8>(), runtime_memory_size)
1781            };
1782            let runtime_account_region =
1783                MemoryRegion::new(&raw mut runtime_memory_slice[..], runtime_account_addr);
1784
1785            let mut account_metas = vec![SolAccountMetaV2 {
1786                account_index: 0,
1787                is_writable: 1, // true
1788                is_signer: 0,   // false
1789            }];
1790            let account_metas_size = mem::size_of_val(account_metas.as_slice());
1791            let account_metas_memory = unsafe {
1792                slice::from_raw_parts_mut(
1793                    account_metas.as_mut_ptr().cast::<u8>(),
1794                    account_metas_size,
1795                )
1796            };
1797            let account_metas_region =
1798                MemoryRegion::new(&raw mut account_metas_memory[..], account_metas_addr);
1799
1800            let account_metadata = SerializedAccountMetadata {
1801                vm_addr: runtime_account_addr,
1802                original_data_len,
1803                vm_key_addr: runtime_account_addr + mem::offset_of!(RuntimeAccount, address) as u64,
1804                vm_lamports_addr: runtime_account_addr
1805                    + mem::offset_of!(RuntimeAccount, lamports) as u64,
1806                vm_owner_addr: runtime_account_addr + mem::offset_of!(RuntimeAccount, owner) as u64,
1807                vm_data_addr: data_addr,
1808            };
1809
1810            (
1811                runtime_memory,
1812                account_metas,
1813                vec![account_metas_region, runtime_account_region],
1814                account_metadata,
1815            )
1816        }
1817    }
1818
1819    struct MockInstruction {
1820        program_id: Pubkey,
1821        accounts: Vec<AccountMeta>,
1822        data: Vec<u8>,
1823    }
1824
1825    impl MockInstruction {
1826        fn into_region(self, vm_addr: u64) -> (Vec<u8>, MemoryRegion) {
1827            let accounts_len = mem::size_of::<AccountMeta>() * self.accounts.len();
1828
1829            let size = mem::size_of::<StableInstruction>() + accounts_len + self.data.len();
1830
1831            let mut data = vec![0; size];
1832
1833            let vm_addr = vm_addr as usize;
1834            let accounts_addr = vm_addr + mem::size_of::<StableInstruction>();
1835            let data_addr = accounts_addr + accounts_len;
1836
1837            let ins = Instruction {
1838                program_id: self.program_id,
1839                accounts: unsafe {
1840                    Vec::from_raw_parts(
1841                        accounts_addr as *mut _,
1842                        self.accounts.len(),
1843                        self.accounts.len(),
1844                    )
1845                },
1846                data: unsafe {
1847                    Vec::from_raw_parts(data_addr as *mut _, self.data.len(), self.data.len())
1848                },
1849            };
1850            let ins = StableInstruction::from(ins);
1851
1852            unsafe {
1853                ptr::write_unaligned(data.as_mut_ptr().cast(), ins);
1854                data[accounts_addr - vm_addr..][..accounts_len].copy_from_slice(
1855                    slice::from_raw_parts(self.accounts.as_ptr().cast(), accounts_len),
1856                );
1857                data[data_addr - vm_addr..].copy_from_slice(&self.data);
1858            }
1859
1860            let region = MemoryRegion::new(&raw mut data[..], vm_addr as u64);
1861            (data, region)
1862        }
1863    }
1864
1865    #[repr(C)]
1866    struct RcBox<T> {
1867        strong: Cell<usize>,
1868        weak: Cell<usize>,
1869        value: T,
1870    }
1871
1872    impl<T> RcBox<T> {
1873        const VALUE_OFFSET: usize = mem::size_of::<Cell<usize>>() * 2;
1874        fn new(value: T) -> RcBox<T> {
1875            RcBox {
1876                strong: Cell::new(0),
1877                weak: Cell::new(0),
1878                value,
1879            }
1880        }
1881    }
1882
1883    type TestTransactionAccount = (Pubkey, AccountSharedData, bool);
1884
1885    fn transaction_with_one_writable_instruction_account(
1886        data: Vec<u8>,
1887    ) -> Vec<TestTransactionAccount> {
1888        let program_id = Pubkey::new_unique();
1889        let account = AccountSharedData::from(Account {
1890            lamports: 1,
1891            data,
1892            owner: program_id,
1893            executable: false,
1894            rent_epoch: 100,
1895        });
1896        vec![
1897            (
1898                program_id,
1899                AccountSharedData::from(Account {
1900                    lamports: 0,
1901                    data: vec![],
1902                    owner: bpf_loader::id(),
1903                    executable: true,
1904                    rent_epoch: 0,
1905                }),
1906                false,
1907            ),
1908            (Pubkey::new_unique(), account, true),
1909        ]
1910    }
1911
1912    fn transaction_with_one_readonly_instruction_account(
1913        data: Vec<u8>,
1914    ) -> Vec<TestTransactionAccount> {
1915        let program_id = Pubkey::new_unique();
1916        let account_owner = Pubkey::new_unique();
1917        let account = AccountSharedData::from(Account {
1918            lamports: 1,
1919            data,
1920            owner: account_owner,
1921            executable: false,
1922            rent_epoch: 100,
1923        });
1924        vec![
1925            (
1926                program_id,
1927                AccountSharedData::from(Account {
1928                    lamports: 0,
1929                    data: vec![],
1930                    owner: bpf_loader::id(),
1931                    executable: true,
1932                    rent_epoch: 0,
1933                }),
1934                false,
1935            ),
1936            (Pubkey::new_unique(), account, true),
1937        ]
1938    }
1939
1940    fn mock_signers(signers: &[&[u8]], vm_addr: u64) -> (Vec<u8>, MemoryRegion) {
1941        let vm_addr = vm_addr as usize;
1942
1943        // calculate size
1944        let fat_ptr_size_of_slice = mem::size_of::<&[()]>(); // pointer size + length size
1945        let singers_length = signers.len();
1946        let sum_signers_data_length: usize = signers.iter().map(|s| s.len()).sum();
1947
1948        // init data vec
1949        let total_size = fat_ptr_size_of_slice
1950            + singers_length * fat_ptr_size_of_slice
1951            + sum_signers_data_length;
1952        let mut data = vec![0; total_size];
1953
1954        // data is composed by 3 parts
1955        // A.
1956        // [ singers address, singers length, ...,
1957        // B.                                      |
1958        //                                         signer1 address, signer1 length, signer2 address ...,
1959        //                                         ^ p1 --->
1960        // C.                                                                                           |
1961        //                                                                                              signer1 data, signer2 data, ... ]
1962        //                                                                                              ^ p2 --->
1963
1964        // A.
1965        data[..fat_ptr_size_of_slice / 2]
1966            .clone_from_slice(&(fat_ptr_size_of_slice + vm_addr).to_le_bytes());
1967        data[fat_ptr_size_of_slice / 2..fat_ptr_size_of_slice]
1968            .clone_from_slice(&(singers_length).to_le_bytes());
1969
1970        // B. + C.
1971        let (mut p1, mut p2) = (
1972            fat_ptr_size_of_slice,
1973            fat_ptr_size_of_slice + singers_length * fat_ptr_size_of_slice,
1974        );
1975        for signer in signers.iter() {
1976            let signer_length = signer.len();
1977
1978            // B.
1979            data[p1..p1 + fat_ptr_size_of_slice / 2]
1980                .clone_from_slice(&(p2 + vm_addr).to_le_bytes());
1981            data[p1 + fat_ptr_size_of_slice / 2..p1 + fat_ptr_size_of_slice]
1982                .clone_from_slice(&(signer_length).to_le_bytes());
1983            p1 += fat_ptr_size_of_slice;
1984
1985            // C.
1986            data[p2..p2 + signer_length].clone_from_slice(signer);
1987            p2 += signer_length;
1988        }
1989
1990        let region = MemoryRegion::new(&raw mut data[..], vm_addr as u64);
1991        (data, region)
1992    }
1993
1994    #[test]
1995    fn test_translate_instruction() {
1996        let transaction_accounts =
1997            transaction_with_one_writable_instruction_account(b"foo".to_vec());
1998        mock_invoke_context!(
1999            invoke_context,
2000            transaction_context,
2001            b"instruction data",
2002            transaction_accounts,
2003            0,
2004            &[1]
2005        );
2006
2007        let program_id = Pubkey::new_unique();
2008        let accounts = vec![AccountMeta {
2009            pubkey: Pubkey::new_unique(),
2010            is_signer: true,
2011            is_writable: false,
2012        }];
2013        let data = b"ins data".to_vec();
2014        let vm_addr = MM_INPUT_START;
2015        let (_mem, region) = MockInstruction {
2016            program_id,
2017            accounts: accounts.clone(),
2018            data: data.clone(),
2019        }
2020        .into_region(vm_addr);
2021
2022        let config = Config {
2023            aligned_memory_mapping: false,
2024            ..Config::default()
2025        };
2026        let memory_mapping =
2027            unsafe { MemoryMapping::new(vec![region], &config, SBPFVersion::V3).unwrap() };
2028        invoke_context
2029            .memory_contexts
2030            .mock_set_mapping_abi_v1(memory_mapping);
2031
2032        let ins = translate_instruction_rust(vm_addr, &invoke_context).unwrap();
2033        assert_eq!(ins.program_id, program_id);
2034        assert_eq!(ins.accounts, accounts);
2035        assert_eq!(ins.data, data);
2036    }
2037
2038    #[test]
2039    fn test_translate_signers() {
2040        let transaction_accounts =
2041            transaction_with_one_writable_instruction_account(b"foo".to_vec());
2042        mock_invoke_context!(
2043            invoke_context,
2044            transaction_context,
2045            b"instruction data",
2046            transaction_accounts,
2047            0,
2048            &[1]
2049        );
2050
2051        let program_id = Pubkey::new_unique();
2052        let (derived_key, bump_seed) = Pubkey::find_program_address(&[b"foo"], &program_id);
2053
2054        let vm_addr = MM_INPUT_START;
2055        let (_mem, region) = mock_signers(&[b"foo", &[bump_seed]], vm_addr);
2056
2057        let config = Config {
2058            aligned_memory_mapping: false,
2059            ..Config::default()
2060        };
2061        let mapping =
2062            unsafe { MemoryMapping::new(vec![region], &config, SBPFVersion::V3).unwrap() };
2063        invoke_context
2064            .memory_contexts
2065            .set_memory_context_abi_v1(MemoryContext::new(
2066                BpfAllocator::new(0),
2067                Vec::new(),
2068                mapping,
2069            ))
2070            .unwrap();
2071
2072        let signers = translate_signers(&program_id, vm_addr, 1, &invoke_context).unwrap();
2073        assert_eq!(signers[0], derived_key);
2074    }
2075
2076    #[test]
2077    fn test_translate_accounts_rust() {
2078        let transaction_accounts =
2079            transaction_with_one_writable_instruction_account(b"foobar".to_vec());
2080        let account = transaction_accounts[1].1.clone();
2081        let key = transaction_accounts[1].0;
2082        let original_data_len = account.data().len();
2083
2084        let vm_addr = MM_STACK_START;
2085        let (_mem, region, account_metadata) =
2086            MockAccountInfo::new(key, &account).into_region(vm_addr);
2087
2088        let config = Config {
2089            aligned_memory_mapping: false,
2090            ..Config::default()
2091        };
2092        let memory_mapping =
2093            unsafe { MemoryMapping::new(vec![region], &config, SBPFVersion::V3).unwrap() };
2094
2095        mock_invoke_context!(
2096            invoke_context,
2097            transaction_context,
2098            b"instruction data",
2099            transaction_accounts,
2100            0,
2101            &[1, 1]
2102        );
2103
2104        invoke_context
2105            .memory_contexts
2106            .set_memory_context_abi_v1(MemoryContext::new(
2107                BpfAllocator::new(solana_program_entrypoint::HEAP_LENGTH as u64),
2108                vec![account_metadata],
2109                memory_mapping,
2110            ))
2111            .unwrap();
2112
2113        invoke_context
2114            .transaction_context
2115            .configure_next_cpi_for_tests(
2116                0,
2117                vec![
2118                    InstructionAccount::new(1, false, true),
2119                    InstructionAccount::new(1, false, true),
2120                ],
2121                vec![],
2122            )
2123            .unwrap();
2124
2125        let accounts = translate_accounts_rust(vm_addr, 1, &invoke_context).unwrap();
2126        assert_eq!(accounts.len(), 1);
2127        let caller_account = &accounts[0].caller_account;
2128        assert_eq!(caller_account.serialized_data, account.data());
2129        assert_eq!(caller_account.original_data_len, original_data_len);
2130    }
2131
2132    #[test]
2133    fn test_translate_accounts_v2() {
2134        let transaction_accounts =
2135            transaction_with_one_writable_instruction_account(b"foobar".to_vec());
2136        let account = transaction_accounts[1].1.clone();
2137        let key = transaction_accounts[1].0;
2138        let original_data_len = account.data().len();
2139        let account_metas_addr = solana_sbpf::ebpf::MM_HEAP_START;
2140        let (_runtime_memory, _account_metas, regions, account_metadata) =
2141            MockAccountMetaV2::new(key, &account).into_regions(account_metas_addr);
2142
2143        let config = Config {
2144            aligned_memory_mapping: false,
2145            ..Config::default()
2146        };
2147        let memory_mapping =
2148            unsafe { MemoryMapping::new(regions, &config, SBPFVersion::V3).unwrap() };
2149
2150        mock_invoke_context!(
2151            invoke_context,
2152            transaction_context,
2153            b"instruction data",
2154            transaction_accounts,
2155            0,
2156            &[1, 1]
2157        );
2158        invoke_context
2159            .memory_contexts
2160            .set_memory_context_abi_v1(MemoryContext::new(
2161                BpfAllocator::new(solana_program_entrypoint::HEAP_LENGTH as u64),
2162                vec![account_metadata],
2163                memory_mapping,
2164            ))
2165            .unwrap();
2166        invoke_context
2167            .transaction_context
2168            .configure_next_cpi_for_tests(
2169                0,
2170                vec![
2171                    InstructionAccount::new(1, false, true),
2172                    InstructionAccount::new(1, false, true),
2173                ],
2174                vec![],
2175            )
2176            .unwrap();
2177
2178        let accounts = translate_accounts_v2(account_metas_addr, 1, &invoke_context).unwrap();
2179        assert_eq!(accounts.len(), 1);
2180        let caller_account = &accounts[0].caller_account;
2181        assert_eq!(*caller_account.lamports, account.lamports());
2182        assert_eq!(caller_account.owner, account.owner());
2183        assert_eq!(caller_account.serialized_data, account.data());
2184        assert_eq!(caller_account.original_data_len, original_data_len);
2185        assert_eq!(*caller_account.ref_to_len_in_vm as usize, original_data_len);
2186    }
2187
2188    #[test]
2189    fn test_caller_account_from_account_meta_v2_with_invalid_pointer() {
2190        let mut transaction_accounts =
2191            transaction_with_one_writable_instruction_account(b"foobar".to_vec());
2192        let account = transaction_accounts[1].1.clone();
2193        let key = transaction_accounts[1].0;
2194        let other_key = Pubkey::new_unique();
2195        transaction_accounts.push((other_key, account.clone(), true));
2196
2197        let account_metas_addr = solana_sbpf::ebpf::MM_HEAP_START;
2198        let (_runtime_memory, account_metas, mut regions, account_metadata) =
2199            MockAccountMetaV2::new(key, &account).into_regions(account_metas_addr);
2200
2201        let other_account_metas_addr = account_metas_addr + size_of::<SolAccountMetaV2>() as u64;
2202        let (_other_runtime_memory, mut other_account_metas, other_regions, other_account_metadata) =
2203            MockAccountMetaV2::new(other_key, &account).into_regions(other_account_metas_addr);
2204
2205        other_account_metas[0].account_index = 1;
2206        regions.extend(other_regions);
2207
2208        let config = Config {
2209            aligned_memory_mapping: false,
2210            ..Config::default()
2211        };
2212        let memory_mapping =
2213            unsafe { MemoryMapping::new(regions, &config, SBPFVersion::V3).unwrap() };
2214
2215        mock_invoke_context!(
2216            invoke_context,
2217            transaction_context,
2218            b"instruction data",
2219            transaction_accounts,
2220            0,
2221            &[1, 2]
2222        );
2223        invoke_context
2224            .memory_contexts
2225            .set_memory_context_abi_v1(MemoryContext::new(
2226                BpfAllocator::new(solana_program_entrypoint::HEAP_LENGTH as u64),
2227                vec![account_metadata.clone(), other_account_metadata.clone()],
2228                memory_mapping,
2229            ))
2230            .unwrap();
2231
2232        let memory_mapping = invoke_context.memory_contexts.memory_mapping().unwrap();
2233
2234        // Both accounts translate successfully when paired with their own metadata.
2235        for (vm_addr, account_meta, metadata) in [
2236            (account_metas_addr, &account_metas[0], &account_metadata),
2237            (
2238                other_account_metas_addr,
2239                &other_account_metas[0],
2240                &other_account_metadata,
2241            ),
2242        ] {
2243            assert!(
2244                CallerAccount::from_account_meta_v2(
2245                    &invoke_context,
2246                    memory_mapping,
2247                    invoke_context.abi(),
2248                    vm_addr,
2249                    account_meta,
2250                    metadata,
2251                )
2252                .is_ok()
2253            );
2254        }
2255
2256        // Selecting the first account with the second account's metadata must fail.
2257        assert_matches!(
2258            CallerAccount::from_account_meta_v2(
2259                &invoke_context,
2260                memory_mapping,
2261                invoke_context.abi(),
2262                account_metas_addr,
2263                &account_metas[0],
2264                &other_account_metadata,
2265            ),
2266            Err(error) if error.downcast_ref::<CpiError>() == Some(&CpiError::InvalidPointer)
2267        );
2268    }
2269
2270    #[case(0, 0; "empty_account_metadata")]
2271    #[case(1, 1; "index_past_last_account")]
2272    #[case(1, u16::MAX; "maximum_account_index")]
2273    fn test_caller_account_from_account_meta_v2_with_invalid_account_index(
2274        available_accounts: usize,
2275        account_index: u16,
2276    ) {
2277        let transaction_accounts =
2278            transaction_with_one_writable_instruction_account(b"foobar".to_vec());
2279        let account = transaction_accounts[1].1.clone();
2280        let key = transaction_accounts[1].0;
2281        let account_metas_addr = solana_sbpf::ebpf::MM_HEAP_START;
2282        let (_runtime_memory, mut account_metas, regions, account_metadata) =
2283            MockAccountMetaV2::new(key, &account).into_regions(account_metas_addr);
2284
2285        // Simulate a guest selecting an account outside the serialized account metadata.
2286        account_metas[0].account_index = account_index;
2287        let config = Config {
2288            aligned_memory_mapping: false,
2289            ..Config::default()
2290        };
2291        let memory_mapping =
2292            unsafe { MemoryMapping::new(regions, &config, SBPFVersion::V3).unwrap() };
2293
2294        mock_invoke_context!(
2295            invoke_context,
2296            transaction_context,
2297            b"instruction data",
2298            transaction_accounts,
2299            0,
2300            &[1]
2301        );
2302
2303        // Set up the memory context with the serialized account metadata and memory mapping.
2304        invoke_context
2305            .memory_contexts
2306            .set_memory_context_abi_v1(MemoryContext::new(
2307                BpfAllocator::new(solana_program_entrypoint::HEAP_LENGTH as u64),
2308                vec![account_metadata.clone(); available_accounts],
2309                memory_mapping,
2310            ))
2311            .unwrap();
2312
2313        let memory_mapping = invoke_context.memory_contexts.memory_mapping().unwrap();
2314        let abi = invoke_context.abi();
2315        let account_meta =
2316            translate_type::<SolAccountMetaV2>(memory_mapping, account_metas_addr, abi).unwrap();
2317
2318        assert_matches!(
2319            CallerAccount::from_account_meta_v2(
2320                &invoke_context,
2321                memory_mapping,
2322                abi,
2323                account_metas_addr,
2324                account_meta,
2325                &account_metadata,
2326            ),
2327            Err(error) if error.downcast_ref::<InstructionError>() == Some(&InstructionError::MissingAccount)
2328        );
2329    }
2330
2331    #[test]
2332    fn test_get_serialized_data() {
2333        let transaction_accounts =
2334            transaction_with_one_writable_instruction_account(b"foo".to_vec());
2335        let account = transaction_accounts[1].1.clone();
2336        mock_invoke_context!(
2337            invoke_context,
2338            transaction_context,
2339            b"instruction data",
2340            transaction_accounts,
2341            0,
2342            &[1]
2343        );
2344
2345        let config = Config {
2346            aligned_memory_mapping: false,
2347            ..Config::default()
2348        };
2349        let memory_mapping =
2350            unsafe { MemoryMapping::new(vec![], &config, SBPFVersion::V3).unwrap() };
2351        let serialized_data = unsafe {
2352            CallerAccount::get_serialized_data(
2353                &memory_mapping,
2354                ABI::V1,
2355                MM_INPUT_START,
2356                account.data().len(),
2357                account
2358                    .data()
2359                    .len()
2360                    .saturating_add(MAX_PERMITTED_DATA_INCREASE)
2361                    .saturating_add(1),
2362                true,  // virtual_address_space_adjustments
2363                false, // account_data_direct_mapping
2364            )
2365        };
2366
2367        assert_matches!(
2368            serialized_data,
2369            Err(error) if error.downcast_ref::<InstructionError>().unwrap() == &InstructionError::InvalidRealloc
2370        );
2371    }
2372
2373    #[test]
2374    fn test_caller_account_from_account_info() {
2375        let transaction_accounts =
2376            transaction_with_one_writable_instruction_account(b"foo".to_vec());
2377        let account = transaction_accounts[1].1.clone();
2378        mock_invoke_context!(
2379            invoke_context,
2380            transaction_context,
2381            b"instruction data",
2382            transaction_accounts,
2383            0,
2384            &[1]
2385        );
2386
2387        let key = Pubkey::new_unique();
2388        let vm_addr = MM_STACK_START;
2389        let (_mem, region, account_metadata) =
2390            MockAccountInfo::new(key, &account).into_region(vm_addr);
2391
2392        let config = Config {
2393            aligned_memory_mapping: false,
2394            ..Config::default()
2395        };
2396        let memory_mapping =
2397            unsafe { MemoryMapping::new(vec![region], &config, SBPFVersion::V3).unwrap() };
2398
2399        let account_info =
2400            translate_type::<stable::AccountInfo>(&memory_mapping, vm_addr, ABI::V0).unwrap();
2401
2402        invoke_context
2403            .memory_contexts
2404            .mock_set_mapping_abi_v1(memory_mapping);
2405        let abi = invoke_context.abi();
2406        let memory_mapping = invoke_context.memory_contexts.memory_mapping().unwrap();
2407        let caller_account = CallerAccount::from_account_info(
2408            &invoke_context,
2409            memory_mapping,
2410            abi,
2411            vm_addr,
2412            account_info,
2413            &account_metadata,
2414        )
2415        .unwrap();
2416        assert_eq!(*caller_account.lamports, account.lamports());
2417        assert_eq!(caller_account.owner, account.owner());
2418        assert_eq!(caller_account.original_data_len, account.data().len());
2419        assert_eq!(
2420            *caller_account.ref_to_len_in_vm as usize,
2421            account.data().len()
2422        );
2423        assert_eq!(caller_account.serialized_data, account.data());
2424    }
2425
2426    #[case(false, false)]
2427    #[case(true, false)]
2428    #[case(true, true)]
2429    fn test_update_caller_account_lamports_owner(
2430        virtual_address_space_adjustments: bool,
2431        account_data_direct_mapping: bool,
2432    ) {
2433        let transaction_accounts = transaction_with_one_writable_instruction_account(vec![]);
2434        let account = transaction_accounts[1].1.clone();
2435        mock_invoke_context!(
2436            invoke_context,
2437            transaction_context,
2438            b"instruction data",
2439            transaction_accounts,
2440            0,
2441            &[1]
2442        );
2443
2444        let mut mock_caller_account =
2445            MockCallerAccount::new(1234, *account.owner(), account.data(), false);
2446
2447        let config = Config {
2448            aligned_memory_mapping: false,
2449            ..Config::default()
2450        };
2451        let memory_mapping = unsafe {
2452            MemoryMapping::new(
2453                mock_caller_account.regions.split_off(0),
2454                &config,
2455                SBPFVersion::V3,
2456            )
2457            .unwrap()
2458        };
2459        invoke_context
2460            .memory_contexts
2461            .mock_set_mapping_abi_v1(memory_mapping);
2462
2463        let mut caller_account = mock_caller_account.caller_account();
2464        let instruction_context = invoke_context
2465            .transaction_context
2466            .get_current_instruction_context()
2467            .unwrap();
2468        let mut callee_account = instruction_context
2469            .try_borrow_instruction_account(0)
2470            .unwrap();
2471        callee_account.set_lamports(42).unwrap();
2472        callee_account
2473            .set_owner(Pubkey::new_unique().as_ref())
2474            .unwrap();
2475
2476        update_caller_account(
2477            &invoke_context,
2478            ABI::V1,
2479            &mut caller_account,
2480            &mut callee_account,
2481            virtual_address_space_adjustments,
2482            account_data_direct_mapping,
2483        )
2484        .unwrap();
2485
2486        assert_eq!(*caller_account.lamports, 42);
2487        assert_eq!(caller_account.owner, callee_account.get_owner());
2488    }
2489
2490    #[test]
2491    fn test_update_caller_account_data() {
2492        let transaction_accounts =
2493            transaction_with_one_writable_instruction_account(b"foobar".to_vec());
2494        let account = transaction_accounts[1].1.clone();
2495        let original_data_len = account.data().len();
2496
2497        mock_invoke_context!(
2498            invoke_context,
2499            transaction_context,
2500            b"instruction data",
2501            transaction_accounts,
2502            0,
2503            &[1]
2504        );
2505
2506        let mut mock_caller_account =
2507            MockCallerAccount::new(account.lamports(), *account.owner(), account.data(), false);
2508
2509        let config = Config {
2510            aligned_memory_mapping: false,
2511            ..Config::default()
2512        };
2513        let memory_mapping = unsafe {
2514            MemoryMapping::new(
2515                mock_caller_account.regions.clone(),
2516                &config,
2517                SBPFVersion::V3,
2518            )
2519            .unwrap()
2520        };
2521        invoke_context
2522            .memory_contexts
2523            .mock_set_mapping_abi_v1(memory_mapping);
2524
2525        let data_slice = mock_caller_account.data_slice();
2526        let len_ptr = unsafe {
2527            data_slice
2528                .as_ptr()
2529                .offset(-(mem::size_of::<u64>() as isize))
2530        };
2531        let serialized_len = || unsafe { *len_ptr.cast::<u64>() as usize };
2532        let mut caller_account = mock_caller_account.caller_account();
2533        let instruction_context = invoke_context
2534            .transaction_context
2535            .get_current_instruction_context()
2536            .unwrap();
2537        let mut callee_account = instruction_context
2538            .try_borrow_instruction_account(0)
2539            .unwrap();
2540
2541        for (new_value, expected_realloc_size) in [
2542            (b"foo".to_vec(), MAX_PERMITTED_DATA_INCREASE + 3),
2543            (b"foobaz".to_vec(), MAX_PERMITTED_DATA_INCREASE),
2544            (b"foobazbad".to_vec(), MAX_PERMITTED_DATA_INCREASE - 3),
2545        ] {
2546            assert_eq!(caller_account.serialized_data, callee_account.get_data());
2547            callee_account.set_data_from_slice(&new_value).unwrap();
2548
2549            update_caller_account(
2550                &invoke_context,
2551                ABI::V1,
2552                &mut caller_account,
2553                &mut callee_account,
2554                false, // virtual_address_space_adjustments
2555                false, // account_data_direct_mapping
2556            )
2557            .unwrap();
2558
2559            let data_len = callee_account.get_data().len();
2560            assert_eq!(data_len, *caller_account.ref_to_len_in_vm as usize);
2561            assert_eq!(data_len, serialized_len());
2562            assert_eq!(data_len, caller_account.serialized_data.len());
2563            assert_eq!(
2564                callee_account.get_data(),
2565                &caller_account.serialized_data[..data_len]
2566            );
2567            assert_eq!(data_slice[data_len..].len(), expected_realloc_size);
2568            assert!(is_zeroed(&data_slice[data_len..]));
2569        }
2570
2571        callee_account
2572            .set_data_length(original_data_len + MAX_PERMITTED_DATA_INCREASE)
2573            .unwrap();
2574        update_caller_account(
2575            &invoke_context,
2576            ABI::V1,
2577            &mut caller_account,
2578            &mut callee_account,
2579            false, // virtual_address_space_adjustments
2580            false, // account_data_direct_mapping
2581        )
2582        .unwrap();
2583        let data_len = callee_account.get_data().len();
2584        assert_eq!(data_slice[data_len..].len(), 0);
2585        assert!(is_zeroed(&data_slice[data_len..]));
2586
2587        callee_account
2588            .set_data_length(original_data_len + MAX_PERMITTED_DATA_INCREASE + 1)
2589            .unwrap();
2590        assert_matches!(
2591            update_caller_account(
2592                &invoke_context,
2593                ABI::V1,
2594                &mut caller_account,
2595                &mut callee_account,
2596                false, // virtual_address_space_adjustments
2597                false, // account_data_direct_mapping
2598            ),
2599            Err(error) if error.downcast_ref::<InstructionError>().unwrap() == &InstructionError::InvalidRealloc
2600        );
2601
2602        // close the account
2603        callee_account.set_data_length(0).unwrap();
2604        callee_account
2605            .set_owner(system_program::id().as_ref())
2606            .unwrap();
2607        update_caller_account(
2608            &invoke_context,
2609            ABI::V1,
2610            &mut caller_account,
2611            &mut callee_account,
2612            false, // virtual_address_space_adjustments
2613            false, // account_data_direct_mapping
2614        )
2615        .unwrap();
2616        let data_len = callee_account.get_data().len();
2617        assert_eq!(data_len, 0);
2618    }
2619
2620    #[case(false, false)]
2621    #[case(true, false)]
2622    #[case(true, true)]
2623    fn test_update_callee_account_lamports_owner(
2624        virtual_address_space_adjustments: bool,
2625        account_data_direct_mapping: bool,
2626    ) {
2627        let transaction_accounts = transaction_with_one_writable_instruction_account(vec![]);
2628        let account = transaction_accounts[1].1.clone();
2629
2630        mock_invoke_context!(
2631            invoke_context,
2632            transaction_context,
2633            b"instruction data",
2634            transaction_accounts,
2635            0,
2636            &[1]
2637        );
2638
2639        let mut mock_caller_account =
2640            MockCallerAccount::new(1234, *account.owner(), account.data(), false);
2641        let config = Config {
2642            aligned_memory_mapping: false,
2643            ..Config::default()
2644        };
2645        let memory_mapping = unsafe {
2646            MemoryMapping::new(
2647                mock_caller_account.regions.clone(),
2648                &config,
2649                SBPFVersion::V3,
2650            )
2651            .unwrap()
2652        };
2653        let caller_account = mock_caller_account.caller_account();
2654
2655        borrow_instruction_account!(callee_account, invoke_context, 0);
2656
2657        *caller_account.lamports = 42;
2658        *caller_account.owner = Pubkey::new_unique();
2659
2660        update_callee_account(
2661            &memory_mapping,
2662            ABI::V1,
2663            &caller_account,
2664            callee_account,
2665            virtual_address_space_adjustments,
2666            account_data_direct_mapping,
2667        )
2668        .unwrap();
2669
2670        borrow_instruction_account!(callee_account, invoke_context, 0);
2671        assert_eq!(callee_account.get_lamports(), 42);
2672        assert_eq!(caller_account.owner, callee_account.get_owner());
2673    }
2674
2675    #[case(false, false)]
2676    #[case(true, false)]
2677    #[case(true, true)]
2678    fn test_update_callee_account_data_writable(
2679        virtual_address_space_adjustments: bool,
2680        account_data_direct_mapping: bool,
2681    ) {
2682        let transaction_accounts =
2683            transaction_with_one_writable_instruction_account(b"foobar".to_vec());
2684        let account = transaction_accounts[1].1.clone();
2685
2686        mock_invoke_context!(
2687            invoke_context,
2688            transaction_context,
2689            b"instruction data",
2690            transaction_accounts,
2691            0,
2692            &[1]
2693        );
2694
2695        let mut mock_caller_account =
2696            MockCallerAccount::new(1234, *account.owner(), account.data(), false);
2697        let config = Config {
2698            aligned_memory_mapping: false,
2699            ..Config::default()
2700        };
2701        let memory_mapping = unsafe {
2702            MemoryMapping::new(
2703                mock_caller_account.regions.clone(),
2704                &config,
2705                SBPFVersion::V3,
2706            )
2707            .unwrap()
2708        };
2709        let mut caller_account = mock_caller_account.caller_account();
2710        borrow_instruction_account!(callee_account, invoke_context, 0);
2711
2712        // Data is not copied in update_callee_account() with virtual_address_space_adjustments
2713        caller_account.serialized_data[0] = b'b';
2714        update_callee_account(
2715            &memory_mapping,
2716            ABI::V1,
2717            &caller_account,
2718            callee_account,
2719            false, // virtual_address_space_adjustments,
2720            false, // account_data_direct_mapping
2721        )
2722        .unwrap();
2723        borrow_instruction_account!(callee_account, invoke_context, 0);
2724        assert_eq!(callee_account.get_data(), b"boobar");
2725
2726        // growing resize
2727        let mut data = b"foobarbaz".to_vec();
2728        *caller_account.ref_to_len_in_vm = data.len() as u64;
2729        caller_account.serialized_data = &mut data;
2730        assert_eq!(
2731            update_callee_account(
2732                &memory_mapping,
2733                ABI::V1,
2734                &caller_account,
2735                callee_account,
2736                virtual_address_space_adjustments,
2737                account_data_direct_mapping,
2738            )
2739            .unwrap(),
2740            virtual_address_space_adjustments,
2741        );
2742
2743        // truncating resize
2744        let mut data = b"baz".to_vec();
2745        *caller_account.ref_to_len_in_vm = data.len() as u64;
2746        caller_account.serialized_data = &mut data;
2747        borrow_instruction_account!(callee_account, invoke_context, 0);
2748        assert_eq!(
2749            update_callee_account(
2750                &memory_mapping,
2751                ABI::V1,
2752                &caller_account,
2753                callee_account,
2754                virtual_address_space_adjustments,
2755                account_data_direct_mapping,
2756            )
2757            .unwrap(),
2758            virtual_address_space_adjustments,
2759        );
2760
2761        // close the account
2762        let mut data = Vec::new();
2763        caller_account.serialized_data = &mut data;
2764        *caller_account.ref_to_len_in_vm = 0;
2765        let mut owner = system_program::id();
2766        caller_account.owner = &mut owner;
2767        borrow_instruction_account!(callee_account, invoke_context, 0);
2768        update_callee_account(
2769            &memory_mapping,
2770            ABI::V1,
2771            &caller_account,
2772            callee_account,
2773            virtual_address_space_adjustments,
2774            account_data_direct_mapping,
2775        )
2776        .unwrap();
2777        borrow_instruction_account!(callee_account, invoke_context, 0);
2778        assert_eq!(callee_account.get_data(), b"");
2779    }
2780
2781    #[case(false, false)]
2782    #[case(true, false)]
2783    #[case(true, true)]
2784    fn test_update_callee_account_data_readonly(
2785        virtual_address_space_adjustments: bool,
2786        account_data_direct_mapping: bool,
2787    ) {
2788        let transaction_accounts =
2789            transaction_with_one_readonly_instruction_account(b"foobar".to_vec());
2790        let account = transaction_accounts[1].1.clone();
2791
2792        mock_invoke_context!(
2793            invoke_context,
2794            transaction_context,
2795            b"instruction data",
2796            transaction_accounts,
2797            0,
2798            &[1]
2799        );
2800
2801        let mut mock_caller_account =
2802            MockCallerAccount::new(1234, *account.owner(), account.data(), false);
2803        let config = Config {
2804            aligned_memory_mapping: false,
2805            ..Config::default()
2806        };
2807        let memory_mapping = unsafe {
2808            MemoryMapping::new(
2809                mock_caller_account.regions.clone(),
2810                &config,
2811                SBPFVersion::V3,
2812            )
2813            .unwrap()
2814        };
2815        let mut caller_account = mock_caller_account.caller_account();
2816        borrow_instruction_account!(callee_account, invoke_context, 0);
2817
2818        // Data is not copied in update_callee_account() with virtual_address_space_adjustments
2819        caller_account.serialized_data[0] = b'b';
2820        assert_matches!(
2821            update_callee_account(
2822                &memory_mapping,
2823                ABI::V1,
2824                &caller_account,
2825                callee_account,
2826                false, // virtual_address_space_adjustments,
2827                false, // account_data_direct_mapping
2828            ),
2829            Err(error) if error.downcast_ref::<InstructionError>().unwrap() == &InstructionError::ExternalAccountDataModified
2830        );
2831
2832        // growing resize
2833        let mut data = b"foobarbaz".to_vec();
2834        *caller_account.ref_to_len_in_vm = data.len() as u64;
2835        caller_account.serialized_data = &mut data;
2836        borrow_instruction_account!(callee_account, invoke_context, 0);
2837        assert_matches!(
2838            update_callee_account(
2839                &memory_mapping,
2840                ABI::V1,
2841                &caller_account,
2842                callee_account,
2843                virtual_address_space_adjustments,
2844                account_data_direct_mapping,
2845            ),
2846            Err(error) if error.downcast_ref::<InstructionError>().unwrap() == &InstructionError::ExternalAccountDataModified
2847        );
2848
2849        // truncating resize
2850        let mut data = b"baz".to_vec();
2851        *caller_account.ref_to_len_in_vm = data.len() as u64;
2852        caller_account.serialized_data = &mut data;
2853        borrow_instruction_account!(callee_account, invoke_context, 0);
2854        assert_matches!(
2855            update_callee_account(
2856                &memory_mapping,
2857                ABI::V1,
2858                &caller_account,
2859                callee_account,
2860                virtual_address_space_adjustments,
2861                account_data_direct_mapping,
2862            ),
2863            Err(error) if error.downcast_ref::<InstructionError>().unwrap() == &InstructionError::ExternalAccountDataModified
2864        );
2865    }
2866
2867    #[test_case(ABI::V0, 0; "abi_v0")]
2868    #[test_case(ABI::V1, MAX_PERMITTED_DATA_INCREASE; "abi_v1")]
2869    fn test_get_serialized_data_realloc_limit(abi: ABI, realloc_padding: usize) {
2870        let config = Config {
2871            aligned_memory_mapping: false,
2872            ..Config::default()
2873        };
2874        let memory_mapping =
2875            unsafe { MemoryMapping::new(vec![], &config, SBPFVersion::V3).unwrap() };
2876        let original_data_len = 3;
2877        let serialized_data = |len| unsafe {
2878            CallerAccount::get_serialized_data(
2879                &memory_mapping,
2880                abi,
2881                MM_INPUT_START,
2882                original_data_len,
2883                len,
2884                true, // virtual_address_space_adjustments
2885                true, // account_data_direct_mapping
2886            )
2887        };
2888
2889        let limit = original_data_len + realloc_padding;
2890        assert!(serialized_data(limit).is_ok());
2891        assert_matches!(
2892            serialized_data(limit + 1),
2893            Err(error) if error.downcast_ref::<InstructionError>().unwrap() == &InstructionError::InvalidRealloc
2894        );
2895    }
2896
2897    // With direct mapping, only `address_space_reserved_for_account` enforces the limit.
2898    #[test_case(ABI::V0, 0, false; "abi_v0")]
2899    #[test_case(ABI::V0, 0, true; "abi_v0_direct_mapping")]
2900    #[test_case(ABI::V1, MAX_PERMITTED_DATA_INCREASE, false; "abi_v1")]
2901    #[test_case(ABI::V1, MAX_PERMITTED_DATA_INCREASE, true; "abi_v1_direct_mapping")]
2902    fn test_update_caller_account_realloc_limit(
2903        abi: ABI,
2904        realloc_padding: usize,
2905        direct_mapping: bool,
2906    ) {
2907        let transaction_accounts =
2908            transaction_with_one_writable_instruction_account(b"foobar".to_vec());
2909        let account = transaction_accounts[1].1.clone();
2910        let limit = account.data().len() + realloc_padding;
2911
2912        mock_invoke_context!(
2913            invoke_context,
2914            transaction_context,
2915            b"instruction data",
2916            transaction_accounts,
2917            0,
2918            &[1]
2919        );
2920
2921        let mut mock_caller_account = MockCallerAccount::new(
2922            account.lamports(),
2923            *account.owner(),
2924            account.data(),
2925            direct_mapping,
2926        );
2927        let config = Config {
2928            aligned_memory_mapping: false,
2929            ..Config::default()
2930        };
2931        let memory_mapping = unsafe {
2932            MemoryMapping::new(
2933                mock_caller_account.regions.clone(),
2934                &config,
2935                SBPFVersion::V3,
2936            )
2937            .unwrap()
2938        };
2939        invoke_context
2940            .memory_contexts
2941            .mock_set_mapping_abi_v1(memory_mapping);
2942
2943        let mut caller_account = mock_caller_account.caller_account();
2944        let instruction_context = invoke_context
2945            .transaction_context
2946            .get_current_instruction_context()
2947            .unwrap();
2948        let mut callee_account = instruction_context
2949            .try_borrow_instruction_account(0)
2950            .unwrap();
2951
2952        callee_account.set_data_length(limit).unwrap();
2953        update_caller_account(
2954            &invoke_context,
2955            abi,
2956            &mut caller_account,
2957            &mut callee_account,
2958            direct_mapping, // virtual_address_space_adjustments
2959            direct_mapping, // account_data_direct_mapping
2960        )
2961        .unwrap();
2962
2963        callee_account.set_data_length(limit + 1).unwrap();
2964        assert_matches!(
2965            update_caller_account(
2966                &invoke_context,
2967                abi,
2968                &mut caller_account,
2969                &mut callee_account,
2970                direct_mapping, // virtual_address_space_adjustments
2971                direct_mapping, // account_data_direct_mapping
2972            ),
2973            Err(error) if error.downcast_ref::<InstructionError>().unwrap() == &InstructionError::InvalidRealloc
2974        );
2975    }
2976}