News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

General Pushing/Popping

Started by RedXVII, March 03, 2006, 10:34:33 PM

Previous topic - Next topic

RedXVII

I just wanted to know if doing this is considered ok.


invoke fucntion, var1
push eax
invoke blahfunction, var1, var2
invoke anotherblahfunctions, var1
pop eax
invoke myfunction, eax


Or will a problem occur during the calling of these functions that will either cause it to crash, or screw up my eax value? I vagueley understand Local variables, and pushing/popping, but not enough to know if this is bad or not  :red

So, is it bad, or ok?

hutch--

Its not that simple, you push values on the stack for a number of reasons. What you have to keep in mind is that the stack must remain balanced otherwise you can get the wrong data returned or execution returned to the wrong location which will almost exclusively result in a crash.
Download site for MASM32      New MASM Forum
https://masm32.com          https://masm32.com/board/index.php

Mark Jones

The stack is a FIRST ON - LAST OFF buffer. It's called the "stack" because you can think of it as a big stack of something like coins. Each coin is a dword and if you push three on there, you need to take three off to get your first coin back. That said, your code might be ok IF the same number of coins has been placed on the stack as has been removed. The stack is just a buffer, so it doesn't matter where the source of the coin comes from - eax, ecx, edx etc. That makes this possible:


    push eax   ; save eax to stack
    pop edx    ; edx now == eax


The stack will also take 4 bytes of memory at a time.

    push dword ptr szSource   ; save four bytes of szSource offset to stack
    pop dword ptr szDest      ; put 4 bytes at dest


Where you get into trouble is when you accidentally handle the wrong coins, or imbalance the stack. This is bad because the stack cannot recover:

    push eax
    ;push ecx
    call myProc  ; this proc takes two arguments but only one is given, so eventually crashes


This is even worse:

    Invoke MessageBox,0,addr myString,0,MB_OK
    pop eax   ; stack now lost a value
    ret       ; CRRRRRRRRRASH! :)


But this is perfectly fine:

    mov edx,69
    push edx
    Invoke MessageBox,0,addr myString,0,MB_OK
    pop eax   ; eax now == 69
    ret       ; exit normally


Enjoy.
"To deny our impulses... foolish; to revel in them, chaos." MCJ 2003.08

zooba

Assuming that all your procedures balance the stack correctly (if they're PROCs and you've got a '.model flat, stdcall' somewhere you should be fine - look up calling conventions for more info :wink) there should be no problem.

Cheers,

Zooba :U