-->

Assembly - js versus ja instruction

2019-09-14 12:26发布

问题:

So the goal is for me to write out the C code that corresponds to this assembly :

0:  85 f6                   test   %esi,%esi
2:  78 13                   js     17 <part3+0x17>
4:  83 fe 07                cmp    $0x7,%esi
7:  77 14                   ja     1d <part3+0x1d>
9:  8d 0c f5 00 00 00 00    lea    0x0(,%rsi,8),%ecx
10: 48 d3 ff                sar    %cl,%rdi
13: 48 89 f8                mov    %rdi,%rax
16: c3                      retq   
17: b8 00 00 00 00          mov    $0x0,%eax
1c: c3                      retq   
1d: b8 00 00 00 00          mov    $0x0,%eax
22: c3                      retq   

I am a little confused because the first loop testing the %esi register ends before the second loop ends.

Is the second if statement comparing %esi to 7 inside the first loop? or is this a if , else if situation??

回答1:

Let me sum up, what's already been said

0:  85 f6                   test   %esi,%esi
2:  78 13                   js     17 <part3+0x17>

this is " if (esi < 0) goto 17; "

4:  83 fe 07                cmp    $0x7,%esi
7:  77 14                   ja     1d <part3+0x1d>

this is " if (esi >7) goto 1d; "

9:  8d 0c f5 00 00 00 00    lea    0x0(,%rsi,8),%ecx

"cx = 8*rsi" // not that obvious it's "just" a multiplication)

10: 48 d3 ff                sar    %cl,%rdi

rdi >> cl; // not cx, but cx is safe to be <= 7*8, so that's the same 13: 48 89 f8 mov %rdi,%rax 16: c3 retq

return rdi;

17: b8 00 00 00 00          mov    $0x0,%eax
1c: c3                      retq   

17: "return 0"

1d: b8 00 00 00 00          mov    $0x0,%eax
22: c3                      retq

1d: another "return 0"

so the C-Code is:

{
    if (esi < 0) return 0;
    if (esi > 7) return 0;
    return rdi >> ( 8 * rsi );
}

PS: the 2 "return 0" (17 and 1d) give a clear indication that, in the C-code, the two ifs were NOT combined into one
PSS: the C Code was obviously not compiled with optimization :P