Files
betterxen/docs/interfaces.md
T
2026-11-25 09:56:31 -05:00

54 KiB
Raw Permalink Blame History

Interfaces

gfx1030 compute fixtures

The first input is little-endian gfx1030 machine code for a compute fixture with optional statically resolved forward scalar branches. The synthetic ABI starts with full Wave32 EXEC and reserves vector general-purpose register (VGPR) 0 for the grid index used by buffer accesses. Resource operands select documented synthetic bindings. The parser must require explicit target identification and validate all lengths before allocating. Console containers and AMDHSA initialization require separate contracts.

The production decoder takes borrowed code bytes. Its output records typed instructions, operand classes, original offsets and byte lengths. Unknown encodings and unsupported forms fail with a byte offset. The reference interpreter takes the original bytes and input words and performs its own decoding. It shares no production instruction definitions.

The compiler lifts decoded instructions to typed operations and verifies register initialization, supported resource offsets and termination before generating MSL. The initial subset permits only lane-indexed 32-bit buffer accesses against two disjoint buffers with equal lengths. The input is read-only. Each invocation may write only its own output word. The compiler and reference check instruction boundaries, termination placement and buffer bindings throughout the stream. Register initialization and transfer state are checked on the path selected by compile-time known forward scalar branches. Dynamic branches, workgroup barriers and cross-lane operations remain unsupported.

The Wave32 execution mask (EXEC) starts full. A supported scalar move can assign a known 32-bit value to its low half. Each bit selects the corresponding logical lane, numbered by the one-dimensional grid index modulo 32. Partial masks limit vector arithmetic and moves to selected lanes. These instructions must write an initialized destination so inactive lanes can retain their values. Empty EXEC suppresses vector arithmetic and moves. Reachable vector memory operations require full EXEC. Forward branches on EXEC or the vector condition code (VCC) test only their low halves. VCC must be initialized before use.

The native backend exposes NativeCompute::new() and run_words(source, entry, input) for trusted MSL. It binds input at index 0 and output at index 1, dispatches one invocation per word and returns owned readback after completion. run_words_profiled returns the same output plus measured library, pipeline, GPU and host durations for the benchmark harness; those timings are single submissions, not distributions. The caller runs generated MSL in a bounded child process. Raw MSL is a trusted developer input. Errors report the operation and backend detail. Across other stages, diagnostics carry a stage, error kind, optional byte offset and human-readable context.

Synthetic guest experiment

The separate X1–X4 driver loads fixed-base PE32+ fixtures, interprets a bounded x86-64 subset and dispatches synthetic services. X3 and X4 validate fixed-size command records from read-only guest bytes before issuing compute or draw work. Their command formats and Metal shaders are authored for the experiment.

The multi-function guest fixture (X6) maps PE32+ sections with separate read, write and execute permissions. Its interpreter tracks the expected return slot and continuation for each call. A return from the authenticated root frame ends execution.

The named-import fixture (X7) resolves imports for one synthetic module before guest entry. An indirect call may invoke only a resolved slot in the guest import address table. The handler validates the guest buffer and operates on words in checked guest memory. The command prints the guest exit value, while its host exit code reports whether loading and execution succeeded.

With the Metal feature, the guest compute fixture (X8) adds the xenora_compute import to the same loader. RCX points to a four-byte-aligned readable and writable three-word buffer. RDX points to a readable aligned 16-byte record containing four little-endian 32-bit fields: command 1, handle 0, input slot 0, and word count 3. Handle 0 names the buffer supplied on this call and is consumed after a successful dispatch. A second submission within the same guest run fails with a stale-resource fault. The CPU validates both spans before creating a Metal context. It selects the original translated XOR program, waits for completion, writes the three output words back to guest memory, and returns 3. The guest can read the result through its existing report import.

A general guest command stream must submit validated resource handles and ranges through an explicit address translation boundary. The graphics side owns mappings and the lifetime of in-flight views. Completion and fence signaling flow back across the command boundary. Guest addresses are never host pointers.

NativeCompute::run_guest_words takes a host-provided immutable resource table and a synthetic guest view. The view selects an input slot, table index, byte offset and byte length. The backend validates slot zero, little-endian 32-bit words, alignment, bounds and dispatch size before copying the selected range into a Metal buffer. Slot one holds a separate output buffer. The call returns owned words after command completion or a stage-specific error.

PE32+ fixture startup and static import reports

xenora_loader::startup::run_synthetic_startup takes an original, trusted fixture, guest memory addresses, a service registry and an entry instruction budget. It maps and rebases the image, binds imports, initializes thread-local storage, invokes its callbacks and runs the entry point. The fixture entry point uses a Win64-aligned stack. It may end with HLT, call ExitProcess, or return. The result includes the loaded guest memory and the entry execution outcome.

A guest ends its process through kernel32.dll!ExitProcess, also reachable as api-ms-win-core-processthreads-l1-1-0.dll!ExitProcess. Execution stops with ExitReason::ProcessExit(status), where the status is the full 32-bit value the guest passed. Only the guest stops: the host process is not ended. A returning entry point does the same with EAX as the status, which matches Windows while the process has one thread. The exit closes every guest handle: kernel objects, Winsock sockets and task-queue handles, which ServicesState::open_handle_count counts together. Files stay on the synthetic C: drive, guest memory stays mapped so the host can inspect it, and atexit functions are not run: that belongs to the C runtime's exit, described below. ServicesState::exit_status reports the status. After an exit the DbtEngine that ran the guest executes no further guest instruction and answers every later run with the same ProcessExit. A service callback that was in progress is never resumed.

A C program ends through the C runtime instead. ucrtbase.dll and api-ms-win-crt-runtime-l1-1-0.dll provide three ways out, each ending the guest with the same ProcessExit and the same cleanup as ExitProcess:

Service Behaviour
exit(status) Calls the functions registered with atexit and _crt_atexit, most recently registered first, then ends the process with status
_exit(status) Ends the process with status and calls no registered function
abort() Ends the process with exit code 3 and calls no registered function

exit takes one function at a time from the registered list. A function registered while exit runs is therefore called next, before the older ones that have not run yet, which is ISO C's rule. A registered function that calls exit again is undefined in ISO C; here the functions that have not run yet run once each and the process ends with the status of the later call. Functions that _cexit has already run are not run again.

All three are partial. exit flushes no stream, because there are none, and runs no thread-local destructor. It does not walk a module's own _onexit table; that module's startup code runs it through _execute_onexit_table. abort prints no message and does not call a SIGABRT handler, which the documentation says it does when one is set. _Exit, quick_exit and _c_exit are not provided. None of this has been compared with Windows.

A TLS callback may end the process too. Startup then reports the exit as its outcome, with the status, and runs neither the remaining callbacks nor the entry point; StartupResult::tls_callbacks counts the callbacks that finished. Any other stop inside a TLS callback is still a startup error.

The engine recognises two return addresses, one under the entry point and one under a guest callback, before it executes anything at them. Both are in the 4 KiB page at imports::RETURN_SENTINEL_PAGE, which startup reserves with no access. An image or layout that covers that page is refused, and a guest allocation there fails. The import trampolines above that page are intercepted in the same way and are not reserved.

Loading an image maps its headers as well as its sections. The first SizeOfHeaders bytes of the file are mapped read-only at the image base, in whole 4 KiB pages. Everything in those pages past SizeOfHeaders is zero, even where the file holds more bytes there. A guest can read its own DOS header, section table and data directories; it cannot write or execute them.

When startup loads an image away from its preferred base, it writes the load base into the mapped optional header's ImageBase field after the relocations have been applied, so an entry aimed at that field cannot leave any other value there. This is BetterXen's policy: the PE specification defines ImageBase as the preferred base, and the behaviour has not been compared with Windows.

The load is refused with PeError::InvalidHeaderSize when SizeOfHeaders is zero, ends before the section table does, runs past the end of the file, or its pages would reach into a section, and when the bytes given to the loader are not the PE32+ headers that were parsed. The page rule is stricter than the loader was before: an image whose section alignment is below 4 KiB, with a section that starts inside the header page, used to load and is now refused. The header pages count toward the 256 MiB mapping budget of one image, which is checked before anything is mapped. ParsedPe::parse does not make these checks, so static inspection of a file is unchanged.

betterxen run --experimental --pe <trusted-fixture> --startup-report <path> writes a versioned JSON summary after the worker stops. The supervisor creates the new report path before launching the worker. The report is optional and uses the same exact-byte fixture admission, startup observer and wall deadline as an ordinary run.

Schema version 1 lists the observed stages in order in stages and copies the last valid stage to last_completed_stage (null if none). The order is parsed, mapped, relocated, imports_bound, tls_completed, entry, exit, and framebuffer. entry records the handoff to guest entry. exit records the fixture halt, and framebuffer records verification of its offscreen readback. The supervisor reports an outcome of verified, stage_failure, early_exit, timeout, or unknown. It includes the worker exit code when available, termination detail when applicable, and the original reported error when available. Errors are capped at 2 KiB of UTF-8 and carry an error_truncated flag.

The supervisor reads at most 8 KiB plus one byte from the worker journal. record_integrity reports complete, truncated, malformed, oversized, unreadable, or unwritable. Worker exit codes 124 and 125 are reserved for its watchdog and journal I/O errors, respectively. --startup-journal is an internal worker option. Only the valid ordered prefix counts toward progress. A complete journal may still contain only a partial startup if the worker stopped between records. These records describe runtime observations from the trusted fixtures.

betterxen probe --mode static inventories ordinary and delay-loaded PE imports without guest execution. Without --report it writes to diagnostics/probe, where betterxen imports sync also looks. missing_imports.csv lists unresolved ordinary keys with their import address table relative virtual addresses. The full inventory, imports.csv, marks each entry ordinary or delayed in its import_table column and records whether each key is registered, its implementation status, and the canonical module behind API-set aliases. Modules and services loaded by other means at run time require separate analysis. The coverage matrix groups unresolved ordinary imports by shared startup prerequisites. Static imports do not reveal call order. The JSON report counts import slots, DLL and symbol keys, distinct names with DLL-scoped ordinals, and canonical registered handlers separately. The unresolved total includes explicitly tracked unsupported APIs and other missing handlers. Existing stubs remain visible in the full inventory.

Delay-loaded imports come from the PE32+ delay-load directory, data directory 13 in Microsoft's PE format. The probe reports each one with its DLL, symbol or ordinal, and slot in the delay import address table, after the ordinary rows. Binding does not resolve them: the PE format leaves that to a delay-load helper inside the image. The totals above and missing_imports.csv therefore cover ordinary imports only, and the JSON report counts delayed slots and DLLs in delayed_imports and delayed_imported_dlls_count. betterxen imports sync leaves delayed rows out of its backlog for the same reason.

The probe reads only descriptors that lie wholly inside the directory's declared size, and expects that size to hold the empty descriptor that ends the table. It reads descriptors whose RvaBased attribute is set, and requires each one's DLL name, import address table and import name table to be present and to start in section data. A table that breaks one of these rules, sets a reserved attribute bit, is truncated, or uses the earlier virtual-address descriptor form is reported in delay_import_error and in the Markdown report, together with the entries read before it.

xenora_import_gen::demangle decodes Microsoft Visual C++ decorated names for diagnostics, in the style of Microsoft's undname. It covers functions, data, member access and storage, this qualifiers, calling conventions, constructors, destructors, common operators, vftable names, classes, structs, unions, enums, pointers, references, primitive types, templates with type and integer arguments, and name and type back-references. Function pointer types, RTTI descriptors, nested function scopes and other constructs return None, so callers show the decorated name instead of a guess. The generator manifest's list of imports that need manual engineering shows the undecorated form beside each decorated C++ import. Tests check names mangled by clang for x86_64-pc-windows-msvc against their source declarations.

The synthetic process registry supports the current-process pseudo handle and its process ID. The priority boost setter and getter record and query a guest policy. They are partial until a guest scheduler applies the policy. The process ID lookup is limited to the current-process pseudo handle. An unsupported handle reports ERROR_INVALID_HANDLE through the guest error slot. The getter rejects invalid guest output addresses with ERROR_NOACCESS.

Win32 references include Microsoft's documentation for GetCurrentProcess, GetProcessId, SetProcessPriorityBoost, and GetProcessPriorityBoost.

Performance timing

The guest can import QueryPerformanceCounter and QueryPerformanceFrequency from Kernel32 or the profile API set. The counter measures monotonic elapsed time at a fixed 10 MHz, independently of wall-clock time. Synthetic fixtures can advance it deterministically. A failed guest output write returns false and records ERROR_NOACCESS. GetTickCount and GetTickCount64 return whole milliseconds since the synthetic runtime was created. The 32-bit value wraps at 2³² milliseconds. Both use the monotonic clock and are available through Kernel32 and the system-information API set.

See Microsoft's documentation for QueryPerformanceCounter QueryPerformanceFrequency, GetTickCount, and GetTickCount64.

Thread handles and virtual memory

The thread object model exposes one guest thread with a stable synthetic ID. OpenThread issues rights-checked handles to that thread, and CloseHandle invalidates real handles. A thread pseudo handle refers to the current synthetic thread. GetThreadId accepts the pseudo handle and live thread handles with query rights. The priority APIs store and query the thread's base-priority setting. Thread creation, inheritance, debugger exceptions, and scheduling remain outside this model. Within the synthetic process, DuplicateHandle can convert the thread pseudo handle to a real handle or copy a live thread handle. The new handle can keep or reduce the source's rights. The original and duplicate can be closed independently. Cross-process duplication, inheritable handles, process-handle duplication, and closing the source during duplication are outside this subset. A failed output write leaves the handle table unchanged.

VirtualAlloc supports combined reserve and commit for data-only pages. VirtualFree supports MEM_RELEASE with the exact allocation base and a zero size. The guest memory map tracks allocation ownership and bounds live virtual allocations to 64 MiB. Decommit, executable pages, and console-specific allocation lifecycle remain unsupported.

References include Microsoft's thread handle, thread ID, thread priority, handle duplication, handle close, virtual allocation, and virtual release contracts.

Stubs a hosted C program binds

VirtualProtect, VirtualQuery and __C_specific_handler are declared stub in the typed registry (docs/runtime/services.md). A C program built with the mingw-w64 runtime imports all three and does not call them on a normal run: the first two serve its runtime pseudo-relocations, and the third is the language handler Windows calls while dispatching a structured exception. They exist so that such a program's imports bind.

A call to any of them stops the guest with the runtime-limit fault (IllegalInstruction(0xFE)). The service writes nothing: no output buffer, no result and no last-error value. It does not return a made-up success or a failure code Windows would not give, so a program that needs one of them stops at that call. Nothing here changes a page protection, describes a region or dispatches an exception; each needs work the runtime does not have yet (regions that can be split, translated-code invalidation for executable pages, recorded allocation bases, exception dispatch).

CRT strings and byte memory

The standard registry provides strlen and strnlen under UCRT and the CRT string API set. They count bytes using checked guest memory. The scan stops at a null byte or the requested bound for strnlen. A scan that would continue past 1 MiB reports an unsupported-service fault. See the Microsoft CRT string-length contract.

The same modules expose strcmp and strncmp. These compare unsigned bytes and stop at the first difference, null byte, or supplied comparison bound. They share the 1 MiB scan budget. wcslen, wcsnlen, wcscmp, and wcsncmp apply the same rules to unsigned 16-bit Windows code units. Counts and bounds for the wide variants are in code units.

The same modules expose memset, memcpy, memmove, and memcmp for spans up to 1 MiB. Each nonempty span must be fully mapped with the required permissions. A span may cross adjacent guest regions. Writes validate the full destination before changing bytes, and moves preserve the original source bytes when ranges overlap.

Program arguments and environment

A hosted C program's startup code gets argc, argv and envp for main from five C runtime services. A host supplies the arguments with ServicesState::set_program_arguments(&["program", "first", ...]), program name first, before it runs the guest.

Service Behaviour
__p___argc(), __p___argv(), __p__environ() The address of the guest variable __argc, __argv or _environ. All three start as zero or null
_configure_narrow_argv(mode) For mode 1 or 2, sets __argc to the number of arguments and __argv to a table of pointers to their NUL-terminated strings, with a null pointer after the last, and returns 0. It builds the table once; later calls return 0 and change nothing. Mode 0 returns 0 and builds nothing. Any other mode returns EINVAL
_initialize_narrow_environment() Points _environ at a table holding one null pointer, once, and returns 0

set_program_arguments refuses an argument containing a NUL byte, arguments whose bytes and terminators exceed 32,767 (MAX_PROGRAM_ARGUMENT_BYTES, the documented Windows command-line limit), and a call after the guest has built its table. A host that never calls it gives the program one argument, the empty string, which is what ISO C specifies when no program name is available. An empty list gives it none.

What is documented, inferred and chosen:

  • Documented: the three global variables and what they hold, and ISO C's rules for argv (a null pointer after the last argument, strings the program may modify).
  • Inferred: that each __p_ function returns the address of its variable, as the documented __p__fmode does. Microsoft lists these five functions only by name.
  • Xenora's choice: what the two initialization functions do. Arguments reach the guest as the bytes of the host's strings, with no code page. Mode 2 asks for wildcard expansion and none is performed. The environment is empty. The variables and tables are blocks from the process heap.

The wide-character counterparts, GetCommandLineA and GetCommandLineW, and environment variables do not exist. All five services are partial. None of this has been compared with Windows.

Guest heaps

GetProcessHeap, HeapAlloc, HeapSize, and HeapFree expose the default synthetic heap. Allocations are at least 16-byte aligned and zero initialized. A zero-size request allocates one byte. All heaps in an address space share a 64 MiB budget and a limit of 4096 live allocations. Heap and virtual allocations have distinct ownership. HeapReAlloc preserves the retained bytes and zeroes newly added bytes. It can move a block unless HEAP_REALLOC_IN_PLACE_ONLY is set. Failed resizes preserve the original block. HeapCreate supports up to 256 growable private heaps with default flags. The initial size is checked against the budget and backing is allocated on demand. HeapDestroy frees all blocks owned by that private heap and invalidates its handle. The default heap cannot be destroyed. See the Windows heap API reference.

UCRT and the CRT heap API set expose malloc, calloc, realloc, and free on the bounded default guest heap. calloc checks for size overflow. realloc(NULL, size) allocates a new block, and resizing a nonnull block to zero frees it. Allocation failures return null and preserve existing blocks. Allocation failures also set the synthetic main thread's CRT errno to ENOMEM. The runtime API set and UCRT expose _errno, _get_errno, and _set_errno through a stable guest memory slot. Additional guest threads and CRT parameter or new-handler callbacks remain unsupported. See Microsoft CRT allocation documentation.

Standard output and formatted printing

A hosted C program prints through the C runtime. Six services give it the standard streams, and what it writes to stdout and to stderr is captured where a host or a test can read it: ServicesState::standard_output() and ServicesState::standard_error().

Service Behaviour
__acrt_iob_func(index) The FILE object of stdin (0), stdout (1) or stderr (2)
__stdio_common_vfprintf(options, stream, format, locale, arguments) Formats with the arguments in the guest's va_list, writes to stdout or stderr, and returns the number of characters written. This is what printf and fprintf call
fwrite(buffer, size, count, stream) Writes size * count bytes and returns count
fputs(string, stream) Writes the string without its terminator and returns 0
fflush(stream) Returns 0. A null stream means every stream
setvbuf(stream, buffer, mode, size) Checks the mode and size and returns 0

The standard streams are text-mode streams, so each line feed a program writes is captured as a carriage return and a line feed, as the Windows documentation of text mode describes. Function results count the characters before that replacement. Output is never held back: fflush has nothing to do and setvbuf only validates. Each captured stream keeps at most 16 MiB (MAX_CAPTURED_OUTPUT).

The formatting engine (crates/loader/src/services/crt_format.rs) follows Microsoft's "Format specification syntax: printf and wprintf functions" and ISO C:

  • Flags -, +, blank, # and 0; a width and a precision as digits or *; size prefixes hh, h, l, ll, j, z, t, I, I32, I64.
  • Types d, i, u, o, x, X, c, s, p and %%. An integer without a size prefix, and a long, is 32 bits. A null string prints (null).
  • Its output is compared with the host C library's snprintf on 2,600 generated cases whose result ISO C defines (crates/loader/tests/printf/reference.py).

Documented failures return their documented result and set errno to EINVAL: a null stream, format, buffer or string, and an invalid setvbuf mode or size. An invalid format, which includes %n because Windows disables it by default, also returns -1 with EINVAL and writes nothing; on Windows the invalid parameter handler runs first.

Everything else that is not modelled stops the guest with the runtime-limit fault and writes nothing, so that nothing is printed wrongly: the floating-point types (e, f, g, a), wide characters and strings (C, S, lc, ls), a locale object, option bits other than the three that do not affect these conversions, a pointer that is no stream, writing stdin, an index above 2, more than 1 MiB in one call, and output past the 16 MiB bound.

Choices where the documentation leaves room, each marked in the source: %p prints sixteen upper-case hexadecimal digits; 0 pads a character and a string as it pads a number; a precision also limits (null); %#.0o of zero prints 0, which is ISO C's rule. All six services are partial. None of this has been compared with Windows.

Files through the C runtime

fopen, fclose and fgets give a hosted C program files, and the output services above (__stdio_common_vfprintf, fwrite, fputs, fflush, setvbuf) accept a stream fopen returned as well as stdout and stderr. The files are the ones on the in-memory C: drive described under "Synthetic guest files": a file written through a C stream is the file ReadFile reads, and the reverse.

Service Behaviour
fopen(name, mode) Opens a file and returns its FILE*, or null with errno set. r needs the file to exist; w creates it or destroys its contents; a creates it and makes every write go to its end; + adds the other direction; b or t selects binary or text
fclose(stream) Closes the stream and returns 0; EOF with EINVAL for a null stream
fgets(buffer, count, stream) Reads up to count - 1 characters, stopping after a newline, which it keeps, and adds a terminator. Returns the buffer, or null at end of file or on an error
perror(message) Writes the message, : , the text for errno and a newline to stderr; only the text when the message is null or empty

A stream is in text mode unless its mode has b: a line feed is stored as a carriage return and a line feed, the pair is read back as a line feed, and CTRL+Z ends the input. Names are ASCII, with either slash, in any case, with or without C:\, as the drive accepts them.

errno after a failed fopen: EINVAL for a null or empty name or mode, a mode this runtime does not open, and a name the drive rejects; ENOENT when the file or its directory does not exist; EACCES for a directory; EMFILE when 64 streams are already open; ENOSPC when the drive holds its 256 files; ENOMEM when the FILE object cannot be allocated. Output to a stream that was not opened for writing, and reading one not opened for reading, fail with EBADF; output the drive has no room for fails with ENOSPC. A failed write writes nothing.

What is not provided, and what is Xenora's choice:

  • Not provided: the mode characters x, c, n, N, S, R, T, D and ccs=, which are refused; fread, fseek, ftell, rewind, feof, ferror, fscanf; reading stdin and closing a standard stream, which stop the guest.
  • No buffering. A write reaches the drive at once, so the rule that a + stream needs fflush or a seek between writing and reading does not apply.
  • No sharing. A C stream is not a Win32 handle. It does not stop DeleteFileW or MoveFileW, and ignores a handle's sharing mode. After its file is deleted a stream's reads and writes fail with EBADF.
  • Choices: the errno values above other than EINVAL for a null or empty argument, which is documented; an a+ stream reads from the start; every perror text except "No such file or directory", which is the one Microsoft's page shows.

All four services are partial. None of this has been compared with Windows.

CRT integer conversion

UCRT and the CRT conversion API set expose strtol, strtoul, wcstol, and wcstoul with 32-bit Windows long results. The parser supports C-locale whitespace, explicit bases 2–36 and automatic base selection, and writes the first unparsed guest address to a supplied end pointer. Overflow clamps the result and sets ERANGE. Scans have a 1 MiB input budget. The long-long variants and Microsoft's _strtoi64, _strtoui64, _wcstoi64, and _wcstoui64 apply the same rules with 64-bit results.

Built-in guest modules

GetModuleHandleA and GetModuleHandleW recognize synthetic Kernel32 and UCRT module names and their registered API-set aliases. GetProcAddress resolves case-sensitive named exports to guest service trampolines. The registry captures built-in bindings at standard service registration and excludes stubs. Missing names and unsupported ordinals fail explicitly. These APIs expose synthetic module handles and never load host libraries.

Synthetic guest files

The runtime exposes an in-memory C: drive through CreateFileW, ReadFile, WriteFile, GetFileSizeEx, and CloseHandle. It supports UTF-16 file and directory names, ASCII case folding, synchronous I/O, per-open file positions, and read/write sharing. SetFilePointerEx supports seeking from the beginning, current position, and end. SetEndOfFile truncates or zero-extends writable files at the current position. Seeks alone do not change file length. Paths cannot access host files. The drive supports 256 files and 16 MiB of data, with a 1 MiB limit per transfer. CreateDirectoryW and RemoveDirectoryW manage up to 256 directories. Parents must exist, and directories must be empty before removal. DeleteFileW deletes closed files. MoveFileW moves closed files to an unused name under an existing directory. GetFileAttributesW distinguishes files and directories. Traversal components and device names are rejected. FindFirstFileW, FindNextFileW, and FindClose enumerate a sorted snapshot of direct children. The final path component accepts literal names, * and ? wildcards, and . matches every name. Results include attributes, byte size, and a UTF-16 name. Times and alternate names are zero. Up to 32 searches can be open. Same-process file handle duplicates share the file position and keep the original sharing reservation until the last duplicate closes. Access can be reduced per handle. DOS wildcard edge cases, persistence, and asynchronous I/O remain outside this subset.

Event and semaphore signaling

The synthetic runtime supports unnamed manual-reset and auto-reset events created with default security attributes. SetEvent signals an event, ResetEvent clears it, and CloseHandle invalidates the handle. WaitForSingleObject consumes an auto-reset signal once, leaves a manual-reset signal set, and reports WAIT_TIMEOUT when a zero-timeout poll finds no signal. Without an attached thread scheduler, a wait that would block returns WAIT_FAILED with ERROR_NOT_SUPPORTED; with one it blocks the calling guest thread (guest threads). Thread and event handles are distinct types in the same bounded table. Event duplicates share signal state and keep the event alive independently. A duplicate can retain or reduce its rights. Waiting requires synchronize access, and setting or resetting requires modify-state access.

WaitForMultipleObjects supports immediate waits on up to 64 events or semaphores. Wait-any selects the first signaled handle. Wait-all consumes auto-reset signals only when every object is ready. Repeated handles and wait-all aliases to the same event are rejected. The extended single- and multiple- object wait APIs support the same immediate behavior when alerting is disabled. Alertable calls and waits that would block return an unsupported error.

CreateSemaphoreA and CreateSemaphoreW create unnamed semaphores with default security attributes. A successful wait consumes one permit. ReleaseSemaphore can return the previous count and rejects a release that exceeds the maximum without changing the count. Duplicates share the same permit count.

CreateMutexA, CreateMutexW and their Ex forms create unnamed mutexes, optionally owned by the caller. Ownership belongs to the calling guest thread, identified by its TEB. The owner can acquire the mutex again, and each acquisition needs a matching ReleaseMutex. Another thread sees the mutex as unsignaled. A release by a thread that is not the owner fails with ERROR_NOT_OWNER. Waits, duplicates and wait-all treat mutexes like the other waitable objects. A mutex whose owner thread ended is reported once as abandoned.

See Microsoft's event object documentation.

Locks, one-time initialization and thread-local storage

These services keep their state in the runtime and key ownership by guest TEB. These objects do not block through the guest scheduler yet, so any call that would block stops the guest with the runtime-limit fault (IllegalInstruction(0xFE)) rather than reporting success. Guest code reaches that fault by entering a critical section owned by another thread, acquiring a held SRW lock, or beginning a one-time initialization that another thread has pending.

  • Critical sections use the x64 RTL_CRITICAL_SECTION layout from winnt.h. Initialization writes the 40-byte structure. LockCount is -1 when free and -2 when held; the runtime also updates RecursionCount and OwningThread. The owner may enter recursively. TryEnterCriticalSection returns FALSE when another thread owns it. Leaving a section the caller does not own, or using one that was never initialized, stops the guest. The runtime holds up to 4,096 sections.
  • SRW locks allow any number of shared holders or one exclusive holder. The try forms return FALSE instead of waiting. Exclusive acquisition is not recursive. Releasing a mode the caller does not hold stops the guest.
  • Condition variables check that the caller holds the named lock. A zero-timeout sleep returns FALSE with ERROR_TIMEOUT and leaves the lock held in its original mode. Longer sleeps return ERROR_NOT_SUPPORTED. Wake calls do nothing, because no thread can be sleeping.
  • InitOnceBeginInitialize and InitOnceComplete support the synchronous mode, INIT_ONCE_CHECK_ONLY and INIT_ONCE_INIT_FAILED. The completed context is stored in the INIT_ONCE word, so later calls read it back. Asynchronous mode returns ERROR_NOT_SUPPORTED. InitOnceExecuteOnce calls the guest initializer once with the object, the parameter and a context pointer. A FALSE result, or a context that uses the two reserved low bits, leaves the object uninitialized so a later call can retry.
  • Interlocked SLists use the x64 SLIST_HEADER layout. The low 16 bits hold the depth, and bits 4 to 63 of the second quadword hold the first entry. Headers and entries must be 16-byte aligned. Updates are atomic with respect to other services. They are not atomic with respect to guest instructions that modify the header directly on another host thread.
  • TLS provides the documented 1,088 indexes. FLS provides the 128 FLS_MAXIMUM_AVAILABLE slots defined in the MinGW-w64 headers. Values are per guest thread, new indexes read as zero everywhere, and successful get calls clear the last error. Values live in the runtime, not in the TEB TlsSlots array, so guest code that reads the TEB directly does not see them. FlsFree releases the slot, then calls its cleanup callback on the calling thread for each thread's nonnull value, in TEB order.

System information, calendar time and sleeping

The guest sees a simulated machine described by GuestSystemProfile on ServicesState, and never the host's hardware. HostCapabilities::detect reports the Mac's logical processors, physical memory and page size separately, for diagnostics.

  • GetSystemInfo and GetNativeSystemInfo report an AMD64 processor (PROCESSOR_ARCHITECTURE_AMD64, PROCESSOR_AMD_X8664), 4 KiB pages, 64 KiB allocation granularity and the x64 user address range 0x10000–0x7FFFFFFEFFFF. The processor count comes from the profile and defaults to one, because guest code runs on one thread at a time. The processor level and revision are zero, because no CPU model is simulated.
  • GlobalMemoryStatusEx requires dwLength to be 64. Guest physical memory is the virtual-allocation and heap budgets together, 128 MiB. Available memory and dwMemoryLoad reflect current guest allocations. There is no paging file, and the virtual totals cover the x64 user range.
  • GetSystemTime, GetLocalTime and GetSystemTimePreciseAsFileTime read the injected clock. The guest time zone is UTC, so local time equals system time. FileTimeToSystemTime and SystemTimeToFileTime convert using the proleptic Gregorian calendar. They reject FILETIME values with the top bit set and invalid dates (years outside 1601–30827), ignore the day of week on input, and return ERROR_INVALID_PARAMETER without writing output.
  • QueryUnbiasedInterruptTime reports 100 ns ticks since the service state was created.
  • Sleep and SleepEx suspend the calling thread through the clock, so the mock clock advances instead of waiting. No APCs exist, so an alertable sleep always returns zero. INFINITE and sleeps longer than 10 seconds stop the guest with the runtime-limit fault, because a single guest thread could not be woken.

Services that call guest code

A service registered as a callback task can call guest functions before it returns. The dispatcher reserves 72 bytes of guest stack below the caller's return address. That space holds the callback's return address, its 32-byte home area and 16 bytes of scratch owned by the service, and it keeps RSP at 8 modulo 16 on entry, as after a CALL. Each callback receives up to four integer register arguments and must preserve the Win64 nonvolatile registers, or the guest stops with ServiceAbiViolation. The callback's RAX is passed to the task, which either calls guest code again or returns a value to the original caller with its RSP restored. Up to 32 callback frames may be active. Callback entry points must be executable. The earlier one-shot dispatch used by the GDK task queue is unchanged.

The CRT uses this for:

  • qsort and qsort_s, which sort up to 1 MiB in place with a guest comparator. Elements stay in place while the comparator runs and are permuted once at the end. qsort_s passes its context as the first comparator argument.

  • bsearch and bsearch_s, which return a pointer to a matching element or null.

  • _initterm and _initterm_e, which call each nonnull entry of an initializer table in order. _initterm_e stops at the first nonzero result and returns it. Tables hold at most 65,536 entries.

  • _initialize_onexit_table, _register_onexit_function and _execute_onexit_table manage _onexit_table_t tables. Their storage is on the default guest heap, and they hold at most 65,536 entries. Execution resets the table first, then calls the functions in reverse order of registration. atexit and _crt_atexit record process exit functions, which _cexit runs in reverse order and returns. exit runs them and then ends the process; see "PE32+ fixture startup" above.

Null comparators, null arrays with a nonzero count, and reversed or misaligned tables would reach the CRT invalid-parameter handler. That handler is not modeled, so these inputs stop the guest with the runtime-limit fault.

API-set aliases follow Microsoft's Win32 APIs for UWP apps listing: critical sections, SRW locks and mutexes use api-ms-win-core-synch-l1-1-0; condition variables and one-time initialization use api-ms-win-core-synch-l1-2-0; SLists use api-ms-win-core-interlocked-l1-1-0; TLS uses api-ms-win-core-processthreads-l1-1-0; and FLS uses api-ms-win-core-fibers-l1-1-0.

C runtime startup configuration

A C program's startup code configures the C runtime before main. Nine services record what it sets and return what their public documentation says. They are declared in the typed registry (docs/runtime/services.md), all partial, because nothing acts on a recorded value:

Service Returns Not provided
_set_app_type(type) nothing Nothing depends on the type
_set_new_mode(mode) the previous mode; -1 and errno EINVAL unless the mode is 0 or 1 malloc never calls a new handler
_configthreadlocale(request) the setting before the call (1 enabled, 2 disabled; a program starts disabled); -1 and errno EINVAL unless the request is 0, 1 or 2 There is no locale
__setusermatherr(handler) nothing The handler is never called
_set_invalid_parameter_handler(handler) the previous handler, null at first No service calls it for an invalid argument
__p__fmode(), __p__commode() the address of the guest int _fmode (initially _O_TEXT, 0x4000, as documented) or _commode (initially 0; its documentation gives no initial value) Nothing reads either until stdio exists
signal(sig, handler) the previous handler, SIG_DFL at first; SIG_ERR and errno EINVAL for a signal other than SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM and SIGABRT No signal is ever raised. One table serves the process
SetUnhandledExceptionFilter(filter) the previous filter, null at first No exception reaches it

_fmode and _commode share one 8-byte block allocated from the process heap on the first call to either. ServicesState::crt_app_type and ServicesState::crt_user_math_error let a host read the two values no service returns. signal.h also defines SIGBREAK and SIGABRT_COMPAT, which the documentation of signal does not list; they are refused, and whether Windows accepts them was not checked. memcpy also resolves through api-ms-win-crt-private-l1-1-0.dll, the API set the mingw-w64 runtime imports it from. None of this has been compared with Windows.

Synthetic tiled textures

The texture crate reads original fixtures in an array-layer-major layout. Each layer stores a consecutive mip chain. Within each mip, row-major 2×2 tiles store four row-major Block Compression 1 (BC1) blocks, including slots beyond the logical edge. The reader validates the full byte length, rejects padding coordinates and can decode each logical block to sixteen RGBA8 texels. The decoder uses bit replication to expand 5:6:5 endpoints and rounds integer palette interpolation down. This layout is specific to BetterXen fixtures. The block encoding follows the Direct3D BC1 description.

TiledBc1::linearize strips the tile padding from one selected subresource while retaining complete compressed blocks at logical image edges. NativeCompute::read_tiled_bc1 checks the pixel budget and the Metal device's BC texture capability, then uploads the selected blocks as a single BC1 RGBA texture. A fixed Metal compute kernel reads each texel and returns row-major RGBA8 words. The texture path uses authored MSL and takes its input from the host fixture.

Persistent guest graphics resources (X9)

A separate fixed-base PE32+ test profile exposes xenora_resource. RCX points to a readable, four-byte-aligned request of five little-endian 32-bit words (operation, handle, offset, length and kind). RDX carries a guest data address for uploads and readback. Other operations require it to be zero. Handle values encode a slot and generation. Every guest run owns a separate eight-slot table. Slots can be reused only with a new generation. Guest addresses and handles never expose host pointers.

Operation Request data
1, create buffer Length in bytes and kind 1 (compute words) or 2 (draw vertices). RDX points to initial data.
2, update buffer Handle, byte offset and length. RDX points to source bytes.
3, destroy resource Handle. A queued snapshot retains its bytes after destruction.
4, queue compute Handle, byte offset and length. The selected view binds the original translated XOR compute fixture.
5, complete and read back Exact result length and a writable RDX destination.
6, queue draw Handle, byte offset, length 96 and program ID 1 (constant color) or 2 (interpolated color). The input contains three float4 clip positions followed by three float4 colors. Readback is 4×3 row-major RGBA8.
7, create texture Length of compressed data in bytes. RDX points to eight descriptor words followed immediately by the compressed data.
8, queue texture read Handle, array layer in the offset field and mip index in the length field. Completion returns row-major RGBA8.

The texture descriptor contains width, height, mip count, layer count, format (1 for BC1), usage (1 for sampling), row pitch and slice pitch. The row pitch is aligned to the eight-byte BC1 block size. Each mip occupies one slice and uses the same pitches. Slices appear in mip order within each layer. The whole descriptor and payload must occupy one readable guest span. Textures are immutable. This is an original linear upload contract for the test profile. Opcode 8 uploads the selected subresource and uses an authored Metal texel reader.

Buffers and compressed texture payloads are limited to 4096 bytes. Queueing captures one immutable view. Completion validates the guest destination before submitting GPU work and waits for Metal before writing the result. An update or destruction after queueing cannot change the captured bytes. Guest exit drops resources and any queued view. Data persists across guest calls in host memory and is uploaded to Metal for execution. Persistent device allocations and GPU work in flight across guest calls are outside this interface.

Translated offscreen stages

compile_graphics decodes two original gfx1030 byte streams and links one vertex position export, an optional four-component parameter export, and one pixel color export. Buffer 0 supplies positions to vertex vector registers 0–3 and buffer 1 supplies colors to registers 4–7. The pixel stage can consume parameter zero through matching, adjacent interpolation phase pairs. This maps to center-perspective interpolation in Metal. The vertex stage supports a bounded set of 32-bit floating-point add and multiply forms. The graphics ABI also supports register and finite literal moves. Unsupported stage instructions or export combinations fail explicitly. The Xbox graphics ABI, hardware-specific floating-point modes, image instructions, and additional varyings remain unsupported.

Graphics draw and blend contracts

NativeCompute::render_indexed issues one real drawIndexedPrimitives call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an offscreen RGBA8 target. A draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects malformed draws; execution checks each draw in turn.

NativeCompute::render_blend draws up to 16 flat-coloured triangles in order into an offscreen RGBA8 target. Each draw has its own colour write mask and either blending disabled or separate RGB and alpha blend factors and operations. Colours are compared per channel against expectations derived independently from the public Metal blend equations.

NativeCompute::render_depth draws up to 16 triangles in order with an optional Depth32Float attachment, a chosen clear depth and a per-draw depth compare function. Colour and the stored depth are both read back.

These passes are checked on the GPU with Metal validation against expectations derived independently from the public semantics; synthetic fixtures only.

Guest texture binding (descriptor tables)

GraphicsContext lets a guest command list sample one texture in the pixel stage through a D3D12-shaped binding. A draw samples only if a root signature is bound. Draws without one keep the flat-colour path. The supported subset is fixed. Anything outside it fails with GraphicsError::Unsupported when the object is created, or with an error at execution. A rejected draw never reaches the backend. Draws recorded before it in the same list have already run.

Object Supported
create_descriptor_heap Shader-visible CBV_SRV_UAV (0) or SAMPLER (1) heaps of 1–64 descriptors. RTV, DSV and CPU-only heaps are unsupported.
create_committed_texture2d One level of R8G8B8A8_UNORM (28) or BC1_UNORM (71), 1–64 texels per side. BC1 sizes must be multiples of four. Rows are linear: 4 bytes per texel, or 8 bytes per 4×4 block. Xbox tiling is not handled.
create_shader_resource_view A Texture2D view of mip 0 of a single-level, single-slice 2D texture, in the resource's own format.
create_sampler Point filtering (MIN_MAG_MIP_POINT), clamp addressing on U, V and W, no LOD bias and a minimum LOD of 0.
create_root_signature Exactly two pixel-visibility descriptor tables, in either order: one with a single SRV range for t0, and one with a single sampler range for s0 (one descriptor each, space 0). Root constants, root descriptors, CBV and UAV ranges, extra tables or ranges and static samplers are unsupported.
cmd_set_descriptor_heaps At most one heap of each type.
cmd_set_graphics_root_descriptor_table The base must be a GPU handle to a slot of the bound heap of the table's type. The slot must hold a descriptor when a draw reads it. Changing the heaps or binding a different root signature clears every table. Setting the same heaps or the same root signature again keeps them.

Descriptor handles follow D3D12 pointer arithmetic: the heap start plus index × GetDescriptorHandleIncrementSize (32 here; guests must query the value). offset returns None rather than carry into the next heap. CPU and GPU handles are separate spaces. A textured draw is a DrawInstanced of one instance of three vertices with start instance 0, starting at any vertex. Zero vertices or instances draw nothing. The sampled texture must be in COMMON or a read-only state that includes PIXEL_SHADER_RESOURCE. The software reference draws at most 4096 pixels. Each vertex record holds a float4 position at byte 0 and a float4 texture coordinate at byte 16, with a stride of at least 32. Textured indexed draws are unsupported.

The native backend receives a TexturedDraw with the bound level and must bind it to fragment texture 0 and sampler 0, which are the tex0 and samp0 arguments of the translated image_sample_lz pixel stage. NativeCompute::render_rgba8_sampled_bc1 binds a BC1 level natively for that purpose. The software reference has no clipping or depth test. A pixel is covered when its centre lies inside or on an edge of the triangle. The texture coordinate is interpolated affinely, so w = 1 is required, and point sampled with min(floor(clamp(u, 0, 1) × width), width − 1). It decodes BC1 with the spec-exact xenora_texture::decode_bc1. Apple's hardware rounds BC1's two interpolated palette entries differently (171/84 against 170/85, measured on an M5 Pro), so the tests use endpoint colours only. Pipeline state objects do not exist yet, so the backend, not the guest, chooses the pixel shader. These entry points are not yet wired to guest imports.