简体   繁体   English

从程序集调用C函数(printf)时出现段错误

[英]Segfault while calling C function (printf) from Assembly

I am using NASM on linux to write a basic assembly program that calls a function from the C libraries (printf). 我正在Linux上使用NASM编写一个基本的汇编程序,该程序从C库(printf)调用一个函数。 Unfortunately, I am incurring a segmentation fault while doing so. 不幸的是,我在这样做时遇到了分段错误。 Commenting out the call to printf allows the program to run without error. 注释掉对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

x86_64 does not use the stack for the first 6 args. x86_64的前6个参数不使用堆栈。 You need to load them in the proper registers. 您需要将它们加载到适当的寄存器中。 Those are: 那些是:

rdi, rsi, rdx, rcx, r8, r9

The trick I use to remember the first two is to imagine the function is memcpy implemented as rep movsb , 我记得前两个技巧是想像该函数是memcpy实现为rep movsb

You're calling a varargs function -- printf expects a variable number of arguments and you have to account for that in the argument stack. 您正在调用varargs函数-printf需要可变数量的参数,并且必须在参数堆栈中考虑该数量。 See here: http://www.csee.umbc.edu/portal/help/nasm/sample.shtml#printf1 参见此处: http : //www.csee.umbc.edu/portal/help/nasm/sample.shtml#printf1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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