Forward an invocation of a variadic function in C

前端 未结 12 2432
悲哀的现实
悲哀的现实 2020-11-22 06:41

In C, is it possible to forward the invocation of a variadic function? As in,

int my_printf(char *fmt, ...) {
    fprintf(stderr, \"Calling printf with fmt %         


        
12条回答
  •  名媛妹妹
    2020-11-22 07:26

    The best way to do this is

    static BOOL(__cdecl *OriginalVarArgsFunction)(BYTE variable1, char* format, ...)(0x12345678); //TODO: change address lolz
    
    BOOL __cdecl HookedVarArgsFunction(BYTE variable1, char* format, ...)
    {
        BOOL res;
    
        va_list vl;
        va_start(vl, format);
    
        // Get variable arguments count from disasm. -2 because of existing 'format', 'variable1'
        uint32_t argCount = *((uint8_t*)_ReturnAddress() + 2) / sizeof(void*) - 2;
        printf("arg count = %d\n", argCount);
    
        // ((int( __cdecl* )(const char*, ...))&oldCode)(fmt, ...);
        __asm
        {
            mov eax, argCount
            test eax, eax
            je noLoop
            mov edx, vl
            loop1 :
            push dword ptr[edx + eax * 4 - 4]
            sub eax, 1
            jnz loop1
            noLoop :
            push format
            push variable1
            //lea eax, [oldCode] // oldCode - original function pointer
            mov eax, OriginalVarArgsFunction
            call eax
            mov res, eax
            mov eax, argCount
            lea eax, [eax * 4 + 8] //+8 because 2 parameters (format and variable1)
            add esp, eax
        }
        return res;
    }
    

提交回复
热议问题