我需要在x86程序集中实现一个堆栈,所以我写了这个:
section .bss
my_stack:
resb 5
但是在继续我的程序
之后,该地址内的数据消失了有一种更好的方法可以实现堆栈?????
答案 0 :(得分:6)
我不确定你想要什么,但是由于x86汇编语言提供了自己的堆栈,为什么不使用它呢?
push reg ; push register reg to the stack
pop reg ; pop register reg from the stack
; actual stack pointer = sp
顺便说一下,你的代码只为变量保留了5个字节的空间,看看你的数据消失的原因,程序的其余部分会很有趣。仅使用5个字节的堆栈也很奇怪。
答案 1 :(得分:1)
以下是如何在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 ?
我在这里使用过FASM语法,但这应该不是问题。我还建议在内存中分配堆栈,例如使用VirtualAlloc。
答案 2 :(得分:1)
要使用你的堆栈,你必须正确设置ss:sp,如果你是16位,否则(ss):esp。 设置ss:sp的首选方法是LSS指令,它在同一条指令中加载ss和sp。
section .bss
my_stack:
resb 5
section .text
setup_stack:
lss sp, [my_stack]
; rest of your code