从程序集调用C函数(printf)时出现段错误 [英] Segfault while calling C function (printf) from Assembly
本文介绍了从程序集调用C函数(printf)时出现段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Linux上使用NASM编写一个基本的汇编程序,该程序从C库(printf)中调用一个函数.不幸的是,我在这样做时遇到了分段错误.注释掉对printf的调用,可以使程序正常运行.
I am using NASM on linux to write a basic assembly program that calls a function from the C libraries (printf). Unfortunately, I am incurring a segmentation fault while doing so. Commenting out the call to printf allows the program to run without error.
; 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
推荐答案
x86_64的前6个参数不使用堆栈.您需要将它们加载到适当的寄存器中.这些是:
x86_64 does not use the stack for the first 6 args. You need to load them in the proper registers. Those are:
rdi, rsi, rdx, rcx, r8, r9
我用来记住前两个的技巧是想象功能是memcpy
实现为rep movsb
,
The trick I use to remember the first two is to imagine the function is memcpy
implemented as rep movsb
,
这篇关于从程序集调用C函数(printf)时出现段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文