【问题标题】:NASM loop over bytesNASM 循环字节
【发布时间】:2012-02-19 13:12:36
【问题描述】:

目前我正在尝试遍历缓冲区中的每个字节(从文件中读取)并比较它以查看其中是否有空格,然后将它们写入 STDOUT。由于某种原因,程序编译并运行良好,但输出为零。

section .data
   bufsize dw      1024

section .bss
   buf     resb    1024
section  .text
  global  _start

_start:
    ; open the file provided form cli in read mode
    mov edi, 0
    pop   ebx
    pop   ebx
    pop   ebx
    mov   eax,  5
    mov   ecx,  0 
    int   80h
    ; write the contents in to the buffer 'buf'
    mov     eax,  3
    mov     ebx,  eax
    mov     ecx,  buf
    mov     edx,  bufsize
    int     80h

    ; write the value at buf+edi to STDOUT 
    mov     eax,  4
    mov     ebx,  1
    mov     ecx,  [buf+edi]
    mov     edx, 1
    int     80h
    ; if not equal to whitespace, jump to the loop
    cmp byte [buf+edi], 0x20
    jne loop

loop:
    ; increment the loop counter
    add     edi, 1
    mov     eax,  4
    mov     ebx,  1
    mov     ecx,  [buf+edi]
    int     80h
    ; compare the value at buf+edi with the HEX for whitespace
    cmp byte [buf+edi], 0x20
    jne loop

; exit the program
mov   eax,  1
mov   ebx,  0 
int   80h

【问题讨论】:

  • 0x20 不是“空白”,它实际上只是 space,即空白的子集。不过,这可能是吹毛求疵。 :)
  • 愚蠢的问题,但你确定你的文件中有0x20吗?
  • 这是 32 位 linux 还是 BSD?
  • 所以你想打印字符直到找到一个空格,然后停止?你能提供一个测试输入文件吗?我不使用 NASM,但大多数系统调用看起来都不错,即使您没有检查它们的返回码。无论出于何种原因,这些打开/读/写调用都可能失败。即使它工作正常,如果输入文件的开头有两个空格,您也不会产生任何输出(尽管它会打印一个空格)。
  • 该程序对我来说运行不正常。我通过 GDB 编译并运行它,它产生了一个分段错误。我会进行一些错误检查,然后使用调试器检查代码。

标签: linux assembly x86 nasm


【解决方案1】:

主要问题是我没有给出bufsize的地址([bufsize]),循环也有问题。

这是固定版本,谢谢大家的意见。

section .data
   bufsize dd      1024

section .bss
   buf:     resb    1024
section  .text
  global  _start

_start:
    ; open the file provided form cli in read mode
    mov edi, 0
    pop   ebx
    pop   ebx
    pop   ebx
    mov   eax,  5
    mov   ecx,  0
    int   80h
    ; write the contents in to the buffer 'buf'
    mov     eax,  3
    mov     ebx,  eax
    mov     ecx,  buf
    mov     edx,  [bufsize]
    int     80h

    ; write the value at buf+edi to STDOUT
    ; if equal to whitespace, done
loop:
    cmp byte [buf+edi], 0x20
    je done
    mov     eax,  4
    mov     ebx,  1
    lea     ecx,  [buf+edi]
    mov     edx,  1
    int     80h
    ; increment the loop counter
    add     edi, 1
    jmp loop
done:
; exit the program
mov   eax,  1
mov   ebx,  0
int   80h

【讨论】:

  • 这仍然包含错误。例如,“bufsize dw”创建一个 16 位值,但您将其读取为 32 位值。应将其更改为“bufsize dd”或“movzx edx,word [bufsize]”。也没有错误处理(例如,如果“open()”失败了怎么办?)。我还想使用(相当于)“puts()”或“write()”进行输出,而不是为每个单独的字符调用内核。
  • 有效积分,谢谢。更改了代码以适应您的建议,但错误处理除外。
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多