4 * Minimal BPF JIT image disassembler
6 * Disassembles BPF JIT compiler emitted opcodes back to asm insn's for
7 * debugging or verification purposes.
9 * Copyright 2013 Daniel Borkmann <daniel@iogearbox.net>
10 * Licensed under the GNU General Public License, version 2.0 (GPLv2)
22 #include <sys/types.h>
26 #include "json_writer.h"
29 static void get_exec_path(char *tpath
, size_t size
)
34 snprintf(tpath
, size
, "/proc/%d/exe", (int) getpid());
40 len
= readlink(path
, tpath
, size
- 1);
47 static int oper_count
;
48 static int fprintf_json(void *out
, const char *fmt
, ...)
57 s
= va_arg(ap
, char *);
59 /* Strip trailing spaces */
64 jsonw_string_field(json_wtr
, "operation", s
);
65 jsonw_name(json_wtr
, "operands");
66 jsonw_start_array(json_wtr
);
68 } else if (!strcmp(fmt
, ",")) {
71 s
= va_arg(ap
, char *);
72 jsonw_string(json_wtr
, s
);
79 void disasm_print_insn(unsigned char *image
, ssize_t len
, int opcodes
,
80 const char *arch
, const char *disassembler_options
)
82 disassembler_ftype disassemble
;
83 struct disassemble_info info
;
91 memset(tpath
, 0, sizeof(tpath
));
92 get_exec_path(tpath
, sizeof(tpath
));
94 bfdf
= bfd_openr(tpath
, NULL
);
96 assert(bfd_check_format(bfdf
, bfd_object
));
99 init_disassemble_info(&info
, stdout
,
100 (fprintf_ftype
) fprintf_json
);
102 init_disassemble_info(&info
, stdout
,
103 (fprintf_ftype
) fprintf
);
105 /* Update architecture info for offload. */
107 const bfd_arch_info_type
*inf
= bfd_scan_arch(arch
);
110 bfdf
->arch_info
= inf
;
112 p_err("No libfd support for %s", arch
);
117 info
.arch
= bfd_get_arch(bfdf
);
118 info
.mach
= bfd_get_mach(bfdf
);
119 if (disassembler_options
)
120 info
.disassembler_options
= disassembler_options
;
122 info
.buffer_length
= len
;
124 disassemble_init_for_target(&info
);
126 #ifdef DISASM_FOUR_ARGS_SIGNATURE
127 disassemble
= disassembler(info
.arch
,
128 bfd_big_endian(bfdf
),
132 disassemble
= disassembler(bfdf
);
137 jsonw_start_array(json_wtr
);
140 jsonw_start_object(json_wtr
);
142 jsonw_name(json_wtr
, "pc");
143 jsonw_printf(json_wtr
, "\"0x%x\"", pc
);
145 printf("%4x:\t", pc
);
148 count
= disassemble(pc
, &info
);
150 /* Operand array, was started in fprintf_json. Before
151 * that, make sure we have a _null_ value if no operand
152 * other than operation code was present.
155 jsonw_null(json_wtr
);
156 jsonw_end_array(json_wtr
);
161 jsonw_name(json_wtr
, "opcodes");
162 jsonw_start_array(json_wtr
);
163 for (i
= 0; i
< count
; ++i
)
164 jsonw_printf(json_wtr
, "\"0x%02hhx\"",
165 (uint8_t)image
[pc
+ i
]);
166 jsonw_end_array(json_wtr
);
169 for (i
= 0; i
< count
; ++i
)
171 (uint8_t)image
[pc
+ i
]);
175 jsonw_end_object(json_wtr
);
180 } while (count
> 0 && pc
< len
);
182 jsonw_end_array(json_wtr
);