NASM and a clarification on POP

813 Views Asked by At

I've been learning me some Assembly lately and am writing really simple programs just to see how things work and to remember things better.

Anyway, I decided to simply write a program that prints your input. I'm using SASM and its io macros.

%include "io.inc"

section .text
global CMAIN
CMAIN:
segment .data
    message db "Input a number", 0 
segment .bss
    input resb 4
    input2 resb 4
segment .text

    PRINT_STRING message ;prints message
    GET_UDEC 4, eax ;gets 4bytes of user input and puts into eax
    mov [input], eax ;moves eax into input's actual data
    PRINT_UDEC 4, input ;prints input
    NEWLINE
    PRINT_UDEC 4, esp ;Prints 2686764
    NEWLINE
    push input ;pushes input onto the stack
    PRINT_UDEC 4, esp ;Prints 2686760, we pushed a dw
    NEWLINE

    pop ebx ;pops (input) and puts it into ebx?
    mov [input2], ebx ;moves ebx into input2
    PRINT_UDEC 4, input2 ;prints input2. //Prints some crazy number.

    GET_UDEC 4, eax ;Stops program from exiting.

xor eax, eax
ret

I must be missing something elementary here, but I can't find it to save my life. Anyone know?

1

There are 1 best solutions below

5
On

The Problem With Your Code

Before I answer your question about pop I would like to say that you should do push dword [input] instead of push input so that you push the value of input instead of a pointer to it.

pop and push Explanation

In assembly there are four main ways to interact with the stack. push pushes the first argument to the top of the stack. pop takes the top element from the stack and puts it into the first argument. pusha pushes all the registers to the stack. popa is like pusha but pops all the registers instead.

You can also change the location of the stack by changing the esp register. And example of this is:

mov esp, 0x100000
mov ebp, esp

This will set the stack to be at memory location 0x100000. Please note that this is rarely done by programs and only by the OS or system.