kernel+libc: Implement fcntl() for F_DUPFD and F_DUPFD_CLOEXEC
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-03-24 21:33:20 +01:00
parent 0de41410c6
commit 770286a19d
Signed by: apio
GPG Key ID: B8A7D06E42258954
7 changed files with 68 additions and 1 deletions

View File

@ -3,6 +3,8 @@
#include "memory/MemoryManager.h"
#include "sys/Syscall.h"
#include "thread/Scheduler.h"
#include <bits/fcntl.h>
#include <bits/open-flags.h>
#include <bits/seek.h>
#include <luna/SafeArithmetic.h>
#include <sys/types.h>
@ -84,3 +86,33 @@ Result<u64> sys_lseek(Registers*, SyscallArgs args)
return (u64)new_offset;
}
Result<u64> sys_fcntl(Registers*, SyscallArgs args)
{
int fd = (int)args[0];
int cmd = (int)args[1];
Thread* current = Scheduler::current();
auto& descriptor = *TRY(current->resolve_fd(fd));
bool is_cloexec = true;
switch (cmd)
{
case F_DUPFD: is_cloexec = false; [[fallthrough]];
case F_DUPFD_CLOEXEC: {
int arg = (int)args[2];
int new_fd = TRY(current->allocate_fd(arg));
current->fd_table[new_fd] = descriptor;
if (is_cloexec) current->fd_table[new_fd]->flags |= O_CLOEXEC;
else
current->fd_table[new_fd]->flags &= ~O_CLOEXEC;
return (u64)new_fd;
}
default: return err(EINVAL);
}
}

View File

@ -0,0 +1,9 @@
/* bits/fcntl.h: File control flags. */
#ifndef _BITS_FCNTL_H
#define _BITS_FCNTL_H
#define F_DUPFD 0
#define F_DUPFD_CLOEXEC 1
#endif

View File

@ -3,6 +3,7 @@
#ifndef _FCNTL_H
#define _FCNTL_H
#include <bits/fcntl.h>
#include <bits/open-flags.h>
#include <sys/types.h>
@ -17,6 +18,9 @@ extern "C"
/* Create a file and return a file descriptor to it. */
int creat(const char* path, mode_t mode);
/* Perform a file control operation. */
int fcntl(int fd, int cmd, ...);
#ifdef __cplusplus
}
#endif

View File

@ -55,6 +55,9 @@ extern "C"
/* Modify a file descriptor's offset. */
off_t lseek(int fd, off_t offset, int whence);
/* Duplicate a file descriptor. */
int dup(int fd);
#ifdef __cplusplus
}
#endif

View File

@ -23,4 +23,17 @@ extern "C"
{
return open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
}
int fcntl(int fd, int cmd, ...)
{
va_list ap;
va_start(ap, cmd);
uintptr_t arg = (uintptr_t)va_arg(ap, uintptr_t);
long rc = syscall(SYS_fcntl, fd, cmd, arg);
va_end(ap);
__errno_return(rc, int);
}
}

View File

@ -1,4 +1,5 @@
#include <bits/errno-return.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdint.h>
#include <sys/syscall.h>
@ -83,4 +84,9 @@ extern "C"
long rc = syscall(SYS_lseek, fd, offset, whence);
__errno_return(rc, off_t);
}
int dup(int fd)
{
return fcntl(fd, F_DUPFD, 0);
}
}

View File

@ -2,7 +2,7 @@
#define enumerate_syscalls(_e) \
_e(exit) _e(clock_gettime) _e(mmap) _e(munmap) _e(usleep) _e(open) _e(close) _e(read) _e(getpid) _e(write) \
_e(lseek) _e(mkdir) _e(exec) _e(mknod) _e(fork) _e(waitpid) _e(getppid)
_e(lseek) _e(mkdir) _e(exec) _e(mknod) _e(fork) _e(waitpid) _e(getppid) _e(fcntl)
enum Syscalls
{