Skip to content

Commit

Permalink
Minor readibility improvements (#476)
Browse files Browse the repository at this point in the history
* Improve readibility

* Address comments

---------

Co-authored-by: green <xgreenx9999@gmail.com>
  • Loading branch information
Dentosal and xgreenx authored Jun 9, 2023
1 parent 0b04b2d commit 6e76b6d
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 71 deletions.
33 changes: 23 additions & 10 deletions fuel-vm/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,26 @@ impl Call {
}
}

impl From<Call> for [u8; Call::LEN] {
fn from(val: Call) -> [u8; Call::LEN] {
let mut buf = [0u8; Call::LEN];
bytes::store_at(&mut buf, Call::layout(Call::LAYOUT.to), &val.to);
bytes::store_number_at(&mut buf, Call::layout(Call::LAYOUT.a), val.a);
bytes::store_number_at(&mut buf, Call::layout(Call::LAYOUT.b), val.b);
buf
}
}

impl From<[u8; Self::LEN]> for Call {
fn from(buf: [u8; Self::LEN]) -> Self {
let to = bytes::restore_at(&buf, Self::layout(Self::LAYOUT.to));
let a = bytes::restore_number_at(&buf, Self::layout(Self::LAYOUT.a));
let b = bytes::restore_number_at(&buf, Self::layout(Self::LAYOUT.b));

Self { to: to.into(), a, b }
}
}

impl SizedBytes for Call {
fn serialized_size(&self) -> usize {
Self::LEN
Expand All @@ -70,9 +90,8 @@ impl io::Read for Call {
.and_then(|slice| slice.try_into().ok())
.ok_or(bytes::eof())?;

bytes::store_at(buf, Self::layout(Self::LAYOUT.to), &self.to);
bytes::store_number_at(buf, Self::layout(Self::LAYOUT.a), self.a);
bytes::store_number_at(buf, Self::layout(Self::LAYOUT.b), self.b);
let bytes: [u8; Self::LEN] = (*self).into();
buf.copy_from_slice(&bytes);

Ok(Self::LEN)
}
Expand All @@ -85,13 +104,7 @@ impl io::Write for Call {
.and_then(|slice| slice.try_into().ok())
.ok_or(bytes::eof())?;

let to = bytes::restore_at(buf, Self::layout(Self::LAYOUT.to));
let a = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.a));
let b = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.b));

self.to = to.into();
self.a = a;
self.b = b;
*self = Self::from(*buf);

Ok(Self::LEN)
}
Expand Down
25 changes: 12 additions & 13 deletions fuel-vm/src/interpreter/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,12 +306,10 @@ impl<'vm, S, I> LoadContractCodeCtx<'vm, S, I> {
return Err(PanicReason::MemoryOverflow.into());
}

// compiler will optimize to memset
self.memory[memory_offset..memory_offset_end]
.iter_mut()
.for_each(|m| *m = 0);
// Clear memory
self.memory[memory_offset..memory_offset_end].fill(0);

// fetch the contract id
// Fetch the contract id
let contract_id: &[u8; ContractId::LEN] = &self.memory[contract_id..contract_id_end]
.try_into()
.expect("This can't fail, because we checked the bounds above.");
Expand Down Expand Up @@ -360,10 +358,14 @@ impl<'vm, S, I> LoadContractCodeCtx<'vm, S, I> {
let fp_code_size = add_usize(fp, CallFrame::code_size_offset());
let fp_code_size_end = add_usize(fp_code_size, WORD_SIZE);

if fp_code_size_end > self.memory.len() {
Err(PanicReason::MemoryOverflow)?;
}

let length = Word::from_be_bytes(
self.memory[fp_code_size..fp_code_size_end]
.try_into()
.map_err(|_| PanicReason::MemoryOverflow)?,
.expect("`fp_code_size_end` is `WORD_SIZE`"),
)
.checked_add(length as Word)
.ok_or(PanicReason::MemoryOverflow)?;
Expand Down Expand Up @@ -484,7 +486,7 @@ pub(crate) fn block_hash<S: InterpreterStorage>(
let height = u32::try_from(b).map_err(|_| PanicReason::ArithmeticOverflow)?.into();
let hash = storage.block_hash(height).map_err(|e| e.into())?;

try_mem_write(a as usize, hash.as_ref(), owner, memory)?;
try_mem_write(a, hash.as_ref(), owner, memory)?;

inc_pc(pc)
}
Expand All @@ -506,11 +508,8 @@ pub(crate) fn coinbase<S: InterpreterStorage>(
pc: RegMut<PC>,
a: Word,
) -> Result<(), RuntimeError> {
storage
.coinbase()
.map_err(RuntimeError::from_io)
.and_then(|data| try_mem_write(a as usize, data.as_ref(), owner, memory))?;

let coinbase = storage.coinbase().map_err(RuntimeError::from_io)?;
try_mem_write(a, coinbase.as_ref(), owner, memory)?;
inc_pc(pc)
}

Expand Down Expand Up @@ -541,7 +540,7 @@ where
.map_err(RuntimeError::from_io)?
.into_owned();

try_mem_write(a as usize, root.as_ref(), owner, memory)?;
try_mem_write(a, root.as_ref(), owner, memory)?;

inc_pc(pc)
}
Expand Down
2 changes: 1 addition & 1 deletion fuel-vm/src/interpreter/executors/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ where
let (a, b, c, d) = call.unpack();

// Enter call context
self.prepare_call(a, b, c, d)?;
self.prepare_call(r!(a), r!(b), r!(c), r!(d))?;
}

Instruction::CB(cb) => {
Expand Down
67 changes: 22 additions & 45 deletions fuel-vm/src/interpreter/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use fuel_storage::{StorageAsRef, StorageInspect, StorageRead, StorageSize};
use fuel_tx::{ConsensusParameters, PanicReason, Receipt, Script};
use fuel_types::bytes::SerializableVec;
use fuel_types::{AssetId, Bytes32, ContractId, Word};
use std::{cmp, io};
use std::cmp;

#[cfg(test)]
mod jump_tests;
Expand Down Expand Up @@ -275,12 +275,19 @@ where
S: InterpreterStorage,
Tx: ExecutableTransaction,
{
fn prepare_call_inner(&mut self, a: Word, b: Word, c: Word, d: Word) -> Result<(), RuntimeError> {
/// Prepare a call instruction for execution
pub(crate) fn prepare_call(
&mut self,
call_params_mem_address: Word,
amount_of_coins_to_forward: Word,
asset_id_mem_address: Word,
amount_of_gas_to_forward: Word,
) -> Result<(), RuntimeError> {
let params = PrepareCallParams {
call_params_mem_address: a,
amount_of_coins_to_forward: b,
asset_id_mem_address: c,
amount_of_gas_to_forward: d,
call_params_mem_address,
amount_of_coins_to_forward,
asset_id_mem_address,
amount_of_gas_to_forward,
};
let current_contract = current_contract(&self.context, self.registers.fp(), self.memory.as_ref())?.copied();
let memory = PrepareCallMemory::try_from((self.memory.as_mut(), &params))?;
Expand All @@ -305,48 +312,17 @@ where
}
.prepare_call()
}

/// Prepare a call instruction for execution
pub fn prepare_call(&mut self, ra: RegId, rb: RegId, rc: RegId, rd: RegId) -> Result<(), RuntimeError> {
const M: &str = "the provided id is not a valid register";

let a = self
.registers
.get(ra.to_u8() as usize)
.copied()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, M))?;

let b = self
.registers
.get(rb.to_u8() as usize)
.copied()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, M))?;

let c = self
.registers
.get(rc.to_u8() as usize)
.copied()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, M))?;

let d = self
.registers
.get(rd.to_u8() as usize)
.copied()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, M))?;

self.prepare_call_inner(a, b, c, d)
}
}

#[cfg_attr(test, derive(Default))]
struct PrepareCallParams {
/// A
/// Register A of input
pub call_params_mem_address: Word,
/// B
/// Register B of input
pub amount_of_coins_to_forward: Word,
/// C
/// Register C of input
pub asset_id_mem_address: Word,
/// D
/// Register D of input
pub amount_of_gas_to_forward: Word,
}

Expand Down Expand Up @@ -485,11 +461,12 @@ impl<'vm, S> PrepareCallCtx<'vm, S> {
self.memory.memory,
);

let sp = *self.registers.system_registers.sp;
set_frame_pointer(self.context, self.registers.system_registers.fp.as_mut(), sp);
let old_sp = *self.registers.system_registers.sp;
let new_sp = arith::checked_add_word(old_sp, len)?;

*self.registers.system_registers.sp = arith::checked_add_word(*self.registers.system_registers.sp, len)?;
*self.registers.system_registers.ssp = *self.registers.system_registers.sp;
set_frame_pointer(self.context, self.registers.system_registers.fp.as_mut(), old_sp);
*self.registers.system_registers.sp = new_sp;
*self.registers.system_registers.ssp = new_sp;

let code_frame_mem_range = MemoryRange::new(*self.registers.system_registers.fp, len)?;
let frame_end = write_call_to_memory(
Expand Down
2 changes: 2 additions & 0 deletions fuel-vm/src/interpreter/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use fuel_types::Word;
mod tests;

impl<S, Tx> Interpreter<S, Tx> {
/// Global remaining gas amount
pub(crate) fn remaining_gas(&self) -> Word {
self.registers[RegId::GGAS]
}
Expand All @@ -41,6 +42,7 @@ impl<S, Tx> Interpreter<S, Tx> {
dependent_gas_charge(cgas, ggas, profiler, gas_cost, arg)
}

/// Do a gas charge with the given amount, panicing when running out of gas.
pub(crate) fn gas_charge(&mut self, gas: Word) -> Result<(), RuntimeError> {
let current_contract = self.contract_id();
let SystemRegisters { pc, ggas, cgas, is, .. } = split_registers(&mut self.registers).0;
Expand Down
4 changes: 2 additions & 2 deletions fuel-vm/src/interpreter/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,8 +444,8 @@ impl OwnershipRegisters {
}
}

pub(crate) fn try_mem_write(
addr: usize,
pub(crate) fn try_mem_write<A: ToAddr>(
addr: A,
data: &[u8],
registers: OwnershipRegisters,
memory: &mut [u8; MEM_SIZE],
Expand Down

0 comments on commit 6e76b6d

Please sign in to comment.