Skip to main content

solana_program_runtime/
cpi.rs

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