在带有64位Linux的Assembly for x86_64中编写putchar吗? [英] Writing a putchar in Assembly for x86_64 with 64 bit Linux?
问题描述
我正在尝试使用写入 syscall
来重现打印单个字符的 putchar
函数行为.我的代码如下,
I am trying to use the write syscall
in order to reproduce the putchar
function behavior which prints a single character. My code is as follows,
asm_putchar:
push rbp
mov rbp, rsp
mov r8, rdi
call:
mov rax, 1
mov rdi, 1
mov rsi, r8
mov rdx, 1
syscall
return:
mov rsp, rbp
pop rbp
ret
推荐答案
从 man 2 write
中,您可以看到 write
的签名是
From man 2 write
, you can see the signature of write
is,
ssize_t write(int fd, const void *buf, size_t count);
它需要一个指向内存中缓冲区的指针( const void * buf
).您无法按值传递 char
,因此必须将其存储到内存并传递指针.
It takes a pointer (const void *buf
) to a buffer in memory. You can't pass it a char
by value, so you have to store it to memory and pass a pointer.
(除非您只有一个要打印的字符,否则不要一次打印一个字符,这确实效率低下.在内存中构造一个缓冲区并进行打印.例如,此x86-64 Linux NASM函数:
(Don't print one char at a time unless you only have one to print, that's really inefficient. Construct a buffer in memory and print that. e.g. this x86-64 Linux NASM function: How do I print an integer in Assembly Level Programming without printf from the c library?)
NASA版本的 GCC:内联汇编中的putchar(char):
; x86-64 System V calling convention: input = byte in DIL
; clobbers: RDI, RSI, RDX, RCX, R11 (last 2 by syscall itself)
; returns: RAX = write return value: 1 for success, -1..-4095 for error
writechar:
mov byte [rsp-4], dil ; store the char from RDI
mov edi, 1 ; EDI = fd=1 = stdout
lea rsi, [rsp-4] ; RSI = buf
mov edx, edi ; RDX = len = 1
syscall ; rax = write(1, buf, 1)
ret
这篇关于在带有64位Linux的Assembly for x86_64中编写putchar吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!