4
0

assembler.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // SPDX-License-Identifier: (Apache-2.0 OR MIT)
  2. // Copyright 2017 Rich Lane <lanerl@gmail.com>
  3. //! This module translates eBPF assembly language to binary.
  4. use self::InstructionType::{
  5. AluBinary, AluUnary, Call, Callx, Endian, JumpConditional, JumpUnconditional, LoadAbs, LoadImm,
  6. LoadInd, LoadReg, NoOperand, StoreImm, StoreReg,
  7. };
  8. use crate::asm_parser::Operand::{Integer, Memory, Nil, Register};
  9. use crate::asm_parser::{parse, Instruction, Operand};
  10. use crate::ebpf;
  11. use crate::ebpf::Insn;
  12. use crate::lib::*;
  13. #[derive(Clone, Copy, Debug, PartialEq)]
  14. enum InstructionType {
  15. AluBinary,
  16. AluUnary,
  17. LoadImm,
  18. LoadAbs,
  19. LoadInd,
  20. LoadReg,
  21. StoreImm,
  22. StoreReg,
  23. JumpUnconditional,
  24. JumpConditional,
  25. Call,
  26. Callx,
  27. Endian(i64),
  28. NoOperand,
  29. }
  30. fn make_instruction_map() -> HashMap<String, (InstructionType, u8)> {
  31. let mut result = HashMap::new();
  32. let alu_binary_ops = [
  33. ("add", ebpf::BPF_ADD),
  34. ("sub", ebpf::BPF_SUB),
  35. ("mul", ebpf::BPF_MUL),
  36. ("div", ebpf::BPF_DIV),
  37. ("or", ebpf::BPF_OR),
  38. ("and", ebpf::BPF_AND),
  39. ("lsh", ebpf::BPF_LSH),
  40. ("rsh", ebpf::BPF_RSH),
  41. ("mod", ebpf::BPF_MOD),
  42. ("xor", ebpf::BPF_XOR),
  43. ("mov", ebpf::BPF_MOV),
  44. ("arsh", ebpf::BPF_ARSH),
  45. ];
  46. let mem_sizes = [
  47. ("w", ebpf::BPF_W),
  48. ("h", ebpf::BPF_H),
  49. ("b", ebpf::BPF_B),
  50. ("dw", ebpf::BPF_DW),
  51. ];
  52. let jump_conditions = [
  53. ("jeq", ebpf::BPF_JEQ),
  54. ("jgt", ebpf::BPF_JGT),
  55. ("jge", ebpf::BPF_JGE),
  56. ("jlt", ebpf::BPF_JLT),
  57. ("jle", ebpf::BPF_JLE),
  58. ("jset", ebpf::BPF_JSET),
  59. ("jne", ebpf::BPF_JNE),
  60. ("jsgt", ebpf::BPF_JSGT),
  61. ("jsge", ebpf::BPF_JSGE),
  62. ("jslt", ebpf::BPF_JSLT),
  63. ("jsle", ebpf::BPF_JSLE),
  64. ];
  65. {
  66. let mut entry = |name: &str, inst_type: InstructionType, opc: u8| {
  67. result.insert(name.to_string(), (inst_type, opc))
  68. };
  69. // Miscellaneous.
  70. entry("exit", NoOperand, ebpf::EXIT);
  71. entry("ja", JumpUnconditional, ebpf::JA);
  72. entry("call", Call, ebpf::CALL);
  73. entry("callx", Callx, ebpf::CALL);
  74. entry("lddw", LoadImm, ebpf::LD_DW_IMM);
  75. // AluUnary.
  76. entry("neg", AluUnary, ebpf::NEG64);
  77. entry("neg32", AluUnary, ebpf::NEG32);
  78. entry("neg64", AluUnary, ebpf::NEG64);
  79. // AluBinary.
  80. for &(name, opc) in &alu_binary_ops {
  81. entry(name, AluBinary, ebpf::BPF_ALU64 | opc);
  82. entry(&format!("{name}32"), AluBinary, ebpf::BPF_ALU | opc);
  83. entry(&format!("{name}64"), AluBinary, ebpf::BPF_ALU64 | opc);
  84. }
  85. // LoadAbs, LoadInd, LoadReg, StoreImm, and StoreReg.
  86. for &(suffix, size) in &mem_sizes {
  87. entry(
  88. &format!("ldabs{suffix}"),
  89. LoadAbs,
  90. ebpf::BPF_ABS | ebpf::BPF_LD | size,
  91. );
  92. entry(
  93. &format!("ldind{suffix}"),
  94. LoadInd,
  95. ebpf::BPF_IND | ebpf::BPF_LD | size,
  96. );
  97. entry(
  98. &format!("ldx{suffix}"),
  99. LoadReg,
  100. ebpf::BPF_MEM | ebpf::BPF_LDX | size,
  101. );
  102. entry(
  103. &format!("st{suffix}"),
  104. StoreImm,
  105. ebpf::BPF_MEM | ebpf::BPF_ST | size,
  106. );
  107. entry(
  108. &format!("stx{suffix}"),
  109. StoreReg,
  110. ebpf::BPF_MEM | ebpf::BPF_STX | size,
  111. );
  112. }
  113. // JumpConditional.
  114. for &(name, condition) in &jump_conditions {
  115. entry(name, JumpConditional, ebpf::BPF_JMP | condition);
  116. entry(
  117. &format!("{name}32"),
  118. JumpConditional,
  119. ebpf::BPF_JMP32 | condition,
  120. );
  121. }
  122. // Endian.
  123. for &size in &[16, 32, 64] {
  124. entry(&format!("be{size}"), Endian(size), ebpf::BE);
  125. entry(&format!("le{size}"), Endian(size), ebpf::LE);
  126. }
  127. }
  128. result
  129. }
  130. fn insn(opc: u8, dst: i64, src: i64, off: i64, imm: i64) -> Result<Insn, String> {
  131. if !(0..16).contains(&dst) {
  132. return Err(format!("Invalid destination register {dst}"));
  133. }
  134. if dst < 0 || src >= 16 {
  135. return Err(format!("Invalid source register {src}"));
  136. }
  137. if !(-32768..32768).contains(&off) {
  138. return Err(format!("Invalid offset {off}"));
  139. }
  140. if !(-2147483648..2147483648).contains(&imm) {
  141. return Err(format!("Invalid immediate {imm}"));
  142. }
  143. Ok(Insn {
  144. opc,
  145. dst: dst as u8,
  146. src: src as u8,
  147. off: off as i16,
  148. imm: imm as i32,
  149. })
  150. }
  151. // TODO Use slice patterns when available and remove this function.
  152. fn operands_tuple(operands: &[Operand]) -> Result<(Operand, Operand, Operand), String> {
  153. match operands.len() {
  154. 0 => Ok((Nil, Nil, Nil)),
  155. 1 => Ok((operands[0], Nil, Nil)),
  156. 2 => Ok((operands[0], operands[1], Nil)),
  157. 3 => Ok((operands[0], operands[1], operands[2])),
  158. _ => Err("Too many operands".to_string()),
  159. }
  160. }
  161. fn encode(inst_type: InstructionType, opc: u8, operands: &[Operand]) -> Result<Insn, String> {
  162. let (a, b, c) = (operands_tuple(operands))?;
  163. match (inst_type, a, b, c) {
  164. (AluBinary, Register(dst), Register(src), Nil) => insn(opc | ebpf::BPF_X, dst, src, 0, 0),
  165. (AluBinary, Register(dst), Integer(imm), Nil) => insn(opc | ebpf::BPF_K, dst, 0, 0, imm),
  166. (AluUnary, Register(dst), Nil, Nil) => insn(opc, dst, 0, 0, 0),
  167. (LoadAbs, Integer(imm), Nil, Nil) => insn(opc, 0, 0, 0, imm),
  168. (LoadInd, Register(src), Integer(imm), Nil) => insn(opc, 0, src, 0, imm),
  169. (LoadReg, Register(dst), Memory(src, off), Nil)
  170. | (StoreReg, Memory(dst, off), Register(src), Nil) => insn(opc, dst, src, off, 0),
  171. (StoreImm, Memory(dst, off), Integer(imm), Nil) => insn(opc, dst, 0, off, imm),
  172. (NoOperand, Nil, Nil, Nil) => insn(opc, 0, 0, 0, 0),
  173. (JumpUnconditional, Integer(off), Nil, Nil) => insn(opc, 0, 0, off, 0),
  174. (JumpConditional, Register(dst), Register(src), Integer(off)) => {
  175. insn(opc | ebpf::BPF_X, dst, src, off, 0)
  176. }
  177. (JumpConditional, Register(dst), Integer(imm), Integer(off)) => {
  178. insn(opc | ebpf::BPF_K, dst, 0, off, imm)
  179. }
  180. (Call, Integer(imm), Nil, Nil) => insn(opc, 0, 0, 0, imm),
  181. (Callx, Integer(imm), Nil, Nil) => insn(opc, 0, 1, 0, imm),
  182. (Endian(size), Register(dst), Nil, Nil) => insn(opc, dst, 0, 0, size),
  183. (LoadImm, Register(dst), Integer(imm), Nil) => insn(opc, dst, 0, 0, (imm << 32) >> 32),
  184. _ => Err(format!("Unexpected operands: {operands:?}")),
  185. }
  186. }
  187. fn assemble_internal(parsed: &[Instruction]) -> Result<Vec<Insn>, String> {
  188. let instruction_map = make_instruction_map();
  189. let mut result: Vec<Insn> = vec![];
  190. for instruction in parsed {
  191. let name = instruction.name.as_str();
  192. match instruction_map.get(name) {
  193. Some(&(inst_type, opc)) => {
  194. match encode(inst_type, opc, &instruction.operands) {
  195. Ok(insn) => result.push(insn),
  196. Err(msg) => return Err(format!("Failed to encode {name}: {msg}")),
  197. }
  198. // Special case for lddw.
  199. if let LoadImm = inst_type {
  200. if let Integer(imm) = instruction.operands[1] {
  201. result.push(insn(0, 0, 0, 0, imm >> 32).unwrap());
  202. }
  203. }
  204. }
  205. None => return Err(format!("Invalid instruction {name:?}")),
  206. }
  207. }
  208. Ok(result)
  209. }
  210. /// Parse assembly source and translate to binary.
  211. ///
  212. /// # Examples
  213. ///
  214. /// ```
  215. /// use rbpf::assembler::assemble;
  216. /// let prog = assemble("add64 r1, 0x605
  217. /// mov64 r2, 0x32
  218. /// mov64 r1, r0
  219. /// be16 r0
  220. /// neg64 r2
  221. /// exit");
  222. /// println!("{:?}", prog);
  223. /// # assert_eq!(prog,
  224. /// # Ok(vec![0x07, 0x01, 0x00, 0x00, 0x05, 0x06, 0x00, 0x00,
  225. /// # 0xb7, 0x02, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
  226. /// # 0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  227. /// # 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
  228. /// # 0x87, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  229. /// # 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  230. /// ```
  231. ///
  232. /// This will produce the following output:
  233. ///
  234. /// ```test
  235. /// Ok([0x07, 0x01, 0x00, 0x00, 0x05, 0x06, 0x00, 0x00,
  236. /// 0xb7, 0x02, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
  237. /// 0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  238. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
  239. /// 0x87, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  240. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
  241. /// ```
  242. pub fn assemble(src: &str) -> Result<Vec<u8>, String> {
  243. let parsed = (parse(src))?;
  244. let insns = (assemble_internal(&parsed))?;
  245. let mut result: Vec<u8> = vec![];
  246. for insn in insns {
  247. result.extend_from_slice(&insn.to_array());
  248. }
  249. Ok(result)
  250. }