x86 汇编器,add 和 sub 的奇怪行为

发布于 2024-12-20 06:32:02 字数 404 浏览 2 评论 0原文

我有这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

纸伞微斜 2024-12-27 06:32:02

您不应该在 sub 之前对堆栈指针进行 add 操作,就像您不应该对 pop 操作一样在推送之前。

当您添加到堆栈时,您基本上是在说小于堆栈指针指向的地址的任何内容都是可以使用的空闲内存。当您从堆栈中sub时,实际上就是在分配内存。堆栈指针从高内存开始,并随着事物被推入堆栈而移向低内存。

在上面的评论中,汉斯对中断有一定的看法。如果任何东西add之后取得控制权并且使用堆栈,它将覆盖您的返回地址。那是因为您基本上通过添加到堆栈指针来“释放”它。

You shouldn't ever have an add to the stack pointer before a sub, in the same way that you shouldn't ever have a pop before a push.

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 you sub 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.

清风疏影 2024-12-27 06:32:02

有可能在 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).

蘑菇王子 2024-12-27 06:32:02

我猜这是一个线程/中断问题 - 更改堆栈,线程发生,返回并繁荣。为您编写这样的堆栈指针提供帮助:)

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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文