Cág*_*Cág 6 linux assembly x86-64 gnu-assembler system-calls
我在 64 位 Linux 环境中运行我的代码,其中 Linux 内核是使用IA32_EMULATION和X86_X32 disabled构建的。
在《从头开始编程》一书中,第一个程序除了产生段错误之外什么都不做:
.section .data
.section .text
.globl _start
_start:
movl $1, %eax
movl $0, %ebx
int $0x80
Run Code Online (Sandbox Code Playgroud)
我将代码转换为使用 x86-64 指令,但它也会出现段错误:
.section .data
.section .text
.globl _start
_start:
movq $1, %rax
movq $0, %rbx
int $0x80
Run Code Online (Sandbox Code Playgroud)
我像这样组装了这两个程序:
as exit.s -o exit.o
ld exit.o -o exit
Run Code Online (Sandbox Code Playgroud)
运行./exit
给出了Segmentation fault
两个。我究竟做错了什么?
PS 我看过很多用gcc组装代码的教程,但是我想使用gas。
结合评论和答案,这是代码的最终版本:
.section .data
.section .text
.globl _start
_start:
movq $60, %rax
xor %rbx, %rbx
syscall
Run Code Online (Sandbox Code Playgroud)
原因是x86_64 的 Linux 系统调用表与 x86 的表不同。
在 x86 中,SYS_EXIT 是1
. 在 x64 中,SYS_EXIT 是60
SYS_WRITE1
的值,如果调用该值,则需要const char *buf
%RSI 形式的值。如果该缓冲区指针无效,则可能会出现段错误。
%rax System call %rdi %rsi %rdx %r10 %r8 %r9
1 sys_write unsigned int fd const char *buf size_t
60 sys_exit int error_code
Run Code Online (Sandbox Code Playgroud)