Romario Ramirez
Romario Ramirez

Reputation: 87

Writing to a file in Assembly file descriptor trouble

I am writing a program that writes the contents from one file into another. What I am doing now (for testing) is to open the two files and write an string in one of them. The program doesn't show up any error, however nothing is writing in the file.

Here is my code

BITS 32

section .data
    msg db "Hola"

section .bss
    src_file    resb 1      ; Source file descriptor 
    dest_file   resb 1      ; Destination file descriptor

section .text
    global _start

_start:
    pop ebx             ; argc
    pop ebx             ; argv[0] nombre del ejecutable

    pop ebx             ; src file name
    ;; Open src file
    mov ecx,1           ; Write mode
    mov eax,5           ; sys_open()
    int 0x80            ; Interruption 80. kernel call
    mov [src_file],eax

    pop ebx             ; dest file name
    ;; Open dest file
    mov ecx,1           ; Write mode
    mov eax,5           ; sys_open()
    int 0x80            ; Interruption 80. kernel call
    mov [dest_file],eax

    ;; Writes in src file
    mov edx,4           ; Long
    mov ecx,msg         ; text
    mov ebx,[src_file]  ; File descriptor of dest file
    mov eax,4
    int 0x80

    ;; Closes src file
    mov ebx,[src_file]  ; File descriptor of src file
    mov eax,6           ; sys_close()
    int 0x80            ; Kernel call

    ;; Closes dest file
    mov ebx,[dest_file] ; File descriptor of src file
    mov eax,6           ; sys_close()
    int 0x80            ; Kernel call

    ;; Exits the program
    mov ebx,0           ; OS exit code
    mov eax,1           ; sys_exit
    int 0x80            ; Kernel call

I think maybe there is something wrong in storing the file descriptor after opening a file because if I move the block of code which writes into the file right after opening the source file it works just fine.

Thanks for the help!

Upvotes: 0

Views: 1296

Answers (1)

Gunner
Gunner

Reputation: 5884

src_file    resb 1      ; Source file descriptor 
dest_file   resb 1      ; Destination file descriptor

1 byte for the file descriptors will not cut it. When you do a 4-byte load like mov ebx,[src_file], the 2nd-lowest byte of EBX will come from the dest_file byte instead of being zero, so the read or write system call will return -EBADF. They need to be DWORD sized variables!

src_file    resd 1      ; Source file descriptor 
dest_file   resd 1      ; Destination file descriptor

The program doesn't show up any error

Why would the program show an error? You never told it to! This is Assembly, nothing is automatic. The CPU happily put the file descriptors where you told it to, and just overwrote whatever was after them since they weren't big enough.

Upvotes: 2

Related Questions