0
votes

I have the following 32-bit x86 assembly code:

.text
    .global _start

_start:
    /* Compare 3 < 2 */
    mov     $2, %eax
    cmp     $3, %eax

    /* Set the low byte of %eax according to the SF and 0F flags. */
    setl    %al

    /* Syscall exit with the value of %eax. */
    mov     %eax, %ebx
    mov     $1, %eax
    int     $0x80

If I assemble and link it, I get a binary that exits with an exit code of 1. If I switch the CMP operands, my binary exits with 0.

This is the opposite of what I expected. CMP according to this x86 reference:

The comparison is performed by subtracting the second operand from the first operand and then setting the status flags in the same manner as the SUB instruction.

The first operand is 3, the second operand is 2. 3-2 is 1, which is greater than zero, so why is SF (the sign flag) set?

1

1 Answers

6
votes

You got bitten by the AT&T syntax. In Intel syntax your compare looks like:

cmp eax, 3

in which the result matches the description.