Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the assembly TEST instruction work with these jump instructions?

Using AT&T assembly syntax, I'm trying to understand how testl is used in assembly code. Specifically:

testl  %edx, %edx
jle    .L3

I know testl does a bitwise and of the same value to set the condition flags, but how can I interpret 'jump if less than or equal to' if it isn't comparing two values?

like image 487
amorimluc Avatar asked Jan 30 '13 02:01

amorimluc


People also ask

How does jump work in assembly?

A jump instruction, like "jmp", just switches the CPU to executing a different piece of code. It's the assembly equivalent of "goto", but unlike goto, jumps are notconsidered shameful in assembly.

How does JMP work in assembly?

In the x86 assembly language, the JMP instruction performs an unconditional jump. Such an instruction transfers the flow of execution by changing the program counter.

How does TEST work in assembly?

The TEST instruction performs an implied AND operation between corresponding bits in the two operands and sets the flags without modifying either operand. reg, mem, and immed can be 8, 16, or 32 bits. The CMP instruction sets the flags as if it had performed subtraction on the operand.


1 Answers

Here's an excerpt from the official documentation from Intel on test:

Operation
TEMP ← SRC1 AND SRC2;
SF ← MSB(TEMP);
IF TEMP = 0
    THEN ZF ← 1;
    ELSE ZF ← 0;
FI:
PF ← BitwiseXNOR(TEMP[0:7]);
CF ← 0;
OF ← 0;

And the same on jle:

Jump if less or equal (ZF=1 or SF≠OF)

So, the jump will be performed if edx is 0 (because edx AND edx = edx and that's 0 only when edx is 0, and because ZF is set to 1 when the result of AND is 0) or if the most significant bit of edx is 1 (because SF = most significant bit of edx AND edx (or, equivalently, of edx itself) and OF is always 0, which means SF ≠ OF is only true when SF ≠ 0).

IOW, the jump will be performed only if edx is ≤ 0 when interpreted as a signed integer or, equivalently, when edx is either 0 or greater or equal than 0x80000000 when interpreted as an unsigned integer.

like image 75
Alexey Frunze Avatar answered Nov 15 '22 07:11

Alexey Frunze