在 .DATA 部分中将 reg 存储到 var 时出现段错误 [英] Segfault when storing reg to var in section .DATA
问题描述
所以我正在尝试使用 x86 编写一些代码,但我似乎无法让它将寄存器的内容移动到内存中的某个位置.
So I am trying to write some code using x86 and I can't seem to get it to move contents of a register to a spot in memory.
代码就是这样
global main
SECTION .DATA
var_i: DD 0
SECTION .TEXT
main:
push DWORD 4
pop EAX
mov [var_i], EAX
mov EAX, 0
ret
我在代码上使用 nasm 和 gcc.我遇到的问题是,每当我尝试移动到内存中的位置时,它都会出现段错误
I am using nasm and gcc on the code. The problem I am having is that whenever I try to move to the spot in memory it segfaults
推荐答案
你使用什么样的系统/对象格式?我猜你在 Linux 或 Unix 上使用 ELF,因为这可以解释你的问题:
What kind of system/object format are you using? I'm guessing you're using ELF on Linux or Unix, as that would explain your problem:
ELF 中的部分名称区分大小写,大多数基于 ELF 的操作系统的特殊部分 .text
和 .data
都可以理解,但您的部分 .TEXT
和 .DATA
没有意义.结果,他们只是在其他部分之后卡在可执行文件中并获得相同的访问权限.如果您只是链接上面的代码,那将在 .fini
部分之后,因此它将是可执行和只读的.因此,当您尝试写入变量时,会出现段错误.
Section names in ELF are case sensitive, and most ELF-based OS's the special sections .text
and .data
are understood, but your sections .TEXT
and .DATA
have no meaning. As a result, they just get stuck into the executable after the other sections and get the same access permissions. If you're just linking the above code, that will be after the .fini
section, so it will executable and read-only. So when you try to write to the variable, you get a segfault.
更改您的代码以使用 .data
和 .text
作为部分名称,它应该可以工作.
Change your code to use .data
and .text
as section names and it should work.
这篇关于在 .DATA 部分中将 reg 存储到 var 时出现段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!