Gnu 汇编程序 .data 部分值在系统调用后损坏

Gnu assembler .data section value corrupted after syscall

我有以下代码

.data
result: .byte 1
.lcomm input 1
.lcomm cha 2

.text
(some other code, syscalls)

起初一切都很好。调用系统调用(例如读取)时,标签 'result' 处的值更改为一些随机垃圾值。

有人知道怎么回事吗?

P.S。环境 Debian x86_64 最新 运行 在 vi​​rtualbox 中 使用 as -g ld emacs make latest

-----编辑-----

(continue)
.global _start
_start:
mov ,%rax
mov [=11=],%rbx
mov $input,%rcx
mov ,%rdx
int [=11=]x80
(sys_exit)

'input'的值被正确更改了,但是'result'的值在

之后也变成了随机值
int [=12=]x80 

您正在查看从 result 开始的 4 个字节,其中包括 input 作为第二个或第三个字节。 (这就是为什么值会增加 256 或 65536 的倍数,如果 print (char)result 则低字节 = 1)。如果您使用 p /x 打印为十六进制,这会更明显。

当没有调试信息时,GDB 对 print result 的默认行为是假设 int。现在,由于像这样的用户错误,Arch Linux 上的 gdb 8.1,print result'result' has unknown type; cast it to its declared type

GAS + ld 出乎意料地(无论如何对我来说)将 BSS 和数据段合并到一页中,因此即使您将变量放在不同的部分中,您的变量也是相邻的,您希望它们得到不同的对待. (BSS 由匿名归零页面支持,数据由文件的私有读写映射支持)。

使用 gcc -nostdlib -no-pie test.S 构建后,我得到:

(gdb) p &result
 = (<data variable, no debug info> *) 0x600126
(gdb) p &input
 = (<data variable, no debug info> *) 0x600128 <input>

与使用 .section .bss 和手动保留 space 不同,.lcomm 可以随意填充。大概是为了对齐,也许在这里 BSS 从 8 字节边界开始。当我用 clang 构建时,我在 result 之后的字节中得到了 input (在不同的地址)。


我通过添加一个带有 .lcomm arr, 888332 的大型数组进行了调查。一旦我意识到它没有在可执行文件中存储 BSS 的文字零,我就使用 readelf -a a.out 进一步检查:

(相关:What's the difference of section and segment in ELF file format

...
Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x0000000000000126 0x0000000000000126  R E    0x200000
  LOAD           0x0000000000000126 0x0000000000600126 0x0000000000600126
                 0x0000000000000001 0x00000000000d8e1a  RW     0x200000
  NOTE           0x00000000000000e8 0x00000000004000e8 0x00000000004000e8
                 0x0000000000000024 0x0000000000000024  R      0x4

 Section to Segment mapping:
  Segment Sections...
   00     .note.gnu.build-id .text 
   01     .data .bss 
   02     .note.gnu.build-id 

...

所以是的,.data.bss 部分在同一个 ELF 段中结束。

我认为这里发生的事情是 ELF 元数据表示要映射从 virt addr 0x600126 开始的 0xd8e1a 字节(归零页面)的 MemSize。并且 LOAD 从文件中的偏移量 0x126 到虚拟地址 0x600126.

的 1 个字节

因此,ELF 程序加载器必须将文件中的数据复制到支持 BSS 和 .data 部分的其他清零页面,而不仅仅是一个 mmap。

它可能是一个更大的 .data 部分,链接器需要它来决定使用单独的段。