Debian Codegraph @

bindings/python/tests/test_bpf.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 # Capstone Python bindings
4 # BPF tests by david942j <[email protected]>, 2019
5
6 from __future__ import print_function
7 from capstone import *
8 from capstone.bpf import *
9
10
11 CBPF_CODE = b"\x94\x09\x00\x00\x37\x13\x03\x00\x87\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00\x16\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00"
12 EBPF_CODE = b"\x97\x09\x00\x00\x37\x13\x03\x00\xdc\x02\x00\x00\x20\x00\x00\x00\x30\x00\x00\x00\x00\x00\x00\x00\xdb\x3a\x00\x01\x00\x00\x00\x00\x84\x02\x00\x00\x00\x00\x00\x00\x6d\x33\x17\x02\x00\x00\x00\x00"
13
14 all_tests = (
15 (CS_ARCH_BPF, CS_MODE_LITTLE_ENDIAN | CS_MODE_BPF_CLASSIC, CBPF_CODE, "cBPF Le", None),
16 (CS_ARCH_BPF, CS_MODE_LITTLE_ENDIAN | CS_MODE_BPF_EXTENDED, EBPF_CODE, "eBPF Le", None),
17 )
18 mask32 = lambda v: v & 0xFFFFFFFF
19
20 ext_name = {}
21 ext_name[BPF_EXT_LEN] = '#len'
22
23 def print_insn_detail(insn):
24 # print address, mnemonic and operands
25 print("0x%x:\t%s\t%s" % (insn.address, insn.mnemonic, insn.op_str))
26
27 # "data" instruction generated by SKIPDATA option has no detail
28 if insn.id == 0:
29 return
30
31 if len(insn.groups) > 0:
32 print('\tGroups: ' + ' '.join(map(lambda g: insn.group_name(g), insn.groups)))
33
34 print("\tOperand count: %u" % len(insn.operands))
35 for c, op in enumerate(insn.operands):
36 print("\t\toperands[%u].type: " % c, end='')
37 if op.type == BPF_OP_REG:
38 print("REG = " + insn.reg_name(op.reg))
39 elif op.type == BPF_OP_IMM:
40 print("IMM = " + hex(op.imm)[:-1])
41 elif op.type == BPF_OP_OFF:
42 print("OFF = +0x%x" % mask32(op.off))
43 elif op.type == BPF_OP_MEM:
44 print("MEM")
45 if op.mem.base != 0:
46 print("\t\t\toperands[%u].mem.base: REG = %s" \
47 % (c, insn.reg_name(op.mem.base)))
48 print("\t\t\toperands[%u].mem.disp: 0x%x" \
49 % (c, mask32(op.mem.disp)))
50 elif op.type == BPF_OP_MMEM:
51 print("MMEM = 0x%x" % mask32(op.mmem))
52 elif op.type == BPF_OP_MSH:
53 print("MSH = 4*([0x%x]&0xf)" % mask32(op.msh))
54 elif op.type == BPF_OP_EXT:
55 print("EXT = " + ext_name[op.ext])
56
57 (regs_read, regs_write) = insn.regs_access()
58
59 if len(regs_read) > 0:
60 print("\tRegisters read:", end="")
61 for r in regs_read:
62 print(" %s" % insn.reg_name(r), end="")
63 print("")
64
65 if len(regs_write) > 0:
66 print("\tRegisters modified:", end="")
67 for r in regs_write:
68 print(" %s" % insn.reg_name(r), end="")
69 print("")
70
71 def test_class():
72
73 for (arch, mode, code, comment, syntax) in all_tests:
74 print("*" * 16)
75 print("Platform: %s" % comment)
76 print("Code: %s" % code.hex(' '))
77 print("Disasm:")
78
79 try:
80 md = Cs(arch, mode)
81 if syntax is not None:
82 md.syntax = syntax
83 md.detail = True
84 for insn in md.disasm(code, 0x0):
85 print_insn_detail(insn)
86 print ()
87 except CsError as e:
88 print("ERROR: %s" % e)
89
90
91 if __name__ == '__main__':
92 test_class()