I am new to assembly language and trying to understand a simple program which will add two nunbers and display the result.
section .data
message1 db \"value=%d%
The printf
librarymay be implemented in many ways, so it would be dangerous to assert that ALL
printf
routines will execute in the manner that THIS
printf
acts.
The sequence
push eax // push 100 on to stack push ebx // push 45 on to stack push message1 // push THE ADDRESS OF the message "value=%d" onto stack call printf // push the RETURN ADDRESS to the stack
enters the printf
routine with, reading the stack from the BOTTOM
So, PRINTF
would most likely
POP
the return address and save it POP
the pointer to the message MOV
e the STACK POINTER
to a register or save itThen it can go about its task - using the pointer to the message, write each character out until it encounters a keystring like %d
which says 'print something as a decimal. So it POP
s the next value from the stack (45, as pushed in ebx
), formats that as a decimal and prints it, then continues with the printf
string.
Another %d
- the 100 pushed from eax
, then continue - until you find the 0
byte indicating end-of-string.
All printf
needs to do now to return is to restore the stack pointer
from wherever it was stored, and return to the return address - wherever that's been stored.
And when it returns, the stack is restored to exactly what it was when the printf
was called - and at that time, EBX
and EAX
had been PUSH
ed. Each is 4 bytes, so the stack pointer
needs to be adjusted by 8 bytes to remove the data stored by these two PUSH
instructions.
So - why do it that way - why not simply allw PRINTF
to adjust the stack - which it could, since it knows it's removed 8 bytes for display (2*%d)?
Well, in essence, it could - but suppose the message only contained one %d - or 3 - or something that consumed something OTHER than 8 bytes? On return, the stack-pointer
would contain an unexpected value - which depends on how PRINTF
interprets a string. Very difficult to pull assembler tricks like overwriting parts of messages withou being extraordinarily careful. As it's written, the printf
function always acts in a predictable manner, returning having popped off the message address, regardless of any other consideration. Up to the programmer to properly deal with the stack contents.