Search code examples
assemblyx86-64nasmfunction-pointers

What's the best way to associate a number with a method in x86_64 assembly


I have a server socket which receives a byte (operation code) from the client.

Depending on what the value of that byte is, I need to decode further data with a specific function.

For example:

  • if the value is 0x01, I need to call function1 to decode it.
  • for 0x02, execute call function2
  • and so forth...

I don't want to hardcode it all with compare and jump statements because there are more than 150 possible values and that would result to 400+ lines of code.

What would be the best option to implement this, resulting in the cleanest code? In C language, I would do this with a simple array: array[index] where array stores the function pointers and index is the operation code. This would result in O(1) speeds.

This is just a general question, but I'm working with x86_64 asm with NASM syntax if that helps.


Solution

  • Yes, a table of function pointers is the obvious way in asm as well.
    call [dispatch_table + rax*8] in non-PIE / non-PIC code where the label address itself can fit in a 32-bit sign-extended value so you can use a label with other registers, otherwise use a RIP-relative LEA to get the table base into another register. (Look at C compiler output for a function-pointer dispatch if you need an example.)

    Don't forget to validate input first, e.g. cmp eax, MAX_FUNC_NUMBER / ja error, after you do a zero-extending byte load into RAX with movzx eax, byte [mem] to zero-extend the index.

    Or just a jmp instead of call to make it like a switch within a function if that's more convenient than a call that pushes a return address.