Merge api/program into single units (#7061)
This commit is contained in:
17
programs/bpf_loader/src/alloc.rs
Normal file
17
programs/bpf_loader/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<u64, AllocErr>;
|
||||
fn dealloc(&mut self, addr: u64, 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")
|
||||
}
|
||||
}
|
40
programs/bpf_loader/src/allocator_bump.rs
Normal file
40
programs/bpf_loader/src/allocator_bump.rs
Normal file
@ -0,0 +1,40 @@
|
||||
use crate::alloc;
|
||||
|
||||
use alloc::{Alloc, AllocErr};
|
||||
use std::alloc::Layout;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BPFAllocator {
|
||||
heap: Vec<u8>,
|
||||
start: u64,
|
||||
len: u64,
|
||||
pos: u64,
|
||||
}
|
||||
|
||||
impl BPFAllocator {
|
||||
pub fn new(heap: Vec<u8>, virtual_address: u64) -> Self {
|
||||
let len = heap.len() as u64;
|
||||
Self {
|
||||
heap,
|
||||
start: virtual_address,
|
||||
len,
|
||||
pos: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Alloc for BPFAllocator {
|
||||
fn alloc(&mut self, layout: Layout) -> Result<u64, AllocErr> {
|
||||
if self.pos + layout.size() as u64 <= self.len {
|
||||
let addr = self.start + self.pos;
|
||||
self.pos += layout.size() as u64;
|
||||
Ok(addr)
|
||||
} else {
|
||||
Err(AllocErr)
|
||||
}
|
||||
}
|
||||
|
||||
fn dealloc(&mut self, _addr: u64, _layout: Layout) {
|
||||
// It's a bump allocator, free not supported
|
||||
}
|
||||
}
|
318
programs/bpf_loader/src/bpf_verifier.rs
Normal file
318
programs/bpf_loader/src/bpf_verifier.rs
Normal file
@ -0,0 +1,318 @@
|
||||
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())?;
|
||||
}
|
||||
|
||||
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> {
|
||||
if insn_ptr >= (prog.len() / ebpf::INSN_SIZE) {
|
||||
// Last instruction cannot be LD_DW because there would be no 2nd DW
|
||||
reject("LD_DW instruction cannot be last in program".to_string())?;
|
||||
}
|
||||
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(())
|
||||
}
|
179
programs/bpf_loader/src/helpers.rs
Normal file
179
programs/bpf_loader/src/helpers.rs
Normal file
@ -0,0 +1,179 @@
|
||||
use crate::alloc;
|
||||
use alloc::Alloc;
|
||||
use libc::c_char;
|
||||
use log::*;
|
||||
use solana_rbpf::{
|
||||
ebpf::{HelperContext, MM_HEAP_START},
|
||||
memory_region::{translate_addr, MemoryRegion},
|
||||
EbpfVm,
|
||||
};
|
||||
use std::alloc::Layout;
|
||||
use std::ffi::CStr;
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::mem;
|
||||
use std::slice::from_raw_parts;
|
||||
use std::str::from_utf8;
|
||||
|
||||
/// Program heap allocators are intended to allocate/free from a given
|
||||
/// chunk of memory. The specific allocator implementation is
|
||||
/// selectable at build-time.
|
||||
/// Only one allocator is currently supported
|
||||
|
||||
/// Simple bump allocator, never frees
|
||||
use crate::allocator_bump::BPFAllocator;
|
||||
|
||||
/// Default program heap size, allocators
|
||||
/// are expected to enforce this
|
||||
const DEFAULT_HEAP_SIZE: usize = 32 * 1024;
|
||||
|
||||
pub fn register_helpers(vm: &mut EbpfVm) -> Result<MemoryRegion, Error> {
|
||||
vm.register_helper_ex("abort", helper_abort, None)?;
|
||||
vm.register_helper_ex("sol_panic", helper_sol_panic, None)?;
|
||||
vm.register_helper_ex("sol_panic_", helper_sol_panic, None)?;
|
||||
vm.register_helper_ex("sol_log", helper_sol_log, None)?;
|
||||
vm.register_helper_ex("sol_log_", helper_sol_log, None)?;
|
||||
vm.register_helper_ex("sol_log_64", helper_sol_log_u64, None)?;
|
||||
vm.register_helper_ex("sol_log_64_", helper_sol_log_u64, None)?;
|
||||
|
||||
let heap = vec![0_u8; DEFAULT_HEAP_SIZE];
|
||||
let heap_region = MemoryRegion::new_from_slice(&heap, MM_HEAP_START);
|
||||
let context = Box::new(BPFAllocator::new(heap, MM_HEAP_START));
|
||||
vm.register_helper_ex("sol_alloc_free_", helper_sol_alloc_free, Some(context))?;
|
||||
|
||||
Ok(heap_region)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
_arg1: u64,
|
||||
_arg2: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut HelperContext,
|
||||
_ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<u64, Error> {
|
||||
Err(Error::new(
|
||||
ErrorKind::Other,
|
||||
"Error: BPF program called abort()!",
|
||||
))
|
||||
}
|
||||
|
||||
/// 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(
|
||||
file: u64,
|
||||
len: u64,
|
||||
line: u64,
|
||||
column: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut HelperContext,
|
||||
ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<u64, Error> {
|
||||
if let Ok(host_addr) = translate_addr(file, len as usize, "Load", 0, ro_regions) {
|
||||
let c_buf: *const c_char = host_addr 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_log(
|
||||
addr: u64,
|
||||
len: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
_context: &mut HelperContext,
|
||||
ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<u64, Error> {
|
||||
if log_enabled!(log::Level::Info) {
|
||||
let host_addr = translate_addr(addr, len as usize, "Load", 0, ro_regions)?;
|
||||
let c_buf: *const c_char = host_addr as *const c_char;
|
||||
unsafe {
|
||||
for i in 0..len {
|
||||
let c = std::ptr::read(c_buf.offset(i as isize));
|
||||
if i == len - 1 || c == 0 {
|
||||
let message =
|
||||
from_utf8(from_raw_parts(host_addr as *const u8, len as usize)).unwrap();
|
||||
info!("info!: {}", message);
|
||||
return Ok(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(Error::new(
|
||||
ErrorKind::Other,
|
||||
"Error: Unterminated string logged",
|
||||
))
|
||||
} else {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn helper_sol_log_u64(
|
||||
arg1: u64,
|
||||
arg2: u64,
|
||||
arg3: u64,
|
||||
arg4: u64,
|
||||
arg5: u64,
|
||||
_context: &mut HelperContext,
|
||||
_ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<u64, Error> {
|
||||
if log_enabled!(log::Level::Info) {
|
||||
info!(
|
||||
"info!: {:#x}, {:#x}, {:#x}, {:#x}, {:#x}",
|
||||
arg1, arg2, arg3, arg4, arg5
|
||||
);
|
||||
}
|
||||
Ok(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_addr: u64,
|
||||
_arg3: u64,
|
||||
_arg4: u64,
|
||||
_arg5: u64,
|
||||
context: &mut HelperContext,
|
||||
_ro_regions: &[MemoryRegion],
|
||||
_rw_regions: &[MemoryRegion],
|
||||
) -> Result<u64, Error> {
|
||||
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_addr == 0 {
|
||||
match allocator.alloc(layout) {
|
||||
Ok(addr) => Ok(addr as u64),
|
||||
Err(_) => Ok(0),
|
||||
}
|
||||
} else {
|
||||
allocator.dealloc(free_addr, layout);
|
||||
Ok(0)
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
panic!("Failed to get alloc_free context");
|
||||
}
|
328
programs/bpf_loader/src/lib.rs
Normal file
328
programs/bpf_loader/src/lib.rs
Normal file
@ -0,0 +1,328 @@
|
||||
pub mod alloc;
|
||||
pub mod allocator_bump;
|
||||
pub mod bpf_verifier;
|
||||
pub mod helpers;
|
||||
|
||||
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
|
||||
use log::*;
|
||||
use solana_rbpf::{memory_region::MemoryRegion, EbpfVm};
|
||||
use solana_sdk::account::KeyedAccount;
|
||||
use solana_sdk::bpf_loader::PROGRAM_ID;
|
||||
use solana_sdk::instruction::InstructionError;
|
||||
use solana_sdk::instruction_processor_utils::{limited_deserialize, next_keyed_account};
|
||||
use solana_sdk::loader_instruction::LoaderInstruction;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use solana_sdk::sysvar::rent;
|
||||
use std::convert::TryFrom;
|
||||
use std::io::prelude::*;
|
||||
use std::io::Error;
|
||||
use std::mem;
|
||||
|
||||
solana_sdk::declare_program!(
|
||||
PROGRAM_ID,
|
||||
"BPFLoader1111111111111111111111111111111111",
|
||||
solana_bpf_loader_program,
|
||||
process_instruction
|
||||
);
|
||||
|
||||
pub fn create_vm(prog: &[u8]) -> Result<(EbpfVm, MemoryRegion), Error> {
|
||||
let mut vm = EbpfVm::new(None)?;
|
||||
vm.set_verifier(bpf_verifier::check)?;
|
||||
vm.set_max_instruction_count(100_000)?;
|
||||
vm.set_elf(&prog)?;
|
||||
|
||||
let heap_region = helpers::register_helpers(&mut vm)?;
|
||||
|
||||
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],
|
||||
ix_data: &[u8],
|
||||
) -> Result<(), InstructionError> {
|
||||
solana_logger::setup();
|
||||
|
||||
if let Ok(instruction) = limited_deserialize(ix_data) {
|
||||
match instruction {
|
||||
LoaderInstruction::Write { offset, bytes } => {
|
||||
let mut keyed_accounts_iter = keyed_accounts.iter_mut();
|
||||
let program = next_keyed_account(&mut keyed_accounts_iter)?;
|
||||
if program.signer_key().is_none() {
|
||||
warn!("key[0] did not sign the transaction");
|
||||
return Err(InstructionError::MissingRequiredSignature);
|
||||
}
|
||||
let offset = offset as usize;
|
||||
let len = bytes.len();
|
||||
trace!("Write: offset={} length={}", offset, len);
|
||||
if program.account.data.len() < offset + len {
|
||||
warn!(
|
||||
"Write overflow: {} < {}",
|
||||
program.account.data.len(),
|
||||
offset + len
|
||||
);
|
||||
return Err(InstructionError::AccountDataTooSmall);
|
||||
}
|
||||
program.account.data[offset..offset + len].copy_from_slice(&bytes);
|
||||
}
|
||||
LoaderInstruction::Finalize => {
|
||||
let mut keyed_accounts_iter = keyed_accounts.iter_mut();
|
||||
let program = next_keyed_account(&mut keyed_accounts_iter)?;
|
||||
let rent = next_keyed_account(&mut keyed_accounts_iter)?;
|
||||
|
||||
if program.signer_key().is_none() {
|
||||
warn!("key[0] did not sign the transaction");
|
||||
return Err(InstructionError::MissingRequiredSignature);
|
||||
}
|
||||
|
||||
rent::verify_rent_exemption(&program, &rent)?;
|
||||
|
||||
program.account.executable = true;
|
||||
info!("Finalize: account {:?}", program.signer_key().unwrap());
|
||||
}
|
||||
LoaderInstruction::InvokeMain { data } => {
|
||||
let mut keyed_accounts_iter = keyed_accounts.iter_mut();
|
||||
let program = next_keyed_account(&mut keyed_accounts_iter)?;
|
||||
|
||||
if !program.account.executable {
|
||||
warn!("BPF program account not executable");
|
||||
return Err(InstructionError::AccountNotExecutable);
|
||||
}
|
||||
let (mut vm, heap_region) = match create_vm(&program.account.data) {
|
||||
Ok(info) => info,
|
||||
Err(e) => {
|
||||
warn!("Failed to create BPF VM: {}", e);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
};
|
||||
let parameter_accounts = keyed_accounts_iter.into_slice();
|
||||
let mut parameter_bytes =
|
||||
serialize_parameters(program_id, parameter_accounts, &data);
|
||||
|
||||
info!("Call BPF program");
|
||||
match vm.execute_program(parameter_bytes.as_mut_slice(), &[], &[heap_region]) {
|
||||
Ok(status) => match u32::try_from(status) {
|
||||
Ok(status) => {
|
||||
if status > 0 {
|
||||
warn!("BPF program failed: {}", status);
|
||||
return Err(InstructionError::CustomError(status));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("BPF VM encountered invalid status: {}", e);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
warn!("BPF VM failed to run program: {}", e);
|
||||
return Err(InstructionError::GenericError);
|
||||
}
|
||||
}
|
||||
deserialize_parameters(parameter_accounts, ¶meter_bytes);
|
||||
info!("BPF program success");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warn!("Invalid instruction data: {:?}", ix_data);
|
||||
return Err(InstructionError::InvalidInstructionData);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use solana_sdk::account::Account;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Error: Exceeded maximum number of instructions allowed")]
|
||||
fn test_bpf_loader_non_terminating_program() {
|
||||
#[rustfmt::skip]
|
||||
let program = &[
|
||||
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 = EbpfVm::new(None).unwrap();
|
||||
vm.set_verifier(bpf_verifier::check).unwrap();
|
||||
vm.set_max_instruction_count(10).unwrap();
|
||||
vm.set_program(program).unwrap();
|
||||
vm.execute_program(input, &[], &[]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bpf_loader_write() {
|
||||
let program_id = Pubkey::new_rand();
|
||||
let program_key = Pubkey::new_rand();
|
||||
let mut program_account = Account::new(1, 0, &program_id);
|
||||
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &mut program_account)];
|
||||
let ix_data = bincode::serialize(&LoaderInstruction::Write {
|
||||
offset: 3,
|
||||
bytes: vec![1, 2, 3],
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Case: Empty keyed accounts
|
||||
assert_eq!(
|
||||
Err(InstructionError::NotEnoughAccountKeys),
|
||||
process_instruction(&program_id, &mut vec![], &ix_data)
|
||||
);
|
||||
|
||||
// Case: Not signed
|
||||
assert_eq!(
|
||||
Err(InstructionError::MissingRequiredSignature),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
|
||||
// Case: Write bytes to an offset
|
||||
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, true, &mut program_account)];
|
||||
keyed_accounts[0].account.data = vec![0; 6];
|
||||
assert_eq!(
|
||||
Ok(()),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
assert_eq!(vec![0, 0, 0, 1, 2, 3], keyed_accounts[0].account.data);
|
||||
|
||||
// Case: Overflow
|
||||
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, true, &mut program_account)];
|
||||
keyed_accounts[0].account.data = vec![0; 5];
|
||||
assert_eq!(
|
||||
Err(InstructionError::AccountDataTooSmall),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bpf_loader_finalize() {
|
||||
let program_id = Pubkey::new_rand();
|
||||
let program_key = Pubkey::new_rand();
|
||||
let rent_key = rent::id();
|
||||
let mut program_account = Account::new(1, 0, &program_id);
|
||||
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &mut program_account)];
|
||||
let ix_data = bincode::serialize(&LoaderInstruction::Finalize).unwrap();
|
||||
|
||||
// Case: Empty keyed accounts
|
||||
assert_eq!(
|
||||
Err(InstructionError::NotEnoughAccountKeys),
|
||||
process_instruction(&program_id, &mut vec![], &ix_data)
|
||||
);
|
||||
|
||||
let mut rent_account = rent::create_account(1, &rent::Rent::default());
|
||||
keyed_accounts.push(KeyedAccount::new(&rent_key, false, &mut rent_account));
|
||||
|
||||
// Case: Not signed
|
||||
assert_eq!(
|
||||
Err(InstructionError::MissingRequiredSignature),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
|
||||
// Case: Finalize
|
||||
let mut keyed_accounts = vec![
|
||||
KeyedAccount::new(&program_key, true, &mut program_account),
|
||||
KeyedAccount::new(&rent_key, false, &mut rent_account),
|
||||
];
|
||||
assert_eq!(
|
||||
Ok(()),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
assert!(keyed_accounts[0].account.executable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bpf_loader_invoke_main() {
|
||||
let program_id = Pubkey::new_rand();
|
||||
let program_key = Pubkey::new_rand();
|
||||
|
||||
// Create program account
|
||||
let mut file = File::open("test_elfs/noop.so").expect("file open failed");
|
||||
let mut elf = Vec::new();
|
||||
file.read_to_end(&mut elf).unwrap();
|
||||
let mut program_account = Account::new(1, 0, &program_id);
|
||||
program_account.data = elf;
|
||||
program_account.executable = true;
|
||||
|
||||
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &mut program_account)];
|
||||
let ix_data = bincode::serialize(&LoaderInstruction::InvokeMain { data: vec![] }).unwrap();
|
||||
|
||||
// Case: Empty keyed accounts
|
||||
assert_eq!(
|
||||
Err(InstructionError::NotEnoughAccountKeys),
|
||||
process_instruction(&program_id, &mut vec![], &ix_data)
|
||||
);
|
||||
|
||||
// Case: Only a program account
|
||||
assert_eq!(
|
||||
Ok(()),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
|
||||
// Case: Account not executable
|
||||
keyed_accounts[0].account.executable = false;
|
||||
assert_eq!(
|
||||
Err(InstructionError::AccountNotExecutable),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
keyed_accounts[0].account.executable = true;
|
||||
|
||||
// Case: With program and parameter account
|
||||
let mut parameter_account = Account::new(1, 0, &program_id);
|
||||
keyed_accounts.push(KeyedAccount::new(
|
||||
&program_key,
|
||||
false,
|
||||
&mut parameter_account,
|
||||
));
|
||||
assert_eq!(
|
||||
Ok(()),
|
||||
process_instruction(&program_id, &mut keyed_accounts, &ix_data)
|
||||
);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user