1

I am trying to recreate the original function func4(), in C program from the following Assembly code. func4() takes 3 arguments.

  ...
  40104e:   ba 0e 00 00 00          mov    $0xe,%edx
  401053:   be 00 00 00 00          mov    $0x0,%esi
  401058:   8b 3c 24                mov    (%rsp),%edi
  40105b:   e8 85 ff ff ff          call   400fe5 <func4>
  ...
  
0000000000400fe5 <func4>:
  400fe5:   53                      push   %rbx
  400fe6:   89 d0                   mov    %edx,%eax
  400fe8:   29 f0                   sub    %esi,%eax
  400fea:   89 c3                   mov    %eax,%ebx
  400fec:   c1 eb 1f                shr    $0x1f,%ebx
  400fef:   01 d8                   add    %ebx,%eax
  400ff1:   d1 f8                   sar    %eax
  400ff3:   8d 1c 30                lea    (%rax,%rsi,1),%ebx
  400ff6:   39 fb                   cmp    %edi,%ebx
  400ff8:   7e 0c                   jle    401006 <func4+0x21>
  400ffa:   8d 53 ff                lea    -0x1(%rbx),%edx
  400ffd:   e8 e3 ff ff ff          call   400fe5 <func4>    // fist recursion call
  401002:   01 d8                   add    %ebx,%eax
  401004:   eb 10                   jmp    401016 <func4+0x31>
  401006:   89 d8                   mov    %ebx,%eax
  401008:   39 fb                   cmp    %edi,%ebx
  40100a:   7d 0a                   jge    401016 <func4+0x31>
  40100c:   8d 73 01                lea    0x1(%rbx),%esi
  40100f:   e8 d1 ff ff ff          call   400fe5 <func4>   // second recursion call
  401014:   01 d8                   add    %ebx,%eax
  401016:   5b                      pop    %rbx
  401017:   c3                      ret

I am unable to understand 400ff1: d1 f8 sar %eax instruction. How it carries out the arithmetic right shift operation and from where it takes the shift amount ? The shift amount should come from the lower %cl part of %rcx register, but the during that instruction execution the %rcx register contains value 0x0, but instead of that the value in the %rax register is shifted some amount.

Detailed technical explanation is appreciated.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
arka
  • 418
  • 2
  • 9
  • 3
    The no-operand `sar` implicitly shifts by 1. To be technical it's opcode `d1 /7` which the instruction set reference shows as _"SAR r/m32, 1 Signed divide r/m32 by 2, once."_ – Jester Jul 03 '22 at 11:54

0 Answers0