0
votes

I was hoping someone could validate my understanding of the following assembly code:

test %esi,%esi
js 17 <build+0x17>
cmp $0x8,%esi
ja 1d <build+0x1d>
lea (&rsi,2),%ecx
shl $0x2,%rdi
mov %rdi,%rax
retq
mov $0x0,%eax //17
retq
mov $0x0,%eax //1d
retq

Here's what I think the code does:

  • If esi&esi is negative return item at address 0
  • If esi is above 8, return item at address 0
  • Else store address of rsi *2 into ecx
  • Then right shift rdi right by 2 bits
  • Copy rdi to rax and return it
1
Return 0, not return anything at address 0Sami Kuhmonen
Is the rest of it accurate?Keyadun
The line lea (&rsi,8),%ecx should probably be written lea (,%rsi,8),%ecx and means ECX=RSI*8 and not 'address of rsi`. The rest looks good.zx485
And of course "If esi&esi is negative" == "If esi is negative"Michael
same asm code is discussed there: [stackoverflow.com/questions/36379900/…Tommylee2k

1 Answers

1
votes

This is what the code does:

if (esi >= 0 && esi <= 7) {
    return rdi >> (esi * 8);   // Note: arithmetic shift; preserves sign
}
return 0;

So esi specifies the number of bytes (0..7) to shift out on the right from rdi. Since an arithmetic shift is used, the original sign of rdi is preserved.

For example:

Input:
  rdi = 0xFC00AABB12345678
  esi = 2

Output:
  rax = 0xFFFFFC00AABB1234