Merge dev into xbox-button-icons, with the restart and the prompts on the Linux port's portable calls

The restart moves into gfx_present.c's gfx_window_closed, which the Win32 and SDL windows share, and linux.c gets
plat_restart and plat_restart_wait: posix_spawn of /proc/self/exe with no descriptor past stderr and the default
signals, and a wait on a pidfd. The prompts code takes plat_file_exists, plat_setenv, strcasecmp and strdup, and the
menu and the log say a game resolution of another shape than 16:9 (16:10 now as well as 21:9) keeps the Switch prompts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Deon FoucheandClaude Opus 5.5 committed 2026-10-31 22:14:22 +10:00
commit 01d69bf6d1
134 files changed
+9659 -4837

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
// The parts of platform.h built on its locks rather than on the OS: recursive mutexes, one-time initialisation and
// events. Every OS shares them.
#include "platform.h"
// ---- recursive mutex: owner is the holder's thread id (0 when free); only the holder writes depth.
void plat_rmutex_lock(PlatRMutex *m) {
uint32_t me = plat_thread_id();
if (__atomic_load_n(&m->owner, __ATOMIC_RELAXED) == me) {
m->depth++;
return;
}
plat_mutex_lock(&m->m);
__atomic_store_n(&m->owner, me, __ATOMIC_RELAXED);
m->depth = 1;
}
void plat_rmutex_unlock(PlatRMutex *m) {
if (--m->depth) return;
__atomic_store_n(&m->owner, 0, __ATOMIC_RELAXED);
plat_mutex_unlock(&m->m);
}
// ---- once: state 0 not run, 1 running, 2 done. Waiters for a running initialiser sleep on one process-wide
// condition variable; initialisers are rare and short.
static PlatMutex once_lock = PLAT_MUTEX_INIT;
static PlatCond once_done = PLAT_COND_INIT;
void plat_once(PlatOnce *o, void (*fn)(void *arg), void *arg) {
if (__atomic_load_n(&o->state, __ATOMIC_ACQUIRE) == 2) return;
int32_t expected = 0;
if (__atomic_compare_exchange_n(&o->state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
fn(arg);
plat_mutex_lock(&once_lock);
__atomic_store_n(&o->state, 2, __ATOMIC_RELEASE);
plat_cond_broadcast(&once_done);
plat_mutex_unlock(&once_lock);
return;
}
plat_mutex_lock(&once_lock);
while (__atomic_load_n(&o->state, __ATOMIC_ACQUIRE) != 2) plat_cond_wait(&once_done, &once_lock);
plat_mutex_unlock(&once_lock);
}
// ---- events
void plat_event_init(PlatEvent *e, int manual, int initially_set) {
plat_mutex_init(&e->m);
plat_cond_init(&e->c);
e->manual = manual;
e->set = initially_set;
}
void plat_event_set(PlatEvent *e) {
plat_mutex_lock(&e->m);
e->set = 1;
if (e->manual) plat_cond_broadcast(&e->c);
else plat_cond_signal(&e->c);
plat_mutex_unlock(&e->m);
}
void plat_event_reset(PlatEvent *e) {
plat_mutex_lock(&e->m);
e->set = 0;
plat_mutex_unlock(&e->m);
}
void plat_event_wait(PlatEvent *e) {
plat_mutex_lock(&e->m);
while (!e->set) plat_cond_wait(&e->c, &e->m);
if (!e->manual) e->set = 0;
plat_mutex_unlock(&e->m);
}
int plat_event_wait_ns(PlatEvent *e, uint64_t ns) {
uint64_t end = plat_now_ns() + ns;
plat_mutex_lock(&e->m);
while (!e->set) {
uint64_t now = plat_now_ns();
if (now >= end) break;
plat_cond_wait_ns(&e->c, &e->m, end - now);
}
int got = e->set;
if (got && !e->manual) e->set = 0;
plat_mutex_unlock(&e->m);
return got;
}
File diff suppressed because it is too large. Load diff
+265 -9
View File
@@ -1,11 +1,15 @@
// Platform layer: threads, time, locks. New runtime code calls this instead of the OS;
// one implementation per OS (win32.c). The FP control register lives in the per-architecture fp_*.h headers,
// inline, because lifted FP code touches it on every operation.
// Platform layer: threads, time, locks, atomics, files. Runtime code calls this instead of the OS; one implementation
// per OS (win32.c, linux.c). The FP control register lives in the per-architecture fp_*.h headers, inline, because
// lifted FP code touches it on every operation.
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#if defined(__x86_64__) || defined(_M_X64)
#include "fp_x86.h"
#include <immintrin.h>
#endif
// ---- threads
@@ -14,16 +18,70 @@ typedef void (*PlatThreadFn)(void *arg);
// Starts fn(arg) on a new thread named name (shown in debuggers and profilers; may be NULL). NULL on failure.
PlatThread *plat_thread_new(PlatThreadFn fn, void *arg, const char *name);
// The same with the stack size given: stack bytes reserved for the thread (0: PLAT_STACK_DEFAULT). The default is the
// same on every OS, so a thread that fits on Windows fits elsewhere.
#define PLAT_STACK_DEFAULT (16u << 20)
PlatThread *plat_thread_new_ex(PlatThreadFn fn, void *arg, const char *name, size_t stack);
// Starts a thread nobody joins (plat_thread_new_ex + plat_thread_detach). 1 on success.
int plat_thread_spawn(PlatThreadFn fn, void *arg, const char *name, size_t stack);
void plat_thread_join(PlatThread *t); // waits for fn to return, then frees t
// Waits at most ns for fn to return: 1 when it did (t is freed), 0 when it still runs (t stays valid).
int plat_thread_join_ns(PlatThread *t, uint64_t ns);
void plat_thread_detach(PlatThread *t); // frees t; the thread runs on
// Restricts t (NULL: the calling thread) to the logical processors in mask (bit n = processor n of the first group).
// Returns the previous mask, 0 on failure.
uint64_t plat_thread_affinity(PlatThread *t, uint64_t mask);
uint32_t plat_cpu_count(void); // logical processors of the machine (system info)
uint32_t plat_cpu_usable(void); // the ones this process may run on (its affinity mask): size thread pools by it
uint64_t plat_thread_cpu_ns(uint32_t tid); // CPU time of the thread with id tid (plat_thread_id) so far; 0 unknown
// The logical processors the process may use (bit n = processor n, the first 64), into *all, and the lowest of each
// physical core among them into *first; returns the number of physical cores, 0 when unknown.
int plat_cpu_cores(uint64_t *all, uint64_t *first);
int plat_process_affinity(uint64_t mask); // every thread of the process to the processors in mask; 1 on success
// Interrupting a thread (kernel.c's asynchronous preemption). A thread makes its own handle; another thread stops it
// wherever it runs, reads where it is, may send it elsewhere, and lets it go on. While it is stopped the caller must not
// wait for anything the stopped thread could hold.
typedef struct PlatIntr PlatIntr;
PlatIntr *plat_intr_self(void); // NULL on failure
void plat_intr_free(PlatIntr *t);
// Stops t and reads its instruction and stack pointers: 1 when stopped, 0 when it did not stop in time (a thread
// blocked in the OS); t then runs on untouched.
int plat_intr_stop(PlatIntr *t, uint64_t *rip, uint64_t *rsp);
// Lets a stopped t go on: at to when to is nonzero, else where it stopped. 0 when the redirection failed (t then goes
// on where it stopped).
int plat_intr_resume(PlatIntr *t, uint64_t to);
// Fibers: execution contexts with stacks of their own that threads switch between; a fiber may resume on another
// thread. Each switch keeps the callee-saved registers and the floating-point control state.
typedef struct PlatFiber PlatFiber;
PlatFiber *plat_fiber_self(void); // the calling thread's own context as a fiber, once before its first switch
void plat_fiber_unself(void); // the calling thread stops being a fiber (it is on its own context again)
// A fiber that runs fn(arg) on a stack of stack bytes (reserved, committed as it grows); fn never returns.
PlatFiber *plat_fiber_new(size_t stack, void (*fn)(void *arg), void *arg);
void plat_fiber_switch(PlatFiber *to); // from the fiber the calling thread runs
void plat_fiber_free(PlatFiber *f); // a fiber nobody runs
// Scheduling priority, Windows' seven levels: of the calling thread, or of t. On Linux a thread lowered without the
// right to raise its priority again (CAP_SYS_NICE, or an RLIMIT_NICE of 20) could never return to normal, and the
// runtime lowers threads that later take shared locks at normal priority; without that right every change is skipped
// and threads keep the normal priority. Levels above normal need the same right.
enum { PLAT_PRIO_IDLE = -15, PLAT_PRIO_LOWEST = -2, PLAT_PRIO_BELOW_NORMAL = -1, PLAT_PRIO_NORMAL = 0,
PLAT_PRIO_ABOVE_NORMAL = 1, PLAT_PRIO_HIGHEST = 2, PLAT_PRIO_TIME_CRITICAL = 15 };
void plat_thread_priority(int prio);
void plat_thread_set_priority(PlatThread *t, int prio);
int plat_thread_priority_get(void); // the calling thread's level
void plat_yield(void); // gives the rest of the time slice to another ready thread
static inline void plat_pause(void) { // spin-wait hint
#if defined(__x86_64__) || defined(_M_X64)
_mm_pause();
#endif
}
// ---- time
uint64_t plat_now_ns(void); // monotonic, high resolution, arbitrary epoch
uint64_t plat_counter(void); // the OS's raw monotonic counter (QPC on Windows), plat_counter_hz per second
uint64_t plat_counter_hz(void);
void plat_timer_1ms(void); // asks the OS for timed waits accurate to 1 ms or better (call before threads)
// t * num / den for a fixed num / den without a 128-bit division per call (__udivti3 took 5% of the game's running
// samples through plat_now_ns and rt_ticks): t * q + (t * f >> 64) with q = num / den and f = (num % den) * 2^64 / den.
// Monotonic in t and at most one below the exact quotient while t * (num % den) / den fits 64 bits.
@@ -35,9 +93,19 @@ static inline uint64_t plat_scaled(PlatScale s, uint64_t t) {
return t * s.q + (uint64_t)(((unsigned __int128)t * s.f) >> 64);
}
void plat_sleep_ns(uint64_t ns); // returns no earlier than ns later; overshoot well under 1 ms
// Sleeps about ns on the OS's high-resolution timer without spinning: wakes up to PLAT_WAIT_LATE_NS late, never early.
void plat_wait_ns(uint64_t ns);
#ifdef _WIN32
#define PLAT_WAIT_LATE_NS 500000u // high-resolution waitable timer
#else
#define PLAT_WAIT_LATE_NS 60000u // clock_nanosleep with a 1 us timer slack (plat_timer_1ms), scheduler wakeup
#endif
static inline uint64_t plat_now_ms(void) { return plat_now_ns() / 1000000u; }
void plat_sleep_ms(uint32_t ms); // coarse sleep: the scheduler's granularity, no spinning
// ---- locks (not recursive) and condition variables; zero-initialised storage is a valid unlocked lock and an empty
// condition variable (PLAT_MUTEX_INIT / PLAT_COND_INIT spell it).
// ---- locks and condition variables. A PlatMutex is a reader-writer lock taken exclusively (plat_mutex_lock) or
// shared (plat_mutex_lock_shared), not recursive, like Windows' SRW lock it is on Windows. Zero-initialised storage is
// a valid unlocked lock and an empty condition variable (PLAT_MUTEX_INIT / PLAT_COND_INIT spell it).
typedef struct { void *p; } PlatMutex;
typedef struct { void *p; } PlatCond;
#define PLAT_MUTEX_INIT {0}
@@ -46,18 +114,135 @@ void plat_mutex_init(PlatMutex *m);
void plat_mutex_lock(PlatMutex *m);
int plat_mutex_trylock(PlatMutex *m); // 1 when acquired
void plat_mutex_unlock(PlatMutex *m);
void plat_mutex_lock_shared(PlatMutex *m);
int plat_mutex_trylock_shared(PlatMutex *m); // 1 when acquired
void plat_mutex_unlock_shared(PlatMutex *m);
void plat_cond_init(PlatCond *c);
void plat_cond_wait(PlatCond *c, PlatMutex *m);
void plat_cond_wait(PlatCond *c, PlatMutex *m); // m held exclusively
int plat_cond_wait_ns(PlatCond *c, PlatMutex *m, uint64_t ns); // 0 on timeout (spurious wakeups return 1 too)
static inline int plat_cond_wait_ms(PlatCond *c, PlatMutex *m, uint32_t ms) {
return plat_cond_wait_ns(c, m, (uint64_t)ms * 1000000u);
}
void plat_cond_signal(PlatCond *c);
void plat_cond_broadcast(PlatCond *c);
// ---- memory
// A mutex the thread that holds it may take again; unlocked as many times as locked. Zero-initialised is unlocked.
typedef struct { PlatMutex m; uint32_t owner, depth; } PlatRMutex;
#define PLAT_RMUTEX_INIT {PLAT_MUTEX_INIT, 0, 0}
void plat_rmutex_lock(PlatRMutex *m);
void plat_rmutex_unlock(PlatRMutex *m);
// One-time initialisation: the first caller runs fn(arg), every other caller waits until it returned. Zero-initialised
// (PLAT_ONCE_INIT) has not run.
typedef struct { volatile int32_t state; } PlatOnce;
#define PLAT_ONCE_INIT {0}
void plat_once(PlatOnce *o, void (*fn)(void *arg), void *arg);
// An event: set wakes its waiters; an auto-reset event lets one waiter through and clears itself, a manual-reset one
// stays set until reset.
typedef struct { PlatMutex m; PlatCond c; int set, manual; } PlatEvent;
void plat_event_init(PlatEvent *e, int manual, int initially_set);
void plat_event_set(PlatEvent *e);
void plat_event_reset(PlatEvent *e);
void plat_event_wait(PlatEvent *e);
int plat_event_wait_ns(PlatEvent *e, uint64_t ns); // 1 when the event was set, 0 on timeout
// ---- atomics: full barriers, explicit widths (Windows' Interlocked* operate on 32-bit LONG). The value returned is
// noted per function: new for inc/dec/add, previous for xadd/xchg/cas/or.
#define PLAT_SC __ATOMIC_SEQ_CST
static inline int32_t plat_inc32(volatile int32_t *p) { return __atomic_add_fetch(p, 1, PLAT_SC); }
static inline int32_t plat_dec32(volatile int32_t *p) { return __atomic_sub_fetch(p, 1, PLAT_SC); }
static inline int32_t plat_add32(volatile int32_t *p, int32_t v) { return __atomic_add_fetch(p, v, PLAT_SC); }
static inline int32_t plat_xadd32(volatile int32_t *p, int32_t v) { return __atomic_fetch_add(p, v, PLAT_SC); }
static inline int32_t plat_xchg32(volatile int32_t *p, int32_t v) { return __atomic_exchange_n(p, v, PLAT_SC); }
static inline int32_t plat_cas32(volatile int32_t *p, int32_t xchg, int32_t cmp) {
__atomic_compare_exchange_n(p, &cmp, xchg, 0, PLAT_SC, PLAT_SC);
return cmp;
}
static inline int64_t plat_inc64(volatile int64_t *p) { return __atomic_add_fetch(p, 1, PLAT_SC); }
static inline int64_t plat_dec64(volatile int64_t *p) { return __atomic_sub_fetch(p, 1, PLAT_SC); }
static inline int64_t plat_add64(volatile int64_t *p, int64_t v) { return __atomic_add_fetch(p, v, PLAT_SC); }
static inline int64_t plat_xadd64(volatile int64_t *p, int64_t v) { return __atomic_fetch_add(p, v, PLAT_SC); }
static inline int64_t plat_xchg64(volatile int64_t *p, int64_t v) { return __atomic_exchange_n(p, v, PLAT_SC); }
static inline int64_t plat_or64(volatile int64_t *p, int64_t v) { return __atomic_fetch_or(p, v, PLAT_SC); }
static inline int64_t plat_cas64(volatile int64_t *p, int64_t xchg, int64_t cmp) {
__atomic_compare_exchange_n(p, &cmp, xchg, 0, PLAT_SC, PLAT_SC);
return cmp;
}
static inline void *plat_xchgp(void *volatile *p, void *v) { return __atomic_exchange_n(p, v, PLAT_SC); }
static inline void *plat_casp(void *volatile *p, void *xchg, void *cmp) {
__atomic_compare_exchange_n(p, &cmp, xchg, 0, PLAT_SC, PLAT_SC);
return cmp;
}
// ---- virtual memory: ranges reserved at fixed addresses below 2^39, their pages committed, decommitted and protected
// at 4 KiB granularity.
enum { PLAT_PROT_NONE, PLAT_PROT_READ, PLAT_PROT_RW };
enum { PLAT_MEM_FREE = -2, PLAT_MEM_RESERVED = -1 }; // plat_mem_state besides PLAT_PROT_* for committed pages
// Reserves [addr, addr + n) inaccessible, exactly there: 0 when any of it is taken. watch: writes to its pages are
// tracked for plat_mem_written.
int plat_mem_reserve(uint64_t addr, uint64_t n, int watch);
// n bytes of read-write memory anywhere, zero, backed only as pages are first written (plat_mem_protect may seal them);
// NULL on failure. Kept until exit.
void *plat_mem_alloc(size_t n);
int plat_mem_commit(uint64_t addr, size_t n); // read-write pages inside a reserved range; 1 on success
int plat_mem_decommit(uint64_t addr, uint64_t n); // contents dropped: committed again, the pages read zero
int plat_mem_protect(uint64_t addr, uint64_t n, int prot); // committed pages only; 1 on success
// The page at addr: PLAT_PROT_* when committed, else PLAT_MEM_RESERVED or PLAT_MEM_FREE (not reserved by us). *end
// gets the end of the run of pages in the same state, at most limit.
int plat_mem_state(uint64_t addr, uint64_t limit, uint64_t *end);
// The pages of a watched reservation written since the last reset, up to max page addresses into pages, in address
// order; reset: those reported start over as unwritten. UINT64_MAX when writes to the range are not tracked.
uint64_t plat_mem_written(uint64_t addr, uint64_t n, uint64_t *pages, uint64_t max, int reset);
// A write that faulted on a read-only page at addr goes to fn first; fn returns 1 when it made the page writable and
// the write should run again, 0 to let the fault go on (to the crash handler). One hook per process.
void plat_mem_fault_hook(int (*fn)(uint64_t addr));
// Starts this program again with the same arguments and ends this process with the new one's exit code (Windows), or
// replaces this process with it (Linux). Environment changes made before the call are passed on.
_Noreturn void plat_reexec(void);
// A crash in this executable's own code (an access violation, an illegal instruction, a division by zero, a stack
// overflow) goes to fn, which reports it and must end the process. Faults in other modules (drivers) are left to the
// OS. The write-fault hook above runs first.
typedef struct {
const char *what; // "access violation", "illegal instruction", ...
uint32_t code; // the Windows exception code or the signal number
uintptr_t rip, offset; // the faulting instruction, and its offset in the executable
int access; // the data access that faulted: 0 read, 1 write, 8 execute; -1 when not an access
uint64_t addr; // its address when access >= 0
} PlatCrash;
void plat_crash_hook(void (*fn)(const PlatCrash *c));
int plat_mem_read(uint64_t addr, void *out, size_t n); // copies n bytes, 0 instead of faulting on unmapped memory
int plat_mem_readable(uint64_t addr, uint64_t n); // every page of [addr, addr + n) can be read; no fault
void *plat_aligned_alloc(size_t size, size_t align); // free with plat_aligned_free; NULL on failure
void plat_aligned_free(void *p);
// ---- process
_Noreturn void plat_exit(int code); // ends the process at once: other threads stop, no atexit handlers run
int plat_setenv(const char *name, const char *value); // value NULL removes it; 1 on success
uint32_t plat_process_id(void);
// CPU time of the process since it started (user and kernel), and wall time since it started, in ns; 0 when unknown.
uint64_t plat_process_cpu_ns(void);
uint64_t plat_process_uptime_ns(void);
uint64_t plat_unix_time_ns(void); // wall clock, ns since 1970
void plat_local_time(struct tm *out); // the wall clock now in the local time zone
int plat_localtime(int64_t unix_s, struct tm *out); // a POSIX time in the local time zone; 0 out of range
int plat_gmtime(int64_t unix_s, struct tm *out); // the same in UTC
long plat_tz_west(void); // the local zone's standard offset, seconds west of UTC (UTC-5: 18000)
// Runs this executable again with the same arguments and env_name=env_value added to its environment, for probes that
// expect the child to stop with a fatal. Its stdout and stderr go into out (NUL-terminated, the rest discarded); waits
// at most timeout_ms (0: no limit) and kills it after that. Returns the exit code, -1 when it could not start.
int plat_run_self(const char *env_name, const char *env_value, char *out, size_t cap, uint32_t timeout_ms);
// ---- randomness
int plat_random(void *out, size_t n); // cryptographically random bytes; 1 on success
// ---- files. Paths are UTF-8 with either separator; each implementation converts to what the OS wants.
int plat_file_exists(const char *path); // 1 for a file (not a directory)
int plat_dir_exists(const char *path); // 1 for a directory
// path made absolute against the working directory (not resolved further); 0 when it does not fit cap.
int plat_full_path(const char *path, char *out, size_t cap);
void plat_file_mkdir_p(const char *path); // creates every missing directory of path, itself included
// Whole file into a malloc'd buffer with a NUL after the last byte; NULL when missing, empty or over 1 GiB.
uint8_t *plat_file_read(const char *path, uint64_t *size);
@@ -67,6 +252,15 @@ int plat_file_replace(const char *from, const char *to); // rename, replacing t
// one, never a torn or zero-filled one. 1 on success.
int plat_file_write_atomic(const char *path, const void *data, size_t n);
int plat_file_flush(const char *path); // flushes a written file's data to the disk; 1 on success
int plat_file_sync(FILE *f); // fflush, then the file's data to the disk; 1 on success
// fseek and ftell with 64-bit offsets (a long is 32 bits on Windows).
#ifdef _WIN32
static inline int plat_fseek64(FILE *f, int64_t off, int whence) { return _fseeki64(f, off, whence); }
static inline int64_t plat_ftell64(FILE *f) { return _ftelli64(f); }
#else
static inline int plat_fseek64(FILE *f, int64_t off, int whence) { return fseeko(f, (off_t)off, whence); }
static inline int64_t plat_ftell64(FILE *f) { return (int64_t)ftello(f); }
#endif
void plat_file_delete(const char *path);
int plat_file_truncate(const char *path, uint64_t size); // 1 on success
int64_t plat_file_size(const char *path); // bytes of a file, -1 when missing or unreadable
@@ -79,11 +273,69 @@ int plat_append_write(PlatAppend *f, const void *data, size_t n); // 1 when al
// Calls cb(name, ctx) for each file in dir whose name ends in ext (".in"); name has no directory part. cb returns 0 to
// stop. Returns 0 when dir cannot be listed.
int plat_file_list(const char *dir, const char *ext, int (*cb)(const char *name, void *ctx), void *ctx);
// Open files for positional reads: any thread, in parallel on one handle, no file pointer.
typedef struct PlatFile PlatFile;
PlatFile *plat_file_open(const char *path); // read-only; NULL when missing or unreadable
// The same without the OS's file cache (reads go to the disk into the buffer): offsets, sizes and buffers aligned to
// the sector size.
PlatFile *plat_file_open_unbuffered(const char *path);
void plat_file_close(PlatFile *f);
// Bytes read at off (0 at or past the end of the file), -1 on an I/O error, -2 when the OS refused to write into buf
// (a read-only page).
int64_t plat_file_pread(PlatFile *f, void *buf, uint32_t n, uint64_t off);
// What changes when the file is replaced or written: its volume, file id, size, last write and creation (on Linux,
// status change) times in the OS's units. 0 on failure.
typedef struct { uint64_t volume, file_id, size, write_time, create_time; } PlatFileId;
int plat_file_id(PlatFile *f, PlatFileId *out);
const void *plat_file_map(PlatFile *f); // a read-only view of the whole file, kept until exit; NULL
// ---- the host file system under the game's save data (fs_host.c). Calls that can fail return PLAT_FS_OK (0) or the
// reason; other processes may open the same files meanwhile.
enum { PLAT_FS_OK, PLAT_FS_NOT_FOUND, PLAT_FS_EXISTS, PLAT_FS_NOT_EMPTY, PLAT_FS_BUSY, PLAT_FS_ERROR };
enum { PLAT_FS_MISSING = -1, PLAT_FS_FILE, PLAT_FS_DIR, PLAT_FS_LINK }; // plat_fs_kind; LINK: a symbolic link or
// reparse point, never followed
int plat_fs_kind(const char *path);
int plat_fs_mkdir(const char *path); // PLAT_FS_EXISTS when something is there
int plat_fs_rmdir(const char *path); // an empty directory, or a link to one
int plat_fs_unlink(const char *path); // a file or a link; a read-only one too
// Renames a file or directory; never replaces (PLAT_FS_EXISTS). durable: the change is on the disk at return.
int plat_fs_rename(const char *from, const char *to, int durable);
int plat_fs_link(const char *existing, const char *path); // a hard link
int plat_fs_links(const char *path); // the file's hard link count, 0 when unknown
void plat_fs_sync_dir(const char *path); // a directory's entries to the disk, as far as the FS allows
// cb(name, kind, size, ctx) for each entry of dir but "." and ".."; cb returns 0 to stop. The listing's error.
int plat_fs_list(const char *dir, int (*cb)(const char *name, int kind, uint64_t size, void *ctx), void *ctx);
// An existing file for reading and, with write, writing; *err (may be NULL) gets the reason on failure.
PlatFile *plat_fs_open(const char *path, int write, int *err);
PlatFile *plat_fs_create(const char *path, int *err); // a new file for writing; PLAT_FS_EXISTS when there
int64_t plat_file_pwrite(PlatFile *f, const void *buf, uint32_t n, uint64_t off); // bytes written, -1 on error
int plat_file_set_size(PlatFile *f, uint64_t size); // PLAT_FS_*
int plat_file_fsync(PlatFile *f); // the file's data to the disk; 1 on success
int plat_temp_dir(char *out, size_t cap); // the user's temporary directory, no trailing separator
int plat_exe_path(char *out, size_t cap); // path of the running executable; 0 on failure
uintptr_t plat_exe_base(void); // where the executable is loaded
// The module (executable or library) holding code address addr: its file name without directories into name, its load
// address into *base. 0 when none.
int plat_module_of(uintptr_t addr, char *name, size_t cap, uintptr_t *base);
#define PLAT_PATH_MAX 1024 // path buffers of the runtime
#ifdef _WIN32
#define PLAT_EXE_SUFFIX ".exe" // of the programs the runtime starts (totk_xlate)
#else
#define PLAT_EXE_SUFFIX ""
#endif
// The last directory separator in path ('/' or '\\'), NULL when there is none.
static inline char *plat_last_sep(const char *path) {
char *last = NULL;
for (const char *p = path; *p; p++)
if (*p == '/' || *p == '\\') last = (char *)p;
return last;
}
// Environment variable as UTF-8 into out; its length, or 0 when unset, empty or too long for cap.
size_t plat_getenv(const char *name, char *out, size_t cap);
// The user's UI language as a BCP-47 tag ("ru-RU", "en-US"); "" when the system gives none. Valid for the process.
const char *plat_ui_language(void);
// The user's regional format (locale) as a BCP-47 tag; "" when the system gives none. Valid for the process.
const char *plat_user_locale(void);
uint32_t plat_thread_id(void); // id of the calling thread, for unique file names
// A system font file with the glyphs of a catalog language ("ja", "ko", "zh-Hans", "zh-Hant"): the menu shows each
// language's name in its own script. Copies the UTF-8 path into out; 0 when the system has none.
@@ -106,8 +358,9 @@ void *plat_lib_sym(void *lib, const char *name);
// the system does not give is -1.
typedef struct PlatLoad PlatLoad;
// Opens the counters: CPU times, the thermal zones, and the GPU engine and memory counters of the adapter whose LUID is
// gpu_luid (8 bytes, Vulkan's deviceLUID; NULL: the busiest adapter). Never NULL.
PlatLoad *plat_load_open(const uint8_t *gpu_luid);
// gpu_luid (8 bytes, Vulkan's deviceLUID; NULL: the busiest adapter) or, where the system names GPUs by PCI address,
// on PCI bus pci_bus (-1: unknown). Never NULL.
PlatLoad *plat_load_open(const uint8_t *gpu_luid, int pci_bus);
void plat_load_close(PlatLoad *l);
// Since the previous call on l (the first call gives -1): CPU use of the machine and of this process, percent of all
// logical processors, and the hottest ACPI thermal zone in degrees Celsius.
@@ -120,6 +373,9 @@ void plat_mem_info(float *used_mb, float *total_mb, float *proc_mb);
// Commit charge in MB: this process's private bytes, the system's commit in use and its limit (RAM plus page files).
// An allocation fails when the system's reaches the limit, however much physical memory is free. -1 when unknown.
void plat_commit_info(double *proc_mb, double *used_mb, double *limit_mb);
// This process's memory in bytes: resident (the working set) and private (Windows: committed private bytes; Linux: the
// resident anonymous pages). 0 when unknown.
void plat_process_memory(uint64_t *resident, uint64_t *private_bytes);
// ---- child processes: a program with stdin and stdout piped to us (stderr discarded), no console window.
typedef struct PlatChild PlatChild;
+658 -25
View File
@@ -1,11 +1,14 @@
// Windows implementation of platform.h: CreateThread, QueryPerformanceCounter, high-resolution waitable timers,
// SRW locks and condition variables.
#include <io.h>
#include <stdio.h>
#include <windows.h>
#include <bcrypt.h>
#include <pdh.h>
#include <pdhmsg.h>
#include <psapi.h>
#include <shellapi.h>
#include <timeapi.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
@@ -31,11 +34,16 @@ static DWORD WINAPI thread_main(LPVOID p) {
}
PlatThread *plat_thread_new(PlatThreadFn fn, void *arg, const char *name) {
return plat_thread_new_ex(fn, arg, name, 0);
}
PlatThread *plat_thread_new_ex(PlatThreadFn fn, void *arg, const char *name, size_t stack) {
PlatThread *t = calloc(1, sizeof *t);
if (!t) return NULL;
t->fn = fn;
t->arg = arg;
t->h = CreateThread(NULL, 0, thread_main, t, CREATE_SUSPENDED, NULL);
t->h = CreateThread(NULL, stack ? stack : PLAT_STACK_DEFAULT, thread_main, t,
CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);
if (!t->h) { free(t); return NULL; }
if (name) {
wchar_t w[64];
@@ -51,12 +59,150 @@ void plat_thread_join(PlatThread *t) {
free(t);
}
int plat_thread_join_ns(PlatThread *t, uint64_t ns) {
uint64_t ms = (ns + 999999) / 1000000;
if (WaitForSingleObject(t->h, ms >= INFINITE ? INFINITE - 1 : (DWORD)ms) != WAIT_OBJECT_0) return 0;
CloseHandle(t->h);
free(t);
return 1;
}
// The thread keeps using t->fn and t->arg, so the struct stays allocated (a few bytes per detached thread).
void plat_thread_detach(PlatThread *t) {
CloseHandle(t->h);
t->h = NULL;
}
int plat_cpu_cores(uint64_t *all, uint64_t *first) {
DWORD_PTR proc, sys;
*all = *first = 0;
if (!GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys)) return 0;
*all = proc;
DWORD len = 0;
GetLogicalProcessorInformationEx(RelationProcessorCore, NULL, &len);
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buf = len ? malloc(len) : NULL;
int cores = 0;
if (buf && GetLogicalProcessorInformationEx(RelationProcessorCore, buf, &len))
for (DWORD off = 0; off < len;) {
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *e = (void *)((char *)buf + off);
KAFFINITY m = e->Processor.GroupMask[0].Mask & proc;
if (e->Processor.GroupMask[0].Group == 0 && m) *first |= m & -m, cores++; // the lowest of the core's
off += e->Size;
}
free(buf);
return cores;
}
int plat_process_affinity(uint64_t mask) { return SetProcessAffinityMask(GetCurrentProcess(), (DWORD_PTR)mask) != 0; }
uint64_t plat_thread_cpu_ns(uint32_t tid) {
HANDLE th = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, tid);
FILETIME a, b, k, u;
uint64_t ns = 0;
if (th && GetThreadTimes(th, &a, &b, &k, &u))
ns = (((uint64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) + ((uint64_t)u.dwHighDateTime << 32 | u.dwLowDateTime)) *
100;
if (th) CloseHandle(th);
return ns;
}
// ---- thread interruption: SuspendThread, Get/SetThreadContext, ResumeThread.
struct PlatIntr {
CONTEXT ctx; // first: CONTEXT wants 16-byte alignment
HANDLE h;
};
PlatIntr *plat_intr_self(void) {
HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION,
FALSE, GetCurrentThreadId());
PlatIntr *t = h ? _aligned_malloc(sizeof *t, 16) : NULL;
if (!t) {
if (h) CloseHandle(h);
return NULL;
}
t->h = h;
return t;
}
void plat_intr_free(PlatIntr *t) {
if (!t) return;
CloseHandle(t->h);
_aligned_free(t);
}
int plat_intr_stop(PlatIntr *t, uint64_t *rip, uint64_t *rsp) {
if (SuspendThread(t->h) == (DWORD)-1) return 0;
memset(&t->ctx, 0, sizeof t->ctx);
t->ctx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; // set back whole, so the kernel restores every GPR
if (!GetThreadContext(t->h, &t->ctx)) {
ResumeThread(t->h);
return 0;
}
*rip = t->ctx.Rip;
*rsp = t->ctx.Rsp;
return 1;
}
int plat_intr_resume(PlatIntr *t, uint64_t to) {
int ok = 1;
if (to) {
t->ctx.Rip = to;
ok = SetThreadContext(t->h, &t->ctx) != 0;
}
ResumeThread(t->h);
return ok;
}
// ---- fibers: Windows fibers with FIBER_FLAG_FLOAT_SWITCH (the MXCSR and x87 control word switch with them).
struct PlatFiber {
void *h;
void (*fn)(void *arg);
void *arg;
};
static __thread PlatFiber self_fiber;
PlatFiber *plat_fiber_self(void) {
self_fiber.h = ConvertThreadToFiberEx(NULL, FIBER_FLAG_FLOAT_SWITCH);
return self_fiber.h ? &self_fiber : NULL;
}
void plat_fiber_unself(void) {
ConvertFiberToThread();
self_fiber.h = NULL;
}
static void WINAPI fiber_start(void *p) {
PlatFiber *f = p;
f->fn(f->arg);
}
PlatFiber *plat_fiber_new(size_t stack, void (*fn)(void *arg), void *arg) {
PlatFiber *f = malloc(sizeof *f);
if (!f) return NULL;
f->fn = fn, f->arg = arg;
f->h = CreateFiberEx(0x10000, stack, FIBER_FLAG_FLOAT_SWITCH, fiber_start, f);
if (!f->h) {
free(f);
return NULL;
}
return f;
}
void plat_fiber_switch(PlatFiber *to) { SwitchToFiber(to->h); }
void plat_fiber_free(PlatFiber *f) {
if (!f) return;
DeleteFiber(f->h);
free(f);
}
int plat_thread_spawn(PlatThreadFn fn, void *arg, const char *name, size_t stack) {
PlatThread *t = plat_thread_new_ex(fn, arg, name, stack);
if (t) plat_thread_detach(t);
return t != NULL;
}
uint64_t plat_thread_affinity(PlatThread *t, uint64_t mask) {
return (uint64_t)SetThreadAffinityMask(t ? t->h : GetCurrentThread(), (DWORD_PTR)mask);
}
@@ -78,6 +224,13 @@ uint32_t plat_cpu_usable(void) {
return plat_cpu_count();
}
// PLAT_PRIO_* are the THREAD_PRIORITY_* values.
void plat_thread_priority(int prio) { SetThreadPriority(GetCurrentThread(), prio); }
void plat_thread_set_priority(PlatThread *t, int prio) { SetThreadPriority(t->h, prio); }
int plat_thread_priority_get(void) { return GetThreadPriority(GetCurrentThread()); }
void plat_yield(void) { SwitchToThread(); }
// ---- time
static uint64_t qpc_freq(void) {
@@ -90,6 +243,17 @@ static uint64_t qpc_freq(void) {
return freq;
}
uint64_t plat_counter(void) {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (uint64_t)t.QuadPart;
}
uint64_t plat_counter_hz(void) { return qpc_freq(); }
// The default timer tick is 15.6 ms; a 1 ms wait would cost a full tick.
void plat_timer_1ms(void) { timeBeginPeriod(1); }
static PlatScale qpc_ns; // set before main, so no thread reads it half written
__attribute__((constructor)) static void qpc_ns_init(void) { qpc_ns = plat_scale(1000000000u, qpc_freq()); }
@@ -108,24 +272,26 @@ uint64_t plat_now_ns(void) {
static __thread HANDLE sleep_timer;
static __thread int sleep_timer_tried;
void plat_sleep_ns(uint64_t ns) {
uint64_t end = plat_now_ns() + ns;
void plat_wait_ns(uint64_t ns) {
if (!sleep_timer_tried) {
sleep_timer_tried = 1;
sleep_timer = CreateWaitableTimerExW(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);
}
if (ns > PLAT_SPIN_NS) {
uint64_t coarse = ns - PLAT_SPIN_NS;
if (sleep_timer) {
LARGE_INTEGER due = {.QuadPart = -(LONGLONG)(coarse / 100)}; // relative, 100 ns units
if (SetWaitableTimerEx(sleep_timer, &due, 0, NULL, NULL, NULL, 0))
WaitForSingleObject(sleep_timer, INFINITE);
else Sleep((DWORD)(coarse / 1000000));
} else Sleep((DWORD)(coarse / 1000000));
}
LARGE_INTEGER due = {.QuadPart = -(LONGLONG)(ns / 100)}; // relative, 100 ns units
if (!due.QuadPart) due.QuadPart = -1;
if (sleep_timer && SetWaitableTimerEx(sleep_timer, &due, 0, NULL, NULL, NULL, 0))
WaitForSingleObject(sleep_timer, INFINITE);
else Sleep((DWORD)((ns + 999999) / 1000000));
}
void plat_sleep_ns(uint64_t ns) {
uint64_t end = plat_now_ns() + ns;
if (ns > PLAT_SPIN_NS) plat_wait_ns(ns - PLAT_SPIN_NS);
while (plat_now_ns() < end) SwitchToThread();
}
void plat_sleep_ms(uint32_t ms) { Sleep(ms); }
// ---- locks and condition variables
void plat_mutex_init(PlatMutex *m) { InitializeSRWLock((PSRWLOCK)m); }
@@ -133,6 +299,10 @@ void plat_mutex_lock(PlatMutex *m) { AcquireSRWLockExclusive((PSRWLOCK)m); }
int plat_mutex_trylock(PlatMutex *m) { return TryAcquireSRWLockExclusive((PSRWLOCK)m) != 0; }
void plat_mutex_unlock(PlatMutex *m) { ReleaseSRWLockExclusive((PSRWLOCK)m); }
void plat_mutex_lock_shared(PlatMutex *m) { AcquireSRWLockShared((PSRWLOCK)m); }
int plat_mutex_trylock_shared(PlatMutex *m) { return TryAcquireSRWLockShared((PSRWLOCK)m) != 0; }
void plat_mutex_unlock_shared(PlatMutex *m) { ReleaseSRWLockShared((PSRWLOCK)m); }
void plat_cond_init(PlatCond *c) { InitializeConditionVariable((PCONDITION_VARIABLE)c); }
void plat_cond_wait(PlatCond *c, PlatMutex *m) { SleepConditionVariableSRW((PCONDITION_VARIABLE)c, (PSRWLOCK)m, INFINITE, 0); }
@@ -162,6 +332,21 @@ int plat_file_exists(const char *path) {
return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
}
int plat_dir_exists(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return 0;
DWORD a = GetFileAttributesW(w);
return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY);
}
int plat_full_path(const char *path, char *out, size_t cap) {
wchar_t w[WPATH], full[WPATH];
if (!widen(path, w, WPATH)) return 0;
DWORD n = GetFullPathNameW(w, WPATH, full, NULL);
if (!n || n >= WPATH) return 0;
return WideCharToMultiByte(CP_UTF8, 0, full, -1, out, (int)cap, NULL, NULL) != 0;
}
void plat_file_mkdir_p(const char *path) {
wchar_t tmp[WPATH];
if (!widen(path, tmp, WPATH)) return;
@@ -235,7 +420,7 @@ int plat_file_replace(const char *from, const char *to) {
int plat_file_write_atomic(const char *path, const void *data, size_t n) {
char tmp[WPATH + 48];
wchar_t a[WPATH], b[WPATH];
int len = snprintf(tmp, sizeof tmp, "%s.%lu.%lu.tmp", path, GetCurrentProcessId(), GetCurrentThreadId());
int len = snprintf(tmp, sizeof tmp, "%s.%u.%u.tmp", path, (unsigned)GetCurrentProcessId(), (unsigned)GetCurrentThreadId());
if (len < 0 || len >= (int)sizeof tmp || !widen(tmp, a, WPATH) || !widen(path, b, WPATH)) return 0;
HANDLE h = CreateFileW(a, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) return 0;
@@ -257,6 +442,8 @@ int plat_file_flush(const char *path) {
return ok;
}
int plat_file_sync(FILE *f) { return !fflush(f) && !_commit(_fileno(f)); }
void plat_file_delete(const char *path) {
wchar_t w[WPATH];
if (widen(path, w, WPATH)) DeleteFileW(w);
@@ -304,15 +491,442 @@ int plat_file_list(const char *dir, const char *ext, int (*cb)(const char *name,
return 1;
}
// ---- virtual memory: VirtualAlloc reservations, MEM_WRITE_WATCH for the watched ones.
int plat_mem_reserve(uint64_t addr, uint64_t n, int watch) {
void *p = VirtualAlloc((void *)(uintptr_t)addr, n, MEM_RESERVE | (watch ? MEM_WRITE_WATCH : 0), PAGE_NOACCESS);
if (p && p != (void *)(uintptr_t)addr) {
VirtualFree(p, 0, MEM_RELEASE);
p = NULL;
}
return p != NULL;
}
void *plat_mem_alloc(size_t n) { return VirtualAlloc(NULL, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); }
int plat_mem_commit(uint64_t addr, size_t n) {
return VirtualAlloc((void *)(uintptr_t)addr, n, MEM_COMMIT, PAGE_READWRITE) != NULL;
}
// Decommitted pages come back zeroed when committed again.
int plat_mem_decommit(uint64_t addr, uint64_t n) { return VirtualFree((void *)(uintptr_t)addr, n, MEM_DECOMMIT) != 0; }
int plat_mem_protect(uint64_t addr, uint64_t n, int prot) {
DWORD old;
DWORD p = prot == PLAT_PROT_RW ? PAGE_READWRITE : prot == PLAT_PROT_READ ? PAGE_READONLY : PAGE_NOACCESS;
return VirtualProtect((void *)(uintptr_t)addr, n, p, &old) != 0;
}
int plat_mem_state(uint64_t addr, uint64_t limit, uint64_t *end) {
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery((void *)(uintptr_t)addr, &mbi, sizeof mbi)) {
*end = limit;
return PLAT_MEM_FREE;
}
uint64_t e = (uint64_t)(uintptr_t)mbi.BaseAddress + mbi.RegionSize;
*end = e < limit ? e : limit;
if (mbi.State == MEM_RESERVE) return PLAT_MEM_RESERVED;
if (mbi.State != MEM_COMMIT) return PLAT_MEM_FREE;
DWORD p = mbi.Protect & 0xff;
return p == PAGE_READWRITE ? PLAT_PROT_RW : p == PAGE_READONLY ? PLAT_PROT_READ : PLAT_PROT_NONE;
}
// Adapted from LAS Recomp runtime/platform/windows.c:40-63 @ da35b83 (MIT, Copyright (c) 2026 Peiikai): GetWriteWatch
// with the reset flag.
uint64_t plat_mem_written(uint64_t addr, uint64_t n, uint64_t *pages, uint64_t max, int reset) {
if (!max || !n) return 0;
ULONG_PTR got = (ULONG_PTR)max;
DWORD gran;
_Static_assert(sizeof(PVOID) == sizeof(uint64_t), "page addresses are written straight into a uint64_t array");
if (GetWriteWatch(reset ? WRITE_WATCH_FLAG_RESET : 0, (void *)(uintptr_t)addr, (SIZE_T)n, (PVOID *)pages, &got,
&gran))
return UINT64_MAX;
return got;
}
static int (*fault_hook)(uint64_t addr);
// A write access violation (ExceptionInformation[0] == 1) goes to the hook; registered first, before the crash handler.
static LONG CALLBACK fault_veh(EXCEPTION_POINTERS *ep) {
const EXCEPTION_RECORD *er = ep->ExceptionRecord;
if (er->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || er->NumberParameters < 2 || er->ExceptionInformation[0] != 1)
return EXCEPTION_CONTINUE_SEARCH;
return fault_hook((uint64_t)er->ExceptionInformation[1]) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
}
void plat_mem_fault_hook(int (*fn)(uint64_t addr)) {
fault_hook = fn;
AddVectoredExceptionHandler(1, fault_veh);
}
static void (*crash_fn)(const PlatCrash *c);
static LONG CALLBACK crash_veh(EXCEPTION_POINTERS *ep) {
DWORD code = ep->ExceptionRecord->ExceptionCode;
const char *what = code == EXCEPTION_ACCESS_VIOLATION ? "access violation"
: code == EXCEPTION_ILLEGAL_INSTRUCTION ? "illegal instruction"
: code == EXCEPTION_INT_DIVIDE_BY_ZERO ? "integer division by zero"
: code == EXCEPTION_PRIV_INSTRUCTION ? "privileged instruction"
: code == EXCEPTION_STACK_OVERFLOW ? "stack overflow"
: code == EXCEPTION_IN_PAGE_ERROR ? "in-page error" : NULL;
if (!what) return EXCEPTION_CONTINUE_SEARCH;
uintptr_t rip = (uintptr_t)ep->ContextRecord->Rip;
MODULEINFO mi;
if (!GetModuleInformation(GetCurrentProcess(), GetModuleHandleW(NULL), &mi, sizeof mi) ||
rip - (uintptr_t)mi.lpBaseOfDll >= mi.SizeOfImage)
return EXCEPTION_CONTINUE_SEARCH; // not our code: leave it to the handler that expects it
PlatCrash c = {what, (uint32_t)code, rip, rip - (uintptr_t)mi.lpBaseOfDll, -1, 0};
if (code == EXCEPTION_ACCESS_VIOLATION && ep->ExceptionRecord->NumberParameters >= 2)
c.access = (int)ep->ExceptionRecord->ExceptionInformation[0], c.addr = ep->ExceptionRecord->ExceptionInformation[1];
crash_fn(&c);
return EXCEPTION_CONTINUE_SEARCH;
}
void plat_crash_hook(void (*fn)(const PlatCrash *c)) {
crash_fn = fn;
AddVectoredExceptionHandler(0, crash_veh);
}
// A fresh process gets a fresh layout: Windows places DLLs, heaps and thread stacks at random addresses. The parent
// waits and exits with the child's code.
void plat_reexec(void) {
fflush(stdout);
fflush(stderr);
STARTUPINFOW si = {.cb = sizeof si};
PROCESS_INFORMATION pi;
wchar_t *cmd = _wcsdup(GetCommandLineW()); // CreateProcessW may write its command line
if (!cmd || !CreateProcessW(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
fprintf(stderr, "FATAL: re-running the process failed (error %lu)\n", GetLastError());
ExitProcess(70);
}
CloseHandle(pi.hThread);
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD code = 70;
GetExitCodeProcess(pi.hProcess, &code);
ExitProcess(code);
}
int plat_mem_read(uint64_t addr, void *out, size_t n) {
SIZE_T got = 0;
return ReadProcessMemory(GetCurrentProcess(), (const void *)(uintptr_t)addr, out, n, &got) && got == n;
}
int plat_mem_readable(uint64_t addr, uint64_t n) {
for (uint64_t a = addr, end = addr + n; a < end || a == addr;) {
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery((void *)(uintptr_t)a, &mbi, sizeof mbi) || mbi.State != MEM_COMMIT) return 0;
if (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) return 0;
a = (uint64_t)(uintptr_t)mbi.BaseAddress + mbi.RegionSize;
if (a >= end) return 1;
}
return 1;
}
void *plat_aligned_alloc(size_t size, size_t align) { return _aligned_malloc(size, align); }
void plat_aligned_free(void *p) { _aligned_free(p); }
// ---- process
void plat_exit(int code) {
fflush(stdout);
fflush(stderr);
ExitProcess((UINT)code);
}
// _putenv_s, not SetEnvironmentVariableA: getenv reads the C runtime's copy of the environment, which only the CRT's
// own calls update. An empty value removes the variable.
int plat_setenv(const char *name, const char *value) { return _putenv_s(name, value ? value : "") == 0; }
uint32_t plat_process_id(void) { return GetCurrentProcessId(); }
static uint64_t ft64(FILETIME f) { return (uint64_t)f.dwHighDateTime << 32 | f.dwLowDateTime; }
uint64_t plat_process_cpu_ns(void) {
FILETIME cr, ex, k, u;
if (!GetProcessTimes(GetCurrentProcess(), &cr, &ex, &k, &u)) return 0;
return (ft64(k) + ft64(u)) * 100;
}
uint64_t plat_process_uptime_ns(void) {
FILETIME cr, ex, k, u, now;
if (!GetProcessTimes(GetCurrentProcess(), &cr, &ex, &k, &u)) return 0;
GetSystemTimeAsFileTime(&now);
return ft64(now) > ft64(cr) ? (ft64(now) - ft64(cr)) * 100 : 0;
}
uint64_t plat_unix_time_ns(void) {
FILETIME now;
GetSystemTimeAsFileTime(&now);
return (ft64(now) - 116444736000000000ull) * 100; // FILETIME counts 100 ns from 1601
}
void plat_local_time(struct tm *out) {
time_t t = time(NULL);
localtime_s(out, &t);
}
int plat_localtime(int64_t unix_s, struct tm *out) {
time_t t = (time_t)unix_s;
return !localtime_s(out, &t);
}
int plat_gmtime(int64_t unix_s, struct tm *out) {
time_t t = (time_t)unix_s;
return !gmtime_s(out, &t);
}
long plat_tz_west(void) {
long west = 0;
_tzset();
_get_timezone(&west);
return west;
}
int plat_run_self(const char *env_name, const char *env_value, char *out, size_t cap, uint32_t timeout_ms) {
SECURITY_ATTRIBUTES sa = {sizeof sa, NULL, TRUE};
HANDLE rd, wr;
if (!CreatePipe(&rd, &wr, &sa, 0)) return -1;
SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0);
STARTUPINFOW si = {.cb = sizeof si, .dwFlags = STARTF_USESTDHANDLES, .hStdInput = GetStdHandle(STD_INPUT_HANDLE),
.hStdOutput = wr, .hStdError = wr};
PROCESS_INFORMATION pi;
wchar_t *cmdline = _wcsdup(GetCommandLineW());
SetEnvironmentVariableA(env_name, env_value);
BOOL ok = cmdline && CreateProcessW(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
SetEnvironmentVariableA(env_name, NULL);
free(cmdline);
CloseHandle(wr);
if (!ok) {
CloseHandle(rd);
return -1;
}
size_t len = 0;
DWORD got;
char sink[512];
while (len + 1 < cap && ReadFile(rd, out + len, (DWORD)(cap - 1 - len), &got, NULL) && got) len += got;
if (cap) out[len] = 0;
while (ReadFile(rd, sink, sizeof sink, &got, NULL) && got) {}
CloseHandle(rd);
if (WaitForSingleObject(pi.hProcess, timeout_ms ? timeout_ms : INFINITE) != WAIT_OBJECT_0)
TerminateProcess(pi.hProcess, 1), WaitForSingleObject(pi.hProcess, INFINITE);
DWORD code = 1;
GetExitCodeProcess(pi.hProcess, &code);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return (int)code;
}
int plat_random(void *out, size_t n) {
return BCryptGenRandom(NULL, out, (ULONG)n, BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0;
}
// FILE_FLAG_OVERLAPPED handles: a read names its offset, and each thread waits on an event of its own, so concurrent
// reads on one handle do not share the file pointer or the event.
PlatFile *plat_file_open(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return NULL;
HANDLE h = CreateFileW(w, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
return h == INVALID_HANDLE_VALUE ? NULL : (PlatFile *)h;
}
PlatFile *plat_file_open_unbuffered(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return NULL;
HANDLE h = CreateFileW(w, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL);
return h == INVALID_HANDLE_VALUE ? NULL : (PlatFile *)h;
}
void plat_file_close(PlatFile *f) {
if (f) CloseHandle((HANDLE)f);
}
int64_t plat_file_pread(PlatFile *f, void *buf, uint32_t n, uint64_t off) {
static __thread HANDLE ev;
if (!ev && !(ev = CreateEventW(NULL, TRUE, FALSE, NULL))) return -1;
OVERLAPPED ov = {.Offset = (DWORD)off, .OffsetHigh = (DWORD)(off >> 32), .hEvent = ev};
DWORD got = 0;
if (ReadFile((HANDLE)f, buf, n, &got, &ov)) return got;
DWORD e = GetLastError();
if (e == ERROR_IO_PENDING) {
if (GetOverlappedResult((HANDLE)f, &ov, &got, TRUE)) return got;
e = GetLastError();
}
return e == ERROR_HANDLE_EOF ? 0 : e == ERROR_NOACCESS ? -2 : -1;
}
int plat_file_id(PlatFile *f, PlatFileId *out) {
BY_HANDLE_FILE_INFORMATION i;
if (!GetFileInformationByHandle((HANDLE)f, &i)) return 0;
*out = (PlatFileId){i.dwVolumeSerialNumber, (uint64_t)i.nFileIndexHigh << 32 | i.nFileIndexLow,
(uint64_t)i.nFileSizeHigh << 32 | i.nFileSizeLow,
(uint64_t)i.ftLastWriteTime.dwHighDateTime << 32 | i.ftLastWriteTime.dwLowDateTime,
(uint64_t)i.ftCreationTime.dwHighDateTime << 32 | i.ftCreationTime.dwLowDateTime};
return 1;
}
const void *plat_file_map(PlatFile *f) {
HANDLE map = CreateFileMappingW((HANDLE)f, NULL, PAGE_READONLY, 0, 0, NULL);
const void *v = map ? MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0) : NULL;
if (map) CloseHandle(map); // the view keeps the mapping alive
return v;
}
static int fs_err(DWORD e) {
switch (e) {
case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_DIRECTORY: return PLAT_FS_NOT_FOUND;
case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: return PLAT_FS_EXISTS;
case ERROR_DIR_NOT_EMPTY: return PLAT_FS_NOT_EMPTY;
case ERROR_ACCESS_DENIED: case ERROR_SHARING_VIOLATION: return PLAT_FS_BUSY;
default: return PLAT_FS_ERROR;
}
}
int plat_fs_kind(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return PLAT_FS_MISSING;
DWORD a = GetFileAttributesW(w);
if (a == INVALID_FILE_ATTRIBUTES) return PLAT_FS_MISSING;
return a & FILE_ATTRIBUTE_REPARSE_POINT ? PLAT_FS_LINK : a & FILE_ATTRIBUTE_DIRECTORY ? PLAT_FS_DIR : PLAT_FS_FILE;
}
int plat_fs_mkdir(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return PLAT_FS_ERROR;
return CreateDirectoryW(w, NULL) ? PLAT_FS_OK : fs_err(GetLastError());
}
int plat_fs_rmdir(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return PLAT_FS_ERROR;
return RemoveDirectoryW(w) ? PLAT_FS_OK : fs_err(GetLastError());
}
int plat_fs_unlink(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return PLAT_FS_ERROR;
DWORD a = GetFileAttributesW(w);
if (a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_READONLY))
SetFileAttributesW(w, a & ~(DWORD)FILE_ATTRIBUTE_READONLY);
return DeleteFileW(w) ? PLAT_FS_OK : fs_err(GetLastError());
}
int plat_fs_rename(const char *from, const char *to, int durable) {
wchar_t a[WPATH], b[WPATH];
if (!widen(from, a, WPATH) || !widen(to, b, WPATH)) return PLAT_FS_ERROR;
return MoveFileExW(a, b, durable ? MOVEFILE_WRITE_THROUGH : 0) ? PLAT_FS_OK : fs_err(GetLastError());
}
int plat_fs_link(const char *existing, const char *path) {
wchar_t a[WPATH], b[WPATH];
if (!widen(existing, a, WPATH) || !widen(path, b, WPATH)) return PLAT_FS_ERROR;
return CreateHardLinkW(b, a, NULL) ? PLAT_FS_OK : fs_err(GetLastError());
}
int plat_fs_links(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return 0;
HANDLE f = CreateFileW(w, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
BY_HANDLE_FILE_INFORMATION fi;
int links = f != INVALID_HANDLE_VALUE && GetFileInformationByHandle(f, &fi) ? (int)fi.nNumberOfLinks : 0;
if (f != INVALID_HANDLE_VALUE) CloseHandle(f);
return links;
}
// NTFS journals directory entries; flushing the directory handle is as far as Windows goes.
void plat_fs_sync_dir(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return;
HANDLE h = CreateFileW(w, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (h != INVALID_HANDLE_VALUE) {
FlushFileBuffers(h);
CloseHandle(h);
}
}
int plat_fs_list(const char *dir, int (*cb)(const char *name, int kind, uint64_t size, void *ctx), void *ctx) {
wchar_t wd[WPATH], pat[WPATH + 4];
if (!widen(dir, wd, WPATH)) return PLAT_FS_ERROR;
swprintf(pat, WPATH + 4, L"%ls\\*", wd);
WIN32_FIND_DATAW fd;
HANDLE h = FindFirstFileW(pat, &fd);
if (h == INVALID_HANDLE_VALUE) return fs_err(GetLastError());
do {
if (!wcscmp(fd.cFileName, L".") || !wcscmp(fd.cFileName, L"..")) continue;
char name[1024];
if (!WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, name, sizeof name, NULL, NULL)) continue;
DWORD a = fd.dwFileAttributes;
int kind = a & FILE_ATTRIBUTE_REPARSE_POINT ? PLAT_FS_LINK : a & FILE_ATTRIBUTE_DIRECTORY ? PLAT_FS_DIR
: PLAT_FS_FILE;
if (!cb(name, kind, (uint64_t)fd.nFileSizeHigh << 32 | fd.nFileSizeLow, ctx)) break;
} while (FindNextFileW(h, &fd));
FindClose(h);
return PLAT_FS_OK;
}
static PlatFile *fs_open(const char *path, DWORD access, DWORD share, DWORD how, int *err) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) {
if (err) *err = PLAT_FS_ERROR;
return NULL;
}
HANDLE h = CreateFileW(w, access, share, NULL, how, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (h == INVALID_HANDLE_VALUE) {
if (err) *err = fs_err(GetLastError());
return NULL;
}
return (PlatFile *)h;
}
PlatFile *plat_fs_open(const char *path, int write, int *err) {
return fs_open(path, GENERIC_READ | (write ? GENERIC_WRITE : 0),
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, OPEN_EXISTING, err);
}
PlatFile *plat_fs_create(const char *path, int *err) { return fs_open(path, GENERIC_WRITE, 0, CREATE_NEW, err); }
int64_t plat_file_pwrite(PlatFile *f, const void *buf, uint32_t n, uint64_t off) {
static __thread HANDLE ev;
if (!ev && !(ev = CreateEventW(NULL, TRUE, FALSE, NULL))) return -1;
OVERLAPPED ov = {.Offset = (DWORD)off, .OffsetHigh = (DWORD)(off >> 32), .hEvent = ev};
DWORD put = 0;
if (WriteFile((HANDLE)f, buf, n, &put, &ov)) return put;
if (GetLastError() == ERROR_IO_PENDING && GetOverlappedResult((HANDLE)f, &ov, &put, TRUE)) return put;
return -1;
}
int plat_file_set_size(PlatFile *f, uint64_t size) {
FILE_END_OF_FILE_INFO eof = {.EndOfFile.QuadPart = (LONGLONG)size};
return SetFileInformationByHandle((HANDLE)f, FileEndOfFileInfo, &eof, sizeof eof) ? PLAT_FS_OK
: fs_err(GetLastError());
}
int plat_file_fsync(PlatFile *f) { return FlushFileBuffers((HANDLE)f) != 0; }
int plat_temp_dir(char *out, size_t cap) {
wchar_t w[MAX_PATH + 1];
DWORD n = GetTempPathW(MAX_PATH + 1, w);
if (!n || n > MAX_PATH) return 0;
while (n && (w[n - 1] == L'\\' || w[n - 1] == L'/')) w[--n] = 0;
return WideCharToMultiByte(CP_UTF8, 0, w, -1, out, (int)cap, NULL, NULL) != 0;
}
uintptr_t plat_exe_base(void) { return (uintptr_t)GetModuleHandleW(NULL); }
int plat_module_of(uintptr_t addr, char *name, size_t cap, uintptr_t *base) {
HMODULE m = NULL;
wchar_t w[WPATH];
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCWSTR)addr, &m) ||
!m || !GetModuleFileNameW(m, w, WPATH))
return 0;
const wchar_t *n = wcsrchr(w, L'\\') ? wcsrchr(w, L'\\') + 1 : w;
*base = (uintptr_t)m;
return WideCharToMultiByte(CP_UTF8, 0, n, -1, name, (int)cap, NULL, NULL) != 0;
}
int plat_exe_path(char *out, size_t cap) {
wchar_t w[WPATH];
DWORD n = GetModuleFileNameW(NULL, w, WPATH);
@@ -344,6 +958,20 @@ const char *plat_ui_language(void) {
return tag;
}
const char *plat_user_locale(void) {
static char tag[LOCALE_NAME_MAX_LENGTH];
static int done;
if (!done) {
wchar_t w[LOCALE_NAME_MAX_LENGTH];
size_t i = 0;
if (GetUserDefaultLocaleName(w, LOCALE_NAME_MAX_LENGTH))
for (; w[i] && w[i] < 0x80 && i + 1 < sizeof tag; i++) tag[i] = (char)w[i];
tag[i] = 0;
done = 1;
}
return tag;
}
int plat_font_path(const char *lang, char *out, size_t cap) {
static const struct { const char *lang; const wchar_t *files[3]; } fonts[] = {
{"ja", {L"YuGothM.ttc", L"meiryo.ttc", L"msgothic.ttc"}},
@@ -512,7 +1140,8 @@ struct PlatLoad {
wchar_t luid[40]; // "luid_0x<high>_0x<low>" of the adapter, lower case; empty for any
};
PlatLoad *plat_load_open(const uint8_t *gpu_luid) {
PlatLoad *plat_load_open(const uint8_t *gpu_luid, int pci_bus) {
(void)pci_bus; // the LUID names the adapter
PlatLoad *l = calloc(1, sizeof *l);
if (!l) return NULL;
if (gpu_luid) { // Vulkan's deviceLUID is the LUID struct's memory: LowPart, then HighPart
@@ -533,8 +1162,6 @@ void plat_load_close(PlatLoad *l) {
free(l);
}
static uint64_t ft64(FILETIME f) { return (uint64_t)f.dwHighDateTime << 32 | f.dwLowDateTime; }
void plat_cpu_load(PlatLoad *l, float *total_pct, float *proc_pct, float *temp_c) {
*total_pct = *proc_pct = *temp_c = -1;
if (!l) return;
@@ -637,6 +1264,13 @@ void plat_commit_info(double *proc_mb, double *used_mb, double *limit_mb) {
*proc_mb = (double)(pmc.PrivateUsage >> 20);
}
void plat_process_memory(uint64_t *resident, uint64_t *private_bytes) {
PROCESS_MEMORY_COUNTERS_EX pm = {.cb = sizeof pm};
*resident = *private_bytes = 0;
if (K32GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *)&pm, sizeof pm))
*resident = pm.WorkingSetSize, *private_bytes = pm.PrivateUsage;
}
// ---- child processes
struct PlatChild {
@@ -713,21 +1347,21 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) {
// the saves) until the old one is gone; no handle is inherited, so none of them stays open in the new one either.
#define RESTART_WAIT "TOTK_RESTART_WAIT"
static unsigned long long process_created(HANDLE h) {
static uint64_t process_created(HANDLE h) {
FILETIME c, e, k, u;
return GetProcessTimes(h, &c, &e, &k, &u) ? (unsigned long long)c.dwHighDateTime << 32 | c.dwLowDateTime : 0;
return GetProcessTimes(h, &c, &e, &k, &u) ? ft64(c) : 0;
}
int plat_restart(void) {
char wait[48];
snprintf(wait, sizeof wait, "%lu.%llu", GetCurrentProcessId(), process_created(GetCurrentProcess()));
SetEnvironmentVariableA(RESTART_WAIT, wait);
snprintf(wait, sizeof wait, "%lu.%llu", GetCurrentProcessId(), (unsigned long long)process_created(GetCurrentProcess()));
plat_setenv(RESTART_WAIT, wait);
STARTUPINFOW si = {.cb = sizeof si};
PROCESS_INFORMATION pi;
wchar_t *cmd = _wcsdup(GetCommandLineW()); // CreateProcessW may write its command line
BOOL ok = cmd && CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
free(cmd);
SetEnvironmentVariableA(RESTART_WAIT, NULL);
plat_setenv(RESTART_WAIT, NULL);
if (!ok) return 0;
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
@@ -736,12 +1370,11 @@ int plat_restart(void) {
int plat_restart_wait(uint32_t timeout_ms) {
char v[48];
DWORD n = GetEnvironmentVariableA(RESTART_WAIT, v, sizeof v);
if (!n) return 0;
SetEnvironmentVariableA(RESTART_WAIT, NULL); // the processes this one starts do not wait again
if (!plat_getenv(RESTART_WAIT, v, sizeof v)) return 0;
plat_setenv(RESTART_WAIT, NULL); // the processes this one starts do not wait again
unsigned long pid = 0;
unsigned long long created = 0;
if (n >= sizeof v || sscanf(v, "%lu.%llu", &pid, &created) != 2) return 0;
if (sscanf(v, "%lu.%llu", &pid, &created) != 2) return 0;
HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!h) return 0; // already gone
int r = process_created(h) != created ? 0 : WaitForSingleObject(h, timeout_ms) == WAIT_OBJECT_0 ? 1 : -1;