Sebastian Wick
Sebastian Wick

Reputation: 23

libopcodes: get the size of a instruction

I have to find out the size of a instruction which I have in memory (actually, I have a small code segment in memory and want to get the size of the first instruction). It took me some time to find libopcodes and libbfd. I red the headers and tried to come up with a simple solution but it seems like I missunderstood something since the program always crashes:

int main(int argc, char **argv) {
    disassemble_info *dis = malloc(sizeof(*dis));
    assert(dis != NULL);

    dis->arch = bfd_arch_i386;
    dis->read_memory_func = buffer_read_memory;
    dis->buffer_length = 64;
    dis->buffer = malloc(dis->buffer_length);
    memset(dis->buffer, 0x90, dis->buffer_length);
    disassemble_init_for_target(dis);

    int instr_size = print_insn_i386(0, dis);

    printf("instruction size is %d\n", instr_size);

    return 0;
}

The expected result would be an instruction size of 1 (nop).

EDIT:

sorry guys, I'm a stupid person.

memset(dis, 0, sizeof(*dis));

Upvotes: 1

Views: 732

Answers (2)

Scott Wisniewski
Scott Wisniewski

Reputation: 25071

There is some code in the Linux kernel you can steal. It should work well if copied into a user mode program.

Take a look at arch/x86/lib and arch/x86/tools There's an opcode map file there, and an awk script that reads it to produce a table in a file named innat.c. There are some other files there that use the table to implement a decoder.

It is sufficient to determine instruction sizes.

This assumes you are ok with GPL, of course.

Upvotes: 1

Multimedia Mike
Multimedia Mike

Reputation: 13276

It looks like the disassemble_info data structure requires more initialization than you have provided. From examples I have been studying, the correct way to initialize is to call init_disassemble_info().

See if that helps. Failing that, compile your program with debug info ('-g') and run gdb to diagnose where the crash occurs.

Upvotes: 0

Related Questions