【问题标题】:file read buffer is empty in nasmnasm 中的文件读取缓冲区为空
【发布时间】:2011-10-07 20:57:41
【问题描述】:

我设法构建了一个 NASM 教程代码来处理文件。它将文件的内容输出到标准输出就好了,但是当我尝试访问数据缓冲区时,它只包含零。例如在下面的中间循环代码中,EBX 总是设置为 0,当它应该包含文件字节时。

section .data
   bufsize dw      1024

section .bss
   buf     resb    1024


section  .text              ; declaring our .text segment
  global  _start            ; telling where program execution should start

_start:                     ; this is where code starts getting exec'ed

  ; get the filename in ebx
    pop   ebx               ; argc
    pop   ebx               ; argv[0]
    pop   ebx               ; the first real arg, a filename

  ; open the file
    mov   eax,  5           ; open(
    mov   ecx,  0           ;   read-only mode
    int   80h               ; );

  ; read the file
    mov     eax,  3         ; read(
    mov     ebx,  eax       ;   file_descriptor,
    mov     ecx,  buf       ;   *buf,
    mov     edx,  bufsize   ;   *bufsize
    int     80h             ; );

    mov ecx, 20
loop:
    mov eax, 20
    sub eax, ecx
    mov ebx, [buf+eax*4]
    loop loop       

  ; write to STDOUT
    mov     eax,  4         ; write(
    mov     ebx,  1         ;   STDOUT,
    mov     ecx,  buf       ;   *buf
    int     80h             ; );

  ; exit
    mov   eax,  1           ; exit(
    mov   ebx,  0           ;   0
    int   80h               ; );

【问题讨论】:

    标签: linux assembly x86 nasm


    【解决方案1】:

    例如在下面的中间循环代码中,EBX 总是设置为 0,当它应该包含文件字节时。

    您如何确定这一点? (也许是在调试器下运行?)

    您的代码有一个不幸的错误:

     ; read the file
        mov     eax,  3         ; read(
        mov     ebx,  eax       ;   file_descriptor,
    

    您正在用值 3 覆盖 EAX(其中包含由 open 系统调用返回的文件描述符,如果 open 成功),然后它作为 read 的文件描述符参数移动到 EBX。

    通常,一个进程会从分配给stdinstdoutstderr的文件描述符0、1和2开始,而您明确open的第一个文件描述符将是3,所以你'我会侥幸逃脱的!

    但是,如果您使用调试器运行,您可能就没那么幸运了。文件描述符 3 可能是别的东西,read 可能会失败(你不检查返回的值是否是负错误代码),或者读取完全意外的东西......

    【讨论】:

    • 好的,我明白了。现在 read 返回正值,但 buf 再次不包含字符数据。
    • 这个问题解决了这个答案stackoverflow.com/questions/5803301/… 我将一个双字加载到 ebx 并屏蔽掉额外的位来生成一个字节。
    • 另外,bufsize 被声明为 dw - 你希望 dd... 和 [bufsize] 访问它的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多