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 environmental::environmental;
39use frame_support::{ensure, weights::Weight};
40use pallet_revive_uapi::{CallFlags, ReturnErrorCode, ReturnFlags, StorageFlags};
41use sp_core::{H160, H256, U256};
42use sp_runtime::DispatchError;
43
44pub fn extract_code_and_data(data: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
46 let blob_len = polkavm::ProgramBlob::blob_length(data)?;
47 let blob_len = blob_len.try_into().ok()?;
48 let (code, data) = data.split_at_checked(blob_len)?;
49 Some((code.to_vec(), data.to_vec()))
50}
51
52pub trait Memory<T: Config> {
59 fn read_into_buf(&mut self, ptr: u32, buf: &mut [u8]) -> Result<(), DispatchError>;
65
66 fn is_readable(&self, ptr: u32, len: u32) -> bool;
68
69 fn write(&mut self, ptr: u32, buf: &[u8]) -> Result<(), DispatchError>;
75
76 fn zero(&mut self, ptr: u32, len: u32) -> Result<(), DispatchError>;
82
83 fn with_caller_cache<R>(&mut self, f: impl FnOnce() -> R) -> R;
90
91 fn read(&mut self, ptr: u32, len: u32) -> Result<Vec<u8>, DispatchError> {
97 if !self.is_readable(ptr, len) {
98 return Err(Error::<T>::OutOfBounds.into());
99 }
100 let mut buf = vec![0u8; len as usize];
101 self.read_into_buf(ptr, buf.as_mut_slice())?;
102 Ok(buf)
103 }
104
105 fn read_array<const N: usize>(&mut self, ptr: u32) -> Result<[u8; N], DispatchError> {
107 let mut buf = [0u8; N];
108 self.read_into_buf(ptr, &mut buf)?;
109 Ok(buf)
110 }
111
112 fn read_u32(&mut self, ptr: u32) -> Result<u32, DispatchError> {
114 let buf: [u8; 4] = self.read_array(ptr)?;
115 Ok(u32::from_le_bytes(buf))
116 }
117
118 fn read_u256(&mut self, ptr: u32) -> Result<U256, DispatchError> {
120 let buf: [u8; 32] = self.read_array(ptr)?;
121 Ok(U256::from_little_endian(&buf))
122 }
123
124 fn read_h160(&mut self, ptr: u32) -> Result<H160, DispatchError> {
126 let mut buf = H160::default();
127 self.read_into_buf(ptr, buf.as_bytes_mut())?;
128 Ok(buf)
129 }
130
131 fn read_h256(&mut self, ptr: u32) -> Result<H256, DispatchError> {
133 let mut code_hash = H256::default();
134 self.read_into_buf(ptr, code_hash.as_bytes_mut())?;
135 Ok(code_hash)
136 }
137}
138
139pub trait PolkaVmInstance<T: Config>: Memory<T> {
145 fn gas(&self) -> polkavm::Gas;
146 fn set_gas(&mut self, gas: polkavm::Gas);
147 fn read_input_regs(&self) -> (u64, u64, u64, u64, u64, u64);
148 fn write_output(&mut self, output: u64);
149}
150
151#[cfg(feature = "runtime-benchmarks")]
158impl<T: Config> Memory<T> for [u8] {
159 fn is_readable(&self, ptr: u32, len: u32) -> bool {
160 (ptr as usize).checked_add(len as usize).is_some_and(|end| end <= self.len())
161 }
162
163 fn read_into_buf(&mut self, ptr: u32, buf: &mut [u8]) -> Result<(), DispatchError> {
164 let ptr = ptr as usize;
165 let bound_checked =
166 self.get(ptr..ptr + buf.len()).ok_or_else(|| Error::<T>::OutOfBounds)?;
167 buf.copy_from_slice(bound_checked);
168 Ok(())
169 }
170
171 fn write(&mut self, ptr: u32, buf: &[u8]) -> Result<(), DispatchError> {
172 let ptr = ptr as usize;
173 let bound_checked =
174 self.get_mut(ptr..ptr + buf.len()).ok_or_else(|| Error::<T>::OutOfBounds)?;
175 bound_checked.copy_from_slice(buf);
176 Ok(())
177 }
178
179 fn zero(&mut self, ptr: u32, len: u32) -> Result<(), DispatchError> {
180 <[u8] as Memory<T>>::write(self, ptr, &vec![0; len as usize])
181 }
182
183 fn with_caller_cache<R>(&mut self, f: impl FnOnce() -> R) -> R {
184 f()
185 }
186}
187
188impl<T: Config> Memory<T> for polkavm::RawInstance {
189 fn is_readable(&self, ptr: u32, len: u32) -> bool {
190 self.is_memory_accessible(ptr, len, polkavm::MemoryProtection::Read)
191 }
192
193 fn read_into_buf(&mut self, ptr: u32, buf: &mut [u8]) -> Result<(), DispatchError> {
194 self.read_memory_into(ptr, buf)
195 .map(|_| ())
196 .map_err(|_| Error::<T>::OutOfBounds.into())
197 }
198
199 fn write(&mut self, ptr: u32, buf: &[u8]) -> Result<(), DispatchError> {
200 self.write_memory(ptr, buf).map_err(|_| Error::<T>::OutOfBounds.into())
201 }
202
203 fn zero(&mut self, ptr: u32, len: u32) -> Result<(), DispatchError> {
204 self.zero_memory(ptr, len).map_err(|_| Error::<T>::OutOfBounds.into())
205 }
206
207 fn with_caller_cache<R>(&mut self, f: impl FnOnce() -> R) -> R {
208 caller_cache::using(self, f)
209 }
210}
211
212environmental!(caller_cache: polkavm::RawInstance);
213
214pub fn reset_caller_cache() -> Result<(), polkavm::Error> {
222 caller_cache::with(|instance| instance.reset_interpreter_cache()).unwrap_or(Ok(()))
223}
224
225impl<T: Config> PolkaVmInstance<T> for polkavm::RawInstance {
226 fn gas(&self) -> polkavm::Gas {
227 self.gas()
228 }
229
230 fn set_gas(&mut self, gas: polkavm::Gas) {
231 self.set_gas(gas)
232 }
233
234 fn read_input_regs(&self) -> (u64, u64, u64, u64, u64, u64) {
235 (
236 self.reg(polkavm::Reg::A0),
237 self.reg(polkavm::Reg::A1),
238 self.reg(polkavm::Reg::A2),
239 self.reg(polkavm::Reg::A3),
240 self.reg(polkavm::Reg::A4),
241 self.reg(polkavm::Reg::A5),
242 )
243 }
244
245 fn write_output(&mut self, output: u64) {
246 self.set_reg(polkavm::Reg::A0, output);
247 }
248}
249
250impl From<&ExecReturnValue> for ReturnErrorCode {
251 fn from(from: &ExecReturnValue) -> Self {
252 if from.flags.contains(ReturnFlags::REVERT) { Self::CalleeReverted } else { Self::Success }
253 }
254}
255
256#[derive(Debug)]
258pub struct ReturnData {
259 flags: u32,
262 data: Vec<u8>,
264}
265
266#[derive(Debug)]
273pub enum TrapReason {
274 SupervisorError(DispatchError),
277 Return(ReturnData),
279 Termination,
282}
283
284impl<T: Into<DispatchError>> From<T> for TrapReason {
285 fn from(from: T) -> Self {
286 Self::SupervisorError(from.into())
287 }
288}
289
290impl fmt::Display for TrapReason {
291 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
292 Ok(())
293 }
294}
295
296macro_rules! charge_gas {
301 ($runtime:expr, $costs:expr) => {{ $runtime.ext.frame_meter_mut().charge_weight_token($costs) }};
302}
303
304enum CallType {
306 Call { value_ptr: u32 },
308 DelegateCall,
311}
312
313impl CallType {
314 fn cost(&self) -> RuntimeCosts {
315 match self {
316 CallType::Call { .. } => RuntimeCosts::CallBase,
317 CallType::DelegateCall => RuntimeCosts::DelegateCallBase,
318 }
319 }
320}
321
322fn already_charged(_: u32) -> Option<RuntimeCosts> {
326 None
327}
328
329fn extract_hi_lo(reg: u64) -> (u32, u32) {
331 ((reg >> 32) as u32, reg as u32)
332}
333
334enum StorageValue {
336 Memory { ptr: u32, len: u32 },
340
341 Value(Vec<u8>),
345}
346
347enum StorageReadMode {
349 VariableOutput { output_len_ptr: u32 },
352 FixedOutput32,
355}
356
357pub struct Runtime<'a, E: Ext, M: ?Sized> {
359 ext: &'a mut E,
360 input_data: Option<Vec<u8>>,
361 _phantom_data: PhantomData<M>,
362}
363
364impl<'a, E: Ext, M: ?Sized + Memory<E::T>> Runtime<'a, E, M> {
365 pub fn new(ext: &'a mut E, input_data: Vec<u8>) -> Self {
366 Self { ext, input_data: Some(input_data), _phantom_data: Default::default() }
367 }
368
369 pub fn ext(&mut self) -> &mut E {
371 self.ext
372 }
373
374 fn charge_gas(&mut self, costs: RuntimeCosts) -> Result<ChargedAmount, DispatchError> {
378 charge_gas!(self, costs)
379 }
380
381 fn adjust_gas(&mut self, charged: ChargedAmount, actual_costs: RuntimeCosts) {
386 self.ext.frame_meter_mut().adjust_weight(charged, actual_costs);
387 }
388
389 pub fn write_sandbox_output(
410 &mut self,
411 memory: &mut M,
412 out_ptr: u32,
413 out_len_ptr: u32,
414 buf: &[u8],
415 allow_skip: bool,
416 create_token: impl FnOnce(u32) -> Option<RuntimeCosts>,
417 ) -> Result<(), DispatchError> {
418 if allow_skip && out_ptr == SENTINEL {
419 return Ok(());
420 }
421
422 let len = memory.read_u32(out_len_ptr)?;
423 let buf_len = len.min(buf.len() as u32);
424
425 if let Some(costs) = create_token(buf_len) {
426 self.charge_gas(costs)?;
427 }
428
429 memory.write(out_ptr, &buf[..buf_len as usize])?;
430 memory.write(out_len_ptr, &buf_len.encode())
431 }
432
433 pub fn write_fixed_sandbox_output(
435 &mut self,
436 memory: &mut M,
437 out_ptr: u32,
438 buf: &[u8],
439 allow_skip: bool,
440 create_token: impl FnOnce(u32) -> Option<RuntimeCosts>,
441 ) -> Result<(), DispatchError> {
442 if buf.is_empty() || (allow_skip && out_ptr == SENTINEL) {
443 return Ok(());
444 }
445
446 let buf_len = buf.len() as u32;
447 if let Some(costs) = create_token(buf_len) {
448 self.charge_gas(costs)?;
449 }
450
451 memory.write(out_ptr, buf)
452 }
453
454 fn compute_hash_on_intermediate_buffer<F, R>(
467 &self,
468 memory: &mut M,
469 hash_fn: F,
470 input_ptr: u32,
471 input_len: u32,
472 output_ptr: u32,
473 ) -> Result<(), DispatchError>
474 where
475 F: FnOnce(&[u8]) -> R,
476 R: AsRef<[u8]>,
477 {
478 let input = memory.read(input_ptr, input_len)?;
480 let hash = hash_fn(&input);
482 memory.write(output_ptr, hash.as_ref())?;
484 Ok(())
485 }
486
487 fn decode_key(&self, memory: &mut M, key_ptr: u32, key_len: u32) -> Result<Key, TrapReason> {
488 let res = match key_len {
489 SENTINEL => {
490 let mut buffer = [0u8; 32];
491 memory.read_into_buf(key_ptr, buffer.as_mut())?;
492 Ok(Key::from_fixed(buffer))
493 },
494 len => {
495 ensure!(len <= limits::STORAGE_KEY_BYTES, Error::<E::T>::DecodingFailed);
496 let key = memory.read(key_ptr, len)?;
497 Key::try_from_var(key)
498 },
499 };
500
501 res.map_err(|_| Error::<E::T>::DecodingFailed.into())
502 }
503
504 fn is_transient(flags: u32) -> Result<bool, TrapReason> {
505 StorageFlags::from_bits(flags)
506 .ok_or_else(|| <Error<E::T>>::InvalidStorageFlags.into())
507 .map(|flags| flags.contains(StorageFlags::TRANSIENT))
508 }
509
510 fn set_storage(
511 &mut self,
512 memory: &mut M,
513 flags: u32,
514 key_ptr: u32,
515 key_len: u32,
516 value: StorageValue,
517 ) -> Result<u32, TrapReason> {
518 let transient = Self::is_transient(flags)?;
519
520 let value_len = match &value {
521 StorageValue::Memory { ptr: _, len } => *len,
522 StorageValue::Value(data) => data.len() as u32,
523 };
524
525 let max_size = limits::STORAGE_BYTES;
526 let key = self.decode_key(memory, key_ptr, key_len)?;
527
528 if value_len > max_size {
529 let access_kind =
531 StorageAccessKind::new(transient, || self.ext.peek_storage_access(&key));
532 self.charge_gas(RuntimeCosts::SetStorage {
533 new_bytes: value_len,
534 old_bytes: max_size,
535 kind: access_kind,
536 })?;
537 return Err(Error::<E::T>::ValueTooLarge.into());
538 }
539
540 let access_kind = StorageAccessKind::new(transient, || {
541 self.ext.touch_storage_access(&key, StorageOp::Write)
542 });
543 let charged = self.charge_gas(RuntimeCosts::SetStorage {
544 new_bytes: value_len,
545 old_bytes: max_size,
546 kind: access_kind,
547 })?;
548 let value = match value {
549 StorageValue::Memory { ptr, len } => Some(memory.read(ptr, len)?),
550 StorageValue::Value(data) => Some(data),
551 };
552
553 let write_outcome = if transient {
554 self.ext.set_transient_storage(&key, value, false)?
555 } else {
556 self.ext.set_storage(&key, value, false)?
557 };
558
559 self.adjust_gas(
560 charged,
561 RuntimeCosts::SetStorage {
562 new_bytes: value_len,
563 old_bytes: write_outcome.old_len(),
564 kind: access_kind,
565 },
566 );
567 Ok(write_outcome.old_len_with_sentinel())
568 }
569
570 fn clear_storage(
571 &mut self,
572 memory: &mut M,
573 flags: u32,
574 key_ptr: u32,
575 key_len: u32,
576 ) -> Result<u32, TrapReason> {
577 let transient = Self::is_transient(flags)?;
578 let key = self.decode_key(memory, key_ptr, key_len)?;
579 let access_kind = StorageAccessKind::new(transient, || {
580 self.ext.touch_storage_access(&key, StorageOp::Write)
581 });
582 let charged = self.charge_gas(RuntimeCosts::ClearStorage {
583 len: limits::STORAGE_BYTES,
584 kind: access_kind,
585 })?;
586 let outcome = if transient {
587 self.ext.set_transient_storage(&key, None, false)?
588 } else {
589 self.ext.set_storage(&key, None, false)?
590 };
591 self.adjust_gas(
592 charged,
593 RuntimeCosts::ClearStorage { len: outcome.old_len(), kind: access_kind },
594 );
595 Ok(outcome.old_len_with_sentinel())
596 }
597
598 fn get_storage(
599 &mut self,
600 memory: &mut M,
601 flags: u32,
602 key_ptr: u32,
603 key_len: u32,
604 out_ptr: u32,
605 read_mode: StorageReadMode,
606 ) -> Result<ReturnErrorCode, TrapReason> {
607 let transient = Self::is_transient(flags)?;
608 let key = self.decode_key(memory, key_ptr, key_len)?;
609 let access_kind = StorageAccessKind::new(transient, || {
610 self.ext.touch_storage_access(&key, StorageOp::Read)
611 });
612 let charged = self.charge_gas(RuntimeCosts::GetStorage {
613 len: limits::STORAGE_BYTES,
614 kind: access_kind,
615 })?;
616 let outcome = if transient {
617 self.ext.get_transient_storage(&key)
618 } else {
619 self.ext.get_storage(&key)
620 };
621 let len = outcome.as_ref().map(|v| v.len() as u32).unwrap_or(0);
622 self.adjust_gas(charged, RuntimeCosts::GetStorage { len, kind: access_kind });
623
624 if let Some(value) = outcome {
625 match read_mode {
626 StorageReadMode::FixedOutput32 => {
627 let mut fixed_output = [0u8; 32];
628 let len = value.len().min(fixed_output.len());
629 fixed_output[..len].copy_from_slice(&value[..len]);
630
631 self.write_fixed_sandbox_output(
632 memory,
633 out_ptr,
634 &fixed_output,
635 false,
636 already_charged,
637 )?;
638 Ok(ReturnErrorCode::Success)
639 },
640 StorageReadMode::VariableOutput { output_len_ptr: out_len_ptr } => {
641 self.write_sandbox_output(
642 memory,
643 out_ptr,
644 out_len_ptr,
645 &value,
646 false,
647 already_charged,
648 )?;
649 Ok(ReturnErrorCode::Success)
650 },
651 }
652 } else {
653 match read_mode {
654 StorageReadMode::FixedOutput32 => {
655 self.write_fixed_sandbox_output(
656 memory,
657 out_ptr,
658 &[0u8; 32],
659 false,
660 already_charged,
661 )?;
662 Ok(ReturnErrorCode::Success)
663 },
664 StorageReadMode::VariableOutput { .. } => Ok(ReturnErrorCode::KeyNotFound),
665 }
666 }
667 }
668
669 fn call(
670 &mut self,
671 memory: &mut M,
672 flags: CallFlags,
673 call_type: CallType,
674 callee_ptr: u32,
675 resources: &CallResources<E::T>,
676 input_data_ptr: u32,
677 input_data_len: u32,
678 output_ptr: u32,
679 output_len_ptr: u32,
680 ) -> Result<ReturnErrorCode, TrapReason> {
681 let callee = memory.read_h160(callee_ptr)?;
682 let precompile = <AllPrecompiles<E::T>>::get::<E>(&callee.as_fixed_bytes());
683 match &precompile {
684 Some(precompile) if precompile.has_contract_info() => {
685 self.charge_gas(RuntimeCosts::PrecompileWithInfoBase)?
686 },
687 Some(_) => self.charge_gas(RuntimeCosts::PrecompileBase)?,
688 None => self.charge_gas(call_type.cost())?,
689 };
690
691 if input_data_len > limits::CALLDATA_BYTES {
693 Err(<Error<E::T>>::CallDataTooLarge)?;
694 }
695
696 let input_data = if flags.contains(CallFlags::CLONE_INPUT) {
697 let input = self.input_data.as_ref().ok_or(Error::<E::T>::InputForwarded)?;
698 charge_gas!(self, RuntimeCosts::CallInputCloned(input.len() as u32))?;
699 input.clone()
700 } else if flags.contains(CallFlags::FORWARD_INPUT) {
701 self.input_data.take().ok_or(Error::<E::T>::InputForwarded)?
702 } else {
703 if precompile.is_some() {
704 self.charge_gas(RuntimeCosts::PrecompileDecode(input_data_len))?;
705 } else {
706 self.charge_gas(RuntimeCosts::CopyFromContract(input_data_len))?;
707 }
708 memory.read(input_data_ptr, input_data_len)?
709 };
710
711 let call_outcome = match call_type {
712 CallType::Call { value_ptr } => {
713 let read_only = flags.contains(CallFlags::READ_ONLY);
714 let value = memory.read_u256(value_ptr)?;
715 if value > 0u32.into() {
716 if read_only || self.ext.is_read_only() {
719 return Err(Error::<E::T>::StateChangeDenied.into());
720 }
721
722 self.charge_gas(RuntimeCosts::CallTransferSurcharge {
723 dust_transfer: Pallet::<E::T>::has_dust(value),
724 })?;
725 }
726
727 let reentrancy = if flags.contains(CallFlags::ALLOW_REENTRY) {
728 ReentrancyProtection::AllowReentry
729 } else {
730 ReentrancyProtection::Strict
731 };
732
733 memory.with_caller_cache(|| {
734 self.ext.call(resources, &callee, value, input_data, reentrancy, read_only)
735 })
736 },
737 CallType::DelegateCall => {
738 if flags.intersects(CallFlags::ALLOW_REENTRY | CallFlags::READ_ONLY) {
739 return Err(Error::<E::T>::InvalidCallFlags.into());
740 }
741 memory.with_caller_cache(|| self.ext.delegate_call(resources, callee, input_data))
742 },
743 };
744
745 match call_outcome {
746 Ok(_) if flags.contains(CallFlags::TAIL_CALL) => {
749 let output = mem::take(self.ext.last_frame_output_mut());
750 return Err(TrapReason::Return(ReturnData {
751 flags: output.flags.bits(),
752 data: output.data,
753 }));
754 },
755 Ok(_) => {
756 let output = mem::take(self.ext.last_frame_output_mut());
757 let write_result = self.write_sandbox_output(
758 memory,
759 output_ptr,
760 output_len_ptr,
761 &output.data,
762 true,
763 |len| Some(RuntimeCosts::CopyToContract(len)),
764 );
765 *self.ext.last_frame_output_mut() = output;
766 write_result?;
767 Ok(self.ext.last_frame_output().into())
768 },
769 Err(err) => {
770 let error_code = super::exec_error_into_return_code::<E>(err)?;
771 memory.write(output_len_ptr, &0u32.to_le_bytes())?;
772 Ok(error_code)
773 },
774 }
775 }
776
777 fn instantiate(
778 &mut self,
779 memory: &mut M,
780 code_hash_ptr: u32,
781 weight: Weight,
782 deposit_ptr: u32,
783 value_ptr: u32,
784 input_data_ptr: u32,
785 input_data_len: u32,
786 address_ptr: u32,
787 output_ptr: u32,
788 output_len_ptr: u32,
789 salt_ptr: u32,
790 ) -> Result<ReturnErrorCode, TrapReason> {
791 let value = match memory.read_u256(value_ptr) {
792 Ok(value) => {
793 self.charge_gas(RuntimeCosts::Instantiate {
794 input_data_len,
795 balance_transfer: Pallet::<E::T>::has_balance(value),
796 dust_transfer: Pallet::<E::T>::has_dust(value),
797 })?;
798 value
799 },
800 Err(err) => {
801 self.charge_gas(RuntimeCosts::Instantiate {
802 input_data_len: 0,
803 balance_transfer: false,
804 dust_transfer: false,
805 })?;
806 return Err(err.into());
807 },
808 };
809 let deposit_limit: U256 = memory.read_u256(deposit_ptr)?;
810 let code_hash = memory.read_h256(code_hash_ptr)?;
811 if input_data_len > limits::CALLDATA_BYTES {
812 Err(<Error<E::T>>::CallDataTooLarge)?;
813 }
814 let input_data = memory.read(input_data_ptr, input_data_len)?;
815 let salt = if salt_ptr == SENTINEL {
816 None
817 } else {
818 let salt: [u8; 32] = memory.read_array(salt_ptr)?;
819 Some(salt)
820 };
821
822 let instantiate_outcome = memory.with_caller_cache(|| {
823 self.ext.instantiate(
824 &CallResources::from_weight_and_deposit(weight, deposit_limit),
825 Code::Existing(code_hash),
826 value,
827 input_data,
828 salt.as_ref(),
829 )
830 });
831 match instantiate_outcome {
832 Ok(address) => {
833 if !self.ext.last_frame_output().flags.contains(ReturnFlags::REVERT) {
834 self.write_fixed_sandbox_output(
835 memory,
836 address_ptr,
837 &address.as_bytes(),
838 true,
839 already_charged,
840 )?;
841 }
842 let output = mem::take(self.ext.last_frame_output_mut());
843 let write_result = self.write_sandbox_output(
844 memory,
845 output_ptr,
846 output_len_ptr,
847 &output.data,
848 true,
849 |len| Some(RuntimeCosts::CopyToContract(len)),
850 );
851 *self.ext.last_frame_output_mut() = output;
852 write_result?;
853 Ok(self.ext.last_frame_output().into())
854 },
855 Err(err) => Ok(super::exec_error_into_return_code::<E>(err)?),
856 }
857 }
858}
859
860impl<'a, E: Ext, M: ?Sized + Memory<E::T>> FrameTraceInfo for Runtime<'a, E, M> {
861 fn gas_left(&self) -> u64 {
862 let meter = self.ext.frame_meter();
863 meter.eth_gas_left().unwrap_or_default().try_into().unwrap_or_default()
864 }
865 fn weight_consumed(&self) -> Weight {
866 let meter = self.ext.frame_meter();
867 meter.weight_consumed()
868 }
869
870 fn last_frame_output(&self) -> crate::evm::Bytes {
871 crate::evm::Bytes(self.ext.last_frame_output().data.clone())
872 }
873}
874
875pub struct PreparedCall<'a, E: Ext> {
876 module: polkavm::Module,
877 instance: polkavm::RawInstance,
878 runtime: Runtime<'a, E, polkavm::RawInstance>,
879}
880
881impl<'a, E: Ext> PreparedCall<'a, E> {
882 pub fn call(mut self) -> ExecResult {
883 let exec_result = loop {
884 let interrupt = self.instance.run();
885 if let Some(exec_result) =
886 self.runtime.handle_interrupt(interrupt, &self.module, &mut self.instance)
887 {
888 break exec_result;
889 }
890 };
891 crate::tracing::if_tracing(|tracer| {
892 tracer.enter_ecall(crate::tracing::PVM_FUEL_NAME, &[], &self.runtime)
893 });
894 let sync_result =
895 self.runtime.ext().frame_meter_mut().sync_from_executor(self.instance.gas());
896 crate::tracing::if_tracing(|tracer| tracer.exit_step(&self.runtime, None));
897 sync_result?;
898 exec_result
899 }
900}
901
902#[cfg(feature = "runtime-benchmarks")]
904impl<'a, E: Ext> PreparedCall<'a, E> {
905 pub fn memory_map(&self) -> &polkavm::MemoryMap {
907 self.instance.module().memory_map()
908 }
909
910 pub fn write_memory(
912 &mut self,
913 address: u32,
914 data: &[u8],
915 ) -> frame_support::dispatch::DispatchResult {
916 self.instance.write_memory(address, data).map_err(|err| {
917 log::debug!(target: LOG_TARGET, "failed to write memory: {err:?}");
918 Error::<E::T>::CodeRejected.into()
919 })
920 }
921
922 pub fn set_reg(&mut self, reg: polkavm::Reg, value: u64) {
924 self.instance.set_reg(reg, value);
925 }
926
927 pub fn reset_interpreter_cache(&mut self) -> Result<(), DispatchError> {
932 self.instance.reset_interpreter_cache().map_err(|err| {
933 log::error!(target: LOG_TARGET, "failed to reset the interpreter cache: {err}");
934 Error::<E::T>::ExecutionFailed.into()
935 })
936 }
937}
938
939#[cfg(test)]
940mod tests {
941 use super::*;
942 use crate::tests::Test;
943
944 struct Unreadable;
945
946 impl Memory<Test> for Unreadable {
947 fn is_readable(&self, _ptr: u32, _len: u32) -> bool {
948 false
949 }
950
951 fn read_into_buf(&mut self, _ptr: u32, _buf: &mut [u8]) -> Result<(), DispatchError> {
952 unimplemented!()
953 }
954
955 fn write(&mut self, _ptr: u32, _buf: &[u8]) -> Result<(), DispatchError> {
956 unimplemented!()
957 }
958
959 fn zero(&mut self, _ptr: u32, _len: u32) -> Result<(), DispatchError> {
960 unimplemented!()
961 }
962
963 fn with_caller_cache<R>(&mut self, _f: impl FnOnce() -> R) -> R {
964 unimplemented!()
965 }
966 }
967
968 #[test]
969 fn mem_read_early_return() {
970 assert_eq!(
971 Memory::<Test>::read(&mut Unreadable, 0, 1024 * 1024),
972 Err(Error::<Test>::OutOfBounds.into())
973 );
974 }
975}