x86 汇编器,add 和 sub 的奇怪行为
我有这段代码:
openFileToRead:
sub sp,4
add sp,4
ret
然后我的代码中有这样的代码
call openFileToRead
现在我们遇到了问题。当 add 之前有一个 sub 时,这一切都有效,但是当我像这样用 add 更改 sub 时:
openFileToRead:
add sp,4
sub sp,4
ret
一切都崩溃了。在ret中,他跳到了一些奇怪的位置和记忆。这两个标签之间不应该有任何区别,但确实存在。这是为什么?
我在带有 Intel CPU 的 Windows XP 上使用 Masm 进行编译,我使用 16 位链接器。
I have this piece of code:
openFileToRead:
sub sp,4
add sp,4
ret
then I have in my code
call openFileToRead
And now we have a problem. It all works when there is a sub before add, but when I change the sub with add like here:
openFileToRead:
add sp,4
sub sp,4
ret
all hell breaks loose. In ret he jumps to some strange location and memory. There shouldn't be any difference between those two labels, but there is. Why is that?
I compile with masm on windows xp with Intel CPU, I use 16 bit linker.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该在
sub
之前对堆栈指针进行add
操作,就像您不应该对pop
操作一样在推送
之前。当您
添加
到堆栈时,您基本上是在说小于堆栈指针指向的地址的任何内容都是可以使用的空闲内存。当您从堆栈中sub
时,实际上就是在分配内存。堆栈指针从高内存开始,并随着事物被推入堆栈而移向低内存。在上面的评论中,汉斯对中断有一定的看法。如果任何东西在
add
之后取得控制权并且使用堆栈,它将覆盖您的返回地址。那是因为您基本上通过添加到堆栈指针来“释放”它。You shouldn't ever have an
add
to the stack pointer before asub
, in the same way that you shouldn't ever have apop
before apush
.When you
add
to the stack, you're basically saying that anything at an address less than what's pointed to by the stack pointer is free memory to be used. When yousub
from the stack is when you're essentially allocating memory. The stack pointer starts at high memory and moves towards low memory as things are pushed onto the stack.In the comment above, Hans has a point with the interrupts. If anything takes control after the
add
and uses the stack, it'll overwrite your return address. That's because you've basically "deallocated" it by adding to the stack pointer.有可能在 add sp,4 之后立即处理一个中断(例如时钟滴答),从而破坏您的返回值,而此时该返回值似乎位于堆栈的未使用区域(堆栈指针下方)。
It's possible that an interrupt - say a clock tick - is serviced right after your add sp,4, clobbering your return value, which at that precise moment appears to be in an unused area of the stack (below the stack pointer).
我猜这是一个线程/中断问题 - 更改堆栈,线程发生,返回并繁荣。为您编写这样的堆栈指针提供帮助:)
I'm going to guess it's a threading/interrupt issue - change stack, thread happens, come back and boom. Serves you write for playing with your stack pointer like that :)