简体   繁体   中英

Printf Assembly Language Stack pointer nasm intel

Setup: Nasm intel 64bit ubuntu I am getting a segmentation error when I include the printf line. Without including it compiles and runs fine. I am just trying to print the 1 in this code.

Does calling printf print whatever is at the stack pointer? Would DD2 be at the stack pointer when printf is called here?

I just popped the last two items to have the stack return to its initial position.

All help appreciated, have a great evening!

SECTION .data
DD:
    db 1
DD2:
    db "%d"
extern printf

SECTION .text
global main

main:
    push DD
    push DD2
    call printf
    pop rax ; 
    pop rbx ;

    ret

The calling conventions for 64 bit are VERY different then what you are used to with 32bit.

http://en.wikipedia.org/wiki/X86_calling_conventions

Scroll down to x86-64 it will tell you that the first 6 parameters are passed in registers: 1st param in RDI, 2nd param in RSI, 3rd param in RDX, 4th RCX, 5th R8, 6th R9, any more and they are passed on the stack; floating point params are passed in XMM0–7

So, your printf call should be:

mov     rsi, DD
mov     rdi, DD2
mov     rax, 0
call    printf

since we don't pass anything in the xmm regs, we set rax to 0 (without it it may crash)

I should also note that the stack must be 16 byte aligned, which it is when your program starts and you link to the c library. But, since the call pushes an 8 byte value on the stack (the return address) the stack is not aligned. At the start of your functions (in your case main), just do a sub rsp, 8 and that will take care of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM