Search code examples
assemblyx86cmp

cmpl and jge not working as exected, x86


I have to translate the following simple C code:

int add(int a, int b);

int main()
{
    int a,b;
    a = 0;
    while(a<5)
    {
        a++;
        printi(a);
        prints("\n");
    }
    return 0;
}

int add(int a, int b)
{
    char cx = 'a';
    int x = a-b;
    return x;
}

And I have made a compiler that translates it to the following GNU x86 assembly code. (printi and prints are library functions that I link after translation).

.section    .rodata
.LC0:
    .string "\n"
    .text
    .globl  main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    movl    $0, -4(%ebp)
    movl    -4(%ebp), %eax
    movl    %eax, -12(%ebp)
.L0:
    movl    $5, %eax
    movl    -4(%ebp), %edx
    cmpl    %edx, %eax
    jge .CH1
.CH0:
    movl    $1, -16(%ebp)
    jmp .CH2
.CH1:
    movl    $0, -16(%ebp)
.CH2:
    movl    $0, %eax
    cmpl    -16(%ebp), %eax
    je  .L2
    jmp .L1
.L1:
    movl    -4(%ebp), %eax
    movl    %eax, -20(%ebp)
    movl    -20(%ebp), %eax
    movl    $1, %edx
    addl    %edx, %eax
    movl    %eax, -4(%ebp)
    movl    -4(%ebp), %eax
    movl    %eax, (%esp)
    call    printi
    movl    %eax, -24(%ebp)
    movl    $.LC0, (%esp)
    call    prints
    movl    %eax, -28(%ebp)
    jmp .L0
.L2:
    movl    $0, %eax
    leave
    ret
    .size   main, .-main
    .globl  add
    .type   add, @function
add:
    pushl   %ebp
    movl    %esp, %ebp
    movb    $97, -1(%ebp)
    movl    4(%ebp), %eax
    movl    8(%ebp), %edx
    subl    %edx, %eax
    movl    %eax, -9(%ebp)
    movl    -9(%ebp), %eax
    movl    %eax, -5(%ebp)
    movl    -5(%ebp), %eax
    leave
    ret
    .size   add, .-add

The program however does not output anything. It seems I have made a mistake somewhere around the check expression of while.

The instruction cmpl %edx, %eax should set the flag as 0-5, which is -5. jge should hence does not branch it to .CH1. Hence -16(%ebp) should be set as 1, and it should then get into .CH2. As 1!=0, it should then get into L1. I don't know where am I going wrong.


Solution

  • The instruction cmpl %edx, %eax should set the flag as 0-5, which is -5. j

    Nope. Remember that in AT&T syntax the operand order is source, destination. You've got eax = 5 and edx = 0, so cmpl %edx, %eax sets the flags based on 5-0, after which the jge should jump.