Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional jumps -- comparing c code to assembly

Tags:

c

x86

assembly

I am trying to compare a c function code to the equivalent of the assembly and kind of confused on the conditional jumps

enter image description here

I looked up jl instruction and it says jump if < but the answer to the question was >= Can someone explain why is that?

like image 915
hmaxx Avatar asked Feb 28 '17 07:02

hmaxx


3 Answers

To my understanding, the condition is inverted, but the logic is the same; the C source defines

if the condition is satisfied, execute the following block

whereas the assembly source defines

if the condition is violated, skip the following block

which means that the flow of execution will be the same in both implementations.

like image 189
Codor Avatar answered Sep 23 '22 22:09

Codor


In essence, what this assembly is doing, is executing your condition as you set it, but using negative logic.

Your condition says:

If a is smaller then b, return x. Otherwise, return y.

What the assembly code says (simplified):

Move y into the buffer for returning. Move b into a different buffer. If a is bigger then b, jump ahead to the return step. Then y is returned. If a is not bigger then b, continue in the program. The next step assigns x to the return buffer. The step after that returns as normal.

The outcome is the same, but the process is slightly different.

like image 35
Magisch Avatar answered Sep 25 '22 22:09

Magisch


the assembly does, line by line (code not included, because you posted it as image):

foo:
    return_value (eax) = y; // !!!
    temporary_edx = b;      // x86 can't compare memory with memory, so "b" goes to register
    set_flags_by(a-b);      // cmp does subtraction and discards result, except flags
    "jump less to return"   // so when a < b => return y (see first line)
    return_value (eax) = x;
    return

so to make that C code do the same thing, you need:

if (a >= b) { return x; } else { return y; }

BTW, see how easy it is to flip:

if (a < b) { return y; } else { return x; }

So there's no point to translate jl into "less" into C, you have to track down each branch, what really happens, and find for each branch of calculation the correct C-side calculation, and then "create" the condition in C to get the same calculation on both sides, so this task is not about "translating" the assembly, but about deciphering the asm logic + rewriting it back in C. Looks like you sort of completely missed the point and expected you can get away with some simple "match pattern" translation, while you have to work it out fully.

like image 40
Ped7g Avatar answered Sep 21 '22 22:09

Ped7g