2

I am learning assembly using Jeff Duntemann's book. I am trying to figure out how to write function that can be called in C.

Say for example that I want to implement the following function in assembly:

int my_function(int a, int b)
{
      return a+2*b
}

How do I write that? How do I access the arguments and how do I tell C that the return value is an integer?

EDIT: I am doing this on an old 32bit ubuntu.

fuz
  • 88,405
  • 25
  • 200
  • 352
tst
  • 1,117
  • 2
  • 10
  • 21
  • 2
    You need to learn about the [calling convention](https://en.wikipedia.org/wiki/Calling_convention) of your target architecture. – Eugene Sh. Jan 29 '21 at 17:39
  • 3
    https://www.agner.org/optimize/calling_conventions.pdf – Arthur Kalliokoski Jan 29 '21 at 17:41
  • The only way to tell the C compiler what external function returns and that type parameters it takes is by providing the function prototype. – 0___________ Jan 29 '21 at 17:43
  • I know that the registers ebx, esp, ebp, esi and edi cannot be changed and that the return value is stored in eax and possibly also in edx. I cannot figure out at which offset the arguments are stored – tst Jan 29 '21 at 17:46
  • 2
    The parameters are pushed in the stack from right to left in the 32-Bit System V ABI (Which 32-bit Linux uses). A call instruction (or equivalent) will push the return address on the stack. This all means that when a function first starts executing the first 32-bit integer class function parameter is at [ESP+4] , 2nd is at [ESP+8], 3rd at [ESP+12] etc. [ESP+0] is the return address – Michael Petch Jan 29 '21 at 18:09
  • We really need a canonical question for this sort of thing. Peter Cordes, might this one be it? – fuz Jan 29 '21 at 18:23
  • @fuz: Yeah, if there isn't one already. [Calling NASM function in C](//stackoverflow.com/q/36871564) has an attempt which only slightly violates the calling convention, so calling-convention details are only addressed in comments. https://stackoverflow.com/tags/x86/info already has links to guides and tutorials, but IDK how good any of them are. Most of the questions with titles like this are an attempt with some random mistake, so that's all the answers cover. e.g. [calling assembly functions from c](//stackoverflow.com/q/4676587) AT&T `push foo` instead of `push $foo`, or an off-by-1 – Peter Cordes Jan 29 '21 at 18:38
  • 1
    @fuz: [Function Calls and Assembly](https://stackoverflow.com/q/26129017) got closed as too broad. But yeah, this one could be a decent place to write a canonical Q&A / tutorial for the 32-bit stack-args calling convention (i386 System V). There are more Q&As about x86-64 because I think more people were first switching to and learning it during the early days of Stack Overflow. – Peter Cordes Jan 29 '21 at 18:44

0 Answers0