2

I have 64-bit MacOS assembly code which performs binary search on an array. Binary search in standard C library is:

void* bsearch (const void* key, const void* base,
               size_t num, size_t size,
               int (*compar)(const void*,const void*));

And my assembly looks like

mov    %edi,0x2(%rsp)
mov    $0x2010,%r8d
mov    $0x4,%ecx
lea    0x2(%rsp),%rdi
callq  <bsearch@plt>

I am wondering if there is any definitive order of parameters that the bsearch takes, i.e. is there any way of knowing what rdi, ecx, r8d correspond to here? Is it key, base, compar?

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
dipankar
  • 79
  • 4
  • It depends on the calling convention for the platform you are on. For example the Calling Convention for 64-bit Windows is different than 64-bit Linux (or OSX) code. Looking at the code you provided I can infer you are not targeting Windows and you appear to be using a system that uses the AMD64 System V ABI. You can find a summary of the calling convention and the registers used [here](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI) .A complete copy can be found [here](https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf) – Michael Petch Nov 24 '18 at 04:57
  • Thanks. I am using OSX. – dipankar Nov 24 '18 at 04:59
  • Yep, OSX uses the AMD64 System V ABI so the links I gave should apply. – Michael Petch Nov 24 '18 at 04:59
  • the linked duplicate covers the normal function calling convention as well as the system-call calling convention. – Peter Cordes Nov 24 '18 at 05:13

1 Answers1

2

There are two possible calling conventions, depending on your OS (see here for more details). On Microsoft, the order is RCX, RDX, R8, R9. On Unix, the order is RDI, RSI, RDX, RCX, R8, R9. Note that the "r" or "e" at the beginning just indicates whether you are using all 64 bits of the register (r) or only the lower 32 bits (e). So in your case, I would guess that you are using Unix and the correspondence is rdi=key, ecx=size, r8d=compar.

Flight Odyssey
  • 2,267
  • 18
  • 25