简体   繁体   中英

Assembly Code to C

I was practicing some assembly code to C and need some help with two questions. Based on the GCC objdump it seems okay but I want to make sure I can do this WITHOUT a computer (still kind of new to assembly code)

Question 1 :

q1:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $4, %esp
    cmpl    $0, 8(%ebp)\\ compare variable1 to zero
    jle .L2 \\jump if less than or equal to zero
    movl    $1, -4(%ebp)\\ ?? variable2 = 1??
    jmp .L4\\else 
.L2:
    movl    $0, -4(%ebp)\\ variable2 = 0
.L4:
    movl    -4(%ebp), %eax\\ variable2 = variable1
    leave
    ret

what I got was

int main(int x, int z)  
{
    if (x < 0)
        z = 0;
    else
        z = x;
 }

But I was not sure what the purpose of movl $1, -4(%ebp) was.

Question 2 :

fn:
    pushl   %ebp
    movl    $1, %eax
    movl    %esp, %ebp
    movl    8(%ebp), %edx 
    cmpl    $1, %edx\\ compare variable1 to 1
    jle .L4\\ less than or equal jump.
.L5:
    imull   %edx, %eax\\ multiply variable1 by variable 2
    subl    $1, %edx\\ variable1 -1
    cmpl    $1, %edx\\ compare variable1 with 1
    jne .L5 Loop if not equal
.L4:
    popl    %ebp\\ return value
    ret

How I interpreted the information

int main(int x)
{
    int result;
    if (x <= 1){
    for (result=1; x != 1; x = x-1)
            result *= x;}
    else{return result;}
}

Not sure if my logic is correct on either of those.

Q1 you have one argument 8(%ebp) and one local variable at -4(%ebp) . Return value will be in %eax . Knowing this, the function looks more like:

int foo(int arg)
{
    int local;
    if (arg <= 0) {
        local = 0;
    } else {
        local = 1;
    }
    return local;
}

Q2 popl %ebp // return value that's not the return value, that's restoring the saved %ebp of the caller (that was pushed in the beginning). Also, the condition in the loop should use > not != . You are missing an if (x > 1) conditional around the for loop. (Thanks to Mooing Duck for pointing this out.) Also, technically it's a do - while loop. Otherwise you got this function right.

int factorial(int x)
{
    int result = 1;
    if (x > 1) {
        do {
            result *= x;
            x -= 1;
        } while(x != 1);
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM