0

I'm trying to print the first argument to my 64-bit NASM program. I'm getting 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

I'm creating an executable like so:

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

And running like so:

./L26 foo

I'm very new to assembly (and C). Answers online and ChatGPT are making it seem like it should be this simple to print arguments (just offsetting rsi). I'd appreciate any guidance.

1
  • 1
    FYI, ChatGPT is very bad at assembly (e.g. Does this ChatGPT "swap" snippet do anything? - no, it loads two values and stores them back to the same places, not the opposite. See comments there). It's also not good at conceptual questions about CPU architecture (like why CPUs are designed the way they are), at least not judging from the answers people have copy/pasted onto SO, but that's probably a sample of the worst results from people who didn't care about the answer themselves to even try to refine their prompt. Commented Feb 22, 2024 at 19:33

1 Answer 1

2

You should align the stack to 16-byte boundary before calling 64-bit functions. Otherwise, some functions that assumes this 16-byte boundary and using some SSE instructions (like movaps) may fail.

Assuming your function is called with 16-byte aligned stack, a 8-byte return address should be pushed by the call, so you should add another 8-byte placeholder on the stack to achieve 16-byte alignment.

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.