assembler.rs 9.1 KB

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