首页 > 解决方案 > C 函数在 64 位代码中产生分段错误

问题描述

我正在尝试在 Linux(Ubuntu 18.04 LTS)中编译以下 64 位代码:

global start

extern scanf, printf, exit

section .data
    read_name db '%255s', 0
    msg db 'Hello, %s', 0Ah, 0

section .text
start:
    sub rsp, 256
    mov rsi, rsp
    mov rdi, read_name
    call scanf
    mov rsi, rsp
    mov rdi, msg
    call printf
    add rsp, 256
    xor rdi, rdi
    call exit

这就是我编译代码的方式:

nasm -f elf64 hello64.asm
gcc -nostartfiles -m64 -o hello64 hello64.o -Wl,--entry="start"

代码编译没有错误,但是当我运行它时,我得到了这个分段错误:

./hello64: Symbol `scanf' causes overflow in R_X86_64_PC32 relocation
./hello64: Symbol `printf' causes overflow in R_X86_64_PC32 relocation
./hello64: Symbol `exit' causes overflow in R_X86_64_PC32 relocation
Segmentation fault (core dumped)

不知道发生了什么。由于这是 64 位代码,我假设 C 函数使用System V AMD64 ABI,所以我相应地调用它们(第一个参数在RDI, RSI, RDX, RCX, R8, 中R9)。任何人都可以帮助我了解问题所在吗?

标签: assemblynasm

解决方案


推荐阅读