尝试将地址复制到结构中时出现分段错误?

时间:2017-09-28 20:07:23

标签: linux assembly nasm x86-64

我的NASM程序因分段错误而崩溃。

在文件的开头,定义了以下结构:

struc mystruct
    .myhandler resq 1
endstruc

.bss部分创建结构的实例:

section .bss

    inst resb mystruct

程序所做的第一件事是尝试将标签的地址存储在struct的唯一字段中:

section .text
global _start

_start:

    lea rax, [handler]
    mov [inst + mystruct.myhandler], rax

handler:

    ; ...

根据GDB,leamov说明如下:

(gdb) disassemble _start
Dump of assembler code for function _start:
=> 0x0000000000400080 <+0>: lea    rax,ds:0x400090
   0x0000000000400088 <+8>: mov    QWORD PTR ds:0x601000,rax
...

但是,运行应用程序会导致分段错误:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400088 in _start ()

为什么会这样?

修改:其他信息:

$ nm -S app.o
0000000000000010 t handler
0000000000000000 b inst
0000000000000000 a mystruct
0000000000000000 a mystruct.myhandler
0000000000000008 a mystruct_size
0000000000000000 T _start

$ size -A app.o
app.o  :
section   size   addr
.text     16      0
.bss       0      0
Total     16

1 个答案:

答案 0 :(得分:1)

Peter Cordes在评论中指出:

  

看起来inst resb mystruct在BSS中保留了0个字节,所以你的进程根本就没有BSS。但它仍然以某种方式组装和链接。我不知道NASM中sizeof()的正确语法是什么;我从不使用它的结构语法。

事实证明,我需要做的就是改变:

act resb mystruct

...到...

act resb mystruct_size

此符号由汇编程序自动定义,并以字节为单位设置为结构的大小。

程序不再在该部分代码崩溃。