Search code examples
assemblyx86fasm

Why can't I achive writting with `write` system-call in linux?


First things first:

format ELF

section '.text' executable

public _start
_start:
    ; OPENNIN FILE DESCRIPTOR FOR A PATH -->
    mov ebx, logfile
    mov eax, 5
    mov ecx, 64
    mov edx, 777o
    int 0x80

    ; JUNT `STRLEN` -->
    mov edi, ebx
    mov ebx, eax
    xor ecx, ecx
    not ecx
    xor eax, eax
    cld
    repne scasb
    not ecx

    ; WRITTING INTO THE FD'S FILE -->
    mov edx, ecx
    sub edi, edx
    mov ecx, edi
    lea edx, [edx]
    mov eax, 4
    int 0x80

    ; CLOSE DESCRIPTOR -->
    mov eax, 6
    int 0x80 

    ; EXIT -->
    mov eax, 1
    xor ebx, ebx
    int 0x80

section '.data' writeable

logfile db "#!@#$%$:",0

The above is my code I wrote into fasm. When compiling and running this piece of code (This part went well so I will not go into this.), I encounter the situation of -> My file created (and named #!@#$%$: of course...), but nothing was written to it.

I cant understand the reason why anything not written into the new file! The registers state should be just like this, as mentioned in: https://syscalls.kernelgrok.com/ And the file closed fine.

What could be the reason for this to happend?


Solution

  • Using strace(1) will tell you why immediately:

    $ strace ./test
    execve("./test", ["./test"], 0x7ffef0f1b5f0 /* 72 vars */) = 0
    strace: [ Process PID=32288 runs in 32 bit mode. ]
    open("#!@#$%$:", O_RDONLY|O_CREAT, 0777) = 3
    write(3, "#!@#$%$:\0", 9)               = -1 EBADF (Bad file descriptor)
    close(3)                                = 0
    exit(0)                                 = ?
    +++ exited with 0 +++
    

    Note the O_RDONLY|O_CREAT: you've opened the file as read-only, thus the subsequent write fails.