Luna/kernel/src/sys/exec.cpp
apio 8c72e9a49a
All checks were successful
continuous-integration/drone/push Build is passing
kernel: Add an exec() system call
Doesn't support arguments or environment for now.
2023-03-16 22:44:58 +01:00

46 lines
1.2 KiB
C++

#include "ELF.h"
#include "Log.h"
#include "fs/VFS.h"
#include "memory/MemoryManager.h"
#include "sys/Syscall.h"
#include "thread/Scheduler.h"
#include "thread/ThreadImage.h"
#include <bits/modes.h>
#include <luna/CString.h>
#include <luna/ScopeGuard.h>
Result<u64> sys_exec(Registers* regs, SyscallArgs args)
{
auto path = TRY(MemoryManager::strdup_from_user(args[0]));
auto inode = TRY(VFS::resolve_path(path.chars()));
// Not executable
if ((inode->mode() & S_IXUSR) != S_IXUSR) return err(EACCES);
kinfoln("exec: attempting to replace current image with %s", path.chars());
auto current = Scheduler::current();
auto image = TRY(ThreadImage::try_load_from_elf(inode));
// From now on, nothing should fail.
kinfoln("exec: image load ok, will now replace existing process image");
// FIXME: Close only O_CLOEXEC file descriptors.
for (int i = 0; i < FD_MAX; i++) { current->fd_table[i] = {}; }
MMU::delete_userspace_page_directory(current->directory);
image->apply(current);
MMU::switch_page_directory(current->directory);
memcpy(regs, &current->regs, sizeof(*regs));
kinfoln("exec: done");
return 0;
}