Assembly Language for Beginners

(Jeff_L) #1

1.5. HELLO, WORLD!


The result is almost the same. The address of thehello, worldstring (stored in the data segment) is
loaded in theEAXregister first, and then saved onto the stack.
In addition, the function prologue hasAND 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)^21.


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 thePUSH
instruction.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.


Thelastinstruction,LEAVE—istheequivalentoftheMOV ESP, EBPandPOP EBPinstructionpair—inother
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, ...).


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 1.17: let’s compile in GCC 4.7.3

gcc -S 1_1.c


We get this:


Listing 1.18: 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:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3"
.section .note.GNU-stack,"",@progbits


(^21) Wikipedia: Data structure alignment

Free download pdf