Skip to content

Commit

Permalink
fix: Fix build errors on wasm32 target with no_std (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
conr2d authored Dec 31, 2024
1 parent 288fecf commit 586bfc7
Show file tree
Hide file tree
Showing 26 changed files with 124 additions and 56 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ derive-where = "1.2"
eager = "0.1.0"
enum-iterator = "1.5.0"
ethereum = { version = "0.15.0", default-features = false }
getrandom = { version = "0.2", default-features = false }
hex-literal = "0.4"
itertools = { version = "0.12.1", default-features = false }
k256 = { version = "0.13", default-features = false }
Expand Down
4 changes: 4 additions & 0 deletions frame/solana/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ solana-sdk = { workspace = true, features = ["full", "scale"] }
solana-system-program = { workspace = true }
solana_rbpf = { workspace = true }

# workaround
getrandom = { workspace = true, features = ["custom"] }

[dev-dependencies]
assert_matches = { workspace = true }
libsecp256k1 = { workspace = true, default-features = true }
Expand All @@ -62,6 +65,7 @@ std = [
"parity-scale-codec/std",
"scale-info/std",
"serde/std",
"solana-address-lookup-table-program/std",
"solana-bpf-loader-program/std",
"solana-compute-budget/std",
"solana-compute-budget-program/std",
Expand Down
2 changes: 1 addition & 1 deletion frame/solana/src/runtime/bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use frame_support::{
BoundedVec,
};
use frame_system::pallet_prelude::BlockNumberFor;
use nostd::{marker::PhantomData, sync::Arc};
use nostd::{marker::PhantomData, prelude::*, sync::Arc};
use np_runtime::traits::LateInit;
use solana_program_runtime::loaded_programs::ProgramCacheEntry;
use solana_sdk::{
Expand Down
1 change: 1 addition & 0 deletions frame/solana/src/svm/account_rent_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ impl RentState {
}

fn submit_rent_state_metrics(pre_rent_state: &Self, post_rent_state: &Self) {
#[cfg(feature = "std")]
match (pre_rent_state, post_rent_state) {
(&RentState::Uninitialized, &RentState::RentPaying { .. }) => {
inc_new_counter_info!("rent_paying_err-new_account", 1);
Expand Down
1 change: 1 addition & 0 deletions frame/solana/src/svm/message_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use nostd::prelude::*;
use solana_measure::measure::Measure;
use solana_program_runtime::{
invoke_context::InvokeContext,
Expand Down
4 changes: 2 additions & 2 deletions frame/solana/src/svm/program_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
// limitations under the License.

use crate::svm::transaction_processing_callback::TransactionProcessingCallback;
use nostd::sync::Arc;
use nostd::{prelude::*, sync::Arc};
use solana_program_runtime::{
loaded_programs::{
LoadProgramMetrics, ProgramCacheEntry, ProgramCacheEntryOwner, ProgramCacheEntryType,
Expand Down Expand Up @@ -53,7 +53,7 @@ pub(crate) fn load_program_from_bytes(
deployment_slot: Slot,
program_runtime_environment: ProgramRuntimeEnvironment,
reloading: bool,
) -> std::result::Result<ProgramCacheEntry, Box<dyn std::error::Error>> {
) -> core::result::Result<ProgramCacheEntry, Box<dyn core::error::Error>> {
if reloading {
// Safety: this is safe because the program is being reloaded in the cache.
unsafe {
Expand Down
1 change: 1 addition & 0 deletions frame/solana/src/svm/transaction_account_state_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
// limitations under the License.

use crate::svm::account_rent_state::RentState;
use nostd::prelude::*;
use solana_sdk::{
account::ReadableAccount,
message::SanitizedMessage,
Expand Down
2 changes: 1 addition & 1 deletion frame/solana/src/svm/transaction_results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
// limitations under the License.

// Re-exported since these have moved to `solana_sdk`.
use nostd::{collections::BTreeMap, sync::Arc};
use nostd::{collections::BTreeMap, prelude::*, sync::Arc};
use serde::{Deserialize, Serialize};
use solana_program_runtime::loaded_programs::ProgramCacheEntry;
#[deprecated(
Expand Down
5 changes: 4 additions & 1 deletion vendor/solana/curves/curve25519/src/edwards.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use bytemuck_derive::{Pod, Zeroable};
pub use target_arch::*;
use {
alloc::vec::Vec,
bytemuck_derive::{Pod, Zeroable},
};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Pod, Zeroable)]
#[repr(transparent)]
Expand Down
2 changes: 2 additions & 0 deletions vendor/solana/curves/curve25519/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
#![allow(clippy::arithmetic_side_effects, clippy::op_ref)]
//! Syscall operations for curve25519
extern crate alloc;

pub mod curve_syscall_traits;
pub mod edwards;
pub mod errors;
Expand Down
5 changes: 4 additions & 1 deletion vendor/solana/curves/curve25519/src/ristretto.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use bytemuck_derive::{Pod, Zeroable};
pub use target_arch::*;
use {
alloc::vec::Vec,
bytemuck_derive::{Pod, Zeroable},
};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Pod, Zeroable)]
#[repr(transparent)]
Expand Down
3 changes: 2 additions & 1 deletion vendor/solana/program-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ solana-compute-budget = { workspace = true }
solana-frozen-abi = { workspace = true, optional = true }
solana-frozen-abi-macro = { workspace = true, optional = true }
solana-measure = { workspace = true }
solana-metrics = { workspace = true }
solana-metrics = { workspace = true, optional = true }
solana-sdk = { workspace = true }
#solana-type-overrides = { workspace = true }
#solana-vote = { workspace = true }
Expand Down Expand Up @@ -62,6 +62,7 @@ std = [
"serde/std",
"solana-compute-budget/std",
"solana-measure/std",
"solana-metrics",
"solana-sdk/std",
"solana_rbpf/std",
"thiserror/std",
Expand Down
5 changes: 3 additions & 2 deletions vendor/solana/program-runtime/src/invoke_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use {
nostd::{
alloc::Layout,
cell::RefCell,
prelude::*,
rc::Rc,
sync::{atomic::Ordering, Arc},
},
Expand Down Expand Up @@ -571,7 +572,7 @@ impl<'a> InvokeContext<'a> {
}

/// Consume compute units
pub fn consume_checked(&self, amount: u64) -> Result<(), Box<dyn std::error::Error>> {
pub fn consume_checked(&self, amount: u64) -> Result<(), Box<dyn core::error::Error>> {
let mut compute_meter = self.compute_meter.borrow_mut();
let exceeded = *compute_meter < amount;
*compute_meter = compute_meter.saturating_sub(amount);
Expand Down Expand Up @@ -650,7 +651,7 @@ impl<'a> InvokeContext<'a> {
pub fn get_syscall_context(&self) -> Result<&SyscallContext, InstructionError> {
self.syscall_context
.last()
.and_then(std::option::Option::as_ref)
.and_then(Option::as_ref)
.ok_or(InstructionError::CallDepth)
}

Expand Down
2 changes: 2 additions & 0 deletions vendor/solana/program-runtime/src/loaded_programs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use {
},
nostd::{
collections::BTreeMap,
prelude::*,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
Expand Down Expand Up @@ -202,6 +203,7 @@ impl LoadProgramMetrics {
saturating_add_assign!(timings.create_executor_load_elf_us, self.load_elf_us);
saturating_add_assign!(timings.create_executor_verify_code_us, self.verify_code_us);
saturating_add_assign!(timings.create_executor_jit_compile_us, self.jit_compile_us);
#[cfg(feature = "std")]
datapoint_trace!(
"create_executor_trace",
("program_id", self.program_id, String),
Expand Down
1 change: 1 addition & 0 deletions vendor/solana/programs/address-lookup-table/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(incomplete_features)]
#![cfg_attr(RUSTC_WITH_SPECIALIZATION, feature(specialization))]

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use {
core::convert::TryFrom,
nostd::prelude::*,
solana_program_runtime::{declare_process_instruction, ic_msg, invoke_context::InvokeContext},
solana_sdk::{
address_lookup_table::{
Expand Down
3 changes: 3 additions & 0 deletions vendor/solana/programs/bpf_loader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ solana-sdk = { workspace = true }
solana_rbpf = { workspace = true }
thiserror = { workspace = true }

# workaround
lazy_static = { version = "1.5", default-features = false, features = ["spin"] }

[dev-dependencies]
assert_matches = { workspace = true }
memoffset = { workspace = true }
Expand Down
31 changes: 21 additions & 10 deletions vendor/solana/programs/bpf_loader/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@
pub mod serialization;
pub mod syscalls;

#[cfg(not(feature = "std"))]
mod single_thread;
#[cfg(not(feature = "std"))]
use single_thread::LocalKey;
use {
nostd::{
cell::RefCell,
mem,
prelude::*,
rc::Rc,
sync::{atomic::Ordering, Arc},
},
Expand Down Expand Up @@ -61,10 +66,16 @@ pub const DEFAULT_LOADER_COMPUTE_UNITS: u64 = 570;
pub const DEPRECATED_LOADER_COMPUTE_UNITS: u64 = 1_140;
pub const UPGRADEABLE_LOADER_COMPUTE_UNITS: u64 = 2_370;

#[cfg(feature = "std")]
thread_local! {
pub static MEMORY_POOL: RefCell<VmMemoryPool> = RefCell::new(VmMemoryPool::new());
}

#[cfg(not(feature = "std"))]
lazy_static::lazy_static! {
pub static ref MEMORY_POOL: LocalKey<VmMemoryPool> = LocalKey::new(VmMemoryPool::new());
}

#[allow(clippy::too_many_arguments)]
pub fn load_program_from_bytes(
log_collector: Option<Rc<RefCell<LogCollector>>>,
Expand Down Expand Up @@ -252,7 +263,7 @@ pub fn create_vm<'a, 'b>(
invoke_context: &'a mut InvokeContext<'b>,
stack: &mut [u8],
heap: &mut [u8],
) -> Result<EbpfVm<'a, InvokeContext<'b>>, Box<dyn std::error::Error>> {
) -> Result<EbpfVm<'a, InvokeContext<'b>>, Box<dyn core::error::Error>> {
let stack_size = stack.len();
let heap_size = heap.len();
let accounts = Rc::clone(invoke_context.transaction_context.accounts());
Expand Down Expand Up @@ -358,7 +369,7 @@ fn create_memory_mapping<'a, 'b, C: ContextObject>(
heap: &'b mut [u8],
additional_regions: Vec<MemoryRegion>,
cow_cb: Option<MemoryCowCallback>,
) -> Result<MemoryMapping<'a>, Box<dyn std::error::Error>> {
) -> Result<MemoryMapping<'a>, Box<dyn core::error::Error>> {
let config = executable.get_config();
let sbpf_version = executable.get_sbpf_version();
let regions: Vec<MemoryRegion> = vec![
Expand Down Expand Up @@ -395,14 +406,14 @@ declare_builtin_function!(
_arg3: u64,
_arg4: u64,
_memory_mapping: &mut MemoryMapping,
) -> Result<u64, Box<dyn std::error::Error>> {
) -> Result<u64, Box<dyn core::error::Error>> {
process_instruction_inner(invoke_context)
}
);

pub fn process_instruction_inner(
invoke_context: &mut InvokeContext,
) -> Result<u64, Box<dyn std::error::Error>> {
) -> Result<u64, Box<dyn core::error::Error>> {
let log_collector = invoke_context.get_log_collector();
let transaction_context = &invoke_context.transaction_context;
let instruction_context = transaction_context.get_current_instruction_context()?;
Expand Down Expand Up @@ -432,7 +443,7 @@ pub fn process_instruction_inner(
Err(InstructionError::IncorrectProgramId)
}
.map(|_| 0)
.map_err(|error| Box::new(error) as Box<dyn std::error::Error>);
.map_err(|error| Box::new(error) as Box<dyn core::error::Error>);
}

// Program Invocation
Expand Down Expand Up @@ -462,10 +473,10 @@ pub fn process_instruction_inner(
| ProgramCacheEntryType::Closed
| ProgramCacheEntryType::DelayVisibility => {
ic_logger_msg!(log_collector, "Program is not deployed");
Err(Box::new(InstructionError::InvalidAccountData) as Box<dyn std::error::Error>)
Err(Box::new(InstructionError::InvalidAccountData) as Box<dyn core::error::Error>)
}
ProgramCacheEntryType::Loaded(executable) => execute(executable, invoke_context),
_ => Err(Box::new(InstructionError::IncorrectProgramId) as Box<dyn std::error::Error>),
_ => Err(Box::new(InstructionError::IncorrectProgramId) as Box<dyn core::error::Error>),
}
.map(|_| 0)
}
Expand Down Expand Up @@ -1341,7 +1352,7 @@ fn common_close_account(
fn execute<'a, 'b: 'a>(
executable: &'a Executable<InvokeContext<'static>>,
invoke_context: &'a mut InvokeContext<'b>,
) -> Result<(), Box<dyn std::error::Error>> {
) -> Result<(), Box<dyn core::error::Error>> {
// We dropped the lifetime tracking in the Executor by setting it to 'static,
// thus we need to reintroduce the correct lifetime of InvokeContext here again.
let executable = unsafe {
Expand Down Expand Up @@ -1435,7 +1446,7 @@ fn execute<'a, 'b: 'a>(
match result {
ProgramResult::Ok(status) if status != SUCCESS => {
let error: InstructionError = status.into();
Err(Box::new(error) as Box<dyn std::error::Error>)
Err(Box::new(error) as Box<dyn core::error::Error>)
}
ProgramResult::Err(mut error) => {
if direct_mapping {
Expand Down Expand Up @@ -1502,7 +1513,7 @@ fn execute<'a, 'b: 'a>(
let mut deserialize_time = Measure::start("deserialize");
let execute_or_deserialize_result = execution_result.and_then(|_| {
deserialize_parameters(invoke_context, parameter_bytes.as_slice(), !direct_mapping)
.map_err(|error| Box::new(error) as Box<dyn std::error::Error>)
.map_err(|error| Box::new(error) as Box<dyn core::error::Error>)
});
deserialize_time.stop();

Expand Down
1 change: 1 addition & 0 deletions vendor/solana/programs/bpf_loader/src/serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use {
byteorder::{ByteOrder, LittleEndian},
core::mem::{self, size_of},
nostd::prelude::*,
solana_program_runtime::invoke_context::SerializedAccountMetadata,
solana_rbpf::{
aligned_memory::{AlignedMemory, Pod},
Expand Down
15 changes: 15 additions & 0 deletions vendor/solana/programs/bpf_loader/src/single_thread.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use core::cell::UnsafeCell;

pub struct LocalKey<T>(UnsafeCell<T>);

unsafe impl<T> Sync for LocalKey<T> {}

impl<T> LocalKey<T> {
pub const fn new(value: T) -> Self {
Self(UnsafeCell::new(value))
}

pub fn with_borrow_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
unsafe { f(&mut *self.0.get()) }
}
}
12 changes: 6 additions & 6 deletions vendor/solana/programs/bpf_loader/src/syscalls/cpi.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use {
super::*,
crate::serialization::account_data_region_memory_state,
core::{mem, ptr},
scopeguard::defer,
solana_measure::measure::Measure,
solana_program_runtime::invoke_context::SerializedAccountMetadata,
Expand All @@ -17,7 +18,6 @@ use {
},
transaction_context::BorrowedAccount,
},
std::{mem, ptr},
};

fn check_account_info_pointer(
Expand Down Expand Up @@ -462,8 +462,8 @@ impl SyscallInvokeSigned for SyscallInvokeSignedRust {
#[allow(clippy::indexing_slicing)]
let account_meta = &account_metas[account_index];
if unsafe {
std::ptr::read_volatile(&account_meta.is_signer as *const _ as *const u8) > 1
|| std::ptr::read_volatile(&account_meta.is_writable as *const _ as *const u8)
core::ptr::read_volatile(&account_meta.is_signer as *const _ as *const u8) > 1
|| core::ptr::read_volatile(&account_meta.is_writable as *const _ as *const u8)
> 1
} {
return Err(Box::new(InstructionError::InvalidArgument));
Expand Down Expand Up @@ -689,8 +689,8 @@ impl SyscallInvokeSigned for SyscallInvokeSignedC {
#[allow(clippy::indexing_slicing)]
let account_meta = &account_metas[account_index];
if unsafe {
std::ptr::read_volatile(&account_meta.is_signer as *const _ as *const u8) > 1
|| std::ptr::read_volatile(&account_meta.is_writable as *const _ as *const u8)
core::ptr::read_volatile(&account_meta.is_signer as *const _ as *const u8) > 1
|| core::ptr::read_volatile(&account_meta.is_writable as *const _ as *const u8)
> 1
} {
return Err(Box::new(InstructionError::InvalidArgument));
Expand Down Expand Up @@ -1448,7 +1448,7 @@ fn update_caller_account(
memory_mapping,
caller_account
.vm_data_addr
.saturating_sub(std::mem::size_of::<u64>() as u64),
.saturating_sub(core::mem::size_of::<u64>() as u64),
invoke_context.get_check_aligned(),
)?;
*serialized_len_ptr = post_len as u64;
Expand Down
Loading

0 comments on commit 586bfc7

Please sign in to comment.