1

I'm trying to learn more about the x86 assembly. I have the assembly code of a mystery function. All I know about this function is that it must return an integer and has an integer as an argument:

int mystery(int n){}

The assembly for this function is

0000000000400526 <mystery_util>:
  400526:    89 f8                    mov    %edi,%eax
  400528:    d1 e8                    shr    %eax
  40052a:    83 e7 01                 and    $0x1,%edi
  40052d:    01 f8                    add    %edi,%eax
  40052f:    c3                       retq   

0000000000400530 <mystery>:
  400530:    89 f8                    mov    %edi,%eax
  400532:    8d 3c fd 00 00 00 00     lea    0x0(,%rdi,8),%edi
  400539:    29 c7                    sub    %eax,%edi
  40053b:    83 c7 04                 add    $0x4,%edi
  40053e:    e8 e3 ff ff ff           callq  400526 <mystery_util>
  400543:    f3 c3                    repz retq

I don't understand how to write this as a C function. If there is a callq wouldn't it mean there are 2 different functions?

I'm trying to write this out in one function that returns an integer. I see how it could return a boolean but can there be a way to return an integer?

minturtle
  • 55
  • 5
  • 2
    Yes, these are two functions. The `mystery` is calling the `mystery_util`, as can be deduced from the name too. You can of course merge them if required. – Jester Mar 18 '18 at 23:53
  • @MichaelPetch oh i just noticed that question. However they return bool type and I'm trying to see if it can return an int. – minturtle Mar 19 '18 at 00:42
  • 1
    @Pablo: https://stackoverflow.com/questions/49350723/writing-a-c-function-from-given-x86-assembly had a different `mystery` function, so that was not quite the right duplicate. **This one matches exactly, except the last instruction in `mystery_util` is `ADD` instead of `AND`** So it's no longer equivalent to `n%3 == 0`, instead being a significantly different function that can have non-zero bits at any position. – Peter Cordes Mar 19 '18 at 02:19
  • @MichaelPetch yes mystery_util was not defined. And also as pointed out above, the code in the other question is not exactly the same. the code for my mystery_util has AND and then ADD before retq. The other one only has and. – minturtle Mar 19 '18 at 02:42
  • Okay, not a duplicate (I didn't see the minor difference), but you probably can get some useful information from the other answer that should help you with this one. – Michael Petch Mar 19 '18 at 02:44
  • @MichaelPetch yup! thanks! – minturtle Mar 19 '18 at 02:45
  • The function results are very different, but the C expression differs only by one operator: `n += (n>>1) & 1;` instead of `n &= (n>>1) & 1;`. (Also, I wonder if the person who posted the duplicate question maybe typed it in by hand, and it was actually `add` for them, too. :P) – Peter Cordes Mar 19 '18 at 20:17

0 Answers0