-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtest_binary.c
92 lines (77 loc) · 2.5 KB
/
test_binary.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Guillaume Valadon <guillaume@valadon.net>
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <bfd.h>
#include <dis-asm.h>
void override_print_address(bfd_vma addr, struct disassemble_info *info)
{
// This function change how addresses are displayed
printf ("0x%x", addr);
}
static int
fprintf_styled_func (void *arg,
enum disassembler_style st ATTRIBUTE_UNUSED,
const char *fmt ATTRIBUTE_UNUSED, ...)
{
int res;
va_list ap;
va_start (ap, fmt);
res = vfprintf (arg, fmt, ap);
va_end (ap);
return res;
}
int main(int argc, char **argv)
{
bfd *bfdFile;
asection *section;
disassembler_ftype disassemble;
struct disassemble_info info;
unsigned long count, pc;
/* Open an ELF binary with libbfd */
bfd_init ();
bfdFile = bfd_openr ("/bin/ls", "elf64-x86-64");
if (bfdFile == NULL) {
printf ("Error [%x]: %s\n", bfd_get_error (),
bfd_errmsg (bfd_get_error ()));
return EXIT_FAILURE;
}
if (!bfd_check_format( bfdFile, bfd_object)) {
printf ("Error [%x]: %s\n", bfd_get_error (),
bfd_errmsg (bfd_get_error ()));
return EXIT_FAILURE;
}
/* Retrieve the ELF .text code section */
section = bfd_get_section_by_name (bfdFile, ".text");
if (section == NULL) {
printf ("Error accessing .text section\n");
return EXIT_FAILURE;
}
/* Get a disassemble function pointer */
disassemble = disassembler (bfd_get_arch (bfdFile), bfd_big_endian (bfdFile),
bfd_get_mach (bfdFile), bfdFile);
if (disassemble == NULL) {
printf ("Error creating disassembler\n");
return EXIT_FAILURE;
}
/* Construct and configure the disassembler_info class */
init_disassemble_info (&info, stdout, (fprintf_ftype) fprintf, (fprintf_styled_ftype) fprintf_styled_func);
info.disassembler_options = "intel";
info.print_address_func = override_print_address;
info.arch = bfd_get_arch (bfdFile);
info.mach = bfd_get_mach (bfdFile);
info.buffer_vma = section->vma;
info.buffer_length = section->size;
info.section = section;
bfd_malloc_and_get_section (bfdFile, section, &info.buffer);
disassemble_init_for_target (&info);
/* Start diassembling */
pc = bfd_get_start_address (bfdFile);
do {
printf ("0x%x ", pc);
count = disassemble (pc, &info);
pc += count;
printf ("\n");
} while (count > 0 && pc <= section->size);
return EXIT_SUCCESS;
}