1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 10:58:12 +00:00

Kernel: Replace "current" with Thread::current and Process::current

Suggested by Sergey. The currently running Thread and Process are now
Thread::current and Process::current respectively. :^)
This commit is contained in:
Andreas Kling 2020-02-17 15:04:27 +01:00
parent 4f4af24b9d
commit 48f7c28a5c
37 changed files with 257 additions and 252 deletions

View file

@ -115,8 +115,8 @@ DebugLogStream dbg()
stream << "\033[33;1m" << process_name_buffer << '(' << getpid() << ")\033[0m: "; stream << "\033[33;1m" << process_name_buffer << '(' << getpid() << ")\033[0m: ";
#endif #endif
#if defined(__serenity__) && defined(KERNEL) && !defined(BOOTSTRAPPER) #if defined(__serenity__) && defined(KERNEL) && !defined(BOOTSTRAPPER)
if (Kernel::current) if (Kernel::Thread::current)
stream << "\033[34;1m[" << *Kernel::current << "]\033[0m: "; stream << "\033[34;1m[" << *Kernel::Thread::current << "]\033[0m: ";
else else
stream << "\033[36;1m[Kernel]\033[0m: "; stream << "\033[36;1m[Kernel]\033[0m: ";
#endif #endif

View file

@ -159,7 +159,7 @@ static void dump(const RegisterState& regs)
{ {
u16 ss; u16 ss;
u32 esp; u32 esp;
if (!current || current->process().is_ring0()) { if (!Process::current || Process::current->is_ring0()) {
ss = regs.ss; ss = regs.ss;
esp = regs.esp; esp = regs.esp;
} else { } else {
@ -186,7 +186,7 @@ static void dump(const RegisterState& regs)
: "=a"(cr4)); : "=a"(cr4));
kprintf("cr0=%08x cr2=%08x cr3=%08x cr4=%08x\n", cr0, cr2, cr3, cr4); kprintf("cr0=%08x cr2=%08x cr3=%08x cr4=%08x\n", cr0, cr2, cr3, cr4);
if (current && current->process().validate_read((void*)regs.eip, 8)) { if (Process::current && Process::current->validate_read((void*)regs.eip, 8)) {
SmapDisabler disabler; SmapDisabler disabler;
u8* codeptr = (u8*)regs.eip; u8* codeptr = (u8*)regs.eip;
kprintf("code: %02x %02x %02x %02x %02x %02x %02x %02x\n", kprintf("code: %02x %02x %02x %02x %02x %02x %02x %02x\n",
@ -203,31 +203,31 @@ static void dump(const RegisterState& regs)
void handle_crash(RegisterState& regs, const char* description, int signal) void handle_crash(RegisterState& regs, const char* description, int signal)
{ {
if (!current) { if (!Process::current) {
kprintf("%s with !current\n", description); kprintf("%s with !current\n", description);
hang(); hang();
} }
// If a process crashed while inspecting another process, // If a process crashed while inspecting another process,
// make sure we switch back to the right page tables. // make sure we switch back to the right page tables.
MM.enter_process_paging_scope(current->process()); MM.enter_process_paging_scope(*Process::current);
kprintf("\033[31;1mCRASH: %s. %s: %s(%u)\033[0m\n", kprintf("\033[31;1mCRASH: %s. %s: %s(%u)\033[0m\n",
description, description,
current->process().is_ring0() ? "Kernel" : "Process", Process::current->is_ring0() ? "Kernel" : "Process",
current->process().name().characters(), Process::current->name().characters(),
current->pid()); Process::current->pid());
dump(regs); dump(regs);
if (current->process().is_ring0()) { if (Process::current->is_ring0()) {
kprintf("Oh shit, we've crashed in ring 0 :(\n"); kprintf("Oh shit, we've crashed in ring 0 :(\n");
dump_backtrace(); dump_backtrace();
hang(); hang();
} }
cli(); cli();
current->process().crash(signal, regs.eip); Process::current->crash(signal, regs.eip);
} }
EH_ENTRY_NO_CODE(6, illegal_instruction); EH_ENTRY_NO_CODE(6, illegal_instruction);
@ -274,8 +274,8 @@ void page_fault_handler(RegisterState regs)
#ifdef PAGE_FAULT_DEBUG #ifdef PAGE_FAULT_DEBUG
u32 fault_page_directory = read_cr3(); u32 fault_page_directory = read_cr3();
dbgprintf("%s(%u): ring%u %s page fault in PD=%x, %s%s V%08x\n", dbgprintf("%s(%u): ring%u %s page fault in PD=%x, %s%s V%08x\n",
current ? current->process().name().characters() : "(none)", current ? Process::current->name().characters() : "(none)",
current ? current->pid() : 0, current ? Process::current->pid() : 0,
regs.cs & 3, regs.cs & 3,
regs.exception_code & 1 ? "PV" : "NP", regs.exception_code & 1 ? "PV" : "NP",
fault_page_directory, fault_page_directory,
@ -289,7 +289,7 @@ void page_fault_handler(RegisterState regs)
#endif #endif
bool faulted_in_userspace = (regs.cs & 3) == 3; bool faulted_in_userspace = (regs.cs & 3) == 3;
if (faulted_in_userspace && !MM.validate_user_stack(current->process(), VirtualAddress(regs.userspace_esp))) { if (faulted_in_userspace && !MM.validate_user_stack(*Process::current, VirtualAddress(regs.userspace_esp))) {
dbgprintf("Invalid stack pointer: %p\n", regs.userspace_esp); dbgprintf("Invalid stack pointer: %p\n", regs.userspace_esp);
handle_crash(regs, "Bad stack on page fault", SIGSTKFLT); handle_crash(regs, "Bad stack on page fault", SIGSTKFLT);
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
@ -298,15 +298,15 @@ void page_fault_handler(RegisterState regs)
auto response = MM.handle_page_fault(PageFault(regs.exception_code, VirtualAddress(fault_address))); auto response = MM.handle_page_fault(PageFault(regs.exception_code, VirtualAddress(fault_address)));
if (response == PageFaultResponse::ShouldCrash) { if (response == PageFaultResponse::ShouldCrash) {
if (current->has_signal_handler(SIGSEGV)) { if (Thread::current->has_signal_handler(SIGSEGV)) {
current->send_urgent_signal_to_self(SIGSEGV); Thread::current->send_urgent_signal_to_self(SIGSEGV);
return; return;
} }
kprintf("\033[31;1m%s(%u:%u) Unrecoverable page fault, %s%s%s address %p\033[0m\n", kprintf("\033[31;1m%s(%u:%u) Unrecoverable page fault, %s%s%s address %p\033[0m\n",
current->process().name().characters(), Process::current->name().characters(),
current->pid(), Process::current->pid(),
current->tid(), Thread::current->tid(),
regs.exception_code & PageFaultFlags::ReservedBitViolation ? "reserved bit violation / " : "", regs.exception_code & PageFaultFlags::ReservedBitViolation ? "reserved bit violation / " : "",
regs.exception_code & PageFaultFlags::InstructionFetch ? "instruction fetch / " : "", regs.exception_code & PageFaultFlags::InstructionFetch ? "instruction fetch / " : "",
regs.exception_code & PageFaultFlags::Write ? "write to" : "read from", regs.exception_code & PageFaultFlags::Write ? "write to" : "read from",
@ -720,8 +720,8 @@ void __assertion_failed(const char* msg, const char* file, unsigned line, const
// Switch back to the current process's page tables if there are any. // Switch back to the current process's page tables if there are any.
// Otherwise stack walking will be a disaster. // Otherwise stack walking will be a disaster.
if (Kernel::current) if (Process::current)
MM.enter_process_paging_scope(Kernel::current->process()); MM.enter_process_paging_scope(*Process::current);
Kernel::dump_backtrace(); Kernel::dump_backtrace();
asm volatile("hlt"); asm volatile("hlt");

View file

@ -141,14 +141,14 @@ int BXVGADevice::ioctl(FileDescription&, unsigned request, unsigned arg)
switch (request) { switch (request) {
case FB_IOCTL_GET_SIZE_IN_BYTES: { case FB_IOCTL_GET_SIZE_IN_BYTES: {
auto* out = (size_t*)arg; auto* out = (size_t*)arg;
if (!current->process().validate_write_typed(out)) if (!Process::current->validate_write_typed(out))
return -EFAULT; return -EFAULT;
*out = framebuffer_size_in_bytes(); *out = framebuffer_size_in_bytes();
return 0; return 0;
} }
case FB_IOCTL_GET_BUFFER: { case FB_IOCTL_GET_BUFFER: {
auto* index = (int*)arg; auto* index = (int*)arg;
if (!current->process().validate_write_typed(index)) if (!Process::current->validate_write_typed(index))
return -EFAULT; return -EFAULT;
*index = m_y_offset == 0 ? 0 : 1; *index = m_y_offset == 0 ? 0 : 1;
return 0; return 0;
@ -161,7 +161,7 @@ int BXVGADevice::ioctl(FileDescription&, unsigned request, unsigned arg)
} }
case FB_IOCTL_GET_RESOLUTION: { case FB_IOCTL_GET_RESOLUTION: {
auto* resolution = (FBResolution*)arg; auto* resolution = (FBResolution*)arg;
if (!current->process().validate_write_typed(resolution)) if (!Process::current->validate_write_typed(resolution))
return -EFAULT; return -EFAULT;
resolution->pitch = m_framebuffer_pitch; resolution->pitch = m_framebuffer_pitch;
resolution->width = m_framebuffer_width; resolution->width = m_framebuffer_width;
@ -170,7 +170,7 @@ int BXVGADevice::ioctl(FileDescription&, unsigned request, unsigned arg)
} }
case FB_IOCTL_SET_RESOLUTION: { case FB_IOCTL_SET_RESOLUTION: {
auto* resolution = (FBResolution*)arg; auto* resolution = (FBResolution*)arg;
if (!current->process().validate_read_typed(resolution) || !current->process().validate_write_typed(resolution)) if (!Process::current->validate_read_typed(resolution) || !Process::current->validate_write_typed(resolution))
return -EFAULT; return -EFAULT;
if (resolution->width > MAX_RESOLUTION_WIDTH || resolution->height > MAX_RESOLUTION_HEIGHT) if (resolution->width > MAX_RESOLUTION_WIDTH || resolution->height > MAX_RESOLUTION_HEIGHT)
return -EINVAL; return -EINVAL;

View file

@ -77,21 +77,21 @@ int MBVGADevice::ioctl(FileDescription&, unsigned request, unsigned arg)
switch (request) { switch (request) {
case FB_IOCTL_GET_SIZE_IN_BYTES: { case FB_IOCTL_GET_SIZE_IN_BYTES: {
auto* out = (size_t*)arg; auto* out = (size_t*)arg;
if (!current->process().validate_write_typed(out)) if (!Process::current->validate_write_typed(out))
return -EFAULT; return -EFAULT;
*out = framebuffer_size_in_bytes(); *out = framebuffer_size_in_bytes();
return 0; return 0;
} }
case FB_IOCTL_GET_BUFFER: { case FB_IOCTL_GET_BUFFER: {
auto* index = (int*)arg; auto* index = (int*)arg;
if (!current->process().validate_write_typed(index)) if (!Process::current->validate_write_typed(index))
return -EFAULT; return -EFAULT;
*index = 0; *index = 0;
return 0; return 0;
} }
case FB_IOCTL_GET_RESOLUTION: { case FB_IOCTL_GET_RESOLUTION: {
auto* resolution = (FBResolution*)arg; auto* resolution = (FBResolution*)arg;
if (!current->process().validate_write_typed(resolution)) if (!Process::current->validate_write_typed(resolution))
return -EFAULT; return -EFAULT;
resolution->pitch = m_framebuffer_pitch; resolution->pitch = m_framebuffer_pitch;
resolution->width = m_framebuffer_width; resolution->width = m_framebuffer_width;
@ -100,7 +100,7 @@ int MBVGADevice::ioctl(FileDescription&, unsigned request, unsigned arg)
} }
case FB_IOCTL_SET_RESOLUTION: { case FB_IOCTL_SET_RESOLUTION: {
auto* resolution = (FBResolution*)arg; auto* resolution = (FBResolution*)arg;
if (!current->process().validate_read_typed(resolution) || !current->process().validate_write_typed(resolution)) if (!Process::current->validate_read_typed(resolution) || !Process::current->validate_write_typed(resolution))
return -EFAULT; return -EFAULT;
resolution->pitch = m_framebuffer_pitch; resolution->pitch = m_framebuffer_pitch;
resolution->width = m_framebuffer_width; resolution->width = m_framebuffer_width;

View file

@ -184,7 +184,7 @@ void PATAChannel::wait_for_irq()
{ {
cli(); cli();
enable_irq(); enable_irq();
current->wait_on(m_irq_queue); Thread::current->wait_on(m_irq_queue);
disable_irq(); disable_irq();
} }
@ -279,8 +279,8 @@ bool PATAChannel::ata_read_sectors_with_dma(u32 lba, u16 count, u8* outbuf, bool
LOCKER(s_lock()); LOCKER(s_lock());
#ifdef PATA_DEBUG #ifdef PATA_DEBUG
kprintf("%s(%u): PATAChannel::ata_read_sectors_with_dma (%u x%u) -> %p\n", kprintf("%s(%u): PATAChannel::ata_read_sectors_with_dma (%u x%u) -> %p\n",
current->process().name().characters(), Process::current->name().characters(),
current->pid(), lba, count, outbuf); Process::current->pid(), lba, count, outbuf);
#endif #endif
prdt().offset = m_dma_buffer_page->paddr(); prdt().offset = m_dma_buffer_page->paddr();
@ -352,8 +352,8 @@ bool PATAChannel::ata_write_sectors_with_dma(u32 lba, u16 count, const u8* inbuf
LOCKER(s_lock()); LOCKER(s_lock());
#ifdef PATA_DEBUG #ifdef PATA_DEBUG
kprintf("%s(%u): PATAChannel::ata_write_sectors_with_dma (%u x%u) <- %p\n", kprintf("%s(%u): PATAChannel::ata_write_sectors_with_dma (%u x%u) <- %p\n",
current->process().name().characters(), Process::current->name().characters(),
current->pid(), lba, count, inbuf); Process::current->pid(), lba, count, inbuf);
#endif #endif
prdt().offset = m_dma_buffer_page->paddr(); prdt().offset = m_dma_buffer_page->paddr();
@ -423,8 +423,8 @@ bool PATAChannel::ata_read_sectors(u32 start_sector, u16 count, u8* outbuf, bool
LOCKER(s_lock()); LOCKER(s_lock());
#ifdef PATA_DEBUG #ifdef PATA_DEBUG
kprintf("%s(%u): PATAChannel::ata_read_sectors request (%u sector(s) @ %u into %p)\n", kprintf("%s(%u): PATAChannel::ata_read_sectors request (%u sector(s) @ %u into %p)\n",
current->process().name().characters(), Process::current->name().characters(),
current->pid(), Process::current->pid(),
count, count,
start_sector, start_sector,
outbuf); outbuf);
@ -481,8 +481,8 @@ bool PATAChannel::ata_write_sectors(u32 start_sector, u16 count, const u8* inbuf
LOCKER(s_lock()); LOCKER(s_lock());
#ifdef PATA_DEBUG #ifdef PATA_DEBUG
kprintf("%s(%u): PATAChannel::ata_write_sectors request (%u sector(s) @ %u)\n", kprintf("%s(%u): PATAChannel::ata_write_sectors request (%u sector(s) @ %u)\n",
current->process().name().characters(), Process::current->name().characters(),
current->pid(), Process::current->pid(),
count, count,
start_sector); start_sector);
#endif #endif

View file

@ -171,7 +171,7 @@ void SB16::wait_for_irq()
{ {
cli(); cli();
enable_irq(); enable_irq();
current->wait_on(m_irq_queue); Thread::current->wait_on(m_irq_queue);
disable_irq(); disable_irq();
} }

View file

@ -132,7 +132,7 @@ ssize_t FIFO::read(FileDescription&, u8* buffer, ssize_t size)
ssize_t FIFO::write(FileDescription&, const u8* buffer, ssize_t size) ssize_t FIFO::write(FileDescription&, const u8* buffer, ssize_t size)
{ {
if (!m_readers) { if (!m_readers) {
current->send_signal(SIGPIPE, &current->process()); Thread::current->send_signal(SIGPIPE, Process::current);
return -EPIPE; return -EPIPE;
} }
#ifdef FIFO_DEBUG #ifdef FIFO_DEBUG

View file

@ -45,7 +45,7 @@ ssize_t InodeFile::read(FileDescription& description, u8* buffer, ssize_t count)
{ {
ssize_t nread = m_inode->read_bytes(description.offset(), count, buffer, &description); ssize_t nread = m_inode->read_bytes(description.offset(), count, buffer, &description);
if (nread > 0) if (nread > 0)
current->did_file_read(nread); Thread::current->did_file_read(nread);
return nread; return nread;
} }
@ -54,7 +54,7 @@ ssize_t InodeFile::write(FileDescription& description, const u8* data, ssize_t c
ssize_t nwritten = m_inode->write_bytes(description.offset(), count, data, &description); ssize_t nwritten = m_inode->write_bytes(description.offset(), count, data, &description);
if (nwritten > 0) { if (nwritten > 0) {
m_inode->set_mtime(kgettimeofday().tv_sec); m_inode->set_mtime(kgettimeofday().tv_sec);
current->did_file_write(nwritten); Thread::current->did_file_write(nwritten);
} }
return nwritten; return nwritten;
} }

View file

@ -292,7 +292,7 @@ Optional<KBuffer> procfs$pid_vm(InodeIdentifier identifier)
KBufferBuilder builder; KBufferBuilder builder;
JsonArraySerializer array { builder }; JsonArraySerializer array { builder };
for (auto& region : process.regions()) { for (auto& region : process.regions()) {
if (!region.is_user_accessible() && !current->process().is_superuser()) if (!region.is_user_accessible() && !Process::current->is_superuser())
continue; continue;
auto region_object = array.add_object(); auto region_object = array.add_object();
region_object.add("readable", region.is_readable()); region_object.add("readable", region.is_readable());
@ -399,7 +399,7 @@ Optional<KBuffer> procfs$profile(InodeIdentifier)
InterruptDisabler disabler; InterruptDisabler disabler;
KBufferBuilder builder; KBufferBuilder builder;
JsonArraySerializer array(builder); JsonArraySerializer array(builder);
bool mask_kernel_addresses = !current->process().is_superuser(); bool mask_kernel_addresses = !Process::current->is_superuser();
Profiling::for_each_sample([&](auto& sample) { Profiling::for_each_sample([&](auto& sample) {
auto object = array.add_object(); auto object = array.add_object();
object.add("pid", sample.pid); object.add("pid", sample.pid);
@ -640,7 +640,7 @@ Optional<KBuffer> procfs$pid_root(InodeIdentifier identifier)
Optional<KBuffer> procfs$self(InodeIdentifier) Optional<KBuffer> procfs$self(InodeIdentifier)
{ {
char buffer[16]; char buffer[16];
sprintf(buffer, "%u", current->pid()); sprintf(buffer, "%u", Process::current->pid());
return KBuffer::copy((const u8*)buffer, strlen(buffer)); return KBuffer::copy((const u8*)buffer, strlen(buffer));
} }

View file

@ -192,7 +192,7 @@ KResult VFS::utime(StringView path, Custody& base, time_t atime, time_t mtime)
auto& inode = *descriptor_or_error.value()->inode(); auto& inode = *descriptor_or_error.value()->inode();
if (inode.fs().is_readonly()) if (inode.fs().is_readonly())
return KResult(-EROFS); return KResult(-EROFS);
if (!current->process().is_superuser() && inode.metadata().uid != current->process().euid()) if (!Process::current->is_superuser() && inode.metadata().uid != Process::current->euid())
return KResult(-EACCES); return KResult(-EACCES);
int error = inode.set_atime(atime); int error = inode.set_atime(atime);
@ -242,18 +242,18 @@ KResultOr<NonnullRefPtr<FileDescription>> VFS::open(StringView path, int options
bool should_truncate_file = false; bool should_truncate_file = false;
if ((options & O_RDONLY) && !metadata.may_read(current->process())) if ((options & O_RDONLY) && !metadata.may_read(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
if (options & O_WRONLY) { if (options & O_WRONLY) {
if (!metadata.may_write(current->process())) if (!metadata.may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
if (metadata.is_directory()) if (metadata.is_directory())
return KResult(-EISDIR); return KResult(-EISDIR);
should_truncate_file = options & O_TRUNC; should_truncate_file = options & O_TRUNC;
} }
if (options & O_EXEC) { if (options & O_EXEC) {
if (!metadata.may_execute(current->process()) || (custody.mount_flags() & MS_NOEXEC)) if (!metadata.may_execute(*Process::current) || (custody.mount_flags() & MS_NOEXEC))
return KResult(-EACCES); return KResult(-EACCES);
} }
@ -297,12 +297,12 @@ KResult VFS::mknod(StringView path, mode_t mode, dev_t dev, Custody& base)
if (existing_file_or_error.error() != -ENOENT) if (existing_file_or_error.error() != -ENOENT)
return existing_file_or_error.error(); return existing_file_or_error.error();
auto& parent_inode = parent_custody->inode(); auto& parent_inode = parent_custody->inode();
if (!parent_inode.metadata().may_write(current->process())) if (!parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
FileSystemPath p(path); FileSystemPath p(path);
dbg() << "VFS::mknod: '" << p.basename() << "' mode=" << mode << " dev=" << dev << " in " << parent_inode.identifier(); dbg() << "VFS::mknod: '" << p.basename() << "' mode=" << mode << " dev=" << dev << " in " << parent_inode.identifier();
return parent_inode.fs().create_inode(parent_inode.identifier(), p.basename(), mode, 0, dev, current->process().uid(), current->process().gid()).result(); return parent_inode.fs().create_inode(parent_inode.identifier(), p.basename(), mode, 0, dev, Process::current->uid(), Process::current->gid()).result();
} }
KResultOr<NonnullRefPtr<FileDescription>> VFS::create(StringView path, int options, mode_t mode, Custody& parent_custody, Optional<UidAndGid> owner) KResultOr<NonnullRefPtr<FileDescription>> VFS::create(StringView path, int options, mode_t mode, Custody& parent_custody, Optional<UidAndGid> owner)
@ -313,14 +313,14 @@ KResultOr<NonnullRefPtr<FileDescription>> VFS::create(StringView path, int optio
} }
auto& parent_inode = parent_custody.inode(); auto& parent_inode = parent_custody.inode();
if (!parent_inode.metadata().may_write(current->process())) if (!parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
FileSystemPath p(path); FileSystemPath p(path);
#ifdef VFS_DEBUG #ifdef VFS_DEBUG
dbg() << "VFS::create: '" << p.basename() << "' in " << parent_inode.identifier(); dbg() << "VFS::create: '" << p.basename() << "' in " << parent_inode.identifier();
#endif #endif
uid_t uid = owner.has_value() ? owner.value().uid : current->process().uid(); uid_t uid = owner.has_value() ? owner.value().uid : Process::current->uid();
gid_t gid = owner.has_value() ? owner.value().gid : current->process().gid(); gid_t gid = owner.has_value() ? owner.value().gid : Process::current->gid();
auto inode_or_error = parent_inode.fs().create_inode(parent_inode.identifier(), p.basename(), mode, 0, 0, uid, gid); auto inode_or_error = parent_inode.fs().create_inode(parent_inode.identifier(), p.basename(), mode, 0, 0, uid, gid);
if (inode_or_error.is_error()) if (inode_or_error.is_error())
return inode_or_error.error(); return inode_or_error.error();
@ -344,14 +344,14 @@ KResult VFS::mkdir(StringView path, mode_t mode, Custody& base)
return result.error(); return result.error();
auto& parent_inode = parent_custody->inode(); auto& parent_inode = parent_custody->inode();
if (!parent_inode.metadata().may_write(current->process())) if (!parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
FileSystemPath p(path); FileSystemPath p(path);
#ifdef VFS_DEBUG #ifdef VFS_DEBUG
dbg() << "VFS::mkdir: '" << p.basename() << "' in " << parent_inode.identifier(); dbg() << "VFS::mkdir: '" << p.basename() << "' in " << parent_inode.identifier();
#endif #endif
return parent_inode.fs().create_directory(parent_inode.identifier(), p.basename(), mode, current->process().uid(), current->process().gid()); return parent_inode.fs().create_directory(parent_inode.identifier(), p.basename(), mode, Process::current->uid(), Process::current->gid());
} }
KResult VFS::access(StringView path, int mode, Custody& base) KResult VFS::access(StringView path, int mode, Custody& base)
@ -363,15 +363,15 @@ KResult VFS::access(StringView path, int mode, Custody& base)
auto& inode = custody.inode(); auto& inode = custody.inode();
auto metadata = inode.metadata(); auto metadata = inode.metadata();
if (mode & R_OK) { if (mode & R_OK) {
if (!metadata.may_read(current->process())) if (!metadata.may_read(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
} }
if (mode & W_OK) { if (mode & W_OK) {
if (!metadata.may_write(current->process())) if (!metadata.may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
} }
if (mode & X_OK) { if (mode & X_OK) {
if (!metadata.may_execute(current->process())) if (!metadata.may_execute(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
} }
return KSuccess; return KSuccess;
@ -386,7 +386,7 @@ KResultOr<NonnullRefPtr<Custody>> VFS::open_directory(StringView path, Custody&
auto& inode = custody.inode(); auto& inode = custody.inode();
if (!inode.is_directory()) if (!inode.is_directory())
return KResult(-ENOTDIR); return KResult(-ENOTDIR);
if (!inode.metadata().may_execute(current->process())) if (!inode.metadata().may_execute(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
return custody; return custody;
} }
@ -396,7 +396,7 @@ KResult VFS::chmod(Inode& inode, mode_t mode)
if (inode.fs().is_readonly()) if (inode.fs().is_readonly())
return KResult(-EROFS); return KResult(-EROFS);
if (current->process().euid() != inode.metadata().uid && !current->process().is_superuser()) if (Process::current->euid() != inode.metadata().uid && !Process::current->is_superuser())
return KResult(-EPERM); return KResult(-EPERM);
// Only change the permission bits. // Only change the permission bits.
@ -436,14 +436,14 @@ KResult VFS::rename(StringView old_path, StringView new_path, Custody& base)
if (&old_parent_inode.fs() != &new_parent_inode.fs()) if (&old_parent_inode.fs() != &new_parent_inode.fs())
return KResult(-EXDEV); return KResult(-EXDEV);
if (!new_parent_inode.metadata().may_write(current->process())) if (!new_parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
if (!old_parent_inode.metadata().may_write(current->process())) if (!old_parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
if (old_parent_inode.metadata().is_sticky()) { if (old_parent_inode.metadata().is_sticky()) {
if (!current->process().is_superuser() && old_inode.metadata().uid != current->process().euid()) if (!Process::current->is_superuser() && old_inode.metadata().uid != Process::current->euid())
return KResult(-EACCES); return KResult(-EACCES);
} }
@ -456,7 +456,7 @@ KResult VFS::rename(StringView old_path, StringView new_path, Custody& base)
if (&new_inode == &old_inode) if (&new_inode == &old_inode)
return KSuccess; return KSuccess;
if (new_parent_inode.metadata().is_sticky()) { if (new_parent_inode.metadata().is_sticky()) {
if (!current->process().is_superuser() && new_inode.metadata().uid != current->process().euid()) if (!Process::current->is_superuser() && new_inode.metadata().uid != Process::current->euid())
return KResult(-EACCES); return KResult(-EACCES);
} }
if (new_inode.is_directory() && !old_inode.is_directory()) if (new_inode.is_directory() && !old_inode.is_directory())
@ -486,19 +486,19 @@ KResult VFS::chown(Inode& inode, uid_t a_uid, gid_t a_gid)
auto metadata = inode.metadata(); auto metadata = inode.metadata();
if (current->process().euid() != metadata.uid && !current->process().is_superuser()) if (Process::current->euid() != metadata.uid && !Process::current->is_superuser())
return KResult(-EPERM); return KResult(-EPERM);
uid_t new_uid = metadata.uid; uid_t new_uid = metadata.uid;
gid_t new_gid = metadata.gid; gid_t new_gid = metadata.gid;
if (a_uid != (uid_t)-1) { if (a_uid != (uid_t)-1) {
if (current->process().euid() != a_uid && !current->process().is_superuser()) if (Process::current->euid() != a_uid && !Process::current->is_superuser())
return KResult(-EPERM); return KResult(-EPERM);
new_uid = a_uid; new_uid = a_uid;
} }
if (a_gid != (gid_t)-1) { if (a_gid != (gid_t)-1) {
if (!current->process().in_group(a_gid) && !current->process().is_superuser()) if (!Process::current->in_group(a_gid) && !Process::current->is_superuser())
return KResult(-EPERM); return KResult(-EPERM);
new_gid = a_gid; new_gid = a_gid;
} }
@ -541,7 +541,7 @@ KResult VFS::link(StringView old_path, StringView new_path, Custody& base)
if (parent_inode.fs().is_readonly()) if (parent_inode.fs().is_readonly())
return KResult(-EROFS); return KResult(-EROFS);
if (!parent_inode.metadata().may_write(current->process())) if (!parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
if (old_inode.is_directory()) if (old_inode.is_directory())
@ -563,11 +563,11 @@ KResult VFS::unlink(StringView path, Custody& base)
return KResult(-EISDIR); return KResult(-EISDIR);
auto& parent_inode = parent_custody->inode(); auto& parent_inode = parent_custody->inode();
if (!parent_inode.metadata().may_write(current->process())) if (!parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
if (parent_inode.metadata().is_sticky()) { if (parent_inode.metadata().is_sticky()) {
if (!current->process().is_superuser() && inode.metadata().uid != current->process().euid()) if (!Process::current->is_superuser() && inode.metadata().uid != Process::current->euid())
return KResult(-EACCES); return KResult(-EACCES);
} }
@ -590,12 +590,12 @@ KResult VFS::symlink(StringView target, StringView linkpath, Custody& base)
if (existing_custody_or_error.error() != -ENOENT) if (existing_custody_or_error.error() != -ENOENT)
return existing_custody_or_error.error(); return existing_custody_or_error.error();
auto& parent_inode = parent_custody->inode(); auto& parent_inode = parent_custody->inode();
if (!parent_inode.metadata().may_write(current->process())) if (!parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
FileSystemPath p(linkpath); FileSystemPath p(linkpath);
dbg() << "VFS::symlink: '" << p.basename() << "' (-> '" << target << "') in " << parent_inode.identifier(); dbg() << "VFS::symlink: '" << p.basename() << "' (-> '" << target << "') in " << parent_inode.identifier();
auto inode_or_error = parent_inode.fs().create_inode(parent_inode.identifier(), p.basename(), 0120644, 0, 0, current->process().uid(), current->process().gid()); auto inode_or_error = parent_inode.fs().create_inode(parent_inode.identifier(), p.basename(), 0120644, 0, 0, Process::current->uid(), Process::current->gid());
if (inode_or_error.is_error()) if (inode_or_error.is_error())
return inode_or_error.error(); return inode_or_error.error();
auto& inode = inode_or_error.value(); auto& inode = inode_or_error.value();
@ -625,7 +625,7 @@ KResult VFS::rmdir(StringView path, Custody& base)
auto& parent_inode = parent_custody->inode(); auto& parent_inode = parent_custody->inode();
if (!parent_inode.metadata().may_write(current->process())) if (!parent_inode.metadata().may_write(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
if (inode.directory_entry_count() != 2) if (inode.directory_entry_count() != 2)
@ -700,7 +700,7 @@ Custody& VFS::root_custody()
const UnveiledPath* VFS::find_matching_unveiled_path(StringView path) const UnveiledPath* VFS::find_matching_unveiled_path(StringView path)
{ {
for (auto& unveiled_path : current->process().unveiled_paths()) { for (auto& unveiled_path : Process::current->unveiled_paths()) {
if (path == unveiled_path.path) if (path == unveiled_path.path)
return &unveiled_path; return &unveiled_path;
if (path.starts_with(unveiled_path.path) && path.length() > unveiled_path.path.length() && path[unveiled_path.path.length()] == '/') if (path.starts_with(unveiled_path.path) && path.length() > unveiled_path.path.length() && path[unveiled_path.path.length()] == '/')
@ -711,7 +711,7 @@ const UnveiledPath* VFS::find_matching_unveiled_path(StringView path)
KResult VFS::validate_path_against_process_veil(StringView path, int options) KResult VFS::validate_path_against_process_veil(StringView path, int options)
{ {
if (current->process().veil_state() == VeilState::None) if (Process::current->veil_state() == VeilState::None)
return KSuccess; return KSuccess;
// FIXME: Figure out a nicer way to do this. // FIXME: Figure out a nicer way to do this.
@ -777,7 +777,7 @@ KResultOr<NonnullRefPtr<Custody>> VFS::resolve_path(StringView path, Custody& ba
return KResult(-EINVAL); return KResult(-EINVAL);
auto parts = path.split_view('/', true); auto parts = path.split_view('/', true);
auto& current_root = current->process().root_directory(); auto& current_root = Process::current->root_directory();
NonnullRefPtr<Custody> custody = path[0] == '/' ? current_root : base; NonnullRefPtr<Custody> custody = path[0] == '/' ? current_root : base;
@ -787,7 +787,7 @@ KResultOr<NonnullRefPtr<Custody>> VFS::resolve_path(StringView path, Custody& ba
if (!parent_metadata.is_directory()) if (!parent_metadata.is_directory())
return KResult(-ENOTDIR); return KResult(-ENOTDIR);
// Ensure the current user is allowed to resolve paths inside this directory. // Ensure the current user is allowed to resolve paths inside this directory.
if (!parent_metadata.may_execute(current->process())) if (!parent_metadata.may_execute(*Process::current))
return KResult(-EACCES); return KResult(-EACCES);
auto& part = parts[i]; auto& part = parts[i];

View file

@ -125,7 +125,7 @@ void* kmalloc_impl(size_t size)
if (sum_free < real_size) { if (sum_free < real_size) {
Kernel::dump_backtrace(); Kernel::dump_backtrace();
kprintf("%s(%u) kmalloc(): PANIC! Out of memory (sucks, dude)\nsum_free=%u, real_size=%u\n", Kernel::current->process().name().characters(), Kernel::current->pid(), sum_free, real_size); kprintf("%s(%u) kmalloc(): PANIC! Out of memory (sucks, dude)\nsum_free=%u, real_size=%u\n", Kernel::Process::current->name().characters(), Kernel::Process::current->pid(), sum_free, real_size);
Kernel::hang(); Kernel::hang();
} }
@ -177,7 +177,7 @@ void* kmalloc_impl(size_t size)
} }
} }
kprintf("%s(%u) kmalloc(): PANIC! Out of memory (no suitable block for size %u)\n", Kernel::current->process().name().characters(), Kernel::current->pid(), size); kprintf("%s(%u) kmalloc(): PANIC! Out of memory (no suitable block for size %u)\n", Kernel::Process::current->name().characters(), Kernel::Process::current->pid(), size);
Kernel::dump_backtrace(); Kernel::dump_backtrace();
Kernel::hang(); Kernel::hang();
} }

View file

@ -136,13 +136,13 @@ static void load_ksyms_from_data(const ByteBuffer& buffer)
int recognized_symbol_count = 0; int recognized_symbol_count = 0;
if (use_ksyms) { if (use_ksyms) {
for (u32* stack_ptr = (u32*)ebp; for (u32* stack_ptr = (u32*)ebp;
(current ? current->process().validate_read_from_kernel(VirtualAddress(stack_ptr), sizeof(void*) * 2) : 1) && recognized_symbol_count < max_recognized_symbol_count; stack_ptr = (u32*)*stack_ptr) { (Process::current ? Process::current->validate_read_from_kernel(VirtualAddress(stack_ptr), sizeof(void*) * 2) : 1) && recognized_symbol_count < max_recognized_symbol_count; stack_ptr = (u32*)*stack_ptr) {
u32 retaddr = stack_ptr[1]; u32 retaddr = stack_ptr[1];
recognized_symbols[recognized_symbol_count++] = { retaddr, ksymbolicate(retaddr) }; recognized_symbols[recognized_symbol_count++] = { retaddr, ksymbolicate(retaddr) };
} }
} else { } else {
for (u32* stack_ptr = (u32*)ebp; for (u32* stack_ptr = (u32*)ebp;
(current ? current->process().validate_read_from_kernel(VirtualAddress(stack_ptr), sizeof(void*) * 2) : 1); stack_ptr = (u32*)*stack_ptr) { (Process::current ? Process::current->validate_read_from_kernel(VirtualAddress(stack_ptr), sizeof(void*) * 2) : 1); stack_ptr = (u32*)*stack_ptr) {
u32 retaddr = stack_ptr[1]; u32 retaddr = stack_ptr[1];
dbgprintf("%x (next: %x)\n", retaddr, stack_ptr ? (u32*)*stack_ptr : 0); dbgprintf("%x (next: %x)\n", retaddr, stack_ptr ? (u32*)*stack_ptr : 0);
} }
@ -154,8 +154,8 @@ static void load_ksyms_from_data(const ByteBuffer& buffer)
if (!symbol.address) if (!symbol.address)
break; break;
if (!symbol.ksym) { if (!symbol.ksym) {
if (current && current->process().elf_loader() && current->process().elf_loader()->has_symbols()) { if (Process::current && Process::current->elf_loader() && Process::current->elf_loader()->has_symbols()) {
dbgprintf("%p %s\n", symbol.address, current->process().elf_loader()->symbolicate(symbol.address).characters()); dbgprintf("%p %s\n", symbol.address, Process::current->elf_loader()->symbolicate(symbol.address).characters());
} else { } else {
dbgprintf("%p (no ELF symbols for process)\n", symbol.address); dbgprintf("%p (no ELF symbols for process)\n", symbol.address);
} }

View file

@ -41,13 +41,13 @@ void Lock::lock()
for (;;) { for (;;) {
bool expected = false; bool expected = false;
if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) { if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
if (!m_holder || m_holder == current) { if (!m_holder || m_holder == Thread::current) {
m_holder = current; m_holder = Thread::current;
++m_level; ++m_level;
m_lock.store(false, AK::memory_order_release); m_lock.store(false, AK::memory_order_release);
return; return;
} }
current->wait_on(m_queue, &m_lock, m_holder, m_name); Thread::current->wait_on(m_queue, &m_lock, m_holder, m_name);
} }
} }
} }
@ -57,7 +57,7 @@ void Lock::unlock()
for (;;) { for (;;) {
bool expected = false; bool expected = false;
if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) { if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
ASSERT(m_holder == current); ASSERT(m_holder == Thread::current);
ASSERT(m_level); ASSERT(m_level);
--m_level; --m_level;
if (m_level) { if (m_level) {
@ -76,10 +76,10 @@ void Lock::unlock()
bool Lock::force_unlock_if_locked() bool Lock::force_unlock_if_locked()
{ {
InterruptDisabler disabler; InterruptDisabler disabler;
if (m_holder != current) if (m_holder != Thread::current)
return false; return false;
ASSERT(m_level == 1); ASSERT(m_level == 1);
ASSERT(m_holder == current); ASSERT(m_holder == Thread::current);
m_holder = nullptr; m_holder = nullptr;
--m_level; --m_level;
m_queue.wake_one(); m_queue.wake_one();

View file

@ -35,8 +35,6 @@
namespace Kernel { namespace Kernel {
extern Thread* current;
class Lock { class Lock {
public: public:
Lock(const char* name = nullptr) Lock(const char* name = nullptr)

View file

@ -395,7 +395,7 @@ void E1000NetworkAdapter::send_raw(const u8* data, size_t length)
sti(); sti();
break; break;
} }
current->wait_on(m_wait_queue); Thread::current->wait_on(m_wait_queue);
} }
#ifdef E1000_DEBUG #ifdef E1000_DEBUG
kprintf("E1000: Sent packet, status is now %b!\n", descriptor.status); kprintf("E1000: Sent packet, status is now %b!\n", descriptor.status);

View file

@ -68,7 +68,7 @@ IPv4Socket::IPv4Socket(int type, int protocol)
: Socket(AF_INET, type, protocol) : Socket(AF_INET, type, protocol)
{ {
#ifdef IPV4_SOCKET_DEBUG #ifdef IPV4_SOCKET_DEBUG
kprintf("%s(%u) IPv4Socket{%p} created with type=%u, protocol=%d\n", current->process().name().characters(), current->pid(), this, type, protocol); kprintf("%s(%u) IPv4Socket{%p} created with type=%u, protocol=%d\n", Process::current->name().characters(), Process::current->pid(), this, type, protocol);
#endif #endif
m_buffer_mode = type == SOCK_STREAM ? BufferMode::Bytes : BufferMode::Packets; m_buffer_mode = type == SOCK_STREAM ? BufferMode::Bytes : BufferMode::Packets;
if (m_buffer_mode == BufferMode::Bytes) { if (m_buffer_mode == BufferMode::Bytes) {
@ -111,9 +111,9 @@ KResult IPv4Socket::bind(const sockaddr* user_address, socklen_t address_size)
return KResult(-EINVAL); return KResult(-EINVAL);
auto requested_local_port = ntohs(address.sin_port); auto requested_local_port = ntohs(address.sin_port);
if (!current->process().is_superuser()) { if (!Process::current->is_superuser()) {
if (requested_local_port < 1024) { if (requested_local_port < 1024) {
dbg() << current->process() << " (uid " << current->process().uid() << ") attempted to bind " << class_name() << " to port " << requested_local_port; dbg() << Process::current << " (uid " << Process::current->uid() << ") attempted to bind " << class_name() << " to port " << requested_local_port;
return KResult(-EACCES); return KResult(-EACCES);
} }
} }
@ -232,7 +232,7 @@ ssize_t IPv4Socket::sendto(FileDescription&, const void* data, size_t data_lengt
int nsent = protocol_send(data, data_length); int nsent = protocol_send(data, data_length);
if (nsent > 0) if (nsent > 0)
current->did_ipv4_socket_write(nsent); Thread::current->did_ipv4_socket_write(nsent);
return nsent; return nsent;
} }
@ -244,7 +244,7 @@ ssize_t IPv4Socket::receive_byte_buffered(FileDescription& description, void* bu
if (!description.is_blocking()) if (!description.is_blocking())
return -EAGAIN; return -EAGAIN;
auto res = current->block<Thread::ReadBlocker>(description); auto res = Thread::current->block<Thread::ReadBlocker>(description);
LOCKER(lock()); LOCKER(lock());
if (!m_can_read) { if (!m_can_read) {
@ -259,7 +259,7 @@ ssize_t IPv4Socket::receive_byte_buffered(FileDescription& description, void* bu
ASSERT(!m_receive_buffer.is_empty()); ASSERT(!m_receive_buffer.is_empty());
int nreceived = m_receive_buffer.read((u8*)buffer, buffer_length); int nreceived = m_receive_buffer.read((u8*)buffer, buffer_length);
if (nreceived > 0) if (nreceived > 0)
current->did_ipv4_socket_read((size_t)nreceived); Thread::current->did_ipv4_socket_read((size_t)nreceived);
m_can_read = !m_receive_buffer.is_empty(); m_can_read = !m_receive_buffer.is_empty();
return nreceived; return nreceived;
@ -293,7 +293,7 @@ ssize_t IPv4Socket::receive_packet_buffered(FileDescription& description, void*
return 0; return 0;
} }
auto res = current->block<Thread::ReadBlocker>(description); auto res = Thread::current->block<Thread::ReadBlocker>(description);
LOCKER(lock()); LOCKER(lock());
if (!m_can_read) { if (!m_can_read) {
@ -351,7 +351,7 @@ ssize_t IPv4Socket::recvfrom(FileDescription& description, void* buffer, size_t
nreceived = receive_packet_buffered(description, buffer, buffer_length, flags, addr, addr_length); nreceived = receive_packet_buffered(description, buffer, buffer_length, flags, addr, addr_length);
if (nreceived > 0) if (nreceived > 0)
current->did_ipv4_socket_read(nreceived); Thread::current->did_ipv4_socket_read(nreceived);
return nreceived; return nreceived;
} }
@ -463,7 +463,7 @@ int IPv4Socket::ioctl(FileDescription&, unsigned request, unsigned arg)
{ {
REQUIRE_PROMISE(inet); REQUIRE_PROMISE(inet);
auto* ifr = (ifreq*)arg; auto* ifr = (ifreq*)arg;
if (!current->process().validate_read_typed(ifr)) if (!Process::current->validate_read_typed(ifr))
return -EFAULT; return -EFAULT;
char namebuf[IFNAMSIZ + 1]; char namebuf[IFNAMSIZ + 1];
@ -475,7 +475,7 @@ int IPv4Socket::ioctl(FileDescription&, unsigned request, unsigned arg)
switch (request) { switch (request) {
case SIOCSIFADDR: case SIOCSIFADDR:
if (!current->process().is_superuser()) if (!Process::current->is_superuser())
return -EPERM; return -EPERM;
if (ifr->ifr_addr.sa_family != AF_INET) if (ifr->ifr_addr.sa_family != AF_INET)
return -EAFNOSUPPORT; return -EAFNOSUPPORT;
@ -483,14 +483,14 @@ int IPv4Socket::ioctl(FileDescription&, unsigned request, unsigned arg)
return 0; return 0;
case SIOCGIFADDR: case SIOCGIFADDR:
if (!current->process().validate_write_typed(ifr)) if (!Process::current->validate_write_typed(ifr))
return -EFAULT; return -EFAULT;
ifr->ifr_addr.sa_family = AF_INET; ifr->ifr_addr.sa_family = AF_INET;
((sockaddr_in&)ifr->ifr_addr).sin_addr.s_addr = adapter->ipv4_address().to_u32(); ((sockaddr_in&)ifr->ifr_addr).sin_addr.s_addr = adapter->ipv4_address().to_u32();
return 0; return 0;
case SIOCGIFHWADDR: case SIOCGIFHWADDR:
if (!current->process().validate_write_typed(ifr)) if (!Process::current->validate_write_typed(ifr))
return -EFAULT; return -EFAULT;
ifr->ifr_hwaddr.sa_family = AF_INET; ifr->ifr_hwaddr.sa_family = AF_INET;
{ {

View file

@ -63,12 +63,12 @@ LocalSocket::LocalSocket(int type)
LOCKER(all_sockets().lock()); LOCKER(all_sockets().lock());
all_sockets().resource().append(this); all_sockets().resource().append(this);
m_prebind_uid = current->process().uid(); m_prebind_uid = Process::current->uid();
m_prebind_gid = current->process().gid(); m_prebind_gid = Process::current->gid();
m_prebind_mode = 0666; m_prebind_mode = 0666;
#ifdef DEBUG_LOCAL_SOCKET #ifdef DEBUG_LOCAL_SOCKET
kprintf("%s(%u) LocalSocket{%p} created with type=%u\n", current->process().name().characters(), current->pid(), this, type); kprintf("%s(%u) LocalSocket{%p} created with type=%u\n", Process::current->name().characters(), Process::current->pid(), this, type);
#endif #endif
} }
@ -105,12 +105,12 @@ KResult LocalSocket::bind(const sockaddr* user_address, socklen_t address_size)
auto path = String(address.sun_path, strnlen(address.sun_path, sizeof(address.sun_path))); auto path = String(address.sun_path, strnlen(address.sun_path, sizeof(address.sun_path)));
#ifdef DEBUG_LOCAL_SOCKET #ifdef DEBUG_LOCAL_SOCKET
kprintf("%s(%u) LocalSocket{%p} bind(%s)\n", current->process().name().characters(), current->pid(), this, safe_address); kprintf("%s(%u) LocalSocket{%p} bind(%s)\n", Process::current->name().characters(), Process::current->pid(), this, safe_address);
#endif #endif
mode_t mode = S_IFSOCK | (m_prebind_mode & 04777); mode_t mode = S_IFSOCK | (m_prebind_mode & 04777);
UidAndGid owner { m_prebind_uid, m_prebind_gid }; UidAndGid owner { m_prebind_uid, m_prebind_gid };
auto result = VFS::the().open(path, O_CREAT | O_EXCL | O_NOFOLLOW_NOERROR, mode, current->process().current_directory(), owner); auto result = VFS::the().open(path, O_CREAT | O_EXCL | O_NOFOLLOW_NOERROR, mode, Process::current->current_directory(), owner);
if (result.is_error()) { if (result.is_error()) {
if (result.error() == -EEXIST) if (result.error() == -EEXIST)
return KResult(-EADDRINUSE); return KResult(-EADDRINUSE);
@ -145,10 +145,10 @@ KResult LocalSocket::connect(FileDescription& description, const sockaddr* addre
memcpy(safe_address, local_address.sun_path, sizeof(local_address.sun_path)); memcpy(safe_address, local_address.sun_path, sizeof(local_address.sun_path));
#ifdef DEBUG_LOCAL_SOCKET #ifdef DEBUG_LOCAL_SOCKET
kprintf("%s(%u) LocalSocket{%p} connect(%s)\n", current->process().name().characters(), current->pid(), this, safe_address); kprintf("%s(%u) LocalSocket{%p} connect(%s)\n", Process::current->name().characters(), Process::current->pid(), this, safe_address);
#endif #endif
auto description_or_error = VFS::the().open(safe_address, O_RDWR, 0, current->process().current_directory()); auto description_or_error = VFS::the().open(safe_address, O_RDWR, 0, Process::current->current_directory());
if (description_or_error.is_error()) if (description_or_error.is_error())
return KResult(-ECONNREFUSED); return KResult(-ECONNREFUSED);
@ -175,13 +175,13 @@ KResult LocalSocket::connect(FileDescription& description, const sockaddr* addre
return KSuccess; return KSuccess;
} }
if (current->block<Thread::ConnectBlocker>(description) != Thread::BlockResult::WokeNormally) { if (Thread::current->block<Thread::ConnectBlocker>(description) != Thread::BlockResult::WokeNormally) {
m_connect_side_role = Role::None; m_connect_side_role = Role::None;
return KResult(-EINTR); return KResult(-EINTR);
} }
#ifdef DEBUG_LOCAL_SOCKET #ifdef DEBUG_LOCAL_SOCKET
kprintf("%s(%u) LocalSocket{%p} connect(%s) status is %s\n", current->process().name().characters(), current->pid(), this, safe_address, to_string(setup_state())); kprintf("%s(%u) LocalSocket{%p} connect(%s) status is %s\n", Process::current->name().characters(), Process::current->pid(), this, safe_address, to_string(setup_state()));
#endif #endif
if (!is_connected()) { if (!is_connected()) {
@ -265,7 +265,7 @@ ssize_t LocalSocket::sendto(FileDescription& description, const void* data, size
return -EPIPE; return -EPIPE;
ssize_t nwritten = send_buffer_for(description).write((const u8*)data, data_size); ssize_t nwritten = send_buffer_for(description).write((const u8*)data, data_size);
if (nwritten > 0) if (nwritten > 0)
current->did_unix_socket_write(nwritten); Thread::current->did_unix_socket_write(nwritten);
return nwritten; return nwritten;
} }
@ -299,7 +299,7 @@ ssize_t LocalSocket::recvfrom(FileDescription& description, void* buffer, size_t
return -EAGAIN; return -EAGAIN;
} }
} else if (!can_read(description)) { } else if (!can_read(description)) {
auto result = current->block<Thread::ReadBlocker>(description); auto result = Thread::current->block<Thread::ReadBlocker>(description);
if (result != Thread::BlockResult::WokeNormally) if (result != Thread::BlockResult::WokeNormally)
return -EINTR; return -EINTR;
} }
@ -308,7 +308,7 @@ ssize_t LocalSocket::recvfrom(FileDescription& description, void* buffer, size_t
ASSERT(!buffer_for_me.is_empty()); ASSERT(!buffer_for_me.is_empty());
int nread = buffer_for_me.read((u8*)buffer, buffer_size); int nread = buffer_for_me.read((u8*)buffer, buffer_size);
if (nread > 0) if (nread > 0)
current->did_unix_socket_read(nread); Thread::current->did_unix_socket_read(nread);
return nread; return nread;
} }
@ -389,7 +389,7 @@ KResult LocalSocket::chown(uid_t uid, gid_t gid)
if (m_file) if (m_file)
return m_file->chown(uid, gid); return m_file->chown(uid, gid);
if (!current->process().is_superuser() && (current->process().euid() != uid || !current->process().in_group(gid))) if (!Process::current->is_superuser() && (Process::current->euid() != uid || !Process::current->in_group(gid)))
return KResult(-EPERM); return KResult(-EPERM);
m_prebind_uid = uid; m_prebind_uid = uid;

View file

@ -109,7 +109,7 @@ void NetworkTask_main()
for (;;) { for (;;) {
size_t packet_size = dequeue_packet(buffer, buffer_size); size_t packet_size = dequeue_packet(buffer, buffer_size);
if (!packet_size) { if (!packet_size) {
current->wait_on(packet_wait_queue); Thread::current->wait_on(packet_wait_queue);
continue; continue;
} }
if (packet_size < sizeof(EthernetFrameHeader)) { if (packet_size < sizeof(EthernetFrameHeader)) {

View file

@ -137,7 +137,7 @@ RoutingDecision route_to(const IPv4Address& target, const IPv4Address& source)
request.set_sender_protocol_address(adapter->ipv4_address()); request.set_sender_protocol_address(adapter->ipv4_address());
adapter->send({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, request); adapter->send({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, request);
(void)current->block_until("Routing (ARP)", [next_hop_ip] { (void)Thread::current->block_until("Routing (ARP)", [next_hop_ip] {
return arp_table().resource().get(next_hop_ip).has_value(); return arp_table().resource().get(next_hop_ip).has_value();
}); });

View file

@ -54,7 +54,7 @@ Socket::Socket(int domain, int type, int protocol)
, m_type(type) , m_type(type)
, m_protocol(protocol) , m_protocol(protocol)
{ {
auto& process = current->process(); auto& process = *Process::current;
m_origin = { process.pid(), process.uid(), process.gid() }; m_origin = { process.pid(), process.uid(), process.gid() };
} }
@ -65,7 +65,7 @@ Socket::~Socket()
void Socket::set_setup_state(SetupState new_setup_state) void Socket::set_setup_state(SetupState new_setup_state)
{ {
#ifdef SOCKET_DEBUG #ifdef SOCKET_DEBUG
kprintf("%s(%u) Socket{%p} setup state moving from %s to %s\n", current->process().name().characters(), current->pid(), this, to_string(m_setup_state), to_string(new_setup_state)); kprintf("%s(%u) Socket{%p} setup state moving from %s to %s\n", Process::current->name().characters(), Process::current->pid(), this, to_string(m_setup_state), to_string(new_setup_state));
#endif #endif
m_setup_state = new_setup_state; m_setup_state = new_setup_state;
@ -77,11 +77,11 @@ RefPtr<Socket> Socket::accept()
if (m_pending.is_empty()) if (m_pending.is_empty())
return nullptr; return nullptr;
#ifdef SOCKET_DEBUG #ifdef SOCKET_DEBUG
kprintf("%s(%u) Socket{%p} de-queueing connection\n", current->process().name().characters(), current->pid(), this); kprintf("%s(%u) Socket{%p} de-queueing connection\n", Process::current->name().characters(), Process::current->pid(), this);
#endif #endif
auto client = m_pending.take_first(); auto client = m_pending.take_first();
ASSERT(!client->is_connected()); ASSERT(!client->is_connected());
auto& process = current->process(); auto& process = *Process::current;
client->m_acceptor = { process.pid(), process.uid(), process.gid() }; client->m_acceptor = { process.pid(), process.uid(), process.gid() };
client->m_connected = true; client->m_connected = true;
client->m_role = Role::Accepted; client->m_role = Role::Accepted;
@ -91,7 +91,7 @@ RefPtr<Socket> Socket::accept()
KResult Socket::queue_connection_from(NonnullRefPtr<Socket> peer) KResult Socket::queue_connection_from(NonnullRefPtr<Socket> peer)
{ {
#ifdef SOCKET_DEBUG #ifdef SOCKET_DEBUG
kprintf("%s(%u) Socket{%p} queueing connection\n", current->process().name().characters(), current->pid(), this); kprintf("%s(%u) Socket{%p} queueing connection\n", Process::current->name().characters(), Process::current->pid(), this);
#endif #endif
LOCKER(m_lock); LOCKER(m_lock);
if (m_pending.size() >= m_backlog) if (m_pending.size() >= m_backlog)

View file

@ -49,7 +49,7 @@ void TCPSocket::set_state(State new_state)
{ {
#ifdef TCP_SOCKET_DEBUG #ifdef TCP_SOCKET_DEBUG
kprintf("%s(%u) TCPSocket{%p} state moving from %s to %s\n", kprintf("%s(%u) TCPSocket{%p} state moving from %s to %s\n",
current->process().name().characters(), current->pid(), this, Process::current->name().characters(), Process::current->pid(), this,
to_string(m_state), to_string(new_state)); to_string(m_state), to_string(new_state));
#endif #endif
@ -385,7 +385,7 @@ KResult TCPSocket::protocol_connect(FileDescription& description, ShouldBlock sh
m_direction = Direction::Outgoing; m_direction = Direction::Outgoing;
if (should_block == ShouldBlock::Yes) { if (should_block == ShouldBlock::Yes) {
if (current->block<Thread::ConnectBlocker>(description) != Thread::BlockResult::WokeNormally) if (Thread::current->block<Thread::ConnectBlocker>(description) != Thread::BlockResult::WokeNormally)
return KResult(-EINTR); return KResult(-EINTR);
ASSERT(setup_state() == SetupState::Completed); ASSERT(setup_state() == SetupState::Completed);
if (has_error()) { if (has_error()) {

View file

@ -69,7 +69,7 @@ KResult PerformanceEventBuffer::append(int type, uintptr_t arg1, uintptr_t arg2)
Vector<uintptr_t> backtrace; Vector<uintptr_t> backtrace;
{ {
SmapDisabler disabler; SmapDisabler disabler;
backtrace = current->raw_backtrace(ebp); backtrace = Thread::current->raw_backtrace(ebp);
} }
event.stack_size = min(sizeof(event.stack) / sizeof(uintptr_t), static_cast<size_t>(backtrace.size())); event.stack_size = min(sizeof(event.stack) / sizeof(uintptr_t), static_cast<size_t>(backtrace.size()));
memcpy(event.stack, backtrace.data(), event.stack_size * sizeof(uintptr_t)); memcpy(event.stack, backtrace.data(), event.stack_size * sizeof(uintptr_t));

View file

@ -91,6 +91,8 @@ namespace Kernel {
static void create_signal_trampolines(); static void create_signal_trampolines();
static void create_kernel_info_page(); static void create_kernel_info_page();
Process* Process::current;
static pid_t next_pid; static pid_t next_pid;
InlineLinkedList<Process>* g_processes; InlineLinkedList<Process>* g_processes;
static String* s_hostname; static String* s_hostname;
@ -843,7 +845,7 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve
OwnPtr<ELFLoader> loader; OwnPtr<ELFLoader> loader;
{ {
ArmedScopeGuard rollback_regions_guard([&]() { ArmedScopeGuard rollback_regions_guard([&]() {
ASSERT(&current->process() == this); ASSERT(Process::current == this);
m_page_directory = move(old_page_directory); m_page_directory = move(old_page_directory);
m_regions = move(old_regions); m_regions = move(old_regions);
MM.enter_process_paging_scope(*this); MM.enter_process_paging_scope(*this);
@ -940,9 +942,9 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve
m_egid = main_program_metadata.gid; m_egid = main_program_metadata.gid;
} }
current->set_default_signal_dispositions(); Thread::current->set_default_signal_dispositions();
current->m_signal_mask = 0; Thread::current->m_signal_mask = 0;
current->m_pending_signals = 0; Thread::current->m_pending_signals = 0;
m_futex_queues.clear(); m_futex_queues.clear();
@ -955,8 +957,8 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve
} }
Thread* new_main_thread = nullptr; Thread* new_main_thread = nullptr;
if (&current->process() == this) { if (Process::current == this) {
new_main_thread = current; new_main_thread = Thread::current;
} else { } else {
for_each_thread([&](auto& thread) { for_each_thread([&](auto& thread) {
new_main_thread = &thread; new_main_thread = &thread;
@ -972,7 +974,7 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve
// We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield(). // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
// The reason is that the task redirection we've set up above will be clobbered by the timer IRQ. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
// If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec(). // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
if (&current->process() == this) if (Process::current == this)
cli(); cli();
// NOTE: Be careful to not trigger any page faults below! // NOTE: Be careful to not trigger any page faults below!
@ -1187,7 +1189,7 @@ int Process::exec(String path, Vector<String> arguments, Vector<String> environm
if (rc < 0) if (rc < 0)
return rc; return rc;
if (&current->process() == this) { if (Process::current == this) {
Scheduler::yield(); Scheduler::yield();
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
@ -1332,7 +1334,7 @@ Process::Process(Thread*& first_thread, const String& name, uid_t uid, gid_t gid
if (fork_parent) { if (fork_parent) {
// NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
first_thread = current->clone(*this); first_thread = Thread::current->clone(*this);
} else { } else {
// NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.) // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
first_thread = new Thread(*this); first_thread = new Thread(*this);
@ -1378,7 +1380,7 @@ void Process::sys$exit(int status)
m_termination_status = status; m_termination_status = status;
m_termination_signal = 0; m_termination_signal = 0;
die(); die();
current->die_if_needed(); Thread::current->die_if_needed();
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
@ -1451,7 +1453,7 @@ int Process::sys$sigreturn(RegisterState& registers)
//pop the stored eax, ebp, return address, handler and signal code //pop the stored eax, ebp, return address, handler and signal code
stack_ptr += 5; stack_ptr += 5;
current->m_signal_mask = *stack_ptr; Thread::current->m_signal_mask = *stack_ptr;
stack_ptr++; stack_ptr++;
//pop edi, esi, ebp, esp, ebx, edx, ecx and eax //pop edi, esi, ebp, esp, ebx, edx, ecx and eax
@ -1472,7 +1474,7 @@ void Process::crash(int signal, u32 eip)
{ {
ASSERT_INTERRUPTS_DISABLED(); ASSERT_INTERRUPTS_DISABLED();
ASSERT(!is_dead()); ASSERT(!is_dead());
ASSERT(&current->process() == this); ASSERT(Process::current == this);
if (eip >= 0xc0000000 && ksyms_ready) { if (eip >= 0xc0000000 && ksyms_ready) {
auto* ksym = ksymbolicate(eip); auto* ksym = ksymbolicate(eip);
@ -1490,7 +1492,7 @@ void Process::crash(int signal, u32 eip)
die(); die();
// We can not return from here, as there is nowhere // We can not return from here, as there is nowhere
// to unwind to, so die right away. // to unwind to, so die right away.
current->die_if_needed(); Thread::current->die_if_needed();
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
@ -1648,7 +1650,7 @@ ssize_t Process::do_write(FileDescription& description, const u8* data, int data
#ifdef IO_DEBUG #ifdef IO_DEBUG
dbgprintf("block write on %d\n", fd); dbgprintf("block write on %d\n", fd);
#endif #endif
if (current->block<Thread::WriteBlocker>(description) != Thread::BlockResult::WokeNormally) { if (Thread::current->block<Thread::WriteBlocker>(description) != Thread::BlockResult::WokeNormally) {
if (nwritten == 0) if (nwritten == 0)
return -EINTR; return -EINTR;
} }
@ -1711,7 +1713,7 @@ ssize_t Process::sys$read(int fd, u8* buffer, ssize_t size)
return -EISDIR; return -EISDIR;
if (description->is_blocking()) { if (description->is_blocking()) {
if (!description->can_read()) { if (!description->can_read()) {
if (current->block<Thread::ReadBlocker>(*description) != Thread::BlockResult::WokeNormally) if (Thread::current->block<Thread::ReadBlocker>(*description) != Thread::BlockResult::WokeNormally)
return -EINTR; return -EINTR;
if (!description->can_read()) if (!description->can_read())
return -EAGAIN; return -EAGAIN;
@ -2175,9 +2177,9 @@ int Process::sys$kill(pid_t pid, int signal)
if (pid == m_pid) { if (pid == m_pid) {
if (signal == 0) if (signal == 0)
return 0; return 0;
if (!current->should_ignore_signal(signal)) { if (!Thread::current->should_ignore_signal(signal)) {
current->send_signal(signal, this); Thread::current->send_signal(signal, this);
(void)current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal); (void)Thread::current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal);
} }
return 0; return 0;
} }
@ -2193,7 +2195,7 @@ int Process::sys$usleep(useconds_t usec)
REQUIRE_PROMISE(stdio); REQUIRE_PROMISE(stdio);
if (!usec) if (!usec)
return 0; return 0;
u64 wakeup_time = current->sleep(usec / 1000); u64 wakeup_time = Thread::current->sleep(usec / 1000);
if (wakeup_time > g_uptime) if (wakeup_time > g_uptime)
return -EINTR; return -EINTR;
return 0; return 0;
@ -2204,7 +2206,7 @@ int Process::sys$sleep(unsigned seconds)
REQUIRE_PROMISE(stdio); REQUIRE_PROMISE(stdio);
if (!seconds) if (!seconds)
return 0; return 0;
u64 wakeup_time = current->sleep(seconds * TICKS_PER_SECOND); u64 wakeup_time = Thread::current->sleep(seconds * TICKS_PER_SECOND);
if (wakeup_time > g_uptime) { if (wakeup_time > g_uptime) {
u32 ticks_left_until_original_wakeup_time = wakeup_time - g_uptime; u32 ticks_left_until_original_wakeup_time = wakeup_time - g_uptime;
return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND; return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
@ -2357,7 +2359,7 @@ KResultOr<siginfo_t> Process::do_waitid(idtype_t idtype, int id, int options)
return KResult(-EINVAL); return KResult(-EINVAL);
} }
if (current->block<Thread::WaitBlocker>(options, waitee_pid) != Thread::BlockResult::WokeNormally) if (Thread::current->block<Thread::WaitBlocker>(options, waitee_pid) != Thread::BlockResult::WokeNormally)
return KResult(-EINTR); return KResult(-EINTR);
InterruptDisabler disabler; InterruptDisabler disabler;
@ -2574,7 +2576,7 @@ int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
if (old_set) { if (old_set) {
if (!validate_write_typed(old_set)) if (!validate_write_typed(old_set))
return -EFAULT; return -EFAULT;
copy_to_user(old_set, &current->m_signal_mask); copy_to_user(old_set, &Thread::current->m_signal_mask);
} }
if (set) { if (set) {
if (!validate_read_typed(set)) if (!validate_read_typed(set))
@ -2583,13 +2585,13 @@ int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
copy_from_user(&set_value, set); copy_from_user(&set_value, set);
switch (how) { switch (how) {
case SIG_BLOCK: case SIG_BLOCK:
current->m_signal_mask &= ~set_value; Thread::current->m_signal_mask &= ~set_value;
break; break;
case SIG_UNBLOCK: case SIG_UNBLOCK:
current->m_signal_mask |= set_value; Thread::current->m_signal_mask |= set_value;
break; break;
case SIG_SETMASK: case SIG_SETMASK:
current->m_signal_mask = set_value; Thread::current->m_signal_mask = set_value;
break; break;
default: default:
return -EINVAL; return -EINVAL;
@ -2603,7 +2605,7 @@ int Process::sys$sigpending(sigset_t* set)
REQUIRE_PROMISE(stdio); REQUIRE_PROMISE(stdio);
if (!validate_write_typed(set)) if (!validate_write_typed(set))
return -EFAULT; return -EFAULT;
copy_to_user(set, &current->m_pending_signals); copy_to_user(set, &Thread::current->m_pending_signals);
return 0; return 0;
} }
@ -2615,7 +2617,7 @@ int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
if (!validate_read_typed(act)) if (!validate_read_typed(act))
return -EFAULT; return -EFAULT;
InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily? InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
auto& action = current->m_signal_action_data[signum]; auto& action = Thread::current->m_signal_action_data[signum];
if (old_act) { if (old_act) {
if (!validate_write_typed(old_act)) if (!validate_write_typed(old_act))
return -EFAULT; return -EFAULT;
@ -2783,7 +2785,7 @@ int Process::sys$select(const Syscall::SC_select_params* params)
#endif #endif
if (!timeout || select_has_timeout) { if (!timeout || select_has_timeout) {
if (current->block<Thread::SelectBlocker>(computed_timeout, select_has_timeout, rfds, wfds, efds) != Thread::BlockResult::WokeNormally) if (Thread::current->block<Thread::SelectBlocker>(computed_timeout, select_has_timeout, rfds, wfds, efds) != Thread::BlockResult::WokeNormally)
return -EINTR; return -EINTR;
} }
@ -2844,7 +2846,7 @@ int Process::sys$poll(pollfd* fds, int nfds, int timeout)
#endif #endif
if (has_timeout || timeout < 0) { if (has_timeout || timeout < 0) {
if (current->block<Thread::SelectBlocker>(actual_timeout, has_timeout, rfds, wfds, Thread::SelectBlocker::FDVector()) != Thread::BlockResult::WokeNormally) if (Thread::current->block<Thread::SelectBlocker>(actual_timeout, has_timeout, rfds, wfds, Thread::SelectBlocker::FDVector()) != Thread::BlockResult::WokeNormally)
return -EINTR; return -EINTR;
} }
@ -2981,7 +2983,7 @@ int Process::sys$chown(const Syscall::SC_chown_params* user_params)
void Process::finalize() void Process::finalize()
{ {
ASSERT(current == g_finalizer); ASSERT(Thread::current == g_finalizer);
#ifdef PROCESS_DEBUG #ifdef PROCESS_DEBUG
dbg() << "Finalizing process " << *this; dbg() << "Finalizing process " << *this;
#endif #endif
@ -3200,7 +3202,7 @@ int Process::sys$accept(int accepting_socket_fd, sockaddr* user_address, socklen
auto& socket = *accepting_socket_description->socket(); auto& socket = *accepting_socket_description->socket();
if (!socket.can_accept()) { if (!socket.can_accept()) {
if (accepting_socket_description->is_blocking()) { if (accepting_socket_description->is_blocking()) {
if (current->block<Thread::AcceptBlocker>(*accepting_socket_description) != Thread::BlockResult::WokeNormally) if (Thread::current->block<Thread::AcceptBlocker>(*accepting_socket_description) != Thread::BlockResult::WokeNormally)
return -EINTR; return -EINTR;
} else { } else {
return -EAGAIN; return -EAGAIN;
@ -3397,7 +3399,7 @@ int Process::sys$sched_setparam(int tid, const struct sched_param* param)
copy_from_user(&desired_priority, &param->sched_priority); copy_from_user(&desired_priority, &param->sched_priority);
InterruptDisabler disabler; InterruptDisabler disabler;
auto* peer = current; auto* peer = Thread::current;
if (tid != 0) if (tid != 0)
peer = Thread::from_tid(tid); peer = Thread::from_tid(tid);
@ -3421,7 +3423,7 @@ int Process::sys$sched_getparam(pid_t pid, struct sched_param* param)
return -EFAULT; return -EFAULT;
InterruptDisabler disabler; InterruptDisabler disabler;
auto* peer = current; auto* peer = Thread::current;
if (pid != 0) if (pid != 0)
peer = Thread::from_tid(pid); peer = Thread::from_tid(pid);
@ -3741,10 +3743,10 @@ void Process::sys$exit_thread(void* exit_value)
{ {
REQUIRE_PROMISE(thread); REQUIRE_PROMISE(thread);
cli(); cli();
current->m_exit_value = exit_value; Thread::current->m_exit_value = exit_value;
current->set_should_die(); Thread::current->set_should_die();
big_lock().force_unlock_if_locked(); big_lock().force_unlock_if_locked();
current->die_if_needed(); Thread::current->die_if_needed();
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
@ -3774,13 +3776,13 @@ int Process::sys$join_thread(int tid, void** exit_value)
if (!thread || thread->pid() != pid()) if (!thread || thread->pid() != pid())
return -ESRCH; return -ESRCH;
if (thread == current) if (thread == Thread::current)
return -EDEADLK; return -EDEADLK;
if (thread->m_joinee == current) if (thread->m_joinee == Thread::current)
return -EDEADLK; return -EDEADLK;
ASSERT(thread->m_joiner != current); ASSERT(thread->m_joiner != Thread::current);
if (thread->m_joiner) if (thread->m_joiner)
return -EINVAL; return -EINVAL;
@ -3791,13 +3793,13 @@ int Process::sys$join_thread(int tid, void** exit_value)
// NOTE: pthread_join() cannot be interrupted by signals. Only by death. // NOTE: pthread_join() cannot be interrupted by signals. Only by death.
for (;;) { for (;;) {
auto result = current->block<Thread::JoinBlocker>(*thread, joinee_exit_value); auto result = Thread::current->block<Thread::JoinBlocker>(*thread, joinee_exit_value);
if (result == Thread::BlockResult::InterruptedByDeath) { if (result == Thread::BlockResult::InterruptedByDeath) {
// NOTE: This cleans things up so that Thread::finalize() won't // NOTE: This cleans things up so that Thread::finalize() won't
// get confused about a missing joiner when finalizing the joinee. // get confused about a missing joiner when finalizing the joinee.
InterruptDisabler disabler; InterruptDisabler disabler;
current->m_joinee->m_joiner = nullptr; Thread::current->m_joinee->m_joiner = nullptr;
current->m_joinee = nullptr; Thread::current->m_joinee = nullptr;
return 0; return 0;
} }
} }
@ -3853,7 +3855,7 @@ int Process::sys$get_thread_name(int tid, char* buffer, size_t buffer_size)
int Process::sys$gettid() int Process::sys$gettid()
{ {
REQUIRE_PROMISE(stdio); REQUIRE_PROMISE(stdio);
return current->tid(); return Thread::current->tid();
} }
int Process::sys$donate(int tid) int Process::sys$donate(int tid)
@ -4259,12 +4261,12 @@ int Process::sys$clock_nanosleep(const Syscall::SC_clock_nanosleep_params* user_
u64 wakeup_time; u64 wakeup_time;
if (is_absolute) { if (is_absolute) {
u64 time_to_wake = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000); u64 time_to_wake = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
wakeup_time = current->sleep_until(time_to_wake); wakeup_time = Thread::current->sleep_until(time_to_wake);
} else { } else {
u32 ticks_to_sleep = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000); u32 ticks_to_sleep = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
if (!ticks_to_sleep) if (!ticks_to_sleep)
return 0; return 0;
wakeup_time = current->sleep(ticks_to_sleep); wakeup_time = Thread::current->sleep(ticks_to_sleep);
} }
if (wakeup_time > g_uptime) { if (wakeup_time > g_uptime) {
u32 ticks_left = wakeup_time - g_uptime; u32 ticks_left = wakeup_time - g_uptime;
@ -4295,14 +4297,14 @@ int Process::sys$sync()
int Process::sys$yield() int Process::sys$yield()
{ {
REQUIRE_PROMISE(stdio); REQUIRE_PROMISE(stdio);
current->yield_without_holding_big_lock(); Thread::current->yield_without_holding_big_lock();
return 0; return 0;
} }
int Process::sys$beep() int Process::sys$beep()
{ {
PCSpeaker::tone_on(440); PCSpeaker::tone_on(440);
u64 wakeup_time = current->sleep(100); u64 wakeup_time = Thread::current->sleep(100);
PCSpeaker::tone_off(); PCSpeaker::tone_off();
if (wakeup_time > g_uptime) if (wakeup_time > g_uptime)
return -EINTR; return -EINTR;
@ -4535,7 +4537,7 @@ int Process::sys$futex(const Syscall::SC_futex_params* user_params)
return -EAGAIN; return -EAGAIN;
// FIXME: This is supposed to be interruptible by a signal, but right now WaitQueue cannot be interrupted. // FIXME: This is supposed to be interruptible by a signal, but right now WaitQueue cannot be interrupted.
// FIXME: Support timeout! // FIXME: Support timeout!
current->wait_on(futex_queue(userspace_address)); Thread::current->wait_on(futex_queue(userspace_address));
break; break;
case FUTEX_WAKE: case FUTEX_WAKE:
if (value == 0) if (value == 0)

View file

@ -97,6 +97,8 @@ class Process : public InlineLinkedListNode<Process> {
friend class Thread; friend class Thread;
public: public:
static Process* current;
static Process* create_kernel_process(Thread*& first_thread, String&& name, void (*entry)()); static Process* create_kernel_process(Thread*& first_thread, String&& name, void (*entry)());
static Process* create_user_process(Thread*& first_thread, const String& path, uid_t, gid_t, pid_t ppid, int& error, Vector<String>&& arguments = Vector<String>(), Vector<String>&& environment = Vector<String>(), TTY* = nullptr); static Process* create_user_process(Thread*& first_thread, const String& path, uid_t, gid_t, pid_t ppid, int& error, Vector<String>&& arguments = Vector<String>(), Vector<String>&& environment = Vector<String>(), TTY* = nullptr);
~Process(); ~Process();
@ -519,14 +521,14 @@ public:
ProcessInspectionHandle(Process& process) ProcessInspectionHandle(Process& process)
: m_process(process) : m_process(process)
{ {
if (&process != &current->process()) { if (&process != Process::current) {
InterruptDisabler disabler; InterruptDisabler disabler;
m_process.increment_inspector_count({}); m_process.increment_inspector_count({});
} }
} }
~ProcessInspectionHandle() ~ProcessInspectionHandle()
{ {
if (&m_process != &current->process()) { if (&m_process != Process::current) {
InterruptDisabler disabler; InterruptDisabler disabler;
m_process.decrement_inspector_count({}); m_process.decrement_inspector_count({});
} }
@ -645,21 +647,21 @@ inline u32 Thread::effective_priority() const
#define REQUIRE_NO_PROMISES \ #define REQUIRE_NO_PROMISES \
do { \ do { \
if (current->process().has_promises()) { \ if (Process::current->has_promises()) { \
dbg() << "Has made a promise"; \ dbg() << "Has made a promise"; \
cli(); \ cli(); \
current->process().crash(SIGABRT, 0); \ Process::current->crash(SIGABRT, 0); \
ASSERT_NOT_REACHED(); \ ASSERT_NOT_REACHED(); \
} \ } \
} while (0) } while (0)
#define REQUIRE_PROMISE(promise) \ #define REQUIRE_PROMISE(promise) \
do { \ do { \
if (current->process().has_promises() \ if (Process::current->has_promises() \
&& !current->process().has_promised(Pledge::promise)) { \ && !Process::current->has_promised(Pledge::promise)) { \
dbg() << "Has not pledged " << #promise; \ dbg() << "Has not pledged " << #promise; \
cli(); \ cli(); \
current->process().crash(SIGABRT, 0); \ Process::current->crash(SIGABRT, 0); \
ASSERT_NOT_REACHED(); \ ASSERT_NOT_REACHED(); \
} \ } \
} while (0) } while (0)

View file

@ -67,7 +67,6 @@ static u32 time_slice_for(const Thread& thread)
return 10; return 10;
} }
Thread* current;
Thread* g_finalizer; Thread* g_finalizer;
Thread* g_colonel; Thread* g_colonel;
WaitQueue* g_finalizer_wait_queue; WaitQueue* g_finalizer_wait_queue;
@ -92,8 +91,8 @@ Thread::JoinBlocker::JoinBlocker(Thread& joinee, void*& joinee_exit_value)
, m_joinee_exit_value(joinee_exit_value) , m_joinee_exit_value(joinee_exit_value)
{ {
ASSERT(m_joinee.m_joiner == nullptr); ASSERT(m_joinee.m_joiner == nullptr);
m_joinee.m_joiner = current; m_joinee.m_joiner = Thread::current;
current->m_joinee = &joinee; Thread::current->m_joinee = &joinee;
} }
bool Thread::JoinBlocker::should_unblock(Thread& joiner, time_t, long) bool Thread::JoinBlocker::should_unblock(Thread& joiner, time_t, long)
@ -320,7 +319,7 @@ bool Scheduler::pick_next()
ASSERT(s_active); ASSERT(s_active);
if (!current) { if (!Thread::current) {
// XXX: The first ever context_switch() goes to the idle process. // XXX: The first ever context_switch() goes to the idle process.
// This to setup a reliable place we can return to. // This to setup a reliable place we can return to.
return context_switch(*g_colonel); return context_switch(*g_colonel);
@ -340,7 +339,7 @@ bool Scheduler::pick_next()
Process::for_each([&](Process& process) { Process::for_each([&](Process& process) {
if (process.is_dead()) { if (process.is_dead()) {
if (current->pid() != process.pid() && (!process.ppid() || !Process::from_pid(process.ppid()))) { if (Process::current->pid() != process.pid() && (!process.ppid() || !Process::from_pid(process.ppid()))) {
auto name = process.name(); auto name = process.name();
auto pid = process.pid(); auto pid = process.pid();
auto exit_status = Process::reap(process); auto exit_status = Process::reap(process);
@ -362,7 +361,7 @@ bool Scheduler::pick_next()
// FIXME: It would be nice if the Scheduler didn't have to worry about who is "current" // FIXME: It would be nice if the Scheduler didn't have to worry about who is "current"
// For now, avoid dispatching signals to "current" and do it in a scheduling pass // For now, avoid dispatching signals to "current" and do it in a scheduling pass
// while some other process is interrupted. Otherwise a mess will be made. // while some other process is interrupted. Otherwise a mess will be made.
if (&thread == current) if (&thread == Thread::current)
return IterationDecision::Continue; return IterationDecision::Continue;
// We know how to interrupt blocked processes, but if they are just executing // We know how to interrupt blocked processes, but if they are just executing
// at some random point in the kernel, let them continue. // at some random point in the kernel, let them continue.
@ -442,13 +441,13 @@ bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
return false; return false;
(void)reason; (void)reason;
unsigned ticks_left = current->ticks_left(); unsigned ticks_left = Thread::current->ticks_left();
if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1) if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
return yield(); return yield();
unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary)); unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary));
#ifdef SCHEDULER_DEBUG #ifdef SCHEDULER_DEBUG
dbgprintf("%s(%u:%u) donating %u ticks to %s(%u:%u), reason=%s\n", current->process().name().characters(), current->pid(), current->tid(), ticks_to_donate, beneficiary->process().name().characters(), beneficiary->pid(), beneficiary->tid(), reason); dbgprintf("%s(%u:%u) donating %u ticks to %s(%u:%u), reason=%s\n", Process::current->name().characters(), Process::current->pid(), Thread::current->tid(), ticks_to_donate, beneficiary->process().name().characters(), beneficiary->pid(), beneficiary->tid(), reason);
#endif #endif
context_switch(*beneficiary); context_switch(*beneficiary);
beneficiary->set_ticks_left(ticks_to_donate); beneficiary->set_ticks_left(ticks_to_donate);
@ -459,7 +458,7 @@ bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
bool Scheduler::yield() bool Scheduler::yield()
{ {
InterruptDisabler disabler; InterruptDisabler disabler;
ASSERT(current); ASSERT(Thread::current);
if (!pick_next()) if (!pick_next())
return false; return false;
switch_now(); switch_now();
@ -475,10 +474,10 @@ void Scheduler::pick_next_and_switch_now()
void Scheduler::switch_now() void Scheduler::switch_now()
{ {
Descriptor& descriptor = get_gdt_entry(current->selector()); Descriptor& descriptor = get_gdt_entry(Thread::current->selector());
descriptor.type = 9; descriptor.type = 9;
asm("sti\n" asm("sti\n"
"ljmp *(%%eax)\n" ::"a"(&current->far_ptr())); "ljmp *(%%eax)\n" ::"a"(&Thread::current->far_ptr()));
} }
bool Scheduler::context_switch(Thread& thread) bool Scheduler::context_switch(Thread& thread)
@ -486,31 +485,33 @@ bool Scheduler::context_switch(Thread& thread)
thread.set_ticks_left(time_slice_for(thread)); thread.set_ticks_left(time_slice_for(thread));
thread.did_schedule(); thread.did_schedule();
if (current == &thread) if (Thread::current == &thread)
return false; return false;
if (current) { if (Thread::current) {
// If the last process hasn't blocked (still marked as running), // If the last process hasn't blocked (still marked as running),
// mark it as runnable for the next round. // mark it as runnable for the next round.
if (current->state() == Thread::Running) if (Thread::current->state() == Thread::Running)
current->set_state(Thread::Runnable); Thread::current->set_state(Thread::Runnable);
asm volatile("fxsave %0" asm volatile("fxsave %0"
: "=m"(current->fpu_state())); : "=m"(Thread::current->fpu_state()));
#ifdef LOG_EVERY_CONTEXT_SWITCH #ifdef LOG_EVERY_CONTEXT_SWITCH
dbgprintf("Scheduler: %s(%u:%u) -> %s(%u:%u) [%u] %w:%x\n", dbgprintf("Scheduler: %s(%u:%u) -> %s(%u:%u) [%u] %w:%x\n",
current->process().name().characters(), current->process().pid(), current->tid(), Process::current->name().characters(), Process::current->pid(), Thread::current->tid(),
thread.process().name().characters(), thread.process().pid(), thread.tid(), thread.process().name().characters(), thread.process().pid(), thread.tid(),
thread.priority(), thread.priority(),
thread.tss().cs, thread.tss().eip); thread.tss().cs, thread.tss().eip);
#endif #endif
} }
current = &thread; Thread::current = &thread;
Process::current = &thread.process();
thread.set_state(Thread::Running); thread.set_state(Thread::Running);
asm volatile("fxrstor %0" ::"m"(current->fpu_state())); asm volatile("fxrstor %0" ::"m"(Thread::current->fpu_state()));
if (!thread.selector()) { if (!thread.selector()) {
thread.set_selector(gdt_alloc_entry()); thread.set_selector(gdt_alloc_entry());
@ -555,7 +556,7 @@ void Scheduler::prepare_for_iret_to_new_process()
{ {
auto& descriptor = get_gdt_entry(s_redirection.selector); auto& descriptor = get_gdt_entry(s_redirection.selector);
descriptor.type = 9; descriptor.type = 9;
s_redirection.tss.backlink = current->selector(); s_redirection.tss.backlink = Thread::current->selector();
load_task_register(s_redirection.selector); load_task_register(s_redirection.selector);
} }
@ -564,7 +565,7 @@ void Scheduler::prepare_to_modify_tss(Thread& thread)
// This ensures that a currently running process modifying its own TSS // This ensures that a currently running process modifying its own TSS
// in order to yield() and end up somewhere else doesn't just end up // in order to yield() and end up somewhere else doesn't just end up
// right after the yield(). // right after the yield().
if (current == &thread) if (Thread::current == &thread)
load_task_register(s_redirection.selector); load_task_register(s_redirection.selector);
} }
@ -587,7 +588,7 @@ void Scheduler::initialize()
void Scheduler::timer_tick(RegisterState& regs) void Scheduler::timer_tick(RegisterState& regs)
{ {
if (!current) if (!Thread::current)
return; return;
++g_uptime; ++g_uptime;
@ -597,12 +598,12 @@ void Scheduler::timer_tick(RegisterState& regs)
tv.tv_usec = PIT::ticks_this_second() * 1000; tv.tv_usec = PIT::ticks_this_second() * 1000;
Process::update_info_page_timestamp(tv); Process::update_info_page_timestamp(tv);
if (current->process().is_profiling()) { if (Process::current->is_profiling()) {
SmapDisabler disabler; SmapDisabler disabler;
auto backtrace = current->raw_backtrace(regs.ebp); auto backtrace = Thread::current->raw_backtrace(regs.ebp);
auto& sample = Profiling::next_sample_slot(); auto& sample = Profiling::next_sample_slot();
sample.pid = current->pid(); sample.pid = Process::current->pid();
sample.tid = current->tid(); sample.tid = Thread::current->tid();
sample.timestamp = g_uptime; sample.timestamp = g_uptime;
for (size_t i = 0; i < min((size_t)backtrace.size(), Profiling::max_stack_frame_count); ++i) { for (size_t i = 0; i < min((size_t)backtrace.size(), Profiling::max_stack_frame_count); ++i) {
sample.frames[i] = backtrace[i]; sample.frames[i] = backtrace[i];
@ -611,10 +612,10 @@ void Scheduler::timer_tick(RegisterState& regs)
TimerQueue::the().fire(); TimerQueue::the().fire();
if (current->tick()) if (Thread::current->tick())
return; return;
auto& outgoing_tss = current->tss(); auto& outgoing_tss = Thread::current->tss();
if (!pick_next()) if (!pick_next())
return; return;
@ -656,7 +657,7 @@ static bool s_should_stop_idling = false;
void Scheduler::stop_idling() void Scheduler::stop_idling()
{ {
if (current != g_colonel) if (Thread::current != g_colonel)
return; return;
s_should_stop_idling = true; s_should_stop_idling = true;

View file

@ -39,7 +39,6 @@ class WaitQueue;
struct RegisterState; struct RegisterState;
struct SchedulerData; struct SchedulerData;
extern Thread* current;
extern Thread* g_finalizer; extern Thread* g_finalizer;
extern Thread* g_colonel; extern Thread* g_colonel;
extern WaitQueue* g_finalizer_wait_queue; extern WaitQueue* g_finalizer_wait_queue;

View file

@ -85,8 +85,8 @@ static Handler s_syscall_table[] = {
int handle(RegisterState& regs, u32 function, u32 arg1, u32 arg2, u32 arg3) int handle(RegisterState& regs, u32 function, u32 arg1, u32 arg2, u32 arg3)
{ {
ASSERT_INTERRUPTS_ENABLED(); ASSERT_INTERRUPTS_ENABLED();
auto& process = current->process(); auto& process = *Process::current;
current->did_syscall(); Thread::current->did_syscall();
if (function == SC_exit || function == SC_exit_thread) { if (function == SC_exit || function == SC_exit_thread) {
// These syscalls need special handling since they never return to the caller. // These syscalls need special handling since they never return to the caller.
@ -126,8 +126,8 @@ void syscall_handler(RegisterState regs)
// Special handling of the "gettid" syscall since it's extremely hot. // Special handling of the "gettid" syscall since it's extremely hot.
// FIXME: Remove this hack once userspace locks stop calling it so damn much. // FIXME: Remove this hack once userspace locks stop calling it so damn much.
if (regs.eax == SC_gettid) { if (regs.eax == SC_gettid) {
regs.eax = current->process().sys$gettid(); regs.eax = Process::current->sys$gettid();
current->did_syscall(); Thread::current->did_syscall();
return; return;
} }
@ -140,7 +140,7 @@ void syscall_handler(RegisterState regs)
asm volatile("" asm volatile(""
: "=m"(*ptr)); : "=m"(*ptr));
auto& process = current->process(); auto& process = *Process::current;
if (!MM.validate_user_stack(process, VirtualAddress(regs.userspace_esp))) { if (!MM.validate_user_stack(process, VirtualAddress(regs.userspace_esp))) {
dbgprintf("Invalid stack pointer: %p\n", regs.userspace_esp); dbgprintf("Invalid stack pointer: %p\n", regs.userspace_esp);
@ -172,10 +172,10 @@ void syscall_handler(RegisterState regs)
process.big_lock().unlock(); process.big_lock().unlock();
// Check if we're supposed to return to userspace or just die. // Check if we're supposed to return to userspace or just die.
current->die_if_needed(); Thread::current->die_if_needed();
if (current->has_unmasked_pending_signals()) if (Thread::current->has_unmasked_pending_signals())
(void)current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal); (void)Thread::current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal);
} }
} }

View file

@ -42,8 +42,8 @@ MasterPTY::MasterPTY(unsigned index)
, m_index(index) , m_index(index)
{ {
m_pts_name = String::format("/dev/pts/%u", m_index); m_pts_name = String::format("/dev/pts/%u", m_index);
set_uid(current->process().uid()); set_uid(Process::current->uid());
set_gid(current->process().gid()); set_gid(Process::current->gid());
} }
MasterPTY::~MasterPTY() MasterPTY::~MasterPTY()

View file

@ -39,8 +39,8 @@ SlavePTY::SlavePTY(MasterPTY& master, unsigned index)
, m_index(index) , m_index(index)
{ {
sprintf(m_tty_name, "/dev/pts/%u", m_index); sprintf(m_tty_name, "/dev/pts/%u", m_index);
set_uid(current->process().uid()); set_uid(Process::current->uid());
set_gid(current->process().gid()); set_gid(Process::current->gid());
DevPtsFS::register_slave_pty(*this); DevPtsFS::register_slave_pty(*this);
set_size(80, 25); set_size(80, 25);
} }

View file

@ -273,7 +273,7 @@ void TTY::set_termios(const termios& t)
int TTY::ioctl(FileDescription&, unsigned request, unsigned arg) int TTY::ioctl(FileDescription&, unsigned request, unsigned arg)
{ {
REQUIRE_PROMISE(tty); REQUIRE_PROMISE(tty);
auto& process = current->process(); auto& process = *Process::current;
pid_t pgid; pid_t pgid;
termios* tp; termios* tp;
winsize* ws; winsize* ws;

View file

@ -36,8 +36,8 @@ extern "C" void module_init()
kprintf("i is now %d\n", i); kprintf("i is now %d\n", i);
} }
kprintf("current pid: %d\n", current->process().sys$getpid()); kprintf("current pid: %d\n", Process::current->sys$getpid());
kprintf("current process name: %s\n", current->process().name().characters()); kprintf("current process name: %s\n", Process::current->name().characters());
} }
extern "C" void module_fini() extern "C" void module_fini()

View file

@ -43,6 +43,8 @@
namespace Kernel { namespace Kernel {
Thread* Thread::current;
static FPUState s_clean_fpu_state; static FPUState s_clean_fpu_state;
u16 thread_specific_selector() u16 thread_specific_selector()
@ -234,7 +236,7 @@ u64 Thread::sleep(u32 ticks)
{ {
ASSERT(state() == Thread::Running); ASSERT(state() == Thread::Running);
u64 wakeup_time = g_uptime + ticks; u64 wakeup_time = g_uptime + ticks;
auto ret = current->block<Thread::SleepBlocker>(wakeup_time); auto ret = Thread::current->block<Thread::SleepBlocker>(wakeup_time);
if (wakeup_time > g_uptime) { if (wakeup_time > g_uptime) {
ASSERT(ret != Thread::BlockResult::WokeNormally); ASSERT(ret != Thread::BlockResult::WokeNormally);
} }
@ -244,7 +246,7 @@ u64 Thread::sleep(u32 ticks)
u64 Thread::sleep_until(u64 wakeup_time) u64 Thread::sleep_until(u64 wakeup_time)
{ {
ASSERT(state() == Thread::Running); ASSERT(state() == Thread::Running);
auto ret = current->block<Thread::SleepBlocker>(wakeup_time); auto ret = Thread::current->block<Thread::SleepBlocker>(wakeup_time);
if (wakeup_time > g_uptime) if (wakeup_time > g_uptime)
ASSERT(ret != Thread::BlockResult::WokeNormally); ASSERT(ret != Thread::BlockResult::WokeNormally);
return wakeup_time; return wakeup_time;

View file

@ -67,6 +67,8 @@ class Thread {
friend class Scheduler; friend class Scheduler;
public: public:
static Thread* current;
explicit Thread(Process&); explicit Thread(Process&);
~Thread(); ~Thread();

View file

@ -34,7 +34,6 @@ namespace Kernel {
NonnullRefPtr<InodeVMObject> InodeVMObject::create_with_inode(Inode& inode) NonnullRefPtr<InodeVMObject> InodeVMObject::create_with_inode(Inode& inode)
{ {
size_t size = inode.size(); size_t size = inode.size();
InterruptDisabler disabler;
if (inode.vmobject()) if (inode.vmobject())
return *inode.vmobject(); return *inode.vmobject();
auto vmobject = adopt(*new InodeVMObject(inode, size)); auto vmobject = adopt(*new InodeVMObject(inode, size));

View file

@ -280,7 +280,7 @@ Region* MemoryManager::region_from_vaddr(VirtualAddress vaddr)
PageFaultResponse MemoryManager::handle_page_fault(const PageFault& fault) PageFaultResponse MemoryManager::handle_page_fault(const PageFault& fault)
{ {
ASSERT_INTERRUPTS_DISABLED(); ASSERT_INTERRUPTS_DISABLED();
ASSERT(current); ASSERT(Thread::current);
#ifdef PAGE_FAULT_DEBUG #ifdef PAGE_FAULT_DEBUG
dbgprintf("MM: handle_page_fault(%w) at V%p\n", fault.code(), fault.vaddr().get()); dbgprintf("MM: handle_page_fault(%w) at V%p\n", fault.code(), fault.vaddr().get());
#endif #endif
@ -475,10 +475,10 @@ RefPtr<PhysicalPage> MemoryManager::allocate_supervisor_physical_page()
void MemoryManager::enter_process_paging_scope(Process& process) void MemoryManager::enter_process_paging_scope(Process& process)
{ {
ASSERT(current); ASSERT(Thread::current);
InterruptDisabler disabler; InterruptDisabler disabler;
current->tss().cr3 = process.page_directory().cr3(); Thread::current->tss().cr3 = process.page_directory().cr3();
write_cr3(process.page_directory().cr3()); write_cr3(process.page_directory().cr3());
} }
@ -675,7 +675,7 @@ void MemoryManager::dump_kernel_regions()
ProcessPagingScope::ProcessPagingScope(Process& process) ProcessPagingScope::ProcessPagingScope(Process& process)
{ {
ASSERT(current); ASSERT(Thread::current);
m_previous_cr3 = read_cr3(); m_previous_cr3 = read_cr3();
MM.enter_process_paging_scope(process); MM.enter_process_paging_scope(process);
} }
@ -683,7 +683,7 @@ ProcessPagingScope::ProcessPagingScope(Process& process)
ProcessPagingScope::~ProcessPagingScope() ProcessPagingScope::~ProcessPagingScope()
{ {
InterruptDisabler disabler; InterruptDisabler disabler;
current->tss().cr3 = m_previous_cr3; Thread::current->tss().cr3 = m_previous_cr3;
write_cr3(m_previous_cr3); write_cr3(m_previous_cr3);
} }

View file

@ -84,15 +84,15 @@ Region::~Region()
NonnullOwnPtr<Region> Region::clone() NonnullOwnPtr<Region> Region::clone()
{ {
ASSERT(current); ASSERT(Process::current);
// FIXME: What should we do for privately mapped InodeVMObjects? // FIXME: What should we do for privately mapped InodeVMObjects?
if (m_shared || vmobject().is_inode()) { if (m_shared || vmobject().is_inode()) {
ASSERT(!m_stack); ASSERT(!m_stack);
#ifdef MM_DEBUG #ifdef MM_DEBUG
dbgprintf("%s<%u> Region::clone(): sharing %s (V%p)\n", dbgprintf("%s<%u> Region::clone(): sharing %s (V%p)\n",
current->process().name().characters(), Process::current->name().characters(),
current->pid(), Process::current->pid(),
m_name.characters(), m_name.characters(),
vaddr().get()); vaddr().get());
#endif #endif
@ -105,8 +105,8 @@ NonnullOwnPtr<Region> Region::clone()
#ifdef MM_DEBUG #ifdef MM_DEBUG
dbgprintf("%s<%u> Region::clone(): cowing %s (V%p)\n", dbgprintf("%s<%u> Region::clone(): cowing %s (V%p)\n",
current->process().name().characters(), Process::current->name().characters(),
current->pid(), Process::current->pid(),
m_name.characters(), m_name.characters(),
vaddr().get()); vaddr().get());
#endif #endif
@ -392,8 +392,8 @@ PageFaultResponse Region::handle_zero_fault(size_t page_index_in_region)
return PageFaultResponse::Continue; return PageFaultResponse::Continue;
} }
if (current) if (Thread::current)
current->did_zero_fault(); Thread::current->did_zero_fault();
auto physical_page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::Yes); auto physical_page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
if (physical_page.is_null()) { if (physical_page.is_null()) {
@ -422,8 +422,8 @@ PageFaultResponse Region::handle_cow_fault(size_t page_index_in_region)
return PageFaultResponse::Continue; return PageFaultResponse::Continue;
} }
if (current) if (Thread::current)
current->did_cow_fault(); Thread::current->did_cow_fault();
#ifdef PAGE_FAULT_DEBUG #ifdef PAGE_FAULT_DEBUG
dbgprintf(" >> It's a COW page and it's time to COW!\n"); dbgprintf(" >> It's a COW page and it's time to COW!\n");
@ -471,8 +471,8 @@ PageFaultResponse Region::handle_inode_fault(size_t page_index_in_region)
return PageFaultResponse::Continue; return PageFaultResponse::Continue;
} }
if (current) if (Thread::current)
current->did_inode_fault(); Thread::current->did_inode_fault();
#ifdef MM_DEBUG #ifdef MM_DEBUG
dbgprintf("MM: page_in_from_inode ready to read from inode\n"); dbgprintf("MM: page_in_from_inode ready to read from inode\n");

View file

@ -174,17 +174,17 @@ extern "C" [[noreturn]] void init()
Process::create_kernel_process(syncd_thread, "syncd", [] { Process::create_kernel_process(syncd_thread, "syncd", [] {
for (;;) { for (;;) {
VFS::the().sync(); VFS::the().sync();
current->sleep(1 * TICKS_PER_SECOND); Thread::current->sleep(1 * TICKS_PER_SECOND);
} }
}); });
Process::create_kernel_process(g_finalizer, "Finalizer", [] { Process::create_kernel_process(g_finalizer, "Finalizer", [] {
current->set_priority(THREAD_PRIORITY_LOW); Thread::current->set_priority(THREAD_PRIORITY_LOW);
for (;;) { for (;;) {
{ {
InterruptDisabler disabler; InterruptDisabler disabler;
if (!g_finalizer_has_work) if (!g_finalizer_has_work)
current->wait_on(*g_finalizer_wait_queue); Thread::current->wait_on(*g_finalizer_wait_queue);
ASSERT(g_finalizer_has_work); ASSERT(g_finalizer_has_work);
g_finalizer_has_work = false; g_finalizer_has_work = false;
} }
@ -303,7 +303,7 @@ void init_stage2()
hang(); hang();
} }
current->process().set_root_directory(VFS::the().root_custody()); Process::current->set_root_directory(VFS::the().root_custody());
dbgprintf("Load ksyms\n"); dbgprintf("Load ksyms\n");
load_ksyms(); load_ksyms();
@ -356,7 +356,7 @@ void init_stage2()
Process::create_kernel_process(thread, "NetworkTask", NetworkTask_main); Process::create_kernel_process(thread, "NetworkTask", NetworkTask_main);
} }
current->process().sys$exit(0); Process::current->sys$exit(0);
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }