簡體   English   中英

從程序集調用C函數(printf)時出現段錯誤

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

我正在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

x86_64的前6個參數不使用堆棧。 您需要將它們加載到適當的寄存器中。 那些是:

rdi, rsi, rdx, rcx, r8, r9

我記得前兩個技巧是想像該函數是memcpy實現為rep movsb

您正在調用varargs函數-printf需要可變數量的參數,並且必須在參數堆棧中考慮該數量。 參見此處: 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