OneAndOnly
OneAndOnly

Reputation: 1056

How does the CPU know how many bytes it should read for the next instruction, considering instructions have different lengths?

So i was reading a paper, and in it, they said that statically disassembling the code of a binary is undecidable, because a series of bytes could be represented as many possible ways as shown in picture ( its x86 )

disassembling

so my question is :

  1. how does the CPU execute this then? for example in the picture, when we reach after C3, how does it know how many bytes it should read for the next instruction?

  2. how does the CPU know how much it should increment the PC after executing one instruction? does it somehow store the size of the current instruction and add that when it wants to increment PC?

  3. if the CPU can somehow know how many bytes it should read for the next instruction or basically how to interpret the next instruction, why cant we do it statically?

Upvotes: 8

Views: 2890

Answers (5)

Ross Ridge
Ross Ridge

Reputation: 39581

The simple way is to just read one byte, decode it and then determine if it's a complete instruction. If not read another byte, decode it if necessary and then determine if a complete instruction has been read. If not continue reading/decoding bytes until the complete instruction is read.

This means that if the instruction pointer is pointing at a given sequence of bytes there's only possible way to decode that first instruction of that sequence of bytes. The ambiguity only comes because the next instruction to be executed might not be located at the bytes immediately that follow the first instruction. That's because the first instruction in the sequence of bytes may change the instruction pointer so some other instruction other than the following one gets executed.

The RET (retn) instruction in your example could be the end of a function. Functions often end with e RET instruction, but not necessarily so. It's possible for a function to have multiple RET instructions, none of which are at the end of the function. Instead the last instruction will be some sort of JMP instruction that jumps back to some location in the function, or to another function entirely.

That means in your example code, without more context, it's impossible to know if any of the bytes following the RET instruction will be ever be executed, and if so, which of the bytes would be the first instruction of the following function. There could be data in between functions or this RET instruction could be the end of the last function in the program.


The x86 instruction set in particular has a pretty complex format of optional prefix bytes, one or more opcode bytes, one or two possible addressing form bytes, and then possible displacement and immediate bytes. The prefix bytes can be prepended to just about any instruction. The opcode bytes determine how many opcode bytes there are and whether the instruction can have a operand bytes and immediate bytes. The opcode may also indicate that there's displacement bytes. The first operand byte determines if there's a second operand byte and if there's displacement bytes.

The Intel 64 and IA-32 Architectures Software Developer's Manual has this figure showing the format of x86 instructions:

X86 Instruction Format

Python-like pseudo-code for decoding x86 instructions would look something like this:

# read possible prefixes

prefixes = []
while is_prefix(memory[IP]):
    prefixes.append(memory[IP))
    IP += 1

# read the opcode 

opcode = [memory[IP]]
IP += 1
while not is_opcode_complete(opcode):
    opcode.append(memory[IP])
    IP += 1

# read addressing form bytes, if any

modrm = None
addressing_form = []    
if opcode_has_modrm_byte(opcode):
    modrm = memory[IP]
    IP += 1
    if modrm_has_sib_byte(modrm):
        addressing_form = [modrm, memory[IP]]
        IP += 1
    else:
        addressing_form = [modrm]

# read displacement bytes, if any

displacement = []
if (opcode_has_displacement_bytes(opcode)
    or modrm_has_displacement_bytes(modrm)):
    length = determine_displacement_length(prefixes, opcode, modrm)
    displacement = memory[IP : IP + length]
    IP += length

# read immediate bytes, if any

immediate = []
if opcode_has_immediate_bytes(opcode):
    length = determine_immediate_length(prefixes, opcode)
    immediate = memory[IP : IP + length]
    IP += length

# the full instruction

instruction = prefixes + opcode + addressing_form + displacement + immediate

One important detail left out of the pseudo-code above is that instructions are limited to 15 bytes in length. It's possible to construct otherwise valid x86 instructions that are 16 bytes or longer, but such instruction will generate an undefined opcode CPU exception if executed. (There are other details I've left out, like how part of the opcode can be encoded inside of the Mod R/M byte, but I don't think this affects the length of instructions.)


However x86 CPUs don't actually decode instructions like how I've described above, they only decode instructions as if they read each byte one at a time. Instead modern CPUs will read an entire 15 bytes in to a buffer and then decode bytes in parallel, usually in a single cycle. When it fully decodes the instruction, determining its length, and is ready to read the next instruction it shifts over the remaining bytes in the buffer that weren't part of the instruction. It then reads more bytes to fill the buffer to 15 bytes again and starts decoding the next instruction.

Another thing modern CPUs will do that's isn't implied by what I've written above, is speculatively execute instructions. This means the CPU will decode instructions and tentatively try to execute them even before it has finished executing the previous instructions. This in turn means that the CPU may end up decoding the instructions following the RET instruction, but only if it can't determine where the RET will return to. Because there can be performance penalties from trying to decode and tentatively execute random data that's not intended to be executed, compilers don't normally put data in between functions. Though they may pad this space with NOP instructions that will never be executed in order to align functions for performance reasons.

(They used to put read-only data in between functions long ago, but this was before x86 CPUs that could speculatively execute instructions became common place.)

Upvotes: 8

Martin Rosenau
Martin Rosenau

Reputation: 18493

Your main problem seems to be the following one:

if the CPU can somehow know how many bytes it should read for the next instruction or basically how to interpret the next instruction, why cant we do it statically?

The problem described in the paper is related to "jumping" instructions (which does not only mean jmp, but also int, ret, syscall and similar instructions):

The purpose of such instructions is to continue program execution at a completely different address instead of continuing at the next instruction. (Function calls and while() loops are examples where program execution does not continue at the next instruction.)

Your example begins with the instruction jmp eax which means that the value in the register eax decides which instruction is executed after the jmp eax instruction.

If eax contains the address of the byte 0F, the CPU will execute the jcc instruction (left case in the picture); if it contains the address of 88, it will execute the mov instruction (middle case in the picture); and if it contains the address of 52, it will execute the push instruction (right case in the picture).

Because you do not know which value eax will have when the program is executed, you cannot know which of the three cases will happen.

(I was told that in the 1980s there even were commercial programs where different cases happened during runtime: In your example this would mean that sometimes the jcc instruction and sometimes the mov instruction is executed!)

When we reach after C3, how does it know how many bytes it should read for the next instruction?

How does the CPU know how much it should increment the PC after executing one instruction?

C3 is not a good example because retn is a "jumping" instruction: The "instruction after C3" will never be reached because program execution is continued elsewhere.

However, you might replace C3 by another instruction which is one byte long (such as 52). In this case it is well defined that the next instruction will begin with the byte 0F and not with 88 or 52.

Upvotes: 1

mcleod_ideafix
mcleod_ideafix

Reputation: 11428

Static disassembly is undecidable because the disassembler cannot discern whether a group of bytes is code or data. The example you provided is a good one: after the RETN instruction, ther might be another subroutine, or it might be some data, then a routine. There is no way to decide which is the correct one until you actually execute the code.

When an opcode is read during the instruction fetch phase, the opcode itself encodes one kind of instruction and the sequencer already knows how much bytes to read from it. There is no ambiguity. In your example, after fetching C3 but before executing it, the CPU will adjust its EIP register (Intruction Pointer) to read what it considers it will be the next instruction (the one beginning with 0F), BUT during the execution of instruction C3 (which it's a RETN instruction), the EIP is changed as RETN is "Return from subroutine) so it won't reach instruction 0F 88 52. That instruction will only be reached if some other part of the code jumps to the location of that instruction. If no code performs such jump, then it will be considered as data, but the problem of determining whether a particular instruction will or will not executed is not a decidable problem.

Some clever disassemblers (I think IDA Pro does that) start from a location known to store code, and assume all following bytes to be instructions as well, UNTIL a jump or ret is found. If a jump is found and the destination of the jump is known by reading the binary code, then the scanning continues there. If the jump is conditional, then the scanning branches into two paths: jump not taken and jump taken.

After all brances have been scanned, everything that is left, is considered data (that means that interrupt handlers, exception handlers, and functions that are called from a function pointer calculated at runtime won't be detected)

Upvotes: 3

fuz
fuz

Reputation: 93004

On x86 specifically, the instruction encoding is such that from each byte, the decoder can learn how many more bytes follow.


For example, let me show you how the decoder could possibly decode this instruction stream.

55

the decoder sees 55 and knows that this is push ebp, a single byte instruction. So it decodes push ebp and proceeds to the next instruction.

push ebp
89

the decoder sees 89 which is mov r/m32,r32. This instruction is followed by a modr/m byte specifying the operands.

push ebp
89 e5

the modr/m byte is e5 indicating ebp as the r/m operand and esp as the r operand, so the instruction is mov ebp, esp.

push ebp
mov ebp, esp
8b

this instruction is mov r32,r/m32 which is likewise followed by a modr/m byte.

push ebp
mov ebp, esp
8b 45

this modr/m byte has an r operand of eax and a r/m32 operand of [ebp + disp8] with an 8 bit displacement, which comes with the next byte

push ebp
mov ebp, esp
8b 45 0c

the displacement is 0c so the instruction is mov eax, [ebp + 0xc]

push ebp
mov ebp, esp
mov eax, [ebp + 0xc]
03

this instruction is add r,r/m32 again followed by a modr/m byte.

push ebp
mov ebp, esp
mov eax, [ebp + 0x0c]
03 45

same as before, the r operand is eax while the r/m operand is [ebp + disp8]. The displacement is 08.

push ebp
mov ebp, esp
mov eax, [ebp + 0x0c]
add eax, [ebp + 0x08]
01

this instruction is add r/m32, r followed by a modr/m byte.

push ebp
mov ebp, esp
mov eax, [ebp + 0x0c]
add eax, [ebp + 0x08]
01 05

this modr/m byte indicates an r operand of eax and an r/m operand of [disp32]. The displacement follows in the next four bytes which are 00 00 00 00.

push ebp
mov ebp, esp
mov eax, [ebp + 0x0c]
add eax, [ebp + 0x08]
add [0x00000000], eax
5d

instruction 5d is pop ebp, a single byte instruction.

push ebp
mov ebp, esp
mov eax, [ebp + 0x0c]
add eax, [ebp + 0x08]
add [0x00000000], eax
pop ebp
c3

instruction c3 is ret, a single byte instruction. This instruction transfers control to somewhere else, so the decoder stops decoding from here.

push ebp
mov ebp, esp
mov eax, [ebp + 0x0c]
add eax, [ebp + 0x08]
add [0x00000000], eax
pop ebp
ret

In real x86 processors, complicated parallel decoding techniques are employed. This is possible because the processor may cheat and pre-read instruction bytes that may or may not be part of any instruction.

Upvotes: 4

Nominal Animal
Nominal Animal

Reputation: 39326

Part of the CPU is an instruction decoder (see e.g. the Wikipedia article on Central Processing Unit). The task of the instruction decoder is to determine how many bytes, starting from the address pointed to by the Instruction Pointer, are part of the current instruction, and decode it into its constituent parts.

There are some architectures (mostly microcontrollers nowadays) where all instructions are the same size. On 64-bit Intel/AMD architecture (x86-64 a.k.a. AMD64), the instruction size varies between 1 and 15 bytes, and the instruction encoding is quite complex.

Upvotes: 3

Related Questions