23.03.2013 Views

Quick introduction to reverse engineering for beginners

Quick introduction to reverse engineering for beginners

Quick introduction to reverse engineering for beginners

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1.15.4 Fields packing in structure<br />

One important thing is fields packing in structures 54 .<br />

Let’s take a simple example:<br />

#include <br />

struct s<br />

{<br />

char a;<br />

int b;<br />

char c;<br />

int d;<br />

};<br />

void f(struct s s)<br />

{<br />

printf ("a=%d; b=%d; c=%d; d=%d\n", s.a, s.b, s.c, s.d);<br />

};<br />

As we see, we have two char fields (each is exactly one byte) and two more — int (each - 4 bytes).<br />

That’s all compiling in<strong>to</strong>:<br />

_s$ = 8 ; size = 16<br />

?f@@YAXUs@@@Z PROC ; f<br />

push ebp<br />

mov ebp, esp<br />

mov eax, DWORD PTR _s$[ebp+12]<br />

push eax<br />

movsx ecx, BYTE PTR _s$[ebp+8]<br />

push ecx<br />

mov edx, DWORD PTR _s$[ebp+4]<br />

push edx<br />

movsx eax, BYTE PTR _s$[ebp]<br />

push eax<br />

push OFFSET $SG3842<br />

call _printf<br />

add esp, 20 ; 00000014H<br />

pop ebp<br />

ret 0<br />

?f@@YAXUs@@@Z ENDP ; f<br />

_TEXT ENDS<br />

As we can see, each field’s address is aligned by 4-bytes border. That’s why each char using 4 bytes here,<br />

like int. Why? Thus it’s easier <strong>for</strong> CPU <strong>to</strong> access memory at aligned addresses and <strong>to</strong> cache data from it.<br />

However, it’s not very economical in size sense.<br />

Let’s try <strong>to</strong> compile it with option (/Zp1) (/Zp[n] pack structs on n-byte boundary).<br />

_TEXT SEGMENT<br />

_s$ = 8 ; size = 10<br />

?f@@YAXUs@@@Z PROC ; f<br />

push ebp<br />

mov ebp, esp<br />

mov eax, DWORD PTR _s$[ebp+6]<br />

push eax<br />

54 See also: Wikipedia: Data structure alignment<br />

69

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!