// posix_fd.c - file descriptor table #include "posix.h" #include "posix_fd.h" #include int errno = 0; static FD_ENTRY gFdTable[FD_TABLE_PIDS][FD_MAX]; __declspec(dllexport) void PosixFdInit(void) { uint32_t pid = SysGetCurrentPid(); uint32_t slot = pid % FD_TABLE_PIDS; // Clear this process's slice (handles inherited state from a previous // process that happened to land on the same slot - unlikely but safe). for (int i = 0; i < FD_MAX; i++) gFdTable[slot][i] = (FD_ENTRY){ FD_FREE, 0, false }; gFdTable[slot][0] = (FD_ENTRY){ FD_CONSOLE_R, 0, true }; gFdTable[slot][1] = (FD_ENTRY){ FD_CONSOLE_W, 0, true }; gFdTable[slot][2] = (FD_ENTRY){ FD_CONSOLE_W, 0, true }; } __declspec(dllexport) int FdAlloc(uint32_t pid, FD_TYPE type, uint32_t khandle) { uint32_t slot = pid % FD_TABLE_PIDS; for (int fd = 3; fd < FD_MAX; fd++) { if (!gFdTable[slot][fd].Used) { gFdTable[slot][fd] = (FD_ENTRY){ type, khandle, true }; return fd; } } errno = EMFILE; return -1; } __declspec(dllexport) FD_ENTRY* FdGet(uint32_t pid, int fd) { if (fd < 0 || fd >= FD_MAX) { errno = EBADF; return (FD_ENTRY*)0; } uint32_t slot = pid % FD_TABLE_PIDS; FD_ENTRY* e = &gFdTable[slot][fd]; if (!e->Used) { errno = EBADF; return (FD_ENTRY*)0; } return e; } __declspec(dllexport) void FdFree(uint32_t pid, int fd) { if (fd < 0 || fd >= FD_MAX) return; uint32_t slot = pid % FD_TABLE_PIDS; gFdTable[slot][fd] = (FD_ENTRY){ FD_FREE, 0, false }; }