kernel+libc: Implement read()
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-03-11 18:02:50 +01:00
parent 810c4bc257
commit 8fa72f3cf0
Signed by: apio
GPG Key ID: B8A7D06E42258954
8 changed files with 52 additions and 5 deletions

View File

@ -21,6 +21,12 @@ int main()
return 1;
}
char buffer[512];
ssize_t nread = read(fd, buffer, sizeof(buffer));
buffer[nread] = 0;
printf("/etc/motd says: %s", buffer);
close(fd);
time_t now = time(NULL);

View File

@ -27,6 +27,7 @@ set(SOURCES
src/sys/allocate_memory.cpp
src/sys/usleep.cpp
src/sys/open.cpp
src/sys/file.cpp
src/fs/VFS.cpp
src/fs/tmpfs/FileSystem.cpp
src/InitRD.cpp

28
kernel/src/sys/file.cpp Normal file
View File

@ -0,0 +1,28 @@
#include "Log.h"
#include "fs/VFS.h"
#include "memory/MemoryManager.h"
#include "sys/Syscall.h"
#include "thread/Scheduler.h"
Result<u64> sys_read(Registers*, SyscallArgs args)
{
int fd = (int)args[0];
u8* buf = (u8*)args[1];
usize size = (usize)args[2];
if (!MemoryManager::validate_user_write(buf, size)) return err(EFAULT);
if (fd < 0 || fd >= FD_MAX) return err(EBADF);
Thread* current = Scheduler::current();
Option<FileDescriptor>& descriptor = current->fd_table->fds[fd];
if (!descriptor.has_value()) return err(EBADF);
usize nread = TRY(descriptor->inode->read(buf, descriptor->offset, size));
descriptor->offset += nread;
return nread;
}

View File

@ -34,12 +34,13 @@ Result<u64> sys_close(Registers*, SyscallArgs args)
Thread* current = Scheduler::current();
if (!current->fd_table->fds[fd].has_value()) return err(EBADF);
Option<FileDescriptor>& descriptor = current->fd_table->fds[fd];
kinfoln("close: closing file descriptor %d (was referencing inode %zu)", fd,
current->fd_table->fds[fd]->inode->inode_number());
if (!descriptor.has_value()) return err(EBADF);
current->fd_table->fds[fd] = {};
kinfoln("close: closing file descriptor %d (was referencing inode %zu)", fd, descriptor->inode->inode_number());
descriptor = {};
return 0;
}

View File

@ -9,6 +9,7 @@
#include <bits/fixed-size-types.h>
typedef int pid_t;
typedef __i64_t ssize_t;
typedef __i64_t time_t;
typedef __u16_t mode_t;
typedef __u64_t useconds_t;

View File

@ -33,6 +33,9 @@ extern "C"
/* Closes a file descriptor. */
int close(int fd);
/* Reads bytes from a file descriptor. */
ssize_t read(int fd, void* buf, size_t size);
#ifdef __cplusplus
}
#endif

View File

@ -43,4 +43,10 @@ extern "C"
long rc = syscall(SYS_close, fd);
__errno_return(rc, int);
}
ssize_t read(int fd, void* buf, size_t size)
{
long rc = syscall(SYS_read, fd, buf, size);
__errno_return(rc, ssize_t);
}
}

View File

@ -1,7 +1,8 @@
#pragma once
#define enumerate_syscalls(_e) \
_e(exit) _e(console_write) _e(clock_gettime) _e(allocate_memory) _e(deallocate_memory) _e(usleep) _e(open) _e(close)
_e(exit) _e(console_write) _e(clock_gettime) _e(allocate_memory) _e(deallocate_memory) _e(usleep) _e(open) \
_e(close) _e(read)
enum Syscalls
{