tags:

views:

465

answers:

3

i need to implement a stack in x86 assembly so i wrote this:

section .bss

my_stack: 
       resb 5

but the data inside this address disappear after i continuing with my program

there is a better way i can implement the stack?????

+6  A: 

I'm not sure what you want, but as the x86 assembly language provides it's own stack, why not use it?

push reg ; push register reg to the stack
pop reg  ; pop register reg from the stack
         ; actual stack pointer = sp

By the way, your code only reserves 5 bytes of space for variables, to see why your data disappears, the rest of the program would be interesting. Using only 5 bytes for a stack is strange, too.

schnaader
A: 

Here is a simple example of how you can create your own stack in x86 asm:

format pe console
entry start

include 'win32ax.inc' ;used for proc macros only

MAXSIZE = 256

section '.text' code readable executable

    start:
            ;test code
            push 12345
            call myPush
            push 22222
            call myPush
            call myPop
            call myPop
            ret

    proc myPush x
         cmp [_top], MAXSIZE        ;did we exceed stack size
         ja stack_full
         inc [_top]                 ;update the last element position
         mov eax, [_top]
         mov esi, _stack
         mov edx, [x]
         mov dword [esi+eax*4], edx ;write the value to stack
    stack_full:
         ;do something when stack is full
         ret
    endp

    proc myPop
         cmp [_top], 0              ;did we write anything previously
         jbe stack_empty
         mov eax, [_top]
         mov [_stack+eax*4], 0       ;clear stack value at last position
         dec [_top]                 ;decrease last element position
    stack_empty:
         ;do something when stack is empty
         ret
    endp

section '.data' data readable writeable
    _stack dd MAXSIZE dup ?
    _top dd ?

I've used FASM syntax here but that shouldn't be a problem. Also i would suggest to allocate the stack in memory, e.g. using VirtualAlloc.

msuvajac
A: 

To use your stack you have to set ss:sp properly if you are in 16-bit, otherwise (ss):esp. The preferred way to set ss:sp is the LSS instruction which loads ss and sp in the same instruction.

section .bss

my_stack: 
       resb 5

section .text

setup_stack:
       lss sp, [my_stack]
       ; rest of your code
Jonas Gulle
actually, LSS receives a far pointer, so it has 2 bytes for SS's selector and 4 or 8 bytes for the offset to be put in ESP.
Nathan Fellman