Files
nt-lite/code/posix/posix_fd.c
T

68 lines
2.4 KiB
C

// posix_fd.c - file descriptor table
#include <syscall.h>
#include "posix.h"
#include "posix_fd.h"
int errno = 0;
int PosixStatusToErrno(uint32_t s) {
switch (s) {
case 0x0000: return 0; // STATUS_SUCCESS
case 0x0002: return ENOSYS; // STATUS_NOT_SUPPORTED
case 0x0003: return EAGAIN; // STATUS_TIMEOUT / would block
case 0x0010: return EINVAL; // STATUS_INVALID_PARAMETER
case 0x0011: return EBADF; // STATUS_INVALID_HANDLE
case 0x0012: return ERANGE; // STATUS_BUFFER_TOO_SMALL
case 0x0020: return ENOMEM; // STATUS_NO_MEMORY
case 0x0021: return EACCES; // STATUS_ACCESS_DENIED
case 0x0022: return ENOENT; // STATUS_NOT_FOUND
case 0x0023: return EEXIST; // STATUS_ALREADY_EXISTS
case 0x0030: return ECONNRESET; // STATUS_OBJECT_DEAD
case 0x0031: return EAGAIN; // STATUS_QUEUE_FULL
case 0x0032: return EAGAIN; // STATUS_QUEUE_EMPTY
default: return EIO;
}
}
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 };
}