Search code examples
mipsvariadic-functionsabi

varargs works in mips


According to mips abi, caller put the first few arguments in GPRs for performance, and don't push these arguments into stack frame. but when i use varargs api(stdarg.h) to define a function with variable argument list, such as void func(int type, ...);, the api works.

I find out stdarg.h apis only search the arguments in stack, If the compiler only push the first few argument into GPRs, why does stdarg.h work? did i miss something about the ABIs?


Solution

  • Conventions for variadic functions are described in the MIPS ELF ABI, page 3-46. Basically, when the called function is variadic (its declared argument list ends with a '...'), then the compiler adds some code which writes the first arguments (passed in registers) into the stack. The stack frame always includes some space for the first four arguments (precisely, for the four words which are passed in registers $4 to $7). Thus, the caller needs not be aware of whether the function was variadic or not (except possibly for floating point arguments; and, anyway, it is best if both caller and callee see and use the same prototype).

    If you compile a C variadic function and look at the produced assembly, you will see, near the beginning of the functions, lines like:

    sw      $5,52($sp)
    sw      $6,56($sp)
    sw      $7,60($sp)
    

    which correspond to that argument-to-stack process.