assembler.rs 9.2 KB

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