Search code examples
linuxassemblyx86att

Linux Assembly Creating File Has A Name Size Limit?


I am trying to create a file in 32 bit assembly, however when the file is created the name is constrained to only four characters. I am not sure why this happens. here is my code;

.section .data

.equ SYS_WRITE, 4
.equ SYS_CREAT, 8
.equ SYS_OPEN, 5
.equ SYS_CLOSE, 6
.equ O_CREAT_WRONLY_TRUNC, 03101
.equ LINUX_SYSCALL, 0x80

name:
.ascii "t.txt\0"

.section .text

.global _start 
_start:                 
movl %esp, %ebp
pushl name
movl $SYS_OPEN, %eax
movl %esp, %ebx
movl $O_CREAT_WRONLY_TRUNC, %ecx
movl $0666, %edx
int $LINUX_SYSCALL


movl %eax, %esi
movl $SYS_CLOSE, %eax
movl %esi, %ebx
int $LINUX_SYSCALL

movl $1, %eax
int $LINUX_SYSCALL

And compiling code via terminal;

as --32 touchfile.s -o touchfile.o
ld touchfile.o -o touchfile -m elf_i386
./touchfile

the file name also has a weird binary symbol at the end.


Solution

  • however when the file is created the name is constrained to only four characters.

    ... and if you are unlucky, there will even be trash characters after the 4th letter (e.g. "t.txDK@-_X=" instead of "t.txt").

    Your code would only work correctly with file names up to 3 characters (which means 4 characters including the terminating NUL)!

    The problem is the following sequence:

    pushl name
    ...
    movl %esp, %ebx
    

    Using the instruction pushl name you copy exactly 4 bytes of the file name to the stack. If your file name is longer, the rest is not copied.

    Using movl %esp, %ebp you tell Linux that the file name is located on the stack.

    The question is: Why do you want the file name to be on the stack?

    If you don't insist the file name to be on the stack, you can remove the istruction pushl name because you don't need to copy the file name to the stack.

    Use the instruction mov $name, %ebx (instead of mov %esp, %ebx) to tell Linux that the file name is located at the address name.