forked from solana-labs/rbpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvm.rs
1204 lines (1136 loc) · 54 KB
/
vm.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Derived from uBPF <https://github.com/iovisor/ubpf>
// Copyright 2015 Big Switch Networks, Inc
// (uBPF: VM architecture, parts of the interpreter, originally in C)
// Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com>
// (Translation to Rust, MetaBuff/multiple classes addition, hashmaps for syscalls)
//
// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Virtual machine and JIT compiler for eBPF programs.
use crate::{
call_frames::CallFrames,
disassembler, ebpf,
elf::EBpfElf,
error::{EbpfError, UserDefinedError},
jit::{JitProgram, JitProgramArgument},
memory_region::{AccessType, MemoryMapping, MemoryRegion},
user_error::UserError,
};
use log::debug;
use std::{collections::HashMap, fmt::Debug, u32};
use crate::gdb_stub::{NUM_REGS, VmReply, VmRequest, BreakpointTable, start_debug_server};
use gdbstub::target::ext::section_offsets::Offsets;
use std::sync::mpsc;
/// eBPF verification function that returns an error if the program does not meet its requirements.
///
/// Some examples of things the verifier may reject the program for:
///
/// - Program does not terminate.
/// - Unknown instructions.
/// - Bad formed instruction.
/// - Unknown eBPF syscall index.
pub type Verifier<E> = fn(prog: &[u8]) -> Result<(), E>;
/// Return value of programs and syscalls
pub type ProgramResult<E> = Result<u64, EbpfError<E>>;
/// Error handling for SyscallObject::call methods
#[macro_export]
macro_rules! question_mark {
( $value:expr, $result:ident ) => {{
let value = $value;
match value {
Err(err) => {
*$result = Err(err.into());
return;
}
Ok(value) => value,
}
}};
}
/// Syscall function without context
pub type SyscallFunction<E, O> =
fn(O, u64, u64, u64, u64, u64, &MemoryMapping, &mut ProgramResult<E>);
/// Syscall with context
pub trait SyscallObject<E: UserDefinedError> {
/// Call the syscall function
#[allow(clippy::too_many_arguments)]
fn call(
&mut self,
arg1: u64,
arg2: u64,
arg3: u64,
arg4: u64,
arg5: u64,
memory_mapping: &MemoryMapping,
result: &mut ProgramResult<E>,
);
}
/// Syscall function and binding slot for a context object
#[derive(Debug, PartialEq)]
pub struct Syscall {
/// Call the syscall function
pub function: u64,
/// Slot of context object
pub context_object_slot: usize,
}
/// A virtual method table for dyn trait objects
pub struct DynTraitVtable {
/// Drops the dyn trait object
pub drop: fn(*const u8),
/// Size of the dyn trait object in bytes
pub size: usize,
/// Alignment of the dyn trait object in bytes
pub align: usize,
/// The methods of the trait
pub methods: [*const u8; 32],
}
// Could be replaced by https://doc.rust-lang.org/std/raw/struct.TraitObject.html
/// A dyn trait fat pointer for SyscallObject
#[derive(Clone, Copy)]
pub struct DynTraitFatPointer {
/// Pointer to the actual object
pub data: *mut u8,
/// Pointer to the virtual method table
pub vtable: &'static DynTraitVtable,
}
/// Holds the syscall function pointers of an Executable
#[derive(Debug, PartialEq, Default)]
pub struct SyscallRegistry {
/// Function pointers by symbol
entries: HashMap<u32, Syscall>,
/// Context object slots by function pointer
context_object_slots: HashMap<u64, usize>,
}
impl SyscallRegistry {
/// Register a syscall function by its symbol hash
pub fn register_syscall_by_hash<E: UserDefinedError, O: SyscallObject<E>>(
&mut self,
hash: u32,
function: SyscallFunction<E, &mut O>,
) -> Result<(), EbpfError<E>> {
let function = function as *const u8 as u64;
let context_object_slot = self.entries.len();
if self
.entries
.insert(
hash,
Syscall {
function,
context_object_slot,
},
)
.is_some()
|| self
.context_object_slots
.insert(function, context_object_slot)
.is_some()
{
Err(EbpfError::SycallAlreadyRegistered)
} else {
Ok(())
}
}
/// Register a syscall function by its symbol name
pub fn register_syscall_by_name<E: UserDefinedError, O: SyscallObject<E>>(
&mut self,
name: &[u8],
function: SyscallFunction<E, &mut O>,
) -> Result<(), EbpfError<E>> {
self.register_syscall_by_hash(ebpf::hash_symbol_name(name), function)
}
/// Get a symbol's function pointer and context object slot
pub fn lookup_syscall(&self, hash: u32) -> Option<&Syscall> {
self.entries.get(&hash)
}
/// Get a function pointer's and context object slot
pub fn lookup_context_object_slot(&self, function_pointer: u64) -> Option<usize> {
self.context_object_slots.get(&function_pointer).copied()
}
/// Get the number of registered syscalls
pub fn get_number_of_syscalls(&self) -> usize {
self.entries.len()
}
}
/// VM configuration settings
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
/// Maximum call depth
pub max_call_depth: usize,
/// Size of a stack frame in bytes, must match the size specified in the LLVM BPF backend
pub stack_frame_size: usize,
/// Enable instruction meter and limiting
pub enable_instruction_meter: bool,
/// Enable instruction tracing
pub enable_instruction_tracing: bool,
/// Enable GDB stub serve. Setting this for an `Executable` will cause the
/// VM to block until it receives a connection from an instance of GDB.
pub enable_debugger: bool
}
impl Default for Config {
fn default() -> Self {
Self {
max_call_depth: 20,
stack_frame_size: 4_096,
enable_instruction_meter: true,
enable_instruction_tracing: false,
enable_debugger: false,
}
}
}
/// An relocated and ready to execute binary
pub trait Executable<E: UserDefinedError, I: InstructionMeter>: Send + Sync {
/// Get the configuration settings
fn get_config(&self) -> &Config;
/// Get the .text section virtual address and bytes
fn get_text_bytes(&self) -> Result<(u64, &[u8]), EbpfError<E>>;
/// Get a vector of virtual addresses for each read-only section
fn get_ro_sections(&self) -> Result<Vec<(u64, &[u8])>, EbpfError<E>>;
/// Get the entry point offset into the text section
fn get_entrypoint_instruction_offset(&self) -> Result<usize, EbpfError<E>>;
/// Get a symbol's instruction offset
fn lookup_bpf_call(&self, hash: u32) -> Option<&usize>;
/// Get the syscall registry
fn get_syscall_registry(&self) -> &SyscallRegistry;
/// Set (overwrite) the syscall registry
fn set_syscall_registry(&mut self, syscall_registry: SyscallRegistry);
/// Get the JIT compiled program
fn get_compiled_program(&self) -> Option<&JitProgram<E, I>>;
/// JIT compile the executable
fn jit_compile(&mut self) -> Result<(), EbpfError<E>>;
/// Report information on a symbol that failed to be resolved
fn report_unresolved_symbol(&self, insn_offset: usize) -> Result<u64, EbpfError<E>>;
/// Get syscalls and BPF functions (if debug symbols are not stripped)
fn get_symbols(&self) -> (HashMap<u32, String>, HashMap<usize, (String, usize)>);
}
/// Static constructors for Executable
impl<E: UserDefinedError, I: 'static + InstructionMeter> dyn Executable<E, I> {
/// Creates a post relocaiton/fixup executable from an ELF file
pub fn from_elf(
elf_bytes: &[u8],
verifier: Option<Verifier<E>>,
config: Config,
) -> Result<Box<Self>, EbpfError<E>> {
let ebpf_elf = EBpfElf::load(config, elf_bytes)?;
let (_, bytes) = ebpf_elf.get_text_bytes()?;
// println!("bytes: {:#?}", bytes);
if let Some(verifier) = verifier {
verifier(bytes)?;
}
Ok(Box::new(ebpf_elf))
}
/// Creates a post relocaiton/fixup executable from machine code
pub fn from_text_bytes(
text_bytes: &[u8],
verifier: Option<Verifier<E>>,
config: Config,
) -> Result<Box<Self>, EbpfError<E>> {
if let Some(verifier) = verifier {
verifier(text_bytes)?;
}
Ok(Box::new(EBpfElf::new_from_text_bytes(config, text_bytes)))
}
}
/// Instruction meter
pub trait InstructionMeter {
/// Consume instructions
fn consume(&mut self, amount: u64);
/// Get the number of remaining instructions allowed
fn get_remaining(&self) -> u64;
}
/// Instruction meter without a limit
#[derive(Debug, PartialEq)]
pub struct DefaultInstructionMeter {}
impl InstructionMeter for DefaultInstructionMeter {
fn consume(&mut self, _amount: u64) {}
fn get_remaining(&self) -> u64 {
std::i64::MAX as u64
}
}
/// Used for instruction tracing
#[derive(Default, Clone)]
pub struct Tracer {
/// Contains the state at every instruction in order of execution
pub log: Vec<[u64; 12]>,
}
impl Tracer {
/// Logs the state of a single instruction
pub fn trace(&mut self, state: [u64; 12]) {
self.log.push(state);
}
/// Use this method to print the log of this tracer
pub fn write<W: std::fmt::Write>(
&self,
out: &mut W,
program: &[u8],
) -> Result<(), std::fmt::Error> {
let disassembled = disassembler::to_insn_vec(program);
let mut pc_to_instruction_index =
vec![0usize; disassembled.last().map(|ins| ins.ptr + 1).unwrap_or(0)];
for index in 0..disassembled.len() {
pc_to_instruction_index[disassembled[index].ptr] = index;
}
for index in 0..self.log.len() {
let entry = &self.log[index];
let ins_index = pc_to_instruction_index[entry[11] as usize];
writeln!(
out,
"{:5?} {:016X?} {:5?}: {}",
index, entry, ins_index, disassembled[ins_index].desc
)?;
}
Ok(())
}
/// Compares an interpreter trace and a JIT trace.
/// The log of the JIT can be longer because it only validates the instruction meter at branches.
pub fn compare(interpreter: &Self, jit: &Self) -> bool {
let interpreter = interpreter.log.as_slice();
let mut jit = jit.log.as_slice();
if jit.len() > interpreter.len() {
jit = &jit[0..interpreter.len()];
}
interpreter == jit
}
}
/// Translates a vm_addr into a host_addr and sets the pc in the error if one occurs
macro_rules! translate_memory_access {
( $self:ident, $vm_addr:ident, $access_type:expr, $pc:ident, $T:ty ) => {
match $self.memory_mapping.map::<UserError>(
$access_type,
$vm_addr,
std::mem::size_of::<$T>() as u64,
) {
Ok(host_addr) => host_addr as *mut $T,
Err(EbpfError::AccessViolation(_pc, access_type, vm_addr, len, regions)) => {
return Err(EbpfError::AccessViolation(
$pc + ebpf::ELF_INSN_DUMP_OFFSET,
access_type,
vm_addr,
len,
regions,
));
}
Err(EbpfError::StackAccessViolation(_pc, access_type, vm_addr, len, stack_frame)) => {
return Err(EbpfError::StackAccessViolation(
$pc + ebpf::ELF_INSN_DUMP_OFFSET,
access_type,
vm_addr,
len,
stack_frame,
));
}
_ => unreachable!(),
}
};
}
/// The syscall_context_objects field also stores some metadata in the front, thus the entries are shifted
pub const SYSCALL_CONTEXT_OBJECTS_OFFSET: usize = 4;
/// A virtual machine to run eBPF program.
///
/// # Examples
///
/// ```
/// use solana_rbpf::{vm::{Config, Executable, EbpfVm, DefaultInstructionMeter}, user_error::UserError};
///
/// let prog = &[
/// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
/// ];
/// let mem = &mut [
/// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
/// ];
///
/// // Instantiate a VM.
/// let executable = Executable::<UserError, DefaultInstructionMeter>::from_text_bytes(prog, None, Config::default()).unwrap();
/// let mut vm = EbpfVm::<UserError, DefaultInstructionMeter>::new(executable.as_ref(), mem, &[]).unwrap();
///
/// // Provide a reference to the packet data.
/// let res = vm.execute_program_interpreted(&mut DefaultInstructionMeter {}).unwrap();
/// assert_eq!(res, 0);
/// ```
pub struct EbpfVm<'a, E: UserDefinedError, I: InstructionMeter> {
executable: &'a dyn Executable<E, I>,
program: &'a [u8],
program_vm_addr: u64,
memory_mapping: MemoryMapping<'a>,
tracer: Tracer,
syscall_context_objects: Vec<*mut u8>,
syscall_context_object_pool: Vec<Box<dyn SyscallObject<E> + 'a>>,
frames: CallFrames,
last_insn_count: u64,
total_insn_count: u64,
}
impl<'a, E: UserDefinedError, I: InstructionMeter> EbpfVm<'a, E, I> {
/// Create a new virtual machine instance, and load an eBPF program into that instance.
/// When attempting to load the program, it passes through a simple verifier.
///
/// # Examples
///
/// ```
/// use solana_rbpf::{vm::{Config, Executable, EbpfVm, DefaultInstructionMeter}, user_error::UserError};
///
/// let prog = &[
/// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
/// ];
///
/// // Instantiate a VM.
/// let executable = Executable::<UserError, DefaultInstructionMeter>::from_text_bytes(prog, None, Config::default()).unwrap();
/// let mut vm = EbpfVm::<UserError, DefaultInstructionMeter>::new(executable.as_ref(), &mut [], &[]).unwrap();
/// ```
pub fn new(
executable: &'a dyn Executable<E, I>,
mem: &mut [u8],
granted_regions: &[MemoryRegion],
) -> Result<EbpfVm<'a, E, I>, EbpfError<E>> {
let config = executable.get_config();
let const_data_regions: Vec<MemoryRegion> =
if let Ok(sections) = executable.get_ro_sections() {
sections
.iter()
.map(|(addr, slice)| MemoryRegion::new_from_slice(slice, *addr, 0, false))
.collect()
} else {
Vec::new()
};
let mut regions: Vec<MemoryRegion> =
Vec::with_capacity(granted_regions.len() + const_data_regions.len() + 3);
regions.extend(granted_regions.iter().cloned());
let frames = CallFrames::new(config.max_call_depth, config.stack_frame_size);
regions.push(frames.get_region().clone());
regions.extend(const_data_regions);
regions.push(MemoryRegion::new_from_slice(
&mem,
ebpf::MM_INPUT_START,
0,
true,
));
let (program_vm_addr, program) = executable.get_text_bytes()?;
regions.push(MemoryRegion::new_from_slice(
program,
program_vm_addr,
0,
false,
));
let number_of_syscalls = executable.get_syscall_registry().get_number_of_syscalls();
let mut vm = EbpfVm {
executable,
program,
program_vm_addr,
memory_mapping: MemoryMapping::new(regions, &config),
tracer: Tracer::default(),
syscall_context_objects: vec![
std::ptr::null_mut();
SYSCALL_CONTEXT_OBJECTS_OFFSET + number_of_syscalls
],
syscall_context_object_pool: Vec::with_capacity(number_of_syscalls),
frames,
last_insn_count: 0,
total_insn_count: 0,
};
unsafe {
libc::memcpy(
vm.syscall_context_objects.as_mut_ptr() as _,
std::mem::transmute::<_, _>(&vm.memory_mapping),
std::mem::size_of::<MemoryMapping>(),
);
}
Ok(vm)
}
/// Returns the number of instructions executed by the last program.
pub fn get_total_instruction_count(&self) -> u64 {
self.total_insn_count
}
/// Returns the program
pub fn get_program(&self) -> &[u8] {
&self.program
}
/// Returns the tracer
pub fn get_tracer(&self) -> &Tracer {
&self.tracer
}
/// Bind a context object instance to a previously registered syscall
///
/// # Examples
///
/// ```
/// use solana_rbpf::{vm::{Config, Executable, EbpfVm, SyscallObject, SyscallRegistry, DefaultInstructionMeter}, syscalls::BpfTracePrintf, user_error::UserError};
///
/// // This program was compiled with clang, from a C program containing the following single
/// // instruction: `return bpf_trace_printk("foo %c %c %c\n", 10, 1, 2, 3);`
/// let prog = &[
/// 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load 0 as u64 into r1 (That would be
/// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // replaced by tc by the address of
/// // the format string, in the .map
/// // section of the ELF file).
/// 0xb7, 0x02, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, // mov r2, 10
/// 0xb7, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // mov r3, 1
/// 0xb7, 0x04, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // mov r4, 2
/// 0xb7, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // mov r5, 3
/// 0x85, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, // call syscall with key 6
/// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
/// ];
///
/// // Register a syscall.
/// // On running the program this syscall will print the content of registers r3, r4 and r5 to
/// // standard output.
/// let mut syscall_registry = SyscallRegistry::default();
/// syscall_registry.register_syscall_by_hash(6, BpfTracePrintf::call).unwrap();
/// // Instantiate an Executable and VM
/// let mut executable = Executable::<UserError, DefaultInstructionMeter>::from_text_bytes(prog, None, Config::default()).unwrap();
/// executable.set_syscall_registry(syscall_registry);
/// let mut vm = EbpfVm::<UserError, DefaultInstructionMeter>::new(executable.as_ref(), &mut [], &[]).unwrap();
/// // Bind a context object instance to the previously registered syscall
/// vm.bind_syscall_context_object(Box::new(BpfTracePrintf {}), None);
/// ```
pub fn bind_syscall_context_object(
&mut self,
syscall_context_object: Box<dyn SyscallObject<E> + 'a>,
hash: Option<u32>,
) -> Result<(), EbpfError<E>> {
let fat_ptr: DynTraitFatPointer = unsafe { std::mem::transmute(&*syscall_context_object) };
let syscall_registry = self.executable.get_syscall_registry();
let slot = match hash {
Some(hash) => {
syscall_registry
.lookup_syscall(hash)
.unwrap()
.context_object_slot
}
None => syscall_registry
.lookup_context_object_slot(fat_ptr.vtable.methods[0] as u64)
.unwrap(),
};
if !self.syscall_context_objects[SYSCALL_CONTEXT_OBJECTS_OFFSET + slot].is_null() {
Err(EbpfError::SycallAlreadyBound)
} else {
self.syscall_context_objects[SYSCALL_CONTEXT_OBJECTS_OFFSET + slot] = fat_ptr.data;
// Keep the dyn trait objects so that they can be dropped properly later
self.syscall_context_object_pool
.push(syscall_context_object);
Ok(())
}
}
/// Lookup a syscall context object by its function pointer. Used for testing and validation.
pub fn get_syscall_context_object(&self, syscall_function: usize) -> Option<*mut u8> {
self.executable
.get_syscall_registry()
.lookup_context_object_slot(syscall_function as u64)
.map(|slot| self.syscall_context_objects[SYSCALL_CONTEXT_OBJECTS_OFFSET + slot])
}
/// Execute the program loaded, with the given packet data.
///
/// Warning: The program is executed without limiting the number of
/// instructions that can be executed
///
/// # Examples
///
/// ```
/// use solana_rbpf::{vm::{Config, Executable, EbpfVm, DefaultInstructionMeter}, user_error::UserError};
///
/// let prog = &[
/// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
/// ];
/// let mem = &mut [
/// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
/// ];
///
/// // Instantiate a VM.
/// let executable = Executable::<UserError, DefaultInstructionMeter>::from_text_bytes(prog, None, Config::default()).unwrap();
/// let mut vm = EbpfVm::<UserError, DefaultInstructionMeter>::new(executable.as_ref(), mem, &[]).unwrap();
///
/// // Provide a reference to the packet data.
/// let res = vm.execute_program_interpreted(&mut DefaultInstructionMeter {}).unwrap();
/// assert_eq!(res, 0);
/// ```
pub fn execute_program_interpreted(&mut self, instruction_meter: &mut I) -> ProgramResult<E> {
let initial_insn_count = if self.executable.get_config().enable_instruction_meter {
instruction_meter.get_remaining()
} else {
0
};
let result = self.execute_program_interpreted_inner(instruction_meter);
if self.executable.get_config().enable_instruction_meter {
instruction_meter.consume(self.last_insn_count);
self.total_insn_count = initial_insn_count - instruction_meter.get_remaining();
}
result
}
// TODO make this not use unwrap
fn handle_dbg_request(
&mut self,
request: VmRequest,
reply: &mut mpsc::SyncSender<VmReply>,
req: &mut mpsc::Receiver<VmRequest>,
breakpoints: &mut BreakpointTable,
step: &mut bool,
reg: &mut [u64],
) {
match request {
VmRequest::Resume => {}
VmRequest::Interrupt => {
reply.send(VmReply::Interrupt).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::Step => {
*step = true;
}
VmRequest::SetBrkpt(addr) => {
breakpoints.set_breakpoint(addr);
reply.send(VmReply::SetBrkpt).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::RemoveBrkpt(addr) => {
breakpoints.remove_breakpoint(addr);
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::Offsets => {
let res = match self.executable.get_text_bytes() {
Ok(text) => {
let (text, _) = text;
println!("text: {}", text);
VmReply::Offsets(Offsets::Segments {
text_seg: text,
data_seg: None,
})
}
Err(_) => VmReply::Err("could not fetch offsets".into()),
};
reply.send(res).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::ReadMem(addr, len) => {
let mut res: Vec<u8> = Vec::new();
for i in 0..len {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(addr as u32 as u64);
match self.memory_mapping.map::<UserError>(
AccessType::Load,
vm_addr,
std::mem::size_of::<u8>() as u64,
) {
Ok(host_addr) => {
let host_ptr = host_addr as *mut u8;
let data = unsafe { *host_ptr };
res.push(data);
}
Err(e) => {
eprintln!("{}", e);
reply.send(VmReply::Err(e.into())).unwrap();
return;
}
}
}
reply.send(VmReply::ReadMem(res)).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::WriteMem(addr, len, bytes) => {
for i in 0..len {
let vm_addr = addr as u64;
match self.memory_mapping.map::<UserError>(
AccessType::Store,
vm_addr,
std::mem::size_of::<u8>() as u64,
) {
Ok(host_addr) => {
let host_ptr = host_addr as *mut u8;
unsafe { *host_ptr = bytes[i as usize] };
}
Err(e) => {
eprintln!("{}", e);
reply.send(VmReply::Err(e.into())).unwrap();
return;
}
}
}
reply.send(VmReply::WriteMem).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::ReadReg(reg_num) => {
let res = reg[reg_num as usize];
reply.send(VmReply::ReadReg(res)).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::ReadRegs => {
let mut regs: [u64; NUM_REGS] = std::default::Default::default();
regs.copy_from_slice(reg);
reply.send(VmReply::ReadRegs(regs)).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::WriteReg(reg_num, val) => {
reg[reg_num as usize] = val;
reply.send(VmReply::WriteReg).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
VmRequest::WriteRegs(vals) => {
reg.copy_from_slice(&vals);
reply.send(VmReply::WriteRegs).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, step, reg);
}
_ => {
reply.send(VmReply::Err("unimplemented".into())).unwrap();
panic!("unimplemented VmRequest!");
}
}
}
// TODO make this not use unwrap
fn check_for_dbg_request(
&mut self,
block: bool,
reply: &mut mpsc::SyncSender<VmReply>,
req: &mut mpsc::Receiver<VmRequest>,
breakpoints: &mut BreakpointTable,
step: &mut bool,
reg: &mut [u64],
) {
if block {
if let Ok(request) = req.recv() {
println!("vm: {:?}", request);
self.handle_dbg_request(request, reply, req, breakpoints, step, reg);
} else {
eprintln!("debugger detatched from VM");
std::process::exit(1);
}
} else {
match req.try_recv() {
Ok(request) => self.handle_dbg_request(request, reply, req, breakpoints, step, reg),
Err(mpsc::TryRecvError::Empty) => {}
Err(mpsc::TryRecvError::Disconnected) => {
eprintln!("debugger detatched from VM");
std::process::exit(1);
}
}
}
}
#[rustfmt::skip]
fn execute_program_interpreted_inner(
&mut self,
instruction_meter: &mut I,
) -> ProgramResult<E> {
const U32MAX: u64 = u32::MAX as u64;
// R1 points to beginning of input memory, R10 to the stack of the first frame
let mut reg: [u64; 11] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, self.frames.get_stack_top()];
if self.memory_mapping.map::<UserError>(AccessType::Store, ebpf::MM_INPUT_START, 1).is_ok() {
reg[1] = ebpf::MM_INPUT_START;
}
// Check config outside of the instruction loop
let instruction_meter_enabled = self.executable.get_config().enable_instruction_meter;
let instruction_tracing_enabled = self.executable.get_config().enable_instruction_tracing;
let debugger_enabled = self.executable.get_config().enable_debugger;
// Loop on instructions
let entry = self.executable.get_entrypoint_instruction_offset()?;
let mut next_pc: usize = entry;
let mut dbg_interface = if debugger_enabled { Some((start_debug_server(10000, ®, next_pc as u64), BreakpointTable::new())) } else { None };
println!("debug server started");
let mut step = false;
let mut first_insn = true;
let mut remaining_insn_count = if instruction_meter_enabled { instruction_meter.get_remaining() } else { 0 };
let initial_insn_count = remaining_insn_count;
self.last_insn_count = 0;
while next_pc * ebpf::INSN_SIZE + ebpf::INSN_SIZE <= self.program.len() {
let pc = next_pc;
next_pc += 1;
let insn = ebpf::get_insn_unchecked(self.program, pc);
let dst = insn.dst as usize;
let src = insn.src as usize;
self.last_insn_count += 1;
if instruction_tracing_enabled {
let mut state = [0u64; 12];
state[0..11].copy_from_slice(®);
state[11] = pc as u64;
self.tracer.trace(state);
}
if let Some(ref mut dbg_interface) = dbg_interface {
// TODO make this not use unwrap()
println!("pc: {}", pc);
{
let ((ref mut reply, ref mut req), ref mut breakpoints) = *dbg_interface;
if first_insn {
self.check_for_dbg_request(true, reply, req, breakpoints, &mut step, &mut reg);
first_insn = false;
} else if step {
step = false;
reply.send(VmReply::DoneStep).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, &mut step, &mut reg);
} else if breakpoints.check_breakpoint(pc as u64) {
reply.send(VmReply::Breakpoint).unwrap();
self.check_for_dbg_request(true, reply, req, breakpoints, &mut step, &mut reg);
} else {
self.check_for_dbg_request(false, reply, req, breakpoints, &mut step, &mut reg);
}
}
}
match insn.opc {
// BPF_LD class
// Since this pointer is constant, and since we already know it (ebpf::MM_INPUT_START), do not
// bother re-fetching it, just use ebpf::MM_INPUT_START already.
ebpf::LD_ABS_B => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u8);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_ABS_H => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u16);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_ABS_W => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u32);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_ABS_DW => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u64);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_IND_B => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(reg[src]).wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u8);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_IND_H => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(reg[src]).wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u16);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_IND_W => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(reg[src]).wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u32);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_IND_DW => {
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(reg[src]).wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u64);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::LD_DW_IMM => {
let next_insn = ebpf::get_insn(self.program, next_pc);
next_pc += 1;
reg[dst] = (insn.imm as u32) as u64 + ((next_insn.imm as u64) << 32);
},
// BPF_LDX class
ebpf::LD_B_REG => {
let vm_addr = (reg[src] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u8);
reg[dst] = unsafe { *host_ptr as u64 };
},
ebpf::LD_H_REG => {
let vm_addr = (reg[src] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u16);
reg[dst] = unsafe { *host_ptr as u64 };
},
ebpf::LD_W_REG => {
let vm_addr = (reg[src] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u32);
reg[dst] = unsafe { *host_ptr as u64 };
},
ebpf::LD_DW_REG => {
let vm_addr = (reg[src] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u64);
reg[dst] = unsafe { *host_ptr as u64 };
},
// BPF_ST class
ebpf::ST_B_IMM => {
let vm_addr = (reg[dst] as i64).wrapping_add( insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u8);
unsafe { *host_ptr = insn.imm as u8 };
},
ebpf::ST_H_IMM => {
let vm_addr = (reg[dst] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u16);
unsafe { *host_ptr = insn.imm as u16 };
},
ebpf::ST_W_IMM => {
let vm_addr = (reg[dst] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u32);
unsafe { *host_ptr = insn.imm as u32 };
},
ebpf::ST_DW_IMM => {
let vm_addr = (reg[dst] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u64);
unsafe { *host_ptr = insn.imm as u64 };
},
// BPF_STX class
ebpf::ST_B_REG => {
let vm_addr = (reg[dst] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u8);
unsafe { *host_ptr = reg[src] as u8 };
},
ebpf::ST_H_REG => {
let vm_addr = (reg[dst] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u16);
unsafe { *host_ptr = reg[src] as u16 };
},
ebpf::ST_W_REG => {
let vm_addr = (reg[dst] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u32);
unsafe { *host_ptr = reg[src] as u32 };
},
ebpf::ST_DW_REG => {
let vm_addr = (reg[dst] as i64).wrapping_add(insn.off as i64) as u64;
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Store, pc, u64);
unsafe { *host_ptr = reg[src] as u64 };
},
// BPF_ALU class
ebpf::ADD32_IMM => reg[dst] = (reg[dst] as i32).wrapping_add(insn.imm) as u64,
ebpf::ADD32_REG => reg[dst] = (reg[dst] as i32).wrapping_add(reg[src] as i32) as u64,
ebpf::SUB32_IMM => reg[dst] = (reg[dst] as i32).wrapping_sub(insn.imm) as u64,
ebpf::SUB32_REG => reg[dst] = (reg[dst] as i32).wrapping_sub(reg[src] as i32) as u64,
ebpf::MUL32_IMM => reg[dst] = (reg[dst] as i32).wrapping_mul(insn.imm) as u64,
ebpf::MUL32_REG => reg[dst] = (reg[dst] as i32).wrapping_mul(reg[src] as i32) as u64,
ebpf::DIV32_IMM => reg[dst] = (reg[dst] as u32 / insn.imm as u32) as u64,
ebpf::DIV32_REG => {
if reg[src] as u32 == 0 {
return Err(EbpfError::DivideByZero(pc + ebpf::ELF_INSN_DUMP_OFFSET));
}
reg[dst] = (reg[dst] as u32 / reg[src] as u32) as u64;
},
ebpf::OR32_IMM => reg[dst] = (reg[dst] as u32 | insn.imm as u32) as u64,
ebpf::OR32_REG => reg[dst] = (reg[dst] as u32 | reg[src] as u32) as u64,
ebpf::AND32_IMM => reg[dst] = (reg[dst] as u32 & insn.imm as u32) as u64,
ebpf::AND32_REG => reg[dst] = (reg[dst] as u32 & reg[src] as u32) as u64,
ebpf::LSH32_IMM => reg[dst] = (reg[dst] as u32).wrapping_shl(insn.imm as u32) as u64,
ebpf::LSH32_REG => reg[dst] = (reg[dst] as u32).wrapping_shl(reg[src] as u32) as u64,
ebpf::RSH32_IMM => reg[dst] = (reg[dst] as u32).wrapping_shr(insn.imm as u32) as u64,
ebpf::RSH32_REG => reg[dst] = (reg[dst] as u32).wrapping_shr(reg[src] as u32) as u64,
ebpf::NEG32 => { reg[dst] = (reg[dst] as i32).wrapping_neg() as u64; reg[dst] &= U32MAX; },
ebpf::MOD32_IMM => reg[dst] = (reg[dst] as u32 % insn.imm as u32) as u64,
ebpf::MOD32_REG => {
if reg[src] as u32 == 0 {
return Err(EbpfError::DivideByZero(pc + ebpf::ELF_INSN_DUMP_OFFSET));
}
reg[dst] = (reg[dst] as u32 % reg[src] as u32) as u64;
},
ebpf::XOR32_IMM => reg[dst] = (reg[dst] as u32 ^ insn.imm as u32) as u64,
ebpf::XOR32_REG => reg[dst] = (reg[dst] as u32 ^ reg[src] as u32) as u64,
ebpf::MOV32_IMM => reg[dst] = insn.imm as u32 as u64,
ebpf::MOV32_REG => reg[dst] = (reg[src] as u32) as u64,
ebpf::ARSH32_IMM => { reg[dst] = (reg[dst] as i32).wrapping_shr(insn.imm as u32) as u64; reg[dst] &= U32MAX; },
ebpf::ARSH32_REG => { reg[dst] = (reg[dst] as i32).wrapping_shr(reg[src] as u32) as u64; reg[dst] &= U32MAX; },
ebpf::LE => {
reg[dst] = match insn.imm {
16 => (reg[dst] as u16).to_le() as u64,
32 => (reg[dst] as u32).to_le() as u64,
64 => reg[dst].to_le(),
_ => unreachable!(),
};
},
ebpf::BE => {
reg[dst] = match insn.imm {
16 => (reg[dst] as u16).to_be() as u64,
32 => (reg[dst] as u32).to_be() as u64,
64 => reg[dst].to_be(),
_ => unreachable!(),
};
},
// BPF_ALU64 class
ebpf::ADD64_IMM => reg[dst] = reg[dst].wrapping_add(insn.imm as u64),
ebpf::ADD64_REG => reg[dst] = reg[dst].wrapping_add(reg[src]),
ebpf::SUB64_IMM => reg[dst] = reg[dst].wrapping_sub(insn.imm as u64),
ebpf::SUB64_REG => reg[dst] = reg[dst].wrapping_sub(reg[src]),
ebpf::MUL64_IMM => reg[dst] = reg[dst].wrapping_mul(insn.imm as u64),
ebpf::MUL64_REG => reg[dst] = reg[dst].wrapping_mul(reg[src]),
ebpf::DIV64_IMM => reg[dst] /= insn.imm as u64,
ebpf::DIV64_REG => {
if reg[src] == 0 {
return Err(EbpfError::DivideByZero(pc + ebpf::ELF_INSN_DUMP_OFFSET));
}
reg[dst] /= reg[src];
},
ebpf::OR64_IMM => reg[dst] |= insn.imm as u64,
ebpf::OR64_REG => reg[dst] |= reg[src],
ebpf::AND64_IMM => reg[dst] &= insn.imm as u64,
ebpf::AND64_REG => reg[dst] &= reg[src],
ebpf::LSH64_IMM => reg[dst] = reg[dst].wrapping_shl(insn.imm as u32),