1pub mod env;
21
22use crate::{
23 Code, Config, Error, LOG_TARGET, Pallet, ReentrancyProtection, RuntimeCosts, SENTINEL,
24 StorageAccessKind,
25 access_list::StorageOp,
26 exec::{CallResources, ExecError, ExecResult, Ext, Key},
27 limits,
28 metering::ChargedAmount,
29 precompiles::{All as AllPrecompiles, Precompiles},
30 primitives::ExecReturnValue,
31 tracing::FrameTraceInfo,
32};
33use alloc::{vec, vec::Vec};
34use codec::Encode;
35use core::{fmt, marker::PhantomData, mem};
36#[cfg(doc)]
37pub use env::SyscallDoc;
38use frame_support::{ensure, weights::Weight};
39use pallet_revive_uapi::{CallFlags, ReturnErrorCode, ReturnFlags, StorageFlags};
40use sp_core::{H160, H256, U256};
41use sp_runtime::DispatchError;
42
43pub fn extract_code_and_data(data: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
45 let blob_len = polkavm::ProgramBlob::blob_length(data)?;
46 let blob_len = blob_len.try_into().ok()?;
47 let (code, data) = data.split_at_checked(blob_len)?;
48 Some((code.to_vec(), data.to_vec()))
49}
50
51pub trait Memory<T: Config> {
58 fn read_into_buf(&mut self, ptr: u32, buf: &mut [u8]) -> Result<(), DispatchError>;
64
65 fn is_readable(&self, ptr: u32, len: u32) -> bool;
67
68 fn write(&mut self, ptr: u32, buf: &[u8]) -> Result<(), DispatchError>;
74
75 fn zero(&mut self, ptr: u32, len: u32) -> Result<(), DispatchError>;
81
82 fn reset_interpreter_cache(&mut self);
88
89 fn read(&mut self, ptr: u32, len: u32) -> Result<Vec<u8>, DispatchError> {
95 if !self.is_readable(ptr, len) {
96 return Err(Error::<T>::OutOfBounds.into());
97 }
98 let mut buf = vec![0u8; len as usize];
99 self.read_into_buf(ptr, buf.as_mut_slice())?;
100 Ok(buf)
101 }
102
103 fn read_array<const N: usize>(&mut self, ptr: u32) -> Result<[u8; N], DispatchError> {
105 let mut buf = [0u8; N];
106 self.read_into_buf(ptr, &mut buf)?;
107 Ok(buf)
108 }
109
110 fn read_u32(&mut self, ptr: u32) -> Result<u32, DispatchError> {
112 let buf: [u8; 4] = self.read_array(ptr)?;
113 Ok(u32::from_le_bytes(buf))
114 }
115
116 fn read_u256(&mut self, ptr: u32) -> Result<U256, DispatchError> {
118 let buf: [u8; 32] = self.read_array(ptr)?;
119 Ok(U256::from_little_endian(&buf))
120 }
121
122 fn read_h160(&mut self, ptr: u32) -> Result<H160, DispatchError> {
124 let mut buf = H160::default();
125 self.read_into_buf(ptr, buf.as_bytes_mut())?;
126 Ok(buf)
127 }
128
129 fn read_h256(&mut self, ptr: u32) -> Result<H256, DispatchError> {
131 let mut code_hash = H256::default();
132 self.read_into_buf(ptr, code_hash.as_bytes_mut())?;
133 Ok(code_hash)
134 }
135}
136
137pub trait PolkaVmInstance<T: Config>: Memory<T> {
143 fn gas(&self) -> polkavm::Gas;
144 fn set_gas(&mut self, gas: polkavm::Gas);
145 fn read_input_regs(&self) -> (u64, u64, u64, u64, u64, u64);
146 fn write_output(&mut self, output: u64);
147}
148
149#[cfg(feature = "runtime-benchmarks")]
156impl<T: Config> Memory<T> for [u8] {
157 fn is_readable(&self, ptr: u32, len: u32) -> bool {
158 (ptr as usize).checked_add(len as usize).is_some_and(|end| end <= self.len())
159 }
160
161 fn read_into_buf(&mut self, ptr: u32, buf: &mut [u8]) -> Result<(), DispatchError> {
162 let ptr = ptr as usize;
163 let bound_checked =
164 self.get(ptr..ptr + buf.len()).ok_or_else(|| Error::<T>::OutOfBounds)?;
165 buf.copy_from_slice(bound_checked);
166 Ok(())
167 }
168
169 fn write(&mut self, ptr: u32, buf: &[u8]) -> Result<(), DispatchError> {
170 let ptr = ptr as usize;
171 let bound_checked =
172 self.get_mut(ptr..ptr + buf.len()).ok_or_else(|| Error::<T>::OutOfBounds)?;
173 bound_checked.copy_from_slice(buf);
174 Ok(())
175 }
176
177 fn zero(&mut self, ptr: u32, len: u32) -> Result<(), DispatchError> {
178 <[u8] as Memory<T>>::write(self, ptr, &vec![0; len as usize])
179 }
180
181 fn reset_interpreter_cache(&mut self) {}
182}
183
184impl<T: Config> Memory<T> for polkavm::RawInstance {
185 fn is_readable(&self, ptr: u32, len: u32) -> bool {
186 self.is_memory_accessible(ptr, len, polkavm::MemoryProtection::Read)
187 }
188
189 fn read_into_buf(&mut self, ptr: u32, buf: &mut [u8]) -> Result<(), DispatchError> {
190 self.read_memory_into(ptr, buf)
191 .map(|_| ())
192 .map_err(|_| Error::<T>::OutOfBounds.into())
193 }
194
195 fn write(&mut self, ptr: u32, buf: &[u8]) -> Result<(), DispatchError> {
196 self.write_memory(ptr, buf).map_err(|_| Error::<T>::OutOfBounds.into())
197 }
198
199 fn zero(&mut self, ptr: u32, len: u32) -> Result<(), DispatchError> {
200 self.zero_memory(ptr, len).map_err(|_| Error::<T>::OutOfBounds.into())
201 }
202
203 fn reset_interpreter_cache(&mut self) {
204 self.reset_interpreter_cache();
205 }
206}
207
208impl<T: Config> PolkaVmInstance<T> for polkavm::RawInstance {
209 fn gas(&self) -> polkavm::Gas {
210 self.gas()
211 }
212
213 fn set_gas(&mut self, gas: polkavm::Gas) {
214 self.set_gas(gas)
215 }
216
217 fn read_input_regs(&self) -> (u64, u64, u64, u64, u64, u64) {
218 (
219 self.reg(polkavm::Reg::A0),
220 self.reg(polkavm::Reg::A1),
221 self.reg(polkavm::Reg::A2),
222 self.reg(polkavm::Reg::A3),
223 self.reg(polkavm::Reg::A4),
224 self.reg(polkavm::Reg::A5),
225 )
226 }
227
228 fn write_output(&mut self, output: u64) {
229 self.set_reg(polkavm::Reg::A0, output);
230 }
231}
232
233impl From<&ExecReturnValue> for ReturnErrorCode {
234 fn from(from: &ExecReturnValue) -> Self {
235 if from.flags.contains(ReturnFlags::REVERT) { Self::CalleeReverted } else { Self::Success }
236 }
237}
238
239#[derive(Debug)]
241pub struct ReturnData {
242 flags: u32,
245 data: Vec<u8>,
247}
248
249#[derive(Debug)]
256pub enum TrapReason {
257 SupervisorError(DispatchError),
260 Return(ReturnData),
262 Termination,
265}
266
267impl<T: Into<DispatchError>> From<T> for TrapReason {
268 fn from(from: T) -> Self {
269 Self::SupervisorError(from.into())
270 }
271}
272
273impl fmt::Display for TrapReason {
274 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
275 Ok(())
276 }
277}
278
279macro_rules! charge_gas {
284 ($runtime:expr, $costs:expr) => {{ $runtime.ext.frame_meter_mut().charge_weight_token($costs) }};
285}
286
287enum CallType {
289 Call { value_ptr: u32 },
291 DelegateCall,
294}
295
296impl CallType {
297 fn cost(&self) -> RuntimeCosts {
298 match self {
299 CallType::Call { .. } => RuntimeCosts::CallBase,
300 CallType::DelegateCall => RuntimeCosts::DelegateCallBase,
301 }
302 }
303}
304
305fn already_charged(_: u32) -> Option<RuntimeCosts> {
309 None
310}
311
312fn extract_hi_lo(reg: u64) -> (u32, u32) {
314 ((reg >> 32) as u32, reg as u32)
315}
316
317enum StorageValue {
319 Memory { ptr: u32, len: u32 },
323
324 Value(Vec<u8>),
328}
329
330enum StorageReadMode {
332 VariableOutput { output_len_ptr: u32 },
335 FixedOutput32,
338}
339
340pub struct Runtime<'a, E: Ext, M: ?Sized> {
342 ext: &'a mut E,
343 input_data: Option<Vec<u8>>,
344 _phantom_data: PhantomData<M>,
345}
346
347impl<'a, E: Ext, M: ?Sized + Memory<E::T>> Runtime<'a, E, M> {
348 pub fn new(ext: &'a mut E, input_data: Vec<u8>) -> Self {
349 Self { ext, input_data: Some(input_data), _phantom_data: Default::default() }
350 }
351
352 pub fn ext(&mut self) -> &mut E {
354 self.ext
355 }
356
357 fn charge_gas(&mut self, costs: RuntimeCosts) -> Result<ChargedAmount, DispatchError> {
361 charge_gas!(self, costs)
362 }
363
364 fn adjust_gas(&mut self, charged: ChargedAmount, actual_costs: RuntimeCosts) {
369 self.ext.frame_meter_mut().adjust_weight(charged, actual_costs);
370 }
371
372 pub fn write_sandbox_output(
393 &mut self,
394 memory: &mut M,
395 out_ptr: u32,
396 out_len_ptr: u32,
397 buf: &[u8],
398 allow_skip: bool,
399 create_token: impl FnOnce(u32) -> Option<RuntimeCosts>,
400 ) -> Result<(), DispatchError> {
401 if allow_skip && out_ptr == SENTINEL {
402 return Ok(());
403 }
404
405 let len = memory.read_u32(out_len_ptr)?;
406 let buf_len = len.min(buf.len() as u32);
407
408 if let Some(costs) = create_token(buf_len) {
409 self.charge_gas(costs)?;
410 }
411
412 memory.write(out_ptr, &buf[..buf_len as usize])?;
413 memory.write(out_len_ptr, &buf_len.encode())
414 }
415
416 pub fn write_fixed_sandbox_output(
418 &mut self,
419 memory: &mut M,
420 out_ptr: u32,
421 buf: &[u8],
422 allow_skip: bool,
423 create_token: impl FnOnce(u32) -> Option<RuntimeCosts>,
424 ) -> Result<(), DispatchError> {
425 if buf.is_empty() || (allow_skip && out_ptr == SENTINEL) {
426 return Ok(());
427 }
428
429 let buf_len = buf.len() as u32;
430 if let Some(costs) = create_token(buf_len) {
431 self.charge_gas(costs)?;
432 }
433
434 memory.write(out_ptr, buf)
435 }
436
437 fn compute_hash_on_intermediate_buffer<F, R>(
450 &self,
451 memory: &mut M,
452 hash_fn: F,
453 input_ptr: u32,
454 input_len: u32,
455 output_ptr: u32,
456 ) -> Result<(), DispatchError>
457 where
458 F: FnOnce(&[u8]) -> R,
459 R: AsRef<[u8]>,
460 {
461 let input = memory.read(input_ptr, input_len)?;
463 let hash = hash_fn(&input);
465 memory.write(output_ptr, hash.as_ref())?;
467 Ok(())
468 }
469
470 fn decode_key(&self, memory: &mut M, key_ptr: u32, key_len: u32) -> Result<Key, TrapReason> {
471 let res = match key_len {
472 SENTINEL => {
473 let mut buffer = [0u8; 32];
474 memory.read_into_buf(key_ptr, buffer.as_mut())?;
475 Ok(Key::from_fixed(buffer))
476 },
477 len => {
478 ensure!(len <= limits::STORAGE_KEY_BYTES, Error::<E::T>::DecodingFailed);
479 let key = memory.read(key_ptr, len)?;
480 Key::try_from_var(key)
481 },
482 };
483
484 res.map_err(|_| Error::<E::T>::DecodingFailed.into())
485 }
486
487 fn is_transient(flags: u32) -> Result<bool, TrapReason> {
488 StorageFlags::from_bits(flags)
489 .ok_or_else(|| <Error<E::T>>::InvalidStorageFlags.into())
490 .map(|flags| flags.contains(StorageFlags::TRANSIENT))
491 }
492
493 fn set_storage(
494 &mut self,
495 memory: &mut M,
496 flags: u32,
497 key_ptr: u32,
498 key_len: u32,
499 value: StorageValue,
500 ) -> Result<u32, TrapReason> {
501 let transient = Self::is_transient(flags)?;
502
503 let value_len = match &value {
504 StorageValue::Memory { ptr: _, len } => *len,
505 StorageValue::Value(data) => data.len() as u32,
506 };
507
508 let max_size = limits::STORAGE_BYTES;
509 let key = self.decode_key(memory, key_ptr, key_len)?;
510
511 if value_len > max_size {
512 let access_kind =
514 StorageAccessKind::new(transient, || self.ext.peek_storage_access(&key));
515 self.charge_gas(RuntimeCosts::SetStorage {
516 new_bytes: value_len,
517 old_bytes: max_size,
518 kind: access_kind,
519 })?;
520 return Err(Error::<E::T>::ValueTooLarge.into());
521 }
522
523 let access_kind = StorageAccessKind::new(transient, || {
524 self.ext.touch_storage_access(&key, StorageOp::Write)
525 });
526 let charged = self.charge_gas(RuntimeCosts::SetStorage {
527 new_bytes: value_len,
528 old_bytes: max_size,
529 kind: access_kind,
530 })?;
531 let value = match value {
532 StorageValue::Memory { ptr, len } => Some(memory.read(ptr, len)?),
533 StorageValue::Value(data) => Some(data),
534 };
535
536 let write_outcome = if transient {
537 self.ext.set_transient_storage(&key, value, false)?
538 } else {
539 self.ext.set_storage(&key, value, false)?
540 };
541
542 self.adjust_gas(
543 charged,
544 RuntimeCosts::SetStorage {
545 new_bytes: value_len,
546 old_bytes: write_outcome.old_len(),
547 kind: access_kind,
548 },
549 );
550 Ok(write_outcome.old_len_with_sentinel())
551 }
552
553 fn clear_storage(
554 &mut self,
555 memory: &mut M,
556 flags: u32,
557 key_ptr: u32,
558 key_len: u32,
559 ) -> Result<u32, TrapReason> {
560 let transient = Self::is_transient(flags)?;
561 let key = self.decode_key(memory, key_ptr, key_len)?;
562 let access_kind = StorageAccessKind::new(transient, || {
563 self.ext.touch_storage_access(&key, StorageOp::Write)
564 });
565 let charged = self.charge_gas(RuntimeCosts::ClearStorage {
566 len: limits::STORAGE_BYTES,
567 kind: access_kind,
568 })?;
569 let outcome = if transient {
570 self.ext.set_transient_storage(&key, None, false)?
571 } else {
572 self.ext.set_storage(&key, None, false)?
573 };
574 self.adjust_gas(
575 charged,
576 RuntimeCosts::ClearStorage { len: outcome.old_len(), kind: access_kind },
577 );
578 Ok(outcome.old_len_with_sentinel())
579 }
580
581 fn get_storage(
582 &mut self,
583 memory: &mut M,
584 flags: u32,
585 key_ptr: u32,
586 key_len: u32,
587 out_ptr: u32,
588 read_mode: StorageReadMode,
589 ) -> Result<ReturnErrorCode, TrapReason> {
590 let transient = Self::is_transient(flags)?;
591 let key = self.decode_key(memory, key_ptr, key_len)?;
592 let access_kind = StorageAccessKind::new(transient, || {
593 self.ext.touch_storage_access(&key, StorageOp::Read)
594 });
595 let charged = self.charge_gas(RuntimeCosts::GetStorage {
596 len: limits::STORAGE_BYTES,
597 kind: access_kind,
598 })?;
599 let outcome = if transient {
600 self.ext.get_transient_storage(&key)
601 } else {
602 self.ext.get_storage(&key)
603 };
604 let len = outcome.as_ref().map(|v| v.len() as u32).unwrap_or(0);
605 self.adjust_gas(charged, RuntimeCosts::GetStorage { len, kind: access_kind });
606
607 if let Some(value) = outcome {
608 match read_mode {
609 StorageReadMode::FixedOutput32 => {
610 let mut fixed_output = [0u8; 32];
611 let len = value.len().min(fixed_output.len());
612 fixed_output[..len].copy_from_slice(&value[..len]);
613
614 self.write_fixed_sandbox_output(
615 memory,
616 out_ptr,
617 &fixed_output,
618 false,
619 already_charged,
620 )?;
621 Ok(ReturnErrorCode::Success)
622 },
623 StorageReadMode::VariableOutput { output_len_ptr: out_len_ptr } => {
624 self.write_sandbox_output(
625 memory,
626 out_ptr,
627 out_len_ptr,
628 &value,
629 false,
630 already_charged,
631 )?;
632 Ok(ReturnErrorCode::Success)
633 },
634 }
635 } else {
636 match read_mode {
637 StorageReadMode::FixedOutput32 => {
638 self.write_fixed_sandbox_output(
639 memory,
640 out_ptr,
641 &[0u8; 32],
642 false,
643 already_charged,
644 )?;
645 Ok(ReturnErrorCode::Success)
646 },
647 StorageReadMode::VariableOutput { .. } => Ok(ReturnErrorCode::KeyNotFound),
648 }
649 }
650 }
651
652 fn call(
653 &mut self,
654 memory: &mut M,
655 flags: CallFlags,
656 call_type: CallType,
657 callee_ptr: u32,
658 resources: &CallResources<E::T>,
659 input_data_ptr: u32,
660 input_data_len: u32,
661 output_ptr: u32,
662 output_len_ptr: u32,
663 ) -> Result<ReturnErrorCode, TrapReason> {
664 let callee = memory.read_h160(callee_ptr)?;
665 let precompile = <AllPrecompiles<E::T>>::get::<E>(&callee.as_fixed_bytes());
666 match &precompile {
667 Some(precompile) if precompile.has_contract_info() => {
668 self.charge_gas(RuntimeCosts::PrecompileWithInfoBase)?
669 },
670 Some(_) => self.charge_gas(RuntimeCosts::PrecompileBase)?,
671 None => self.charge_gas(call_type.cost())?,
672 };
673
674 if input_data_len > limits::CALLDATA_BYTES {
676 Err(<Error<E::T>>::CallDataTooLarge)?;
677 }
678
679 let input_data = if flags.contains(CallFlags::CLONE_INPUT) {
680 let input = self.input_data.as_ref().ok_or(Error::<E::T>::InputForwarded)?;
681 charge_gas!(self, RuntimeCosts::CallInputCloned(input.len() as u32))?;
682 input.clone()
683 } else if flags.contains(CallFlags::FORWARD_INPUT) {
684 self.input_data.take().ok_or(Error::<E::T>::InputForwarded)?
685 } else {
686 if precompile.is_some() {
687 self.charge_gas(RuntimeCosts::PrecompileDecode(input_data_len))?;
688 } else {
689 self.charge_gas(RuntimeCosts::CopyFromContract(input_data_len))?;
690 }
691 memory.read(input_data_ptr, input_data_len)?
692 };
693
694 memory.reset_interpreter_cache();
695
696 let call_outcome = match call_type {
697 CallType::Call { value_ptr } => {
698 let read_only = flags.contains(CallFlags::READ_ONLY);
699 let value = memory.read_u256(value_ptr)?;
700 if value > 0u32.into() {
701 if read_only || self.ext.is_read_only() {
704 return Err(Error::<E::T>::StateChangeDenied.into());
705 }
706
707 self.charge_gas(RuntimeCosts::CallTransferSurcharge {
708 dust_transfer: Pallet::<E::T>::has_dust(value),
709 })?;
710 }
711
712 let reentrancy = if flags.contains(CallFlags::ALLOW_REENTRY) {
713 ReentrancyProtection::AllowReentry
714 } else {
715 ReentrancyProtection::Strict
716 };
717
718 self.ext.call(resources, &callee, value, input_data, reentrancy, read_only)
719 },
720 CallType::DelegateCall => {
721 if flags.intersects(CallFlags::ALLOW_REENTRY | CallFlags::READ_ONLY) {
722 return Err(Error::<E::T>::InvalidCallFlags.into());
723 }
724 self.ext.delegate_call(resources, callee, input_data)
725 },
726 };
727
728 match call_outcome {
729 Ok(_) if flags.contains(CallFlags::TAIL_CALL) => {
732 let output = mem::take(self.ext.last_frame_output_mut());
733 return Err(TrapReason::Return(ReturnData {
734 flags: output.flags.bits(),
735 data: output.data,
736 }));
737 },
738 Ok(_) => {
739 let output = mem::take(self.ext.last_frame_output_mut());
740 let write_result = self.write_sandbox_output(
741 memory,
742 output_ptr,
743 output_len_ptr,
744 &output.data,
745 true,
746 |len| Some(RuntimeCosts::CopyToContract(len)),
747 );
748 *self.ext.last_frame_output_mut() = output;
749 write_result?;
750 Ok(self.ext.last_frame_output().into())
751 },
752 Err(err) => {
753 let error_code = super::exec_error_into_return_code::<E>(err)?;
754 memory.write(output_len_ptr, &0u32.to_le_bytes())?;
755 Ok(error_code)
756 },
757 }
758 }
759
760 fn instantiate(
761 &mut self,
762 memory: &mut M,
763 code_hash_ptr: u32,
764 weight: Weight,
765 deposit_ptr: u32,
766 value_ptr: u32,
767 input_data_ptr: u32,
768 input_data_len: u32,
769 address_ptr: u32,
770 output_ptr: u32,
771 output_len_ptr: u32,
772 salt_ptr: u32,
773 ) -> Result<ReturnErrorCode, TrapReason> {
774 let value = match memory.read_u256(value_ptr) {
775 Ok(value) => {
776 self.charge_gas(RuntimeCosts::Instantiate {
777 input_data_len,
778 balance_transfer: Pallet::<E::T>::has_balance(value),
779 dust_transfer: Pallet::<E::T>::has_dust(value),
780 })?;
781 value
782 },
783 Err(err) => {
784 self.charge_gas(RuntimeCosts::Instantiate {
785 input_data_len: 0,
786 balance_transfer: false,
787 dust_transfer: false,
788 })?;
789 return Err(err.into());
790 },
791 };
792 let deposit_limit: U256 = memory.read_u256(deposit_ptr)?;
793 let code_hash = memory.read_h256(code_hash_ptr)?;
794 if input_data_len > limits::CALLDATA_BYTES {
795 Err(<Error<E::T>>::CallDataTooLarge)?;
796 }
797 let input_data = memory.read(input_data_ptr, input_data_len)?;
798 let salt = if salt_ptr == SENTINEL {
799 None
800 } else {
801 let salt: [u8; 32] = memory.read_array(salt_ptr)?;
802 Some(salt)
803 };
804
805 memory.reset_interpreter_cache();
806
807 match self.ext.instantiate(
808 &CallResources::from_weight_and_deposit(weight, deposit_limit),
809 Code::Existing(code_hash),
810 value,
811 input_data,
812 salt.as_ref(),
813 ) {
814 Ok(address) => {
815 if !self.ext.last_frame_output().flags.contains(ReturnFlags::REVERT) {
816 self.write_fixed_sandbox_output(
817 memory,
818 address_ptr,
819 &address.as_bytes(),
820 true,
821 already_charged,
822 )?;
823 }
824 let output = mem::take(self.ext.last_frame_output_mut());
825 let write_result = self.write_sandbox_output(
826 memory,
827 output_ptr,
828 output_len_ptr,
829 &output.data,
830 true,
831 |len| Some(RuntimeCosts::CopyToContract(len)),
832 );
833 *self.ext.last_frame_output_mut() = output;
834 write_result?;
835 Ok(self.ext.last_frame_output().into())
836 },
837 Err(err) => Ok(super::exec_error_into_return_code::<E>(err)?),
838 }
839 }
840}
841
842impl<'a, E: Ext, M: ?Sized + Memory<E::T>> FrameTraceInfo for Runtime<'a, E, M> {
843 fn gas_left(&self) -> u64 {
844 let meter = self.ext.frame_meter();
845 meter.eth_gas_left().unwrap_or_default().try_into().unwrap_or_default()
846 }
847 fn weight_consumed(&self) -> Weight {
848 let meter = self.ext.frame_meter();
849 meter.weight_consumed()
850 }
851
852 fn last_frame_output(&self) -> crate::evm::Bytes {
853 crate::evm::Bytes(self.ext.last_frame_output().data.clone())
854 }
855}
856
857pub struct PreparedCall<'a, E: Ext> {
858 module: polkavm::Module,
859 instance: polkavm::RawInstance,
860 runtime: Runtime<'a, E, polkavm::RawInstance>,
861}
862
863impl<'a, E: Ext> PreparedCall<'a, E> {
864 pub fn call(mut self) -> ExecResult {
865 let exec_result = loop {
866 let interrupt = self.instance.run();
867 if let Some(exec_result) =
868 self.runtime.handle_interrupt(interrupt, &self.module, &mut self.instance)
869 {
870 break exec_result;
871 }
872 };
873 crate::tracing::if_tracing(|tracer| {
874 tracer.enter_ecall(crate::tracing::PVM_FUEL_NAME, &[], &self.runtime)
875 });
876 let sync_result =
877 self.runtime.ext().frame_meter_mut().sync_from_executor(self.instance.gas());
878 crate::tracing::if_tracing(|tracer| tracer.exit_step(&self.runtime, None));
879 sync_result?;
880 exec_result
881 }
882
883 #[cfg(feature = "runtime-benchmarks")]
885 pub fn aux_data_base(&self) -> u32 {
886 self.instance.module().memory_map().aux_data_address()
887 }
888
889 #[cfg(feature = "runtime-benchmarks")]
896 pub fn setup_aux_data(
897 &mut self,
898 data: &[u8],
899 offset: u32,
900 a1: u64,
901 ) -> frame_support::dispatch::DispatchResult {
902 let a0 = self.aux_data_base().saturating_add(offset);
903 self.instance.write_memory(a0, data).map_err(|err| {
904 log::debug!(target: LOG_TARGET, "failed to write aux data: {err:?}");
905 Error::<E::T>::CodeRejected
906 })?;
907 self.instance.set_reg(polkavm::Reg::A0, a0.into());
908 self.instance.set_reg(polkavm::Reg::A1, a1);
909 Ok(())
910 }
911}
912
913#[cfg(test)]
914mod tests {
915 use super::*;
916 use crate::tests::Test;
917
918 struct Unreadable;
919
920 impl Memory<Test> for Unreadable {
921 fn is_readable(&self, _ptr: u32, _len: u32) -> bool {
922 false
923 }
924
925 fn read_into_buf(&mut self, _ptr: u32, _buf: &mut [u8]) -> Result<(), DispatchError> {
926 unimplemented!()
927 }
928
929 fn write(&mut self, _ptr: u32, _buf: &[u8]) -> Result<(), DispatchError> {
930 unimplemented!()
931 }
932
933 fn zero(&mut self, _ptr: u32, _len: u32) -> Result<(), DispatchError> {
934 unimplemented!()
935 }
936
937 fn reset_interpreter_cache(&mut self) {}
938 }
939
940 #[test]
941 fn mem_read_early_return() {
942 assert_eq!(
943 Memory::<Test>::read(&mut Unreadable, 0, 1024 * 1024),
944 Err(Error::<Test>::OutOfBounds.into())
945 );
946 }
947}