我在linux上使用NASM編寫基本彙編程序,該程序從C庫(printf)調用函數。不幸的是,我在這樣做時發生了分段錯誤。註釋掉對printf的調用可以使程序無誤地運行。從組件調用C函數時發生Seg故障
; 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-22 16:46:31
在我正在閱讀的書中(涵蓋32位程序集,而不是64位),它只是說推動字符串地址,調用函數,清理堆棧指針。我認爲文本將是唯一需要的參數,因爲printf搜索空字節終止。 – user2177208 2013-03-22 16:56:10
文本字符串必須以0字節結尾!如果沒有,'printf()'知道它會在哪裏結束? – 2013-03-22 17:00:30