使用 nasm 在 64 位和 32 位架构上从汇编语言调用 printf [英] calling printf from assembly language on 64bit and 32bit architecture using nasm

查看:43
本文介绍了使用 nasm 在 64 位和 32 位架构上从汇编语言调用 printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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)此处 (x64).

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 程序的结构,所以这里有一个来自 acm.mipt.ru:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆