Reverse Engineering for Beginners

(avery) #1
CHAPTER 46. VARIADIC FUNCTIONS CHAPTER 46. VARIADIC FUNCTIONS
add r8d, 1
.L5:
; decide, which part we will work out now.
; is current argument number less or equal 6?
cmp esi, 47
jbe .L7 ; no, process saved arguments then
; work out arguments from stack
mov rcx, rdx
add rdx, 8
mov ecx, DWORD PTR [rcx]
cmp ecx, -1
jne .L8
.L4:
mov eax, edi
cdq
idiv r8d
ret

.LC1:
.string "%d\n"
main:
sub rsp, 8
mov edx, 7
mov esi, 2
mov edi, 1
mov r9d, -1
mov r8d, 15
mov ecx, 10
xor eax, eax
call arith_mean
mov esi, OFFSET FLAT:.LC1
mov edx, eax
mov edi, 1
xor eax, eax
add rsp, 8
jmp __printf_chk

By the way, a similar usage of theShadow Spaceis also considered here :64.8 on page 654.

46.2vprintf()function case.


Many programmers define their own logging functions which take a printf-like format string + a variable number of argu-
ments.
Another popular example is the die() function, which prints some message and exits. We need some way to pack input
arguments of unknown number and pass them to theprintf()function. But how? That’s why there are functions with
“v” in name. One of them isvprintf(): it takes a format-string and a pointer to a variable of typeva_list:


#include <stdlib.h>
#include <stdarg.h>

void die (const char * fmt, ...)
{
va_list va;
va_start (va, fmt);

vprintf (fmt, va);
exit(0);
};

By closer examination, we can see thatva_listis a pointer to an array. Let’s compile:

Listing 46.4: Optimizing MSVC 2010
_fmt$ = 8
_die PROC
; load 1st argument (format-string)
mov ecx, DWORD PTR _fmt$[esp-4]
Free download pdf