【问题标题】:syscall write not printing correctly the given string系统调用写入未正确打印给定的字符串
【发布时间】:2021-08-29 14:21:27
【问题描述】:

我只是想读取一个从 0 到 9 的数字并从中减去 4,将值存储在表中,然后将其打印到终端。它有点工作,但出于某种原因,当我打印“再见!”时在程序结束时,它会打印“eye!”。另外,出于某种原因,我需要将指针向后设置 2 个字节以“工作”。代码如下:

segment .data
val:                                ; defines a new array of 2 bytes long
    db 0
    db 0

num db 0
msg db 'bye!', 0ah

segment .bss

segment .text
    global _start                   ; defines the entry point

_start:
    mov  ecx ,  num
    mov  edx ,  01h                 ; sets the reading length
    mov  ebx ,  00h                 ; tells that it's an input call
    mov  eax ,  03h                 ; system call (read)
    int  80h                        ; calls it

    mov  eax , [num]                ; moves number to register
    sub  eax ,  04h                 ; subtracts 4 from it

    mov  ecx ,  val                 ; sets ecx to point to val

    mov [ecx],  eax                 ; adds the result to val, pointed by ecx
    inc  ecx                        ; moves the pointer to the next address
    mov [ecx],  byte 0ah            ; appends \n to the end of it
    sub  ecx ,  02h                 ; retreats pointer (is over here that I need to retreat 2 for some reason

    mov  edx ,  03h                 ; sets the string length
    mov  ebx ,  01h                 ; tells that it's an output call
    mov  eax ,  04h                 ; system call (write)
    int  80h                        ; calls it

    mov  ecx ,  msg                 ; passes the string to the function
    mov  edx ,  05h                 ; sets the string length
    mov  ebx ,  01h                 ; tells that it's an output call
    mov  eax ,  04h                 ; system call (write)
    int  80h                        ; calls it

    mov  eax ,  01h                 ; system call (exit)
    int  80h                        ; calls it

输出:

[mmd@pxdev asm]$ ./main
9
5
eye!
[mmd@pxdev asm]$ 
[mmd@pxdev asm]$ 

由于某种原因,它也退出了两次(?)。如果我将第 29 行设置为只后退一个字节,则在最后一行输出为yeye!

我刚开始组装,老实说,我觉得那里的教程解释得不够多。很抱歉,如果我遗漏了一些明显的东西或者我正在做一些非常愚蠢的事情。

编辑:我在第 31 行发现了一个错误,因为我告诉系统我正在打印 3 个字节,而实际上我在上面只打印 2 个字节。所以不再需要从 @987654324 撤回两个字节@。但主要错误不断发生。

【问题讨论】:

  • 您的 num 是一个字节,但您覆盖了 4 个字节,因此您破坏了随后的 bye
  • 好的,但是我在哪里覆盖它 4 个字节?
  • mov [ecx], eax 正在写入 4 个字节,因为 eax 是 32 位。 mov eax , [num] 也在读取 4 个字节,但在这种情况下并没有那么有害。
  • 明白了,非常感谢大人。
  • 不要在您的问题中发布您的答案。将其发布为答案。

标签: assembly nasm i386


【解决方案1】:

注意:这是提问者复制的解决方案,但未将其正确发布为答案。

解决方案:我将一个 32 位值 (eax) 移动到我的单字节变量 num(在 mov [ecx], eax 中),因此我弄乱了堆栈 (msg) 中的下一个地址。一旦修复,它就不起作用(除了它不断退出两次)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多