【问题标题】:Assembly section .code and .text behave differently汇编部分 .code 和 .text 行为不同
【发布时间】:2021-07-09 01:10:53
【问题描述】:

我是汇编新手,据我所知,.code.text 相同,但使用 .code 时下面的代码会崩溃。

segment .data
    msg db "hello, world", 0xa
    len equ $ - msg

section .text
    global _start

_start:
    mov edx, len
    mov ecx, msg

    mov ebx, 1
    mov eax, 4
    int 0x80

    mov ebx, 0
    mov eax, 1
    int 0x80

nasm -f elf64 -o hello.o hello.s 
ld -s -o hello hello.o
hello, world

sed -i s/.text/.code/ ./hello.s
nasm -f elf64 -o hello.o hello.s 
ld -s -o hello hello.o
./stack.sh: line 8:  4621 Segmentation fault      (core dumped) ./hello

实际上,我不认为这有什么不同。为什么会这样?

【问题讨论】:

  • 你学错了。在 nasm 中,.code 无法识别。请参阅manual。特别注意无法识别的部分是noexec
  • section .text 是 Windows MASM .code 的 NASM / Linux 等效,即您放置指令的位置。 section .code 实际上并没有在 NASM 中做你想做的事情。

标签: assembly x86-64 nasm elf


【解决方案1】:

在具有标准工具链 (GNU Binutils ld) 的 Linux 上,.text 是一个“特殊”部分名称,它得到特殊处理(默认为 exec 权限),但 .code 不是。 (其他特殊部分包括.data(可写)和.bss(可写nobits),所有的默认对齐> 1。)

section .text 是 Windows MASM .code 指令的 NASM ELF/Linux 等效项,但 意味着 Linux 工具可以识别 .code 指令或部分名称1.

section .codesection xyz123 没有区别;它只使用默认值 noexec nowrite 请参阅 the table in the NASM docs 底部的 other 条目。

使用readelf -a hello 查看节(链接)和段(程序加载器)属性,明显缺少X 任何地方。

脚注 1:事实上,我认为 Windows 可执行文件仍然使用实际的部分名称.text。至少 GNU objdump -d 仍然说代码在 .text 部分。 所以 MASM .code 指令是切换到 .text 部分的快捷方式。


有趣的事实:如果您将其构建为 32 位代码(您应该 because it's using only 32-bit int 0x80 system calls),这确实会“意外”正确运行,就像在从 16- 错误移植时使用 section .codethis case位 MASM 代码到 Linux NASM。
或者,如果您要在较旧的内核上运行 64 位代码。

原因是,在没有明确指定PT_GNU_STACK 注释的情况下,内核对 32 位可执行文件使用向后兼容假设,并使用影响每一页的READ_IMPLIES_EXECLinux default behavior of executable .data section changed between 5.4 and 5.9?。较旧的内核即使对 64 位可执行文件也这样做,较新的内核仅在这种情况下使堆栈本身可执行。

section .note.GNU-stack noalloc noexec nowrite progbits 添加到您的源代码中会使其出现段错误,即使构建为 32 位可执行文件也是如此。 (nasm -felf32/ld -melf_i386 -o foo foo.o)。见this answer

另请参阅Unexpected exec permission from mmap when assembly files included in the project 了解旧情况。

【讨论】:

  • 旁注: Peter,如果你还没有看过这个:stackoverflow.com/questions/67098983/… 你会爱上它的。对于内容/问题。而且,OP的问题与您的答案之一一样详细。而且,格式样式看起来非常像您的答案之一。
猜你喜欢
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 2020-08-05
相关资源
最近更新 更多