如何在汇编中使用 printf 打印命令行参数?

问题描述 投票:0回答:1

我正在尝试将第一个参数打印到我的 64 位 NASM 程序。我越来越

Segmentation fault (core dumped)

; L26.asm
section .data
    fmt db '%s', 10, 0

section .text
    global main
    extern printf

main:
    mov rdi, fmt
    ; +8 to skip the first argument, which is the program name
    mov rsi, [rsi + 8]
    xor rax, rax
    call printf

    ; Return from the main function
    ret

我正在创建一个可执行文件,如下所示:

nasm -f elf64 -o L26.o L26.asm && gcc -no-pie -o L26 L26.o

像这样跑步:

./L26 foo

我对汇编(和 C)非常陌生。在线答案和 ChatGPT 使得打印参数看起来应该如此简单(只是抵消rsi)。我将不胜感激任何指导。

    

c printf x86-64 nasm
1个回答
0
投票
movaps

)的函数可能会失败。

假设您的函数是使用 16 字节对齐的堆栈调用的,则调用应推送 8 字节的返回地址,因此您应该在堆栈上添加另一个 8 字节占位符以实现 16 字节对齐。

main: sub rsp, 8 ; add this (stack alignment) mov rdi, fmt ; +8 to skip the first argument, which is the program name mov rsi, [rsi + 8] xor rax, rax call printf ; Return from the main function add rsp, 8 ; add this (cleanup) ret

© www.soinside.com 2019 - 2024. All rights reserved.