How do I use file in user's space?

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
User avatar
gamingjam60
Member
Member
Posts: 53
Joined: Sat Aug 24, 2024 10:06 pm
Libera.chat IRC: gamingjam60
Location: India
GitHub: https://github.com/baponkar
Contact:

How do I use file in user's space?

Post by gamingjam60 »

I want to use FatFs Filesystem library in my x86 architecture based 64 bit system. Here my plan is to use fatfs f_open function by following way

f_open => kernel space system call defination => userspace system call is showing invalid file pointer. Here my code was

Code: Select all

case INT_SYSCALL_FATFS_OPEN: {          // 0x33 : Open a file

            const char *path = (const char *)regs->rbx;
            FIL *file = (FIL *)regs->rcx;    // File pointer (output)
            // FIL *file = (FIL *)kheap_alloc(sizeof(FIL), ALLOCATE_DATA);
            BYTE mode = (BYTE)regs->rdx;        // File open mode

            printf("int_syscall_fatfs_open: path: %x, file: %x, mode: %x\n", (uint64_t)path, (uint64_t)file, (uint64_t)mode);

            if (!path || !file || !mode) {
                regs->rax = -1;                 // Invalid path, file, mode
                break;
            }

            FRESULT res = f_open(file, path, mode);
            if (res != FR_OK) {
                kheap_free((void *)file, sizeof(FIL));
                regs->rax = -1;                 // Open file failed
            }
            regs->rax = (uint64_t)file;         // Return file pointer
            
            break;
        }

Code: Select all

uint64_t syscall_fatfs_open(const char *path, uint64_t mode) {

    uint64_t file = syscall_uheap_alloc(128, ALLOCATE_DATA);

    if (!path || !mode) {
        return -1; // Invalid path
    }

    printf("syscall_fatfs_open: path: %x, mode: %x\n", (uint64_t)path, mode);

    uint64_t file_handle;

    asm volatile (
        "mov %[path], %%rbx\n"      // path pointer store into rbx
        "mov %[file], %%rcx\n"
        "mov %[mode], %%rdx\n"      // Store mode into rcx
        "int $0x33\n"
        "mov %%rax, %[handle]\n"
        : [handle] "=r" (file_handle)
        : [path] "r" ((uint64_t)path), [file] "r" ((uint64_t)file), [mode] "r" (mode)
        : "rbx", "rcx", "rax"
    );

    return file_handle;
}

Code: Select all

    uint64_t opened_file = syscall_fatfs_open(file_name, FA_WRITE | FA_READ | FA_CREATE_ALWAYS);
Here I have allocated FIL structure pointer in Lower half which is showing invalid pointer in f_open's output . I also tried to allocate file pointer in Upper half in kernelspace is also causing same proble.

How do I need to allocate file pointer which will be valid in userspace and writable, readable etc.
Post Reply