我想在linux中从汇编语言调用printf函数。
我想知道64位和32位汇编语言程序的方法。
1) 如果我想用字符串在 printf 中传递 32 位争论和 64 位争论,请告诉我两种情况。我该怎么做?
2) 对于 x86 32 位架构,如果我想做与第 1 点相同的事情。
请告诉我代码。让我知道我是否需要调整这两种情况的堆栈,我是否只需要在寄存器中传递参数?
非常感谢
最佳答案
在 Linux 中使用汇编语言打印字符串有两种方法。
1) 对于 x64 使用 syscall
,对于 x86 使用 int 0x80
。它不是 printf
,它是内核例程。您可以找到更多here (x86)和here (x64) 。
2) 使用 glibc 中的 printf
。我假设您熟悉 NASM 程序的结构,所以这里有一个很好的 x86 示例,来自 acm.mipt.ru :
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.asm
组装它,并与 x86 的 gcc -m32 -o foo foo.o
链接。对于 x64,只需将 elf32
替换为 elf64
,将 -m32
替换为 -m64
。请注意,您需要 gcc-multilib
使用 gcc 在 x64 系统上构建 x86 程序。
关于linux - 使用 nasm 在 64 位和 32 位架构上从汇编语言调用 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40458869/