Looking for missing C code given by assembler code?

Code

int f(int x, int y, int z) { if (/* missing code here */) return z; else return -z; } 

And assembly

  pushl %ebp movl %esp, %ebp movl 8(%ebp), %eax cmpl 12(%ebp), %eax jge .L2 movl 16(%ebp), %eax jmp .L3 .L2: movl 16(%ebp), %eax negl %eax .L3: popl %ebp ret 

And the question asks me to find that the missing test expression should lead to the provision of the given assembly code. Good, easy enough. There is an obvious comparison between x and y . The jge is about to transform the jump into the body of the loop if 12(%ebp) > %eax .

Possible options:

x<=y x>=y x>y x<y

My answer was x<=y , since 12(%ebp) is a reference to y , and that is the destination. But this answer was wrong, and I do not understand how to do it. Any hints? Thank you so much.

+6
source share
2 answers

Here is the annotated x86 build:

pushl %ebp ; save the old stack movl %esp, %ebp ; set up your local, new stack movl 8(%ebp), %eax ; take the first function argument and store it into eax cmpl 12(%ebp), %eax ; compare the 2nd function arg with the 1st (in eax)

After that, there is jge , which jge means "jumping if greater than or equal to", which you can do after cmp .

This means that it jumps if the first argument is greater than the second argument and therefore x >= y .

However, this jump (before L2) actually negates z, and then returns z. What you really want is a transition to L3, which will happen if x <y, which should be the end result.

+5
source

You can ask the GCC what it will do. Create a source with several features:

test.c

 int f1 (int x, int y, int z) { if (x < y) return z; else return -z; } int f2 (int x, int y, int z) { if (x > y) return z; else return -z; } int main ( void ) { return 0; } 

f1 does (x <y), f2 does (x> y). Now build it:

 gcc test.c -m32 -Wa,-ahln -fno-asynchronous-unwind-tables 

You see the assembly test.c Find f1: and f2: which are the entry points for the functions. Which one matches your snippet? You will see that f1 matches, while f2 handles jle .

+2
source

All Articles