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)
24 #include <sys/types.h>
28 #include "json_writer.h"
31 static void get_exec_path(char *tpath
, size_t size
)
36 snprintf(tpath
, size
, "/proc/%d/exe", (int) getpid());
42 len
= readlink(path
, tpath
, size
- 1);
49 static int oper_count
;
50 static int fprintf_json(void *out
, const char *fmt
, ...)
56 if (vasprintf(&s
, fmt
, ap
) < 0)
63 /* Strip trailing spaces */
68 jsonw_string_field(json_wtr
, "operation", s
);
69 jsonw_name(json_wtr
, "operands");
70 jsonw_start_array(json_wtr
);
72 } else if (!strcmp(fmt
, ",")) {
75 jsonw_string(json_wtr
, s
);
82 void disasm_print_insn(unsigned char *image
, ssize_t len
, int opcodes
)
84 disassembler_ftype disassemble
;
85 struct disassemble_info info
;
93 memset(tpath
, 0, sizeof(tpath
));
94 get_exec_path(tpath
, sizeof(tpath
));
96 bfdf
= bfd_openr(tpath
, NULL
);
98 assert(bfd_check_format(bfdf
, bfd_object
));
101 init_disassemble_info(&info
, stdout
,
102 (fprintf_ftype
) fprintf_json
);
104 init_disassemble_info(&info
, stdout
,
105 (fprintf_ftype
) fprintf
);
106 info
.arch
= bfd_get_arch(bfdf
);
107 info
.mach
= bfd_get_mach(bfdf
);
109 info
.buffer_length
= len
;
111 disassemble_init_for_target(&info
);
113 #ifdef DISASM_FOUR_ARGS_SIGNATURE
114 disassemble
= disassembler(info
.arch
,
115 bfd_big_endian(bfdf
),
119 disassemble
= disassembler(bfdf
);
124 jsonw_start_array(json_wtr
);
127 jsonw_start_object(json_wtr
);
129 jsonw_name(json_wtr
, "pc");
130 jsonw_printf(json_wtr
, "\"0x%x\"", pc
);
132 printf("%4x:\t", pc
);
135 count
= disassemble(pc
, &info
);
137 /* Operand array, was started in fprintf_json. Before
138 * that, make sure we have a _null_ value if no operand
139 * other than operation code was present.
142 jsonw_null(json_wtr
);
143 jsonw_end_array(json_wtr
);
148 jsonw_name(json_wtr
, "opcodes");
149 jsonw_start_array(json_wtr
);
150 for (i
= 0; i
< count
; ++i
)
151 jsonw_printf(json_wtr
, "\"0x%02hhx\"",
152 (uint8_t)image
[pc
+ i
]);
153 jsonw_end_array(json_wtr
);
156 for (i
= 0; i
< count
; ++i
)
158 (uint8_t)image
[pc
+ i
]);
162 jsonw_end_object(json_wtr
);
167 } while (count
> 0 && pc
< len
);
169 jsonw_end_array(json_wtr
);