assembler.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. }
  95. // Endian.
  96. for &size in &[16, 32, 64] {
  97. entry(&format!("be{size}"), Endian(size), ebpf::BE);
  98. entry(&format!("le{size}"), Endian(size), ebpf::LE);
  99. }
  100. }
  101. result
  102. }
  103. fn insn(opc: u8, dst: i64, src: i64, off: i64, imm: i64) -> Result<Insn, String> {
  104. if !(0..16).contains(&dst) {
  105. return Err(format!("Invalid destination register {dst}"));
  106. }
  107. if dst < 0 || src >= 16 {
  108. return Err(format!("Invalid source register {src}"));
  109. }
  110. if !(-32768..32768).contains(&off) {
  111. return Err(format!("Invalid offset {off}"));
  112. }
  113. if !(-2147483648..2147483648).contains(&imm) {
  114. return Err(format!("Invalid immediate {imm}"));
  115. }
  116. Ok(Insn {
  117. opc: opc,
  118. dst: dst as u8,
  119. src: src as u8,
  120. off: off as i16,
  121. imm: imm as i32,
  122. })
  123. }
  124. // TODO Use slice patterns when available and remove this function.
  125. fn operands_tuple(operands: &[Operand]) -> Result<(Operand, Operand, Operand), String> {
  126. match operands.len() {
  127. 0 => Ok((Nil, Nil, Nil)),
  128. 1 => Ok((operands[0], Nil, Nil)),
  129. 2 => Ok((operands[0], operands[1], Nil)),
  130. 3 => Ok((operands[0], operands[1], operands[2])),
  131. _ => Err("Too many operands".to_string()),
  132. }
  133. }
  134. fn encode(inst_type: InstructionType, opc: u8, operands: &[Operand]) -> Result<Insn, String> {
  135. let (a, b, c) = (operands_tuple(operands))?;
  136. match (inst_type, a, b, c) {
  137. (AluBinary, Register(dst), Register(src), Nil) => insn(opc | ebpf::BPF_X, dst, src, 0, 0),
  138. (AluBinary, Register(dst), Integer(imm), Nil) => insn(opc | ebpf::BPF_K, dst, 0, 0, imm),
  139. (AluUnary, Register(dst), Nil, Nil) => insn(opc, dst, 0, 0, 0),
  140. (LoadAbs, Integer(imm), Nil, Nil) => insn(opc, 0, 0, 0, imm),
  141. (LoadInd, Register(src), Integer(imm), Nil) => insn(opc, 0, src, 0, imm),
  142. (LoadReg, Register(dst), Memory(src, off), Nil) |
  143. (StoreReg, Memory(dst, off), Register(src), Nil) => insn(opc, dst, src, off, 0),
  144. (StoreImm, Memory(dst, off), Integer(imm), Nil) => insn(opc, dst, 0, off, imm),
  145. (NoOperand, Nil, Nil, Nil) => insn(opc, 0, 0, 0, 0),
  146. (JumpUnconditional, Integer(off), Nil, Nil) => insn(opc, 0, 0, off, 0),
  147. (JumpConditional, Register(dst), Register(src), Integer(off)) => {
  148. insn(opc | ebpf::BPF_X, dst, src, off, 0)
  149. }
  150. (JumpConditional, Register(dst), Integer(imm), Integer(off)) => {
  151. insn(opc | ebpf::BPF_K, dst, 0, off, imm)
  152. }
  153. (Call, Integer(imm), Nil, Nil) => insn(opc, 0, 0, 0, imm),
  154. (Endian(size), Register(dst), Nil, Nil) => insn(opc, dst, 0, 0, size),
  155. (LoadImm, Register(dst), Integer(imm), Nil) => insn(opc, dst, 0, 0, (imm << 32) >> 32),
  156. _ => Err(format!("Unexpected operands: {operands:?}")),
  157. }
  158. }
  159. fn assemble_internal(parsed: &[Instruction]) -> Result<Vec<Insn>, String> {
  160. let instruction_map = make_instruction_map();
  161. let mut result: Vec<Insn> = vec![];
  162. for instruction in parsed {
  163. let name = instruction.name.as_str();
  164. match instruction_map.get(name) {
  165. Some(&(inst_type, opc)) => {
  166. match encode(inst_type, opc, &instruction.operands) {
  167. Ok(insn) => result.push(insn),
  168. Err(msg) => return Err(format!("Failed to encode {name}: {msg}")),
  169. }
  170. // Special case for lddw.
  171. if let LoadImm = inst_type {
  172. if let Integer(imm) = instruction.operands[1] {
  173. result.push(insn(0, 0, 0, 0, imm >> 32).unwrap());
  174. }
  175. }
  176. }
  177. None => return Err(format!("Invalid instruction {name:?}")),
  178. }
  179. }
  180. Ok(result)
  181. }
  182. /// Parse assembly source and translate to binary.
  183. ///
  184. /// # Examples
  185. ///
  186. /// ```
  187. /// use rbpf::assembler::assemble;
  188. /// let prog = assemble("add64 r1, 0x605
  189. /// mov64 r2, 0x32
  190. /// mov64 r1, r0
  191. /// be16 r0
  192. /// neg64 r2
  193. /// exit");
  194. /// println!("{:?}", prog);
  195. /// # assert_eq!(prog,
  196. /// # Ok(vec![0x07, 0x01, 0x00, 0x00, 0x05, 0x06, 0x00, 0x00,
  197. /// # 0xb7, 0x02, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
  198. /// # 0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  199. /// # 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
  200. /// # 0x87, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  201. /// # 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  202. /// ```
  203. ///
  204. /// This will produce the following output:
  205. ///
  206. /// ```test
  207. /// Ok([0x07, 0x01, 0x00, 0x00, 0x05, 0x06, 0x00, 0x00,
  208. /// 0xb7, 0x02, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
  209. /// 0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  210. /// 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
  211. /// 0x87, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  212. /// 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
  213. /// ```
  214. pub fn assemble(src: &str) -> Result<Vec<u8>, String> {
  215. let parsed = (parse(src))?;
  216. let insns = (assemble_internal(&parsed))?;
  217. let mut result: Vec<u8> = vec![];
  218. for insn in insns {
  219. result.extend_from_slice(&insn.to_array());
  220. }
  221. Ok(result)
  222. }