Reverse Engineering for Beginners

(avery) #1

CHAPTER 3. HELLO, WORLD! CHAPTER 3. HELLO, WORLD!


and esp, 0FFFFFFF0h
sub esp, 10h
mov eax, offset aHelloWorld ; "hello, world\n"
mov [esp+10h+var_10], eax
call _printf
mov eax, 0
leave
retn
main endp


The result is almost the same. The address of thehello, worldstring (stored in the data segment) is loaded in theEAX
register first and then it is saved onto the stack. In addition, the function prologue containsAND ESP, 0FFFFFFF0h—this
instruction aligns theESPregister value on a 16-byte boundary. This results in all values in the stack being aligned the
same way (The CPU performs better if the values it is dealing with are located in memory at addresses aligned on a 4-byte
or 16-byte boundary)^6.


SUB ESP, 10hallocates 16 bytes on the stack. Although, as we can see hereafter, only 4 are necessary here.


This is because the size of the allocated stack is also aligned on a 16-byte boundary.


The string address (or a pointer to the string) is then stored directly onto the stack without using thePUSHinstruction.
var_10—is a local variable and is also an argument forprintf(). Read about it below.


Then theprintf()function is called.


Unlike MSVC, when GCC is compiling without optimization turned on, it emitsMOV EAX, 0instead of a shorter opcode.


The last instruction,LEAVE—is the equivalent of theMOV ESP, EBPandPOP EBPinstruction pair —in other words, this
instruction sets thestack pointer(ESP) back and restores theEBPregister to its initial state. This is necessary since we
modified these register values (ESPandEBP) at the beginning of the function (by executingMOV EBP, ESP/AND ESP,
...).


3.1.3 GCC: AT&T syntax


Let’s see how this can be represented in assembly language AT&T syntax.This syntax is much more popular in the UNIX-world.


Listing 3.4: let’s compile in GCC 4.7.3

gcc -S 1_1.c


We get this:


Listing 3.5: GCC 4.7.3
.file "1_1.c"
.section .rodata
.LC0:
.string "hello, world\n"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
andl $-16, %esp
subl $16, %esp
movl $.LC0, (%esp)
call printf
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:


(^6) Wikipedia: Data structure alignment

Free download pdf