Dominick Navarro
Dominick Navarro

Reputation: 752

Assembly: trying to write to file, but text is appending to filename

I'm trying to study assembly, while trying out the example in the tutorials I get stuck. I am compiling this using an ubuntu virtual machine.

Here is the code:

SYS_READ equ 3
SYS_WRITE equ 4
SYS_OPEN equ 5
SYS_CLOSE equ 6
SYS_CREATE equ 8
SYS_EXIT equ 1

section .text
    global _start

_start:
    mov eax, SYS_CREATE
    mov ebx, filename
    mov ecx, 0777
    int 0x80

    mov [fd_out],ebx

    mov eax,SYS_WRITE
    mov edx,len
    mov ecx,msg
    mov ebx,[fd_out]
    int 0x80

    mov eax,SYS_CLOSE
    mov ebx,[fd_out]
    int 80h

    mov eax,SYS_OPEN
    mov ebx,filename
    mov ecx,0
    mov edx,0777
    int 0x80

    mov [fd_in],eax

    mov eax, SYS_READ
    mov ebx,[fd_in]
    mov ecx,info
    mov edx,26
    int 0x80

    mov eax,SYS_WRITE
    mov ebx,1
    mov ecx,info
    mov edx,26
    int 0x80

    mov eax,SYS_EXIT
    mov ebx,0
    int 0x80

section .data
    filename db 'test.txt'
    msg db 'Hello world file'
    len equ $-msg

section .bss
    fd_out resb 1
    fd_in resb 1
    info resb 26

after executing the compiled output, I get a file named test.txtHello world file.

Upvotes: 1

Views: 409

Answers (1)

johnfound
johnfound

Reputation: 7061

While SYS_WRITE accepts the length of the information in EDX, the function SYS_CREATE needs a pointer to NULL terminated string for the filename.

Your filename, defined as

filename db 'test.txt'

is not NULL terminated and that is why it concatenates with the next string:

msg db 'Hello world file'

The terminating NULL in this case is the next defined:

fd_out resb 1

In order to fix it, simply define the filename with zero terminating byte:

filename db 'test.txt', 0

Upvotes: 2

Related Questions