Split BPF loader to match the rest of the programs (#4636)
This commit is contained in:
1
programs/bpf_loader_api/.gitignore
vendored
Normal file
1
programs/bpf_loader_api/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/target/
|
23
programs/bpf_loader_api/Cargo.toml
Normal file
23
programs/bpf_loader_api/Cargo.toml
Normal file
@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "solana-bpf-loader-api"
|
||||
version = "0.16.0"
|
||||
description = "Solana BPF Loader"
|
||||
authors = ["Solana Maintainers <maintainers@solana.com>"]
|
||||
repository = "https://github.com/solana-labs/solana"
|
||||
license = "Apache-2.0"
|
||||
homepage = "https://solana.com/"
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
bincode = "1.1.4"
|
||||
byteorder = "1.3.2"
|
||||
libc = "0.2.58"
|
||||
log = "0.4.2"
|
||||
serde = "1.0.92"
|
||||
solana-logger = { path = "../../logger", version = "0.16.0" }
|
||||
solana-sdk = { path = "../../sdk", version = "0.16.0" }
|
||||
solana_rbpf = "=0.1.13"
|
||||
|
||||
[lib]
|
||||
crate-type = ["lib"]
|
||||
name = "solana_bpf_loader_api"
|
17
programs/bpf_loader_api/src/alloc.rs
Normal file
17
programs/bpf_loader_api/src/alloc.rs
Normal file
@ -0,0 +1,17 @@
|
||||
use std::alloc::Layout;
|
||||
use std::fmt;
|
||||
|
||||
/// Based loosely on the unstable std::alloc::Alloc trait
|
||||
pub trait Alloc {
|
||||
fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr>;
|
||||
fn dealloc(&mut self, ptr: *mut u8, layout: Layout);
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct AllocErr;
|
||||
|
||||
impl fmt::Display for AllocErr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("Error: Memory allocation failed")
|
||||
}
|
||||
}
|
32
programs/bpf_loader_api/src/allocator_bump.rs
Normal file
32
programs/bpf_loader_api/src/allocator_bump.rs
Normal file
@ -0,0 +1,32 @@
|
||||
use crate::alloc;
|
||||
|
||||
use alloc::{Alloc, AllocErr};
|
||||
use std::alloc::Layout;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BPFAllocator {
|
||||
heap: Vec<u8>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl BPFAllocator {
|
||||
pub fn new(heap: Vec<u8>) -> Self {
|
||||
Self { heap, pos: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Alloc for BPFAllocator {
|
||||
fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
|
||||
if self.pos + layout.size() <= self.heap.len() {
|
||||
let ptr = unsafe { self.heap.as_mut_ptr().add(self.pos) };
|
||||
self.pos += layout.size();
|
||||
Ok(ptr)
|
||||
} else {
|
||||
Err(AllocErr)
|
||||
}
|
||||
}
|
||||
|
||||
fn dealloc(&mut self, _ptr: *mut u8, _layout: Layout) {
|
||||
// It's a bump allocator, free not supported
|
||||
}
|
||||
}
|
40
programs/bpf_loader_api/src/allocator_system.rs
Normal file
40
programs/bpf_loader_api/src/allocator_system.rs
Normal file
@ -0,0 +1,40 @@
|
||||
use crate::alloc;
|
||||
|
||||
use alloc::{Alloc, AllocErr};
|
||||
use std::alloc::{self as system_alloc, Layout};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BPFAllocator {
|
||||
allocated: usize,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
impl BPFAllocator {
|
||||
pub fn new(heap: Vec<u8>) -> Self {
|
||||
Self {
|
||||
allocated: 0,
|
||||
size: heap.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Alloc for BPFAllocator {
|
||||
fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
|
||||
if self.allocated + layout.size() <= self.size {
|
||||
let ptr = unsafe { system_alloc::alloc(layout) };
|
||||
if !ptr.is_null() {
|
||||
self.allocated += layout.size();
|
||||
return Ok(ptr);
|
||||
}
|
||||
}
|
||||
Err(AllocErr)
|
||||
}
|
||||
|
||||
#[allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
|
||||
self.allocated -= layout.size();
|
||||
unsafe {
|
||||
system_alloc::dealloc(ptr, layout);
|
||||
}
|
||||
}
|
||||
}
|
324
programs/bpf_loader_api/src/bpf_verifier.rs
Normal file
324
programs/bpf_loader_api/src/bpf_verifier.rs
Normal file
@ -0,0 +1,324 @@
|
||||
use solana_rbpf::ebpf;
|
||||
use std::io::{Error, ErrorKind};
|
||||
|
||||
fn reject<S: AsRef<str>>(msg: S) -> Result<(), Error> {
|
||||
let full_msg = format!("[Verifier] Error: {}", msg.as_ref());
|
||||
Err(Error::new(ErrorKind::Other, full_msg))
|
||||
}
|
||||
|
||||
fn check_prog_len(prog: &[u8]) -> Result<(), Error> {
|
||||
if prog.len() % ebpf::INSN_SIZE != 0 {
|
||||
reject(format!(
|
||||
"eBPF program length must be a multiple of {:?} octets",
|
||||
ebpf::INSN_SIZE
|
||||
))?;
|
||||
}
|
||||
if prog.len() > ebpf::PROG_MAX_SIZE {
|
||||
reject(format!(
|
||||
"eBPF program length limited to {:?}, here {:?}",
|
||||
ebpf::PROG_MAX_INSNS,
|
||||
prog.len() / ebpf::INSN_SIZE
|
||||
))?;
|
||||
}
|
||||
|
||||
if prog.is_empty() {
|
||||
reject("No program set, call prog_set() to load one".to_string())?;
|
||||
}
|
||||
|
||||
// TODO BPF program may deterministically exit even if the last
|
||||
// instruction in the block is not an exit (might be earlier and jumped to)
|
||||
// TODO need to validate more intelligently
|
||||
// let last_insn = ebpf::get_insn(prog, (prog.len() / ebpf::INSN_SIZE) - 1);
|
||||
// if last_insn.opc != ebpf::EXIT {
|
||||
// reject("program does not end with “EXIT” instruction".to_string())?;
|
||||
// }
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_imm_nonzero(insn: &ebpf::Insn, insn_ptr: usize) -> Result<(), Error> {
|
||||
if insn.imm == 0 {
|
||||
reject(format!("division by 0 (insn #{:?})", insn_ptr))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_imm_endian(insn: &ebpf::Insn, insn_ptr: usize) -> Result<(), Error> {
|
||||
match insn.imm {
|
||||
16 | 32 | 64 => Ok(()),
|
||||
_ => reject(format!(
|
||||
"unsupported argument for LE/BE (insn #{:?})",
|
||||
insn_ptr
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_load_dw(prog: &[u8], insn_ptr: usize) -> Result<(), Error> {
|
||||
// We know we can reach next insn since we enforce an EXIT insn at the end of program, while
|
||||
// this function should be called only for LD_DW insn, that cannot be last in program.
|
||||
let next_insn = ebpf::get_insn(prog, insn_ptr + 1);
|
||||
if next_insn.opc != 0 {
|
||||
reject(format!(
|
||||
"incomplete LD_DW instruction (insn #{:?})",
|
||||
insn_ptr
|
||||
))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_jmp_offset(prog: &[u8], insn_ptr: usize) -> Result<(), Error> {
|
||||
let insn = ebpf::get_insn(prog, insn_ptr);
|
||||
if insn.off == -1 {
|
||||
reject(format!("infinite loop (insn #{:?})", insn_ptr))?;
|
||||
}
|
||||
|
||||
let dst_insn_ptr = insn_ptr as isize + 1 + insn.off as isize;
|
||||
if dst_insn_ptr < 0 || dst_insn_ptr as usize >= (prog.len() / ebpf::INSN_SIZE) {
|
||||
reject(format!(
|
||||
"jump out of code to #{:?} (insn #{:?})",
|
||||
dst_insn_ptr, insn_ptr
|
||||
))?;
|
||||
}
|
||||
|
||||
let dst_insn = ebpf::get_insn(prog, dst_insn_ptr as usize);
|
||||
if dst_insn.opc == 0 {
|
||||
reject(format!(
|
||||
"jump to middle of LD_DW at #{:?} (insn #{:?})",
|
||||
dst_insn_ptr, insn_ptr
|
||||
))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_registers(insn: &ebpf::Insn, store: bool, insn_ptr: usize) -> Result<(), Error> {
|
||||
if insn.src > 10 {
|
||||
reject(format!("invalid source register (insn #{:?})", insn_ptr))?;
|
||||
}
|
||||
|
||||
match (insn.dst, store) {
|
||||
(0...9, _) | (10, true) => Ok(()),
|
||||
(10, false) => reject(format!(
|
||||
"cannot write into register r10 (insn #{:?})",
|
||||
insn_ptr
|
||||
)),
|
||||
(_, _) => reject(format!(
|
||||
"invalid destination register (insn #{:?})",
|
||||
insn_ptr
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(prog: &[u8]) -> Result<(), Error> {
|
||||
check_prog_len(prog)?;
|
||||
|
||||
let mut insn_ptr: usize = 0;
|
||||
while insn_ptr * ebpf::INSN_SIZE < prog.len() {
|
||||
let insn = ebpf::get_insn(prog, insn_ptr);
|
||||
let mut store = false;
|
||||
|
||||
match insn.opc {
|
||||
// BPF_LD class
|
||||
ebpf::LD_ABS_B => {}
|
||||
ebpf::LD_ABS_H => {}
|
||||
ebpf::LD_ABS_W => {}
|
||||
ebpf::LD_ABS_DW => {}
|
||||
ebpf::LD_IND_B => {}
|
||||
ebpf::LD_IND_H => {}
|
||||
ebpf::LD_IND_W => {}
|
||||
ebpf::LD_IND_DW => {}
|
||||
|
||||
ebpf::LD_DW_IMM => {
|
||||
store = true;
|
||||
check_load_dw(prog, insn_ptr)?;
|
||||
insn_ptr += 1;
|
||||
}
|
||||
|
||||
// BPF_LDX class
|
||||
ebpf::LD_B_REG => {}
|
||||
ebpf::LD_H_REG => {}
|
||||
ebpf::LD_W_REG => {}
|
||||
ebpf::LD_DW_REG => {}
|
||||
|
||||
// BPF_ST class
|
||||
ebpf::ST_B_IMM => store = true,
|
||||
ebpf::ST_H_IMM => store = true,
|
||||
ebpf::ST_W_IMM => store = true,
|
||||
ebpf::ST_DW_IMM => store = true,
|
||||
|
||||
// BPF_STX class
|
||||
ebpf::ST_B_REG => store = true,
|
||||
ebpf::ST_H_REG => store = true,
|
||||
ebpf::ST_W_REG => store = true,
|
||||
ebpf::ST_DW_REG => store = true,
|
||||
ebpf::ST_W_XADD => {
|
||||
unimplemented!();
|
||||
}
|
||||
ebpf::ST_DW_XADD => {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
// BPF_ALU class
|
||||
ebpf::ADD32_IMM => {}
|
||||
ebpf::ADD32_REG => {}
|
||||
ebpf::SUB32_IMM => {}
|
||||
ebpf::SUB32_REG => {}
|
||||
ebpf::MUL32_IMM => {}
|
||||
ebpf::MUL32_REG => {}
|
||||
ebpf::DIV32_IMM => {
|
||||
check_imm_nonzero(&insn, insn_ptr)?;
|
||||
}
|
||||
ebpf::DIV32_REG => {}
|
||||
ebpf::OR32_IMM => {}
|
||||
ebpf::OR32_REG => {}
|
||||
ebpf::AND32_IMM => {}
|
||||
ebpf::AND32_REG => {}
|
||||
ebpf::LSH32_IMM => {}
|
||||
ebpf::LSH32_REG => {}
|
||||
ebpf::RSH32_IMM => {}
|
||||
ebpf::RSH32_REG => {}
|
||||
ebpf::NEG32 => {}
|
||||
ebpf::MOD32_IMM => {
|
||||
check_imm_nonzero(&insn, insn_ptr)?;
|
||||
}
|
||||
ebpf::MOD32_REG => {}
|
||||
ebpf::XOR32_IMM => {}
|
||||
ebpf::XOR32_REG => {}
|
||||
ebpf::MOV32_IMM => {}
|
||||
ebpf::MOV32_REG => {}
|
||||
ebpf::ARSH32_IMM => {}
|
||||
ebpf::ARSH32_REG => {}
|
||||
ebpf::LE => {
|
||||
check_imm_endian(&insn, insn_ptr)?;
|
||||
}
|
||||
ebpf::BE => {
|
||||
check_imm_endian(&insn, insn_ptr)?;
|
||||
}
|
||||
|
||||
// BPF_ALU64 class
|
||||
ebpf::ADD64_IMM => {}
|
||||
ebpf::ADD64_REG => {}
|
||||
ebpf::SUB64_IMM => {}
|
||||
ebpf::SUB64_REG => {}
|
||||
ebpf::MUL64_IMM => {
|
||||
check_imm_nonzero(&insn, insn_ptr)?;
|
||||
}
|
||||
ebpf::MUL64_REG => {}
|
||||
ebpf::DIV64_IMM => {
|
||||
check_imm_nonzero(&insn, insn_ptr)?;
|
||||
}
|
||||
ebpf::DIV64_REG => {}
|
||||
ebpf::OR64_IMM => {}
|
||||
ebpf::OR64_REG => {}
|
||||
ebpf::AND64_IMM => {}
|
||||
ebpf::AND64_REG => {}
|
||||
ebpf::LSH64_IMM => {}
|
||||
ebpf::LSH64_REG => {}
|
||||
ebpf::RSH64_IMM => {}
|
||||
ebpf::RSH64_REG => {}
|
||||
ebpf::NEG64 => {}
|
||||
ebpf::MOD64_IMM => {}
|
||||
ebpf::MOD64_REG => {}
|
||||
ebpf::XOR64_IMM => {}
|
||||
ebpf::XOR64_REG => {}
|
||||
ebpf::MOV64_IMM => {}
|
||||
ebpf::MOV64_REG => {}
|
||||
ebpf::ARSH64_IMM => {}
|
||||
ebpf::ARSH64_REG => {}
|
||||
|
||||
// BPF_JMP class
|
||||
ebpf::JA => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JEQ_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JEQ_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JGT_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JGT_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JGE_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JGE_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JLT_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JLT_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JLE_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JLE_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSET_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSET_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JNE_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JNE_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSGT_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSGT_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSGE_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSGE_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSLT_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSLT_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSLE_IMM => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::JSLE_REG => {
|
||||
check_jmp_offset(prog, insn_ptr)?;
|
||||
}
|
||||
ebpf::CALL_IMM => {}
|
||||
ebpf::CALL_REG => {}
|
||||
ebpf::EXIT => {}
|
||||
|
||||
_ => {
|
||||
reject(format!(
|
||||
"unknown eBPF opcode {:#2x} (insn #{:?})",
|
||||
insn.opc, insn_ptr
|
||||
))?;
|
||||
}
|
||||
}
|
||||
|
||||
check_registers(&insn, store, insn_ptr)?;
|
||||
|
||||
insn_ptr += 1;
|
||||
}
|
||||
|
||||
// insn_ptr should now be equal to number of instructions.
|
||||
if insn_ptr != prog.len() / ebpf::INSN_SIZE {
|
||||
reject(format!("jumped out of code to #{:?}", insn_ptr))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
399
programs/bpf_loader_api/src/lib.rs
Normal file
399
programs/bpf_loader_api/src/lib.rs
Normal file
@ -0,0 +1,399 @@
|
||||
pub mod alloc;
|
||||
pub mod allocator_bump;
|
||||
pub mod allocator_system;
|
||||
pub mod bpf_verifier;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! solana_bpf_loader {
|
||||
() => {
|
||||
(
|
||||
"solana_bpf_loader".to_string(),
|
||||
solana_sdk::bpf_loader::id(),
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
use alloc::Alloc;
|
||||
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
|
||||
use libc::c_char;
|
||||
use log::*;
|
||||
use solana_rbpf::{EbpfVmRaw, MemoryRegion};
|
||||
use solana_sdk::account::KeyedAccount;
|
||||
use solana_sdk::instruction::InstructionError;
|
||||
use solana_sdk::loader_instruction::LoaderInstruction;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use std::alloc::Layout;
|
||||
use std::any::Any;
|
||||
use std::ffi::CStr;
|
||||
use std::io::prelude::*;
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::mem;
|
||||
|
||||
/// Program heap allocators are intended to allocate/free from a given
|
||||
/// chunk of memory. The specific allocator implementation is
|
||||
/// selectable at build-time.
|
||||
/// Enable only one of the following BPFAllocator implementations.
|
||||
|
||||
/// Simple bump allocator, never frees
|
||||
use allocator_bump::BPFAllocator;
|
||||
|
||||
/// Use the system heap (test purposes only). This allocator relies on the system heap
|
||||
/// and there is no mechanism to check read-write access privileges
|
||||
/// at the moment. Therefor you must disable memory bounds checking
|
||||
// use allocator_system::BPFAllocator;
|
||||
|
||||
/// Default program heap size, allocators
|
||||
/// are expected to enforce this
|
||||
const DEFAULT_HEAP_SIZE: usize = 32 * 1024;
|
||||
|
||||
/// Verifies a string passed out of the program
|
||||
fn verify_string(addr: u64, ro_regions: &[MemoryRegion]) -> Result<(()), Error> {
|
||||
for region in ro_regions.iter() {
|
||||
if region.addr <= addr && (addr as u64) < region.addr + region.len {
|
||||
let c_buf: *const c_char = addr as *const c_char;
|
||||
let max_size = region.addr + region.len - addr;
|
||||
unsafe {
|
||||
for i in 0..max_size {
|
||||
if std::ptr::read(c_buf.offset(i as isize)) == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
return Err(Error::new(ErrorKind::Other, "Error, Unterminated string"));
|
||||
}
|
||||
}
|
||||
Err(Error::new(
|
||||
ErrorKind::Other,
|
||||
"Error: Load segfault, bad string pointer",
|
||||
))
|
||||
}
|
||||
|
||||
/// Abort helper functions, called when the BPF program calls `abort()`
|
||||
/// The verify function returns an error which will cause the BPF program
|
||||
/// to be halted immediately
|
||||
pub fn helper_abort_verify(
|
||||
_arg1: u64,
|
||||
_arg2: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut Option<Box<Any + 'static>>,
|
||||
_ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<(()), Error> {
|
||||
Err(Error::new(
|
||||
ErrorKind::Other,
|
||||
"Error: BPF program called abort()!",
|
||||
))
|
||||
}
|
||||
pub fn helper_abort(
|
||||
_arg1: u64,
|
||||
_arg2: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut Option<Box<Any + 'static>>,
|
||||
) -> u64 {
|
||||
// Never called because its verify function always returns an error
|
||||
0
|
||||
}
|
||||
|
||||
/// Panic helper functions, called when the BPF program calls 'sol_panic_()`
|
||||
/// The verify function returns an error which will cause the BPF program
|
||||
/// to be halted immediately
|
||||
pub fn helper_sol_panic_verify(
|
||||
file: u64,
|
||||
line: u64,
|
||||
column: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut Option<Box<Any + 'static>>,
|
||||
ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<(()), Error> {
|
||||
if verify_string(file, ro_regions).is_ok() {
|
||||
let c_buf: *const c_char = file as *const c_char;
|
||||
let c_str: &CStr = unsafe { CStr::from_ptr(c_buf) };
|
||||
if let Ok(slice) = c_str.to_str() {
|
||||
return Err(Error::new(
|
||||
ErrorKind::Other,
|
||||
format!(
|
||||
"Error: BPF program Panicked at {}, {}:{}",
|
||||
slice, line, column
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(Error::new(ErrorKind::Other, "Error: BPF program Panicked"))
|
||||
}
|
||||
pub fn helper_sol_panic(
|
||||
_arg1: u64,
|
||||
_arg2: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut Option<Box<Any + 'static>>,
|
||||
) -> u64 {
|
||||
// Never called because its verify function always returns an error
|
||||
0
|
||||
}
|
||||
|
||||
/// Logging helper functions, called when the BPF program calls `sol_log_()` or
|
||||
/// `sol_log_64_()`. Both functions use a common verify function to validate
|
||||
/// their parameters.
|
||||
pub fn helper_sol_log_verify(
|
||||
addr: u64,
|
||||
_arg2: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut Option<Box<Any + 'static>>,
|
||||
ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<(()), Error> {
|
||||
verify_string(addr, ro_regions)
|
||||
}
|
||||
pub fn helper_sol_log(
|
||||
addr: u64,
|
||||
_arg2: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut Option<Box<Any + 'static>>,
|
||||
) -> u64 {
|
||||
let c_buf: *const c_char = addr as *const c_char;
|
||||
let c_str: &CStr = unsafe { CStr::from_ptr(c_buf) };
|
||||
match c_str.to_str() {
|
||||
Ok(slice) => info!("sol_log: {:?}", slice),
|
||||
Err(e) => warn!("Error: Cannot print invalid string: {}", e),
|
||||
};
|
||||
0
|
||||
}
|
||||
pub fn helper_sol_log_u64(
|
||||
arg1: u64,
|
||||
arg2: u64,
|
||||
arg3: u64,
|
||||
arg4: u64,
|
||||
arg5: u64,
|
||||
_context: &mut Option<Box<Any + 'static>>,
|
||||
) -> u64 {
|
||||
info!(
|
||||
"sol_log_u64: {:#x}, {:#x}, {:#x}, {:#x}, {:#x}",
|
||||
arg1, arg2, arg3, arg4, arg5
|
||||
);
|
||||
0
|
||||
}
|
||||
|
||||
/// Dynamic memory allocation helper called when the BPF program calls
|
||||
/// `sol_alloc_free_()`. The allocator is expected to allocate/free
|
||||
/// from/to a given chunk of memory and enforce size restrictions. The
|
||||
/// memory chunk is given to the allocator during allocator creation and
|
||||
/// information about that memory (start address and size) is passed
|
||||
/// to the VM to use for enforcement.
|
||||
pub fn helper_sol_alloc_free(
|
||||
size: u64,
|
||||
free_ptr: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
context: &mut Option<Box<Any + 'static>>,
|
||||
) -> u64 {
|
||||
if let Some(context) = context {
|
||||
if let Some(allocator) = context.downcast_mut::<BPFAllocator>() {
|
||||
return {
|
||||
let layout = Layout::from_size_align(size as usize, mem::align_of::<u8>()).unwrap();
|
||||
if free_ptr == 0 {
|
||||
match allocator.alloc(layout) {
|
||||
Ok(ptr) => ptr as u64,
|
||||
Err(_) => 0,
|
||||
}
|
||||
} else {
|
||||
allocator.dealloc(free_ptr as *mut u8, layout);
|
||||
0
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
panic!("Failed to get alloc_free context");
|
||||
}
|
||||
|
||||
pub fn create_vm(prog: &[u8]) -> Result<(EbpfVmRaw, MemoryRegion), Error> {
|
||||
let mut vm = EbpfVmRaw::new(None)?;
|
||||
vm.set_verifier(bpf_verifier::check)?;
|
||||
vm.set_max_instruction_count(36000)?;
|
||||
vm.set_elf(&prog)?;
|
||||
vm.register_helper_ex("abort", Some(helper_abort_verify), helper_abort, None)?;
|
||||
vm.register_helper_ex(
|
||||
"sol_panic",
|
||||
Some(helper_sol_panic_verify),
|
||||
helper_sol_panic,
|
||||
None,
|
||||
)?;
|
||||
vm.register_helper_ex(
|
||||
"sol_panic_",
|
||||
Some(helper_sol_panic_verify),
|
||||
helper_sol_panic,
|
||||
None,
|
||||
)?;
|
||||
vm.register_helper_ex("sol_log", Some(helper_sol_log_verify), helper_sol_log, None)?;
|
||||
vm.register_helper_ex(
|
||||
"sol_log_",
|
||||
Some(helper_sol_log_verify),
|
||||
helper_sol_log,
|
||||
None,
|
||||
)?;
|
||||
vm.register_helper_ex("sol_log_64", None, helper_sol_log_u64, None)?;
|
||||
vm.register_helper_ex("sol_log_64_", None, helper_sol_log_u64, None)?;
|
||||
|
||||
let heap = vec![0_u8; DEFAULT_HEAP_SIZE];
|
||||
let heap_region = MemoryRegion::new_from_slice(&heap);
|
||||
let context = Box::new(BPFAllocator::new(heap));
|
||||
vm.register_helper_ex(
|
||||
"sol_alloc_free_",
|
||||
None,
|
||||
helper_sol_alloc_free,
|
||||
Some(context),
|
||||
)?;
|
||||
|
||||
Ok((vm, heap_region))
|
||||
}
|
||||
|
||||
fn serialize_parameters(
|
||||
program_id: &Pubkey,
|
||||
keyed_accounts: &mut [KeyedAccount],
|
||||
data: &[u8],
|
||||
) -> Vec<u8> {
|
||||
assert_eq!(32, mem::size_of::<Pubkey>());
|
||||
|
||||
let mut v: Vec<u8> = Vec::new();
|
||||
v.write_u64::<LittleEndian>(keyed_accounts.len() as u64)
|
||||
.unwrap();
|
||||
for info in keyed_accounts.iter_mut() {
|
||||
v.write_u64::<LittleEndian>(info.signer_key().is_some() as u64)
|
||||
.unwrap();
|
||||
v.write_all(info.unsigned_key().as_ref()).unwrap();
|
||||
v.write_u64::<LittleEndian>(info.account.lamports).unwrap();
|
||||
v.write_u64::<LittleEndian>(info.account.data.len() as u64)
|
||||
.unwrap();
|
||||
v.write_all(&info.account.data).unwrap();
|
||||
v.write_all(info.account.owner.as_ref()).unwrap();
|
||||
}
|
||||
v.write_u64::<LittleEndian>(data.len() as u64).unwrap();
|
||||
v.write_all(data).unwrap();
|
||||
v.write_all(program_id.as_ref()).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
fn deserialize_parameters(keyed_accounts: &mut [KeyedAccount], buffer: &[u8]) {
|
||||
assert_eq!(32, mem::size_of::<Pubkey>());
|
||||
|
||||
let mut start = mem::size_of::<u64>();
|
||||
for info in keyed_accounts.iter_mut() {
|
||||
start += mem::size_of::<u64>(); // skip signer_key boolean
|
||||
start += mem::size_of::<Pubkey>(); // skip pubkey
|
||||
info.account.lamports = LittleEndian::read_u64(&buffer[start..]);
|
||||
|
||||
start += mem::size_of::<u64>() // skip lamports
|
||||
+ mem::size_of::<u64>(); // skip length tag
|
||||
let end = start + info.account.data.len();
|
||||
info.account.data.clone_from_slice(&buffer[start..end]);
|
||||
|
||||
start += info.account.data.len() // skip data
|
||||
+ mem::size_of::<Pubkey>(); // skip owner
|
||||
}
|
||||
}
|
||||
|
||||
pub fn process_instruction(
|
||||
program_id: &Pubkey,
|
||||
keyed_accounts: &mut [KeyedAccount],
|
||||
tx_data: &[u8],
|
||||
) -> Result<(), InstructionError> {
|
||||
solana_logger::setup();
|
||||
|
||||
if keyed_accounts[0].account.executable {
|
||||
let (progs, params) = keyed_accounts.split_at_mut(1);
|
||||
let prog = &progs[0].account.data;
|
||||
info!("Call BPF program");
|
||||
let (mut vm, heap_region) = match create_vm(prog) {
|
||||
Ok(info) => info,
|
||||
Err(e) => {
|
||||
warn!("Failed to create BPF VM: {}", e);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
};
|
||||
let mut v = serialize_parameters(program_id, params, &tx_data);
|
||||
|
||||
match vm.execute_program(v.as_mut_slice(), &[], &[heap_region]) {
|
||||
Ok(status) => {
|
||||
if 0 == status {
|
||||
warn!("BPF program failed: {}", status);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("BPF VM failed to run program: {}", e);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
}
|
||||
deserialize_parameters(params, &v);
|
||||
info!(
|
||||
"BPF program executed {} instructions",
|
||||
vm.get_last_instruction_count()
|
||||
);
|
||||
} else if let Ok(instruction) = bincode::deserialize(tx_data) {
|
||||
if keyed_accounts[0].signer_key().is_none() {
|
||||
warn!("key[0] did not sign the transaction");
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
match instruction {
|
||||
LoaderInstruction::Write { offset, bytes } => {
|
||||
let offset = offset as usize;
|
||||
let len = bytes.len();
|
||||
debug!("Write: offset={} length={}", offset, len);
|
||||
if keyed_accounts[0].account.data.len() < offset + len {
|
||||
warn!(
|
||||
"Write overflow: {} < {}",
|
||||
keyed_accounts[0].account.data.len(),
|
||||
offset + len
|
||||
);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
keyed_accounts[0].account.data[offset..offset + len].copy_from_slice(&bytes);
|
||||
}
|
||||
LoaderInstruction::Finalize => {
|
||||
keyed_accounts[0].account.executable = true;
|
||||
info!(
|
||||
"Finalize: account {:?}",
|
||||
keyed_accounts[0].signer_key().unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warn!("Invalid program transaction: {:?}", tx_data);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Error: Execution exceeded maximum number of instructions")]
|
||||
fn test_non_terminating_program() {
|
||||
#[rustfmt::skip]
|
||||
let prog = &[
|
||||
0x07, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // r6 + 1
|
||||
0x05, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, // goto -2
|
||||
0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // exit
|
||||
];
|
||||
let input = &mut [0x00];
|
||||
|
||||
let mut vm = EbpfVmRaw::new(None).unwrap();
|
||||
vm.set_verifier(bpf_verifier::check).unwrap();
|
||||
vm.set_max_instruction_count(10).unwrap();
|
||||
vm.set_program(prog).unwrap();
|
||||
vm.execute_program(input, &[], &[]).unwrap();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user