How to count the number of arguments passed to a function that accepts a variable number of arguments?

前端 未结 10 2148
旧时难觅i
旧时难觅i 2020-12-01 05:18

How to count the no of arguments passed to the function in following program:

#include
#include
void varfun(int i, ...);
int m         


        
10条回答
  •  被撕碎了的回忆
    2020-12-01 05:40

    Read a pointer to pointers from EBP.

    #define getReturnAddresses() void ** puEBP = NULL; __asm { mov puEBP, ebp };
    

    Usage

    getReturnAddresses();
    int argumentCount = *((unsigned char*)puEBP[1] + 2) / sizeof(void*) ;
    printf("CalledFrom: 0x%08X Argument Count: %i\n", puEBP[1], argumentCount);
    

    Not portable, but I have used it in a x86 C++ detour of __cdecl method that took a variable number of arguments to some success.

    You may need to adjust the -1 part depending on your stack/arguments.

    I did not come up with this method. Suspect I may have found it on UC forums at some point.

    I can't recommend to use this in propper code, but if you have a hacky detour on a x86 exe with __cdecl calling convention with 1 argument and then the rest are ... variable arguments it might work. (Win32)

    Example calling convention of detour method.

    void __cdecl hook_ofSomeKind_va_list(void* self, unsigned char first, ...)
    

    Proof: Screen shot showing console output next to x32dbg on target process with a detour applied

提交回复
热议问题