使用nasm在64位和32位体系结构上从汇编语言调用printf [英] calling printf from assembly language on 64bit and 32bit architecture using nasm
问题描述
我想从Linux中的汇编语言调用printf函数.
I want to call printf function from assembly language in linux.
我想知道用于64位和32位汇编语言程序的方法.
i want to know the method for for 64 bit and 32 bit assembly language programs.
1)如果我想在printf中使用字符串传递32位争论和64位争论,请告诉我两种情况.我该怎么办?
1) please tell me for two cases if i want to pass a 32 bit arguement and 64 bit arguement in printf with a string. how should i do it?
2)对于x86 32位体系结构,如果我想做与第1点相同的事情.
2) for x86 32 bit architecture if i want to do the same thing as in point 1.
请告诉我代码.让我知道我是否需要针对这两种情况调整堆栈,是否只需要在寄存器中传递争论?
please tell me the code. and let me know do i need to adjust the stack for both cases and do i just need to pass the arguements in registers?
非常感谢
推荐答案
在Linux中,有两种使用汇编语言打印字符串的方法.
There are 2 ways to print a string with assembly language in Linux.
1)对于x64使用syscall
,对于x86使用int 0x80
.不是printf
,它是内核例程.您可以在此处(x86)和
1) Use syscall
for x64, or int 0x80
for x86. It's not printf
, it's kernel routines. You can find more here (x86) and here (x64).
2)使用glibc中的printf
.我假设您熟悉NASM程序的结构,因此这是一个
2) Use printf
from glibc. I assume you are familiar with the structure of NASM program, so here is a nice x86 example from 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
组装在一起,并与gcc -m32 -o foo foo.o
链接以用于x86.对于x64,只需将elf32
替换为elf64
,将-m32
替换为-m64
.请注意,您需要gcc-multilib
才能使用gcc在x64系统上构建x86程序.
You can assembly it with nasm -f elf32 -o foo.o foo.asm
and link with gcc -m32 -o foo foo.o
for x86. For x64 just replace elf32
with elf64
and -m32
with -m64
. Note than you need gcc-multilib
to build x86 programs on x64 system using gcc.
这篇关于使用nasm在64位和32位体系结构上从汇编语言调用printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!