【问题标题】:NASM Linux Assembly Printing IntegersNASM Linux 汇编打印整数
【发布时间】:2011-10-17 17:18:46
【问题描述】:

我正在尝试在 linux 上的 nasm 程序集中打印一个数字整数。我目前的编译很好,但没有任何内容被写入屏幕。谁能向我解释我在这里做错了什么?

section .text
    global _start

_start:
    mov ecx, 1          ; stores 1 in rcx
    add edx, ecx        ; stores ecx in edx
    add edx, 30h        ; gets the ascii value in edx
    mov ecx, edx        ; ascii value is now in ecx
    jmp write           ; jumps to write


write:
    mov eax, ecx        ; moves ecx to eax for writing
    mov eax, 4          ; sys call for write
    mov ebx, 1          ; stdout

    int 80h             ; call kernel
    mov eax,1           ; system exit
    mov ebx,0           ; exit 0
    int 80h             ; call the kernel again 

【问题讨论】:

标签: linux assembly nasm


【解决方案1】:

这是添加,而不是存储:

add edx, ecx        ; stores ecx in edx

这会将 ecx 复制到 eax,然后用 4 覆盖它:

mov eax, ecx        ; moves ecx to eax for writing
mov eax, 4          ; sys call for write

编辑:

对于“写入”系统调用:

eax = 4
ebx = file descriptor (1 = screen)
ecx = address of string
edx = length of string

【讨论】:

  • 我试过了,它也编译得很好,但没有任何东西写入屏幕。
  • 我仍然无法让它工作,但我会将此作为公认的答案。
  • @FrozenWasteland - 这个答案中提到了剩下的问题,但没有特别引起您的注意:“ecx = 字符串地址 edx = 字符串长度”但您一直在尝试提供数据字节本身 inc ecx 而不是那里的地址和 edx 中的长度。
【解决方案2】:

在查看了其他两个答案之后,我终于想到了。

sys_exit        equ     1
sys_write       equ     4
stdout          equ     1

section .bss
    outputBuffer    resb    4       

section .text
    global _start

_start:
    mov  ecx, 1                 ; Number 1
    add  ecx, 0x30              ; Add 30 hex for ascii
    mov  [outputBuffer], ecx    ; Save number in buffer
    mov  ecx, outputBuffer      ; Store address of outputBuffer in ecx

    mov  eax, sys_write         ; sys_write
    mov  ebx, stdout            ; to STDOUT
    mov  edx, 1                 ; length = one byte
    int  0x80                   ; Call the kernel

    mov eax, sys_exit           ; system exit
    mov ebx, 0                  ; exit 0
    int 0x80                    ; call the kernel again

【讨论】:

    【解决方案3】:

    从人 2 写

    ssize_t write(int fd, const void *buf, size_t count);
    

    除了已经指出的其他错误之外,write() 需要一个 指针 指向数据和一个长度,而不是您尝试提供的寄存器中的实际字节本身。

    因此,您必须将数据从寄存器存储到内存并使用该地址(或者如果它当前是常量,则不要将数据加载到寄存器中,而是加载其地址)。

    【讨论】:

    • 幸运的是,这不是答案的关键部分,只是为了方便而包括在内。
    猜你喜欢
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 2013-12-14
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多