如何在Linux x86 NASM中打印字符? [英] How to print a character in Linux x86 NASM?

查看:73
本文介绍了如何在Linux x86 NASM中打印字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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应该包含一个指向char缓冲区开始的指针.因此,您必须将缓冲区存储在内存中.您可以执行以下操作:

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

如果可以覆盖堆栈中的任何内容,则可以mov byte [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中打印字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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