lib.rs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  1. // SPDX-License-Identifier: (Apache-2.0 OR MIT)
  2. // Derived from uBPF <https://github.com/iovisor/ubpf>
  3. // Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com>
  4. // Copyright 2023 Isovalent, Inc. <quentin@isovalent.com>
  5. //! Virtual machine and JIT compiler for eBPF programs.
  6. #![doc(
  7. html_logo_url = "https://raw.githubusercontent.com/qmonnet/rbpf/main/misc/rbpf.png",
  8. html_favicon_url = "https://raw.githubusercontent.com/qmonnet/rbpf/main/misc/rbpf.ico"
  9. )]
  10. // Test examples from README.md as part as doc tests.
  11. #![doc = include_str!("../README.md")]
  12. // Configures the crate to be `no_std` when `std` feature is disabled.
  13. #![cfg_attr(not(feature = "std"), no_std)]
  14. extern crate byteorder;
  15. extern crate combine;
  16. extern crate log;
  17. #[cfg(feature = "std")]
  18. extern crate time;
  19. #[cfg(not(feature = "std"))]
  20. extern crate alloc;
  21. #[cfg(feature = "cranelift")]
  22. extern crate cranelift_codegen;
  23. #[cfg(feature = "cranelift")]
  24. extern crate cranelift_frontend;
  25. #[cfg(feature = "cranelift")]
  26. extern crate cranelift_jit;
  27. #[cfg(feature = "cranelift")]
  28. extern crate cranelift_module;
  29. #[cfg(feature = "cranelift")]
  30. extern crate cranelift_native;
  31. use crate::lib::*;
  32. use byteorder::{ByteOrder, LittleEndian};
  33. mod asm_parser;
  34. pub mod assembler;
  35. #[cfg(feature = "cranelift")]
  36. mod cranelift;
  37. pub mod disassembler;
  38. pub mod ebpf;
  39. pub mod helpers;
  40. pub mod insn_builder;
  41. mod interpreter;
  42. #[cfg(all(not(windows), feature = "std"))]
  43. mod jit;
  44. #[cfg(not(feature = "std"))]
  45. mod no_std_error;
  46. mod verifier;
  47. /// Reexports all the types needed from the `std`, `core`, and `alloc`
  48. /// crates. This avoids elaborate import wrangling having to happen in every
  49. /// module. Inspired by the design used in `serde`.
  50. pub mod lib {
  51. mod core {
  52. #[cfg(not(feature = "std"))]
  53. pub use core::*;
  54. #[cfg(feature = "std")]
  55. pub use std::*;
  56. }
  57. pub use self::core::convert::TryInto;
  58. pub use self::core::mem;
  59. pub use self::core::mem::ManuallyDrop;
  60. pub use self::core::ptr;
  61. pub use self::core::f64;
  62. #[cfg(feature = "std")]
  63. pub use std::println;
  64. #[cfg(not(feature = "std"))]
  65. pub use alloc::vec;
  66. #[cfg(not(feature = "std"))]
  67. pub use alloc::vec::Vec;
  68. #[cfg(feature = "std")]
  69. pub use std::vec::Vec;
  70. #[cfg(not(feature = "std"))]
  71. pub use alloc::string::{String, ToString};
  72. #[cfg(feature = "std")]
  73. pub use std::string::{String, ToString};
  74. // In no_std we cannot use randomness for hashing, thus we need to use
  75. // BTree-based implementations of Maps and Sets. The cranelift module uses
  76. // BTrees by default, hence we need to expose it twice here.
  77. #[cfg(not(feature = "std"))]
  78. pub use alloc::collections::{BTreeMap as HashMap, BTreeMap, BTreeSet as HashSet, BTreeSet};
  79. #[cfg(feature = "std")]
  80. pub use std::collections::{BTreeMap, HashMap, HashSet};
  81. /// In no_std we use a custom implementation of the error which acts as a
  82. /// replacement for the io Error.
  83. #[cfg(not(feature = "std"))]
  84. pub use crate::no_std_error::{Error, ErrorKind};
  85. #[cfg(feature = "std")]
  86. pub use std::io::{Error, ErrorKind};
  87. #[cfg(not(feature = "std"))]
  88. pub use alloc::format;
  89. }
  90. /// eBPF verification function that returns an error if the program does not meet its requirements.
  91. ///
  92. /// Some examples of things the verifier may reject the program for:
  93. ///
  94. /// - Program does not terminate.
  95. /// - Unknown instructions.
  96. /// - Bad formed instruction.
  97. /// - Unknown eBPF helper index.
  98. pub type Verifier = fn(prog: &[u8]) -> Result<(), Error>;
  99. /// eBPF helper function.
  100. pub type Helper = fn(u64, u64, u64, u64, u64) -> u64;
  101. // A metadata buffer with two offset indications. It can be used in one kind of eBPF VM to simulate
  102. // the use of a metadata buffer each time the program is executed, without the user having to
  103. // actually handle it. The offsets are used to tell the VM where in the buffer the pointers to
  104. // packet data start and end should be stored each time the program is run on a new packet.
  105. struct MetaBuff {
  106. data_offset: usize,
  107. data_end_offset: usize,
  108. buffer: Vec<u8>,
  109. }
  110. /// A virtual machine to run eBPF program. This kind of VM is used for programs expecting to work
  111. /// on a metadata buffer containing pointers to packet data.
  112. ///
  113. /// # Examples
  114. ///
  115. /// ```
  116. /// let prog = &[
  117. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff at offset 8 into R1.
  118. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  119. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  120. /// ];
  121. /// let mem = &mut [
  122. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  123. /// ];
  124. ///
  125. /// // Just for the example we create our metadata buffer from scratch, and we store the pointers
  126. /// // to packet data start and end in it.
  127. /// let mut mbuff = [0u8; 32];
  128. /// unsafe {
  129. /// let mut data = mbuff.as_ptr().offset(8) as *mut u64;
  130. /// let mut data_end = mbuff.as_ptr().offset(24) as *mut u64;
  131. /// *data = mem.as_ptr() as u64;
  132. /// *data_end = mem.as_ptr() as u64 + mem.len() as u64;
  133. /// }
  134. ///
  135. /// // Instantiate a VM.
  136. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  137. ///
  138. /// // Provide both a reference to the packet data, and to the metadata buffer.
  139. /// let res = vm.execute_program(mem, &mut mbuff).unwrap();
  140. /// assert_eq!(res, 0x2211);
  141. /// ```
  142. pub struct EbpfVmMbuff<'a> {
  143. prog: Option<&'a [u8]>,
  144. verifier: Verifier,
  145. #[cfg(all(not(windows), feature = "std"))]
  146. jit: Option<jit::JitMemory<'a>>,
  147. #[cfg(feature = "cranelift")]
  148. cranelift_prog: Option<cranelift::CraneliftProgram>,
  149. helpers: HashMap<u32, ebpf::Helper>,
  150. allowed_memory: HashSet<u64>,
  151. }
  152. impl<'a> EbpfVmMbuff<'a> {
  153. /// Create a new virtual machine instance, and load an eBPF program into that instance.
  154. /// When attempting to load the program, it passes through a simple verifier.
  155. ///
  156. /// # Examples
  157. ///
  158. /// ```
  159. /// let prog = &[
  160. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff into R1.
  161. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  162. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  163. /// ];
  164. ///
  165. /// // Instantiate a VM.
  166. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  167. /// ```
  168. pub fn new(prog: Option<&'a [u8]>) -> Result<EbpfVmMbuff<'a>, Error> {
  169. if let Some(prog) = prog {
  170. verifier::check(prog)?;
  171. }
  172. Ok(EbpfVmMbuff {
  173. prog,
  174. verifier: verifier::check,
  175. #[cfg(all(not(windows), feature = "std"))]
  176. jit: None,
  177. #[cfg(feature = "cranelift")]
  178. cranelift_prog: None,
  179. helpers: HashMap::new(),
  180. allowed_memory: HashSet::new(),
  181. })
  182. }
  183. /// Load a new eBPF program into the virtual machine instance.
  184. ///
  185. /// # Examples
  186. ///
  187. /// ```
  188. /// let prog1 = &[
  189. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  190. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  191. /// ];
  192. /// let prog2 = &[
  193. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff into R1.
  194. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  195. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  196. /// ];
  197. ///
  198. /// // Instantiate a VM.
  199. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog1)).unwrap();
  200. /// vm.set_program(prog2).unwrap();
  201. /// ```
  202. pub fn set_program(&mut self, prog: &'a [u8]) -> Result<(), Error> {
  203. (self.verifier)(prog)?;
  204. self.prog = Some(prog);
  205. Ok(())
  206. }
  207. /// Set a new verifier function. The function should return an `Error` if the program should be
  208. /// rejected by the virtual machine. If a program has been loaded to the VM already, the
  209. /// verifier is immediately run.
  210. ///
  211. /// # Examples
  212. ///
  213. /// ```
  214. /// use rbpf::lib::{Error, ErrorKind};
  215. /// use rbpf::ebpf;
  216. ///
  217. /// // Define a simple verifier function.
  218. /// fn verifier(prog: &[u8]) -> Result<(), Error> {
  219. /// let last_insn = ebpf::get_insn(prog, (prog.len() / ebpf::INSN_SIZE) - 1);
  220. /// if last_insn.opc != ebpf::EXIT {
  221. /// return Err(Error::new(ErrorKind::Other,
  222. /// "[Verifier] Error: program does not end with “EXIT” instruction"));
  223. /// }
  224. /// Ok(())
  225. /// }
  226. ///
  227. /// let prog1 = &[
  228. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  229. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  230. /// ];
  231. ///
  232. /// // Instantiate a VM.
  233. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog1)).unwrap();
  234. /// // Change the verifier.
  235. /// vm.set_verifier(verifier).unwrap();
  236. /// ```
  237. pub fn set_verifier(&mut self, verifier: Verifier) -> Result<(), Error> {
  238. if let Some(prog) = self.prog {
  239. verifier(prog)?;
  240. }
  241. self.verifier = verifier;
  242. Ok(())
  243. }
  244. /// Register a built-in or user-defined helper function in order to use it later from within
  245. /// the eBPF program. The helper is registered into a hashmap, so the `key` can be any `u32`.
  246. ///
  247. /// If using JIT-compiled eBPF programs, be sure to register all helpers before compiling the
  248. /// program. You should be able to change registered helpers after compiling, but not to add
  249. /// new ones (i.e. with new keys).
  250. ///
  251. /// # Examples
  252. ///
  253. /// ```
  254. /// use rbpf::helpers;
  255. ///
  256. /// // This program was compiled with clang, from a C program containing the following single
  257. /// // instruction: `return bpf_trace_printk("foo %c %c %c\n", 10, 1, 2, 3);`
  258. /// let prog = &[
  259. /// 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load 0 as u64 into r1 (That would be
  260. /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // replaced by tc by the address of
  261. /// // the format string, in the .map
  262. /// // section of the ELF file).
  263. /// 0xb7, 0x02, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, // mov r2, 10
  264. /// 0xb7, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // mov r3, 1
  265. /// 0xb7, 0x04, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // mov r4, 2
  266. /// 0xb7, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // mov r5, 3
  267. /// 0x85, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, // call helper with key 6
  268. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  269. /// ];
  270. ///
  271. /// // Instantiate a VM.
  272. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  273. ///
  274. /// // Register a helper.
  275. /// // On running the program this helper will print the content of registers r3, r4 and r5 to
  276. /// // standard output.
  277. /// # #[cfg(feature = "std")]
  278. /// vm.register_helper(6, helpers::bpf_trace_printf).unwrap();
  279. /// ```
  280. pub fn register_helper(&mut self, key: u32, function: Helper) -> Result<(), Error> {
  281. self.helpers.insert(key, function);
  282. Ok(())
  283. }
  284. /// Register a set of addresses that the eBPF program is allowed to load and store.
  285. ///
  286. /// When using certain helpers, typically map lookups, the Linux kernel will return pointers
  287. /// to structs that the eBPF program needs to interact with. By default rbpf only allows the
  288. /// program to interact with its stack, the memory buffer and the program itself, making it
  289. /// impossible to supply functional implementations of these helpers.
  290. /// This option allows you to pass in a list of addresses that rbpf will allow the program
  291. /// to load and store to. Given Rust's memory model you will always know these addresses up
  292. /// front when implementing the helpers.
  293. ///
  294. /// Each invocation of this method will append to the set of allowed addresses.
  295. ///
  296. /// # Examples
  297. ///
  298. /// ```
  299. /// use std::iter::FromIterator;
  300. /// use std::ptr::addr_of;
  301. ///
  302. /// struct MapValue {
  303. /// data: u8
  304. /// }
  305. /// static VALUE: MapValue = MapValue { data: 1 };
  306. ///
  307. /// let prog = &[
  308. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  309. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  310. /// ];
  311. ///
  312. /// // Instantiate a VM.
  313. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  314. /// let start = addr_of!(VALUE) as u64;
  315. /// let addrs = Vec::from_iter(start..start+size_of::<MapValue>() as u64);
  316. /// vm.register_allowed_memory(&addrs);
  317. /// ```
  318. pub fn register_allowed_memory(&mut self, addrs: &[u64]) {
  319. for i in addrs {
  320. self.allowed_memory.insert(*i);
  321. }
  322. }
  323. /// Execute the program loaded, with the given packet data and metadata buffer.
  324. ///
  325. /// If the program is made to be compatible with Linux kernel, it is expected to load the
  326. /// address of the beginning and of the end of the memory area used for packet data from the
  327. /// metadata buffer, at some appointed offsets. It is up to the user to ensure that these
  328. /// pointers are correctly stored in the buffer.
  329. ///
  330. /// # Examples
  331. ///
  332. /// ```
  333. /// let prog = &[
  334. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff into R1.
  335. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  336. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  337. /// ];
  338. /// let mem = &mut [
  339. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  340. /// ];
  341. ///
  342. /// // Just for the example we create our metadata buffer from scratch, and we store the
  343. /// // pointers to packet data start and end in it.
  344. /// let mut mbuff = [0u8; 32];
  345. /// unsafe {
  346. /// let mut data = mbuff.as_ptr().offset(8) as *mut u64;
  347. /// let mut data_end = mbuff.as_ptr().offset(24) as *mut u64;
  348. /// *data = mem.as_ptr() as u64;
  349. /// *data_end = mem.as_ptr() as u64 + mem.len() as u64;
  350. /// }
  351. ///
  352. /// // Instantiate a VM.
  353. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  354. ///
  355. /// // Provide both a reference to the packet data, and to the metadata buffer.
  356. /// let res = vm.execute_program(mem, &mut mbuff).unwrap();
  357. /// assert_eq!(res, 0x2211);
  358. /// ```
  359. pub fn execute_program(&self, mem: &[u8], mbuff: &[u8]) -> Result<u64, Error> {
  360. interpreter::execute_program(self.prog, mem, mbuff, &self.helpers, &self.allowed_memory)
  361. }
  362. /// JIT-compile the loaded program. No argument required for this.
  363. ///
  364. /// If using helper functions, be sure to register them into the VM before calling this
  365. /// function.
  366. ///
  367. /// # Examples
  368. ///
  369. /// ```
  370. /// let prog = &[
  371. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff into R1.
  372. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  373. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  374. /// ];
  375. ///
  376. /// // Instantiate a VM.
  377. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  378. ///
  379. /// vm.jit_compile();
  380. /// ```
  381. #[cfg(all(not(windows), feature = "std"))]
  382. pub fn jit_compile(&mut self) -> Result<(), Error> {
  383. let prog = match self.prog {
  384. Some(prog) => prog,
  385. None => Err(Error::new(
  386. ErrorKind::Other,
  387. "Error: No program set, call prog_set() to load one",
  388. ))?,
  389. };
  390. self.jit = Some(jit::JitMemory::new(prog, &self.helpers, true, false)?);
  391. Ok(())
  392. }
  393. /// Execute the previously JIT-compiled program, with the given packet data and metadata
  394. /// buffer, in a manner very similar to `execute_program()`.
  395. ///
  396. /// If the program is made to be compatible with Linux kernel, it is expected to load the
  397. /// address of the beginning and of the end of the memory area used for packet data from the
  398. /// metadata buffer, at some appointed offsets. It is up to the user to ensure that these
  399. /// pointers are correctly stored in the buffer.
  400. ///
  401. /// # Safety
  402. ///
  403. /// **WARNING:** JIT-compiled assembly code is not safe, in particular there is no runtime
  404. /// check for memory access; so if the eBPF program attempts erroneous accesses, this may end
  405. /// very bad (program may segfault). It may be wise to check that the program works with the
  406. /// interpreter before running the JIT-compiled version of it.
  407. ///
  408. /// For this reason the function should be called from within an `unsafe` bloc.
  409. ///
  410. /// # Examples
  411. ///
  412. /// ```
  413. /// let prog = &[
  414. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff into r1.
  415. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  416. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  417. /// ];
  418. /// let mem = &mut [
  419. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  420. /// ];
  421. ///
  422. /// // Just for the example we create our metadata buffer from scratch, and we store the
  423. /// // pointers to packet data start and end in it.
  424. /// let mut mbuff = [0u8; 32];
  425. /// unsafe {
  426. /// let mut data = mbuff.as_ptr().offset(8) as *mut u64;
  427. /// let mut data_end = mbuff.as_ptr().offset(24) as *mut u64;
  428. /// *data = mem.as_ptr() as u64;
  429. /// *data_end = mem.as_ptr() as u64 + mem.len() as u64;
  430. /// }
  431. ///
  432. /// // Instantiate a VM.
  433. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  434. ///
  435. /// # #[cfg(all(not(windows), feature = "std"))]
  436. /// vm.jit_compile();
  437. ///
  438. /// // Provide both a reference to the packet data, and to the metadata buffer.
  439. /// # #[cfg(all(not(windows), feature = "std"))]
  440. /// unsafe {
  441. /// let res = vm.execute_program_jit(mem, &mut mbuff).unwrap();
  442. /// assert_eq!(res, 0x2211);
  443. /// }
  444. /// ```
  445. #[cfg(all(not(windows), feature = "std"))]
  446. pub unsafe fn execute_program_jit(
  447. &self,
  448. mem: &mut [u8],
  449. mbuff: &'a mut [u8],
  450. ) -> Result<u64, Error> {
  451. // If packet data is empty, do not send the address of an empty slice; send a null pointer
  452. // as first argument instead, as this is uBPF's behavior (empty packet should not happen
  453. // in the kernel; anyway the verifier would prevent the use of uninitialized registers).
  454. // See `mul_loop` test.
  455. let mem_ptr = match mem.len() {
  456. 0 => std::ptr::null_mut(),
  457. _ => mem.as_ptr() as *mut u8,
  458. };
  459. // The last two arguments are not used in this function. They would be used if there was a
  460. // need to indicate to the JIT at which offset in the mbuff mem_ptr and mem_ptr + mem.len()
  461. // should be stored; this is what happens with struct EbpfVmFixedMbuff.
  462. match &self.jit {
  463. Some(jit) => Ok(jit.get_prog()(
  464. mbuff.as_ptr() as *mut u8,
  465. mbuff.len(),
  466. mem_ptr,
  467. mem.len(),
  468. 0,
  469. 0,
  470. )),
  471. None => Err(Error::new(
  472. ErrorKind::Other,
  473. "Error: program has not been JIT-compiled",
  474. )),
  475. }
  476. }
  477. /// Compile the loaded program using the Cranelift JIT.
  478. ///
  479. /// If using helper functions, be sure to register them into the VM before calling this
  480. /// function.
  481. ///
  482. /// # Examples
  483. ///
  484. /// ```
  485. /// let prog = &[
  486. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff into R1.
  487. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  488. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  489. /// ];
  490. ///
  491. /// // Instantiate a VM.
  492. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  493. ///
  494. /// vm.cranelift_compile();
  495. /// ```
  496. #[cfg(feature = "cranelift")]
  497. pub fn cranelift_compile(&mut self) -> Result<(), Error> {
  498. use crate::cranelift::CraneliftCompiler;
  499. let prog = match self.prog {
  500. Some(prog) => prog,
  501. None => Err(Error::new(
  502. ErrorKind::Other,
  503. "Error: No program set, call prog_set() to load one",
  504. ))?,
  505. };
  506. let compiler = CraneliftCompiler::new(self.helpers.clone());
  507. let program = compiler.compile_function(prog)?;
  508. self.cranelift_prog = Some(program);
  509. Ok(())
  510. }
  511. /// Execute the previously compiled program, with the given packet data and metadata
  512. /// buffer, in a manner very similar to `execute_program()`.
  513. ///
  514. /// If the program is made to be compatible with Linux kernel, it is expected to load the
  515. /// address of the beginning and of the end of the memory area used for packet data from the
  516. /// metadata buffer, at some appointed offsets. It is up to the user to ensure that these
  517. /// pointers are correctly stored in the buffer.
  518. ///
  519. ///
  520. /// # Examples
  521. ///
  522. /// ```
  523. /// let prog = &[
  524. /// 0x79, 0x11, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // Load mem from mbuff into r1.
  525. /// 0x69, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // ldhx r1[2], r0
  526. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  527. /// ];
  528. /// let mem = &mut [
  529. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  530. /// ];
  531. ///
  532. /// // Just for the example we create our metadata buffer from scratch, and we store the
  533. /// // pointers to packet data start and end in it.
  534. /// let mut mbuff = [0u8; 32];
  535. /// unsafe {
  536. /// let mut data = mbuff.as_ptr().offset(8) as *mut u64;
  537. /// let mut data_end = mbuff.as_ptr().offset(24) as *mut u64;
  538. /// *data = mem.as_ptr() as u64;
  539. /// *data_end = mem.as_ptr() as u64 + mem.len() as u64;
  540. /// }
  541. ///
  542. /// // Instantiate a VM.
  543. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog)).unwrap();
  544. ///
  545. /// vm.cranelift_compile();
  546. ///
  547. /// // Provide both a reference to the packet data, and to the metadata buffer.
  548. /// let res = vm.execute_program_cranelift(mem, &mut mbuff).unwrap();
  549. /// assert_eq!(res, 0x2211);
  550. /// ```
  551. #[cfg(feature = "cranelift")]
  552. pub fn execute_program_cranelift(
  553. &self,
  554. mem: &mut [u8],
  555. mbuff: &'a mut [u8],
  556. ) -> Result<u64, Error> {
  557. // If packet data is empty, do not send the address of an empty slice; send a null pointer
  558. // as first argument instead, as this is uBPF's behavior (empty packet should not happen
  559. // in the kernel; anyway the verifier would prevent the use of uninitialized registers).
  560. // See `mul_loop` test.
  561. let mem_ptr = match mem.len() {
  562. 0 => ptr::null_mut(),
  563. _ => mem.as_ptr() as *mut u8,
  564. };
  565. // The last two arguments are not used in this function. They would be used if there was a
  566. // need to indicate to the JIT at which offset in the mbuff mem_ptr and mem_ptr + mem.len()
  567. // should be stored; this is what happens with struct EbpfVmFixedMbuff.
  568. match &self.cranelift_prog {
  569. Some(prog) => {
  570. Ok(prog.execute(mem_ptr, mem.len(), mbuff.as_ptr() as *mut u8, mbuff.len()))
  571. }
  572. None => Err(Error::new(
  573. ErrorKind::Other,
  574. "Error: program has not been compiled with cranelift",
  575. )),
  576. }
  577. }
  578. }
  579. /// A virtual machine to run eBPF program. This kind of VM is used for programs expecting to work
  580. /// on a metadata buffer containing pointers to packet data, but it internally handles the buffer
  581. /// so as to save the effort to manually handle the metadata buffer for the user.
  582. ///
  583. /// This struct implements a static internal buffer that is passed to the program. The user has to
  584. /// indicate the offset values at which the eBPF program expects to find the start and the end of
  585. /// packet data in the buffer. On calling the `execute_program()` or `execute_program_jit()` functions, the
  586. /// struct automatically updates the addresses in this static buffer, at the appointed offsets, for
  587. /// the start and the end of the packet data the program is called upon.
  588. ///
  589. /// # Examples
  590. ///
  591. /// This was compiled with clang from the following program, in C:
  592. ///
  593. /// ```c
  594. /// #include <linux/bpf.h>
  595. /// #include "path/to/linux/samples/bpf/bpf_helpers.h"
  596. ///
  597. /// SEC(".classifier")
  598. /// int classifier(struct __sk_buff *skb)
  599. /// {
  600. /// void *data = (void *)(long)skb->data;
  601. /// void *data_end = (void *)(long)skb->data_end;
  602. ///
  603. /// // Check program is long enough.
  604. /// if (data + 5 > data_end)
  605. /// return 0;
  606. ///
  607. /// return *((char *)data + 5);
  608. /// }
  609. /// ```
  610. ///
  611. /// Some small modifications have been brought to have it work, see comments.
  612. ///
  613. /// ```
  614. /// let prog = &[
  615. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  616. /// // Here opcode 0x61 had to be replace by 0x79 so as to load a 8-bytes long address.
  617. /// // Also, offset 0x4c had to be replace with e.g. 0x40 so as to prevent the two pointers
  618. /// // from overlapping in the buffer.
  619. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load pointer to mem from r1[0x40] to r2
  620. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  621. /// // Here opcode 0x61 had to be replace by 0x79 so as to load a 8-bytes long address.
  622. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load ptr to mem_end from r1[0x50] to r1
  623. /// 0x2d, 0x12, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  624. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  625. /// 0x67, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, // r0 >>= 56
  626. /// 0xc7, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, // r0 <<= 56 (arsh) extend byte sign to u64
  627. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  628. /// ];
  629. /// let mem1 = &mut [
  630. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  631. /// ];
  632. /// let mem2 = &mut [
  633. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0x27
  634. /// ];
  635. ///
  636. /// // Instantiate a VM. Note that we provide the start and end offsets for mem pointers.
  637. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  638. ///
  639. /// // Provide only a reference to the packet data. We do not manage the metadata buffer.
  640. /// let res = vm.execute_program(mem1).unwrap();
  641. /// assert_eq!(res, 0xffffffffffffffdd);
  642. ///
  643. /// let res = vm.execute_program(mem2).unwrap();
  644. /// assert_eq!(res, 0x27);
  645. /// ```
  646. pub struct EbpfVmFixedMbuff<'a> {
  647. parent: EbpfVmMbuff<'a>,
  648. mbuff: MetaBuff,
  649. }
  650. impl<'a> EbpfVmFixedMbuff<'a> {
  651. /// Create a new virtual machine instance, and load an eBPF program into that instance.
  652. /// When attempting to load the program, it passes through a simple verifier.
  653. ///
  654. /// # Examples
  655. ///
  656. /// ```
  657. /// let prog = &[
  658. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  659. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  660. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  661. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  662. /// 0x2d, 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  663. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  664. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  665. /// ];
  666. ///
  667. /// // Instantiate a VM. Note that we provide the start and end offsets for mem pointers.
  668. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  669. /// ```
  670. pub fn new(
  671. prog: Option<&'a [u8]>,
  672. data_offset: usize,
  673. data_end_offset: usize,
  674. ) -> Result<EbpfVmFixedMbuff<'a>, Error> {
  675. let parent = EbpfVmMbuff::new(prog)?;
  676. let get_buff_len = |x: usize, y: usize| if x >= y { x + 8 } else { y + 8 };
  677. let buffer = vec![0u8; get_buff_len(data_offset, data_end_offset)];
  678. let mbuff = MetaBuff {
  679. data_offset,
  680. data_end_offset,
  681. buffer,
  682. };
  683. Ok(EbpfVmFixedMbuff { parent, mbuff })
  684. }
  685. /// Load a new eBPF program into the virtual machine instance.
  686. ///
  687. /// At the same time, load new offsets for storing pointers to start and end of packet data in
  688. /// the internal metadata buffer.
  689. ///
  690. /// # Examples
  691. ///
  692. /// ```
  693. /// let prog1 = &[
  694. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  695. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  696. /// ];
  697. /// let prog2 = &[
  698. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  699. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  700. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  701. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  702. /// 0x2d, 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  703. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  704. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  705. /// ];
  706. ///
  707. /// let mem = &mut [
  708. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0x27,
  709. /// ];
  710. ///
  711. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog1), 0, 0).unwrap();
  712. /// vm.set_program(prog2, 0x40, 0x50);
  713. ///
  714. /// let res = vm.execute_program(mem).unwrap();
  715. /// assert_eq!(res, 0x27);
  716. /// ```
  717. pub fn set_program(
  718. &mut self,
  719. prog: &'a [u8],
  720. data_offset: usize,
  721. data_end_offset: usize,
  722. ) -> Result<(), Error> {
  723. let get_buff_len = |x: usize, y: usize| if x >= y { x + 8 } else { y + 8 };
  724. let buffer = vec![0u8; get_buff_len(data_offset, data_end_offset)];
  725. self.mbuff.buffer = buffer;
  726. self.mbuff.data_offset = data_offset;
  727. self.mbuff.data_end_offset = data_end_offset;
  728. self.parent.set_program(prog)?;
  729. Ok(())
  730. }
  731. /// Set a new verifier function. The function should return an `Error` if the program should be
  732. /// rejected by the virtual machine. If a program has been loaded to the VM already, the
  733. /// verifier is immediately run.
  734. ///
  735. /// # Examples
  736. ///
  737. /// ```
  738. /// use rbpf::lib::{Error, ErrorKind};
  739. /// use rbpf::ebpf;
  740. ///
  741. /// // Define a simple verifier function.
  742. /// fn verifier(prog: &[u8]) -> Result<(), Error> {
  743. /// let last_insn = ebpf::get_insn(prog, (prog.len() / ebpf::INSN_SIZE) - 1);
  744. /// if last_insn.opc != ebpf::EXIT {
  745. /// return Err(Error::new(ErrorKind::Other,
  746. /// "[Verifier] Error: program does not end with “EXIT” instruction"));
  747. /// }
  748. /// Ok(())
  749. /// }
  750. ///
  751. /// let prog1 = &[
  752. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  753. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  754. /// ];
  755. ///
  756. /// // Instantiate a VM.
  757. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog1)).unwrap();
  758. /// // Change the verifier.
  759. /// vm.set_verifier(verifier).unwrap();
  760. /// ```
  761. pub fn set_verifier(&mut self, verifier: Verifier) -> Result<(), Error> {
  762. self.parent.set_verifier(verifier)
  763. }
  764. /// Register a built-in or user-defined helper function in order to use it later from within
  765. /// the eBPF program. The helper is registered into a hashmap, so the `key` can be any `u32`.
  766. ///
  767. /// If using JIT-compiled eBPF programs, be sure to register all helpers before compiling the
  768. /// program. You should be able to change registered helpers after compiling, but not to add
  769. /// new ones (i.e. with new keys).
  770. ///
  771. /// # Examples
  772. ///
  773. /// ```
  774. /// #[cfg(feature = "std")] {
  775. /// use rbpf::helpers;
  776. ///
  777. /// // This program was compiled with clang, from a C program containing the following single
  778. /// // instruction: `return bpf_trace_printk("foo %c %c %c\n", 10, 1, 2, 3);`
  779. /// let prog = &[
  780. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  781. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  782. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  783. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  784. /// 0x2d, 0x12, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 6 instructions
  785. /// 0x71, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r1
  786. /// 0xb7, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r2, 0
  787. /// 0xb7, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r3, 0
  788. /// 0xb7, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r4, 0
  789. /// 0xb7, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r5, 0
  790. /// 0x85, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // call helper with key 1
  791. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  792. /// ];
  793. ///
  794. /// let mem = &mut [
  795. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0x09,
  796. /// ];
  797. ///
  798. /// // Instantiate a VM.
  799. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  800. ///
  801. /// // Register a helper. This helper will store the result of the square root of r1 into r0.
  802. /// vm.register_helper(1, helpers::sqrti);
  803. ///
  804. /// let res = vm.execute_program(mem).unwrap();
  805. /// assert_eq!(res, 3);
  806. /// }
  807. /// ```
  808. pub fn register_helper(
  809. &mut self,
  810. key: u32,
  811. function: fn(u64, u64, u64, u64, u64) -> u64,
  812. ) -> Result<(), Error> {
  813. self.parent.register_helper(key, function)
  814. }
  815. /// Register an object that the eBPF program is allowed to load and store.
  816. ///
  817. /// When using certain helpers, typically map lookups, the Linux kernel will return pointers
  818. /// to structs that the eBPF program needs to interact with. By default rbpf only allows the
  819. /// program to interact with its stack, the memory buffer and the program itself, making it
  820. /// impossible to supply functional implementations of these helpers.
  821. /// This option allows you to pass in a list of addresses that rbpf will allow the program
  822. /// to load and store to. Given Rust's memory model you will always know these addresses up
  823. /// front when implementing the helpers.
  824. ///
  825. /// Each invocation of this method will append to the set of allowed addresses.
  826. ///
  827. /// # Examples
  828. ///
  829. /// ```
  830. /// use std::iter::FromIterator;
  831. /// use std::ptr::addr_of;
  832. ///
  833. /// struct MapValue {
  834. /// data: u8
  835. /// }
  836. /// static VALUE: MapValue = MapValue { data: 1 };
  837. ///
  838. /// let prog = &[
  839. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  840. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  841. /// ];
  842. ///
  843. /// // Instantiate a VM.
  844. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  845. /// let start = addr_of!(VALUE) as u64;
  846. /// let addrs = Vec::from_iter(start..start+size_of::<MapValue>() as u64);
  847. /// vm.register_allowed_memory(&addrs);
  848. /// ```
  849. pub fn register_allowed_memory(&mut self, allowed: &[u64]) {
  850. self.parent.register_allowed_memory(allowed)
  851. }
  852. /// Execute the program loaded, with the given packet data.
  853. ///
  854. /// If the program is made to be compatible with Linux kernel, it is expected to load the
  855. /// address of the beginning and of the end of the memory area used for packet data from some
  856. /// metadata buffer, which in the case of this VM is handled internally. The offsets at which
  857. /// the addresses should be placed should have be set at the creation of the VM.
  858. ///
  859. /// # Examples
  860. ///
  861. /// ```
  862. /// let prog = &[
  863. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  864. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  865. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  866. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  867. /// 0x2d, 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  868. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  869. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  870. /// ];
  871. /// let mem = &mut [
  872. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  873. /// ];
  874. ///
  875. /// // Instantiate a VM. Note that we provide the start and end offsets for mem pointers.
  876. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  877. ///
  878. /// // Provide only a reference to the packet data. We do not manage the metadata buffer.
  879. /// let res = vm.execute_program(mem).unwrap();
  880. /// assert_eq!(res, 0xdd);
  881. /// ```
  882. pub fn execute_program(&mut self, mem: &'a mut [u8]) -> Result<u64, Error> {
  883. let l = self.mbuff.buffer.len();
  884. // Can this ever happen? Probably not, should be ensured at mbuff creation.
  885. if self.mbuff.data_offset + 8 > l || self.mbuff.data_end_offset + 8 > l {
  886. Err(Error::new(ErrorKind::Other, format!("Error: buffer too small ({:?}), cannot use data_offset {:?} and data_end_offset {:?}",
  887. l, self.mbuff.data_offset, self.mbuff.data_end_offset)))?;
  888. }
  889. LittleEndian::write_u64(
  890. &mut self.mbuff.buffer[(self.mbuff.data_offset)..],
  891. mem.as_ptr() as u64,
  892. );
  893. LittleEndian::write_u64(
  894. &mut self.mbuff.buffer[(self.mbuff.data_end_offset)..],
  895. mem.as_ptr() as u64 + mem.len() as u64,
  896. );
  897. self.parent.execute_program(mem, &self.mbuff.buffer)
  898. }
  899. /// JIT-compile the loaded program. No argument required for this.
  900. ///
  901. /// If using helper functions, be sure to register them into the VM before calling this
  902. /// function.
  903. ///
  904. /// # Examples
  905. ///
  906. /// ```
  907. /// let prog = &[
  908. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  909. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  910. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  911. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  912. /// 0x2d, 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  913. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  914. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  915. /// ];
  916. ///
  917. /// // Instantiate a VM. Note that we provide the start and end offsets for mem pointers.
  918. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  919. ///
  920. /// vm.jit_compile();
  921. /// ```
  922. #[cfg(all(not(windows), feature = "std"))]
  923. pub fn jit_compile(&mut self) -> Result<(), Error> {
  924. let prog = match self.parent.prog {
  925. Some(prog) => prog,
  926. None => Err(Error::new(
  927. ErrorKind::Other,
  928. "Error: No program set, call prog_set() to load one",
  929. ))?,
  930. };
  931. self.parent.jit = Some(jit::JitMemory::new(prog, &self.parent.helpers, true, true)?);
  932. Ok(())
  933. }
  934. /// Execute the previously JIT-compiled program, with the given packet data, in a manner very
  935. /// similar to `execute_program()`.
  936. ///
  937. /// If the program is made to be compatible with Linux kernel, it is expected to load the
  938. /// address of the beginning and of the end of the memory area used for packet data from some
  939. /// metadata buffer, which in the case of this VM is handled internally. The offsets at which
  940. /// the addresses should be placed should have be set at the creation of the VM.
  941. ///
  942. /// # Safety
  943. ///
  944. /// **WARNING:** JIT-compiled assembly code is not safe, in particular there is no runtime
  945. /// check for memory access; so if the eBPF program attempts erroneous accesses, this may end
  946. /// very bad (program may segfault). It may be wise to check that the program works with the
  947. /// interpreter before running the JIT-compiled version of it.
  948. ///
  949. /// For this reason the function should be called from within an `unsafe` bloc.
  950. ///
  951. /// # Examples
  952. ///
  953. /// ```
  954. /// let prog = &[
  955. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  956. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  957. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  958. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  959. /// 0x2d, 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  960. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  961. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  962. /// ];
  963. /// let mem = &mut [
  964. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  965. /// ];
  966. ///
  967. /// // Instantiate a VM. Note that we provide the start and end offsets for mem pointers.
  968. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  969. ///
  970. /// # #[cfg(all(not(windows), feature = "std"))]
  971. /// vm.jit_compile();
  972. ///
  973. /// // Provide only a reference to the packet data. We do not manage the metadata buffer.
  974. /// # #[cfg(all(not(windows), feature = "std"))]
  975. /// unsafe {
  976. /// let res = vm.execute_program_jit(mem).unwrap();
  977. /// assert_eq!(res, 0xdd);
  978. /// }
  979. /// ```
  980. // This struct redefines the `execute_program_jit()` function, in order to pass the offsets
  981. // associated with the fixed mbuff.
  982. #[cfg(all(not(windows), feature = "std"))]
  983. pub unsafe fn execute_program_jit(&mut self, mem: &'a mut [u8]) -> Result<u64, Error> {
  984. // If packet data is empty, do not send the address of an empty slice; send a null pointer
  985. // as first argument instead, as this is uBPF's behavior (empty packet should not happen
  986. // in the kernel; anyway the verifier would prevent the use of uninitialized registers).
  987. // See `mul_loop` test.
  988. let mem_ptr = match mem.len() {
  989. 0 => ptr::null_mut(),
  990. _ => mem.as_ptr() as *mut u8,
  991. };
  992. match &self.parent.jit {
  993. Some(jit) => Ok(jit.get_prog()(
  994. self.mbuff.buffer.as_ptr() as *mut u8,
  995. self.mbuff.buffer.len(),
  996. mem_ptr,
  997. mem.len(),
  998. self.mbuff.data_offset,
  999. self.mbuff.data_end_offset,
  1000. )),
  1001. None => Err(Error::new(
  1002. ErrorKind::Other,
  1003. "Error: program has not been JIT-compiled",
  1004. )),
  1005. }
  1006. }
  1007. /// Compile the loaded program using the Cranelift JIT.
  1008. ///
  1009. /// If using helper functions, be sure to register them into the VM before calling this
  1010. /// function.
  1011. ///
  1012. /// # Examples
  1013. ///
  1014. /// ```
  1015. /// let prog = &[
  1016. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1017. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  1018. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  1019. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  1020. /// 0x2d, 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  1021. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  1022. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1023. /// ];
  1024. ///
  1025. /// // Instantiate a VM. Note that we provide the start and end offsets for mem pointers.
  1026. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  1027. ///
  1028. /// vm.cranelift_compile();
  1029. /// ```
  1030. #[cfg(feature = "cranelift")]
  1031. pub fn cranelift_compile(&mut self) -> Result<(), Error> {
  1032. use crate::cranelift::CraneliftCompiler;
  1033. let prog = match self.parent.prog {
  1034. Some(prog) => prog,
  1035. None => Err(Error::new(
  1036. ErrorKind::Other,
  1037. "Error: No program set, call prog_set() to load one",
  1038. ))?,
  1039. };
  1040. let compiler = CraneliftCompiler::new(self.parent.helpers.clone());
  1041. let program = compiler.compile_function(prog)?;
  1042. self.parent.cranelift_prog = Some(program);
  1043. Ok(())
  1044. }
  1045. /// Execute the previously compiled program, with the given packet data and metadata
  1046. /// buffer, in a manner very similar to `execute_program()`.
  1047. ///
  1048. /// If the program is made to be compatible with Linux kernel, it is expected to load the
  1049. /// address of the beginning and of the end of the memory area used for packet data from some
  1050. /// metadata buffer, which in the case of this VM is handled internally. The offsets at which
  1051. /// the addresses should be placed should have be set at the creation of the VM.
  1052. ///
  1053. /// # Examples
  1054. ///
  1055. /// ```
  1056. /// let prog = &[
  1057. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1058. /// 0x79, 0x12, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem from r1[0x40] to r2
  1059. /// 0x07, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // add r2, 5
  1060. /// 0x79, 0x11, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, // load mem_end from r1[0x50] to r1
  1061. /// 0x2d, 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // if r2 > r1 skip 3 instructions
  1062. /// 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // load r2 (= *(mem + 5)) into r0
  1063. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1064. /// ];
  1065. /// let mem = &mut [
  1066. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  1067. /// ];
  1068. ///
  1069. /// // Instantiate a VM. Note that we provide the start and end offsets for mem pointers.
  1070. /// let mut vm = rbpf::EbpfVmFixedMbuff::new(Some(prog), 0x40, 0x50).unwrap();
  1071. ///
  1072. /// vm.cranelift_compile();
  1073. ///
  1074. /// // Provide only a reference to the packet data. We do not manage the metadata buffer.
  1075. /// let res = vm.execute_program_cranelift(mem).unwrap();
  1076. /// assert_eq!(res, 0xdd);
  1077. /// ```
  1078. #[cfg(feature = "cranelift")]
  1079. pub fn execute_program_cranelift(&mut self, mem: &'a mut [u8]) -> Result<u64, Error> {
  1080. // If packet data is empty, do not send the address of an empty slice; send a null pointer
  1081. // as first argument instead, as this is uBPF's behavior (empty packet should not happen
  1082. // in the kernel; anyway the verifier would prevent the use of uninitialized registers).
  1083. // See `mul_loop` test.
  1084. let mem_ptr = match mem.len() {
  1085. 0 => ptr::null_mut(),
  1086. _ => mem.as_ptr() as *mut u8,
  1087. };
  1088. let l = self.mbuff.buffer.len();
  1089. // Can this ever happen? Probably not, should be ensured at mbuff creation.
  1090. if self.mbuff.data_offset + 8 > l || self.mbuff.data_end_offset + 8 > l {
  1091. Err(Error::new(ErrorKind::Other, format!("Error: buffer too small ({:?}), cannot use data_offset {:?} and data_end_offset {:?}",
  1092. l, self.mbuff.data_offset, self.mbuff.data_end_offset)))?;
  1093. }
  1094. LittleEndian::write_u64(
  1095. &mut self.mbuff.buffer[(self.mbuff.data_offset)..],
  1096. mem.as_ptr() as u64,
  1097. );
  1098. LittleEndian::write_u64(
  1099. &mut self.mbuff.buffer[(self.mbuff.data_end_offset)..],
  1100. mem.as_ptr() as u64 + mem.len() as u64,
  1101. );
  1102. match &self.parent.cranelift_prog {
  1103. Some(prog) => Ok(prog.execute(
  1104. mem_ptr,
  1105. mem.len(),
  1106. self.mbuff.buffer.as_ptr() as *mut u8,
  1107. self.mbuff.buffer.len(),
  1108. )),
  1109. None => Err(Error::new(
  1110. ErrorKind::Other,
  1111. "Error: program has not been compiled with cranelift",
  1112. )),
  1113. }
  1114. }
  1115. }
  1116. /// A virtual machine to run eBPF program. This kind of VM is used for programs expecting to work
  1117. /// directly on the memory area representing packet data.
  1118. ///
  1119. /// # Examples
  1120. ///
  1121. /// ```
  1122. /// let prog = &[
  1123. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1124. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1125. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1126. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1127. /// ];
  1128. /// let mem = &mut [
  1129. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd
  1130. /// ];
  1131. ///
  1132. /// // Instantiate a VM.
  1133. /// let vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1134. ///
  1135. /// // Provide only a reference to the packet data.
  1136. /// let res = vm.execute_program(mem).unwrap();
  1137. /// assert_eq!(res, 0x22cc);
  1138. /// ```
  1139. pub struct EbpfVmRaw<'a> {
  1140. parent: EbpfVmMbuff<'a>,
  1141. }
  1142. impl<'a> EbpfVmRaw<'a> {
  1143. /// Create a new virtual machine instance, and load an eBPF program into that instance.
  1144. /// When attempting to load the program, it passes through a simple verifier.
  1145. ///
  1146. /// # Examples
  1147. ///
  1148. /// ```
  1149. /// let prog = &[
  1150. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1151. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1152. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1153. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1154. /// ];
  1155. ///
  1156. /// // Instantiate a VM.
  1157. /// let vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1158. /// ```
  1159. pub fn new(prog: Option<&'a [u8]>) -> Result<EbpfVmRaw<'a>, Error> {
  1160. let parent = EbpfVmMbuff::new(prog)?;
  1161. Ok(EbpfVmRaw { parent })
  1162. }
  1163. /// Load a new eBPF program into the virtual machine instance.
  1164. ///
  1165. /// # Examples
  1166. ///
  1167. /// ```
  1168. /// let prog1 = &[
  1169. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1170. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1171. /// ];
  1172. /// let prog2 = &[
  1173. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1174. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1175. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1176. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1177. /// ];
  1178. ///
  1179. /// let mem = &mut [
  1180. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0x27,
  1181. /// ];
  1182. ///
  1183. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog1)).unwrap();
  1184. /// vm.set_program(prog2);
  1185. ///
  1186. /// let res = vm.execute_program(mem).unwrap();
  1187. /// assert_eq!(res, 0x22cc);
  1188. /// ```
  1189. pub fn set_program(&mut self, prog: &'a [u8]) -> Result<(), Error> {
  1190. self.parent.set_program(prog)?;
  1191. Ok(())
  1192. }
  1193. /// Set a new verifier function. The function should return an `Error` if the program should be
  1194. /// rejected by the virtual machine. If a program has been loaded to the VM already, the
  1195. /// verifier is immediately run.
  1196. ///
  1197. /// # Examples
  1198. ///
  1199. /// ```
  1200. /// use rbpf::lib::{Error, ErrorKind};
  1201. /// use rbpf::ebpf;
  1202. ///
  1203. /// // Define a simple verifier function.
  1204. /// fn verifier(prog: &[u8]) -> Result<(), Error> {
  1205. /// let last_insn = ebpf::get_insn(prog, (prog.len() / ebpf::INSN_SIZE) - 1);
  1206. /// if last_insn.opc != ebpf::EXIT {
  1207. /// return Err(Error::new(ErrorKind::Other,
  1208. /// "[Verifier] Error: program does not end with “EXIT” instruction"));
  1209. /// }
  1210. /// Ok(())
  1211. /// }
  1212. ///
  1213. /// let prog1 = &[
  1214. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1215. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1216. /// ];
  1217. ///
  1218. /// // Instantiate a VM.
  1219. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog1)).unwrap();
  1220. /// // Change the verifier.
  1221. /// vm.set_verifier(verifier).unwrap();
  1222. /// ```
  1223. pub fn set_verifier(&mut self, verifier: Verifier) -> Result<(), Error> {
  1224. self.parent.set_verifier(verifier)
  1225. }
  1226. /// Register a built-in or user-defined helper function in order to use it later from within
  1227. /// the eBPF program. The helper is registered into a hashmap, so the `key` can be any `u32`.
  1228. ///
  1229. /// If using JIT-compiled eBPF programs, be sure to register all helpers before compiling the
  1230. /// program. You should be able to change registered helpers after compiling, but not to add
  1231. /// new ones (i.e. with new keys).
  1232. ///
  1233. /// # Examples
  1234. ///
  1235. /// ```
  1236. /// #[cfg(feature = "std")] {
  1237. /// use rbpf::helpers;
  1238. ///
  1239. /// let prog = &[
  1240. /// 0x79, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxdw r1, r1[0x00]
  1241. /// 0xb7, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r2, 0
  1242. /// 0xb7, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r3, 0
  1243. /// 0xb7, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r4, 0
  1244. /// 0xb7, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r5, 0
  1245. /// 0x85, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // call helper with key 1
  1246. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1247. /// ];
  1248. ///
  1249. /// let mem = &mut [
  1250. /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
  1251. /// ];
  1252. ///
  1253. /// // Instantiate a VM.
  1254. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1255. ///
  1256. /// // Register a helper. This helper will store the result of the square root of r1 into r0.
  1257. /// vm.register_helper(1, helpers::sqrti);
  1258. ///
  1259. /// let res = vm.execute_program(mem).unwrap();
  1260. /// assert_eq!(res, 0x10000000);
  1261. /// }
  1262. /// ```
  1263. pub fn register_helper(
  1264. &mut self,
  1265. key: u32,
  1266. function: fn(u64, u64, u64, u64, u64) -> u64,
  1267. ) -> Result<(), Error> {
  1268. self.parent.register_helper(key, function)
  1269. }
  1270. /// Register an object that the eBPF program is allowed to load and store.
  1271. ///
  1272. /// When using certain helpers, typically map lookups, the Linux kernel will return pointers
  1273. /// to structs that the eBPF program needs to interact with. By default rbpf only allows the
  1274. /// program to interact with its stack, the memory buffer and the program itself, making it
  1275. /// impossible to supply functional implementations of these helpers.
  1276. /// This option allows you to pass in a list of addresses that rbpf will allow the program
  1277. /// to load and store to. Given Rust's memory model you will always know these addresses up
  1278. /// front when implementing the helpers.
  1279. ///
  1280. /// Each invocation of this method will append to the set of allowed addresses.
  1281. ///
  1282. /// # Examples
  1283. ///
  1284. /// ```
  1285. /// use std::iter::FromIterator;
  1286. /// use std::ptr::addr_of;
  1287. ///
  1288. /// struct MapValue {
  1289. /// data: u8
  1290. /// }
  1291. /// static VALUE: MapValue = MapValue { data: 1 };
  1292. ///
  1293. /// let prog = &[
  1294. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1295. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1296. /// ];
  1297. ///
  1298. /// // Instantiate a VM.
  1299. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1300. /// let start = addr_of!(VALUE) as u64;
  1301. /// let addrs = Vec::from_iter(start..start+size_of::<MapValue>() as u64);
  1302. /// vm.register_allowed_memory(&addrs);
  1303. /// ```
  1304. pub fn register_allowed_memory(&mut self, allowed: &[u64]) {
  1305. self.parent.register_allowed_memory(allowed)
  1306. }
  1307. /// Execute the program loaded, with the given packet data.
  1308. ///
  1309. /// # Examples
  1310. ///
  1311. /// ```
  1312. /// let prog = &[
  1313. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1314. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1315. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1316. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1317. /// ];
  1318. ///
  1319. /// let mem = &mut [
  1320. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0x27
  1321. /// ];
  1322. ///
  1323. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1324. ///
  1325. /// let res = vm.execute_program(mem).unwrap();
  1326. /// assert_eq!(res, 0x22cc);
  1327. /// ```
  1328. pub fn execute_program(&self, mem: &'a mut [u8]) -> Result<u64, Error> {
  1329. self.parent.execute_program(mem, &[])
  1330. }
  1331. /// JIT-compile the loaded program. No argument required for this.
  1332. ///
  1333. /// If using helper functions, be sure to register them into the VM before calling this
  1334. /// function.
  1335. ///
  1336. /// # Examples
  1337. ///
  1338. /// ```
  1339. /// let prog = &[
  1340. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1341. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1342. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1343. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1344. /// ];
  1345. ///
  1346. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1347. ///
  1348. /// vm.jit_compile();
  1349. /// ```
  1350. #[cfg(all(not(windows), feature = "std"))]
  1351. pub fn jit_compile(&mut self) -> Result<(), Error> {
  1352. let prog = match self.parent.prog {
  1353. Some(prog) => prog,
  1354. None => Err(Error::new(
  1355. ErrorKind::Other,
  1356. "Error: No program set, call prog_set() to load one",
  1357. ))?,
  1358. };
  1359. self.parent.jit = Some(jit::JitMemory::new(
  1360. prog,
  1361. &self.parent.helpers,
  1362. false,
  1363. false,
  1364. )?);
  1365. Ok(())
  1366. }
  1367. /// Execute the previously JIT-compiled program, with the given packet data, in a manner very
  1368. /// similar to `execute_program()`.
  1369. ///
  1370. /// # Safety
  1371. ///
  1372. /// **WARNING:** JIT-compiled assembly code is not safe, in particular there is no runtime
  1373. /// check for memory access; so if the eBPF program attempts erroneous accesses, this may end
  1374. /// very bad (program may segfault). It may be wise to check that the program works with the
  1375. /// interpreter before running the JIT-compiled version of it.
  1376. ///
  1377. /// For this reason the function should be called from within an `unsafe` bloc.
  1378. ///
  1379. /// # Examples
  1380. ///
  1381. /// ```
  1382. /// let prog = &[
  1383. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1384. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1385. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1386. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1387. /// ];
  1388. ///
  1389. /// let mem = &mut [
  1390. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0x27
  1391. /// ];
  1392. ///
  1393. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1394. ///
  1395. /// # #[cfg(all(not(windows), feature = "std"))]
  1396. /// vm.jit_compile();
  1397. ///
  1398. /// # #[cfg(all(not(windows), feature = "std"))]
  1399. /// unsafe {
  1400. /// let res = vm.execute_program_jit(mem).unwrap();
  1401. /// assert_eq!(res, 0x22cc);
  1402. /// }
  1403. /// ```
  1404. #[cfg(all(not(windows), feature = "std"))]
  1405. pub unsafe fn execute_program_jit(&self, mem: &'a mut [u8]) -> Result<u64, Error> {
  1406. let mut mbuff = vec![];
  1407. self.parent.execute_program_jit(mem, &mut mbuff)
  1408. }
  1409. /// Compile the loaded program using the Cranelift JIT.
  1410. ///
  1411. /// If using helper functions, be sure to register them into the VM before calling this
  1412. /// function.
  1413. ///
  1414. /// # Examples
  1415. ///
  1416. /// ```
  1417. /// let prog = &[
  1418. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1419. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1420. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1421. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1422. /// ];
  1423. ///
  1424. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1425. ///
  1426. /// vm.cranelift_compile();
  1427. /// ```
  1428. #[cfg(feature = "cranelift")]
  1429. pub fn cranelift_compile(&mut self) -> Result<(), Error> {
  1430. use crate::cranelift::CraneliftCompiler;
  1431. let prog = match self.parent.prog {
  1432. Some(prog) => prog,
  1433. None => Err(Error::new(
  1434. ErrorKind::Other,
  1435. "Error: No program set, call prog_set() to load one",
  1436. ))?,
  1437. };
  1438. let compiler = CraneliftCompiler::new(self.parent.helpers.clone());
  1439. let program = compiler.compile_function(prog)?;
  1440. self.parent.cranelift_prog = Some(program);
  1441. Ok(())
  1442. }
  1443. /// Execute the previously compiled program, with the given packet data, in a manner very
  1444. /// similar to `execute_program()`.
  1445. ///
  1446. /// # Examples
  1447. ///
  1448. /// ```
  1449. /// let prog = &[
  1450. /// 0x71, 0x11, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // ldxb r1[0x04], r1
  1451. /// 0x07, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, // add r1, 0x22
  1452. /// 0xbf, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, r1
  1453. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1454. /// ];
  1455. ///
  1456. /// let mem = &mut [
  1457. /// 0xaa, 0xbb, 0x11, 0x22, 0xcc, 0x27
  1458. /// ];
  1459. ///
  1460. /// let mut vm = rbpf::EbpfVmRaw::new(Some(prog)).unwrap();
  1461. ///
  1462. /// vm.cranelift_compile();
  1463. ///
  1464. /// let res = vm.execute_program_cranelift(mem).unwrap();
  1465. /// assert_eq!(res, 0x22cc);
  1466. /// ```
  1467. #[cfg(feature = "cranelift")]
  1468. pub fn execute_program_cranelift(&self, mem: &'a mut [u8]) -> Result<u64, Error> {
  1469. let mut mbuff = vec![];
  1470. self.parent.execute_program_cranelift(mem, &mut mbuff)
  1471. }
  1472. }
  1473. /// A virtual machine to run eBPF program. This kind of VM is used for programs that do not work
  1474. /// with any memory area—no metadata buffer, no packet data either.
  1475. ///
  1476. /// # Examples
  1477. ///
  1478. /// ```
  1479. /// let prog = &[
  1480. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1481. /// 0xb7, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // mov r1, 1
  1482. /// 0xb7, 0x02, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // mov r2, 2
  1483. /// 0xb7, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // mov r3, 3
  1484. /// 0xb7, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // mov r4, 4
  1485. /// 0xb7, 0x05, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, // mov r5, 5
  1486. /// 0xb7, 0x06, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, // mov r6, 6
  1487. /// 0xb7, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, // mov r7, 7
  1488. /// 0xb7, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, // mov r8, 8
  1489. /// 0x4f, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // or r0, r5
  1490. /// 0x47, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, // or r0, 0xa0
  1491. /// 0x57, 0x00, 0x00, 0x00, 0xa3, 0x00, 0x00, 0x00, // and r0, 0xa3
  1492. /// 0xb7, 0x09, 0x00, 0x00, 0x91, 0x00, 0x00, 0x00, // mov r9, 0x91
  1493. /// 0x5f, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // and r0, r9
  1494. /// 0x67, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, // lsh r0, 32
  1495. /// 0x67, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, // lsh r0, 22
  1496. /// 0x6f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // lsh r0, r8
  1497. /// 0x77, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, // rsh r0, 32
  1498. /// 0x77, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, // rsh r0, 19
  1499. /// 0x7f, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // rsh r0, r7
  1500. /// 0xa7, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // xor r0, 0x03
  1501. /// 0xaf, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // xor r0, r2
  1502. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1503. /// ];
  1504. ///
  1505. /// // Instantiate a VM.
  1506. /// let vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1507. ///
  1508. /// // Provide only a reference to the packet data.
  1509. /// let res = vm.execute_program().unwrap();
  1510. /// assert_eq!(res, 0x11);
  1511. /// ```
  1512. pub struct EbpfVmNoData<'a> {
  1513. parent: EbpfVmRaw<'a>,
  1514. }
  1515. impl<'a> EbpfVmNoData<'a> {
  1516. /// Create a new virtual machine instance, and load an eBPF program into that instance.
  1517. /// When attempting to load the program, it passes through a simple verifier.
  1518. ///
  1519. /// # Examples
  1520. ///
  1521. /// ```
  1522. /// let prog = &[
  1523. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1524. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // be16 r0
  1525. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1526. /// ];
  1527. ///
  1528. /// // Instantiate a VM.
  1529. /// let vm = rbpf::EbpfVmNoData::new(Some(prog));
  1530. /// ```
  1531. pub fn new(prog: Option<&'a [u8]>) -> Result<EbpfVmNoData<'a>, Error> {
  1532. let parent = EbpfVmRaw::new(prog)?;
  1533. Ok(EbpfVmNoData { parent })
  1534. }
  1535. /// Load a new eBPF program into the virtual machine instance.
  1536. ///
  1537. /// # Examples
  1538. ///
  1539. /// ```
  1540. /// let prog1 = &[
  1541. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1542. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1543. /// ];
  1544. /// let prog2 = &[
  1545. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1546. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // be16 r0
  1547. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1548. /// ];
  1549. ///
  1550. /// let mut vm = rbpf::EbpfVmNoData::new(Some(prog1)).unwrap();
  1551. ///
  1552. /// let res = vm.execute_program().unwrap();
  1553. /// assert_eq!(res, 0x2211);
  1554. ///
  1555. /// vm.set_program(prog2);
  1556. ///
  1557. /// let res = vm.execute_program().unwrap();
  1558. /// assert_eq!(res, 0x1122);
  1559. /// ```
  1560. pub fn set_program(&mut self, prog: &'a [u8]) -> Result<(), Error> {
  1561. self.parent.set_program(prog)?;
  1562. Ok(())
  1563. }
  1564. /// Set a new verifier function. The function should return an `Error` if the program should be
  1565. /// rejected by the virtual machine. If a program has been loaded to the VM already, the
  1566. /// verifier is immediately run.
  1567. ///
  1568. /// # Examples
  1569. ///
  1570. /// ```
  1571. /// use rbpf::lib::{Error, ErrorKind};
  1572. /// use rbpf::ebpf;
  1573. ///
  1574. /// // Define a simple verifier function.
  1575. /// fn verifier(prog: &[u8]) -> Result<(), Error> {
  1576. /// let last_insn = ebpf::get_insn(prog, (prog.len() / ebpf::INSN_SIZE) - 1);
  1577. /// if last_insn.opc != ebpf::EXIT {
  1578. /// return Err(Error::new(ErrorKind::Other,
  1579. /// "[Verifier] Error: program does not end with “EXIT” instruction"));
  1580. /// }
  1581. /// Ok(())
  1582. /// }
  1583. ///
  1584. /// let prog1 = &[
  1585. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1586. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1587. /// ];
  1588. ///
  1589. /// // Instantiate a VM.
  1590. /// let mut vm = rbpf::EbpfVmMbuff::new(Some(prog1)).unwrap();
  1591. /// // Change the verifier.
  1592. /// vm.set_verifier(verifier).unwrap();
  1593. /// ```
  1594. pub fn set_verifier(&mut self, verifier: Verifier) -> Result<(), Error> {
  1595. self.parent.set_verifier(verifier)
  1596. }
  1597. /// Register a built-in or user-defined helper function in order to use it later from within
  1598. /// the eBPF program. The helper is registered into a hashmap, so the `key` can be any `u32`.
  1599. ///
  1600. /// If using JIT-compiled eBPF programs, be sure to register all helpers before compiling the
  1601. /// program. You should be able to change registered helpers after compiling, but not to add
  1602. /// new ones (i.e. with new keys).
  1603. ///
  1604. /// # Examples
  1605. ///
  1606. /// ```
  1607. /// #[cfg(feature = "std")] {
  1608. /// use rbpf::helpers;
  1609. ///
  1610. /// let prog = &[
  1611. /// 0xb7, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // mov r1, 0x010000000
  1612. /// 0xb7, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r2, 0
  1613. /// 0xb7, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r3, 0
  1614. /// 0xb7, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r4, 0
  1615. /// 0xb7, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r5, 0
  1616. /// 0x85, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // call helper with key 1
  1617. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1618. /// ];
  1619. ///
  1620. /// let mut vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1621. ///
  1622. /// // Register a helper. This helper will store the result of the square root of r1 into r0.
  1623. /// vm.register_helper(1, helpers::sqrti).unwrap();
  1624. ///
  1625. /// let res = vm.execute_program().unwrap();
  1626. /// assert_eq!(res, 0x1000);
  1627. /// }
  1628. /// ```
  1629. pub fn register_helper(
  1630. &mut self,
  1631. key: u32,
  1632. function: fn(u64, u64, u64, u64, u64) -> u64,
  1633. ) -> Result<(), Error> {
  1634. self.parent.register_helper(key, function)
  1635. }
  1636. /// Register an object that the eBPF program is allowed to load and store.
  1637. ///
  1638. /// When using certain helpers, typically map lookups, the Linux kernel will return pointers
  1639. /// to structs that the eBPF program needs to interact with. By default rbpf only allows the
  1640. /// program to interact with its stack, the memory buffer and the program itself, making it
  1641. /// impossible to supply functional implementations of these helpers.
  1642. /// This option allows you to pass in a list of addresses that rbpf will allow the program
  1643. /// to load and store to. Given Rust's memory model you will always know these addresses up
  1644. /// front when implementing the helpers.
  1645. ///
  1646. /// Each invocation of this method will append to the set of allowed addresses.
  1647. ///
  1648. /// # Examples
  1649. ///
  1650. /// ```
  1651. /// use std::iter::FromIterator;
  1652. /// use std::ptr::addr_of;
  1653. ///
  1654. /// struct MapValue {
  1655. /// data: u8
  1656. /// }
  1657. /// static VALUE: MapValue = MapValue { data: 1 };
  1658. ///
  1659. /// let prog = &[
  1660. /// 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r0, 0
  1661. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1662. /// ];
  1663. ///
  1664. /// // Instantiate a VM.
  1665. /// let mut vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1666. /// let start = addr_of!(VALUE) as u64;
  1667. /// let addrs = Vec::from_iter(start..start+size_of::<MapValue>() as u64);
  1668. /// vm.register_allowed_memory(&addrs);
  1669. /// ```
  1670. pub fn register_allowed_memory(&mut self, allowed: &[u64]) {
  1671. self.parent.register_allowed_memory(allowed)
  1672. }
  1673. /// JIT-compile the loaded program. No argument required for this.
  1674. ///
  1675. /// If using helper functions, be sure to register them into the VM before calling this
  1676. /// function.
  1677. ///
  1678. /// # Examples
  1679. ///
  1680. /// ```
  1681. /// let prog = &[
  1682. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1683. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // be16 r0
  1684. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1685. /// ];
  1686. ///
  1687. /// let mut vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1688. ///
  1689. ///
  1690. /// vm.jit_compile();
  1691. /// ```
  1692. #[cfg(all(not(windows), feature = "std"))]
  1693. pub fn jit_compile(&mut self) -> Result<(), Error> {
  1694. self.parent.jit_compile()
  1695. }
  1696. /// Execute the program loaded, without providing pointers to any memory area whatsoever.
  1697. ///
  1698. /// # Examples
  1699. ///
  1700. /// ```
  1701. /// let prog = &[
  1702. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1703. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // be16 r0
  1704. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1705. /// ];
  1706. ///
  1707. /// let vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1708. ///
  1709. /// // For this kind of VM, the `execute_program()` function needs no argument.
  1710. /// let res = vm.execute_program().unwrap();
  1711. /// assert_eq!(res, 0x1122);
  1712. /// ```
  1713. pub fn execute_program(&self) -> Result<u64, Error> {
  1714. self.parent.execute_program(&mut [])
  1715. }
  1716. /// Execute the previously JIT-compiled program, without providing pointers to any memory area
  1717. /// whatsoever, in a manner very similar to `execute_program()`.
  1718. ///
  1719. /// # Safety
  1720. ///
  1721. /// **WARNING:** JIT-compiled assembly code is not safe, in particular there is no runtime
  1722. /// check for memory access; so if the eBPF program attempts erroneous accesses, this may end
  1723. /// very bad (program may segfault). It may be wise to check that the program works with the
  1724. /// interpreter before running the JIT-compiled version of it.
  1725. ///
  1726. /// For this reason the function should be called from within an `unsafe` bloc.
  1727. ///
  1728. /// # Examples
  1729. ///
  1730. /// ```
  1731. /// let prog = &[
  1732. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1733. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // be16 r0
  1734. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1735. /// ];
  1736. ///
  1737. /// let mut vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1738. ///
  1739. /// # #[cfg(all(not(windows), feature = "std"))]
  1740. /// vm.jit_compile();
  1741. ///
  1742. /// # #[cfg(all(not(windows), feature = "std"))]
  1743. /// unsafe {
  1744. /// let res = vm.execute_program_jit().unwrap();
  1745. /// assert_eq!(res, 0x1122);
  1746. /// }
  1747. /// ```
  1748. #[cfg(all(not(windows), feature = "std"))]
  1749. pub unsafe fn execute_program_jit(&self) -> Result<u64, Error> {
  1750. self.parent.execute_program_jit(&mut [])
  1751. }
  1752. /// Compile the loaded program using the Cranelift JIT.
  1753. ///
  1754. /// If using helper functions, be sure to register them into the VM before calling this
  1755. /// function.
  1756. ///
  1757. /// # Examples
  1758. ///
  1759. /// ```
  1760. /// let prog = &[
  1761. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1762. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // be16 r0
  1763. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1764. /// ];
  1765. ///
  1766. /// let mut vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1767. ///
  1768. ///
  1769. /// vm.cranelift_compile();
  1770. /// ```
  1771. #[cfg(feature = "cranelift")]
  1772. pub fn cranelift_compile(&mut self) -> Result<(), Error> {
  1773. self.parent.cranelift_compile()
  1774. }
  1775. /// Execute the previously JIT-compiled program, without providing pointers to any memory area
  1776. /// whatsoever, in a manner very similar to `execute_program()`.
  1777. ///
  1778. /// # Examples
  1779. ///
  1780. /// ```
  1781. /// let prog = &[
  1782. /// 0xb7, 0x00, 0x00, 0x00, 0x11, 0x22, 0x00, 0x00, // mov r0, 0x2211
  1783. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, // be16 r0
  1784. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // exit
  1785. /// ];
  1786. ///
  1787. /// let mut vm = rbpf::EbpfVmNoData::new(Some(prog)).unwrap();
  1788. ///
  1789. /// vm.cranelift_compile();
  1790. ///
  1791. /// let res = vm.execute_program_cranelift().unwrap();
  1792. /// assert_eq!(res, 0x1122);
  1793. /// ```
  1794. #[cfg(feature = "cranelift")]
  1795. pub fn execute_program_cranelift(&self) -> Result<u64, Error> {
  1796. self.parent.execute_program_cranelift(&mut [])
  1797. }
  1798. }