瀏覽代碼

src/insn_builder.rs: add a test with several instructions

I could not find a test using the API to build a real program, with
several instructions. Add one so that we have a more concrete example to
show users how to use the API.
Quentin Monnet 6 年之前
父節點
當前提交
22264f5722
共有 1 個文件被更改,包括 31 次插入0 次删除
  1. 31 0
      src/insn_builder.rs

+ 31 - 0
src/insn_builder.rs

@@ -1530,4 +1530,35 @@ mod tests {
             }
         }
     }
+
+    #[cfg(test)]
+    mod programs {
+        use super::super::*;
+
+        #[test]
+        fn example_from_assembler() {
+            let mut program = BpfCode::new();
+            program.add(Source::Imm, Arch::X64).set_dst(1).set_imm(0x605).push()
+                   .mov(Source::Imm, Arch::X64).set_dst(2).set_imm(0x32).push()
+                   .mov(Source::Reg, Arch::X64).set_src(0).set_dst(1).push()
+                   .swap_bytes(Endian::Big).set_dst(0).set_imm(0x10).push()
+                   .negate(Arch::X64).set_dst(2).push()
+                   .exit().push();
+
+            let bytecode = program.into_bytes();
+            let ref_prog = &[
+                0x07, 0x01, 0x00, 0x00, 0x05, 0x06, 0x00, 0x00,
+                0xb7, 0x02, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
+                0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
+                0x87, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+            ];
+            // cargo says: "`[{integer}; 48]` cannot be formatted using `{:?}`
+            //              because it doesn't implement `std::fmt::Debug`"
+            // So let's check in two steps.
+            assert_eq!(bytecode[..32], ref_prog[..32]);
+            assert_eq!(bytecode[33..], ref_prog[33..]);
+        }
+    }
 }