Luna/kernel/src/sys/exec.cpp

128 lines
3.1 KiB
C++
Raw Normal View History

#define MODULE "exec"
#include "errno.h"
#include "interrupts/Interrupts.h"
#include "kassert.h"
2022-10-16 16:23:33 +00:00
#include "log/Log.h"
#include "memory/MemoryManager.h"
#include "memory/PMM.h"
#include "memory/VMM.h"
#include "std/stdlib.h"
#include "std/string.h"
#include "sys/Syscall.h"
#include "sys/elf/ELFLoader.h"
#include "thread/Scheduler.h"
void sys_fork(Context* context)
{
kinfoln("fork(): attempting fork");
Task* parent = Scheduler::current_task();
Task* child = Scheduler::create_user_task();
if (!child)
{
context->rax = -ENOMEM;
return;
}
if (!child->allocator.inherit(parent->allocator))
{
child->state = child->Exited;
child->exit_status = -127; // so the reaper reaps it on next reaping
context->rax = -ENOMEM;
return;
}
child->save_context(context);
child->save_floating();
for (int i = 0; i < TASK_MAX_FDS; i++) { child->files[i] = parent->files[i]; }
child->address_space = parent->address_space.clone();
child->regs.rax = 0;
context->rax = child->id;
strlcpy(child->name, parent->name, sizeof(child->name));
child->state = child->Running;
kinfoln("fork(): forked parent %ld into child %ld", parent->id, child->id);
return;
}
void sys_exec(Context* context, const char* pathname)
{
2022-10-14 16:00:33 +00:00
char* kpathname = Syscall::strdup_from_user(pathname);
if (!kpathname)
{
2022-10-12 17:25:35 +00:00
context->rax = -EFAULT;
return;
}
kinfoln("exec(): executing %s", kpathname);
VFS::Node* program = VFS::resolve_path(kpathname);
if (!program)
{
kfree(kpathname);
context->rax = -ENOENT;
return;
}
if (program->type == VFS_DIRECTORY)
{
kfree(kpathname);
context->rax = -EISDIR;
return;
}
long memusage;
if ((memusage = ELFLoader::check_elf_image(program)) < 0)
{
kfree(kpathname);
context->rax = -ENOEXEC;
return;
}
if ((uint64_t)memusage > PMM::get_free())
{
kfree(kpathname);
context->rax = -ENOMEM;
return;
}
Interrupts::disable();
ASSERT(!Interrupts::are_enabled()); // This part is pretty sensitive.
Task* task = Scheduler::current_task();
ASSERT(task);
// At this point, pretty much nothing can fail.
task->allocator.free();
task->allocator
.init(); // If we had enough space for the old bitmap, we should have enough space for the new bitmap.
task->address_space.clear();
task->allocated_stack = (uint64_t)MemoryManager::get_pages_at(
0x100000, TASK_PAGES_IN_STACK,
MAP_USER | MAP_READ_WRITE); // If we had enough space for the old stack, there should be enough space for the
// new stack.
ELFImage* image = ELFLoader::load_elf_from_vfs(program);
ASSERT(image); // If check_elf_image succeeded, load_elf_from_vfs MUST succeed, unless something has gone terribly
// wrong.
strlcpy(task->name, kpathname, sizeof(task->name));
Scheduler::reset_task(task, image);
task->restore_context(context);
kfree(kpathname);
2022-10-14 16:00:33 +00:00
return;
}