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

13,232

Solution 1

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

Solution 2

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.

Solution 3

The first instruction is at [main+0] and the second is at [main+1] so the first instruction is 1 byte. The third instruction is at [main+3], so the second instruction is two bytes. You can't tell from the listing how long the third instruction is, since it doesn't show the address of the 4. instruction.

Share:
13,232
Mask
Author by

Mask

Updated on June 04, 2022

Comments

  • Mask
    Mask 7 months
    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