Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many byes is each instruction compiled to in x86 assembly?

0x004012d0 <main+0>:    push   %ebp
0x004012d1 <main+1>:    mov    %esp,%ebp
0x004012d3 <main+3>:    sub    $0x28,%esp

If the address is not available, can we calculate it ourselves?

I mean we only have this:

push   %ebp
mov    %esp,%ebp
sub    $0x28,%esp
like image 530
Mask Avatar asked Mar 30 '10 16:03

Mask


2 Answers

amount of bytes is difference of addresses between adjacent instructions:

0x004012d0 <main+0>:    push   %ebp ;1 byte
0x004012d1 <main+1>:    mov    %esp,%ebp ;2 bytes
0x004012d3 <main+3>:    sub    $0x28,%esp

if you have only text then go here: http://www.swansontec.com/sintel.html and here: http://faydoc.tripod.com/cpu/conventions.htm and calculate for each instruction, prefix and operand

like image 168
Andrey Avatar answered Nov 03 '22 02:11

Andrey


You can't necessarily determine the instruction size from the mnemonic. Here are some special cases:

  • if you're in a 16-bit segment, mov eax, 0 requires a 0x66 prefix, while in a 32-bit segment it doesn't. You need to know the size of the segment.

  • in 32-bit or 16-bit mode you can encode add eax, 1 as either 0x40 (inc eax) or 0x83 0xc0 0x01 (add eax, 1). That is, there are some mnemonics that can be encoded in more than one way.

  • The memory operand [eax] may encode eax as either the base or the index. If it's the index, you'll have an additional SIB byte after the MOD/RM.

  • in 64-bit mode you can use the REX prefix 0x4x to encode the registers r8-r15. However, you can use 0x40 as some sort of null REX byte, which will add another byte to your instruction.

  • segment overrides may be used, even if the explicit segment is the same as the implicit one.

There are many other ways to encode an instruction using more or less bytes. A good assembler should probably always use the shortest one, but it's certainly not required by the architecture. The good thing is that if you study volume 2 of the Intel IA-32 Software Developer's Manual, you should be able to work it out by yourself.

like image 21
Nathan Fellman Avatar answered Nov 03 '22 02:11

Nathan Fellman