x86汇编中向mmap分配内存写入数据触发段错误
x86 Linux下mmap系统调用段错误问题排查
在x86 Linux环境中使用NASM汇编器和ld链接器自学汇编时,尝试实现mmap系统调用触发段错误,问题定位在向分配内存写入数据的步骤。以下是出错代码、修正后的可运行代码及关键错误点分析:
出错代码
section .text global _start _start: mov rax, 9 ;mmap syscall mov rsi, 2 ;length in bytes mov rdx, 3 ;read and write permissions mov r8, -1 ;file descriptor for anonymous mapping mov r9, 0 ;no offset mov r10, 0x22 ;private and anonymous memory syscall mov ax, "hi" ;define string mov [rdi], ax ;write string to memory (fails here) mov rsi, rdi mov rax, 1 mov rdi, 1 mov rdx, 2 syscall ;print string mov rax, 60 mov rdi, 0 syscall ;end program
修正后的可运行代码
section .text global _start _start: mov rax, 9 ;mmap syscall mov rdi, 0 ;let kernel choose mapping address mov rsi, 2 ;length in bytes mov rdx, 3 ;read and write permissions mov r8, -1 ;file descriptor for anonymous mapping mov r9, 0 ;no offset mov r10, 0x22 ;private and anonymous memory syscall mov bx, "hi" ;define string mov [rax], bx ;write string to memory returned by mmap mov rsi, rax mov rax, 1 mov rdi, 1 mov rdx, 2 syscall ;print string mov rax, 60 mov rdi, 0 syscall ;end program
关键错误点分析
未初始化mmap的第一个参数(rdi寄存器)
x86_64 Linux系统调用中,mmap的第一个参数是期望的映射内存地址,传入0表示让内核自动分配合适地址。出错代码未设置rdi,其值为随机垃圾值,导致mmap无法正确分配有效内存。错误使用寄存器访问分配的内存
mmap调用成功后,分配的内存地址会返回在rax寄存器中。出错代码错误地向rdi指向的地址写入数据,而rdi是未正确初始化的传入参数,并非mmap返回的有效内存地址。修正后改用rax作为写入目标地址,符合系统调用的返回规则。
内容的提问来源于stack exchange,提问作者Neurowa
相关产品推荐
相关产品推荐

