Confusion stack

Bare metal programming in PureBasic, for experienced users
User_Russian
Addict
Addict
Posts: 1161
Joined: Wed Nov 12, 2008 5:01 pm
Location: Russia

Confusion stack

Post by User_Russian »

Why is the procedure returns 2, instead of 1234?

Code: Select all

EnableASM

ss:

Procedure Tst(x)
  PUSH dword 2
  MOV eax,l_ss
  PUSH eax
  PUSH x
  POP eax
  ADD esp,8
  ProcedureReturn
EndProcedure

Debug Tst(1234)
User avatar
Danilo
Addict
Addict
Posts: 3010
Joined: Sat Apr 26, 2003 8:26 am
Location: Planet Earth

Re: Confusion stack

Post by Danilo »

You manipulate the stack with your PUSHes, so PB gets confused. "PUSH x" becomes "PUSH dword [esp+PS0+0]".
That means, PB expects 'x' at a certain position on the stack. It does not recognize your stack manipulations, so
after the PUSHes it loads the wrong value for 'x'.

Code: Select all

EnableASM

ss:
DisableDebugger
    Procedure Tst(x)
      PUSH dword 2
      MOV eax,l_ss
      PUSH eax
      
      ;PUSH x ; becomes PUSH dword [esp+4]
      PUSH dword [esp+12]
      
      POP eax
      ADD esp,8
      ProcedureReturn
    EndProcedure
EnableDebugger

x = Tst(1234)
Debug x
User avatar
Tristano
Enthusiast
Enthusiast
Posts: 191
Joined: Thu Nov 26, 2015 6:52 pm
Location: Italy
Contact:

Re: Confusion stack

Post by Tristano »

This issue of PB variables and the stack pointer seems to popup a lot --- other posts dealing with this issue: Thanks for your added comments to @User_Russian's code, @Danilo! they make understanding the issue easier.

The other posts offer some examples of workarounds to the problem.

If I've undestood correctly, EBP can't be used to store ESP (as customary) because it's being used by PureBASIC internally (or the debugger)?

It would be nice to have some reference documentation explaining in detail (or in summary) this topic --- more generally, what are the limitations in using ASM inside PB code.
The PureBASIC Archives: FOSS Resources:
Post Reply