bvk256
bvk256

Reputation: 1903

file read buffer is empty in nasm

I managed to build a NASM tutorial code for dealing with files. It outputs the contents of a file to stdout just fine, but when I try to access the data buffer, it contains just zeros. For example in the code below in middle loop EBX is always set to 0, when it should contain file bytes.

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               ; );

Upvotes: 0

Views: 1907

Answers (1)

Matthew Slattery
Matthew Slattery

Reputation: 46998

For example in the code below in middle loop EBX is always set to 0, when it should contain file bytes.

How are you determining this? (Running under a debugger, perhaps?)

Your code has an unfortunate bug:

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

You're overwriting EAX (which contains the file descriptor returned by the open syscall, if the open succeeded) with the value 3, before it gets moved to EBX as the file descriptor argument to read.

Normally, a process will start out with file descriptors 0, 1 and 2 assigned to stdin, stdout and stderr, and the first file descriptor that you explicitly open will be 3, so you'll get away with it!

But you might not be so lucky if you're running with a debugger. File descriptor 3 might be something else, and the read might fail (you don't check to see if the returned value is a negative error code), or read something completely unexpected...

Upvotes: 1

Related Questions