问题描述
我正在尝试使用 NASM 打印单个字符或数字,目标是 x86 GNU/Linux 架构.
I'm trying to print a single character or a number using NASM, targeting an x86 GNU/Linux architecture.
这是我正在使用的代码:
Here's the code I'm using:
section .text
global _start
_start:
; Linux printing preparation
mov eax,4
mov ebx,1
; Print 'A' character
mov ecx,'A' ; ecx should contain the value to print
mov edx,1 ; edx should contain how many characters to print
int 80h
; System exit
mov eax,1
mov ebx,0
int 80h
然而,运行此代码,什么也不打印.我做错了什么?
Running this code, however, prints nothing. What am I doing wrong?
推荐答案
ecx
应该包含一个指向字符缓冲区开始的指针.所以你必须在内存中有你的缓冲区.您可以执行以下操作:
ecx
should contain a pointer to the start of your char buffer. So you have to have your buffer in memory. You can do the following:
; Print 'A' character
mov eax, 4 ; __NR_write from asm/unistd_32.h (32-bit int 0x80 ABI)
mov ebx, 1 ; stdout fileno
push 'A'
mov ecx, esp ; esp now points to your char
mov edx, 1 ; edx should contain how many characters to print
int 80h ; sys_write(1, "A", 1)
; return value in EAX = 1 (byte written), or error (-errno)
add esp, 4 ; restore esp if necessary
如果可以覆盖堆栈中的任何内容,您可以移动字节 [esp]、'A'
或任何其他地址.
You can mov byte [esp], 'A'
or whatever other address if it's OK to overwrite whatever is on the stack.
或者你可以在 section .rodata
中有一个字符数组,而不是即时存储.
Or you can have a character array in section .rodata
instead of storing on the fly.
制作一个write()
系统使用 const void *buf
arg 调用 是一些小数字(如 'A'
)将使其返回 -EFAULT
而没有打印任何东西.无论如何,内核必须检查指针,系统调用返回错误而不是在错误指针上引发 SIGSEGV.
Making a write()
system call with the const void *buf
arg being some small number (like 'A'
) will make it return -EFAULT
without printing anything. The kernel has to check the pointer anyway, and system calls return an error instead of raising SIGSEGV on bad pointers.
使用 strace ./my_program
来跟踪您实际进行的系统调用,包括解码返回值.
Use strace ./my_program
to trace the system calls you actually made, including decoding the return values.
这篇关于如何在 Linux x86 NASM 中打印字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!