2016-11-07 128 views
-5

我想在Linux中使用匯編語言調用printf函數。使用nasm在64位和32位體系結構上從彙編語言調用printf

我想知道64位和32位彙編語言程序的方法。

1)如果我想通過一個字符串在printf中進行32位的爭論和64位的爭論,請告訴我兩種情況。我應該怎麼做?

2)x86的32位架構,如果我想要做同樣的事情在1點

請告訴我的代碼。並讓我知道我是否需要調整這兩種情況下的堆棧,並且只需要通過寄存器中的爭論?

非常感謝

+0

我正在使用corei7 64位體系結構。但我想知道在32位和64位程序中調用printf的方法。我想知道在哪裏通過爭論,以及是否需要在通話後手動調整堆棧。請給我兩個例子。用於在兩種情況下傳遞32位和64位的字符串。 – user2277648

+0

谷歌搜索_「printf nasm」_或_「x86-64 printf nasm」_時的第一個命中是帶有一堆示例程序的頁面,其中包括一個調用'printf'的程序。 – Michael

回答

1

在Linux中有兩種使用匯編語言打印字符串的方法。

1)對於x64,使用syscall或對於x86使用int 0x80。它不是printf,它是內核例程。你可以找到更多here (x86)here (x64)

2)使用glibc中的printf。我假設你熟悉NASM程序的結構,所以這裏是從acm.mipt.ru一個很好的例子86:

global main 

;Declare used libc functions 
extern exit 
extern puts 
extern scanf 
extern printf 

section .text 

main: 

;Arguments are passed in reversed order via stack (for x86) 
;For x64 first six arguments are passed in straight order 
; via RDI, RSI, RDX, RCX, R8, R9 and other are passed via stack 
;The result comes back in EAX/RAX 
push dword msg 
call puts 
;After passing arguments via stack, you have to clear it to 
; prevent segfault with add esp, 4 * (number of arguments) 
add esp, 4 

push dword a 
push dword b 
push dword msg1 
call scanf 
add esp, 12 
;For x64 this scanf call will look like: 
; mov rdi, msg1 
; mov rsi, b 
; mov rdx, a 
; call scanf 

mov eax, dword [a] 
add eax, dword [b] 
push eax 
push dword msg2 
call printf 
add esp, 8 

push dword 0 
call exit 
add esp, 4 
ret 

section .data 
msg : db "An example of interfacing with GLIBC.",0xA,0 
msg1 : db "%d%d",0 
msg2 : db "%d", 0xA, 0 

section .bss 
a resd 1 
b resd 1 

您可以用nasm -f elf32 -o foo.o foo.asmgcc -m32 -o foo foo.o鏈接x86彙編它。對於x64,只需將elf32替換爲elf64-m32並將其替換爲-m64即可。請注意,您需要使用gcc在x64系統上構建x86程序,才能使用gcc-multilib

+1

您實際上需要'gcc -nostartfiles'來鏈接定義'_start'(而不是'main')的'.o'。有關完整的詳細信息,請參閱http://stackoverflow.com/questions/36861903/assembling-32-bit-binaries-on-a-64-bit-system-gnu-toolchain/36901649#36901649。 –

+1

另外,在CALL之後,您需要添加,而不是子。 'sub esp,12'保留更多的堆棧空間。或者讓ESP單獨存放,並存儲到您沒有用MOV指令彈出的空間中,以便爲下一個CALL設置。 –

+0

@PeterCordes哦謝謝,我搞砸了一點 – trexxet