我正在linux上使用NASM编写一个基本的汇编程序,该程序调用C库中的函数(printf)。不幸的是,我在这样做的时候遇到了一个分段错误。注释掉对printf的调用允许程序运行时没有错误。
; Build using these commands:
; nasm -f elf64 -g -F stabs <filename>.asm
; gcc <filename>.o -o <filename>
;
SECTION .bss ; Section containing uninitialized data
SECTION .data ; Section containing initialized data
text db "hello world",10 ;
SECTION .text ; Section containing code
global main
extern printf
;-------------
;MAIN PROGRAM BEGINS HERE
;-------------
main:
push rbp
mov rbp,rsp
push rbx
push rsi
push rdi ;preserve registers
****************
;code i wish to execute
push text ;pushing address of text on to the stack
;x86-64 uses registers for first 6 args, thus should have been:
;mov rdi,text (place address of text in rdi)
;mov rax,0 (place a terminating byte at end of rdi)
call printf ;calling printf from c-libraries
add rsp,8 ;reseting the stack to pre "push text"
**************
pop rdi ;preserve registers
pop rsi
pop rbx
mov rsp,rbp
pop rbp
ret发布于 2013-03-23 00:57:23
对于前6个参数,x86_64不使用堆栈。您需要将它们加载到适当的寄存器中。它们是:
rdi, rsi, rdx, rcx, r8, r9我用来记住前两个的诀窍是把函数想象成实现为rep movsb的memcpy,
发布于 2013-03-23 00:48:21
您正在调用一个varargs函数-- printf需要一个可变数量的参数,并且您必须在参数堆栈中考虑到这一点。查看此处:http://www.csee.umbc.edu/portal/help/nasm/sample.shtml#printf1
https://stackoverflow.com/questions/15575647
复制相似问题