How do vararg functions find out the number of arguments in machine code?

后端 未结 4 2097
清酒与你
清酒与你 2020-12-03 11:51

How can variadic functions like printf find out the number of arguments they got?

The amount of arguments obviously isn\'t passed as a (hidden) parameter (s

4条回答
  •  再見小時候
    2020-12-03 12:02

    This is the reason why arguments are pushed on reverse order on the C calling convention, e.g:

    If you call:

    printf("%s %s", foo, bar);
    

    The stack ends up like:

      ...
    +-------------------+
    | bar               |
    +-------------------+
    | foo               |
    +-------------------+
    | "%s %s"           |
    +-------------------+
    | return address    |
    +-------------------+
    | old frame pointer | <- frame pointer
    +-------------------+
      ...
    

    Arguments are accesed indirectly using its offset from the frame pointer (the frame pointer can be omitted by smart compilers that know how to calculate things from the stack pointer). The first argument is always at a well-known address in this scheme, the function accesses as many arguments as its first arguments tell it to.

    Try the following:

    printf("%x %x %x %x %x %x\n");
    

    This will dump part of the stack.

提交回复
热议问题